diff --git a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/ansiCodes.js b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/ansiCodes.js deleted file mode 100644 index 7f7dacd2..00000000 --- a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/ansiCodes.js +++ /dev/null @@ -1,50 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/diff.js b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/diff.js deleted file mode 100644 index 8148779d..00000000 --- a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/diff.js +++ /dev/null @@ -1,17 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/index.js b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/index.js deleted file mode 100644 index 9e66dca3..00000000 --- a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/index.js +++ /dev/null @@ -1,7 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/reduce.js b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/reduce.js deleted file mode 100644 index 0e91e9dc..00000000 --- a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/reduce.js +++ /dev/null @@ -1,38 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/styledChars.js b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/styledChars.js deleted file mode 100644 index 13016ee6..00000000 --- a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/styledChars.js +++ /dev/null @@ -1,38 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/tokenize.js b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/tokenize.js deleted file mode 100644 index 0d2055e9..00000000 --- a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/tokenize.js +++ /dev/null @@ -1,141 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/undo.js b/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/undo.js deleted file mode 100644 index 9465b411..00000000 --- a/claude-code-source/node_modules/@alcalzone/ansi-tokenize/build/undo.js +++ /dev/null @@ -1,11 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@ant/computer-use-input/js/index.js b/claude-code-source/node_modules/@ant/computer-use-input/js/index.js deleted file mode 100644 index a184765d..00000000 --- a/claude-code-source/node_modules/@ant/computer-use-input/js/index.js +++ /dev/null @@ -1,25 +0,0 @@ -const path = require("path"); - -// Discriminated union: { isSupported: false } on non-darwin, -// { isSupported: true, ...nativeFns } on darwin. Cross-platform consumers -// (claude-cli-internal) require() unconditionally and narrow on isSupported. -if (process.platform !== "darwin") { - module.exports = { isSupported: false }; -} else { - // COMPUTER_USE_INPUT_NODE_PATH: escape hatch for bundlers. Bun's --compile - // embeds the .node as an asset, not in a node_modules tree — __dirname is - // the exe dir and ../prebuilds/ doesn't exist. The consuming build bakes - // this var to the embedded asset's path. Unset → normal node_modules layout. - // - // key()/keys() dispatch enigo work onto DispatchQueue.main via - // dispatch2::run_on_main, then block a tokio worker on a channel. Under - // Electron (CFRunLoop drains the main queue) this works; under libuv - // (Node/bun) the main queue never drains and the promise hangs. Consumers - // running under libuv must pump CFRunLoop while key()/keys() are pending — - // e.g. claude-cli-internal borrows @ant/computer-use-swift's _drainMainRunLoop. - const native = require( - process.env.COMPUTER_USE_INPUT_NODE_PATH ?? - path.resolve(__dirname, "../prebuilds/computer-use-input.node"), - ); - module.exports = { isSupported: true, ...native }; -} diff --git a/claude-code-source/node_modules/@ant/computer-use-mcp/src/deniedApps.ts b/claude-code-source/node_modules/@ant/computer-use-mcp/src/deniedApps.ts deleted file mode 100644 index 92f14e0b..00000000 --- a/claude-code-source/node_modules/@ant/computer-use-mcp/src/deniedApps.ts +++ /dev/null @@ -1,553 +0,0 @@ -/** - * App category lookup for tiered CU permissions. Three categories land at a - * restricted tier instead of `"full"`: - * - * - **browser** → `"read"` tier — visible in screenshots, NO interaction. - * The model can read an already-open page but must use the Claude-in-Chrome - * MCP for navigation/clicking/typing. - * - **terminal** → `"click"` tier — visible + clickable, NO typing. The - * model can click a Run button or scroll test output in an IDE, but can't - * type into the integrated terminal. Use the Bash tool for shell work. - * - **trading** → `"read"` tier — same restrictions as browsers, but no - * CiC-MCP alternative exists. For platforms where a stray click can - * execute a trade or send a message to a counterparty. - * - * Uncategorized apps default to `"full"`. See `getDefaultTierForApp`. - * - * Identification is two-layered: - * 1. Bundle ID match (macOS-only; `InstalledApp.bundleId` is a - * CFBundleIdentifier and meaningless on Windows). Fast, exact, the - * primary mechanism while CU is darwin-gated. - * 2. Display-name substring match (cross-platform fallback). Catches - * unresolved requests ("Chrome" when Chrome isn't installed) AND will - * be the primary mechanism on Windows/Linux where there's no bundle ID. - * Windows-relevant names (PowerShell, cmd, Windows Terminal) are - * included now so they activate the moment the darwin gate lifts. - * - * Keep this file **import-free** (like sentinelApps.ts) — the renderer may - * import it via a package.json subpath export, and pulling in - * `@modelcontextprotocol/sdk` (a devDep) through the index → mcpServer chain - * would fail module resolution in Next.js. The `CuAppPermTier` type is - * duplicated as a string literal below rather than imported. - */ - -export type DeniedCategory = "browser" | "terminal" | "trading"; - -/** - * Map a category to its hardcoded tier. Return-type is the string-literal - * union inline (this file is import-free; see header comment). The - * authoritative type is `CuAppPermTier` in types.ts — keep in sync. - * - * Not bijective — both `"browser"` and `"trading"` map to `"read"`. Copy - * that differs by category (the "use CiC" hint is browser-only) must check - * the category, not just the tier. - */ -export function categoryToTier( - category: DeniedCategory | null, -): "read" | "click" | "full" { - if (category === "browser" || category === "trading") return "read"; - if (category === "terminal") return "click"; - return "full"; -} - -// ─── Bundle-ID deny sets (macOS) ───────────────────────────────────────── - -const BROWSER_BUNDLE_IDS: ReadonlySet = new Set([ - // Apple - "com.apple.Safari", - "com.apple.SafariTechnologyPreview", - // Google - "com.google.Chrome", - "com.google.Chrome.beta", - "com.google.Chrome.dev", - "com.google.Chrome.canary", - // Microsoft - "com.microsoft.edgemac", - "com.microsoft.edgemac.Beta", - "com.microsoft.edgemac.Dev", - "com.microsoft.edgemac.Canary", - // Mozilla - "org.mozilla.firefox", - "org.mozilla.firefoxdeveloperedition", - "org.mozilla.nightly", - // Chromium-based - "org.chromium.Chromium", - "com.brave.Browser", - "com.brave.Browser.beta", - "com.brave.Browser.nightly", - "com.operasoftware.Opera", - "com.operasoftware.OperaGX", - "com.operasoftware.OperaDeveloper", - "com.vivaldi.Vivaldi", - // The Browser Company - "company.thebrowser.Browser", // Arc - "company.thebrowser.dia", // Dia (agentic) - // Privacy-focused - "org.torproject.torbrowser", - "com.duckduckgo.macos.browser", - "ru.yandex.desktop.yandex-browser", - // Agentic / AI browsers — newer entrants with LLM integrations - "ai.perplexity.comet", - "com.sigmaos.sigmaos.macos", // SigmaOS - // Webkit-based misc - "com.kagi.kagimacOS", // Orion -]); - -/** - * Terminals + IDEs with integrated terminals. Supersets - * `SHELL_ACCESS_BUNDLE_IDS` from sentinelApps.ts — terminals proceed to the - * approval dialog at tier "click", and the sentinel warning renders - * alongside the tier badge. - */ -const TERMINAL_BUNDLE_IDS: ReadonlySet = new Set([ - // Dedicated terminals - "com.apple.Terminal", - "com.googlecode.iterm2", - "dev.warp.Warp-Stable", - "dev.warp.Warp-Beta", - "com.github.wez.wezterm", - "org.alacritty", - "io.alacritty", // pre-v0.11.0 (renamed 2022-07) — kept for legacy installs - "net.kovidgoyal.kitty", - "co.zeit.hyper", - "com.mitchellh.ghostty", - "org.tabby", - "com.termius-dmg.mac", // Termius - // IDEs with integrated terminals — we can't distinguish "type in the - // editor" from "type in the integrated terminal" via screenshot+click. - // VS Code family - "com.microsoft.VSCode", - "com.microsoft.VSCodeInsiders", - "com.vscodium", // VSCodium - "com.todesktop.230313mzl4w4u92", // Cursor - "com.exafunction.windsurf", // Windsurf / Codeium - "dev.zed.Zed", - "dev.zed.Zed-Preview", - // JetBrains family (all have integrated terminals) - "com.jetbrains.intellij", - "com.jetbrains.intellij.ce", - "com.jetbrains.pycharm", - "com.jetbrains.pycharm.ce", - "com.jetbrains.WebStorm", - "com.jetbrains.CLion", - "com.jetbrains.goland", - "com.jetbrains.rubymine", - "com.jetbrains.PhpStorm", - "com.jetbrains.datagrip", - "com.jetbrains.rider", - "com.jetbrains.AppCode", - "com.jetbrains.rustrover", - "com.jetbrains.fleet", - "com.google.android.studio", // Android Studio (JetBrains-based) - // Other IDEs - "com.axosoft.gitkraken", // GitKraken has an integrated terminal panel. Also keeps the "kraken" trading-substring from miscategorizing it — bundle-ID wins. - "com.sublimetext.4", - "com.sublimetext.3", - "org.vim.MacVim", - "com.neovim.neovim", - "org.gnu.Emacs", - // Xcode's previous carve-out (full tier for Interface Builder / simulator) - // was reversed — at tier "click" IB and simulator taps still work (both are - // plain clicks) while the integrated terminal is blocked from keyboard input. - "com.apple.dt.Xcode", - "org.eclipse.platform.ide", - "org.netbeans.ide", - "com.microsoft.visual-studio", // Visual Studio for Mac - // AppleScript/automation execution surfaces — same threat as terminals: - // type(script) → key("cmd+r") runs arbitrary code. Added after #28011 - // removed the osascript MCP server, making CU the only tool-call route - // to AppleScript. - "com.apple.ScriptEditor2", - "com.apple.Automator", - "com.apple.shortcuts", -]); - -/** - * Trading / crypto platforms — granted at tier `"read"` so the agent can see - * balances and prices but can't click into an order, transfer, or IB chat. - * Bundle IDs populated from Homebrew cask `uninstall.quit` stanzas as they're - * verified; the name-substring fallback below is the primary check. Bloomberg - * Terminal has no native macOS build per their FAQ (web/Citrix only). - * - * Budgeting/accounting apps (Quicken, YNAB, QuickBooks, etc.) are NOT listed - * here — they default to tier `"full"`. The risk model for brokerage/crypto - * (a stray click can execute a trade) doesn't apply to budgeting apps; the - * Cowork system prompt carries the soft instruction to never execute trades - * or transfer money on the user's behalf. - */ -const TRADING_BUNDLE_IDS: ReadonlySet = new Set([ - // Verified via Homebrew quit/zap stanzas + mdls + electron-builder source. - // Trading - "com.webull.desktop.v1", // Webull (direct download, Qt) - "com.webull.trade.mac.v1", // Webull (Mac App Store) - "com.tastytrade.desktop", - "com.tradingview.tradingviewapp.desktop", - "com.fidelity.activetrader", // Fidelity Trader+ (new) - "com.fmr.activetrader", // Fidelity Active Trader Pro (legacy) - // Interactive Brokers TWS — install4j wrapper; Homebrew quit stanza is - // authoritative for this exact value but install4j IDs can drift across - // major versions — name-substring "trader workstation" is the fallback. - "com.install4j.5889-6375-8446-2021", - // Crypto - "com.binance.BinanceDesktop", - "com.electron.exodus", - // Electrum uses PyInstaller with bundle_identifier=None → defaults to - // org.pythonmac.unspecified.. Confirmed in spesmilo/electrum - // source + Homebrew zap. IntuneBrew's "org.electrum.electrum" is a fork. - "org.pythonmac.unspecified.Electrum", - "com.ledger.live", - "io.trezor.TrezorSuite", - // No native macOS app (name-substring only): Schwab, E*TRADE, TradeStation, - // Robinhood, NinjaTrader, Coinbase, Kraken, Bloomberg. thinkorswim - // install4j ID drifts per-install — substring safer. -]); - -// ─── Policy-deny (not a tier — cannot be granted at all) ───────────────── -// -// Streaming / ebook / music apps and a handful of publisher apps. These -// are auto-denied before the approval dialog — no tier can be granted. -// Rationale is copyright / content-control (the agent has no legitimate -// need to screenshot Netflix or click Play on Spotify). -// -// Sourced from the ACP CU-apps blocklist xlsx ("Full block" tab). See -// /tmp/extract_cu_blocklist.py for the extraction script. - -const POLICY_DENIED_BUNDLE_IDS: ReadonlySet = new Set([ - // Verified via Homebrew quit/zap + mdls /System/Applications + IntuneBrew. - // Apple built-ins - "com.apple.TV", - "com.apple.Music", - "com.apple.iBooksX", - "com.apple.podcasts", - // Music - "com.spotify.client", - "com.amazon.music", - "com.tidal.desktop", - "com.deezer.deezer-desktop", - "com.pandora.desktop", - "com.electron.pocket-casts", // direct-download Electron wrapper - "au.com.shiftyjelly.PocketCasts", // Mac App Store - // Video - "tv.plex.desktop", - "tv.plex.htpc", - "tv.plex.plexamp", - "com.amazon.aiv.AIVApp", // Prime Video (iOS-on-Apple-Silicon) - // Ebooks - "net.kovidgoyal.calibre", - "com.amazon.Kindle", // legacy desktop, discontinued - "com.amazon.Lassen", // current Mac App Store (iOS-on-Mac) - "com.kobo.desktop.Kobo", - // No native macOS app (name-substring only): Netflix, Disney+, Hulu, - // HBO Max, Peacock, Paramount+, YouTube, Crunchyroll, Tubi, Vudu, - // Audible, Reddit, NYTimes. Their iOS apps don't opt into iPad-on-Mac. -]); - -const POLICY_DENIED_NAME_SUBSTRINGS: readonly string[] = [ - // Video streaming - "netflix", - "disney+", - "hulu", - "prime video", - "apple tv", - "peacock", - "paramount+", - // "plex" is too generic — would match "Perplexity". Covered by - // tv.plex.* bundle IDs on macOS. - "tubi", - "crunchyroll", - "vudu", - // E-readers / audiobooks - "kindle", - "apple books", - "kobo", - "play books", - "calibre", - "libby", - "readium", - "audible", - "libro.fm", - "speechify", - // Music - "spotify", - "apple music", - "amazon music", - "youtube music", - "tidal", - "deezer", - "pandora", - "pocket casts", - // Publisher / social apps (from the same blocklist tab) - "naver", - "reddit", - "sony music", - "vegas pro", - "pitchfork", - "economist", - "nytimes", - // Skipped (too generic for substring matching — need bundle ID): - // HBO Max / Max, YouTube (non-Music), Nook, Sony Catalyst, Wired -]; - -/** - * Policy-level auto-deny. Unlike `userDeniedBundleIds` (per-user Settings - * page), this is baked into the build. `buildAccessRequest` strips these - * before the approval dialog with "blocked by policy" guidance; the agent - * is told to not retry. - */ -export function isPolicyDenied( - bundleId: string | undefined, - displayName: string, -): boolean { - if (bundleId && POLICY_DENIED_BUNDLE_IDS.has(bundleId)) return true; - const lower = displayName.toLowerCase(); - for (const sub of POLICY_DENIED_NAME_SUBSTRINGS) { - if (lower.includes(sub)) return true; - } - return false; -} - -export function getDeniedCategory(bundleId: string): DeniedCategory | null { - if (BROWSER_BUNDLE_IDS.has(bundleId)) return "browser"; - if (TERMINAL_BUNDLE_IDS.has(bundleId)) return "terminal"; - if (TRADING_BUNDLE_IDS.has(bundleId)) return "trading"; - return null; -} - -// ─── Display-name fallback (cross-platform) ────────────────────────────── - -/** - * Lowercase substrings checked against the requested display name. Catches: - * - Unresolved requests (app not installed, Spotlight miss) - * - Future Windows/Linux support where bundleId is meaningless - * - * Matched via `.includes()` on `name.toLowerCase()`. Entries are ordered - * by specificity (more-specific first is irrelevant since we return on - * first match, but groupings are by category for readability). - */ -const BROWSER_NAME_SUBSTRINGS: readonly string[] = [ - "safari", - "chrome", - "firefox", - "microsoft edge", - "brave", - "opera", - "vivaldi", - "chromium", - // Arc/Dia: the canonical display name is just "Arc"/"Dia" — too short for - // substring matching (false-positives: "Arcade", "Diagram"). Covered by - // bundle ID on macOS. The "... browser" entries below catch natural-language - // phrasings ("the arc browser") but NOT the canonical short name. - "arc browser", - "tor browser", - "duckduckgo", - "yandex", - "orion browser", - // Agentic / AI browsers - "comet", // Perplexity's browser — "Comet" substring risks false positives - // but leaving for now; "comet" in an app name is rare - "sigmaos", - "dia browser", -]; - -const TERMINAL_NAME_SUBSTRINGS: readonly string[] = [ - // macOS / cross-platform terminals - "terminal", // catches Terminal, Windows Terminal (NOT iTerm — separate entry) - "iterm", - "wezterm", - "alacritty", - "kitty", - "ghostty", - "tabby", - "termius", - // AppleScript runners — see bundle-ID comment above. "shortcuts" is too - // generic for substring matching (many apps have "shortcuts" in the name); - // covered by bundle ID only, like warp/hyper. - "script editor", - "automator", - // NOTE: "warp" and "hyper" are too generic for substring matching — - // they'd false-positive on "Warpaint" or "Hyperion". Covered by bundle ID - // (dev.warp.Warp-Stable, co.zeit.hyper) for macOS; Windows exe-name - // matching can be added when Windows CU ships. - // Windows shells (activate when the darwin gate lifts) - "powershell", - "cmd.exe", - "command prompt", - "git bash", - "conemu", - "cmder", - // IDEs (VS Code family) - "visual studio code", - "visual studio", // catches VS for Mac + Windows - "vscode", - "vs code", - "vscodium", - "cursor", // Cursor IDE — "cursor" is generic but IDE is the only common app - "windsurf", - // Zed: display name is just "Zed" — too short for substring matching - // (false-positives). Covered by bundle ID (dev.zed.Zed) on macOS. - // IDEs (JetBrains family) - "intellij", - "pycharm", - "webstorm", - "clion", - "goland", - "rubymine", - "phpstorm", - "datagrip", - "rider", - "appcode", - "rustrover", - "fleet", - "android studio", - // Other IDEs - "sublime text", - "macvim", - "neovim", - "emacs", - "xcode", - "eclipse", - "netbeans", -]; - -const TRADING_NAME_SUBSTRINGS: readonly string[] = [ - // Trading — brokerage apps. Sourced from the ACP CU-apps blocklist xlsx - // ("Read Only" tab). Name-substring safe for proper nouns below; generic - // names (IG, Delta, HTX) are skipped and need bundle-ID matching once - // verified. - "bloomberg", - "ameritrade", - "thinkorswim", - "schwab", - "fidelity", - "e*trade", - "interactive brokers", - "trader workstation", // Interactive Brokers TWS - "tradestation", - "webull", - "robinhood", - "tastytrade", - "ninjatrader", - "tradingview", - "moomoo", - "tradezero", - "prorealtime", - "plus500", - "saxotrader", - "oanda", - "metatrader", - "forex.com", - "avaoptions", - "ctrader", - "jforex", - "iq option", - "olymp trade", - "binomo", - "pocket option", - "raceoption", - "expertoption", - "quotex", - "naga", - "morgan stanley", - "ubs neo", - "eikon", // Thomson Reuters / LSEG Workspace - // Crypto — exchanges, wallets, portfolio trackers - "coinbase", - "kraken", - "binance", - "okx", - "bybit", - // "gate.io" is too generic — the ".io" TLD suffix is common in app names - // (e.g., "Draw.io"). Needs bundle-ID matching once verified. - "phemex", - "stormgain", - "crypto.com", - // "exodus" is too generic — it's a common noun and would match unrelated - // apps/games. Needs bundle-ID matching once verified. - "electrum", - "ledger live", - "trezor", - "guarda", - "atomic wallet", - "bitpay", - "bisq", - "koinly", - "cointracker", - "blockfi", - "stripe cli", - // Crypto games / metaverse (same trade-execution risk model) - "decentraland", - "axie infinity", - "gods unchained", -]; - -/** - * Display-name substring match. Called when bundle-ID resolution returned - * nothing (`resolved === undefined`) or when no bundle-ID deny-list entry - * matched. Returns the category for the first matching substring, or null. - * - * Case-insensitive, substring — so `"Google Chrome"`, `"chrome"`, and - * `"Chrome Canary"` all match the `"chrome"` entry. - */ -export function getDeniedCategoryByDisplayName( - name: string, -): DeniedCategory | null { - const lower = name.toLowerCase(); - // Trading first — proper-noun-only set, most specific. "Bloomberg Terminal" - // contains "terminal" and would miscategorize if TERMINAL_NAME_SUBSTRINGS - // ran first. - for (const sub of TRADING_NAME_SUBSTRINGS) { - if (lower.includes(sub)) return "trading"; - } - for (const sub of BROWSER_NAME_SUBSTRINGS) { - if (lower.includes(sub)) return "browser"; - } - for (const sub of TERMINAL_NAME_SUBSTRINGS) { - if (lower.includes(sub)) return "terminal"; - } - return null; -} - -/** - * Combined check — bundle ID first (exact, fast), then display-name - * fallback. This is the function tool-call handlers should use. - * - * `bundleId` may be undefined (unresolved request — model asked for an app - * that isn't installed or Spotlight didn't find). In that case only the - * display-name check runs. - */ -export function getDeniedCategoryForApp( - bundleId: string | undefined, - displayName: string, -): DeniedCategory | null { - if (bundleId) { - const byId = getDeniedCategory(bundleId); - if (byId) return byId; - } - return getDeniedCategoryByDisplayName(displayName); -} - -/** - * Default tier for an app at grant time. Wraps `getDeniedCategoryForApp` + - * `categoryToTier`. Browsers → `"read"`, terminals/IDEs → `"click"`, - * everything else → `"full"`. - * - * Called by `buildAccessRequest` to populate `ResolvedAppRequest.proposedTier` - * before the approval dialog shows. - */ -export function getDefaultTierForApp( - bundleId: string | undefined, - displayName: string, -): "read" | "click" | "full" { - return categoryToTier(getDeniedCategoryForApp(bundleId, displayName)); -} - -export const _test = { - BROWSER_BUNDLE_IDS, - TERMINAL_BUNDLE_IDS, - TRADING_BUNDLE_IDS, - POLICY_DENIED_BUNDLE_IDS, - BROWSER_NAME_SUBSTRINGS, - TERMINAL_NAME_SUBSTRINGS, - TRADING_NAME_SUBSTRINGS, - POLICY_DENIED_NAME_SUBSTRINGS, -}; diff --git a/claude-code-source/node_modules/@ant/computer-use-mcp/src/imageResize.ts b/claude-code-source/node_modules/@ant/computer-use-mcp/src/imageResize.ts deleted file mode 100644 index fc529714..00000000 --- a/claude-code-source/node_modules/@ant/computer-use-mcp/src/imageResize.ts +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Port of the API's image transcoder target-size algorithm. Pre-sizing - * screenshots to this function's output means the API's early-return fires - * (tokens ≤ max) and the image is NOT resized server-side — so the model - * sees exactly the dimensions in `ScreenshotResult.width/height` and - * `scaleCoord` stays coherent. - * - * Rust reference: api/api/image_transcoder/rust_transcoder/src/utils/resize.rs - * Sibling TS port: apps/claude-browser-use/src/utils/imageResize.ts (identical - * algorithm, lives in the Chrome extension tree — not a shared package). - * - * See COORDINATES.md for why this matters for click accuracy. - */ - -export interface ResizeParams { - pxPerToken: number; - maxTargetPx: number; - maxTargetTokens: number; -} - -/** - * Production defaults — match `resize.rs:160-164` and Chrome's - * `CDPService.ts:638-642`. Vision encoder uses 28px tiles; 1568 is both - * the long-edge cap (56 tiles) AND the token budget. - */ -export const API_RESIZE_PARAMS: ResizeParams = { - pxPerToken: 28, - maxTargetPx: 1568, - maxTargetTokens: 1568, -}; - -/** ceil(px / pxPerToken). Matches resize.rs:74-76 (which uses integer ceil-div). */ -export function nTokensForPx(px: number, pxPerToken: number): number { - return Math.floor((px - 1) / pxPerToken) + 1; -} - -function nTokensForImg( - width: number, - height: number, - pxPerToken: number, -): number { - return nTokensForPx(width, pxPerToken) * nTokensForPx(height, pxPerToken); -} - -/** - * Binary-search along the width dimension for the largest image that: - * - preserves the input aspect ratio - * - has long edge ≤ maxTargetPx - * - has ceil(w/pxPerToken) × ceil(h/pxPerToken) ≤ maxTargetTokens - * - * Returns [width, height]. No-op if input already satisfies all three. - * - * The long-edge constraint alone (what we used to use) is insufficient on - * squarer-than-16:9 displays: 1568×1014 (MBP 16" AR) is 56×37 = 2072 tokens, - * over budget, and gets server-resized to 1372×887 — model then clicks in - * 1372-space but scaleCoord assumed 1568-space → ~14% coord error. - * - * Matches resize.rs:91-155 exactly (verified against its test vectors). - */ -export function targetImageSize( - width: number, - height: number, - params: ResizeParams, -): [number, number] { - const { pxPerToken, maxTargetPx, maxTargetTokens } = params; - - if ( - width <= maxTargetPx && - height <= maxTargetPx && - nTokensForImg(width, height, pxPerToken) <= maxTargetTokens - ) { - return [width, height]; - } - - // Normalize to landscape for the search; transpose result back. - if (height > width) { - const [w, h] = targetImageSize(height, width, params); - return [h, w]; - } - - const aspectRatio = width / height; - - // Loop invariant: lowerBoundWidth is always valid, upperBoundWidth is - // always invalid. ~12 iterations for a 4000px image. - let upperBoundWidth = width; - let lowerBoundWidth = 1; - - for (;;) { - if (lowerBoundWidth + 1 === upperBoundWidth) { - return [ - lowerBoundWidth, - Math.max(Math.round(lowerBoundWidth / aspectRatio), 1), - ]; - } - - const middleWidth = Math.floor((lowerBoundWidth + upperBoundWidth) / 2); - const middleHeight = Math.max(Math.round(middleWidth / aspectRatio), 1); - - if ( - middleWidth <= maxTargetPx && - nTokensForImg(middleWidth, middleHeight, pxPerToken) <= maxTargetTokens - ) { - lowerBoundWidth = middleWidth; - } else { - upperBoundWidth = middleWidth; - } - } -} diff --git a/claude-code-source/node_modules/@ant/computer-use-mcp/src/index.ts b/claude-code-source/node_modules/@ant/computer-use-mcp/src/index.ts deleted file mode 100644 index 1e012cb2..00000000 --- a/claude-code-source/node_modules/@ant/computer-use-mcp/src/index.ts +++ /dev/null @@ -1,69 +0,0 @@ -export type { - ComputerExecutor, - DisplayGeometry, - FrontmostApp, - InstalledApp, - ResolvePrepareCaptureResult, - RunningApp, - ScreenshotResult, -} from "./executor.js"; - -export type { - AppGrant, - CuAppPermTier, - ComputerUseHostAdapter, - ComputerUseOverrides, - ComputerUseSessionContext, - CoordinateMode, - CuGrantFlags, - CuPermissionRequest, - CuPermissionResponse, - CuSubGates, - CuTeachPermissionRequest, - Logger, - ResolvedAppRequest, - ScreenshotDims, - TeachStepRequest, - TeachStepResult, -} from "./types.js"; - -export { DEFAULT_GRANT_FLAGS } from "./types.js"; - -export { - SENTINEL_BUNDLE_IDS, - getSentinelCategory, -} from "./sentinelApps.js"; -export type { SentinelCategory } from "./sentinelApps.js"; - -export { - categoryToTier, - getDefaultTierForApp, - getDeniedCategory, - getDeniedCategoryByDisplayName, - getDeniedCategoryForApp, - isPolicyDenied, -} from "./deniedApps.js"; -export type { DeniedCategory } from "./deniedApps.js"; - -export { isSystemKeyCombo, normalizeKeySequence } from "./keyBlocklist.js"; - -export { ALL_SUB_GATES_OFF, ALL_SUB_GATES_ON } from "./subGates.js"; - -export { API_RESIZE_PARAMS, targetImageSize } from "./imageResize.js"; -export type { ResizeParams } from "./imageResize.js"; - -export { defersLockAcquire, handleToolCall } from "./toolCalls.js"; -export type { - CuCallTelemetry, - CuCallToolResult, - CuErrorKind, -} from "./toolCalls.js"; - -export { bindSessionContext, createComputerUseMcpServer } from "./mcpServer.js"; -export { buildComputerUseTools } from "./tools.js"; - -export { - comparePixelAtLocation, - validateClickTarget, -} from "./pixelCompare.js"; -export type { CropRawPatchFn, PixelCompareResult } from "./pixelCompare.js"; diff --git a/claude-code-source/node_modules/@ant/computer-use-mcp/src/keyBlocklist.ts b/claude-code-source/node_modules/@ant/computer-use-mcp/src/keyBlocklist.ts deleted file mode 100644 index 1373e150..00000000 --- a/claude-code-source/node_modules/@ant/computer-use-mcp/src/keyBlocklist.ts +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Key combos that cross app boundaries or terminate processes. Gated behind - * the `systemKeyCombos` grant flag. When that flag is off, the `key` tool - * rejects these and returns a tool error telling the model to request the - * flag; all other combos work normally. - * - * Matching is canonicalized: every modifier alias the Rust executor accepts - * collapses to one canonical name. Without this, `command+q` / `meta+q` / - * `cmd+alt+escape` bypass the gate — see keyBlocklist.test.ts for the three - * bypass forms and the Rust parity check that catches future alias drift. - */ - -/** - * Every modifier alias enigo_wrap.rs accepts (two copies: :351-359, :564-572), - * mapped to one canonical per Key:: variant. Left/right variants collapse — - * the blocklist doesn't distinguish which Ctrl. - * - * Canonical names are Rust's own variant names lowercased. Blocklist entries - * below use ONLY these. "meta" reads odd for Cmd+Q but it's honest: Rust - * sends Key::Meta, which is Cmd on darwin and Win on win32. - */ -const CANONICAL_MODIFIER: Readonly> = { - // Key::Meta — "meta"|"super"|"command"|"cmd"|"windows"|"win" - meta: "meta", - super: "meta", - command: "meta", - cmd: "meta", - windows: "meta", - win: "meta", - // Key::Control + LControl + RControl - ctrl: "ctrl", - control: "ctrl", - lctrl: "ctrl", - lcontrol: "ctrl", - rctrl: "ctrl", - rcontrol: "ctrl", - // Key::Shift + LShift + RShift - shift: "shift", - lshift: "shift", - rshift: "shift", - // Key::Alt and Key::Option — distinct Rust variants but same keycode on - // darwin (kVK_Option). Collapse: cmd+alt+escape and cmd+option+escape - // both Force Quit. - alt: "alt", - option: "alt", -}; - -/** Sort order for canonicals. ctrl < alt < shift < meta. */ -const MODIFIER_ORDER = ["ctrl", "alt", "shift", "meta"]; - -/** - * Canonical-form entries only. Every modifier must be a CANONICAL_MODIFIER - * *value* (not key), modifiers must be in MODIFIER_ORDER, non-modifier last. - * The self-consistency test enforces this. - */ -const BLOCKED_DARWIN = new Set([ - "meta+q", // Cmd+Q — quit frontmost app - "shift+meta+q", // Cmd+Shift+Q — log out - "alt+meta+escape", // Cmd+Option+Esc — Force Quit dialog - "meta+tab", // Cmd+Tab — app switcher - "meta+space", // Cmd+Space — Spotlight - "ctrl+meta+q", // Ctrl+Cmd+Q — lock screen -]); - -const BLOCKED_WIN32 = new Set([ - "ctrl+alt+delete", // Secure Attention Sequence - "alt+f4", // close window - "alt+tab", // window switcher - "meta+l", // Win+L — lock - "meta+d", // Win+D — show desktop -]); - -/** - * Partition into sorted-canonical modifiers and non-modifier keys. - * Shared by normalizeKeySequence (join for display) and isSystemKeyCombo - * (check mods+each-key to catch the cmd+q+a suffix bypass). - */ -function partitionKeys(seq: string): { mods: string[]; keys: string[] } { - const parts = seq - .toLowerCase() - .split("+") - .map((p) => p.trim()) - .filter(Boolean); - const mods: string[] = []; - const keys: string[] = []; - for (const p of parts) { - const canonical = CANONICAL_MODIFIER[p]; - if (canonical !== undefined) { - mods.push(canonical); - } else { - keys.push(p); - } - } - // Dedupe: "cmd+command+q" → "meta+q", not "meta+meta+q". - const uniqueMods = [...new Set(mods)]; - uniqueMods.sort( - (a, b) => MODIFIER_ORDER.indexOf(a) - MODIFIER_ORDER.indexOf(b), - ); - return { mods: uniqueMods, keys }; -} - -/** - * Normalize "Cmd + Shift + Q" → "shift+meta+q": lowercase, trim, alias → - * canonical, dedupe, sort modifiers, non-modifiers last. - */ -export function normalizeKeySequence(seq: string): string { - const { mods, keys } = partitionKeys(seq); - return [...mods, ...keys].join("+"); -} - -/** - * True if the sequence would fire a blocked OS shortcut. - * - * Checks mods + EACH non-modifier key individually, not just the full - * joined string. `cmd+q+a` → Rust presses Cmd, then Q (Cmd+Q fires here), - * then A. Exact-match against "meta+q+a" misses; checking "meta+q" and - * "meta+a" separately catches the Q. - * - * Modifiers-only sequences ("cmd+shift") are checked as-is — no key to - * pair with, and no blocklist entry is modifier-only, so this is a no-op - * that falls through to false. Covers the click-modifier case where - * `left_click(text="cmd")` is legitimate. - */ -export function isSystemKeyCombo( - seq: string, - platform: "darwin" | "win32", -): boolean { - const blocklist = platform === "darwin" ? BLOCKED_DARWIN : BLOCKED_WIN32; - const { mods, keys } = partitionKeys(seq); - const prefix = mods.length > 0 ? mods.join("+") + "+" : ""; - - // No non-modifier keys (e.g. "cmd+shift" as click-modifiers) — check the - // whole thing. Never matches (no blocklist entry is modifier-only) but - // keeps the contract simple: every call reaches a .has(). - if (keys.length === 0) { - return blocklist.has(mods.join("+")); - } - - // mods + each key. Any hit blocks the whole sequence. - for (const key of keys) { - if (blocklist.has(prefix + key)) { - return true; - } - } - return false; -} - -export const _test = { - CANONICAL_MODIFIER, - BLOCKED_DARWIN, - BLOCKED_WIN32, - MODIFIER_ORDER, -}; diff --git a/claude-code-source/node_modules/@ant/computer-use-mcp/src/mcpServer.ts b/claude-code-source/node_modules/@ant/computer-use-mcp/src/mcpServer.ts deleted file mode 100644 index 4b1f0ca2..00000000 --- a/claude-code-source/node_modules/@ant/computer-use-mcp/src/mcpServer.ts +++ /dev/null @@ -1,313 +0,0 @@ -/** - * MCP server factory + session-context binder. - * - * Two entry points: - * - * `bindSessionContext` — the wrapper closure. Takes a `ComputerUseSessionContext` - * (getters + callbacks backed by host session state), returns a dispatcher. - * Reusable by both the MCP CallTool handler here AND Cowork's - * `InternalServerDefinition.handleToolCall` (which doesn't go through MCP). - * This replaces the duplicated wrapper closures in apps/desktop/…/serverDef.ts - * and the Claude Code CLI's CU host wrapper — both did the same thing: build `ComputerUseOverrides` - * fresh from getters, call `handleToolCall`, stash screenshot, merge permissions. - * - * `createComputerUseMcpServer` — the Server object. When `context` is provided, - * the CallTool handler is real (uses `bindSessionContext`). When not, it's the - * legacy stub that returns a not-wired error. The tool-schema ListTools handler - * is the same either way. - */ - -import { Server } from "@modelcontextprotocol/sdk/server/index.js"; -import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; -import { - CallToolRequestSchema, - ListToolsRequestSchema, -} from "@modelcontextprotocol/sdk/types.js"; - -import type { ScreenshotResult } from "./executor.js"; -import type { CuCallToolResult } from "./toolCalls.js"; -import { - defersLockAcquire, - handleToolCall, - resetMouseButtonHeld, -} from "./toolCalls.js"; -import { buildComputerUseTools } from "./tools.js"; -import type { - AppGrant, - ComputerUseHostAdapter, - ComputerUseOverrides, - ComputerUseSessionContext, - CoordinateMode, - CuGrantFlags, - CuPermissionResponse, -} from "./types.js"; -import { DEFAULT_GRANT_FLAGS } from "./types.js"; - -const DEFAULT_LOCK_HELD_MESSAGE = - "Another Claude session is currently using the computer. Wait for that " + - "session to finish, or find a non-computer-use approach."; - -/** - * Dedupe `granted` into `existing` on bundleId, spread truthy-only flags over - * defaults+existing. Truthy-only: a subsequent `request_access` that doesn't - * request clipboard can't revoke an earlier clipboard grant — revocation lives - * in a Settings page, not here. - * - * Same merge both hosts implemented independently today. - */ -function mergePermissionResponse( - existing: readonly AppGrant[], - existingFlags: CuGrantFlags, - response: CuPermissionResponse, -): { apps: AppGrant[]; flags: CuGrantFlags } { - const seen = new Set(existing.map((a) => a.bundleId)); - const apps = [ - ...existing, - ...response.granted.filter((g) => !seen.has(g.bundleId)), - ]; - const truthyFlags = Object.fromEntries( - Object.entries(response.flags).filter(([, v]) => v === true), - ); - const flags: CuGrantFlags = { - ...DEFAULT_GRANT_FLAGS, - ...existingFlags, - ...truthyFlags, - }; - return { apps, flags }; -} - -/** - * Bind session state to a reusable dispatcher. The returned function is the - * wrapper closure: async lock gate → build overrides fresh → `handleToolCall` - * → stash screenshot → strip piggybacked fields. - * - * The last-screenshot blob is held in a closure cell here (not on `ctx`), so - * hosts don't need to guarantee `ctx` object identity across calls — they just - * need to hold onto the returned dispatcher. Cowork caches per - * `InternalServerContext` in a WeakMap; the CLI host constructs once at server creation. - */ -export function bindSessionContext( - adapter: ComputerUseHostAdapter, - coordinateMode: CoordinateMode, - ctx: ComputerUseSessionContext, -): (name: string, args: unknown) => Promise { - const { logger, serverName } = adapter; - - // Screenshot blob persists here across calls — NOT on `ctx`. Hosts hold - // onto the returned dispatcher; that's the identity that matters. - let lastScreenshot: ScreenshotResult | undefined; - - const wrapPermission = ctx.onPermissionRequest - ? async ( - req: Parameters>[0], - signal: AbortSignal, - ): Promise => { - const response = await ctx.onPermissionRequest!(req, signal); - const { apps, flags } = mergePermissionResponse( - ctx.getAllowedApps(), - ctx.getGrantFlags(), - response, - ); - logger.debug( - `[${serverName}] permission result: granted=${response.granted.length} denied=${response.denied.length}`, - ); - ctx.onAllowedAppsChanged?.(apps, flags); - return response; - } - : undefined; - - const wrapTeachPermission = ctx.onTeachPermissionRequest - ? async ( - req: Parameters>[0], - signal: AbortSignal, - ): Promise => { - const response = await ctx.onTeachPermissionRequest!(req, signal); - logger.debug( - `[${serverName}] teach permission result: granted=${response.granted.length} denied=${response.denied.length}`, - ); - // Teach doesn't request grant flags — preserve existing. - const { apps } = mergePermissionResponse( - ctx.getAllowedApps(), - ctx.getGrantFlags(), - response, - ); - ctx.onAllowedAppsChanged?.(apps, { - ...DEFAULT_GRANT_FLAGS, - ...ctx.getGrantFlags(), - }); - return response; - } - : undefined; - - return async (name, args) => { - // ─── Async lock gate ───────────────────────────────────────────────── - // Replaces the sync Gate-3 in `handleToolCall` — we pass - // `checkCuLock: undefined` below so it no-ops. Hosts with - // cross-process locks (O_EXCL file) await the real primitive here - // instead of pre-computing + feeding a fake sync result. - if (ctx.checkCuLock) { - const lock = await ctx.checkCuLock(); - if (lock.holder !== undefined && !lock.isSelf) { - const text = - ctx.formatLockHeldMessage?.(lock.holder) ?? DEFAULT_LOCK_HELD_MESSAGE; - return { - content: [{ type: "text", text }], - isError: true, - telemetry: { error_kind: "cu_lock_held" }, - }; - } - if (lock.holder === undefined && !defersLockAcquire(name)) { - await ctx.acquireCuLock?.(); - // Re-check: the awaits above yield the microtask queue, so another - // session's check+acquire can interleave with ours. Hosts where - // acquire is a no-op when already held (Cowork's CuLockManager) give - // no signal that we lost — verify we're now the holder before - // proceeding. The CLI's O_EXCL file lock would surface this as a throw from - // acquire instead; this re-check is a belt-and-suspenders for that - // path too. - const recheck = await ctx.checkCuLock(); - if (recheck.holder !== undefined && !recheck.isSelf) { - const text = - ctx.formatLockHeldMessage?.(recheck.holder) ?? - DEFAULT_LOCK_HELD_MESSAGE; - return { - content: [{ type: "text", text }], - isError: true, - telemetry: { error_kind: "cu_lock_held" }, - }; - } - // Fresh holder → any prior session's mouseButtonHeld is stale. - // Mirrors what Gate-3 does on the acquire branch. After the - // re-check so we only clear module state when we actually won. - resetMouseButtonHeld(); - } - } - - // ─── Build overrides fresh ─────────────────────────────────────────── - // Blob-first; dims-fallback with base64:"" when the closure cell is - // unset (cross-respawn). scaleCoord reads dims; pixelCompare sees "" → - // isEmpty → skip. - const dimsFallback = lastScreenshot - ? undefined - : ctx.getLastScreenshotDims?.(); - - // Per-call AbortController for dialog dismissal. Aborted in `finally` — - // if handleToolCall finishes (MCP timeout, throw) before the user - // answers, the host's dialog handler sees the abort and tears down. - const dialogAbort = new AbortController(); - - const overrides: ComputerUseOverrides = { - allowedApps: [...ctx.getAllowedApps()], - grantFlags: ctx.getGrantFlags(), - userDeniedBundleIds: ctx.getUserDeniedBundleIds(), - coordinateMode, - selectedDisplayId: ctx.getSelectedDisplayId(), - displayPinnedByModel: ctx.getDisplayPinnedByModel?.(), - displayResolvedForApps: ctx.getDisplayResolvedForApps?.(), - lastScreenshot: - lastScreenshot ?? - (dimsFallback ? { ...dimsFallback, base64: "" } : undefined), - onPermissionRequest: wrapPermission - ? (req) => wrapPermission(req, dialogAbort.signal) - : undefined, - onTeachPermissionRequest: wrapTeachPermission - ? (req) => wrapTeachPermission(req, dialogAbort.signal) - : undefined, - onAppsHidden: ctx.onAppsHidden, - getClipboardStash: ctx.getClipboardStash, - onClipboardStashChanged: ctx.onClipboardStashChanged, - onResolvedDisplayUpdated: ctx.onResolvedDisplayUpdated, - onDisplayPinned: ctx.onDisplayPinned, - onDisplayResolvedForApps: ctx.onDisplayResolvedForApps, - onTeachModeActivated: ctx.onTeachModeActivated, - onTeachStep: ctx.onTeachStep, - onTeachWorking: ctx.onTeachWorking, - getTeachModeActive: ctx.getTeachModeActive, - // Undefined → handleToolCall's sync Gate-3 no-ops. The async gate - // above already ran. - checkCuLock: undefined, - acquireCuLock: undefined, - isAborted: ctx.isAborted, - }; - - logger.debug( - `[${serverName}] tool=${name} allowedApps=${overrides.allowedApps.length} coordMode=${coordinateMode}`, - ); - - // ─── Dispatch ──────────────────────────────────────────────────────── - try { - const result = await handleToolCall(adapter, name, args, overrides); - - if (result.screenshot) { - lastScreenshot = result.screenshot; - const { base64: _blob, ...dims } = result.screenshot; - logger.debug(`[${serverName}] screenshot dims: ${JSON.stringify(dims)}`); - ctx.onScreenshotCaptured?.(dims); - } - - return result; - } finally { - dialogAbort.abort(); - } - }; -} - -export function createComputerUseMcpServer( - adapter: ComputerUseHostAdapter, - coordinateMode: CoordinateMode, - context?: ComputerUseSessionContext, -): Server { - const { serverName, logger } = adapter; - - const server = new Server( - { name: serverName, version: "0.1.3" }, - { capabilities: { tools: {}, logging: {} } }, - ); - - const tools = buildComputerUseTools( - adapter.executor.capabilities, - coordinateMode, - ); - - server.setRequestHandler(ListToolsRequestSchema, async () => - adapter.isDisabled() ? { tools: [] } : { tools }, - ); - - if (context) { - const dispatch = bindSessionContext(adapter, coordinateMode, context); - server.setRequestHandler( - CallToolRequestSchema, - async (request): Promise => { - const { screenshot: _s, telemetry: _t, ...result } = await dispatch( - request.params.name, - request.params.arguments ?? {}, - ); - return result; - }, - ); - return server; - } - - // Legacy: no context → stub handler. Reached only if something calls the - // server over MCP transport WITHOUT going through a binder (a wiring - // regression). Clear error instead of silent failure. - server.setRequestHandler( - CallToolRequestSchema, - async (request): Promise => { - logger.warn( - `[${serverName}] tool call "${request.params.name}" reached the stub handler — no session context bound. Per-session state unavailable.`, - ); - return { - content: [ - { - type: "text", - text: "This computer-use server instance is not wired to a session. Per-session app permissions are not available on this code path.", - }, - ], - isError: true, - }; - }, - ); - - return server; -} diff --git a/claude-code-source/node_modules/@ant/computer-use-mcp/src/pixelCompare.ts b/claude-code-source/node_modules/@ant/computer-use-mcp/src/pixelCompare.ts deleted file mode 100644 index 05153f60..00000000 --- a/claude-code-source/node_modules/@ant/computer-use-mcp/src/pixelCompare.ts +++ /dev/null @@ -1,171 +0,0 @@ -/** - * Staleness guard ported from the Vercept acquisition. - * - * Compares the model's last-seen screenshot against a fresh-right-now - * screenshot at the click target, so the model never clicks pixels it hasn't - * seen. If the 9×9 patch around the target differs, the click is aborted and - * the model is told to re-screenshot. This is NOT a popup detector. - * - * Semantics preserved exactly: - * - Skip on no `lastScreenshot` (cold start) — click proceeds. - * - Skip on any internal error (crop throws, screenshot fails, etc.) — - * click proceeds. Validation failure must never block the action. - * - 9×9 exact byte equality on raw pixel bytes. No fuzzing, no tolerance. - * - Compare in percentage coords so Retina scale doesn't matter. - * - * JPEG decode + crop is INJECTED via `ComputerUseHostAdapter.cropRawPatch`. - * The original used `sharp` (LGPL, native `.node` addon); we inject Electron's - * `nativeImage` (Chromium decoders, BSD, nothing to bundle) from the host, so - * this package never imports it — the crop is a function parameter. - */ - -import type { ScreenshotResult } from "./executor.js"; -import type { Logger } from "./types.js"; - -/** Injected by the host. See `ComputerUseHostAdapter.cropRawPatch`. */ -export type CropRawPatchFn = ( - jpegBase64: string, - rect: { x: number; y: number; width: number; height: number }, -) => Buffer | null; - -/** 9×9 is empirically the sweet spot — large enough to catch a tooltip - * appearing, small enough to not false-positive on surrounding animation. - **/ -const DEFAULT_GRID_SIZE = 9; - -export interface PixelCompareResult { - /** true → click may proceed. false → patch changed, abort the click. */ - valid: boolean; - /** true → validation did not run (cold start, sub-gate off, or internal - * error). The caller MUST treat this identically to `valid: true`. */ - skipped: boolean; - /** Populated when valid === false. Returned to the model verbatim. */ - warning?: string; -} - -/** - * Compute the crop rect for a patch centered on (xPercent, yPercent). - * - * Dimensions come from ScreenshotResult.width/height (physical pixels). Both - * screenshots have the same dimensions (same display, consecutive captures), - * so the rect is the same for both. - */ -function computeCropRect( - imgW: number, - imgH: number, - xPercent: number, - yPercent: number, - gridSize: number, -): { x: number; y: number; width: number; height: number } | null { - if (!imgW || !imgH) return null; - - const clampedX = Math.max(0, Math.min(100, xPercent)); - const clampedY = Math.max(0, Math.min(100, yPercent)); - - const centerX = Math.round((clampedX / 100.0) * imgW); - const centerY = Math.round((clampedY / 100.0) * imgH); - - const halfGrid = Math.floor(gridSize / 2); - const cropX = Math.max(0, centerX - halfGrid); - const cropY = Math.max(0, centerY - halfGrid); - const cropW = Math.min(gridSize, imgW - cropX); - const cropH = Math.min(gridSize, imgH - cropY); - if (cropW <= 0 || cropH <= 0) return null; - - return { x: cropX, y: cropY, width: cropW, height: cropH }; -} - -/** - * Compare the same patch location between two screenshots. - * - * @returns true when the raw pixel bytes are identical. false on any - * difference, or on any internal error (the caller treats an error here as - * `skipped`, so the false is harmless). - */ -export function comparePixelAtLocation( - crop: CropRawPatchFn, - lastScreenshot: ScreenshotResult, - freshScreenshot: ScreenshotResult, - xPercent: number, - yPercent: number, - gridSize: number = DEFAULT_GRID_SIZE, -): boolean { - // Both screenshots are of the same display — use the fresh one's - // dimensions (less likely to be stale than last's). - const rect = computeCropRect( - freshScreenshot.width, - freshScreenshot.height, - xPercent, - yPercent, - gridSize, - ); - if (!rect) return false; - - const patch1 = crop(lastScreenshot.base64, rect); - const patch2 = crop(freshScreenshot.base64, rect); - if (!patch1 || !patch2) return false; - - // Direct buffer equality. Note: nativeImage.toBitmap() gives BGRA, sharp's - // .raw() gave RGB. - // Doesn't matter — we're comparing two same-format buffers for equality. - return patch1.equals(patch2); -} - -/** - * Battle-tested click-target validation ported from the Vercept acquisition, - * with the fresh-screenshot capture delegated to the caller (we don't have - * a global `SystemActions.takeScreenshot()` — the executor is injected). - * - * Skip conditions (any of these → `{ valid: true, skipped: true }`): - * - `lastScreenshot` is undefined (cold start). - * - `takeFreshScreenshot()` throws or returns null. - * - Injected crop function returns null (decode failure). - * - Any other exception. - * - * The caller decides whether to invoke this at all (sub-gate check lives - * in toolCalls.ts, not here). - */ -export async function validateClickTarget( - crop: CropRawPatchFn, - lastScreenshot: ScreenshotResult | undefined, - xPercent: number, - yPercent: number, - takeFreshScreenshot: () => Promise, - logger: Logger, - gridSize: number = DEFAULT_GRID_SIZE, -): Promise { - if (!lastScreenshot) { - return { valid: true, skipped: true }; - } - - try { - const fresh = await takeFreshScreenshot(); - if (!fresh) { - return { valid: true, skipped: true }; - } - - const pixelsMatch = comparePixelAtLocation( - crop, - lastScreenshot, - fresh, - xPercent, - yPercent, - gridSize, - ); - - if (pixelsMatch) { - return { valid: true, skipped: false }; - } - return { - valid: false, - skipped: false, - warning: - "Screen content at the target location changed since the last screenshot. Take a new screenshot before clicking.", - }; - } catch (err) { - // Skip validation on technical errors, execute action anyway. - // Battle-tested: validation failure must never block the click. - logger.debug("[pixelCompare] validation error, skipping", err); - return { valid: true, skipped: true }; - } -} diff --git a/claude-code-source/node_modules/@ant/computer-use-mcp/src/sentinelApps.ts b/claude-code-source/node_modules/@ant/computer-use-mcp/src/sentinelApps.ts deleted file mode 100644 index 0d26de60..00000000 --- a/claude-code-source/node_modules/@ant/computer-use-mcp/src/sentinelApps.ts +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Bundle IDs that are escalations-in-disguise. The approval UI shows a warning - * badge for these; they are NOT blocked. Power users may legitimately want the - * model controlling a terminal. - * - * Imported by the renderer via the `./sentinelApps` subpath (package.json - * `exports`), which keeps Next.js from reaching index.ts → mcpServer.ts → - * @modelcontextprotocol/sdk (devDep, would fail module resolution). Keep - * this file import-free so the subpath stays clean. - */ - -/** These apps can execute arbitrary shell commands. */ -const SHELL_ACCESS_BUNDLE_IDS = new Set([ - "com.apple.Terminal", - "com.googlecode.iterm2", - "com.microsoft.VSCode", - "dev.warp.Warp-Stable", - "com.github.wez.wezterm", - "io.alacritty", - "net.kovidgoyal.kitty", - "com.jetbrains.intellij", - "com.jetbrains.pycharm", -]); - -/** Finder in the allowlist ≈ browse + open-any-file. */ -const FILESYSTEM_ACCESS_BUNDLE_IDS = new Set(["com.apple.finder"]); - -const SYSTEM_SETTINGS_BUNDLE_IDS = new Set(["com.apple.systempreferences"]); - -export const SENTINEL_BUNDLE_IDS: ReadonlySet = new Set([ - ...SHELL_ACCESS_BUNDLE_IDS, - ...FILESYSTEM_ACCESS_BUNDLE_IDS, - ...SYSTEM_SETTINGS_BUNDLE_IDS, -]); - -export type SentinelCategory = "shell" | "filesystem" | "system_settings"; - -export function getSentinelCategory(bundleId: string): SentinelCategory | null { - if (SHELL_ACCESS_BUNDLE_IDS.has(bundleId)) return "shell"; - if (FILESYSTEM_ACCESS_BUNDLE_IDS.has(bundleId)) return "filesystem"; - if (SYSTEM_SETTINGS_BUNDLE_IDS.has(bundleId)) return "system_settings"; - return null; -} diff --git a/claude-code-source/node_modules/@ant/computer-use-mcp/src/toolCalls.ts b/claude-code-source/node_modules/@ant/computer-use-mcp/src/toolCalls.ts deleted file mode 100644 index 557eab9f..00000000 --- a/claude-code-source/node_modules/@ant/computer-use-mcp/src/toolCalls.ts +++ /dev/null @@ -1,3649 +0,0 @@ -/** - * Tool dispatch. Every security decision from plan §2 is enforced HERE, - * before any executor method is called. - * - * Enforcement order, every call: - * 1. Kill switch (`adapter.isDisabled()`). - * 2. TCC gate (`adapter.ensureOsPermissions()`). `request_access` is - * exempted — it threads the ungranted state to the renderer so the - * user can grant TCC perms from inside the approval dialog. - * 3. Tool-specific gates (see dispatch table) — ANY exception in a gate - * returns a tool error, executor never called. - * 4. Executor call. - * - * For input actions (click/type/key/scroll/drag/move_mouse) the tool-specific - * gates are, in order: - * a. `prepareForAction` — hide every non-allowlisted app, then defocus us - * (battle-tested pre-action sequence from the Vercept acquisition). - * Sub-gated via `hideBeforeAction`. After this runs the screenshot is - * TRUE (what the - * model sees IS what's at each pixel) and we are not keyboard-focused. - * b. Frontmost gate — branched by actionKind: - * mouse: frontmost ∈ allowlist ∪ {hostBundleId, Finder} → pass. - * hostBundleId passes because the executor's - * `withClickThrough` bracket makes us click-through. - * keyboard: frontmost ∈ allowlist ∪ {Finder} → pass. - * hostBundleId → ERROR (safety net — defocus should have - * moved us off; if it didn't, typing would go into our - * own chat box). - * After step (a) this gate fires RARELY — only when something popped - * up between prepare and action, or the 5-try hide loop gave up. - * Checked FRESH on every call, not cached across calls. - * - * For click variants only, AFTER the above gates but BEFORE the executor call: - * c. Pixel-validation staleness check (sub-gated). - */ - -import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; -import { randomUUID } from "node:crypto"; - -import { getDefaultTierForApp, getDeniedCategoryForApp, isPolicyDenied } from "./deniedApps.js"; -import type { - ComputerExecutor, - DisplayGeometry, - InstalledApp, - ScreenshotResult, -} from "./executor.js"; -import { isSystemKeyCombo } from "./keyBlocklist.js"; -import { validateClickTarget } from "./pixelCompare.js"; -import { SENTINEL_BUNDLE_IDS } from "./sentinelApps.js"; -import type { - AppGrant, - ComputerUseHostAdapter, - ComputerUseOverrides, - CoordinateMode, - CuAppPermTier, - CuGrantFlags, - CuPermissionRequest, - CuSubGates, - CuTeachPermissionRequest, - Logger, - ResolvedAppRequest, - TeachStepRequest, -} from "./types.js"; - -/** - * Finder is never hidden by the hide loop (hiding Finder kills the Desktop), - * so it's always a valid frontmost. - */ -const FINDER_BUNDLE_ID = "com.apple.finder"; - -/** - * Categorical error classes for the cu_tool_call telemetry event. Never - * free text — error messages may contain file paths / app content (PII). - */ -export type CuErrorKind = - | "allowlist_empty" - | "tcc_not_granted" - | "cu_lock_held" - | "teach_mode_conflict" - | "teach_mode_not_active" - | "executor_threw" - | "capture_failed" - | "app_denied" // no longer emitted (tiered model replaced hard-deny); kept for schema compat - | "bad_args" // malformed tool args (type/shape/range/unknown value) - | "app_not_granted" // target app not in session allowlist (distinct from allowlist_empty) - | "tier_insufficient" // app in allowlist but at a tier too low for the action - | "feature_unavailable" // tool callable but session not wired for it - | "state_conflict" // wrong state for action (call sequence, mouse already held) - | "grant_flag_required" // action needs a grant flag (systemKeyCombos, clipboard*) from request_access - | "display_error" // display enumeration failed (platform) - | "other"; - -/** - * Telemetry payload piggybacked on the result — populated by handlers, - * consumed and stripped by the host wrapper (serverDef.ts) before the - * result goes to the SDK. Same pattern as `screenshot`. - */ -export interface CuCallTelemetry { - /** request_access / request_teach_access: apps NEWLY granted in THIS call - * (does NOT include idempotent re-grants of already-allowed apps). */ - granted_count?: number; - /** request_access / request_teach_access: apps denied in THIS call */ - denied_count?: number; - /** request_access / request_teach_access: apps safety-denied (browser) this call */ - denied_browser_count?: number; - /** request_access / request_teach_access: apps safety-denied (terminal) this call */ - denied_terminal_count?: number; - /** Categorical error class (only set when isError) */ - error_kind?: CuErrorKind; -} - -/** - * `CallToolResult` augmented with the screenshot payload. `bindSessionContext` - * reads `result.screenshot` after a `screenshot` tool call and stashes it in a - * closure cell for the next pixel-validation. MCP clients never see this - * field — the host wrapper strips it before returning to the SDK. - */ -export type CuCallToolResult = CallToolResult & { - screenshot?: ScreenshotResult; - /** Piggybacked telemetry — stripped by the host wrapper before SDK return. */ - telemetry?: CuCallTelemetry; -}; - -// --------------------------------------------------------------------------- -// Small result helpers (mirror of chrome-mcp's inline `{content, isError}`) -// --------------------------------------------------------------------------- - -function errorResult(text: string, errorKind?: CuErrorKind): CuCallToolResult { - return { - content: [{ type: "text", text }], - isError: true, - telemetry: errorKind ? { error_kind: errorKind } : undefined, - }; -} - -function okText(text: string): CuCallToolResult { - return { content: [{ type: "text", text }] }; -} - -function okJson(obj: unknown, telemetry?: CuCallTelemetry): CuCallToolResult { - return { - content: [{ type: "text", text: JSON.stringify(obj) }], - telemetry, - }; -} - -// --------------------------------------------------------------------------- -// Arg validation — lightweight, no zod (mirrors chrome-mcp's cast-and-check) -// --------------------------------------------------------------------------- - -function asRecord(args: unknown): Record { - if (typeof args === "object" && args !== null) { - return args as Record; - } - return {}; -} - -function requireNumber( - args: Record, - key: string, -): number | Error { - const v = args[key]; - if (typeof v !== "number" || !Number.isFinite(v)) { - return new Error(`"${key}" must be a finite number.`); - } - return v; -} - -function requireString( - args: Record, - key: string, -): string | Error { - const v = args[key]; - if (typeof v !== "string") { - return new Error(`"${key}" must be a string.`); - } - return v; -} - -/** - * Extract (x, y) from `coordinate: [x, y]` tuple. - * array of length 2, both non-negative numbers. - */ -function extractCoordinate( - args: Record, - paramName: string = "coordinate", -): [number, number] | Error { - const coord = args[paramName]; - if (coord === undefined) { - return new Error(`${paramName} is required`); - } - if (!Array.isArray(coord) || coord.length !== 2) { - return new Error(`${paramName} must be an array of length 2`); - } - const [x, y] = coord; - if (typeof x !== "number" || typeof y !== "number" || x < 0 || y < 0) { - return new Error(`${paramName} must be a tuple of non-negative numbers`); - } - return [x, y]; -} - -// --------------------------------------------------------------------------- -// Coordinate scaling -// --------------------------------------------------------------------------- - -/** - * Convert model-space coordinates to the logical points that enigo expects. - * - * - `normalized_0_100`: (x / 100) * display.width. `display` is fetched - * fresh per tool call — never cached across calls — - * so a mid-session display-settings change doesn't leave us stale. - * - `pixels`: the model sent image-space pixel coords (it read them off the - * last screenshot). With the 1568-px long-edge downsample, the - * screenshot-px → logical-pt ratio is `displayWidth / screenshotWidth`, - * NOT `1/scaleFactor`. Uses the display geometry stashed at CAPTURE time - * (`lastScreenshot.displayWidth`), not fresh — so the transform matches - * what the model actually saw even if the user changed display settings - * since. (Chrome's ScreenshotContext pattern — CDPService.ts:1486-1493.) - */ -function scaleCoord( - rawX: number, - rawY: number, - mode: CoordinateMode, - display: DisplayGeometry, - lastScreenshot: ScreenshotResult | undefined, - logger: Logger, -): { x: number; y: number } { - if (mode === "normalized_0_100") { - // Origin offset targets the selected display in virtual-screen space. - return { - x: Math.round((rawX / 100) * display.width) + display.originX, - y: Math.round((rawY / 100) * display.height) + display.originY, - }; - } - - // mode === "pixels": model sent image-space pixel coords. - if (lastScreenshot) { - // The transform. Chrome coordinateScaling.ts:22-34 + claude-in-a-box - // ComputerTool.swift:70-80 — two independent convergent impls. - // Uses the display geometry stashed AT CAPTURE TIME, not fresh. - // Origin from the same snapshot keeps clicks coherent with the captured display. - return { - x: - Math.round( - rawX * (lastScreenshot.displayWidth / lastScreenshot.width), - ) + lastScreenshot.originX, - y: - Math.round( - rawY * (lastScreenshot.displayHeight / lastScreenshot.height), - ) + lastScreenshot.originY, - }; - } - - // Cold start: model sent pixel coords without having taken a screenshot. - // Degenerate — fall back to the old /sf behavior and warn. - logger.warn( - "[computer-use] pixels-mode coordinate received with no prior screenshot; " + - "falling back to /scaleFactor. Click may be off if downsample is active.", - ); - return { - x: Math.round(rawX / display.scaleFactor) + display.originX, - y: Math.round(rawY / display.scaleFactor) + display.originY, - }; -} - -/** - * Convert model-space coordinates to the 0–100 percentage that - * pixelCompare.ts works in. The staleness check operates in screenshot-image - * space; comparing by percentage lets us crop both last and fresh screenshots - * at the same relative location without caring about their absolute dims. - * - * With the 1568-px downsample, `screenshot.width != display.width * sf`, so - * the old `rawX / (display.width * sf)` formula is wrong. The correct - * denominator is just `lastScreenshot.width` — the model's raw pixel coord is - * already in that image's coordinate space. `DisplayGeometry` is no longer - * consumed at all. - */ -function coordToPercentageForPixelCompare( - rawX: number, - rawY: number, - mode: CoordinateMode, - lastScreenshot: ScreenshotResult | undefined, -): { xPct: number; yPct: number } { - if (mode === "normalized_0_100") { - // Unchanged — already a percentage. - return { xPct: rawX, yPct: rawY }; - } - - // mode === "pixels" - if (!lastScreenshot) { - // validateClickTarget at pixelCompare.ts:141-143 already skips when - // lastScreenshot is undefined, so this return value never reaches a crop. - return { xPct: 0, yPct: 0 }; - } - return { - xPct: (rawX / lastScreenshot.width) * 100, - yPct: (rawY / lastScreenshot.height) * 100, - }; -} - -// --------------------------------------------------------------------------- -// Shared input-action gates -// --------------------------------------------------------------------------- - -/** - * Tier needed to perform a given action class. `undefined` → `"full"`. - * - * - `"mouse_position"` — mouse_move only. Passes at any tier including - * `"read"`. Pure cursor positioning, no app interaction. Still runs - * prepareForAction (hide non-allowed apps). - * - `"mouse"` — plain left click, double/triple, scroll, drag-from. - * Requires tier `"click"` or `"full"`. - * - `"mouse_full"` — right/middle click, any click with modifiers, - * drag-drop (the `to` endpoint of left_click_drag). Requires tier - * `"full"`. Right-click → context menu Paste, modifier chords → - * keystrokes before click, drag-drop → text insertion at the drop - * point. All escalate a click-tier grant to keyboard-equivalent input. - * Blunt: also rejects same-app drags (scrollbar, panel resize) onto - * click-tier apps; `scroll` is the tier-"click" way to scroll. - * - `"keyboard"` — type, key, hold_key. Requires tier `"full"`. - */ -type CuActionKind = "mouse_position" | "mouse" | "mouse_full" | "keyboard"; - -function tierSatisfies( - grantTier: CuAppPermTier | undefined, - actionKind: CuActionKind, -): boolean { - const tier = grantTier ?? "full"; - if (actionKind === "mouse_position") return true; - if (actionKind === "keyboard" || actionKind === "mouse_full") { - return tier === "full"; - } - // mouse - return tier === "click" || tier === "full"; -} - -// Appended to every tier_insufficient error. The model may try to route -// around the gate (osascript, System Events, cliclick via Bash) — this -// closes that door explicitly. Leading space so it concatenates cleanly. -const TIER_ANTI_SUBVERSION = - " Do not attempt to work around this restriction — never use AppleScript, " + - "System Events, shell commands, or any other method to send clicks or " + - "keystrokes to this app."; - -// --------------------------------------------------------------------------- -// Clipboard guard — stash+clear while a click-tier app is frontmost -// --------------------------------------------------------------------------- -// -// Threat: tier "click" blocks type/key/right-click-Paste, but a click-tier -// terminal/IDE may have a UI Paste button that's plain-left-clickable. If the -// clipboard holds `rm -rf /` — from the user, from a prior full-tier paste, -// OR from the agent's own write_clipboard call (which doesn't route through -// runInputActionGates) — a left_click on that button injects it. -// -// Mitigation: stash the user's clipboard on first entry to click-tier, then -// RE-CLEAR before every input action while click-tier stays frontmost. The -// re-clear is the load-bearing part — a stash-on-transition-only design -// leaves a gap between an agent write_clipboard and the next left_click. -// When frontmost becomes anything else, restore. Turn-end restore is inlined -// in the host's result-handler + leavingRunning (same dual-location as -// cuHiddenDuringTurn unhide) — reads `session.cuClipboardStash` directly and -// writes via Electron's `clipboard.writeText`, so no nest-only import. -// -// State lives on the session (via `overrides.getClipboardStash` / -// `onClipboardStashChanged`), not module-level. The CU lock still guarantees -// one session at a time, but session-scoped state means the host's turn-end -// restore doesn't need to reach back into this package. - -async function syncClipboardStash( - adapter: ComputerUseHostAdapter, - overrides: ComputerUseOverrides, - frontmostIsClickTier: boolean, -): Promise { - const current = overrides.getClipboardStash?.(); - if (!frontmostIsClickTier) { - // Restore + clear. Idempotent — if nothing is stashed, no-op. - if (current === undefined) return; - try { - await adapter.executor.writeClipboard(current); - // Clear only after a successful write — a transient pasteboard - // failure must not irrecoverably drop the stash. - overrides.onClipboardStashChanged?.(undefined); - } catch { - // Best effort — stash held, next non-click action retries. - } - return; - } - // Stash the user's clipboard on FIRST entry to click-tier only. - if (current === undefined) { - try { - const read = await adapter.executor.readClipboard(); - overrides.onClipboardStashChanged?.(read); - } catch { - // readClipboard failed — use empty sentinel so we don't retry the stash - // on the next action; restore becomes a harmless writeClipboard(""). - overrides.onClipboardStashChanged?.(""); - } - } - // Re-clear on EVERY click-tier action, not just the first. Defeats the - // bypass where the agent calls write_clipboard (which doesn't route - // through runInputActionGates) between stash and a left_click on a UI - // Paste button — the next action's clear clobbers the agent's write - // before the click lands. - try { - await adapter.executor.writeClipboard(""); - } catch { - // Transient pasteboard failure. The tier-"click" right-click/modifier - // block still holds; this is a net, not a promise. - } -} - -/** Every click/type/key/scroll/drag/move_mouse runs through this before - * touching the executor. Returns null on pass, error-result on block. - * Any throw inside → caught by handleToolCall's outer try → tool error. */ -async function runInputActionGates( - adapter: ComputerUseHostAdapter, - overrides: ComputerUseOverrides, - subGates: CuSubGates, - actionKind: CuActionKind, -): Promise { - // Step A+B — hide non-allowlisted apps + defocus us. Sub-gated. After this - // runs, the frontmost gate below becomes a rare edge-case detector (something - // popped up between prepare and action) rather than a normal-path blocker. - // ALL grant tiers stay visible — visibility is the baseline (tier "read"). - if (subGates.hideBeforeAction) { - const hidden = await adapter.executor.prepareForAction( - overrides.allowedApps.map((a) => a.bundleId), - overrides.selectedDisplayId, - ); - // Empty-check so we don't spam the callback on every action when nothing - // was hidden (the common case after the first action of a turn). - if (hidden.length > 0) { - overrides.onAppsHidden?.(hidden); - } - } - - // Frontmost gate. Check FRESH on every call. - const frontmost = await adapter.executor.getFrontmostApp(); - - const tierByBundleId = new Map( - overrides.allowedApps.map((a) => [a.bundleId, a.tier] as const), - ); - - // After handleToolCall's tier backfill, every grant has a concrete tier — - // .get() returning undefined means the app is not in the allowlist at all. - const frontmostTier = frontmost - ? tierByBundleId.get(frontmost.bundleId) - : undefined; - - // Clipboard guard. Per-action, not per-tool-call — runs for every sub-action - // inside computer_batch and teach_step/teach_batch, so clicking into a - // click-tier app mid-batch stashes+clears before the next click lands. - // Lives here (not in handleToolCall) so deferAcquire tools (request_access, - // list_granted_applications), `wait`, and the teach_step blocking-dialog - // phase don't trigger a sync — only input actions do. - if (subGates.clipboardGuard) { - await syncClipboardStash(adapter, overrides, frontmostTier === "click"); - } - - if (!frontmost) { - // No frontmost app (rare — login window?). Let it through; the click - // will land somewhere and PixelCompare catches staleness. - return null; - } - - const { hostBundleId } = adapter.executor.capabilities; - - if (frontmostTier !== undefined) { - if (tierSatisfies(frontmostTier, actionKind)) return null; - // In the allowlist but tier doesn't cover this action. Tailor the - // guidance to the actual tier — at "read", suggesting left_click or Bash - // is wrong (nothing is allowed; use Chrome MCP). At "click", the - // mouse_full/keyboard-specific messages apply. - if (frontmostTier === "read") { - // tier "read" is not category-unique (browser AND trading map to it) — - // re-look-up so the CiC hint only shows for actual browsers. - const isBrowser = - getDeniedCategoryForApp(frontmost.bundleId, frontmost.displayName) === - "browser"; - return errorResult( - `"${frontmost.displayName}" is granted at tier "read" — ` + - `visible in screenshots only, no clicks or typing.` + - (isBrowser - ? " Use the Claude-in-Chrome MCP for browser interaction (tools " + - "named `mcp__Claude_in_Chrome__*`; load via ToolSearch if " + - "deferred)." - : " No interaction is permitted; ask the user to take any " + - "actions in this app themselves.") + - TIER_ANTI_SUBVERSION, - "tier_insufficient", - ); - } - // frontmostTier === "click" (tier === "full" would have passed tierSatisfies) - if (actionKind === "keyboard") { - return errorResult( - `"${frontmost.displayName}" is granted at tier "click" — ` + - `typing, key presses, and paste require tier "full". The keys ` + - `would go to this app's text fields or integrated terminal. To ` + - `type into a different app, click it first to bring it forward. ` + - `For shell commands, use the Bash tool.` + TIER_ANTI_SUBVERSION, - "tier_insufficient", - ); - } - // actionKind === "mouse_full" ("mouse" and "mouse_position" pass at "click") - return errorResult( - `"${frontmost.displayName}" is granted at tier "click" — ` + - `right-click, middle-click, and clicks with modifier keys require ` + - `tier "full". Right-click opens a context menu with Paste/Cut, and ` + - `modifier chords fire as keystrokes before the click. Plain ` + - `left_click is allowed here.` + TIER_ANTI_SUBVERSION, - "tier_insufficient", - ); - } - // Finder is never-hide, always allowed. - if (frontmost.bundleId === FINDER_BUNDLE_ID) return null; - - if (frontmost.bundleId === hostBundleId) { - if (actionKind !== "keyboard") { - // mouse and mouse_full are both click events — click-through works. - // We're click-through (executor's withClickThrough). Pass. - return null; - } - // Keyboard safety net — defocus (prepareForAction step B) should have - // moved us off. If we're still here, typing would go to our chat box. - return errorResult( - "Claude's own window still has keyboard focus. This should not happen " + - "after the pre-action defocus. Click on the target application first.", - "state_conflict", - ); - } - - // Non-allowlisted, non-us, non-Finder. RARE after the hide loop — means - // something popped up between prepare and action, or the 5-try loop gave up. - return errorResult( - `"${frontmost.displayName}" is not in the allowed applications and is ` + - `currently in front. Take a new screenshot — it may have appeared ` + - `since your last one.`, - "app_not_granted", - ); -} - -/** - * Hit-test gate: reject a mouse action if the window under (x, y) belongs - * to an app whose tier doesn't cover mouse input. Closes the gap where a - * tier-"full" app is frontmost but the click lands on a tier-"read" window - * overlapping it — `runInputActionGates` passes (frontmost is fine), but the - * click actually goes to the read-tier app. - * - * Runs AFTER `scaleCoord` (needs global coords) and BEFORE the executor call. - * Returns null on pass (target is tier-"click"/"full", or desktop/Finder/us), - * error-result on block. - * - * When `appUnderPoint` returns null (desktop, or platform without hit-test), - * falls through — the frontmost check in `runInputActionGates` already ran. - */ -async function runHitTestGate( - adapter: ComputerUseHostAdapter, - overrides: ComputerUseOverrides, - subGates: CuSubGates, - x: number, - y: number, - actionKind: CuActionKind, -): Promise { - const target = await adapter.executor.appUnderPoint(x, y); - if (!target) return null; // desktop / nothing under point / platform no-op - - // Finder (desktop, file dialogs) is always clickable — same exemption as - // runInputActionGates. Our own overlay is filtered by Swift (pid != self). - if (target.bundleId === FINDER_BUNDLE_ID) return null; - - const tierByBundleId = new Map( - overrides.allowedApps.map((a) => [a.bundleId, a.tier] as const), - ); - - if (!tierByBundleId.has(target.bundleId)) { - // Not in the allowlist at all. The frontmost check would catch this if - // the target were frontmost, but here a different app is in front. This - // is the "something popped up" edge case — a new window appeared between - // screenshot and click, or a background app's window overlaps the target. - return errorResult( - `Click at these coordinates would land on "${target.displayName}", ` + - `which is not in the allowed applications. Take a fresh screenshot ` + - `to see the current window layout.`, - "app_not_granted", - ); - } - - const targetTier = tierByBundleId.get(target.bundleId); - - // Frontmost-based sync (runInputActionGates) misses the case where - // the click lands on a NON-FRONTMOST click-tier window. Re-sync by - // the hit-test target's tier — if target is click-tier, stash+clear - // before the click lands, regardless of what's frontmost. - if (subGates.clipboardGuard && targetTier === "click") { - await syncClipboardStash(adapter, overrides, true); - } - - if (tierSatisfies(targetTier, actionKind)) return null; - - // Target is in the allowlist but tier doesn't cover this action. - // runHitTestGate is only called with mouse/mouse_full (keyboard routes to - // frontmost, not window-under-cursor). The branch above catches - // mouse_full ∧ click; the only remaining fall-through is tier "read". - if (actionKind === "mouse_full" && targetTier === "click") { - return errorResult( - `Click at these coordinates would land on "${target.displayName}", ` + - `which is granted at tier "click" — right-click, middle-click, and ` + - `clicks with modifier keys require tier "full" (they can Paste via ` + - `the context menu or fire modifier-chord keystrokes). Plain ` + - `left_click is allowed here.` + TIER_ANTI_SUBVERSION, - "tier_insufficient", - ); - } - const isBrowser = - getDeniedCategoryForApp(target.bundleId, target.displayName) === "browser"; - return errorResult( - `Click at these coordinates would land on "${target.displayName}", ` + - `which is granted at tier "read" (screenshots only, no interaction). ` + - (isBrowser - ? "Use the Claude-in-Chrome MCP for browser interaction." - : "Ask the user to take any actions in this app themselves.") + - TIER_ANTI_SUBVERSION, - "tier_insufficient", - ); -} - -// --------------------------------------------------------------------------- -// Screenshot helpers -// --------------------------------------------------------------------------- - -/** - * §6 item 9 — screenshot retry on implausibly-small buffer. Battle-tested - * threshold (1024 bytes). We retry exactly once. - */ -const MIN_SCREENSHOT_BYTES = 1024; - -function decodedByteLength(base64: string): number { - // 3 bytes per 4 chars, minus padding. Good enough for a threshold check. - const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0; - return Math.floor((base64.length * 3) / 4) - padding; -} - -async function takeScreenshotWithRetry( - executor: ComputerExecutor, - allowedBundleIds: string[], - logger: ComputerUseHostAdapter["logger"], - displayId?: number, -): Promise { - let shot = await executor.screenshot({ allowedBundleIds, displayId }); - if (decodedByteLength(shot.base64) < MIN_SCREENSHOT_BYTES) { - logger.warn( - `[computer-use] screenshot implausibly small (${decodedByteLength(shot.base64)} bytes decoded), retrying once`, - ); - shot = await executor.screenshot({ allowedBundleIds, displayId }); - } - return shot; -} - -// --------------------------------------------------------------------------- -// Grapheme iteration — §6 item 7, ported from the Vercept acquisition -// --------------------------------------------------------------------------- - -const INTER_GRAPHEME_SLEEP_MS = 8; // §6 item 4 — 125 Hz USB polling - -function segmentGraphemes(text: string): string[] { - try { - // Node 18+ has Intl.Segmenter; the try is defence against a stripped- - // -down runtime (falls back to code points). - const Segmenter = ( - Intl as typeof Intl & { - Segmenter?: new ( - locale?: string, - options?: { granularity: "grapheme" | "word" | "sentence" }, - ) => { segment: (s: string) => Iterable<{ segment: string }> }; - } - ).Segmenter; - if (typeof Segmenter === "function") { - const seg = new Segmenter(undefined, { granularity: "grapheme" }); - return Array.from(seg.segment(text), (s) => s.segment); - } - } catch { - // fall through - } - // Code-point iteration. Keeps surrogate pairs together but splits ZWJ. - return Array.from(text); -} - -function sleep(ms: number): Promise { - return new Promise((r) => setTimeout(r, ms)); -} - -/** - * Split a chord string like "ctrl+shift" into individual key names. - * Same parsing as `key` tool / executor.key / keyBlocklist.normalizeKeySequence. - */ -function parseKeyChord(text: string): string[] { - return text - .split("+") - .map((s) => s.trim()) - .filter(Boolean); -} - -// --------------------------------------------------------------------------- -// left_mouse_down / left_mouse_up held-state tracking -// --------------------------------------------------------------------------- - -/** - * Errors on double-down but not on up-without-down. Module-level, but - * reset on every lock acquire (handleToolCall → acquireCuLock branch) so - * a session interrupted mid-drag (overlay stop during left_mouse_down) - * doesn't leave the flag true for the next lock holder. - * - * Still scoped wrong within a single lock cycle if sessions could interleave - * tool calls, but the lock enforces at-most-one-session-uses-CU so they - * can't. The per-turn reset is the correctness boundary. - */ -let mouseButtonHeld = false; -/** Whether mouse_move occurred between left_mouse_down and left_mouse_up. - * When false at mouseUp, the decomposed sequence is a click-release (not a - * drop) — hit-test at "mouse", not "mouse_full". */ -let mouseMoved = false; - -/** Clears the cross-call drag flags. Called from Gate-3 on lock-acquire and - * from `bindSessionContext` in mcpServer.ts — a fresh lock holder must not - * inherit a prior session's mid-drag state. */ -export function resetMouseButtonHeld(): void { - mouseButtonHeld = false; - mouseMoved = false; -} - -/** If a left_mouse_down set the OS button without a matching left_mouse_up - * ever getting its turn, release it now. Same release-before-return as - * handleClick. No-op when not held — callers don't need to check. */ -async function releaseHeldMouse( - adapter: ComputerUseHostAdapter, -): Promise { - if (!mouseButtonHeld) return; - await adapter.executor.mouseUp(); - mouseButtonHeld = false; - mouseMoved = false; -} - -/** - * Tools that check the lock but don't acquire it. `request_access` and - * `list_granted_applications` hit the CHECK (so a blocked session doesn't - * show an approval dialog for access it can't use) but defer ACQUIRE — the - * enter-CU notification/overlay only fires on the first action tool. - * - * `request_teach_access` is NOT here: approving teach mode hides the main - * window, and the lock must be held before that. See Gate-3 block in - * `handleToolCall` for the full explanation. - * - * Exported for `bindSessionContext` in mcpServer.ts so the async lock gate - * uses the same set as the sync one. - */ -export function defersLockAcquire(toolName: string): boolean { - return ( - toolName === "request_access" || - toolName === "list_granted_applications" - ); -} - -// --------------------------------------------------------------------------- -// request_access helpers -// --------------------------------------------------------------------------- - -/** Reverse-DNS-ish: contains at least one dot, no spaces, no slashes. Lets - * raw bundle IDs pass through resolution. */ -const REVERSE_DNS_RE = /^[A-Za-z0-9][\w.-]*\.[A-Za-z0-9][\w.-]*$/; - -function looksLikeBundleId(s: string): boolean { - return REVERSE_DNS_RE.test(s) && !s.includes(" "); -} - -function resolveRequestedApps( - requestedNames: string[], - installed: InstalledApp[], - alreadyGrantedBundleIds: ReadonlySet, -): ResolvedAppRequest[] { - const byLowerDisplayName = new Map(); - const byBundleId = new Map(); - for (const app of installed) { - byBundleId.set(app.bundleId, app); - // Last write wins on collisions. Ambiguous-name handling (multiple - // candidates in the dialog) is plan-documented but deferred — the - // InstalledApps enumerator dedupes by bundle ID, so true display-name - // collisions are rare. TODO(chicago, post-P1): surface all candidates. - byLowerDisplayName.set(app.displayName.toLowerCase(), app); - } - - return requestedNames.map((requested): ResolvedAppRequest => { - let resolved: InstalledApp | undefined; - if (looksLikeBundleId(requested)) { - resolved = byBundleId.get(requested); - } - if (!resolved) { - resolved = byLowerDisplayName.get(requested.toLowerCase()); - } - const bundleId = resolved?.bundleId; - // When unresolved AND the requested string looks like a bundle ID, use it - // directly for tier lookup (e.g. "company.thebrowser.Browser" with Arc not - // installed — the reverse-DNS string won't match any display-name substring). - const bundleIdCandidate = - bundleId ?? (looksLikeBundleId(requested) ? requested : undefined); - return { - requestedName: requested, - resolved, - isSentinel: bundleId ? SENTINEL_BUNDLE_IDS.has(bundleId) : false, - alreadyGranted: bundleId ? alreadyGrantedBundleIds.has(bundleId) : false, - proposedTier: getDefaultTierForApp( - bundleIdCandidate, - resolved?.displayName ?? requested, - ), - }; - }); -} - -// --------------------------------------------------------------------------- -// Individual tool handlers -// --------------------------------------------------------------------------- - -async function handleRequestAccess( - adapter: ComputerUseHostAdapter, - args: Record, - overrides: ComputerUseOverrides, - tccState: { accessibility: boolean; screenRecording: boolean } | undefined, -): Promise { - if (!overrides.onPermissionRequest) { - return errorResult( - "This session was not wired with a permission handler. Computer control is not available here.", - "feature_unavailable", - ); - } - - // Teach mode hides the main window; permission dialogs render in that - // window. Without this, handleToolPermission blocks on an invisible - // prompt and the overlay spins forever. Tell the model to exit teach - // mode, request access, then re-enter. - if (overrides.getTeachModeActive?.()) { - return errorResult( - "Cannot request additional permissions during teach mode — the permission dialog would be hidden. End teach mode (finish the tour or let the turn complete), then call request_access, then start a new tour.", - "teach_mode_conflict", - ); - } - - const reason = requireString(args, "reason"); - if (reason instanceof Error) return errorResult(reason.message, "bad_args"); - - // TCC-ungranted branch. The renderer shows a toggle panel INSTEAD OF the - // app list when `tccState` is present on the request, so we skip app - // resolution entirely (listInstalledApps() may fail without Screen - // Recording anyway). The user grants the OS perms from inside the dialog, - // then clicks "Ask again" — both buttons resolve with deny by design - // (ComputerUseApproval.tsx) so the model re-calls request_access and - // gets the app list on the next call. - if (tccState) { - const req: CuPermissionRequest = { - requestId: randomUUID(), - reason, - apps: [], - requestedFlags: {}, - screenshotFiltering: adapter.executor.capabilities.screenshotFiltering, - tccState, - }; - await overrides.onPermissionRequest(req); - - // Re-check: the user may have granted in System Settings while the - // dialog was up. The `tccState` arg is a pre-dialog snapshot — reading - // it here would tell the model "not yet granted" even after the user - // granted, and the model waits for confirmation instead of retrying. - // The renderer's TCC panel already live-polls (computerUseTccStore); - // this is the same re-check on the tool-result side. - const recheck = await adapter.ensureOsPermissions(); - if (recheck.granted) { - return errorResult( - "macOS Accessibility and Screen Recording are now both granted. " + - "Call request_access again immediately — the next call will show " + - "the app selection list.", - ); - } - - const missing: string[] = []; - if (!recheck.accessibility) missing.push("Accessibility"); - if (!recheck.screenRecording) missing.push("Screen Recording"); - return errorResult( - `macOS ${missing.join(" and ")} permission(s) not yet granted. ` + - `The permission panel has been shown. Once the user grants the ` + - `missing permission(s), call request_access again.`, - "tcc_not_granted", - ); - } - - const rawApps = args.apps; - if (!Array.isArray(rawApps) || !rawApps.every((a) => typeof a === "string")) { - return errorResult('"apps" must be an array of strings.', "bad_args"); - } - const apps = rawApps as string[]; - - const requestedFlags: Partial = {}; - if (typeof args.clipboardRead === "boolean") { - requestedFlags.clipboardRead = args.clipboardRead; - } - if (typeof args.clipboardWrite === "boolean") { - requestedFlags.clipboardWrite = args.clipboardWrite; - } - if (typeof args.systemKeyCombos === "boolean") { - requestedFlags.systemKeyCombos = args.systemKeyCombos; - } - - const { - needDialog, - skipDialogGrants, - willHide, - tieredApps, - userDenied, - policyDenied, - } = await buildAccessRequest( - adapter, - apps, - overrides.allowedApps, - new Set(overrides.userDeniedBundleIds), - overrides.selectedDisplayId, - ); - - let dialogGranted: AppGrant[] = []; - let dialogDenied: Array<{ - bundleId: string; - reason: "user_denied" | "not_installed"; - }> = []; - let dialogFlags: CuGrantFlags = overrides.grantFlags; - - if (needDialog.length > 0 || Object.keys(requestedFlags).length > 0) { - const req: CuPermissionRequest = { - requestId: randomUUID(), - reason, - apps: needDialog, - requestedFlags, - screenshotFiltering: adapter.executor.capabilities.screenshotFiltering, - // Undefined when empty so the renderer skips the section cleanly. - ...(willHide.length > 0 && { - willHide, - autoUnhideEnabled: adapter.getAutoUnhideEnabled(), - }), - }; - const response = await overrides.onPermissionRequest(req); - dialogGranted = response.granted; - dialogDenied = response.denied; - dialogFlags = response.flags; - } - - // Do NOT return display geometry or coordinateMode. See COORDINATES.md - // ("Never give the model a number that invites rescaling"). scaleCoord - // already transforms server-side; the coordinate convention is baked into - // the tool param descriptions at server-construction time. - const allGranted = [...skipDialogGrants, ...dialogGranted]; - // Filter tieredApps to what was actually granted — if the user unchecked - // Chrome in the dialog, don't explain Chrome's tier. - const grantedBundleIds = new Set(allGranted.map((g) => g.bundleId)); - const grantedTieredApps = tieredApps.filter((t) => - grantedBundleIds.has(t.bundleId), - ); - // Best-effort — grants are already persisted by wrappedPermissionHandler; - // a listDisplays/findWindowDisplays failure (monitor hot-unplug, NAPI - // error) must not tank the grant response. Same discipline as - // buildMonitorNote's listDisplays try/catch. - let windowLocations: Awaited> = []; - try { - windowLocations = await buildWindowLocations(adapter, allGranted); - } catch (e) { - adapter.logger.warn( - `[computer-use] buildWindowLocations failed: ${String(e)}`, - ); - } - return okJson( - { - granted: allGranted, - denied: dialogDenied, - // Policy blocklist — precedes userDenied in precedence and response - // order. No escape hatch; the agent is told to find another approach. - ...(policyDenied.length > 0 && { - policyDenied: { - apps: policyDenied, - guidance: buildPolicyDeniedGuidance(policyDenied), - }, - }), - // User-configured auto-deny — stripped before the dialog; this is the - // agent's only signal that these apps exist but are user-blocked. - ...(userDenied.length > 0 && { - userDenied: { - apps: userDenied, - guidance: buildUserDeniedGuidance(userDenied), - }, - }), - // Upfront guidance so the model knows what each tier allows BEFORE - // hitting the gate. Only included when something was tier-restricted. - ...(grantedTieredApps.length > 0 && { - tierGuidance: buildTierGuidanceMessage(grantedTieredApps), - }), - screenshotFiltering: adapter.executor.capabilities.screenshotFiltering, - // Where each granted app currently has open windows, across monitors. - // Omitted when the app isn't running or has no normal windows. - ...(windowLocations.length > 0 ? { windowLocations } : {}), - }, - { - // dialogGranted only — skipDialogGrants are idempotent re-grants of - // apps already in the allowlist (no user action, dialog skips them). - // Matching denied_count's this-call-only semantics. - granted_count: dialogGranted.length, - denied_count: dialogDenied.length, - ...tierAssignmentTelemetry(grantedTieredApps), - }, - ); -} - -/** - * For each granted app with open windows, which displays those windows are - * on. Single-monitor setups return an empty array (no multi-monitor signal - * to give). Apps not running, or running with no normal windows, are omitted. - */ -async function buildWindowLocations( - adapter: ComputerUseHostAdapter, - granted: AppGrant[], -): Promise< - Array<{ - bundleId: string; - displayName: string; - displays: Array<{ id: number; label?: string; isPrimary?: boolean }>; - }> -> { - if (granted.length === 0) return []; - - const displays = await adapter.executor.listDisplays(); - if (displays.length <= 1) return []; - - const grantedBundleIds = granted.map((g) => g.bundleId); - const windowLocs = await adapter.executor.findWindowDisplays(grantedBundleIds); - const displayById = new Map(displays.map((d) => [d.displayId, d])); - const idsByBundle = new Map(windowLocs.map((w) => [w.bundleId, w.displayIds])); - - const out = []; - for (const g of granted) { - const displayIds = idsByBundle.get(g.bundleId); - if (!displayIds || displayIds.length === 0) continue; - out.push({ - bundleId: g.bundleId, - displayName: g.displayName, - displays: displayIds.map((id) => { - const d = displayById.get(id); - return { id, label: d?.label, isPrimary: d?.isPrimary }; - }), - }); - } - return out; -} - -/** - * Shared app-resolution + partition + hide-preview pipeline. Extracted from - * `handleRequestAccess` so `handleRequestTeachAccess` can call the same path. - * - * Does the full app-name→InstalledApp resolution, assigns each a tier - * (browser→"read", terminal/IDE→"click", else "full" — see deniedApps.ts), - * splits into already-granted (skip the dialog, preserve grantedAt+tier) vs - * need-dialog, and computes the willHide preview. Unlike the previous - * hard-deny model, ALL apps proceed to the dialog; the tier just constrains - * what actions are allowed once granted. - */ -/** An app assigned a restricted tier (not `"full"`). Used to build the - * guidance message telling the model what it can/can't do. */ -interface TieredApp { - bundleId: string; - displayName: string; - /** Never `"full"` — only restricted tiers are collected. */ - tier: "read" | "click"; -} - -interface AccessRequestParts { - needDialog: ResolvedAppRequest[]; - skipDialogGrants: AppGrant[]; - willHide: Array<{ bundleId: string; displayName: string }>; - /** Resolved apps with `proposedTier !== "full"` — for the guidance text. - * Unresolved apps are omitted (they go to `denied` with `not_installed`). */ - tieredApps: TieredApp[]; - /** Apps stripped by the user's Settings auto-deny list. Surfaced in the - * response with guidance; never reach the dialog. */ - userDenied: Array<{ requestedName: string; displayName: string }>; - /** Apps stripped by the baked-in policy blocklist (streaming/music/ebooks, - * etc. — `deniedApps.isPolicyDenied`). Precedence over userDenied. */ - policyDenied: Array<{ requestedName: string; displayName: string }>; -} - -async function buildAccessRequest( - adapter: ComputerUseHostAdapter, - apps: string[], - allowedApps: AppGrant[], - userDeniedBundleIds: ReadonlySet, - selectedDisplayId?: number, -): Promise { - const alreadyGranted = new Set(allowedApps.map((g) => g.bundleId)); - const installed = await adapter.executor.listInstalledApps(); - const resolved = resolveRequestedApps(apps, installed, alreadyGranted); - - // Policy-level auto-deny (baked-in, not user-configurable). Stripped - // before userDenied — checks bundle ID AND display name (covers - // unresolved requests). Precedence: policy > user setting > tier. - const policyDenied: Array<{ requestedName: string; displayName: string }> = - []; - const afterPolicy: typeof resolved = []; - for (const r of resolved) { - const displayName = r.resolved?.displayName ?? r.requestedName; - if (isPolicyDenied(r.resolved?.bundleId, displayName)) { - policyDenied.push({ requestedName: r.requestedName, displayName }); - } else { - afterPolicy.push(r); - } - } - - // User-configured auto-deny (Settings → Desktop app → Computer Use). - // Stripped BEFORE - // tier assignment — these never reach the dialog regardless of category. - // Bundle-ID match only (the Settings UI picks from installed apps, which - // always have a bundle ID). Unresolved requests pass through to the tier - // system; the user can't preemptively deny an app that isn't installed. - const userDenied: Array<{ requestedName: string; displayName: string }> = []; - const surviving: typeof afterPolicy = []; - for (const r of afterPolicy) { - if (r.resolved && userDeniedBundleIds.has(r.resolved.bundleId)) { - userDenied.push({ - requestedName: r.requestedName, - displayName: r.resolved.displayName, - }); - } else { - surviving.push(r); - } - } - - // Collect resolved apps with a restricted tier for the guidance message. - // Unresolved apps with a restricted tier (e.g. model asks for "Chrome" but - // it's not installed) are omitted — they'll end up in the `denied` list - // with reason "not_installed" and the model will see that instead. - const tieredApps: TieredApp[] = []; - for (const r of surviving) { - if (r.proposedTier === "full" || !r.resolved) continue; - tieredApps.push({ - bundleId: r.resolved.bundleId, - displayName: r.resolved.displayName, - tier: r.proposedTier, - }); - } - - // Idempotence: apps that are already granted skip the dialog and are - // merged into the `granted` response. Existing grants keep their tier - // (which may differ from the current proposedTier if policy changed). - const skipDialog = surviving.filter((r) => r.alreadyGranted); - const needDialog = surviving.filter((r) => !r.alreadyGranted); - - // Populate icons only for what the dialog will actually show. Sequential - // awaits are fine — the Swift module is cached (listInstalledApps above - // loaded it), each N-API call is synchronous, and the darwin executor - // memoizes by path. Failures leave iconDataUrl undefined; renderer falls - // back to a grey box. - for (const r of needDialog) { - if (!r.resolved) continue; - try { - r.resolved.iconDataUrl = await adapter.executor.getAppIcon( - r.resolved.path, - ); - } catch { - // leave undefined - } - } - - const now = Date.now(); - const skipDialogGrants: AppGrant[] = skipDialog - .filter((r) => r.resolved) - .map((r) => { - // Reuse the existing grant (preserving grantedAt + tier) rather than - // synthesizing a new one — keeps Settings-page "Granted 3m ago" honest. - const existing = allowedApps.find( - (g) => g.bundleId === r.resolved!.bundleId, - ); - return ( - existing ?? { - bundleId: r.resolved!.bundleId, - displayName: r.resolved!.displayName, - grantedAt: now, - tier: r.proposedTier, - } - ); - }); - - // Preview what will be hidden if the user approves exactly the requested - // set plus what they already have. All tiers are visible, so everything - // resolved goes in the exempt set. - const exemptForPreview = [ - ...allowedApps.map((a) => a.bundleId), - ...surviving.filter((r) => r.resolved).map((r) => r.resolved!.bundleId), - ]; - const willHide = await adapter.executor.previewHideSet( - exemptForPreview, - selectedDisplayId, - ); - - return { - needDialog, - skipDialogGrants, - willHide, - tieredApps, - userDenied, - policyDenied, - }; -} - -/** - * Build guidance text for apps granted at a restricted tier. Returned - * inline in the okJson response so the model knows upfront what it can - * do with each app, instead of learning by hitting the tier gate. - */ -function buildTierGuidanceMessage(tiered: TieredApp[]): string { - // tier "read" is not category-unique — split so browsers get the CiC hint - // and trading platforms get "ask the user" instead. - const readBrowsers = tiered.filter( - (t) => - t.tier === "read" && - getDeniedCategoryForApp(t.bundleId, t.displayName) === "browser", - ); - const readOther = tiered.filter( - (t) => - t.tier === "read" && - getDeniedCategoryForApp(t.bundleId, t.displayName) !== "browser", - ); - const clickTier = tiered.filter((t) => t.tier === "click"); - - const parts: string[] = []; - - if (readBrowsers.length > 0) { - const names = readBrowsers.map((b) => `"${b.displayName}"`).join(", "); - parts.push( - `${names} ${readBrowsers.length === 1 ? "is a browser" : "are browsers"} — ` + - `granted at tier "read" (visible in screenshots only; no clicks or ` + - `typing). You can read what's on screen but cannot navigate, click, ` + - `or type into ${readBrowsers.length === 1 ? "it" : "them"}. For browser ` + - `interaction, use the Claude-in-Chrome MCP (tools named ` + - `\`mcp__Claude_in_Chrome__*\`; load via ToolSearch if deferred).`, - ); - } - - if (readOther.length > 0) { - const names = readOther.map((t) => `"${t.displayName}"`).join(", "); - parts.push( - `${names} ${readOther.length === 1 ? "is" : "are"} granted at tier ` + - `"read" (visible in screenshots only; no clicks or typing). You can ` + - `read what's on screen but cannot interact. Ask the user to take any ` + - `actions in ${readOther.length === 1 ? "this app" : "these apps"} ` + - `themselves.`, - ); - } - - if (clickTier.length > 0) { - const names = clickTier.map((t) => `"${t.displayName}"`).join(", "); - parts.push( - `${names} ${clickTier.length === 1 ? "has" : "have"} terminal or IDE ` + - `capabilities — granted at tier "click" (visible + plain left-click ` + - `only; NO typing, key presses, right-click, modifier-clicks, or ` + - `drag-drop). You can click buttons and scroll output, but ` + - `${clickTier.length === 1 ? "its" : "their"} integrated terminal and ` + - `editor are off-limits to keyboard input. Right-click (context-menu ` + - `Paste) and dragging text onto ${clickTier.length === 1 ? "it" : "them"} ` + - `require tier "full". For shell commands, use the Bash tool.`, - ); - } - - if (parts.length === 0) return ""; - // Same anti-subversion clause the gate errors carry — said upfront so the - // model doesn't reach for osascript/cliclick after seeing "no clicks/typing". - return parts.join("\n\n") + TIER_ANTI_SUBVERSION; -} - -/** - * Build guidance text for apps stripped by the user's Settings auto-deny - * list. Returned inline in the okJson response so the agent knows (a) the - * app is auto-denied by request_access and (b) the escape hatch - * is to ask the human to edit Settings, not to retry or reword the request. - */ -function buildUserDeniedGuidance( - userDenied: Array<{ requestedName: string; displayName: string }>, -): string { - const names = userDenied.map((d) => `"${d.displayName}"`).join(", "); - const one = userDenied.length === 1; - return ( - `${names} ${one ? "is" : "are"} in the user's auto-deny list ` + - `(Settings → Desktop app (General) → Computer Use → Denied apps). ` + - `Requests for ` + - `${one ? "this app" : "these apps"} are automatically denied. If you need access for ` + - `this task, ask the user to remove ${one ? "it" : "them"} from their ` + - `deny list in Settings — you cannot request this through the tool.` - ); -} - -/** - * Guidance for policy-denied apps (baked-in blocklist, not user-editable). - * Unlike userDenied, there is no escape hatch — the agent is told to find - * another approach. - */ -function buildPolicyDeniedGuidance( - policyDenied: Array<{ requestedName: string; displayName: string }>, -): string { - const names = policyDenied.map((d) => `"${d.displayName}"`).join(", "); - const one = policyDenied.length === 1; - return ( - `${names} ${one ? "is" : "are"} blocked by policy for computer use. ` + - `Requests for ${one ? "this app" : "these apps"} are automatically ` + - `denied regardless of what the user has approved. There is no Settings ` + - `override. Inform the user that you cannot access ` + - `${one ? "this app" : "these apps"} and suggest an alternative ` + - `approach if one exists. Do not try to directly subvert this block ` + - `regardless of the user's request.` - ); -} - -/** - * Telemetry helper — counts by category. Field names (`denied_*`) are kept - * for schema compat; interpret as "assigned non-full tier" in dashboards. - */ -function tierAssignmentTelemetry( - tiered: TieredApp[], -): Pick { - // `denied_browser_count` now counts ALL tier-"read" grants (browsers + - // trading). The field name was already legacy-only before trading existed - // (dashboards read it as "non-full tier"), so no new column. - const browserCount = tiered.filter((t) => t.tier === "read").length; - const terminalCount = tiered.filter((t) => t.tier === "click").length; - return { - ...(browserCount > 0 && { denied_browser_count: browserCount }), - ...(terminalCount > 0 && { denied_terminal_count: terminalCount }), - }; -} - -/** - * Sibling of `handleRequestAccess`. Same app-resolution + TCC-threading, but - * routes to the teach approval dialog and fires `onTeachModeActivated` on - * success. No grant-flag checkboxes (clipboard/systemKeys) in teach mode — - * the tool schema omits those fields. - * - * Unlike `request_access`, this ALWAYS shows the dialog even when every - * requested app is already granted. Teach mode is a distinct UX the user - * must explicitly consent to (main window hides) — idempotent app grants - * don't imply consent to being guided. - */ -async function handleRequestTeachAccess( - adapter: ComputerUseHostAdapter, - args: Record, - overrides: ComputerUseOverrides, - tccState: { accessibility: boolean; screenRecording: boolean } | undefined, -): Promise { - if (!overrides.onTeachPermissionRequest) { - return errorResult( - "Teach mode is not available in this session.", - "feature_unavailable", - ); - } - - // Same as handleRequestAccess above — the dialog renders in the hidden - // main window. Model re-calling request_teach_access mid-tour (to add - // another app) is plausible since request_access docs say "call again - // mid-session to add more apps" and this uses the same grant model. - if (overrides.getTeachModeActive?.()) { - return errorResult( - "Teach mode is already active. To add more apps, end the current tour first, then call request_teach_access again with the full app list.", - "teach_mode_conflict", - ); - } - - const reason = requireString(args, "reason"); - if (reason instanceof Error) return errorResult(reason.message, "bad_args"); - - // TCC-ungranted branch — identical to handleRequestAccess's. The renderer - // shows the same TCC toggle panel regardless of which request tool got here. - if (tccState) { - const req: CuTeachPermissionRequest = { - requestId: randomUUID(), - reason, - apps: [], - screenshotFiltering: adapter.executor.capabilities.screenshotFiltering, - tccState, - }; - await overrides.onTeachPermissionRequest(req); - - // Same re-check as handleRequestAccess — user may have granted while the - // dialog was up, and the pre-dialog snapshot would mislead the model. - const recheck = await adapter.ensureOsPermissions(); - if (recheck.granted) { - return errorResult( - "macOS Accessibility and Screen Recording are now both granted. " + - "Call request_teach_access again immediately — the next call will " + - "show the app selection list.", - ); - } - - const missing: string[] = []; - if (!recheck.accessibility) missing.push("Accessibility"); - if (!recheck.screenRecording) missing.push("Screen Recording"); - return errorResult( - `macOS ${missing.join(" and ")} permission(s) not yet granted. ` + - `The permission panel has been shown. Once the user grants the ` + - `missing permission(s), call request_teach_access again.`, - "tcc_not_granted", - ); - } - - const rawApps = args.apps; - if (!Array.isArray(rawApps) || !rawApps.every((a) => typeof a === "string")) { - return errorResult('"apps" must be an array of strings.', "bad_args"); - } - const apps = rawApps as string[]; - - const { - needDialog, - skipDialogGrants, - willHide, - tieredApps, - userDenied, - policyDenied, - } = await buildAccessRequest( - adapter, - apps, - overrides.allowedApps, - new Set(overrides.userDeniedBundleIds), - overrides.selectedDisplayId, - ); - - // All requested apps were user-denied (or unresolvable) and none pre-granted - // — skip the dialog entirely. Without this, onTeachPermissionRequest fires - // with apps:[] and the user sees an empty approval dialog where Allow and - // Deny produce the same result (granted=[] → teachModeActive stays false). - // handleRequestAccess has the equivalent guard at the needDialog.length - // check; teach didn't need one before user-deny because needDialog=[] - // previously implied skipDialogGrants.length > 0 (all-already-granted). - if (needDialog.length === 0 && skipDialogGrants.length === 0) { - return okJson( - { - granted: [], - denied: [], - ...(policyDenied.length > 0 && { - policyDenied: { - apps: policyDenied, - guidance: buildPolicyDeniedGuidance(policyDenied), - }, - }), - ...(userDenied.length > 0 && { - userDenied: { - apps: userDenied, - guidance: buildUserDeniedGuidance(userDenied), - }, - }), - teachModeActive: false, - screenshotFiltering: adapter.executor.capabilities.screenshotFiltering, - }, - { granted_count: 0, denied_count: 0 }, - ); - } - - const req: CuTeachPermissionRequest = { - requestId: randomUUID(), - reason, - apps: needDialog, - screenshotFiltering: adapter.executor.capabilities.screenshotFiltering, - ...(willHide.length > 0 && { - willHide, - autoUnhideEnabled: adapter.getAutoUnhideEnabled(), - }), - }; - const response = await overrides.onTeachPermissionRequest(req); - - const granted = [...skipDialogGrants, ...response.granted]; - // Gate on explicit dialog consent, NOT on merged grant length. - // skipDialogGrants are pre-existing idempotent app grants — they don't - // imply the user said yes to THIS dialog. Without the userConsented - // check, Deny would still activate teach mode whenever any requested - // app was previously granted (worst case: needDialog=[] → Allow and - // Deny payloads are structurally identical). - const teachModeActive = response.userConsented === true && granted.length > 0; - if (teachModeActive) { - overrides.onTeachModeActivated?.(); - } - - const grantedBundleIds = new Set(granted.map((g) => g.bundleId)); - const grantedTieredApps = tieredApps.filter((t) => - grantedBundleIds.has(t.bundleId), - ); - - return okJson( - { - granted, - denied: response.denied, - ...(policyDenied.length > 0 && { - policyDenied: { - apps: policyDenied, - guidance: buildPolicyDeniedGuidance(policyDenied), - }, - }), - ...(userDenied.length > 0 && { - userDenied: { - apps: userDenied, - guidance: buildUserDeniedGuidance(userDenied), - }, - }), - ...(grantedTieredApps.length > 0 && { - tierGuidance: buildTierGuidanceMessage(grantedTieredApps), - }), - teachModeActive, - screenshotFiltering: adapter.executor.capabilities.screenshotFiltering, - }, - { - // response.granted only — skipDialogGrants are idempotent re-grants. - // See handleRequestAccess's parallel comment. - granted_count: response.granted.length, - denied_count: response.denied.length, - ...tierAssignmentTelemetry(grantedTieredApps), - }, - ); -} - -// --------------------------------------------------------------------------- -// teach_step + teach_batch — shared step primitives -// --------------------------------------------------------------------------- - -/** A fully-validated teach step, anchor already scaled to logical points. */ -interface ValidatedTeachStep { - explanation: string; - nextPreview: string; - anchorLogical: TeachStepRequest["anchorLogical"]; - actions: Array>; -} - -/** - * Validate one raw step record and scale its anchor. `label` is prefixed to - * error messages so teach_batch can say `steps[2].actions[0]` instead of - * just `actions[0]`. - * - * The anchor transform is the whole coordinate story: model sends image-pixel - * coords (same space as click coords, per COORDINATES.md), `scaleCoord` turns - * them into logical points against `overrides.lastScreenshot`. For - * teach_batch, lastScreenshot stays at its pre-call value for the entire - * batch — same invariant as computer_batch's "coordinates refer to the - * PRE-BATCH screenshot". Anchors for step 2+ must therefore target elements - * the model can predict will be at those coordinates after step 1's actions. - */ -async function validateTeachStepArgs( - raw: Record, - adapter: ComputerUseHostAdapter, - overrides: ComputerUseOverrides, - label: string, -): Promise { - const explanation = requireString(raw, "explanation"); - if (explanation instanceof Error) { - return new Error(`${label}: ${explanation.message}`); - } - const nextPreview = requireString(raw, "next_preview"); - if (nextPreview instanceof Error) { - return new Error(`${label}: ${nextPreview.message}`); - } - - const actions = raw.actions; - if (!Array.isArray(actions)) { - return new Error( - `${label}: "actions" must be an array (empty is allowed).`, - ); - } - for (const [i, act] of actions.entries()) { - if (typeof act !== "object" || act === null) { - return new Error(`${label}: actions[${i}] must be an object`); - } - const action = (act as Record).action; - if (typeof action !== "string") { - return new Error(`${label}: actions[${i}].action must be a string`); - } - if (!BATCHABLE_ACTIONS.has(action)) { - return new Error( - `${label}: actions[${i}].action="${action}" is not allowed. ` + - `Allowed: ${[...BATCHABLE_ACTIONS].join(", ")}.`, - ); - } - } - - let anchorLogical: TeachStepRequest["anchorLogical"]; - if (raw.anchor !== undefined) { - const anchor = raw.anchor; - if ( - !Array.isArray(anchor) || - anchor.length !== 2 || - typeof anchor[0] !== "number" || - typeof anchor[1] !== "number" || - !Number.isFinite(anchor[0]) || - !Number.isFinite(anchor[1]) - ) { - return new Error( - `${label}: "anchor" must be a [x, y] number tuple or omitted.`, - ); - } - const display = await adapter.executor.getDisplaySize( - overrides.selectedDisplayId, - ); - anchorLogical = scaleCoord( - anchor[0], - anchor[1], - overrides.coordinateMode, - display, - overrides.lastScreenshot, - adapter.logger, - ); - } - - return { - explanation, - nextPreview, - anchorLogical, - actions: actions as Array>, - }; -} - -/** Outcome of showing one tooltip + running its actions. */ -type TeachStepOutcome = - | { kind: "exit" } - | { kind: "ok"; results: BatchActionResult[] } - | { - kind: "action_error"; - executed: number; - failed: BatchActionResult; - remaining: number; - /** The inner action's telemetry (error_kind), forwarded so the - * caller can pass it to okJson and keep cu_tool_call accurate - * when the failure happened inside a batch. */ - telemetry: CuCallTelemetry | undefined; - }; - -/** - * Show the tooltip, block for Next/Exit, run actions on Next. - * - * Action execution is a straight lift from `handleComputerBatch`: - * prepareForAction ONCE per step (the user clicked Next — they consented to - * that step's sequence), pixelValidation OFF (committed sequence), frontmost - * gate still per-action, stop-on-first-error with partial results. - * - * Empty `actions` is valid — "read this, click Next to continue" steps. - * Assumes `overrides.onTeachStep` is set (caller guards). - */ -async function executeTeachStep( - step: ValidatedTeachStep, - adapter: ComputerUseHostAdapter, - overrides: ComputerUseOverrides, - subGates: CuSubGates, -): Promise { - // Block until Next or Exit. Same pending-promise pattern as - // onPermissionRequest — host stores the resolver, overlay IPC fires it. - // `!` is safe: both callers guard on overrides.onTeachStep before reaching here. - const stepResult = await overrides.onTeachStep!({ - explanation: step.explanation, - nextPreview: step.nextPreview, - anchorLogical: step.anchorLogical, - }); - - if (stepResult.action === "exit") { - // The host's Exit handler also calls stopSession, so the turn is - // already unwinding. Caller decides what to return for the transcript. - // A PREVIOUS step's left_mouse_down may have left the OS button held. - await releaseHeldMouse(adapter); - return { kind: "exit" }; - } - - // Next clicked. Flip overlay to spinner before we start driving. - overrides.onTeachWorking?.(); - - if (step.actions.length === 0) { - return { kind: "ok", results: [] }; - } - - if (subGates.hideBeforeAction) { - const hidden = await adapter.executor.prepareForAction( - overrides.allowedApps.map((a) => a.bundleId), - overrides.selectedDisplayId, - ); - if (hidden.length > 0) { - overrides.onAppsHidden?.(hidden); - } - } - - const stepSubGates: CuSubGates = { - ...subGates, - hideBeforeAction: false, - pixelValidation: false, - // Anchors are pre-computed against the display at batch start. - // A mid-batch resolver switch would break tooltip positioning. - autoTargetDisplay: false, - }; - - const results: BatchActionResult[] = []; - for (const [i, act] of step.actions.entries()) { - // Same abort check as handleComputerBatch — Exit calls stopSession so - // this IS the exit path, just caught mid-dispatch instead of at the - // onTeachStep await above. Callers already handle { kind: "exit" }. - if (overrides.isAborted?.()) { - await releaseHeldMouse(adapter); - return { kind: "exit" }; - } - // Same inter-step settle as handleComputerBatch. - if (i > 0) await sleep(10); - const action = act.action as string; - - // Drop mid-step screenshot piggyback — same invariant as computer_batch. - // Click coords stay anchored to the screenshot the model took BEFORE - // calling teach_step/teach_batch. - const { screenshot: _dropped, ...inner } = await dispatchAction( - action, - act, - adapter, - overrides, - stepSubGates, - ); - - const text = firstTextContent(inner); - const result = { action, ok: !inner.isError, output: text }; - results.push(result); - - if (inner.isError) { - await releaseHeldMouse(adapter); - return { - kind: "action_error", - executed: results.length - 1, - failed: result, - remaining: step.actions.length - results.length, - telemetry: inner.telemetry, - }; - } - } - - return { kind: "ok", results }; -} - -/** - * Fold a fresh screenshot into the result. Eliminates the separate - * screenshot tool call the model would otherwise make before the next - * teach_step (one fewer API round trip per step). handleScreenshot - * runs its own prepareForAction — that's correct: actions may have - * opened something outside the allowlist. The .screenshot piggyback - * flows through to serverDef.ts's stash → lastScreenshot updates → - * the next teach_step.anchor scales against THIS image, which is what - * the model is now looking at. - */ -async function appendTeachScreenshot( - resultJson: unknown, - adapter: ComputerUseHostAdapter, - overrides: ComputerUseOverrides, - subGates: CuSubGates, -): Promise { - const shotResult = await handleScreenshot(adapter, overrides, subGates); - if (shotResult.isError) { - // Hide+screenshot failed (rare — e.g. SCContentFilter error). Don't - // tank the step; just omit the image. Model will call screenshot - // itself and see the real error. - return okJson(resultJson); - } - return { - content: [ - { type: "text", text: JSON.stringify(resultJson) }, - // handleScreenshot's content is [maybeMonitorNote, maybeHiddenNote, - // image]. Spread all — both notes are useful context and the model - // expects them alongside screenshots. - ...shotResult.content, - ], - // For serverDef.ts to stash. Next teach_step.anchor scales against this. - screenshot: shotResult.screenshot, - }; -} - -/** - * Show one guided-tour tooltip and block until the user clicks Next or Exit. - * On Next, execute `actions[]` with `computer_batch` semantics. - */ -async function handleTeachStep( - adapter: ComputerUseHostAdapter, - args: Record, - overrides: ComputerUseOverrides, - subGates: CuSubGates, -): Promise { - if (!overrides.onTeachStep) { - return errorResult( - "Teach mode is not active. Call request_teach_access first.", - "teach_mode_not_active", - ); - } - - const step = await validateTeachStepArgs( - args, - adapter, - overrides, - "teach_step", - ); - if (step instanceof Error) return errorResult(step.message, "bad_args"); - - const outcome = await executeTeachStep(step, adapter, overrides, subGates); - - if (outcome.kind === "exit") { - return okJson({ exited: true }); - } - if (outcome.kind === "action_error") { - return okJson( - { - executed: outcome.executed, - failed: outcome.failed, - remaining: outcome.remaining, - }, - outcome.telemetry, - ); - } - - // ok. No screenshot for empty actions — screen didn't change, model's - // existing screenshot is still accurate. - if (step.actions.length === 0) { - return okJson({ executed: 0, results: [] }); - } - return appendTeachScreenshot( - { executed: outcome.results.length, results: outcome.results }, - adapter, - overrides, - subGates, - ); -} - -/** - * Queue a whole guided tour in one tool call. Parallels `computer_batch`: N - * steps → one model→API round trip instead of N. Each step still blocks for - * its own Next click (the user paces the tour), but the model doesn't wait - * for a round trip between steps. - * - * Validates ALL steps upfront so a typo in step 5 doesn't surface after the - * user has already clicked through steps 1–4. - * - * Anchors for every step scale against the pre-call `lastScreenshot` — same - * PRE-BATCH invariant as computer_batch. Steps 2+ should either omit anchor - * (centered tooltip) or target elements the model predicts won't have moved. - * - * Result shape: - * {exited: true, stepsCompleted: N} — user clicked Exit - * {stepsCompleted, stepFailed, executed, failed, …} — action error at step N - * {stepsCompleted, results: [...]} + screenshot — all steps ran - */ -async function handleTeachBatch( - adapter: ComputerUseHostAdapter, - args: Record, - overrides: ComputerUseOverrides, - subGates: CuSubGates, -): Promise { - if (!overrides.onTeachStep) { - return errorResult( - "Teach mode is not active. Call request_teach_access first.", - "teach_mode_not_active", - ); - } - - const rawSteps = args.steps; - if (!Array.isArray(rawSteps) || rawSteps.length < 1) { - return errorResult('"steps" must be a non-empty array.', "bad_args"); - } - - // Validate upfront — fail fast before showing any tooltip. - const steps: ValidatedTeachStep[] = []; - for (const [i, raw] of rawSteps.entries()) { - if (typeof raw !== "object" || raw === null) { - return errorResult(`steps[${i}] must be an object`, "bad_args"); - } - const v = await validateTeachStepArgs( - raw as Record, - adapter, - overrides, - `steps[${i}]`, - ); - if (v instanceof Error) return errorResult(v.message, "bad_args"); - steps.push(v); - } - - const allResults: BatchActionResult[][] = []; - for (const [i, step] of steps.entries()) { - const outcome = await executeTeachStep(step, adapter, overrides, subGates); - - if (outcome.kind === "exit") { - return okJson({ exited: true, stepsCompleted: i }); - } - if (outcome.kind === "action_error") { - return okJson( - { - stepsCompleted: i, - stepFailed: i, - executed: outcome.executed, - failed: outcome.failed, - remaining: outcome.remaining, - results: allResults, - }, - outcome.telemetry, - ); - } - allResults.push(outcome.results); - } - - // Final screenshot only if any step ran actions (screen changed). - const screenChanged = steps.some((s) => s.actions.length > 0); - const resultJson = { stepsCompleted: steps.length, results: allResults }; - if (!screenChanged) { - return okJson(resultJson); - } - return appendTeachScreenshot(resultJson, adapter, overrides, subGates); -} - -/** - * Build the hidden-apps note that accompanies a screenshot. Tells the model - * which apps got hidden (not in allowlist) and how to add them. Returns - * undefined when nothing was hidden since the last screenshot. - */ -async function buildHiddenNote( - adapter: ComputerUseHostAdapter, - hiddenSinceLastSeen: string[], -): Promise { - if (hiddenSinceLastSeen.length === 0) return undefined; - const running = await adapter.executor.listRunningApps(); - const nameOf = new Map(running.map((a) => [a.bundleId, a.displayName])); - const names = hiddenSinceLastSeen.map((id) => nameOf.get(id) ?? id); - const list = names.map((n) => `"${n}"`).join(", "); - const one = names.length === 1; - return ( - `${list} ${one ? "was" : "were"} open and got hidden before this screenshot ` + - `(not in the session allowlist). If a previous action was meant to open ` + - `${one ? "it" : "one of them"}, that's why you don't see it — call ` + - `request_access to add ${one ? "it" : "them"} to the allowlist.` - ); -} - -/** - * Assign a human-readable label to each display. Falls back to `display N` - * when NSScreen.localizedName is undefined; disambiguates identical labels - * (matched-pair external monitors) with a `(2)` suffix. Used by both - * buildMonitorNote and handleSwitchDisplay so the name the model sees in a - * screenshot note is the same name it can pass back to switch_display. - */ -function uniqueDisplayLabels( - displays: readonly DisplayGeometry[], -): Map { - // Sort by displayId so the (N) suffix is stable regardless of - // NSScreen.screens iteration order — same label always maps to same - // physical display across buildMonitorNote → switch_display round-trip, - // even if display configuration reorders between the two calls. - const sorted = [...displays].sort((a, b) => a.displayId - b.displayId); - const counts = new Map(); - const out = new Map(); - for (const d of sorted) { - const base = d.label ?? `display ${d.displayId}`; - const n = (counts.get(base) ?? 0) + 1; - counts.set(base, n); - out.set(d.displayId, n === 1 ? base : `${base} (${n})`); - } - return out; -} - -/** - * Build the monitor-context text that accompanies a screenshot. Tells the - * model which monitor it's looking at (by human name), lists other attached - * monitors, and flags when the monitor changed vs. the previous screenshot. - * - * Only emitted when there are 2+ displays AND (first screenshot OR the - * display changed). Single-monitor setups and steady-state same-monitor - * screenshots get no text — avoids noise. - */ -async function buildMonitorNote( - adapter: ComputerUseHostAdapter, - shotDisplayId: number, - lastDisplayId: number | undefined, - canSwitchDisplay: boolean, -): Promise { - // listDisplays failure (e.g. Swift returns zero screens during monitor - // hot-unplug) must not tank the screenshot — this note is optional context. - let displays; - try { - displays = await adapter.executor.listDisplays(); - } catch (e) { - adapter.logger.warn(`[computer-use] listDisplays failed: ${String(e)}`); - return undefined; - } - if (displays.length < 2) return undefined; - - const labels = uniqueDisplayLabels(displays); - const nameOf = (id: number): string => labels.get(id) ?? `display ${id}`; - - const current = nameOf(shotDisplayId); - const others = displays - .filter((d) => d.displayId !== shotDisplayId) - .map((d) => nameOf(d.displayId)); - const switchHint = canSwitchDisplay - ? " Use switch_display to capture a different monitor." - : ""; - const othersList = - others.length > 0 - ? ` Other attached monitors: ${others.map((n) => `"${n}"`).join(", ")}.` + - switchHint - : ""; - - // 0 is kCGNullDirectDisplay (sentinel from old sessions persisted - // pre-multimon) — treat same as undefined. - if (lastDisplayId === undefined || lastDisplayId === 0) { - return `This screenshot was taken on monitor "${current}".` + othersList; - } - if (lastDisplayId !== shotDisplayId) { - const prev = nameOf(lastDisplayId); - return ( - `This screenshot was taken on monitor "${current}", which is different ` + - `from your previous screenshot (taken on "${prev}").` + - othersList - ); - } - return undefined; -} - -async function handleScreenshot( - adapter: ComputerUseHostAdapter, - overrides: ComputerUseOverrides, - subGates: CuSubGates, -): Promise { - // §2 — empty allowlist → tool error, no screenshot. - if (overrides.allowedApps.length === 0) { - return errorResult( - "No applications are granted for this session. Call request_access first.", - "allowlist_empty", - ); - } - - // Atomic resolve→prepare→capture (one Swift call, no scheduler gap). - // Off → fall through to separate-calls path below. - if (subGates.autoTargetDisplay) { - // Model's explicit switch_display pin overrides everything — Swift's - // straight cuDisplayInfo(forDisplayID:) passthrough, no chase chain. - // Otherwise sticky display: only auto-resolve when the allowed-app - // set has changed since the display was last resolved. Prevents the - // resolver yanking the display on every screenshot. - const allowedBundleIds = overrides.allowedApps.map((a) => a.bundleId); - const currentAppSetKey = allowedBundleIds.slice().sort().join(","); - const appSetChanged = currentAppSetKey !== overrides.displayResolvedForApps; - const autoResolve = !overrides.displayPinnedByModel && appSetChanged; - - const result = await adapter.executor.resolvePrepareCapture({ - allowedBundleIds, - preferredDisplayId: overrides.selectedDisplayId, - autoResolve, - // Keep the hideBeforeAction sub-gate independently rollable — - // atomic path honors the same toggle the non-atomic path checks - // at the prepareForAction call site. - doHide: subGates.hideBeforeAction, - }); - - // Non-atomic path's takeScreenshotWithRetry has a MIN_SCREENSHOT_BYTES - // check + retry. The atomic call is expensive (resolve+prepare+capture), - // so no retry here — just a warning when the result is implausibly - // small (transient display state like sleep wake). Skip when - // captureError is set (base64 is intentionally empty then). - if ( - result.captureError === undefined && - decodedByteLength(result.base64) < MIN_SCREENSHOT_BYTES - ) { - adapter.logger.warn( - `[computer-use] resolvePrepareCapture result implausibly small (${decodedByteLength(result.base64)} bytes decoded) — possible transient display state`, - ); - } - - // Resolver picked a different display than the session had selected - // (host window moved, or allowed app on a different display). Write - // the pick back to session so teach overlay positioning and subsequent - // non-resolver calls track the same display. Fire-and-forget. - if (result.displayId !== overrides.selectedDisplayId) { - adapter.logger.debug( - `[computer-use] resolver: preferred=${overrides.selectedDisplayId} resolved=${result.displayId}`, - ); - overrides.onResolvedDisplayUpdated?.(result.displayId); - } - // Record the app set this display was resolved for, so the next - // screenshot skips auto-resolve until the set changes again. Gated on - // autoResolve (not just appSetChanged) — when pinned, we didn't - // actually resolve, so don't update the key. - if (autoResolve) { - overrides.onDisplayResolvedForApps?.(currentAppSetKey); - } - - // Report hidden apps only when the model has already seen the screen. - let hiddenSinceLastSeen: string[] = []; - if (overrides.lastScreenshot !== undefined) { - hiddenSinceLastSeen = result.hidden; - } - if (result.hidden.length > 0) { - overrides.onAppsHidden?.(result.hidden); - } - - // Partial-success case: hide succeeded, capture failed (SCK perm - // revoked mid-session). onAppsHidden fired above so auto-unhide will - // restore hidden apps at turn end. Now surface the error to the model. - if (result.captureError !== undefined) { - return errorResult(result.captureError, "capture_failed"); - } - - const hiddenNote = await buildHiddenNote(adapter, hiddenSinceLastSeen); - - // Cherry-pick — don't spread `result` (would leak resolver fields into lastScreenshot). - const shot: ScreenshotResult = { - base64: result.base64, - width: result.width, - height: result.height, - displayWidth: result.displayWidth, - displayHeight: result.displayHeight, - displayId: result.displayId, - originX: result.originX, - originY: result.originY, - }; - - const monitorNote = await buildMonitorNote( - adapter, - shot.displayId, - overrides.lastScreenshot?.displayId, - overrides.onDisplayPinned !== undefined, - ); - - return { - content: [ - ...(monitorNote ? [{ type: "text" as const, text: monitorNote }] : []), - ...(hiddenNote ? [{ type: "text" as const, text: hiddenNote }] : []), - { - type: "image", - data: shot.base64, - mimeType: "image/jpeg", - }, - ], - screenshot: shot, - }; - } - - // Same hide+defocus sequence as input actions. Screenshot needs hide too - // — if a non-allowlisted app is on top, SCContentFilter would composite it - // out, but the pixels BELOW it are what the model would see, and those are - // NOT what's actually there. Hiding first makes the screenshot TRUE. - let hiddenSinceLastSeen: string[] = []; - if (subGates.hideBeforeAction) { - const hidden = await adapter.executor.prepareForAction( - overrides.allowedApps.map((a) => a.bundleId), - overrides.selectedDisplayId, - ); - // "Something appeared since the model last looked." Report whenever: - // (a) prepare hid something AND - // (b) the model has ALREADY SEEN the screen (lastScreenshot is set). - // - // (b) is the discriminator that silences the first screenshot's - // expected-noise hide. NOT a delta against a cumulative set — that was - // the earlier bug: cuHiddenDuringTurn only grows, so once Preview is in - // it (from the first screenshot's hide), subsequent re-hides of Preview - // delta to zero. The double-click → Preview opens → re-hide → silent - // loop never breaks. - // - // With this check: every re-hide fires. If the model loops "click → file - // opens in Preview → screenshot → Preview hidden", it gets told EVERY - // time. Eventually it'll request_access for Preview (or give up). - // - // False positive: user alt-tabs mid-turn → Safari re-hidden → reported. - // Rare, and "Safari appeared" is at worst mild noise — far better than - // the false-negative of never explaining why the file vanished. - if (overrides.lastScreenshot !== undefined) { - hiddenSinceLastSeen = hidden; - } - if (hidden.length > 0) { - overrides.onAppsHidden?.(hidden); - } - } - - const allowedBundleIds = overrides.allowedApps.map((g) => g.bundleId); - const shot = await takeScreenshotWithRetry( - adapter.executor, - allowedBundleIds, - adapter.logger, - overrides.selectedDisplayId, - ); - - const hiddenNote = await buildHiddenNote(adapter, hiddenSinceLastSeen); - - const monitorNote = await buildMonitorNote( - adapter, - shot.displayId, - overrides.lastScreenshot?.displayId, - overrides.onDisplayPinned !== undefined, - ); - - return { - content: [ - ...(monitorNote ? [{ type: "text" as const, text: monitorNote }] : []), - ...(hiddenNote ? [{ type: "text" as const, text: hiddenNote }] : []), - { - type: "image", - data: shot.base64, - mimeType: "image/jpeg", - }, - ], - // Piggybacked for serverDef.ts to stash on InternalServerContext. - screenshot: shot, - }; -} - -/** - * Region-crop upscaled screenshot. Coord invariant (computer_use_v2.py:1092): - * click coords ALWAYS refer to the full-screen screenshot, never the zoom. - * Enforced structurally: this handler's return has NO `.screenshot` field, - * so serverDef.ts's `if (result.screenshot)` branch cannot fire and - * `cuLastScreenshot` is never touched. `executor.zoom()`'s return type also - * lacks displayWidth/displayHeight, so it's not assignable to - * `ScreenshotResult` even by accident. - */ -async function handleZoom( - adapter: ComputerUseHostAdapter, - args: Record, - overrides: ComputerUseOverrides, -): Promise { - // region: [x0, y0, x1, y1] in IMAGE-PX of lastScreenshot — same space the - // model reads click coords from. - const region = args.region; - if (!Array.isArray(region) || region.length !== 4) { - return errorResult( - "region must be an array of length 4: [x0, y0, x1, y1]", - "bad_args", - ); - } - const [x0, y0, x1, y1] = region; - if (![x0, y0, x1, y1].every((v) => typeof v === "number" && v >= 0)) { - return errorResult( - "region values must be non-negative numbers", - "bad_args", - ); - } - if (x1 <= x0) - return errorResult("region x1 must be greater than x0", "bad_args"); - if (y1 <= y0) - return errorResult("region y1 must be greater than y0", "bad_args"); - - const last = overrides.lastScreenshot; - if (!last) { - return errorResult( - "take a screenshot before zooming (region coords are relative to it)", - "state_conflict", - ); - } - if (x1 > last.width || y1 > last.height) { - return errorResult( - `region exceeds screenshot bounds (${last.width}×${last.height})`, - "bad_args", - ); - } - - // image-px → logical-pt. Same ratio as scaleCoord (:198-199) — - // displayWidth / width, not 1/scaleFactor. The ratio is folded. - const ratioX = last.displayWidth / last.width; - const ratioY = last.displayHeight / last.height; - const regionLogical = { - x: x0 * ratioX, - y: y0 * ratioY, - w: (x1 - x0) * ratioX, - h: (y1 - y0) * ratioY, - }; - - const allowedIds = overrides.allowedApps.map((g) => g.bundleId); - // Crop from the same display as lastScreenshot so the zoom region - // matches the image the model is reading coords from. - const zoomed = await adapter.executor.zoom( - regionLogical, - allowedIds, - last.displayId, - ); - - // Return the image. NO `.screenshot` piggyback — this is the invariant. - return { - content: [{ type: "image", data: zoomed.base64, mimeType: "image/jpeg" }], - }; -} - -/** Shared handler for all five click variants. */ -async function handleClickVariant( - adapter: ComputerUseHostAdapter, - args: Record, - overrides: ComputerUseOverrides, - subGates: CuSubGates, - button: "left" | "right" | "middle", - count: 1 | 2 | 3, -): Promise { - // A prior left_mouse_down may have set mouseButtonHeld without a matching - // left_mouse_up (e.g. drag rejected by a tier gate, model falls back to - // left_click). executor.click() does its own mouseDown+mouseUp, releasing - // the OS button — but without this, the JS flag stays true and all - // subsequent mouse_move calls take the held-button path ("mouse"/ - // "mouse_full" actionKind + hit-test), causing spurious rejections on - // click-tier and read-tier windows. Release first so click() gets a clean - // slate. - if (mouseButtonHeld) { - await adapter.executor.mouseUp(); - mouseButtonHeld = false; - mouseMoved = false; - } - - const coord = extractCoordinate(args); - if (coord instanceof Error) return errorResult(coord.message, "bad_args"); - const [rawX, rawY] = coord; - - // left_click(coordinate=[x,y], text="shift") — hold modifiers - // during the click. Same chord parsing as the key tool. - let modifiers: string[] | undefined; - if (args.text !== undefined) { - if (typeof args.text !== "string") { - return errorResult("text must be a string", "bad_args"); - } - // Same gate as handleKey/handleHoldKey. withModifiers presses each name - // via native.key(m, "press") — a non-modifier like "q" in text="cmd+q" - // gets pressed while Cmd is held → Cmd+Q fires before the click. - if ( - isSystemKeyCombo(args.text, adapter.executor.capabilities.platform) && - !overrides.grantFlags.systemKeyCombos - ) { - return errorResult( - `The modifier chord "${args.text}" would fire a system shortcut. ` + - "Request the systemKeyCombos grant flag via request_access, or use " + - "only modifier keys (shift, ctrl, alt, cmd) in the text parameter.", - "grant_flag_required", - ); - } - modifiers = parseKeyChord(args.text); - } - - // Right/middle-click and any click with a modifier chord escalate to - // keyboard-equivalent input at tier "click" (context-menu Paste, chord - // keystrokes). Compute once, pass to both gates. - const clickActionKind: CuActionKind = - button !== "left" || (modifiers !== undefined && modifiers.length > 0) - ? "mouse_full" - : "mouse"; - - const gate = await runInputActionGates( - adapter, - overrides, - subGates, - clickActionKind, - ); - if (gate) return gate; - - const display = await adapter.executor.getDisplaySize( - overrides.selectedDisplayId, - ); - - // §6 item P — pixel-validation staleness check. Sub-gated. - // Runs AFTER the gates (no point validating if we're about to refuse - // anyway) but BEFORE the executor call. - if (subGates.pixelValidation) { - const { xPct, yPct } = coordToPercentageForPixelCompare( - rawX, - rawY, - overrides.coordinateMode, - overrides.lastScreenshot, - ); - const validation = await validateClickTarget( - adapter.cropRawPatch, - overrides.lastScreenshot, - xPct, - yPct, - async () => { - // The fresh screenshot for validation uses the SAME allow-set as - // the model's last screenshot did, so we compare like with like. - const allowedIds = overrides.allowedApps.map((g) => g.bundleId); - try { - // Fresh shot must match lastScreenshot's display, not the current - // selection — pixel-compare is against the model's last image. - return await adapter.executor.screenshot({ - allowedBundleIds: allowedIds, - displayId: overrides.lastScreenshot?.displayId, - }); - } catch { - return null; - } - }, - adapter.logger, - ); - if (!validation.valid && validation.warning) { - // Warning result — model told to re-screenshot. - return okText(validation.warning); - } - } - - const { x, y } = scaleCoord( - rawX, - rawY, - overrides.coordinateMode, - display, - overrides.lastScreenshot, - adapter.logger, - ); - - const hitGate = await runHitTestGate( - adapter, - overrides, - subGates, - x, - y, - clickActionKind, - ); - if (hitGate) return hitGate; - - await adapter.executor.click(x, y, button, count, modifiers); - return okText("Clicked."); -} - -async function handleType( - adapter: ComputerUseHostAdapter, - args: Record, - overrides: ComputerUseOverrides, - subGates: CuSubGates, -): Promise { - const text = requireString(args, "text"); - if (text instanceof Error) return errorResult(text.message, "bad_args"); - - const gate = await runInputActionGates( - adapter, - overrides, - subGates, - "keyboard", - ); - if (gate) return gate; - - // §6 item 3 — clipboard-paste fast path for multi-line. Sub-gated AND - // requires clipboardWrite grant. The save/restore + read-back-verify - // lives in the EXECUTOR (task #5), not here. Here we just route. - const viaClipboard = - text.includes("\n") && - overrides.grantFlags.clipboardWrite && - subGates.clipboardPasteMultiline; - - if (viaClipboard) { - await adapter.executor.type(text, { viaClipboard: true }); - return okText("Typed (via clipboard)."); - } - - // §6 item 7 — grapheme-cluster iteration. Prevents ZWJ emoji → �. - // §6 item 4 — 8ms between graphemes (125 Hz USB polling). Battle-tested: - // sleep BEFORE each keystroke, not after. - // - // \n, \r, \t MUST route through executor.key(), not type(). Two reasons: - // 1. enigo.text("\n") on macOS posts a stale CGEvent with virtualKey=0 - // after stripping the newline — virtualKey 0 is the 'a' key, so a - // ghost 'a' gets typed. Upstream bug in enigo 0.6.1 fast_text(). - // 2. Unicode text-insertion of '\n' is not a Return key press. URL bars - // and terminals ignore it; the model's intent (submit/execute) is lost. - // CRLF (\r\n) is one grapheme cluster (UAX #29 GB3), so check for it too. - const graphemes = segmentGraphemes(text); - for (const [i, g] of graphemes.entries()) { - // Same abort check as handleComputerBatch. At 8ms/grapheme a 50-char - // type() runs ~400ms; this is where an in-flight batch actually - // spends its time. - if (overrides.isAborted?.()) { - return errorResult( - `Typing aborted after ${i} of ${graphemes.length} graphemes (user interrupt).`, - ); - } - await sleep(INTER_GRAPHEME_SLEEP_MS); - if (g === "\n" || g === "\r" || g === "\r\n") { - await adapter.executor.key("return"); - } else if (g === "\t") { - await adapter.executor.key("tab"); - } else { - await adapter.executor.type(g, { viaClipboard: false }); - } - } - return okText(`Typed ${graphemes.length} grapheme(s).`); -} - -async function handleKey( - adapter: ComputerUseHostAdapter, - args: Record, - overrides: ComputerUseOverrides, - subGates: CuSubGates, -): Promise { - const keySequence = requireString(args, "text"); - if (keySequence instanceof Error) - return errorResult("text is required", "bad_args"); - - // Cap 100, error strings match. - let repeat: number | undefined; - if (args.repeat !== undefined) { - if ( - typeof args.repeat !== "number" || - !Number.isInteger(args.repeat) || - args.repeat < 1 - ) { - return errorResult("repeat must be a positive integer", "bad_args"); - } - if (args.repeat > 100) { - return errorResult("repeat exceeds maximum of 100", "bad_args"); - } - repeat = args.repeat; - } - - // §2 — blocklist check BEFORE gates. A blocked combo with an ungranted - // app frontmost should return the blocklist error, not the frontmost - // error — the model's fix is to request the flag, not change focus. - if ( - isSystemKeyCombo(keySequence, adapter.executor.capabilities.platform) && - !overrides.grantFlags.systemKeyCombos - ) { - return errorResult( - `"${keySequence}" is a system-level shortcut. Request the \`systemKeyCombos\` grant via request_access to use it.`, - "grant_flag_required", - ); - } - - const gate = await runInputActionGates( - adapter, - overrides, - subGates, - "keyboard", - ); - if (gate) return gate; - - await adapter.executor.key(keySequence, repeat); - return okText("Key pressed."); -} - -async function handleScroll( - adapter: ComputerUseHostAdapter, - args: Record, - overrides: ComputerUseOverrides, - subGates: CuSubGates, -): Promise { - const coord = extractCoordinate(args); - if (coord instanceof Error) return errorResult(coord.message, "bad_args"); - const [rawX, rawY] = coord; - - // Uses scroll_direction + scroll_amount. - // Map to our dx/dy executor interface. - const dir = args.scroll_direction; - if (dir !== "up" && dir !== "down" && dir !== "left" && dir !== "right") { - return errorResult( - "scroll_direction must be 'up', 'down', 'left', or 'right'", - "bad_args", - ); - } - const amount = args.scroll_amount; - if (typeof amount !== "number" || !Number.isInteger(amount) || amount < 0) { - return errorResult("scroll_amount must be a non-negative int", "bad_args"); - } - if (amount > 100) { - return errorResult("scroll_amount exceeds maximum of 100", "bad_args"); - } - // up → dy = -amount; down → dy = +amount; left → dx = -amount; right → dx = +amount. - const dx = dir === "left" ? -amount : dir === "right" ? amount : 0; - const dy = dir === "up" ? -amount : dir === "down" ? amount : 0; - - const gate = await runInputActionGates(adapter, overrides, subGates, "mouse"); - if (gate) return gate; - - const display = await adapter.executor.getDisplaySize( - overrides.selectedDisplayId, - ); - const { x, y } = scaleCoord( - rawX, - rawY, - overrides.coordinateMode, - display, - overrides.lastScreenshot, - adapter.logger, - ); - - // When the button is held, executor.scroll's internal moveMouse generates - // a leftMouseDragged event (enigo reads NSEvent.pressedMouseButtons) — - // same mechanism as handleMoveMouse's held-button path. Upgrade the - // hit-test to "mouse_full" so scroll can't be used to drag-drop text onto - // a click-tier terminal, and mark mouseMoved so the subsequent - // left_mouse_up hit-tests as a drop not a click-release. - const hitGate = await runHitTestGate( - adapter, - overrides, - subGates, - x, - y, - mouseButtonHeld ? "mouse_full" : "mouse", - ); - if (hitGate) return hitGate; - if (mouseButtonHeld) mouseMoved = true; - - await adapter.executor.scroll(x, y, dx, dy); - return okText("Scrolled."); -} - -async function handleDrag( - adapter: ComputerUseHostAdapter, - args: Record, - overrides: ComputerUseOverrides, - subGates: CuSubGates, -): Promise { - // executor.drag() does its own press+release internally. Without this - // defensive clear, a prior left_mouse_down leaves mouseButtonHeld=true - // across the drag and desyncs the flag from OS state — same mechanism as - // the handleClickVariant clear above. Release first so drag() gets a - // clean slate. - if (mouseButtonHeld) { - await adapter.executor.mouseUp(); - mouseButtonHeld = false; - mouseMoved = false; - } - - // `coordinate` is the END point - // (required). `start_coordinate` is OPTIONAL — when omitted, drag from - // current cursor position. - const endCoord = extractCoordinate(args, "coordinate"); - if (endCoord instanceof Error) - return errorResult(endCoord.message, "bad_args"); - const rawTo = endCoord; - - let rawFrom: [number, number] | undefined; - if (args.start_coordinate !== undefined) { - const startCoord = extractCoordinate(args, "start_coordinate"); - if (startCoord instanceof Error) - return errorResult(startCoord.message, "bad_args"); - rawFrom = startCoord; - } - // else: rawFrom stays undefined → executor drags from current cursor. - - const gate = await runInputActionGates(adapter, overrides, subGates, "mouse"); - if (gate) return gate; - - const display = await adapter.executor.getDisplaySize( - overrides.selectedDisplayId, - ); - const from = - rawFrom === undefined - ? undefined - : scaleCoord( - rawFrom[0], - rawFrom[1], - overrides.coordinateMode, - display, - overrides.lastScreenshot, - adapter.logger, - ); - const to = scaleCoord( - rawTo[0], - rawTo[1], - overrides.coordinateMode, - display, - overrides.lastScreenshot, - adapter.logger, - ); - - // Check both drag endpoints. `from` is where the mouseDown happens (picks - // up), `to` is where mouseUp happens (drops). When start_coordinate is - // omitted the drag begins at the cursor — same bypass as mouse_move → - // left_mouse_down, so read the cursor and hit-test it (mirrors - // handleLeftMouseDown). - // - // The `to` endpoint uses "mouse_full" (not "mouse"): dropping text onto a - // terminal inserts it as if typed (macOS text drag-drop). Same threat as - // right-click→Paste. `from` stays "mouse" — picking up is a read. - const fromPoint = from ?? (await adapter.executor.getCursorPosition()); - const fromGate = await runHitTestGate( - adapter, - overrides, - subGates, - fromPoint.x, - fromPoint.y, - "mouse", - ); - if (fromGate) return fromGate; - const toGate = await runHitTestGate( - adapter, - overrides, - subGates, - to.x, - to.y, - "mouse_full", - ); - if (toGate) return toGate; - - await adapter.executor.drag(from, to); - return okText("Dragged."); -} - -async function handleMoveMouse( - adapter: ComputerUseHostAdapter, - args: Record, - overrides: ComputerUseOverrides, - subGates: CuSubGates, -): Promise { - const coord = extractCoordinate(args); - if (coord instanceof Error) return errorResult(coord.message, "bad_args"); - const [rawX, rawY] = coord; - - // When the button is held, moveMouse generates leftMouseDragged events on - // the window under the cursor — that's interaction, not positioning. - // Upgrade to "mouse" and hit-test the destination. When the button is NOT - // held: pure positioning, passes at any tier, no hit-test (mouseDown/Up - // hit-test the cursor to close the mouse_move→left_mouse_down decomposition). - const actionKind: CuActionKind = mouseButtonHeld ? "mouse" : "mouse_position"; - const gate = await runInputActionGates( - adapter, - overrides, - subGates, - actionKind, - ); - if (gate) return gate; - - const display = await adapter.executor.getDisplaySize( - overrides.selectedDisplayId, - ); - const { x, y } = scaleCoord( - rawX, - rawY, - overrides.coordinateMode, - display, - overrides.lastScreenshot, - adapter.logger, - ); - - if (mouseButtonHeld) { - // "mouse_full" — same as left_click_drag's to-endpoint. Dragging onto a - // click-tier terminal is text injection regardless of which primitive - // (atomic drag vs. decomposed down/move/up) delivers the events. - const hitGate = await runHitTestGate( - adapter, - overrides, - subGates, - x, - y, - "mouse_full", - ); - if (hitGate) return hitGate; - } - - await adapter.executor.moveMouse(x, y); - if (mouseButtonHeld) mouseMoved = true; - return okText("Moved."); -} - -async function handleOpenApplication( - adapter: ComputerUseHostAdapter, - args: Record, - overrides: ComputerUseOverrides, -): Promise { - const app = requireString(args, "app"); - if (app instanceof Error) return errorResult(app.message, "bad_args"); - - // Resolve display-name → bundle ID. Same logic as request_access. - const allowed = new Set(overrides.allowedApps.map((g) => g.bundleId)); - let targetBundleId: string | undefined; - - if (looksLikeBundleId(app) && allowed.has(app)) { - targetBundleId = app; - } else { - // Try display name → bundle ID, but ONLY against the allowlist itself. - // Avoids paying the listInstalledApps() cost on the hot path and is - // arguably more correct: if the user granted "Slack", the model asking - // to open "Slack" should match THAT grant. - const match = overrides.allowedApps.find( - (g) => g.displayName.toLowerCase() === app.toLowerCase(), - ); - targetBundleId = match?.bundleId; - } - - if (!targetBundleId || !allowed.has(targetBundleId)) { - return errorResult( - `"${app}" is not granted for this session. Call request_access first.`, - "app_not_granted", - ); - } - - // open_application works at any tier — bringing an app forward is exactly - // what tier "read" enables (you need it on screen to screenshot it). The - // tier gates on click/type catch any follow-up interaction. - - await adapter.executor.openApp(targetBundleId); - - // On multi-monitor setups, macOS may place the opened window on a monitor - // the resolver won't pick (e.g. Claude + another allowed app are co-located - // elsewhere). Nudge the model toward switch_display BEFORE it wastes steps - // clicking on dock icons. Single-monitor → no hint. listDisplays failure is - // non-fatal — the hint is advisory. - if (overrides.onDisplayPinned !== undefined) { - let displayCount = 1; - try { - displayCount = (await adapter.executor.listDisplays()).length; - } catch { - // hint skipped - } - if (displayCount >= 2) { - return okText( - `Opened "${app}". If it isn't visible in the next screenshot, it may ` + - `have opened on a different monitor — use switch_display to check.`, - ); - } - } - - return okText(`Opened "${app}".`); -} - -async function handleSwitchDisplay( - adapter: ComputerUseHostAdapter, - args: Record, - overrides: ComputerUseOverrides, -): Promise { - const display = requireString(args, "display"); - if (display instanceof Error) return errorResult(display.message, "bad_args"); - - if (!overrides.onDisplayPinned) { - return errorResult( - "Display switching is not available in this session.", - "feature_unavailable", - ); - } - - if (display.toLowerCase() === "auto") { - overrides.onDisplayPinned(undefined); - return okText( - "Returned to automatic monitor selection. Call screenshot to continue.", - ); - } - - // Resolve label → displayId fresh. Same source buildMonitorNote reads, - // so whatever name the model saw in a screenshot note resolves here. - let displays; - try { - displays = await adapter.executor.listDisplays(); - } catch (e) { - return errorResult( - `Failed to enumerate displays: ${String(e)}`, - "display_error", - ); - } - - if (displays.length < 2) { - return errorResult( - "Only one monitor is connected. There is nothing to switch to.", - "bad_args", - ); - } - - const labels = uniqueDisplayLabels(displays); - const wanted = display.toLowerCase(); - const target = displays.find( - (d) => labels.get(d.displayId)?.toLowerCase() === wanted, - ); - if (!target) { - const available = displays - .map((d) => `"${labels.get(d.displayId)}"`) - .join(", "); - return errorResult( - `No monitor named "${display}" is connected. Available monitors: ${available}.`, - "bad_args", - ); - } - - overrides.onDisplayPinned(target.displayId); - return okText( - `Switched to monitor "${labels.get(target.displayId)}". Call screenshot to see it.`, - ); -} - -function handleListGrantedApplications( - overrides: ComputerUseOverrides, -): CuCallToolResult { - return okJson({ - allowedApps: overrides.allowedApps, - grantFlags: overrides.grantFlags, - }); -} - -async function handleReadClipboard( - adapter: ComputerUseHostAdapter, - overrides: ComputerUseOverrides, - subGates: CuSubGates, -): Promise { - if (!overrides.grantFlags.clipboardRead) { - return errorResult( - "Clipboard read is not granted. Request `clipboardRead` via request_access.", - "grant_flag_required", - ); - } - - // read_clipboard doesn't route through runInputActionGates — sync here so - // reading after clicking into a click-tier app sees the cleared clipboard - // (same as what the app's own Paste would see). - if (subGates.clipboardGuard) { - const frontmost = await adapter.executor.getFrontmostApp(); - const tierByBundleId = new Map( - overrides.allowedApps.map((a) => [a.bundleId, a.tier] as const), - ); - const frontmostTier = frontmost - ? tierByBundleId.get(frontmost.bundleId) - : undefined; - await syncClipboardStash(adapter, overrides, frontmostTier === "click"); - } - - // clipboardGuard may have stashed+cleared — read the actual (possibly - // empty) clipboard. The agent sees what the app would see. - const text = await adapter.executor.readClipboard(); - return okJson({ text }); -} - -async function handleWriteClipboard( - adapter: ComputerUseHostAdapter, - args: Record, - overrides: ComputerUseOverrides, - subGates: CuSubGates, -): Promise { - if (!overrides.grantFlags.clipboardWrite) { - return errorResult( - "Clipboard write is not granted. Request `clipboardWrite` via request_access.", - "grant_flag_required", - ); - } - const text = requireString(args, "text"); - if (text instanceof Error) return errorResult(text.message, "bad_args"); - - if (subGates.clipboardGuard) { - const frontmost = await adapter.executor.getFrontmostApp(); - const tierByBundleId = new Map( - overrides.allowedApps.map((a) => [a.bundleId, a.tier] as const), - ); - const frontmostTier = frontmost - ? tierByBundleId.get(frontmost.bundleId) - : undefined; - - // Defense-in-depth for the clipboardGuard bypass: write_clipboard + - // left_click on a click-tier app's UI Paste button. The re-clear in - // syncClipboardStash already defeats it (the next action clobbers the - // write), but rejecting here gives the agent a clear signal instead of - // silently voiding its write. - if (frontmost && frontmostTier === "click") { - return errorResult( - `"${frontmost.displayName}" is a tier-"click" app and currently ` + - `frontmost. write_clipboard is blocked because the next action ` + - `would clear the clipboard anyway — a UI Paste button in this ` + - `app cannot be used to inject text. Bring a tier-"full" app ` + - `forward before writing to the clipboard.` + - TIER_ANTI_SUBVERSION, - "tier_insufficient", - ); - } - - // write_clipboard doesn't route through runInputActionGates — sync here - // so clicking away from a click-tier app then writing restores the user's - // stash before the agent's text lands. - await syncClipboardStash(adapter, overrides, frontmostTier === "click"); - } - - await adapter.executor.writeClipboard(text); - return okText("Clipboard written."); -} - -/** - * wait(duration=N). Sleeps N seconds, capped at 100. - * No frontmost gate — no input, nothing to protect. Kill-switch + TCC - * are checked in handleToolCall before dispatch reaches here. - */ -async function handleWait( - args: Record, -): Promise { - const duration = args.duration; - if (typeof duration !== "number" || !Number.isFinite(duration)) { - return errorResult("duration must be a number", "bad_args"); - } - if (duration < 0) { - return errorResult("duration must be non-negative", "bad_args"); - } - if (duration > 100) { - return errorResult( - "duration is too long. Duration is in seconds.", - "bad_args", - ); - } - await sleep(duration * 1000); - return okText(`Waited ${duration}s.`); -} - -/** - * Returns "X=...,Y=..." plain text. We return richer JSON with - * coordinateSpace annotation — the model handles both shapes. - * - * When lastScreenshot is present: inverse of scaleCoord — logical points → - * image-pixels via `imageX = logicalX × (screenshotWidth / displayWidth)`. - * Uses capture-time dims so the returned coords match what the model would - * read off that screenshot. - * - * No frontmost gate — read-only, no input. - */ -async function handleCursorPosition( - adapter: ComputerUseHostAdapter, - overrides: ComputerUseOverrides, -): Promise { - const logical = await adapter.executor.getCursorPosition(); - const shot = overrides.lastScreenshot; - if (shot) { - // Inverse of scaleCoord: subtract capture-time origin to go from - // virtual-screen to display-relative before the image-px transform. - const localX = logical.x - shot.originX; - const localY = logical.y - shot.originY; - // Cursor off the captured display (multi-monitor): local coords go - // negative or exceed display dims. Return logical_points + hint rather - // than garbage image-px. - if ( - localX < 0 || - localX > shot.displayWidth || - localY < 0 || - localY > shot.displayHeight - ) { - return okJson({ - x: logical.x, - y: logical.y, - coordinateSpace: "logical_points", - note: "cursor is on a different monitor than your last screenshot; take a fresh screenshot", - }); - } - const x = Math.round(localX * (shot.width / shot.displayWidth)); - const y = Math.round(localY * (shot.height / shot.displayHeight)); - return okJson({ x, y, coordinateSpace: "image_pixels" }); - } - return okJson({ - x: logical.x, - y: logical.y, - coordinateSpace: "logical_points", - note: "take a screenshot first for image-pixel coordinates", - }); -} - -/** - * Presses each key in the - * chord, sleeps duration seconds, releases in reverse. Same duration bounds - * as wait. Keyboard action → frontmost gate applies; same systemKeyCombos - * blocklist check as key. - */ -async function handleHoldKey( - adapter: ComputerUseHostAdapter, - args: Record, - overrides: ComputerUseOverrides, - subGates: CuSubGates, -): Promise { - const text = requireString(args, "text"); - if (text instanceof Error) return errorResult(text.message, "bad_args"); - - const duration = args.duration; - if (typeof duration !== "number" || !Number.isFinite(duration)) { - return errorResult("duration must be a number", "bad_args"); - } - if (duration < 0) { - return errorResult("duration must be non-negative", "bad_args"); - } - if (duration > 100) { - return errorResult( - "duration is too long. Duration is in seconds.", - "bad_args", - ); - } - - // Blocklist check BEFORE gates — same reasoning as handleKey. Holding - // cmd+q is just as dangerous as tapping it. - if ( - isSystemKeyCombo(text, adapter.executor.capabilities.platform) && - !overrides.grantFlags.systemKeyCombos - ) { - return errorResult( - `"${text}" is a system-level shortcut. Request the \`systemKeyCombos\` grant via request_access to use it.`, - "grant_flag_required", - ); - } - - const gate = await runInputActionGates( - adapter, - overrides, - subGates, - "keyboard", - ); - if (gate) return gate; - - const keyNames = parseKeyChord(text); - await adapter.executor.holdKey(keyNames, duration * 1000); - return okText("Key held."); -} - -/** - * Raw press at current cursor, no coordinate. - * Move first with mouse_move. Errors if already held. - */ -async function handleLeftMouseDown( - adapter: ComputerUseHostAdapter, - overrides: ComputerUseOverrides, - subGates: CuSubGates, -): Promise { - if (mouseButtonHeld) { - return errorResult( - "mouse button already held, call left_mouse_up first", - "state_conflict", - ); - } - - const gate = await runInputActionGates(adapter, overrides, subGates, "mouse"); - if (gate) return gate; - - // macOS routes mouseDown to the window under the cursor, not the frontmost - // app. Without this hit-test, mouse_move (positioning, passes at any tier) - // + left_mouse_down decomposes a click that lands on a tier-"read" window - // overlapping a tier-"full" frontmost app — bypassing runHitTestGate's - // whole purpose. All three are batchable, so the bypass is atomic. - const cursor = await adapter.executor.getCursorPosition(); - const hitGate = await runHitTestGate( - adapter, - overrides, - subGates, - cursor.x, - cursor.y, - "mouse", - ); - if (hitGate) return hitGate; - - await adapter.executor.mouseDown(); - mouseButtonHeld = true; - mouseMoved = false; - return okText("Mouse button pressed."); -} - -/** - * Raw release at current cursor. Does NOT error - * if not held (idempotent release). - */ -async function handleLeftMouseUp( - adapter: ComputerUseHostAdapter, - overrides: ComputerUseOverrides, - subGates: CuSubGates, -): Promise { - // Any gate rejection here must release the button FIRST — otherwise the - // OS button stays pressed and mouseButtonHeld stays true. Recovery - // attempts (mouse_move back to a safe app) would generate leftMouseDragged - // events into whatever window is under the cursor, including the very - // read-tier window the gate was protecting. A single mouseUp on a - // restricted window is one event; a stuck button is cascading damage. - // - // This includes the frontmost gate: focus can change between mouseDown and - // mouseUp (something else grabbed focus), in which case runInputActionGates - // rejects here even though it passed at mouseDown. - const releaseFirst = async ( - err: CuCallToolResult, - ): Promise => { - await adapter.executor.mouseUp(); - mouseButtonHeld = false; - mouseMoved = false; - return err; - }; - - const gate = await runInputActionGates(adapter, overrides, subGates, "mouse"); - if (gate) return releaseFirst(gate); - - // When the cursor moved since mouseDown, this is a drop (text-injection - // vector) — hit-test at "mouse_full" same as left_click_drag's `to`. When - // NO move happened, this is a click-release — same semantics as the atomic - // left_click, hit-test at "mouse". Without this distinction, a decomposed - // click on a click-tier app fails here while the atomic left_click works, - // and releaseFirst fires mouseUp anyway so the OS sees a complete click - // while the model gets a misleading error. - const cursor = await adapter.executor.getCursorPosition(); - const hitGate = await runHitTestGate( - adapter, - overrides, - subGates, - cursor.x, - cursor.y, - mouseMoved ? "mouse_full" : "mouse", - ); - if (hitGate) return releaseFirst(hitGate); - - await adapter.executor.mouseUp(); - mouseButtonHeld = false; - mouseMoved = false; - return okText("Mouse button released."); -} - -// --------------------------------------------------------------------------- -// Batch dispatch -// --------------------------------------------------------------------------- - -/** - * Actions allowed inside a computer_batch call. Excludes request_access, - * open_application, clipboard, list_granted (no latency benefit, complicates - * security model). - */ -const BATCHABLE_ACTIONS: ReadonlySet = new Set([ - "key", - "type", - "mouse_move", - "left_click", - "left_click_drag", - "right_click", - "middle_click", - "double_click", - "triple_click", - "scroll", - "hold_key", - "screenshot", - "cursor_position", - "left_mouse_down", - "left_mouse_up", - "wait", -]); - -interface BatchActionResult { - action: string; - ok: boolean; - output: string; -} - -/** - * Executes `actions: [{action, …}, …]` - * sequentially in ONE model→API round trip — the dominant latency cost - * (seconds, vs. ~50ms local overhead per action). - * - * Gate semantics (the security model): - * - Kill-switch + TCC: checked ONCE by handleToolCall before reaching here. - * - prepareForAction: run ONCE at the top. The user approved "do this - * sequence"; hiding apps per-action is wasted work and fast-pathed anyway. - * - Frontmost gate: checked PER ACTION. State can change mid-batch — a - * click might open a non-allowed app. This is the safety net: if action - * 3 of 5 opened Safari (not allowed), action 4's frontmost check fires - * and stops the batch there. - * - PixelCompare: SKIPPED inside batch. The model committed to the full - * sequence without intermediate screenshots; validating mid-batch clicks - * against a pre-batch screenshot would false-positive constantly. - * - * Both skips are implemented by passing `{...subGates, hideBeforeAction: - * false, pixelValidation: false}` to each inner dispatch — the handlers' - * existing gate logic does the right thing, no new code paths. - * - * Stop-on-first-error: accumulate results, on - * first `isError` stop executing, return everything so far + the error. The - * model sees exactly where the batch broke and what succeeded before it. - * - * Mid-batch screenshots are allowed (for inspection) but NEVER piggyback — - * their `.screenshot` field is dropped. Same invariant as zoom: click coords - * always refer to the PRE-BATCH `lastScreenshot`. If the model wants to click - * based on a new screenshot, it ends the batch and screenshots separately. - */ -async function handleComputerBatch( - adapter: ComputerUseHostAdapter, - args: Record, - overrides: ComputerUseOverrides, - subGates: CuSubGates, -): Promise { - const actions = args.actions; - if (!Array.isArray(actions) || actions.length === 0) { - return errorResult("actions must be a non-empty array", "bad_args"); - } - - for (const [i, act] of actions.entries()) { - if (typeof act !== "object" || act === null) { - return errorResult(`actions[${i}] must be an object`, "bad_args"); - } - const action = (act as Record).action; - if (typeof action !== "string") { - return errorResult(`actions[${i}].action must be a string`, "bad_args"); - } - if (!BATCHABLE_ACTIONS.has(action)) { - return errorResult( - `actions[${i}].action="${action}" is not allowed in a batch. ` + - `Allowed: ${[...BATCHABLE_ACTIONS].join(", ")}.`, - "bad_args", - ); - } - } - - // prepareForAction ONCE. After this, inner dispatches skip it via - // hideBeforeAction:false. - if (subGates.hideBeforeAction) { - const hidden = await adapter.executor.prepareForAction( - overrides.allowedApps.map((a) => a.bundleId), - overrides.selectedDisplayId, - ); - if (hidden.length > 0) { - overrides.onAppsHidden?.(hidden); - } - } - - // Inner actions: skip prepare (already ran), skip pixelCompare (stale by - // design). Frontmost still checked — runInputActionGates does it - // unconditionally. - const batchSubGates: CuSubGates = { - ...subGates, - hideBeforeAction: false, - pixelValidation: false, - // Batch already took its screenshot (appended at end); a mid-batch - // resolver switch would make that screenshot inconsistent with - // earlier clicks' lastScreenshot-based scaleCoord targeting. - autoTargetDisplay: false, - }; - - const results: BatchActionResult[] = []; - for (const [i, act] of actions.entries()) { - // Overlay Stop → host's stopSession → lifecycleState leaves "running" - // synchronously before query.interrupt(). The SDK abort tears down the - // host's await but not this loop — without this check the remaining - // actions fire into a dead session. - if (overrides.isAborted?.()) { - await releaseHeldMouse(adapter); - return errorResult( - `Batch aborted after ${results.length} of ${actions.length} actions (user interrupt).`, - ); - } - - // Small inter-step settle. Synthetic CGEvents post instantly; some apps - // need a tick to process step N's input before step N+1 lands (e.g. a - // click opening a menu before the next click targets a menu item). - if (i > 0) await sleep(10); - - const actionArgs = act as Record; - const action = actionArgs.action as string; - - // Drop mid-batch screenshot piggyback (strip .screenshot). Click coords - // stay anchored to the pre-batch lastScreenshot. - const { screenshot: _dropped, ...inner } = await dispatchAction( - action, - actionArgs, - adapter, - overrides, - batchSubGates, - ); - - const text = firstTextContent(inner); - const result = { action, ok: !inner.isError, output: text }; - results.push(result); - - if (inner.isError) { - // Stop-on-first-error. Return everything so far + the error. - // Forward the inner action's telemetry (error_kind) so cu_tool_call - // reflects the actual failure — without this, batch-internal errors - // emit error_kind: undefined despite the inner handler tagging it. - // Release held mouse: the error may be a mid-grapheme abort in - // handleType, or a frontmost gate, landing between mouse_down and - // mouse_up. - await releaseHeldMouse(adapter); - return okJson( - { - completed: results.slice(0, -1), - failed: result, - remaining: actions.length - results.length, - }, - inner.telemetry, - ); - } - } - - return okJson({ completed: results }); -} - -function firstTextContent(r: CuCallToolResult): string { - const first = r.content[0]; - return first && first.type === "text" ? first.text : ""; -} - -/** - * Action dispatch shared by handleToolCall and handleComputerBatch. Called - * AFTER kill-switch + TCC gates have passed. Never sees request_access — it's - * special-cased in handleToolCall for the tccState thread-through. - */ -async function dispatchAction( - name: string, - a: Record, - adapter: ComputerUseHostAdapter, - overrides: ComputerUseOverrides, - subGates: CuSubGates, -): Promise { - switch (name) { - case "screenshot": - return handleScreenshot(adapter, overrides, subGates); - - case "zoom": - return handleZoom(adapter, a, overrides); - - case "left_click": - return handleClickVariant(adapter, a, overrides, subGates, "left", 1); - case "double_click": - return handleClickVariant(adapter, a, overrides, subGates, "left", 2); - case "triple_click": - return handleClickVariant(adapter, a, overrides, subGates, "left", 3); - case "right_click": - return handleClickVariant(adapter, a, overrides, subGates, "right", 1); - case "middle_click": - return handleClickVariant(adapter, a, overrides, subGates, "middle", 1); - - case "type": - return handleType(adapter, a, overrides, subGates); - - case "key": - return handleKey(adapter, a, overrides, subGates); - - case "scroll": - return handleScroll(adapter, a, overrides, subGates); - - case "left_click_drag": - return handleDrag(adapter, a, overrides, subGates); - - case "mouse_move": - return handleMoveMouse(adapter, a, overrides, subGates); - - case "wait": - return handleWait(a); - - case "cursor_position": - return handleCursorPosition(adapter, overrides); - - case "hold_key": - return handleHoldKey(adapter, a, overrides, subGates); - - case "left_mouse_down": - return handleLeftMouseDown(adapter, overrides, subGates); - - case "left_mouse_up": - return handleLeftMouseUp(adapter, overrides, subGates); - - case "open_application": - return handleOpenApplication(adapter, a, overrides); - - case "switch_display": - return handleSwitchDisplay(adapter, a, overrides); - - case "list_granted_applications": - return handleListGrantedApplications(overrides); - - case "read_clipboard": - return handleReadClipboard(adapter, overrides, subGates); - - case "write_clipboard": - return handleWriteClipboard(adapter, a, overrides, subGates); - - case "computer_batch": - return handleComputerBatch(adapter, a, overrides, subGates); - - default: - return errorResult(`Unknown tool "${name}".`, "bad_args"); - } -} - -// --------------------------------------------------------------------------- -// Main dispatch -// --------------------------------------------------------------------------- - -export async function handleToolCall( - adapter: ComputerUseHostAdapter, - name: string, - args: unknown, - rawOverrides: ComputerUseOverrides, -): Promise { - const { logger, serverName } = adapter; - - // Normalize the allowlist before any gate runs: - // - // (a) Strip user-denied. A grant from a previous session (before the user - // added the app to Settings → Desktop app → Computer Use → Denied apps) - // must not survive. Without - // this, a stale grant bypasses the auto-deny. Stripped silently — the - // agent already saw the userDenied guidance at request_access time, and - // a live frontmost-gate rejection cites "not in allowed applications". - // - // (b) Strip policy-denied. Same story as (a) for a grant that predates a - // blocklist addition. buildAccessRequest denies these up front for new - // requests; this catches stale persisted grants. - // - // (c) Backfill tier. A grant persisted before the tier field existed has - // `tier: undefined`, which `tierSatisfies` treats as `"full"` — wrong - // for a legacy Chrome grant. Assign the hardcoded tier based on - // bundle-ID category. Modern grants already have a tier. - // - // `.some()` guard keeps the hot path (empty deny list, no legacy grants) - // zero-alloc. - const userDeniedSet = new Set(rawOverrides.userDeniedBundleIds); - const overrides: ComputerUseOverrides = rawOverrides.allowedApps.some( - (a) => - a.tier === undefined || - userDeniedSet.has(a.bundleId) || - isPolicyDenied(a.bundleId, a.displayName), - ) - ? { - ...rawOverrides, - allowedApps: rawOverrides.allowedApps - .filter((a) => !userDeniedSet.has(a.bundleId)) - .filter((a) => !isPolicyDenied(a.bundleId, a.displayName)) - .map((a) => - a.tier !== undefined - ? a - : { ...a, tier: getDefaultTierForApp(a.bundleId, a.displayName) }, - ), - } - : rawOverrides; - - // ─── Gate 1: kill switch ───────────────────────────────────────────── - if (adapter.isDisabled()) { - return errorResult( - "Computer control is disabled in Settings. Enable it and try again.", - "other", - ); - } - - // ─── Gate 2: TCC ───────────────────────────────────────────────────── - // Accessibility + Screen Recording on macOS. Pure check — no dialog, - // no relaunch. `request_access` is exempted: it threads the ungranted - // state through to the renderer, which shows a TCC toggle panel instead - // of the app list. Every other tool short-circuits here. - const osPerms = await adapter.ensureOsPermissions(); - let tccState: - | { accessibility: boolean; screenRecording: boolean } - | undefined; - if (!osPerms.granted) { - // Both request_* tools thread tccState through to the renderer's - // TCC toggle panel. Every other tool short-circuits. - if (name !== "request_access" && name !== "request_teach_access") { - return errorResult( - "Accessibility and Screen Recording permissions are required. " + - "Call request_access to show the permission panel.", - "tcc_not_granted", - ); - } - tccState = { - accessibility: osPerms.accessibility, - screenRecording: osPerms.screenRecording, - }; - } - - // ─── Gate 3: global CU lock ────────────────────────────────────────── - // At most one session uses CU at a time. Every tool including - // request_access hits the CHECK — even showing the approval dialog while - // another session holds the lock would be confusing ("why approve access - // that can't be used?"). - // - // But ACQUIRE is split: request_access and list_granted_applications - // check-without-acquire (the overlay + notifications are driven by - // cuLockChanged, and showing "Claude is using your computer" while the - // agent is only ASKING for access is premature). First action tool - // acquires and the overlay appears. If the user denies and no action - // follows, the overlay never shows. - // - // request_teach_access is NOT in this set — approving teach mode HIDES - // the main window (via onTeachModeActivated), and the lock must be held - // before that happens. Otherwise a concurrent session's request_access - // would render its dialog in an invisible main window during the gap - // between hide and the first teach_step (seconds of model inference). - // The old acquire-always-at-Gate-3 behavior was correct for teach; only - // the non-teach permission tools benefit from deferral. - // - // Host releases on idle/stop/archive; this package never releases. Both - // Cowork (LAM) and CCD (LSM) wire checkCuLock via the shared cuLock - // singleton. When undefined (tests/future hosts), no gate — absence of - // the mechanism ≠ locked out. - const deferAcquire = defersLockAcquire(name); - const lock = overrides.checkCuLock?.(); - if (lock) { - if (lock.holder !== undefined && !lock.isSelf) { - return errorResult( - "Another Claude session is currently using the computer. Wait for " + - "the user to acknowledge it is finished (stop button in the Claude " + - "window), or find a non-computer-use approach if one is readily " + - "apparent.", - "cu_lock_held", - ); - } - if (lock.holder === undefined && !deferAcquire) { - // Acquire. Emits cuLockChanged → overlay shows. Idempotent — if - // someone else acquired between check and here (won't happen on a - // single-threaded event loop, but defensive), this is a no-op. - overrides.acquireCuLock?.(); - // Fresh lock holder → any prior session's mouseButtonHeld is stale - // (e.g. overlay stop mid-drag). Clear it so this session doesn't get - // a spurious "already held" error. resetMouseButtonHeld is file-local; - // this is the one non-test callsite. - resetMouseButtonHeld(); - } - // lock.isSelf → already held by us, proceed. - // lock.holder === undefined && deferAcquire → - // checked but not acquired — proceed, first action will acquire. - } - - // Sub-gates read FRESH every call so a GrowthBook flip takes effect - // mid-session (plan §3). - const subGates = adapter.getSubGates(); - - // Clipboard guard runs per-action inside runInputActionGates + inline in - // handleReadClipboard/handleWriteClipboard. NOT here — per-tool-call sync - // would run once for computer_batch and miss sub-actions 2..N, and would - // fire during deferAcquire tools / `wait` / teach_step's blocking-dialog - // phase where no input is happening. - - const a = asRecord(args); - - logger.silly( - `[${serverName}] tool=${name} args=${JSON.stringify(a).slice(0, 200)}`, - ); - - // ─── Fail-closed dispatch ──────────────────────────────────────────── - // ANY exception below → tool error, executor never left in a half-called - // state. Explicit inversion of the prior `catch → return true` fail-open. - try { - // request_access / request_teach_access: need tccState thread-through; - // dispatchAction never sees them (not batchable). - // teach_step: blocking UI tool, also not batchable; needs subGates for - // its action-execution phase. - if (name === "request_access") { - return await handleRequestAccess(adapter, a, overrides, tccState); - } - if (name === "request_teach_access") { - return await handleRequestTeachAccess(adapter, a, overrides, tccState); - } - if (name === "teach_step") { - return await handleTeachStep(adapter, a, overrides, subGates); - } - if (name === "teach_batch") { - return await handleTeachBatch(adapter, a, overrides, subGates); - } - return await dispatchAction(name, a, adapter, overrides, subGates); - } catch (err) { - // Fail-closed. If the gate machinery itself throws (e.g. - // getFrontmostApp() rejects), the executor has NOT been called yet for - // the gated tools — the gates run before the executor in every handler. - // For ungated tools, the executor may have been mid-call; that's fine — - // the result is still a tool error, never an implicit success. - const msg = err instanceof Error ? err.message : String(err); - logger.error(`[${serverName}] tool=${name} threw: ${msg}`, err); - return errorResult(`Tool "${name}" failed: ${msg}`, "executor_threw"); - } -} - -export const _test = { - scaleCoord, - coordToPercentageForPixelCompare, - segmentGraphemes, - decodedByteLength, - resolveRequestedApps, - buildAccessRequest, - buildTierGuidanceMessage, - buildUserDeniedGuidance, - tierSatisfies, - looksLikeBundleId, - extractCoordinate, - parseKeyChord, - buildMonitorNote, - handleSwitchDisplay, - uniqueDisplayLabels, -}; diff --git a/claude-code-source/node_modules/@ant/computer-use-mcp/src/tools.ts b/claude-code-source/node_modules/@ant/computer-use-mcp/src/tools.ts deleted file mode 100644 index c744a232..00000000 --- a/claude-code-source/node_modules/@ant/computer-use-mcp/src/tools.ts +++ /dev/null @@ -1,706 +0,0 @@ -/** - * MCP tool schemas for the computer-use server. Mirrors - * claude-for-chrome-mcp/src/browserTools.ts in shape (plain `Tool`-shaped - * object literals, no zod). - * - * Coordinate descriptions are baked in at tool-list build time from the - * `chicago_coordinate_mode` gate. The model sees exactly ONE coordinate - * convention in the param descriptions and never learns the other exists. - * The host (`serverDef.ts`) reads the same frozen gate value for - * `scaleCoord` — both must agree or clicks land in the wrong space. - */ - -import type { Tool } from "@modelcontextprotocol/sdk/types.js"; - -import type { CoordinateMode } from "./types.js"; - -// See packages/desktop/computer-use-mcp/COORDINATES.md before touching any -// model-facing coordinate text. Chrome's browserTools.ts:143 is the reference -// phrasing — "pixels from the left edge", no geometry, no number to do math with. -const COORD_DESC: Record = { - pixels: { - x: "Horizontal pixel position read directly from the most recent screenshot image, measured from the left edge. The server handles all scaling.", - y: "Vertical pixel position read directly from the most recent screenshot image, measured from the top edge. The server handles all scaling.", - }, - normalized_0_100: { - x: "Horizontal position as a percentage of screen width, 0.0–100.0 (0 = left edge, 100 = right edge).", - y: "Vertical position as a percentage of screen height, 0.0–100.0 (0 = top edge, 100 = bottom edge).", - }, -}; - -const FRONTMOST_GATE_DESC = - "The frontmost application must be in the session allowlist at the time of this call, or this tool returns an error and does nothing."; - -/** - * Item schema for the `actions` array in `computer_batch`, `teach_step`, and - * `teach_batch`. All three dispatch through the same `dispatchAction` path - * with the same validation — keep this enum in sync with `BATCHABLE_ACTIONS` - * in toolCalls.ts. - */ -const BATCH_ACTION_ITEM_SCHEMA = { - type: "object", - properties: { - action: { - type: "string", - enum: [ - "key", - "type", - "mouse_move", - "left_click", - "left_click_drag", - "right_click", - "middle_click", - "double_click", - "triple_click", - "scroll", - "hold_key", - "screenshot", - "cursor_position", - "left_mouse_down", - "left_mouse_up", - "wait", - ], - description: "The action to perform.", - }, - coordinate: { - type: "array", - items: { type: "number" }, - minItems: 2, - maxItems: 2, - description: - "(x, y) for click/mouse_move/scroll/left_click_drag end point.", - }, - start_coordinate: { - type: "array", - items: { type: "number" }, - minItems: 2, - maxItems: 2, - description: - "(x, y) drag start — left_click_drag only. Omit to drag from current cursor.", - }, - text: { - type: "string", - description: - "For type: the text. For key/hold_key: the chord string. For click/scroll: modifier keys to hold.", - }, - scroll_direction: { - type: "string", - enum: ["up", "down", "left", "right"], - }, - scroll_amount: { type: "integer", minimum: 0, maximum: 100 }, - duration: { - type: "number", - description: "Seconds (0–100). For hold_key/wait.", - }, - repeat: { - type: "integer", - minimum: 1, - maximum: 100, - description: "For key: repeat count.", - }, - }, - required: ["action"], -}; - -/** - * Build the tool list. Parameterized by capabilities and coordinate mode so - * descriptions are honest and unambiguous (plan §1 — "Unfiltered + honest"). - * - * `coordinateMode` MUST match what the host passes to `scaleCoord` at tool- - * -call time. Both should read the same frozen-at-load gate constant. - * - * `installedAppNames` — optional pre-sanitized list of app display names to - * enumerate in the `request_access` description. The caller is responsible - * for sanitization (length cap, character allowlist, sort, count cap) — - * this function just splices the list into the description verbatim. Omit - * to fall back to the generic "display names or bundle IDs" wording. - */ -export function buildComputerUseTools( - caps: { - screenshotFiltering: "native" | "none"; - platform: "darwin" | "win32"; - /** Include request_teach_access + teach_step. Read once at server construction. */ - teachMode?: boolean; - }, - coordinateMode: CoordinateMode, - installedAppNames?: string[], -): Tool[] { - const coord = COORD_DESC[coordinateMode]; - - // Shared hint suffix for BOTH request_access and request_teach_access — - // they use the same resolveRequestedApps path, so the model should get - // the same enumeration for both. - const installedAppsHint = - installedAppNames && installedAppNames.length > 0 - ? ` Available applications on this machine: ${installedAppNames.join(", ")}.` - : ""; - - // [x, y]` tuple — param shape for all - // click/move/scroll tools. - const coordinateTuple = { - type: "array", - items: { type: "number" }, - minItems: 2, - maxItems: 2, - description: `(x, y): ${coord.x}`, - }; - // Modifier hold during click. Shared across all 5 click variants. - const clickModifierText = { - type: "string", - description: - 'Modifier keys to hold during the click (e.g. "shift", "ctrl+shift"). Supports the same syntax as the key tool.', - }; - - const screenshotDesc = - caps.screenshotFiltering === "native" - ? "Take a screenshot of the primary display. Applications not in the session allowlist are excluded at the compositor level — only granted apps and the desktop are visible." - : "Take a screenshot of the primary display. On this platform, screenshots are NOT filtered — all open windows are visible. Input actions targeting apps not in the session allowlist are rejected."; - - return [ - { - name: "request_access", - description: - "Request user permission to control a set of applications for this session. Must be called before any other tool in this server. " + - "The user sees a single dialog listing all requested apps and either allows the whole set or denies it. " + - "Call this again mid-session to add more apps; previously granted apps remain granted. " + - "Returns the granted apps, denied apps, and screenshot filtering capability.", - inputSchema: { - type: "object" as const, - properties: { - apps: { - type: "array", - items: { type: "string" }, - description: - "Application display names (e.g. \"Slack\", \"Calendar\") or bundle identifiers (e.g. \"com.tinyspeck.slackmacgap\"). Display names are resolved case-insensitively against installed apps." + - installedAppsHint, - }, - reason: { - type: "string", - description: - "One-sentence explanation shown to the user in the approval dialog. Explain the task, not the mechanism.", - }, - clipboardRead: { - type: "boolean", - description: - "Also request permission to read the user's clipboard (separate checkbox in the dialog).", - }, - clipboardWrite: { - type: "boolean", - description: - "Also request permission to write the user's clipboard. When granted, multi-line `type` calls use the clipboard fast path.", - }, - systemKeyCombos: { - type: "boolean", - description: - "Also request permission to send system-level key combos (quit app, switch app, lock screen). Without this, those specific combos are blocked.", - }, - }, - required: ["apps", "reason"], - }, - }, - - { - name: "screenshot", - description: - screenshotDesc + - " Returns an error if the allowlist is empty. The returned image is what subsequent click coordinates are relative to.", - inputSchema: { - type: "object" as const, - properties: { - save_to_disk: { - type: "boolean", - description: - "Save the image to disk so it can be attached to a message for the user. Returns the saved path in the tool result. Only set this when you intend to share the image — screenshots you're just looking at don't need saving.", - }, - }, - required: [], - }, - }, - - { - name: "zoom", - description: - "Take a higher-resolution screenshot of a specific region of the last full-screen screenshot. Use this liberally to inspect small text, button labels, or fine UI details that are hard to read in the downsampled full-screen image. " + - "IMPORTANT: Coordinates in subsequent click calls always refer to the full-screen screenshot, never the zoomed image. This tool is read-only for inspecting detail.", - inputSchema: { - type: "object" as const, - properties: { - region: { - type: "array", - items: { type: "integer" }, - minItems: 4, - maxItems: 4, - description: - "(x0, y0, x1, y1): Rectangle to zoom into, in the coordinate space of the most recent full-screen screenshot. x0,y0 = top-left, x1,y1 = bottom-right.", - }, - save_to_disk: { - type: "boolean", - description: - "Save the image to disk so it can be attached to a message for the user. Returns the saved path in the tool result. Only set this when you intend to share the image.", - }, - }, - required: ["region"], - }, - }, - - { - name: "left_click", - description: `Left-click at the given coordinates. ${FRONTMOST_GATE_DESC}`, - inputSchema: { - type: "object" as const, - properties: { - coordinate: coordinateTuple, - text: clickModifierText, - }, - required: ["coordinate"], - }, - }, - - { - name: "double_click", - description: `Double-click at the given coordinates. Selects a word in most text editors. ${FRONTMOST_GATE_DESC}`, - inputSchema: { - type: "object" as const, - properties: { - coordinate: coordinateTuple, - text: clickModifierText, - }, - required: ["coordinate"], - }, - }, - - { - name: "triple_click", - description: `Triple-click at the given coordinates. Selects a line in most text editors. ${FRONTMOST_GATE_DESC}`, - inputSchema: { - type: "object" as const, - properties: { - coordinate: coordinateTuple, - text: clickModifierText, - }, - required: ["coordinate"], - }, - }, - - { - name: "right_click", - description: `Right-click at the given coordinates. Opens a context menu in most applications. ${FRONTMOST_GATE_DESC}`, - inputSchema: { - type: "object" as const, - properties: { - coordinate: coordinateTuple, - text: clickModifierText, - }, - required: ["coordinate"], - }, - }, - - { - name: "middle_click", - description: `Middle-click (scroll-wheel click) at the given coordinates. ${FRONTMOST_GATE_DESC}`, - inputSchema: { - type: "object" as const, - properties: { - coordinate: coordinateTuple, - text: clickModifierText, - }, - required: ["coordinate"], - }, - }, - - { - name: "type", - description: `Type text into whatever currently has keyboard focus. ${FRONTMOST_GATE_DESC} Newlines are supported. For keyboard shortcuts use \`key\` instead.`, - inputSchema: { - type: "object" as const, - properties: { - text: { type: "string", description: "Text to type." }, - }, - required: ["text"], - }, - }, - - { - name: "key", - description: - `Press a key or key combination (e.g. "return", "escape", "cmd+a", "ctrl+shift+tab"). ${FRONTMOST_GATE_DESC} ` + - "System-level combos (quit app, switch app, lock screen) require the `systemKeyCombos` grant — without it they return an error. All other combos work.", - inputSchema: { - type: "object" as const, - properties: { - text: { - type: "string", - description: 'Modifiers joined with "+", e.g. "cmd+shift+a".', - }, - repeat: { - type: "integer", - minimum: 1, - maximum: 100, - description: "Number of times to repeat the key press. Default is 1.", - }, - }, - required: ["text"], - }, - }, - - { - name: "scroll", - description: `Scroll at the given coordinates. ${FRONTMOST_GATE_DESC}`, - inputSchema: { - type: "object" as const, - properties: { - coordinate: coordinateTuple, - scroll_direction: { - type: "string", - enum: ["up", "down", "left", "right"], - description: "Direction to scroll.", - }, - scroll_amount: { - type: "integer", - minimum: 0, - maximum: 100, - description: "Number of scroll ticks.", - }, - }, - required: ["coordinate", "scroll_direction", "scroll_amount"], - }, - }, - - { - name: "left_click_drag", - description: `Press, move to target, and release. ${FRONTMOST_GATE_DESC}`, - inputSchema: { - type: "object" as const, - properties: { - coordinate: { - ...coordinateTuple, - description: `(x, y) end point: ${coord.x}`, - }, - start_coordinate: { - ...coordinateTuple, - description: `(x, y) start point. If omitted, drags from the current cursor position. ${coord.x}`, - }, - }, - required: ["coordinate"], - }, - }, - - { - name: "mouse_move", - description: `Move the mouse cursor without clicking. Useful for triggering hover states. ${FRONTMOST_GATE_DESC}`, - inputSchema: { - type: "object" as const, - properties: { - coordinate: coordinateTuple, - }, - required: ["coordinate"], - }, - }, - - { - name: "open_application", - description: - "Bring an application to the front, launching it if necessary. The target application must already be in the session allowlist — call request_access first.", - inputSchema: { - type: "object" as const, - properties: { - app: { - type: "string", - description: - "Display name (e.g. \"Slack\") or bundle identifier (e.g. \"com.tinyspeck.slackmacgap\").", - }, - }, - required: ["app"], - }, - }, - - { - name: "switch_display", - description: - "Switch which monitor subsequent screenshots capture. Use this when the " + - "application you need is on a different monitor than the one shown. " + - "The screenshot tool tells you which monitor it captured and lists " + - "other attached monitors by name — pass one of those names here. " + - "After switching, call screenshot to see the new monitor. " + - 'Pass "auto" to return to automatic monitor selection.', - inputSchema: { - type: "object" as const, - properties: { - display: { - type: "string", - description: - 'Monitor name from the screenshot note (e.g. "Built-in Retina Display", ' + - '"LG UltraFine"), or "auto" to re-enable automatic selection.', - }, - }, - required: ["display"], - }, - }, - - { - name: "list_granted_applications", - description: - "List the applications currently in the session allowlist, plus the active grant flags and coordinate mode. No side effects.", - inputSchema: { - type: "object" as const, - properties: {}, - required: [], - }, - }, - - { - name: "read_clipboard", - description: - "Read the current clipboard contents as text. Requires the `clipboardRead` grant.", - inputSchema: { - type: "object" as const, - properties: {}, - required: [], - }, - }, - - { - name: "write_clipboard", - description: - "Write text to the clipboard. Requires the `clipboardWrite` grant.", - inputSchema: { - type: "object" as const, - properties: { - text: { type: "string" }, - }, - required: ["text"], - }, - }, - - { - name: "wait", - description: "Wait for a specified duration.", - inputSchema: { - type: "object" as const, - properties: { - duration: { - type: "number", - description: "Duration in seconds (0–100).", - }, - }, - required: ["duration"], - }, - }, - - { - name: "cursor_position", - description: - "Get the current mouse cursor position. Returns image-pixel coordinates relative to the most recent screenshot, or logical points if no screenshot has been taken.", - inputSchema: { - type: "object" as const, - properties: {}, - required: [], - }, - }, - - { - name: "hold_key", - description: - `Press and hold a key or key combination for the specified duration, then release. ${FRONTMOST_GATE_DESC} ` + - "System-level combos require the `systemKeyCombos` grant.", - inputSchema: { - type: "object" as const, - properties: { - text: { - type: "string", - description: 'Key or chord to hold, e.g. "space", "shift+down".', - }, - duration: { - type: "number", - description: "Duration in seconds (0–100).", - }, - }, - required: ["text", "duration"], - }, - }, - - { - name: "left_mouse_down", - description: - `Press the left mouse button at the current cursor position and leave it held. ${FRONTMOST_GATE_DESC} ` + - "Use mouse_move first to position the cursor. Call left_mouse_up to release. Errors if the button is already held.", - inputSchema: { - type: "object" as const, - properties: {}, - required: [], - }, - }, - - { - name: "left_mouse_up", - description: - `Release the left mouse button at the current cursor position. ${FRONTMOST_GATE_DESC} ` + - "Pairs with left_mouse_down. Safe to call even if the button is not currently held.", - inputSchema: { - type: "object" as const, - properties: {}, - required: [], - }, - }, - - { - name: "computer_batch", - description: - "Execute a sequence of actions in ONE tool call. Each individual tool call requires a model→API round trip (seconds); " + - "batching a predictable sequence eliminates all but one. Use this whenever you can predict the outcome of several actions ahead — " + - "e.g. click a field, type into it, press Return. Actions execute sequentially and stop on the first error. " + - `${FRONTMOST_GATE_DESC} The frontmost check runs before EACH action inside the batch — if an action opens a non-allowed app, the next action's gate fires and the batch stops there. ` + - "Mid-batch screenshot actions are allowed for inspection but coordinates in subsequent clicks always refer to the PRE-BATCH full-screen screenshot.", - inputSchema: { - type: "object" as const, - properties: { - actions: { - type: "array", - minItems: 1, - items: BATCH_ACTION_ITEM_SCHEMA, - description: - 'List of actions. Example: [{"action":"left_click","coordinate":[100,200]},{"action":"type","text":"hello"},{"action":"key","text":"Return"}]', - }, - }, - required: ["actions"], - }, - }, - - ...(caps.teachMode ? buildTeachTools(coord, installedAppsHint) : []), - ]; -} - -/** - * Teach-mode tools. Split out so the spread above stays a single expression; - * takes `coord` so `teach_step.anchor`'s description uses the same - * frozen coordinate-mode phrasing as click coords, and `installedAppsHint` - * so `request_teach_access.apps` gets the same enumeration as - * `request_access.apps` (same resolution path → same hint). - */ -function buildTeachTools( - coord: { x: string; y: string }, - installedAppsHint: string, -): Tool[] { - // Shared between teach_step (top-level) and teach_batch (inside steps[] - // items). Depends on coord, so it lives inside this factory. - const teachStepProperties = { - explanation: { - type: "string", - description: - "Tooltip body text. Explain what the user is looking at and why it matters. " + - "This is the ONLY place the user sees your words — be complete but concise.", - }, - next_preview: { - type: "string", - description: - "One line describing exactly what will happen when the user clicks Next. " + - 'Example: "Next: I\'ll click Create Bucket and type the name." ' + - "Shown below the explanation in a smaller font.", - }, - anchor: { - type: "array", - items: { type: "number" }, - minItems: 2, - maxItems: 2, - description: - `(x, y) — where the tooltip arrow points. ${coord.x} ` + - "Omit to center the tooltip with no arrow (for general-context steps).", - }, - actions: { - type: "array", - // Empty allowed — "read this, click Next" steps. - items: BATCH_ACTION_ITEM_SCHEMA, - description: - "Actions to execute when the user clicks Next. Same item schema as computer_batch.actions. " + - "Empty array is valid for purely explanatory steps. Actions run sequentially and stop on first error.", - }, - } as const; - - return [ - { - name: "request_teach_access", - description: - "Request permission to guide the user through a task step-by-step with on-screen tooltips. " + - "Use this INSTEAD OF request_access when the user wants to LEARN how to do something " + - '(phrases like "teach me", "walk me through", "show me how", "help me learn"). ' + - "On approval the main Claude window hides and a fullscreen tooltip overlay appears. " + - "You then call teach_step repeatedly; each call shows one tooltip and waits for the user to click Next. " + - "Same app-allowlist semantics as request_access, but no clipboard/system-key flags. " + - "Teach mode ends automatically when your turn ends.", - inputSchema: { - type: "object" as const, - properties: { - apps: { - type: "array", - items: { type: "string" }, - description: - 'Application display names (e.g. "Slack", "Calendar") or bundle identifiers. Resolved case-insensitively against installed apps.' + - installedAppsHint, - }, - reason: { - type: "string", - description: - 'What you will be teaching. Shown in the approval dialog as "Claude wants to guide you through {reason}". Keep it short and task-focused.', - }, - }, - required: ["apps", "reason"], - }, - }, - - { - name: "teach_step", - description: - "Show one guided-tour tooltip and wait for the user to click Next. On Next, execute the actions, " + - "take a fresh screenshot, and return both — you do NOT need a separate screenshot call between steps. " + - "The returned image shows the state after your actions ran; anchor the next teach_step against it. " + - "IMPORTANT — the user only sees the tooltip during teach mode. Put ALL narration in `explanation`. " + - "Text you emit outside teach_step calls is NOT visible until teach mode ends. " + - "Pack as many actions as possible into each step's `actions` array — the user waits through " + - "the whole round trip between clicks, so one step that fills a form beats five steps that fill one field each. " + - "Returns {exited:true} if the user clicks Exit — do not call teach_step again after that. " + - "Take an initial screenshot before your FIRST teach_step to anchor it.", - inputSchema: { - type: "object" as const, - properties: teachStepProperties, - required: ["explanation", "next_preview", "actions"], - }, - }, - - { - name: "teach_batch", - description: - "Queue multiple teach steps in one tool call. Parallels computer_batch: " + - "N steps → one model↔API round trip instead of N. Each step still shows a tooltip " + - "and waits for the user's Next click, but YOU aren't waiting for a round trip between steps. " + - "You can call teach_batch multiple times in one tour — treat each batch as one predictable " + - "SEGMENT (typically: all the steps on one page). The returned screenshot shows the state " + - "after the batch's final actions; anchor the NEXT teach_batch against it. " + - "WITHIN a batch, all anchors and click coordinates refer to the PRE-BATCH screenshot " + - "(same invariant as computer_batch) — for steps 2+ in a batch, either omit anchor " + - "(centered tooltip) or target elements you know won't have moved. " + - "Good pattern: batch 5 tooltips on page A (last step navigates) → read returned screenshot → " + - "batch 3 tooltips on page B → done. " + - "Returns {exited:true, stepsCompleted:N} if the user clicks Exit — do NOT call again after that; " + - "{stepsCompleted, stepFailed, ...} if an action errors mid-batch; " + - "otherwise {stepsCompleted, results:[...]} plus a final screenshot. " + - "Fall back to individual teach_step calls when you need to react to each intermediate screenshot.", - inputSchema: { - type: "object" as const, - properties: { - steps: { - type: "array", - minItems: 1, - items: { - type: "object", - properties: teachStepProperties, - required: ["explanation", "next_preview", "actions"], - }, - description: - "Ordered steps. Validated upfront — a typo in step 5 errors before any tooltip shows.", - }, - }, - required: ["steps"], - }, - }, - ]; -} diff --git a/claude-code-source/node_modules/@ant/computer-use-mcp/src/types.ts b/claude-code-source/node_modules/@ant/computer-use-mcp/src/types.ts deleted file mode 100644 index 656f795d..00000000 --- a/claude-code-source/node_modules/@ant/computer-use-mcp/src/types.ts +++ /dev/null @@ -1,622 +0,0 @@ -import type { - ComputerExecutor, - InstalledApp, - ScreenshotResult, -} from "./executor.js"; - -/** `ScreenshotResult` without the base64 blob. The shape hosts persist for - * cross-respawn `scaleCoord` survival. */ -export type ScreenshotDims = Omit; - -/** Shape mirrors claude-for-chrome-mcp/src/types.ts:1-7 */ -export interface Logger { - info: (message: string, ...args: unknown[]) => void; - error: (message: string, ...args: unknown[]) => void; - warn: (message: string, ...args: unknown[]) => void; - debug: (message: string, ...args: unknown[]) => void; - silly: (message: string, ...args: unknown[]) => void; -} - -/** - * Per-app permission tier. Hardcoded by category at grant time — the - * approval dialog displays the tier but the user cannot change it (for now). - * - * - `"read"` — visible in screenshots, NO interaction (no clicks, no typing). - * Browsers land here: the model can read a page that's already open, but - * must use the Claude-in-Chrome MCP for any navigation/clicking. Trading - * platforms land here too (no CiC alternative — the model asks the user). - * - `"click"` — visible + plain left-click, scroll. NO typing/keys, - * NO right/middle-click, NO modifier-clicks, NO drag-drop (all text- - * injection vectors). Terminals/IDEs land here: the model can click a - * Run button or scroll test output, but `type("rm -rf /")` is blocked - * and so is right-click→Paste and dragging text onto the terminal. - * - `"full"` — visible + click + type/key/paste. Everything else. - * - * Enforced in `runInputActionGates` via the frontmost-app check: keyboard - * actions require `"full"`, mouse actions require `"click"` or higher. - */ -export type CuAppPermTier = "read" | "click" | "full"; - -/** - * A single app the user has approved for the current session. Session-scoped - * only — there is no "once" or "forever" scope (unlike Chrome's per-domain - * three-way). CU has no natural "once" unit; one task = hundreds of clicks. - * Mirrors how `chromeAllowedDomains` is a plain `string[]` with no per-item - * scope. - */ -export interface AppGrant { - bundleId: string; - displayName: string; - /** Epoch ms. For Settings-page display ("Granted 3m ago"). */ - grantedAt: number; - /** Undefined → `"full"` (back-compat for pre-tier grants persisted in - * session state). */ - tier?: CuAppPermTier; -} - -/** Orthogonal to the app allowlist. */ -export interface CuGrantFlags { - clipboardRead: boolean; - clipboardWrite: boolean; - /** - * When false, the `key` tool rejects combos in `keyBlocklist.ts` - * (cmd+q, cmd+tab, cmd+space, cmd+shift+q, ctrl+alt+delete). All other - * key sequences work regardless. - */ - systemKeyCombos: boolean; -} - -export const DEFAULT_GRANT_FLAGS: CuGrantFlags = { - clipboardRead: false, - clipboardWrite: false, - systemKeyCombos: false, -}; - -/** - * Host picks via GrowthBook JSON feature `chicago_coordinate_mode`, baked - * into tool param descriptions at server-construction time. The model sees - * ONE convention and never learns the other exists. `normalized_0_100` - * sidesteps the Retina scaleFactor bug class entirely. - */ -export type CoordinateMode = "pixels" | "normalized_0_100"; - -/** - * Independent kill switches for subtle/risky ported behaviors. Read from - * GrowthBook by the host adapter, consulted in `toolCalls.ts`. - */ -export interface CuSubGates { - /** 9×9 exact-byte staleness guard before click. */ - pixelValidation: boolean; - /** Route `type("foo\nbar")` through clipboard instead of keystroke-by-keystroke. */ - clipboardPasteMultiline: boolean; - /** - * Ease-out-cubic mouse glide at 60fps, distance-proportional duration - * (2000 px/sec, capped at 0.5s). Adds up to ~0.5s latency - * per click. When off, cursor teleports instantly. - */ - mouseAnimation: boolean; - /** - * Pre-action sequence: hide non-allowlisted apps, then defocus us (from the - * Vercept acquisition). When off, the - * frontmost gate fires in the normal case and the model gets stuck — this - * is the A/B-test-the-old-broken-behavior switch. - */ - hideBeforeAction: boolean; - /** - * Auto-resolve the target display before each screenshot when the - * selected display has no allowed-app windows. When on, `handleScreenshot` - * uses the atomic Swift path; off → sticks with `selectedDisplayId`. - */ - autoTargetDisplay: boolean; - /** - * Stash+clear the clipboard while a tier-"click" app is frontmost. - * Closes the gap where a click-tier terminal/IDE has a UI Paste button - * that's plain-left-clickable — without this, the tier "click" - * keyboard block can be routed around by clicking Paste. Restored when - * a non-"click" app becomes frontmost, or at turn end. - */ - clipboardGuard: boolean; -} - -// ---------------------------------------------------------------------------- -// Permission request/response (mirror of BridgePermissionRequest, types.ts:77-94) -// ---------------------------------------------------------------------------- - -/** One entry per app the model asked for, after name → bundle ID resolution. */ -export interface ResolvedAppRequest { - /** What the model asked for (e.g. "Slack", "com.tinyspeck.slackmacgap"). */ - requestedName: string; - /** The resolved InstalledApp if found, else undefined (shown greyed in the UI). */ - resolved?: InstalledApp; - /** Shell-access-equivalent bundle IDs get a UI warning. See sentinelApps.ts. */ - isSentinel: boolean; - /** Already in the allowlist → skip the checkbox, return in `granted` immediately. */ - alreadyGranted: boolean; - /** Hardcoded tier for this app (browser→"read", terminal→"click", else "full"). - * The dialog displays this read-only; the renderer passes it through - * verbatim in the AppGrant. */ - proposedTier: CuAppPermTier; -} - -/** - * Payload for the renderer approval dialog. Rides through the existing - * `ToolPermissionRequest.input: unknown` field - * (packages/utils/desktop/bridge/common/claude.web.ts:1262) — no IPC schema - * change needed. - */ -export interface CuPermissionRequest { - requestId: string; - /** Model-provided reason string. Shown prominently in the approval UI. */ - reason: string; - apps: ResolvedAppRequest[]; - /** What the model asked for. User can toggle independently of apps. */ - requestedFlags: Partial; - /** - * For the "On Windows, Claude can see all apps..." footnote. Taken from - * `executor.capabilities.screenshotFiltering` so the renderer doesn't - * need to know about platforms. - */ - screenshotFiltering: "native" | "none"; - /** - * Present only when TCC permissions are NOT yet granted. When present, - * the renderer shows a TCC toggle panel (two rows: Accessibility, Screen - * Recording) INSTEAD OF the app list. Clicking a row's "Request" button - * triggers the OS prompt; the store polls on window-focus and flips the - * toggle when the grant is detected. macOS itself prompts the user to - * restart after granting Screen Recording — we don't. - */ - tccState?: { - accessibility: boolean; - screenRecording: boolean; - }; - /** - * Apps with windows on the CU display that aren't in the requested - * allowlist. These will be hidden the first time Claude takes an action. - * Computed at request_access time — may be slightly stale by the time the - * user clicks Allow, but it's a preview, not a contract. Absent when - * empty so the renderer can skip the section cleanly. - */ - willHide?: Array<{ bundleId: string; displayName: string }>; - /** - * `chicagoAutoUnhide` app preference at request time. The renderer picks - * between "...then restored when Claude is done" and "...will be hidden" - * copy. Absent when `willHide` is absent (same condition). - */ - autoUnhideEnabled?: boolean; -} - -/** - * What the renderer stuffs into `updatedInput._cuGrants` when the user clicks - * "Allow for this session" (mirror of the `_allowAllSites` sentinel at - * LocalAgentModeSessionManager.ts:2794). - */ -export interface CuPermissionResponse { - granted: AppGrant[]; - /** Bundle IDs the user unchecked, or apps that weren't installed. */ - denied: Array<{ bundleId: string; reason: "user_denied" | "not_installed" }>; - flags: CuGrantFlags; - /** - * Whether the user clicked Allow in THIS dialog. Only set by the - * teach-mode handler — regular request_access doesn't need it (the - * session manager's `result.behavior` gates the merge there). Needed - * because when all requested apps are already granted (skipDialogGrants - * non-empty, needDialog empty), Allow and Deny produce identical - * `{granted:[], denied:[]}` payloads and the tool handler can't tell - * them apart without this. Undefined → legacy/regular path, do not - * gate on it. - */ - userConsented?: boolean; -} - -// ---------------------------------------------------------------------------- -// Host adapter (mirror of ClaudeForChromeContext, types.ts:33-62) -// ---------------------------------------------------------------------------- - -/** - * Process-lifetime singleton dependencies. Everything that does NOT vary per - * tool call. Built once by `apps/desktop/src/main/nest-only/chicago/hostAdapter.ts`. - * No Electron imports in this package — the host injects everything. - */ -export interface ComputerUseHostAdapter { - serverName: string; - logger: Logger; - executor: ComputerExecutor; - - /** - * TCC state check — Accessibility + Screen Recording on macOS. Pure check, - * no dialog, no relaunch. When either is missing, `request_access` threads - * the state through to the renderer which shows a toggle panel; all other - * tools return a tool error. - */ - ensureOsPermissions(): Promise< - | { granted: true } - | { granted: false; accessibility: boolean; screenRecording: boolean } - >; - - /** The Settings-page kill switch (`chicagoEnabled` app preference). */ - isDisabled(): boolean; - - /** - * The `chicagoAutoUnhide` app preference. Consumed by `buildAccessRequest` - * to populate `CuPermissionRequest.autoUnhideEnabled` so the renderer's - * "will be hidden" copy can say "then restored" only when true. - */ - getAutoUnhideEnabled(): boolean; - - /** - * Sub-gates re-read on every tool call so GrowthBook flips take effect - * mid-session without restart. - */ - getSubGates(): CuSubGates; - - /** - * JPEG decode + crop + raw pixel bytes, for the PixelCompare staleness guard. - * Injected so this package stays Electron-free. The host implements it via - * `nativeImage.createFromBuffer(jpeg).crop(rect).toBitmap()` — Chromium's - * decoders, BSD-licensed, no `.node` binary. - * - * Returns null on decode/crop failure — caller treats null as `skipped`, - * click proceeds (validation failure must never block the action). - */ - cropRawPatch( - jpegBase64: string, - rect: { x: number; y: number; width: number; height: number }, - ): Buffer | null; -} - -// ---------------------------------------------------------------------------- -// Session context (getter/callback bag for bindSessionContext) -// ---------------------------------------------------------------------------- - -/** - * Per-session state binding for `bindSessionContext`. Hosts build this once - * per session with getters that read fresh from their session store and - * callbacks that write back. The returned dispatcher builds - * `ComputerUseOverrides` from these getters on every call. - * - * Callbacks must be set at construction time — `bindSessionContext` reads - * them once at bind, not per call. - * - * The lock hooks are **async** — `bindSessionContext` awaits them before - * `handleToolCall`, then passes `checkCuLock: undefined` in overrides so the - * sync Gate-3 in `handleToolCall` no-ops. Hosts with in-memory sync locks - * (Cowork) wrap them trivially; hosts with cross-process locks (the CLI's - * O_EXCL file) call the real async primitive directly. - */ -export interface ComputerUseSessionContext { - // ── Read state fresh per call ────────────────────────────────────── - - getAllowedApps(): readonly AppGrant[]; - getGrantFlags(): CuGrantFlags; - /** Per-user auto-deny list (Settings page). Empty array = none. */ - getUserDeniedBundleIds(): readonly string[]; - getSelectedDisplayId(): number | undefined; - getDisplayPinnedByModel?(): boolean; - getDisplayResolvedForApps?(): string | undefined; - getTeachModeActive?(): boolean; - /** Dims-only fallback when `lastScreenshot` is unset (cross-respawn). - * `bindSessionContext` reconstructs `{...dims, base64: ""}` so scaleCoord - * works and pixelCompare correctly skips. */ - getLastScreenshotDims?(): ScreenshotDims | undefined; - - // ── Write-back callbacks ─────────────────────────────────────────── - - /** Shows the approval dialog. Host routes to its UI, awaits user. The - * signal is aborted if the tool call finishes before the user answers - * (MCP timeout, etc.) — hosts dismiss the dialog on abort. */ - onPermissionRequest?( - req: CuPermissionRequest, - signal: AbortSignal, - ): Promise; - /** Teach-mode sibling of `onPermissionRequest`. */ - onTeachPermissionRequest?( - req: CuTeachPermissionRequest, - signal: AbortSignal, - ): Promise; - /** Called by `bindSessionContext` after merging a permission response into - * the allowlist (dedupe on bundleId, truthy-only flag spread). Host - * persists for resume survival. */ - onAllowedAppsChanged?(apps: readonly AppGrant[], flags: CuGrantFlags): void; - onAppsHidden?(bundleIds: string[]): void; - /** Reads the session's clipboardGuard stash. undefined → no stash held. */ - getClipboardStash?(): string | undefined; - /** Writes the clipboardGuard stash. undefined clears it. */ - onClipboardStashChanged?(stash: string | undefined): void; - onResolvedDisplayUpdated?(displayId: number): void; - onDisplayPinned?(displayId: number | undefined): void; - onDisplayResolvedForApps?(sortedBundleIdsKey: string): void; - /** Called after each screenshot. Host persists for respawn survival. */ - onScreenshotCaptured?(dims: ScreenshotDims): void; - onTeachModeActivated?(): void; - onTeachStep?(req: TeachStepRequest): Promise; - onTeachWorking?(): void; - - // ── Lock (async) ─────────────────────────────────────────────────── - - /** At most one session uses CU at a time. Awaited by `bindSessionContext` - * before dispatch. Undefined → no lock gating (proceed). */ - checkCuLock?(): Promise<{ holder: string | undefined; isSelf: boolean }>; - /** Take the lock. Called when `checkCuLock` returned `holder: undefined` - * on a non-deferring tool. Host emits enter-CU signals here. */ - acquireCuLock?(): Promise; - /** Host-specific lock-held error text. Default is the package's generic - * message. The CLI host includes the holder session-ID prefix. */ - formatLockHeldMessage?(holder: string): string; - - /** User-abort signal. Passed through to `ComputerUseOverrides.isAborted` - * for the mid-loop checks in handleComputerBatch / handleType. See that - * field for semantics. */ - isAborted?(): boolean; -} - -// ---------------------------------------------------------------------------- -// Per-call overrides (mirror of PermissionOverrides, types.ts:97-102) -// ---------------------------------------------------------------------------- - -/** - * Built FRESH on every tool call by `bindSessionContext` from - * `ComputerUseSessionContext` getters. This is what lets a singleton MCP - * server carry per-session state — the state lives on the host's session - * store, not the server. - */ -export interface ComputerUseOverrides { - allowedApps: AppGrant[]; - grantFlags: CuGrantFlags; - coordinateMode: CoordinateMode; - - /** - * User-configured auto-deny list (Settings → Desktop app → Computer Use). - * Bundle IDs - * here are stripped from request_access BEFORE the approval dialog — they - * never reach the user for approval regardless of tier. The response tells - * the agent to ask the user to remove the app from their deny list in - * Settings if access is genuinely needed. - * - * Per-USER, persists across restarts (read from appPreferences per call, - * not session state). Contrast with `allowedApps` which is per-session. - * Empty array = no user-configured denies (the default). - */ - userDeniedBundleIds: readonly string[]; - - /** - * Display CU operates on; read fresh per call. `scaleCoord` uses the - * `originX/Y` snapshotted in `lastScreenshot`, so mid-session switches - * only affect the NEXT screenshot/prepare call. - */ - selectedDisplayId?: number; - - /** - * The `request_access` tool handler calls this and awaits. The wrapper - * closure in serverDef.ts (mirroring InternalMcpServerManager.ts:131-177) - * routes through `handleToolPermission` → IPC → renderer ChicagoApproval. - * When it resolves, the wrapper side-effectfully mutates - * `InternalServerContext.cuAllowedApps` BEFORE returning here. - * - * Undefined when the session wasn't wired with a permission handler (e.g. - * a future headless mode). `request_access` returns a tool error in that case. - */ - onPermissionRequest?: (req: CuPermissionRequest) => Promise; - - /** - * For the pixel-validation staleness guard. The model's-last-screenshot, - * stashed by serverDef.ts after each `screenshot` tool call. Undefined on - * cold start → pixel validation skipped (click proceeds). - */ - lastScreenshot?: ScreenshotResult; - - /** - * Fired after every `prepareForAction` with the bundle IDs it just hid. - * The wrapper closure in serverDef.ts accumulates these into - * `Session.cuHiddenDuringTurn` via a write-through callback (same pattern - * as `onCuPermissionUpdated`). At turn end (`sdkMessage.type === "result"`), - * if the `chicagoAutoUnhide` setting is on, everything in the set is - * unhidden. Set is cleared regardless of the setting so it doesn't leak - * across turns. - * - * Undefined when the session wasn't wired with a tracker — unhide just - * doesn't happen. - */ - onAppsHidden?: (bundleIds: string[]) => void; - - /** - * Reads the clipboardGuard stash from session state. `undefined` means no - * stash is held — `syncClipboardStash` stashes on first entry to click-tier - * and clears on restore. Sibling of the `cuHiddenDuringTurn` getter pattern - * — state lives on the host's session, not module-level here. - */ - getClipboardStash?: () => string | undefined; - - /** - * Writes the clipboardGuard stash to session state. `undefined` clears. - * Sibling of `onAppsHidden` — the wrapper closure writes through to - * `Session.cuClipboardStash`. At turn end the host reads + clears it - * directly and restores via Electron's `clipboard.writeText` (no nest-only - * import surface). - */ - onClipboardStashChanged?: (stash: string | undefined) => void; - - /** - * Write the resolver's picked display back to session so teach overlay - * positioning and subsequent non-resolver calls use the same display. - * Fired by `handleScreenshot` in the atomic `autoTargetDisplay` path when - * `resolvePrepareCapture`'s pick differs from `selectedDisplayId`. - * Fire-and-forget. - */ - onResolvedDisplayUpdated?: (displayId: number) => void; - - /** - * Set when the model explicitly picked a display via `switch_display`. - * When true, `handleScreenshot` passes `autoResolve: false` so the Swift - * resolver honors `selectedDisplayId` directly (straight cuDisplayInfo - * passthrough) instead of running the co-location/chase chain. The - * resolver's Step 2 ("host + allowed co-located → host") otherwise - * overrides any `selectedDisplayId` whenever an allowed app shares the - * host's monitor. - */ - displayPinnedByModel?: boolean; - - /** - * Write the model's explicit display pick to session. `displayId: - * undefined` clears both `selectedDisplayId` and the pin (back to auto). - * Sibling of `onResolvedDisplayUpdated` but also sets the pin flag — - * the two are semantically distinct (resolver-picked vs model-picked). - */ - onDisplayPinned?: (displayId: number | undefined) => void; - - /** - * Sorted comma-joined bundle-ID set the display was last auto-resolved - * for. `handleScreenshot` compares this to the current allowed set and - * only passes `autoResolve: true` when they differ — so the resolver - * doesn't yank the display on every screenshot, only when the app set - * has changed since the last resolve (or manual switch). - */ - displayResolvedForApps?: string; - - /** - * Records which app set the current display selection was made for. Fired - * alongside `onResolvedDisplayUpdated` when the resolver picks, so the next - * screenshot sees a matching set and skips auto-resolve. - */ - onDisplayResolvedForApps?: (sortedBundleIdsKey: string) => void; - - /** - * Global CU lock — at most one session actively uses CU at a time. Checked - * in `handleToolCall` after kill-switch/TCC, before dispatch. Every CU tool - * including `request_access` goes through it. - * - * - `holder === undefined` → lock is free, safe to acquire - * - `isSelf === true` → this session already holds it (no-op, proceed) - * - `holder !== undefined && !isSelf` → blocked, return tool error - * - * `undefined` callback → lock system not wired (e.g. CCD). Proceed without - * gating — absence of the mechanism ≠ locked out. - * - * The host manages release (on session idle/stop/archive) — this package - * never releases. - */ - checkCuLock?: () => { holder: string | undefined; isSelf: boolean }; - - /** - * Take the lock for this session. `handleToolCall` calls this exactly once - * per turn, on the FIRST CU tool call when `checkCuLock().holder` is - * undefined. No-op if already held (defensive — the check should have - * short-circuited). Host emits an event the overlay listens to. - */ - acquireCuLock?: () => void; - - /** - * User-abort signal. Checked mid-iteration inside `handleComputerBatch` - * and `handleType`'s grapheme loop so an in-flight batch/type stops - * promptly on overlay Stop instead of running to completion after the - * host has already abandoned the tool result. - * - * Undefined → never aborts (e.g. unwired host). Live per-check read — - * same lazy-getter pattern as `checkCuLock`. - */ - isAborted?: () => boolean; - - // ── Teach mode ─────────────────────────────────────────────────────── - // Wired only when the host's teachModeEnabled gate is on. All five - // undefined → `request_teach_access` / `teach_step` return tool errors - // and teach mode is effectively off. - - /** - * Sibling of `onPermissionRequest`. Same blocking-await-on-renderer-dialog - * semantics, but routes to ComputerUseTeachApproval.tsx (which explains - * the window-hides-during-guide behavior) instead of ComputerUseApproval. - * The wrapper closure in serverDef.ts writes grants through to session state - * via `onCuPermissionUpdated` exactly as `onPermissionRequest` does. - */ - onTeachPermissionRequest?: ( - req: CuTeachPermissionRequest, - ) => Promise; - - /** - * Called by `handleRequestTeachAccess` after the user approves and at least - * one app was granted. Host sets `session.teachModeActive = true`, emits - * `teachModeChanged` → teach controller hides the main window and shows the - * fullscreen overlay. Cleared by the host on turn end (`transitionTo("idle")`) - * alongside the CU lock release. - */ - onTeachModeActivated?: () => void; - - /** - * Read by `handleRequestAccess` and `handleRequestTeachAccess` to - * short-circuit with a clear tool error when teach mode is active. The - * main window is hidden during teach mode, so permission dialogs render - * invisibly and handleToolPermission blocks forever on an invisible - * prompt. Better to tell the model to exit teach mode first. Getter - * (not a boolean field) because teach mode state lives on the session, - * not on this per-call overrides object. - */ - getTeachModeActive?: () => boolean; - - /** - * Called by `handleTeachStep` with the scaled anchor + text. Host stores - * the resolver, emits `teachStepRequested` → teach controller pushes the - * payload to the overlay → user reads, clicks Next → IPC → host calls the - * stored resolver → this promise resolves. `{action: "exit"}` when the user - * clicks Exit (or the turn is interrupted) — `handleTeachStep` short-circuits - * without executing actions. - * - * Same blocking-promise pattern as `onPermissionRequest`, but resolved by - * the teach overlay's own preload (not the main renderer's tool-approval UI). - */ - onTeachStep?: (req: TeachStepRequest) => Promise; - - /** - * Called immediately after `onTeachStep` resolves with "next", before - * action dispatch begins. Host emits `teachStepWorking` → overlay flips to - * the spinner state (Next button gone, Exit stays, "Working…" + rotating - * notch). The next `onTeachStep` call replaces the spinner with the new - * tooltip content. - */ - onTeachWorking?: () => void; -} - -// ---------------------------------------------------------------------------- -// Teach mode (guided-tour tooltips with Next-button action execution) -// ---------------------------------------------------------------------------- - -/** - * Payload the host pushes to the teach overlay BrowserWindow. Built by - * `handleTeachStep` in toolCalls.ts from the model's `teach_step` args. - * - * `anchorLogical` here is POST-`scaleCoord` — **full-display** logical - * macOS points (origin = monitor top-left, menu bar included, since - * cuDisplayInfo returns CGDisplayBounds). The overlay window is positioned - * at `workArea.{x,y}` (excludes menu bar/Dock), so `updateTeachStep` in - * teach/window.ts subtracts the workArea offset before IPC so the HTML's - * CSS coords match. - */ -export interface TeachStepRequest { - explanation: string; - nextPreview: string; - /** Full-display logical points. Undefined → overlay centers the tooltip, hides the arrow. */ - anchorLogical?: { x: number; y: number }; -} - -export type TeachStepResult = { action: "next" } | { action: "exit" }; - -/** - * Payload for the renderer's ComputerUseTeachApproval dialog. Rides through - * `ToolPermissionRequest.input: unknown` same as `CuPermissionRequest`. - * Separate type (not a flag on `CuPermissionRequest`) so the two approval - * components can narrow independently and the teach dialog is free to drop - * fields it doesn't render (no grant-flag checkboxes in teach mode). - */ -export interface CuTeachPermissionRequest { - requestId: string; - /** Model-provided reason. Shown in the dialog headline ("guide you through {reason}"). */ - reason: string; - apps: ResolvedAppRequest[]; - screenshotFiltering: "native" | "none"; - /** Present only when TCC is ungranted — same semantics as `CuPermissionRequest.tccState`. */ - tccState?: { - accessibility: boolean; - screenRecording: boolean; - }; - willHide?: Array<{ bundleId: string; displayName: string }>; - /** Same semantics as `CuPermissionRequest.autoUnhideEnabled`. */ - autoUnhideEnabled?: boolean; -} diff --git a/claude-code-source/node_modules/@ant/computer-use-swift/js/index.js b/claude-code-source/node_modules/@ant/computer-use-swift/js/index.js deleted file mode 100644 index 378798ee..00000000 --- a/claude-code-source/node_modules/@ant/computer-use-swift/js/index.js +++ /dev/null @@ -1,23 +0,0 @@ -const path = require("path"); - -if (process.platform !== "darwin") { - throw new Error("@ant/computer-use-swift is only available on macOS"); -} - -// COMPUTER_USE_SWIFT_NODE_PATH: escape hatch for bundlers. Bun's --compile -// embeds the .node as an asset, not in a node_modules tree — __dirname is the -// exe dir and ../prebuilds/ doesn't exist. The consuming build bakes this var -// to the embedded asset's path. Unset → normal node_modules layout. -// -// Four methods use `Task { @MainActor in ... }` (captureExcluding, -// captureRegion, apps.listInstalled, resolvePrepareCapture) which enqueue -// onto DispatchQueue.main. Electron drains that queue via CFRunLoop; libuv -// (Node/bun) does not — the promises hang. Consumers running under libuv -// must pump `_drainMainRunLoop` via setInterval while those promises are -// pending. Consumers under Electron don't need to (CFRunLoop drains -// automatically). -const native = require( - process.env.COMPUTER_USE_SWIFT_NODE_PATH ?? - path.resolve(__dirname, "../prebuilds/computer_use.node"), -); -module.exports = native.computerUse; diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/AWS_restJson1.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/AWS_restJson1.mjs deleted file mode 100644 index 7f7417c9..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/AWS_restJson1.mjs +++ /dev/null @@ -1,163 +0,0 @@ -// Copied from https://github.com/aws/aws-sdk-js-v3/blob/bee66fbd2a519a16b57c787b2689af857af720af/clients/client-bedrock-runtime/src/protocols/Aws_restJson1.ts -// Modified to remove unnecessary code (we only need to call `de_ResponseStream`) and to adjust imports. -import { collectBody, decorateServiceException as __decorateServiceException, expectInt32 as __expectInt32, expectString as __expectString, map, take, } from '@smithy/smithy-client'; -import { InternalServerException, ModelStreamErrorException, ThrottlingException, ValidationException, } from '@aws-sdk/client-bedrock-runtime'; -/** - * deserializeAws_restJson1InternalServerExceptionRes - */ -const de_InternalServerExceptionRes = async (parsedOutput, context) => { - const contents = map({}); - const data = parsedOutput.body; - const doc = take(data, { - message: __expectString, - }); - Object.assign(contents, doc); - const exception = new InternalServerException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents, - }); - return __decorateServiceException(exception, parsedOutput.body); -}; -/** - * deserializeAws_restJson1ModelStreamErrorExceptionRes - */ -const de_ModelStreamErrorExceptionRes = async (parsedOutput, context) => { - const contents = map({}); - const data = parsedOutput.body; - const doc = take(data, { - message: __expectString, - originalMessage: __expectString, - originalStatusCode: __expectInt32, - }); - Object.assign(contents, doc); - const exception = new ModelStreamErrorException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents, - }); - return __decorateServiceException(exception, parsedOutput.body); -}; -/** - * deserializeAws_restJson1ThrottlingExceptionRes - */ -const de_ThrottlingExceptionRes = async (parsedOutput, context) => { - const contents = map({}); - const data = parsedOutput.body; - const doc = take(data, { - message: __expectString, - }); - Object.assign(contents, doc); - const exception = new ThrottlingException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents, - }); - return __decorateServiceException(exception, parsedOutput.body); -}; -/** - * deserializeAws_restJson1ValidationExceptionRes - */ -const de_ValidationExceptionRes = async (parsedOutput, context) => { - const contents = map({}); - const data = parsedOutput.body; - const doc = take(data, { - message: __expectString, - }); - Object.assign(contents, doc); - const exception = new ValidationException({ - $metadata: deserializeMetadata(parsedOutput), - ...contents, - }); - return __decorateServiceException(exception, parsedOutput.body); -}; -/** - * deserializeAws_restJson1ResponseStream - */ -export const de_ResponseStream = (output, context) => { - return context.eventStreamMarshaller.deserialize(output, async (event) => { - if (event['chunk'] != null) { - return { - chunk: await de_PayloadPart_event(event['chunk'], context), - }; - } - if (event['internalServerException'] != null) { - return { - internalServerException: await de_InternalServerException_event(event['internalServerException'], context), - }; - } - if (event['modelStreamErrorException'] != null) { - return { - modelStreamErrorException: await de_ModelStreamErrorException_event(event['modelStreamErrorException'], context), - }; - } - if (event['validationException'] != null) { - return { - validationException: await de_ValidationException_event(event['validationException'], context), - }; - } - if (event['throttlingException'] != null) { - return { - throttlingException: await de_ThrottlingException_event(event['throttlingException'], context), - }; - } - return { $unknown: output }; - }); -}; -const de_InternalServerException_event = async (output, context) => { - const parsedOutput = { - ...output, - body: await parseBody(output.body, context), - }; - return de_InternalServerExceptionRes(parsedOutput, context); -}; -const de_ModelStreamErrorException_event = async (output, context) => { - const parsedOutput = { - ...output, - body: await parseBody(output.body, context), - }; - return de_ModelStreamErrorExceptionRes(parsedOutput, context); -}; -const de_PayloadPart_event = async (output, context) => { - const contents = {}; - const data = await parseBody(output.body, context); - Object.assign(contents, de_PayloadPart(data, context)); - return contents; -}; -const de_ThrottlingException_event = async (output, context) => { - const parsedOutput = { - ...output, - body: await parseBody(output.body, context), - }; - return de_ThrottlingExceptionRes(parsedOutput, context); -}; -const de_ValidationException_event = async (output, context) => { - const parsedOutput = { - ...output, - body: await parseBody(output.body, context), - }; - return de_ValidationExceptionRes(parsedOutput, context); -}; -/** - * deserializeAws_restJson1PayloadPart - */ -const de_PayloadPart = (output, context) => { - return take(output, { - bytes: context.base64Decoder, - }); -}; -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'] ?? '', -}); -// Encode Uint8Array data into string with utf-8. -const collectBodyString = (streamBody, context) => collectBody(streamBody, context).then((body) => context.utf8Encoder(body)); -const parseBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { - if (encoded.length) { - return JSON.parse(encoded); - } - return {}; -}); -//# sourceMappingURL=AWS_restJson1.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/client.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/client.mjs deleted file mode 100644 index b8d14b13..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/client.mjs +++ /dev/null @@ -1,124 +0,0 @@ -import { BaseAnthropic } from '@anthropic-ai/sdk/client'; -import * as Resources from '@anthropic-ai/sdk/resources/index'; -import { getAuthHeaders } from "./core/auth.mjs"; -import { Stream } from "./core/streaming.mjs"; -import { readEnv } from "./internal/utils/env.mjs"; -import { isObj } from "./internal/utils/values.mjs"; -import { buildHeaders } from "./internal/headers.mjs"; -import { path } from "./internal/utils/path.mjs"; -export { BaseAnthropic } from '@anthropic-ai/sdk/client'; -const DEFAULT_VERSION = 'bedrock-2023-05-31'; -const MODEL_ENDPOINTS = new Set(['/v1/complete', '/v1/messages', '/v1/messages?beta=true']); -/** API Client for interfacing with the Anthropic Bedrock API. */ -export class AnthropicBedrock extends BaseAnthropic { - /** - * API Client for interfacing with the Anthropic Bedrock API. - * - * @param {string | null | undefined} [opts.awsSecretKey] - * @param {string | null | undefined} [opts.awsAccessKey] - * @param {string | undefined} [opts.awsRegion=process.env['AWS_REGION'] ?? us-east-1] - * @param {string | null | undefined} [opts.awsSessionToken] - * @param {(() => Promise) | null} [opts.providerChainResolver] - Custom provider chain resolver for AWS credentials. Useful for non-Node environments. - * @param {string} [opts.baseURL=process.env['ANTHROPIC_BEDROCK_BASE_URL'] ?? https://bedrock-runtime.${this.awsRegion}.amazonaws.com] - Override the default base URL for the API. - * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. - * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. - * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. - * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. - * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. - * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. - * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. - * @param {boolean} [opts.skipAuth=false] - Skip authentication for this request. This is useful if you have an internal proxy that handles authentication for you. - */ - constructor({ awsRegion = readEnv('AWS_REGION') ?? 'us-east-1', baseURL = readEnv('ANTHROPIC_BEDROCK_BASE_URL') ?? `https://bedrock-runtime.${awsRegion}.amazonaws.com`, awsSecretKey = null, awsAccessKey = null, awsSessionToken = null, providerChainResolver = null, ...opts } = {}) { - super({ - baseURL, - ...opts, - }); - this.skipAuth = false; - this.messages = makeMessagesResource(this); - this.completions = new Resources.Completions(this); - this.beta = makeBetaResource(this); - this.awsSecretKey = awsSecretKey; - this.awsAccessKey = awsAccessKey; - this.awsRegion = awsRegion; - this.awsSessionToken = awsSessionToken; - this.skipAuth = opts.skipAuth ?? false; - this.providerChainResolver = providerChainResolver; - } - validateHeaders() { - // auth validation is handled in prepareRequest since it needs to be async - } - async prepareRequest(request, { url, options }) { - if (this.skipAuth) { - return; - } - const regionName = this.awsRegion; - if (!regionName) { - throw new Error('Expected `awsRegion` option to be passed to the client or the `AWS_REGION` environment variable to be present'); - } - const headers = await getAuthHeaders(request, { - url, - regionName, - awsAccessKey: this.awsAccessKey, - awsSecretKey: this.awsSecretKey, - awsSessionToken: this.awsSessionToken, - fetchOptions: this.fetchOptions, - providerChainResolver: this.providerChainResolver, - }); - request.headers = buildHeaders([headers, request.headers]).values; - } - async buildRequest(options) { - options.__streamClass = Stream; - if (isObj(options.body)) { - // create a shallow copy of the request body so that code that mutates it later - // doesn't mutate the original user-provided object - options.body = { ...options.body }; - } - if (isObj(options.body)) { - if (!options.body['anthropic_version']) { - options.body['anthropic_version'] = DEFAULT_VERSION; - } - if (options.headers && !options.body['anthropic_beta']) { - const betas = buildHeaders([options.headers]).values.get('anthropic-beta'); - if (betas != null) { - options.body['anthropic_beta'] = betas.split(','); - } - } - } - if (MODEL_ENDPOINTS.has(options.path) && options.method === 'post') { - if (!isObj(options.body)) { - throw new Error('Expected request body to be an object for post /v1/messages'); - } - const model = options.body['model']; - options.body['model'] = undefined; - const stream = options.body['stream']; - options.body['stream'] = undefined; - if (stream) { - options.path = path `/model/${model}/invoke-with-response-stream`; - } - else { - options.path = path `/model/${model}/invoke`; - } - } - return super.buildRequest(options); - } -} -function makeMessagesResource(client) { - const resource = new Resources.Messages(client); - // @ts-expect-error we're deleting non-optional properties - delete resource.batches; - // @ts-expect-error we're deleting non-optional properties - delete resource.countTokens; - return resource; -} -function makeBetaResource(client) { - const resource = new Resources.Beta(client); - // @ts-expect-error we're deleting non-optional properties - delete resource.promptCaching; - // @ts-expect-error we're deleting non-optional properties - delete resource.messages.batches; - // @ts-expect-error we're deleting non-optional properties - delete resource.messages.countTokens; - return resource; -} -//# sourceMappingURL=client.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/auth.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/auth.mjs deleted file mode 100644 index 05bf307d..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/auth.mjs +++ /dev/null @@ -1,82 +0,0 @@ -import { Sha256 } from '@aws-crypto/sha256-js'; -import { FetchHttpHandler } from '@smithy/fetch-http-handler'; -import { HttpRequest } from '@smithy/protocol-http'; -import { SignatureV4 } from '@smithy/signature-v4'; -import assert from 'assert'; -const DEFAULT_PROVIDER_CHAIN_RESOLVER = () => import('@aws-sdk/credential-providers').then(({ fromNodeProviderChain }) => fromNodeProviderChain({ - clientConfig: { - requestHandler: new FetchHttpHandler({ - requestInit: (httpRequest) => { - return { - ...httpRequest, - }; - }, - }), - }, -})) - .catch((error) => { - throw new Error(`Failed to import '@aws-sdk/credential-providers'.` + - `You can provide a custom \`providerChainResolver\` in the client options if your runtime does not have access to '@aws-sdk/credential-providers': ` + - `\`new AnthropicBedrock({ providerChainResolver })\` ` + - `Original error: ${error.message}`); -}); -export const getAuthHeaders = async (req, props) => { - assert(req.method, 'Expected request method property to be set'); - const providerChain = await (props.providerChainResolver ? - props.providerChainResolver() - : DEFAULT_PROVIDER_CHAIN_RESOLVER()); - const credentials = await withTempEnv(() => { - // Temporarily set the appropriate environment variables if we've been - // explicitly given credentials so that the credentials provider can - // resolve them. - // - // Note: the environment provider is only not run first if the `AWS_PROFILE` - // environment variable is set. - // https://github.com/aws/aws-sdk-js-v3/blob/44a18a34b2c93feccdfcd162928d13e6dbdcaf30/packages/credential-provider-node/src/defaultProvider.ts#L49 - if (props.awsAccessKey) { - process.env['AWS_ACCESS_KEY_ID'] = props.awsAccessKey; - } - if (props.awsSecretKey) { - process.env['AWS_SECRET_ACCESS_KEY'] = props.awsSecretKey; - } - if (props.awsSessionToken) { - process.env['AWS_SESSION_TOKEN'] = props.awsSessionToken; - } - }, () => providerChain()); - const signer = new SignatureV4({ - service: 'bedrock', - region: props.regionName, - credentials, - sha256: Sha256, - }); - const url = new URL(props.url); - const headers = !req.headers ? {} - : Symbol.iterator in req.headers ? - Object.fromEntries(Array.from(req.headers).map((header) => [...header])) - : { ...req.headers }; - // The connection header may be stripped by a proxy somewhere, so the receiver - // of this message may not see this header, so we remove it from the set of headers - // that are signed. - delete headers['connection']; - headers['host'] = url.hostname; - const request = new HttpRequest({ - method: req.method.toUpperCase(), - protocol: url.protocol, - path: url.pathname, - headers, - body: req.body, - }); - const signed = await signer.sign(request); - return signed.headers; -}; -const withTempEnv = async (updateEnv, fn) => { - const previousEnv = { ...process.env }; - try { - updateEnv(); - return await fn(); - } - finally { - process.env = previousEnv; - } -}; -//# sourceMappingURL=auth.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/error.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/error.mjs deleted file mode 100644 index ea9269e5..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/error.mjs +++ /dev/null @@ -1,2 +0,0 @@ -export * from '@anthropic-ai/sdk/core/error'; -//# sourceMappingURL=error.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/streaming.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/streaming.mjs deleted file mode 100644 index af05ecd9..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/core/streaming.mjs +++ /dev/null @@ -1,108 +0,0 @@ -import { EventStreamMarshaller } from '@smithy/eventstream-serde-node'; -import { fromBase64, toBase64 } from '@smithy/util-base64'; -import { streamCollector } from '@smithy/fetch-http-handler'; -import { Stream as CoreStream } from '@anthropic-ai/sdk/streaming'; -import { AnthropicError } from '@anthropic-ai/sdk/error'; -import { APIError } from '@anthropic-ai/sdk'; -import { de_ResponseStream } from "../AWS_restJson1.mjs"; -import { ReadableStreamToAsyncIterable } from "../internal/shims.mjs"; -import { safeJSON } from "../internal/utils/values.mjs"; -import { loggerFor } from "../internal/utils/log.mjs"; -export const toUtf8 = (input) => new TextDecoder('utf-8').decode(input); -export const fromUtf8 = (input) => new TextEncoder().encode(input); -// `de_ResponseStream` parses a Bedrock response stream and emits events as they are found. -// It requires a "context" argument which has many fields, but for what we're using it for -// it only needs this. -export const getMinimalSerdeContext = () => { - const marshaller = new EventStreamMarshaller({ utf8Encoder: toUtf8, utf8Decoder: fromUtf8 }); - return { - base64Decoder: fromBase64, - base64Encoder: toBase64, - utf8Decoder: fromUtf8, - utf8Encoder: toUtf8, - eventStreamMarshaller: marshaller, - streamCollector: streamCollector, - }; -}; -export class Stream extends CoreStream { - static fromSSEResponse(response, controller, client) { - let consumed = false; - const logger = client ? loggerFor(client) : console; - async function* iterMessages() { - if (!response.body) { - controller.abort(); - throw new AnthropicError(`Attempted to iterate over a response with no body`); - } - const responseBodyIter = ReadableStreamToAsyncIterable(response.body); - const eventStream = de_ResponseStream(responseBodyIter, getMinimalSerdeContext()); - for await (const event of eventStream) { - if (event.chunk && event.chunk.bytes) { - const s = toUtf8(event.chunk.bytes); - yield { event: 'chunk', data: s, raw: [] }; - } - else if (event.internalServerException) { - yield { event: 'error', data: 'InternalServerException', raw: [] }; - } - else if (event.modelStreamErrorException) { - yield { event: 'error', data: 'ModelStreamErrorException', raw: [] }; - } - else if (event.validationException) { - yield { event: 'error', data: 'ValidationException', raw: [] }; - } - else if (event.throttlingException) { - yield { event: 'error', data: 'ThrottlingException', raw: [] }; - } - } - } - // Note: this function is copied entirely from the core SDK - async function* iterator() { - if (consumed) { - throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); - } - consumed = true; - let done = false; - try { - for await (const sse of iterMessages()) { - if (sse.event === 'chunk') { - 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 === 'error') { - const errText = sse.data; - const errJSON = safeJSON(errText); - const errMessage = errJSON ? undefined : errText; - throw APIError.generate(undefined, errJSON, errMessage, 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); - } -} -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')))); -} -//# sourceMappingURL=streaming.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/index.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/index.mjs deleted file mode 100644 index 11c1728f..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/index.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export * from "./client.mjs"; -export { AnthropicBedrock as default } from "./client.mjs"; -//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/headers.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/headers.mjs deleted file mode 100644 index 94b059b4..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/headers.mjs +++ /dev/null @@ -1,74 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/shims.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/shims.mjs deleted file mode 100644 index c511fe86..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/shims.mjs +++ /dev/null @@ -1,85 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/env.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/env.mjs deleted file mode 100644 index 58ddfda1..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/env.mjs +++ /dev/null @@ -1,18 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/log.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/log.mjs deleted file mode 100644 index 95cdd225..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/log.mjs +++ /dev/null @@ -1,80 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/path.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/path.mjs deleted file mode 100644 index 0586cbe1..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/path.mjs +++ /dev/null @@ -1,74 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/values.mjs b/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/values.mjs deleted file mode 100644 index 40388cf3..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/bedrock-sdk/internal/utils/values.mjs +++ /dev/null @@ -1,94 +0,0 @@ -// 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; - } -}; -//# sourceMappingURL=values.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/client.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/client.mjs deleted file mode 100644 index 70476b52..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/client.mjs +++ /dev/null @@ -1,98 +0,0 @@ -import { buildHeaders } from "./internal/headers.mjs"; -import * as Errors from "./core/error.mjs"; -import { readEnv } from "./internal/utils.mjs"; -import { Anthropic } from '@anthropic-ai/sdk/client'; -export { BaseAnthropic } from '@anthropic-ai/sdk/client'; -import * as Resources from '@anthropic-ai/sdk/resources/index'; -/** API Client for interfacing with the Anthropic Foundry API. */ -export class AnthropicFoundry extends Anthropic { - /** - * API Client for interfacing with the Anthropic Foundry API. - * - * @param {string | undefined} [opts.resource=process.env['ANTHROPIC_FOUNDRY_RESOURCE'] ?? undefined] - Your Foundry resource name - * @param {string | undefined} [opts.apiKey=process.env['ANTHROPIC_FOUNDRY_API_KEY'] ?? undefined] - * @param {string | null | undefined} [opts.organization=process.env['ANTHROPIC_ORG_ID'] ?? null] - * @param {string} [opts.baseURL=process.env['ANTHROPIC_FOUNDRY_BASE_URL']] - Sets the base URL for the API, e.g. `https://example-resource.azure.anthropic.com/anthropic/`. - * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. - * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. - * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. - * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. - * @param {Headers} opts.defaultHeaders - Default headers to include with every request to the API. - * @param {DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. - * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. - */ - constructor({ baseURL = readEnv('ANTHROPIC_FOUNDRY_BASE_URL'), apiKey = readEnv('ANTHROPIC_FOUNDRY_API_KEY'), resource = readEnv('ANTHROPIC_FOUNDRY_RESOURCE'), azureADTokenProvider, dangerouslyAllowBrowser, ...opts } = {}) { - if (typeof azureADTokenProvider === 'function') { - dangerouslyAllowBrowser = true; - } - if (!azureADTokenProvider && !apiKey) { - throw new Errors.AnthropicError('Missing credentials. Please pass one of `apiKey` and `azureTokenProvider`, or set the `ANTHROPIC_FOUNDRY_API_KEY` environment variable.'); - } - if (azureADTokenProvider && apiKey) { - throw new Errors.AnthropicError('The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.'); - } - if (!baseURL) { - if (!resource) { - throw new Errors.AnthropicError('Must provide one of the `baseURL` or `resource` arguments, or the `ANTHROPIC_FOUNDRY_RESOURCE` environment variable'); - } - baseURL = `https://${resource}.services.ai.azure.com/anthropic/`; - } - else { - if (resource) { - throw new Errors.AnthropicError('baseURL and resource are mutually exclusive'); - } - } - super({ - apiKey: azureADTokenProvider ?? apiKey, - baseURL, - ...opts, - ...(dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}), - }); - this.resource = null; - // @ts-expect-error are using a different Messages type that omits batches - this.messages = makeMessagesResource(this); - // @ts-expect-error are using a different Beta type that omits batches - this.beta = makeBetaResource(this); - // @ts-expect-error Anthropic Foundry does not support models endpoint - this.models = undefined; - } - async authHeaders() { - if (typeof this._options.apiKey === 'function') { - let token; - try { - token = await this._options.apiKey(); - } - catch (err) { - if (err instanceof Errors.AnthropicError) - throw err; - throw new Errors.AnthropicError(`Failed to get token from azureADTokenProvider: ${err.message}`, - // @ts-ignore - { cause: err }); - } - if (typeof token !== 'string' || !token) { - throw new Errors.AnthropicError(`Expected azureADTokenProvider function argument to return a string but it returned ${token}`); - } - return buildHeaders([{ Authorization: `Bearer ${token}` }]); - } - if (typeof this._options.apiKey === 'string') { - return buildHeaders([{ 'x-api-key': this.apiKey }]); - } - return undefined; - } - validateHeaders() { - return; - } -} -function makeMessagesResource(client) { - const resource = new Resources.Messages(client); - // @ts-expect-error we're deleting non-optional properties - delete resource.batches; - return resource; -} -function makeBetaResource(client) { - const resource = new Resources.Beta(client); - // @ts-expect-error we're deleting non-optional properties - delete resource.messages.batches; - return resource; -} -//# sourceMappingURL=client.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/core/error.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/core/error.mjs deleted file mode 100644 index ea9269e5..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/core/error.mjs +++ /dev/null @@ -1,2 +0,0 @@ -export * from '@anthropic-ai/sdk/core/error'; -//# sourceMappingURL=error.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/index.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/index.mjs deleted file mode 100644 index 6b20cb90..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/index.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export * from "./client.mjs"; -export { AnthropicFoundry as default } from "./client.mjs"; -//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/headers.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/headers.mjs deleted file mode 100644 index 94b059b4..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/headers.mjs +++ /dev/null @@ -1,74 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils.mjs deleted file mode 100644 index 01563e2e..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils.mjs +++ /dev/null @@ -1,8 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -export * from "./utils/values.mjs"; -export * from "./utils/base64.mjs"; -export * from "./utils/env.mjs"; -export * from "./utils/log.mjs"; -export * from "./utils/uuid.mjs"; -export * from "./utils/sleep.mjs"; -//# sourceMappingURL=utils.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/base64.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/base64.mjs deleted file mode 100644 index 7e1a83df..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/base64.mjs +++ /dev/null @@ -1,33 +0,0 @@ -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -import { AnthropicError } from "../../core/error.mjs"; -import { encodeUTF8 } from "./bytes.mjs"; -export const toBase64 = (data) => { - if (!data) - return ''; - if (typeof globalThis.Buffer !== 'undefined') { - return globalThis.Buffer.from(data).toString('base64'); - } - if (typeof data === 'string') { - data = encodeUTF8(data); - } - if (typeof btoa !== 'undefined') { - return btoa(String.fromCharCode.apply(null, data)); - } - throw new AnthropicError('Cannot generate base64 string; Expected `Buffer` or `btoa` to be defined'); -}; -export const fromBase64 = (str) => { - if (typeof globalThis.Buffer !== 'undefined') { - const buf = globalThis.Buffer.from(str, 'base64'); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); - } - if (typeof atob !== 'undefined') { - const bstr = atob(str); - const buf = new Uint8Array(bstr.length); - for (let i = 0; i < bstr.length; i++) { - buf[i] = bstr.charCodeAt(i); - } - return buf; - } - throw new AnthropicError('Cannot decode base64 string; Expected `Buffer` or `atob` to be defined'); -}; -//# sourceMappingURL=base64.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/env.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/env.mjs deleted file mode 100644 index 58ddfda1..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/env.mjs +++ /dev/null @@ -1,18 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/log.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/log.mjs deleted file mode 100644 index 95cdd225..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/log.mjs +++ /dev/null @@ -1,80 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/sleep.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/sleep.mjs deleted file mode 100644 index 9d192686..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/sleep.mjs +++ /dev/null @@ -1 +0,0 @@ -export function sleep(ms) { return new Promise(r => setTimeout(r, ms)) } diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/uuid.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/uuid.mjs deleted file mode 100644 index bfb66d9d..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/uuid.mjs +++ /dev/null @@ -1,2 +0,0 @@ -import { randomUUID } from 'crypto' -export function generateUUID() { return randomUUID() } diff --git a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/values.mjs b/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/values.mjs deleted file mode 100644 index 7b9bf757..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/foundry-sdk/internal/utils/values.mjs +++ /dev/null @@ -1,100 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs deleted file mode 100644 index d2e0d5cb..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs +++ /dev/null @@ -1,223 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/client.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/client.mjs deleted file mode 100644 index 8be4f0c6..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/client.mjs +++ /dev/null @@ -1,559 +0,0 @@ -// 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} 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/core/api-promise.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/core/api-promise.mjs deleted file mode 100644 index 3d67649a..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/core/api-promise.mjs +++ /dev/null @@ -1,72 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/core/error.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/core/error.mjs deleted file mode 100644 index b2e189f8..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/core/error.mjs +++ /dev/null @@ -1,98 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/core/pagination.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/core/pagination.mjs deleted file mode 100644 index 3c9870f5..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/core/pagination.mjs +++ /dev/null @@ -1,177 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/core/resource.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/core/resource.mjs deleted file mode 100644 index 98ee0dc7..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/core/resource.mjs +++ /dev/null @@ -1,7 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/core/streaming.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/core/streaming.mjs deleted file mode 100644 index 1a73032a..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/core/streaming.mjs +++ /dev/null @@ -1,283 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/core/uploads.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/core/uploads.mjs deleted file mode 100644 index 40d3593e..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/core/uploads.mjs +++ /dev/null @@ -1,2 +0,0 @@ -export { toFile } from "../internal/to-file.mjs"; -//# sourceMappingURL=uploads.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/error.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/error.mjs deleted file mode 100644 index 350c6d43..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/error.mjs +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./core/error.mjs"; -//# sourceMappingURL=error.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/index.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/index.mjs deleted file mode 100644 index 5d7711c4..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/index.mjs +++ /dev/null @@ -1,8 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/constants.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/constants.mjs deleted file mode 100644 index 4b001aae..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/constants.mjs +++ /dev/null @@ -1,15 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs deleted file mode 100644 index 6d3f4b9e..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs +++ /dev/null @@ -1,35 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs deleted file mode 100644 index 3e1207c0..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs +++ /dev/null @@ -1,108 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs deleted file mode 100644 index 7e828ecf..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs +++ /dev/null @@ -1,157 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/errors.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/errors.mjs deleted file mode 100644 index 8b7356eb..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/errors.mjs +++ /dev/null @@ -1,36 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/headers.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/headers.mjs deleted file mode 100644 index 94b059b4..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/headers.mjs +++ /dev/null @@ -1,74 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/parse.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/parse.mjs deleted file mode 100644 index 50a84eda..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/parse.mjs +++ /dev/null @@ -1,56 +0,0 @@ -// 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` - 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/request-options.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/request-options.mjs deleted file mode 100644 index 312df353..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/request-options.mjs +++ /dev/null @@ -1,10 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/shims.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/shims.mjs deleted file mode 100644 index c511fe86..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/shims.mjs +++ /dev/null @@ -1,85 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/to-file.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/to-file.mjs deleted file mode 100644 index 5644c71e..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/to-file.mjs +++ /dev/null @@ -1,93 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/tslib.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/tslib.mjs deleted file mode 100644 index a80a1321..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/tslib.mjs +++ /dev/null @@ -1,17 +0,0 @@ -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 }; diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/uploads.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/uploads.mjs deleted file mode 100644 index 24680872..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/uploads.mjs +++ /dev/null @@ -1,135 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs deleted file mode 100644 index 5b9bb389..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs +++ /dev/null @@ -1,26 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs deleted file mode 100644 index 58ddfda1..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs +++ /dev/null @@ -1,18 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs deleted file mode 100644 index 95cdd225..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs +++ /dev/null @@ -1,80 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs deleted file mode 100644 index 0586cbe1..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs +++ /dev/null @@ -1,74 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs deleted file mode 100644 index 784954ac..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs +++ /dev/null @@ -1,3 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs deleted file mode 100644 index 4fe2cb25..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs +++ /dev/null @@ -1,15 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs deleted file mode 100644 index 7b9bf757..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs +++ /dev/null @@ -1,100 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs deleted file mode 100644 index 4b9c2355..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs +++ /dev/null @@ -1,616 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs deleted file mode 100644 index bca6c2f7..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs +++ /dev/null @@ -1,591 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs deleted file mode 100644 index 8d5ba0a6..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs +++ /dev/null @@ -1,75 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/parser.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/parser.mjs deleted file mode 100644 index 86a0f957..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/parser.mjs +++ /dev/null @@ -1,62 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/stainless-helper-header.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/stainless-helper-header.mjs deleted file mode 100644 index cc62422d..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/stainless-helper-header.mjs +++ /dev/null @@ -1,63 +0,0 @@ -/** - * 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs deleted file mode 100644 index fa6e3c14..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs +++ /dev/null @@ -1,372 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/CompactionControl.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/CompactionControl.mjs deleted file mode 100644 index 14e54dd7..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/CompactionControl.mjs +++ /dev/null @@ -1,25 +0,0 @@ -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 tags.`; -//# sourceMappingURL=CompactionControl.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/ToolError.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/ToolError.mjs deleted file mode 100644 index 805a6a1c..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/lib/tools/ToolError.mjs +++ /dev/null @@ -1,38 +0,0 @@ -/** - * 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs deleted file mode 100644 index 7a998aa4..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs +++ /dev/null @@ -1,24 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs deleted file mode 100644 index f99b133f..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs +++ /dev/null @@ -1,120 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs deleted file mode 100644 index 259c0011..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs +++ /dev/null @@ -1,200 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs deleted file mode 100644 index e3fcfd1e..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs +++ /dev/null @@ -1,156 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs deleted file mode 100644 index 645c853d..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs +++ /dev/null @@ -1,56 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs deleted file mode 100644 index 73f3508e..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs +++ /dev/null @@ -1,93 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs deleted file mode 100644 index 699cdd11..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs +++ /dev/null @@ -1,96 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/completions.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/completions.mjs deleted file mode 100644 index 648f8e96..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/completions.mjs +++ /dev/null @@ -1,19 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/index.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/index.mjs deleted file mode 100644 index 01d72943..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/index.mjs +++ /dev/null @@ -1,7 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs deleted file mode 100644 index d0fedfec..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs +++ /dev/null @@ -1,149 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs deleted file mode 100644 index 7f0bb155..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs +++ /dev/null @@ -1,123 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/models.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/resources/models.mjs deleted file mode 100644 index 15e0aff8..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/resources/models.mjs +++ /dev/null @@ -1,41 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/streaming.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/streaming.mjs deleted file mode 100644 index 5ca840af..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/streaming.mjs +++ /dev/null @@ -1,2 +0,0 @@ -export * from "./core/streaming.mjs"; -//# sourceMappingURL=streaming.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/sdk/version.mjs b/claude-code-source/node_modules/@anthropic-ai/sdk/version.mjs deleted file mode 100644 index 7e0b250b..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/sdk/version.mjs +++ /dev/null @@ -1,2 +0,0 @@ -export const VERSION = '0.74.0'; // x-release-please-version -//# sourceMappingURL=version.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/client.mjs b/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/client.mjs deleted file mode 100644 index db0d13a9..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/client.mjs +++ /dev/null @@ -1,114 +0,0 @@ -import { BaseAnthropic } from '@anthropic-ai/sdk/client'; -import * as Resources from '@anthropic-ai/sdk/resources/index'; -import { GoogleAuth } from 'google-auth-library'; -import { readEnv } from "./internal/utils/env.mjs"; -import { isObj } from "./internal/utils/values.mjs"; -import { buildHeaders } from "./internal/headers.mjs"; -export { BaseAnthropic } from '@anthropic-ai/sdk/client'; -const DEFAULT_VERSION = 'vertex-2023-10-16'; -const MODEL_ENDPOINTS = new Set(['/v1/messages', '/v1/messages?beta=true']); -export class AnthropicVertex extends BaseAnthropic { - /** - * API Client for interfacing with the Anthropic Vertex API. - * - * @param {string | null} opts.accessToken - * @param {string | null} opts.projectId - * @param {GoogleAuth} opts.googleAuth - Override the default google auth config - * @param {AuthClient} opts.authClient - Provide a pre-configured AuthClient instance (alternative to googleAuth) - * @param {string | null} [opts.region=process.env['CLOUD_ML_REGION']] - The region to use for the API. Use 'global' for global endpoint. [More details here](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations). - * @param {string} [opts.baseURL=process.env['ANTHROPIC_VERTEX__BASE_URL'] ?? https://${region}-aiplatform.googleapis.com/v1] - Override the default base URL for the API. - * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. - * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. - * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. - * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. - * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. - * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. - * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. - */ - constructor({ baseURL = readEnv('ANTHROPIC_VERTEX_BASE_URL'), region = readEnv('CLOUD_ML_REGION') ?? null, projectId = readEnv('ANTHROPIC_VERTEX_PROJECT_ID') ?? null, ...opts } = {}) { - if (!region) { - throw new Error('No region was given. The client should be instantiated with the `region` option or the `CLOUD_ML_REGION` environment variable should be set.'); - } - super({ - baseURL: baseURL || - (region === 'global' ? - 'https://aiplatform.googleapis.com/v1' - : `https://${region}-aiplatform.googleapis.com/v1`), - ...opts, - }); - this.messages = makeMessagesResource(this); - this.beta = makeBetaResource(this); - this.region = region; - this.projectId = projectId; - this.accessToken = opts.accessToken ?? null; - if (opts.authClient && opts.googleAuth) { - throw new Error('You cannot provide both `authClient` and `googleAuth`. Please provide only one of them.'); - } - else if (opts.authClient) { - this._authClientPromise = Promise.resolve(opts.authClient); - } - else { - this._auth = - opts.googleAuth ?? new GoogleAuth({ scopes: 'https://www.googleapis.com/auth/cloud-platform' }); - this._authClientPromise = this._auth.getClient(); - } - } - validateHeaders() { - // auth validation is handled in prepareOptions since it needs to be async - } - async prepareOptions(options) { - const authClient = await this._authClientPromise; - const authHeaders = await authClient.getRequestHeaders(); - const projectId = authClient.projectId ?? authHeaders['x-goog-user-project']; - if (!this.projectId && projectId) { - this.projectId = projectId; - } - options.headers = buildHeaders([authHeaders, options.headers]); - } - async buildRequest(options) { - if (isObj(options.body)) { - // create a shallow copy of the request body so that code that mutates it later - // doesn't mutate the original user-provided object - options.body = { ...options.body }; - } - if (isObj(options.body)) { - if (!options.body['anthropic_version']) { - options.body['anthropic_version'] = DEFAULT_VERSION; - } - } - if (MODEL_ENDPOINTS.has(options.path) && options.method === 'post') { - if (!this.projectId) { - throw new Error('No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.'); - } - if (!isObj(options.body)) { - throw new Error('Expected request body to be an object for post /v1/messages'); - } - const model = options.body['model']; - options.body['model'] = undefined; - const stream = options.body['stream'] ?? false; - const specifier = stream ? 'streamRawPredict' : 'rawPredict'; - options.path = `/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/${model}:${specifier}`; - } - if (options.path === '/v1/messages/count_tokens' || - (options.path == '/v1/messages/count_tokens?beta=true' && options.method === 'post')) { - if (!this.projectId) { - throw new Error('No projectId was given and it could not be resolved from credentials. The client should be instantiated with the `projectId` option or the `ANTHROPIC_VERTEX_PROJECT_ID` environment variable should be set.'); - } - options.path = `/projects/${this.projectId}/locations/${this.region}/publishers/anthropic/models/count-tokens:rawPredict`; - } - return super.buildRequest(options); - } -} -function makeMessagesResource(client) { - const resource = new Resources.Messages(client); - // @ts-expect-error we're deleting non-optional properties - delete resource.batches; - return resource; -} -function makeBetaResource(client) { - const resource = new Resources.Beta(client); - // @ts-expect-error we're deleting non-optional properties - delete resource.messages.batches; - return resource; -} -//# sourceMappingURL=client.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/core/error.mjs b/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/core/error.mjs deleted file mode 100644 index ea9269e5..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/core/error.mjs +++ /dev/null @@ -1,2 +0,0 @@ -export * from '@anthropic-ai/sdk/core/error'; -//# sourceMappingURL=error.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/index.mjs b/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/index.mjs deleted file mode 100644 index 3f2aa54b..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/index.mjs +++ /dev/null @@ -1,3 +0,0 @@ -export * from "./client.mjs"; -export { AnthropicVertex as default } from "./client.mjs"; -//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs b/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs deleted file mode 100644 index 94b059b4..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/headers.mjs +++ /dev/null @@ -1,74 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/utils/env.mjs b/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/utils/env.mjs deleted file mode 100644 index 58ddfda1..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/utils/env.mjs +++ /dev/null @@ -1,18 +0,0 @@ -// 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/utils/values.mjs b/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/utils/values.mjs deleted file mode 100644 index 40388cf3..00000000 --- a/claude-code-source/node_modules/@anthropic-ai/vertex-sdk/internal/utils/values.mjs +++ /dev/null @@ -1,94 +0,0 @@ -// 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; - } -}; -//# sourceMappingURL=values.mjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/crc32/build/main/aws_crc32.js b/claude-code-source/node_modules/@aws-crypto/crc32/build/main/aws_crc32.js deleted file mode 100644 index 09c304cd..00000000 --- a/claude-code-source/node_modules/@aws-crypto/crc32/build/main/aws_crc32.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AwsCrc32 = void 0; -var tslib_1 = require("tslib"); -var util_1 = require("@aws-crypto/util"); -var index_1 = require("./index"); -var AwsCrc32 = /** @class */ (function () { - function AwsCrc32() { - this.crc32 = new index_1.Crc32(); - } - AwsCrc32.prototype.update = function (toHash) { - if ((0, util_1.isEmptyData)(toHash)) - return; - this.crc32.update((0, util_1.convertToBuffer)(toHash)); - }; - AwsCrc32.prototype.digest = function () { - return tslib_1.__awaiter(this, void 0, void 0, function () { - return tslib_1.__generator(this, function (_a) { - return [2 /*return*/, (0, util_1.numToUint8)(this.crc32.digest())]; - }); - }); - }; - AwsCrc32.prototype.reset = function () { - this.crc32 = new index_1.Crc32(); - }; - return AwsCrc32; -}()); -exports.AwsCrc32 = AwsCrc32; -//# sourceMappingURL=aws_crc32.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/crc32/build/main/index.js b/claude-code-source/node_modules/@aws-crypto/crc32/build/main/index.js deleted file mode 100644 index fa789688..00000000 --- a/claude-code-source/node_modules/@aws-crypto/crc32/build/main/index.js +++ /dev/null @@ -1,108 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AwsCrc32 = exports.Crc32 = exports.crc32 = void 0; -var tslib_1 = require("tslib"); -var util_1 = require("@aws-crypto/util"); -function crc32(data) { - return new Crc32().update(data).digest(); -} -exports.crc32 = crc32; -var Crc32 = /** @class */ (function () { - function Crc32() { - this.checksum = 0xffffffff; - } - Crc32.prototype.update = function (data) { - var e_1, _a; - try { - for (var data_1 = tslib_1.__values(data), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) { - var byte = data_1_1.value; - this.checksum = - (this.checksum >>> 8) ^ lookupTable[(this.checksum ^ byte) & 0xff]; - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (data_1_1 && !data_1_1.done && (_a = data_1.return)) _a.call(data_1); - } - finally { if (e_1) throw e_1.error; } - } - return this; - }; - Crc32.prototype.digest = function () { - return (this.checksum ^ 0xffffffff) >>> 0; - }; - return Crc32; -}()); -exports.Crc32 = Crc32; -// prettier-ignore -var a_lookUpTable = [ - 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, - 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, - 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, - 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, - 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, - 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, - 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, - 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, - 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, - 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, - 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, - 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, - 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, - 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, - 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, - 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, - 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, - 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, - 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, - 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, - 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, - 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, - 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, - 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, - 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, - 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, - 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, - 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, - 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, - 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, - 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, - 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, - 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, - 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, - 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, - 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, - 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, - 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, - 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, - 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, - 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, - 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, - 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, - 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, - 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, - 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, - 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, - 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, - 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, - 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, - 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, - 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, - 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, - 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, - 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, - 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, - 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, - 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, - 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, - 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, - 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, - 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, - 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, - 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D, -]; -var lookupTable = (0, util_1.uint32ArrayFrom)(a_lookUpTable); -var aws_crc32_1 = require("./aws_crc32"); -Object.defineProperty(exports, "AwsCrc32", { enumerable: true, get: function () { return aws_crc32_1.AwsCrc32; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/convertToBuffer.js b/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/convertToBuffer.js deleted file mode 100644 index 85bc8af4..00000000 --- a/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/convertToBuffer.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -Object.defineProperty(exports, "__esModule", { value: true }); -exports.convertToBuffer = void 0; -var util_utf8_1 = require("@smithy/util-utf8"); -// Quick polyfill -var fromUtf8 = typeof Buffer !== "undefined" && Buffer.from - ? function (input) { return Buffer.from(input, "utf8"); } - : util_utf8_1.fromUtf8; -function convertToBuffer(data) { - // Already a Uint8, do nothing - if (data instanceof Uint8Array) - return data; - if (typeof data === "string") { - return fromUtf8(data); - } - if (ArrayBuffer.isView(data)) { - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); - } - return new Uint8Array(data); -} -exports.convertToBuffer = convertToBuffer; -//# sourceMappingURL=convertToBuffer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/index.js b/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/index.js deleted file mode 100644 index 94e1ca90..00000000 --- a/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/index.js +++ /dev/null @@ -1,14 +0,0 @@ -"use strict"; -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -Object.defineProperty(exports, "__esModule", { value: true }); -exports.uint32ArrayFrom = exports.numToUint8 = exports.isEmptyData = exports.convertToBuffer = void 0; -var convertToBuffer_1 = require("./convertToBuffer"); -Object.defineProperty(exports, "convertToBuffer", { enumerable: true, get: function () { return convertToBuffer_1.convertToBuffer; } }); -var isEmptyData_1 = require("./isEmptyData"); -Object.defineProperty(exports, "isEmptyData", { enumerable: true, get: function () { return isEmptyData_1.isEmptyData; } }); -var numToUint8_1 = require("./numToUint8"); -Object.defineProperty(exports, "numToUint8", { enumerable: true, get: function () { return numToUint8_1.numToUint8; } }); -var uint32ArrayFrom_1 = require("./uint32ArrayFrom"); -Object.defineProperty(exports, "uint32ArrayFrom", { enumerable: true, get: function () { return uint32ArrayFrom_1.uint32ArrayFrom; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/isEmptyData.js b/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/isEmptyData.js deleted file mode 100644 index 6af1e89e..00000000 --- a/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/isEmptyData.js +++ /dev/null @@ -1,13 +0,0 @@ -"use strict"; -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isEmptyData = void 0; -function isEmptyData(data) { - if (typeof data === "string") { - return data.length === 0; - } - return data.byteLength === 0; -} -exports.isEmptyData = isEmptyData; -//# sourceMappingURL=isEmptyData.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/numToUint8.js b/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/numToUint8.js deleted file mode 100644 index 2f070e10..00000000 --- a/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/numToUint8.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -Object.defineProperty(exports, "__esModule", { value: true }); -exports.numToUint8 = void 0; -function numToUint8(num) { - return new Uint8Array([ - (num & 0xff000000) >> 24, - (num & 0x00ff0000) >> 16, - (num & 0x0000ff00) >> 8, - num & 0x000000ff, - ]); -} -exports.numToUint8 = numToUint8; -//# sourceMappingURL=numToUint8.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/uint32ArrayFrom.js b/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/uint32ArrayFrom.js deleted file mode 100644 index 226cdc3d..00000000 --- a/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/main/uint32ArrayFrom.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -Object.defineProperty(exports, "__esModule", { value: true }); -exports.uint32ArrayFrom = void 0; -// IE 11 does not support Array.from, so we do it manually -function uint32ArrayFrom(a_lookUpTable) { - if (!Uint32Array.from) { - var return_array = new Uint32Array(a_lookUpTable.length); - var a_index = 0; - while (a_index < a_lookUpTable.length) { - return_array[a_index] = a_lookUpTable[a_index]; - a_index += 1; - } - return return_array; - } - return Uint32Array.from(a_lookUpTable); -} -exports.uint32ArrayFrom = uint32ArrayFrom; -//# sourceMappingURL=uint32ArrayFrom.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-cjs/index.js b/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-cjs/index.js deleted file mode 100644 index 0b22680a..00000000 --- a/claude-code-source/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/node_modules/@smithy/util-utf8/dist-cjs/index.js +++ /dev/null @@ -1,65 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - fromUtf8: () => fromUtf8, - toUint8Array: () => toUint8Array, - toUtf8: () => toUtf8 -}); -module.exports = __toCommonJS(src_exports); - -// src/fromUtf8.ts -var import_util_buffer_from = require("@smithy/util-buffer-from"); -var fromUtf8 = /* @__PURE__ */ __name((input) => { - const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); -}, "fromUtf8"); - -// src/toUint8Array.ts -var toUint8Array = /* @__PURE__ */ __name((data) => { - if (typeof data === "string") { - return fromUtf8(data); - } - if (ArrayBuffer.isView(data)) { - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); - } - return new Uint8Array(data); -}, "toUint8Array"); - -// src/toUtf8.ts - -var toUtf8 = /* @__PURE__ */ __name((input) => { - if (typeof input === "string") { - return input; - } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); - } - return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); -}, "toUtf8"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - fromUtf8, - toUint8Array, - toUtf8 -}); - diff --git a/claude-code-source/node_modules/@aws-crypto/sha256-js/build/RawSha256.js b/claude-code-source/node_modules/@aws-crypto/sha256-js/build/RawSha256.js deleted file mode 100644 index 68ceaccd..00000000 --- a/claude-code-source/node_modules/@aws-crypto/sha256-js/build/RawSha256.js +++ /dev/null @@ -1,124 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RawSha256 = void 0; -var constants_1 = require("./constants"); -/** - * @internal - */ -var RawSha256 = /** @class */ (function () { - function RawSha256() { - this.state = Int32Array.from(constants_1.INIT); - this.temp = new Int32Array(64); - this.buffer = new Uint8Array(64); - this.bufferLength = 0; - this.bytesHashed = 0; - /** - * @internal - */ - this.finished = false; - } - RawSha256.prototype.update = function (data) { - if (this.finished) { - throw new Error("Attempted to update an already finished hash."); - } - var position = 0; - var byteLength = data.byteLength; - this.bytesHashed += byteLength; - if (this.bytesHashed * 8 > constants_1.MAX_HASHABLE_LENGTH) { - throw new Error("Cannot hash more than 2^53 - 1 bits"); - } - while (byteLength > 0) { - this.buffer[this.bufferLength++] = data[position++]; - byteLength--; - if (this.bufferLength === constants_1.BLOCK_SIZE) { - this.hashBuffer(); - this.bufferLength = 0; - } - } - }; - RawSha256.prototype.digest = function () { - if (!this.finished) { - var bitsHashed = this.bytesHashed * 8; - var bufferView = new DataView(this.buffer.buffer, this.buffer.byteOffset, this.buffer.byteLength); - var undecoratedLength = this.bufferLength; - bufferView.setUint8(this.bufferLength++, 0x80); - // Ensure the final block has enough room for the hashed length - if (undecoratedLength % constants_1.BLOCK_SIZE >= constants_1.BLOCK_SIZE - 8) { - for (var i = this.bufferLength; i < constants_1.BLOCK_SIZE; i++) { - bufferView.setUint8(i, 0); - } - this.hashBuffer(); - this.bufferLength = 0; - } - for (var i = this.bufferLength; i < constants_1.BLOCK_SIZE - 8; i++) { - bufferView.setUint8(i, 0); - } - bufferView.setUint32(constants_1.BLOCK_SIZE - 8, Math.floor(bitsHashed / 0x100000000), true); - bufferView.setUint32(constants_1.BLOCK_SIZE - 4, bitsHashed); - this.hashBuffer(); - this.finished = true; - } - // The value in state is little-endian rather than big-endian, so flip - // each word into a new Uint8Array - var out = new Uint8Array(constants_1.DIGEST_LENGTH); - for (var i = 0; i < 8; i++) { - out[i * 4] = (this.state[i] >>> 24) & 0xff; - out[i * 4 + 1] = (this.state[i] >>> 16) & 0xff; - out[i * 4 + 2] = (this.state[i] >>> 8) & 0xff; - out[i * 4 + 3] = (this.state[i] >>> 0) & 0xff; - } - return out; - }; - RawSha256.prototype.hashBuffer = function () { - var _a = this, buffer = _a.buffer, state = _a.state; - var state0 = state[0], state1 = state[1], state2 = state[2], state3 = state[3], state4 = state[4], state5 = state[5], state6 = state[6], state7 = state[7]; - for (var i = 0; i < constants_1.BLOCK_SIZE; i++) { - if (i < 16) { - this.temp[i] = - ((buffer[i * 4] & 0xff) << 24) | - ((buffer[i * 4 + 1] & 0xff) << 16) | - ((buffer[i * 4 + 2] & 0xff) << 8) | - (buffer[i * 4 + 3] & 0xff); - } - else { - var u = this.temp[i - 2]; - var t1_1 = ((u >>> 17) | (u << 15)) ^ ((u >>> 19) | (u << 13)) ^ (u >>> 10); - u = this.temp[i - 15]; - var t2_1 = ((u >>> 7) | (u << 25)) ^ ((u >>> 18) | (u << 14)) ^ (u >>> 3); - this.temp[i] = - ((t1_1 + this.temp[i - 7]) | 0) + ((t2_1 + this.temp[i - 16]) | 0); - } - var t1 = ((((((state4 >>> 6) | (state4 << 26)) ^ - ((state4 >>> 11) | (state4 << 21)) ^ - ((state4 >>> 25) | (state4 << 7))) + - ((state4 & state5) ^ (~state4 & state6))) | - 0) + - ((state7 + ((constants_1.KEY[i] + this.temp[i]) | 0)) | 0)) | - 0; - var t2 = ((((state0 >>> 2) | (state0 << 30)) ^ - ((state0 >>> 13) | (state0 << 19)) ^ - ((state0 >>> 22) | (state0 << 10))) + - ((state0 & state1) ^ (state0 & state2) ^ (state1 & state2))) | - 0; - state7 = state6; - state6 = state5; - state5 = state4; - state4 = (state3 + t1) | 0; - state3 = state2; - state2 = state1; - state1 = state0; - state0 = (t1 + t2) | 0; - } - state[0] += state0; - state[1] += state1; - state[2] += state2; - state[3] += state3; - state[4] += state4; - state[5] += state5; - state[6] += state6; - state[7] += state7; - }; - return RawSha256; -}()); -exports.RawSha256 = RawSha256; -//# sourceMappingURL=RawSha256.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/sha256-js/build/constants.js b/claude-code-source/node_modules/@aws-crypto/sha256-js/build/constants.js deleted file mode 100644 index c83aa099..00000000 --- a/claude-code-source/node_modules/@aws-crypto/sha256-js/build/constants.js +++ /dev/null @@ -1,98 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MAX_HASHABLE_LENGTH = exports.INIT = exports.KEY = exports.DIGEST_LENGTH = exports.BLOCK_SIZE = void 0; -/** - * @internal - */ -exports.BLOCK_SIZE = 64; -/** - * @internal - */ -exports.DIGEST_LENGTH = 32; -/** - * @internal - */ -exports.KEY = new Uint32Array([ - 0x428a2f98, - 0x71374491, - 0xb5c0fbcf, - 0xe9b5dba5, - 0x3956c25b, - 0x59f111f1, - 0x923f82a4, - 0xab1c5ed5, - 0xd807aa98, - 0x12835b01, - 0x243185be, - 0x550c7dc3, - 0x72be5d74, - 0x80deb1fe, - 0x9bdc06a7, - 0xc19bf174, - 0xe49b69c1, - 0xefbe4786, - 0x0fc19dc6, - 0x240ca1cc, - 0x2de92c6f, - 0x4a7484aa, - 0x5cb0a9dc, - 0x76f988da, - 0x983e5152, - 0xa831c66d, - 0xb00327c8, - 0xbf597fc7, - 0xc6e00bf3, - 0xd5a79147, - 0x06ca6351, - 0x14292967, - 0x27b70a85, - 0x2e1b2138, - 0x4d2c6dfc, - 0x53380d13, - 0x650a7354, - 0x766a0abb, - 0x81c2c92e, - 0x92722c85, - 0xa2bfe8a1, - 0xa81a664b, - 0xc24b8b70, - 0xc76c51a3, - 0xd192e819, - 0xd6990624, - 0xf40e3585, - 0x106aa070, - 0x19a4c116, - 0x1e376c08, - 0x2748774c, - 0x34b0bcb5, - 0x391c0cb3, - 0x4ed8aa4a, - 0x5b9cca4f, - 0x682e6ff3, - 0x748f82ee, - 0x78a5636f, - 0x84c87814, - 0x8cc70208, - 0x90befffa, - 0xa4506ceb, - 0xbef9a3f7, - 0xc67178f2 -]); -/** - * @internal - */ -exports.INIT = [ - 0x6a09e667, - 0xbb67ae85, - 0x3c6ef372, - 0xa54ff53a, - 0x510e527f, - 0x9b05688c, - 0x1f83d9ab, - 0x5be0cd19 -]; -/** - * @internal - */ -exports.MAX_HASHABLE_LENGTH = Math.pow(2, 53) - 1; -//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/sha256-js/build/index.js b/claude-code-source/node_modules/@aws-crypto/sha256-js/build/index.js deleted file mode 100644 index 4329f109..00000000 --- a/claude-code-source/node_modules/@aws-crypto/sha256-js/build/index.js +++ /dev/null @@ -1,5 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var tslib_1 = require("tslib"); -tslib_1.__exportStar(require("./jsSha256"), exports); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/sha256-js/build/jsSha256.js b/claude-code-source/node_modules/@aws-crypto/sha256-js/build/jsSha256.js deleted file mode 100644 index 2a4f2f19..00000000 --- a/claude-code-source/node_modules/@aws-crypto/sha256-js/build/jsSha256.js +++ /dev/null @@ -1,85 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Sha256 = void 0; -var tslib_1 = require("tslib"); -var constants_1 = require("./constants"); -var RawSha256_1 = require("./RawSha256"); -var util_1 = require("@aws-crypto/util"); -var Sha256 = /** @class */ (function () { - function Sha256(secret) { - this.secret = secret; - this.hash = new RawSha256_1.RawSha256(); - this.reset(); - } - Sha256.prototype.update = function (toHash) { - if ((0, util_1.isEmptyData)(toHash) || this.error) { - return; - } - try { - this.hash.update((0, util_1.convertToBuffer)(toHash)); - } - catch (e) { - this.error = e; - } - }; - /* This synchronous method keeps compatibility - * with the v2 aws-sdk. - */ - Sha256.prototype.digestSync = function () { - if (this.error) { - throw this.error; - } - if (this.outer) { - if (!this.outer.finished) { - this.outer.update(this.hash.digest()); - } - return this.outer.digest(); - } - return this.hash.digest(); - }; - /* The underlying digest method here is synchronous. - * To keep the same interface with the other hash functions - * the default is to expose this as an async method. - * However, it can sometimes be useful to have a sync method. - */ - Sha256.prototype.digest = function () { - return tslib_1.__awaiter(this, void 0, void 0, function () { - return tslib_1.__generator(this, function (_a) { - return [2 /*return*/, this.digestSync()]; - }); - }); - }; - Sha256.prototype.reset = function () { - this.hash = new RawSha256_1.RawSha256(); - if (this.secret) { - this.outer = new RawSha256_1.RawSha256(); - var inner = bufferFromSecret(this.secret); - var outer = new Uint8Array(constants_1.BLOCK_SIZE); - outer.set(inner); - for (var i = 0; i < constants_1.BLOCK_SIZE; i++) { - inner[i] ^= 0x36; - outer[i] ^= 0x5c; - } - this.hash.update(inner); - this.outer.update(outer); - // overwrite the copied key in memory - for (var i = 0; i < inner.byteLength; i++) { - inner[i] = 0; - } - } - }; - return Sha256; -}()); -exports.Sha256 = Sha256; -function bufferFromSecret(secret) { - var input = (0, util_1.convertToBuffer)(secret); - if (input.byteLength > constants_1.BLOCK_SIZE) { - var bufferHash = new RawSha256_1.RawSha256(); - bufferHash.update(input); - input = bufferHash.digest(); - } - var buffer = new Uint8Array(constants_1.BLOCK_SIZE); - buffer.set(input); - return buffer; -} -//# sourceMappingURL=jsSha256.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/sha256-js/node_modules/tslib/tslib.js b/claude-code-source/node_modules/@aws-crypto/sha256-js/node_modules/tslib/tslib.js deleted file mode 100644 index e5b7c9b8..00000000 --- a/claude-code-source/node_modules/@aws-crypto/sha256-js/node_modules/tslib/tslib.js +++ /dev/null @@ -1,284 +0,0 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ - -/* global global, define, System, Reflect, Promise */ -var __extends; -var __assign; -var __rest; -var __decorate; -var __param; -var __metadata; -var __awaiter; -var __generator; -var __exportStar; -var __values; -var __read; -var __spread; -var __spreadArrays; -var __await; -var __asyncGenerator; -var __asyncDelegator; -var __asyncValues; -var __makeTemplateObject; -var __importStar; -var __importDefault; -var __classPrivateFieldGet; -var __classPrivateFieldSet; -var __createBinding; -(function (factory) { - var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; - if (typeof define === "function" && define.amd) { - define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); - } - else if (typeof module === "object" && typeof module.exports === "object") { - factory(createExporter(root, createExporter(module.exports))); - } - else { - factory(createExporter(root)); - } - function createExporter(exports, previous) { - if (exports !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports, "__esModule", { value: true }); - } - else { - exports.__esModule = true; - } - } - return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; - } -}) -(function (exporter) { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - - __extends = function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - - __assign = Object.assign || function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - - __rest = function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; - - __decorate = function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - - __param = function (paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - }; - - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - }; - - __awaiter = function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - - __generator = function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - - __createBinding = function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }; - - __exportStar = function (m, exports) { - for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p]; - }; - - __values = function (o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - - __read = function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - - __spread = function () { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - }; - - __spreadArrays = function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; - }; - - __await = function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - - __asyncGenerator = function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - }; - - __asyncDelegator = function (o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } - }; - - __asyncValues = function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } - }; - - __makeTemplateObject = function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - }; - - __importStar = function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; - }; - - __importDefault = function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - - __classPrivateFieldGet = function (receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - return privateMap.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - privateMap.set(receiver, value); - return value; - }; - - exporter("__extends", __extends); - exporter("__assign", __assign); - exporter("__rest", __rest); - exporter("__decorate", __decorate); - exporter("__param", __param); - exporter("__metadata", __metadata); - exporter("__awaiter", __awaiter); - exporter("__generator", __generator); - exporter("__exportStar", __exportStar); - exporter("__createBinding", __createBinding); - exporter("__values", __values); - exporter("__read", __read); - exporter("__spread", __spread); - exporter("__spreadArrays", __spreadArrays); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); - exporter("__asyncDelegator", __asyncDelegator); - exporter("__asyncValues", __asyncValues); - exporter("__makeTemplateObject", __makeTemplateObject); - exporter("__importStar", __importStar); - exporter("__importDefault", __importDefault); - exporter("__classPrivateFieldGet", __classPrivateFieldGet); - exporter("__classPrivateFieldSet", __classPrivateFieldSet); -}); diff --git a/claude-code-source/node_modules/@aws-crypto/util/build/convertToBuffer.js b/claude-code-source/node_modules/@aws-crypto/util/build/convertToBuffer.js deleted file mode 100644 index 6cc8bcfe..00000000 --- a/claude-code-source/node_modules/@aws-crypto/util/build/convertToBuffer.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -Object.defineProperty(exports, "__esModule", { value: true }); -exports.convertToBuffer = void 0; -var util_utf8_browser_1 = require("@aws-sdk/util-utf8-browser"); -// Quick polyfill -var fromUtf8 = typeof Buffer !== "undefined" && Buffer.from - ? function (input) { return Buffer.from(input, "utf8"); } - : util_utf8_browser_1.fromUtf8; -function convertToBuffer(data) { - // Already a Uint8, do nothing - if (data instanceof Uint8Array) - return data; - if (typeof data === "string") { - return fromUtf8(data); - } - if (ArrayBuffer.isView(data)) { - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); - } - return new Uint8Array(data); -} -exports.convertToBuffer = convertToBuffer; -//# sourceMappingURL=convertToBuffer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/util/build/index.js b/claude-code-source/node_modules/@aws-crypto/util/build/index.js deleted file mode 100644 index 94e1ca90..00000000 --- a/claude-code-source/node_modules/@aws-crypto/util/build/index.js +++ /dev/null @@ -1,14 +0,0 @@ -"use strict"; -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -Object.defineProperty(exports, "__esModule", { value: true }); -exports.uint32ArrayFrom = exports.numToUint8 = exports.isEmptyData = exports.convertToBuffer = void 0; -var convertToBuffer_1 = require("./convertToBuffer"); -Object.defineProperty(exports, "convertToBuffer", { enumerable: true, get: function () { return convertToBuffer_1.convertToBuffer; } }); -var isEmptyData_1 = require("./isEmptyData"); -Object.defineProperty(exports, "isEmptyData", { enumerable: true, get: function () { return isEmptyData_1.isEmptyData; } }); -var numToUint8_1 = require("./numToUint8"); -Object.defineProperty(exports, "numToUint8", { enumerable: true, get: function () { return numToUint8_1.numToUint8; } }); -var uint32ArrayFrom_1 = require("./uint32ArrayFrom"); -Object.defineProperty(exports, "uint32ArrayFrom", { enumerable: true, get: function () { return uint32ArrayFrom_1.uint32ArrayFrom; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/util/build/isEmptyData.js b/claude-code-source/node_modules/@aws-crypto/util/build/isEmptyData.js deleted file mode 100644 index 6af1e89e..00000000 --- a/claude-code-source/node_modules/@aws-crypto/util/build/isEmptyData.js +++ /dev/null @@ -1,13 +0,0 @@ -"use strict"; -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isEmptyData = void 0; -function isEmptyData(data) { - if (typeof data === "string") { - return data.length === 0; - } - return data.byteLength === 0; -} -exports.isEmptyData = isEmptyData; -//# sourceMappingURL=isEmptyData.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/util/build/numToUint8.js b/claude-code-source/node_modules/@aws-crypto/util/build/numToUint8.js deleted file mode 100644 index 2f070e10..00000000 --- a/claude-code-source/node_modules/@aws-crypto/util/build/numToUint8.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -Object.defineProperty(exports, "__esModule", { value: true }); -exports.numToUint8 = void 0; -function numToUint8(num) { - return new Uint8Array([ - (num & 0xff000000) >> 24, - (num & 0x00ff0000) >> 16, - (num & 0x0000ff00) >> 8, - num & 0x000000ff, - ]); -} -exports.numToUint8 = numToUint8; -//# sourceMappingURL=numToUint8.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-crypto/util/build/uint32ArrayFrom.js b/claude-code-source/node_modules/@aws-crypto/util/build/uint32ArrayFrom.js deleted file mode 100644 index 226cdc3d..00000000 --- a/claude-code-source/node_modules/@aws-crypto/util/build/uint32ArrayFrom.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -Object.defineProperty(exports, "__esModule", { value: true }); -exports.uint32ArrayFrom = void 0; -// IE 11 does not support Array.from, so we do it manually -function uint32ArrayFrom(a_lookUpTable) { - if (!Uint32Array.from) { - var return_array = new Uint32Array(a_lookUpTable.length); - var a_index = 0; - while (a_index < a_lookUpTable.length) { - return_array[a_index] = a_lookUpTable[a_index]; - a_index += 1; - } - return return_array; - } - return Uint32Array.from(a_lookUpTable); -} -exports.uint32ArrayFrom = uint32ArrayFrom; -//# sourceMappingURL=uint32ArrayFrom.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/auth/httpAuthSchemeProvider.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/auth/httpAuthSchemeProvider.js deleted file mode 100644 index 8f0cd2ea..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/auth/httpAuthSchemeProvider.js +++ /dev/null @@ -1,64 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/endpoint/endpointResolver.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/endpoint/endpointResolver.js deleted file mode 100644 index 7258a356..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/endpoint/endpointResolver.js +++ /dev/null @@ -1,18 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/endpoint/ruleset.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/endpoint/ruleset.js deleted file mode 100644 index cb5b4ac6..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/endpoint/ruleset.js +++ /dev/null @@ -1,7 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/index.js deleted file mode 100644 index f541fdbe..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/index.js +++ /dev/null @@ -1,2491 +0,0 @@ -'use strict'; - -var middlewareEventstream = require('@aws-sdk/middleware-eventstream'); -var middlewareHostHeader = require('@aws-sdk/middleware-host-header'); -var middlewareLogger = require('@aws-sdk/middleware-logger'); -var middlewareRecursionDetection = require('@aws-sdk/middleware-recursion-detection'); -var middlewareUserAgent = require('@aws-sdk/middleware-user-agent'); -var middlewareWebsocket = require('@aws-sdk/middleware-websocket'); -var configResolver = require('@smithy/config-resolver'); -var core = require('@smithy/core'); -var schema = require('@smithy/core/schema'); -var eventstreamSerdeConfigResolver = require('@smithy/eventstream-serde-config-resolver'); -var middlewareContentLength = require('@smithy/middleware-content-length'); -var middlewareEndpoint = require('@smithy/middleware-endpoint'); -var middlewareRetry = require('@smithy/middleware-retry'); -var smithyClient = require('@smithy/smithy-client'); -var httpAuthSchemeProvider = require('./auth/httpAuthSchemeProvider'); -var runtimeConfig = require('./runtimeConfig'); -var regionConfigResolver = require('@aws-sdk/region-config-resolver'); -var protocolHttp = require('@smithy/protocol-http'); - -const resolveClientEndpointParameters = (options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - defaultSigningName: "bedrock", - }); -}; -const commonParams = { - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, -}; - -const getHttpAuthExtensionConfiguration = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - let _token = runtimeConfig.token; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } - else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - }, - setToken(token) { - _token = token; - }, - token() { - return _token; - }, - }; -}; -const resolveHttpAuthRuntimeConfig = (config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials(), - token: config.token(), - }; -}; - -const resolveRuntimeExtensions = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig), smithyClient.getDefaultExtensionConfiguration(runtimeConfig), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); -}; - -class BedrockRuntimeClient extends smithyClient.Client { - config; - constructor(...[configuration]) { - const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters(_config_0); - const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1); - const _config_3 = middlewareRetry.resolveRetryConfig(_config_2); - const _config_4 = configResolver.resolveRegionConfig(_config_3); - const _config_5 = middlewareHostHeader.resolveHostHeaderConfig(_config_4); - const _config_6 = middlewareEndpoint.resolveEndpointConfig(_config_5); - const _config_7 = eventstreamSerdeConfigResolver.resolveEventStreamSerdeConfig(_config_6); - const _config_8 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_7); - const _config_9 = middlewareEventstream.resolveEventStreamConfig(_config_8); - const _config_10 = middlewareWebsocket.resolveWebSocketConfig(_config_9); - const _config_11 = resolveRuntimeExtensions(_config_10, configuration?.extensions || []); - this.config = _config_11; - this.middlewareStack.use(schema.getSchemaSerdePlugin(this.config)); - this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config)); - this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config)); - this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config)); - this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config)); - this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config)); - this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config)); - this.middlewareStack.use(core.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { - httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultBedrockRuntimeHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config) => new core.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials, - "smithy.api#httpBearerAuth": config.token, - }), - })); - this.middlewareStack.use(core.getHttpSigningPlugin(this.config)); - } - destroy() { - super.destroy(); - } -} - -let BedrockRuntimeServiceException$1 = class BedrockRuntimeServiceException extends smithyClient.ServiceException { - constructor(options) { - super(options); - Object.setPrototypeOf(this, BedrockRuntimeServiceException.prototype); - } -}; - -let AccessDeniedException$1 = class AccessDeniedException extends BedrockRuntimeServiceException$1 { - name = "AccessDeniedException"; - $fault = "client"; - constructor(opts) { - super({ - name: "AccessDeniedException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, AccessDeniedException.prototype); - } -}; -let InternalServerException$1 = class InternalServerException extends BedrockRuntimeServiceException$1 { - name = "InternalServerException"; - $fault = "server"; - constructor(opts) { - super({ - name: "InternalServerException", - $fault: "server", - ...opts, - }); - Object.setPrototypeOf(this, InternalServerException.prototype); - } -}; -let ThrottlingException$1 = class ThrottlingException extends BedrockRuntimeServiceException$1 { - name = "ThrottlingException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ThrottlingException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ThrottlingException.prototype); - } -}; -let ValidationException$1 = class ValidationException extends BedrockRuntimeServiceException$1 { - name = "ValidationException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ValidationException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ValidationException.prototype); - } -}; -let ConflictException$1 = class ConflictException extends BedrockRuntimeServiceException$1 { - name = "ConflictException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ConflictException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ConflictException.prototype); - } -}; -let ResourceNotFoundException$1 = class ResourceNotFoundException extends BedrockRuntimeServiceException$1 { - name = "ResourceNotFoundException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ResourceNotFoundException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ResourceNotFoundException.prototype); - } -}; -let ServiceQuotaExceededException$1 = class ServiceQuotaExceededException extends BedrockRuntimeServiceException$1 { - name = "ServiceQuotaExceededException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ServiceQuotaExceededException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ServiceQuotaExceededException.prototype); - } -}; -let ServiceUnavailableException$1 = class ServiceUnavailableException extends BedrockRuntimeServiceException$1 { - name = "ServiceUnavailableException"; - $fault = "server"; - constructor(opts) { - super({ - name: "ServiceUnavailableException", - $fault: "server", - ...opts, - }); - Object.setPrototypeOf(this, ServiceUnavailableException.prototype); - } -}; -let ModelErrorException$1 = class ModelErrorException extends BedrockRuntimeServiceException$1 { - name = "ModelErrorException"; - $fault = "client"; - originalStatusCode; - resourceName; - constructor(opts) { - super({ - name: "ModelErrorException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ModelErrorException.prototype); - this.originalStatusCode = opts.originalStatusCode; - this.resourceName = opts.resourceName; - } -}; -let ModelNotReadyException$1 = class ModelNotReadyException extends BedrockRuntimeServiceException$1 { - name = "ModelNotReadyException"; - $fault = "client"; - $retryable = {}; - constructor(opts) { - super({ - name: "ModelNotReadyException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ModelNotReadyException.prototype); - } -}; -let ModelTimeoutException$1 = class ModelTimeoutException extends BedrockRuntimeServiceException$1 { - name = "ModelTimeoutException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ModelTimeoutException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ModelTimeoutException.prototype); - } -}; -let ModelStreamErrorException$1 = class ModelStreamErrorException extends BedrockRuntimeServiceException$1 { - name = "ModelStreamErrorException"; - $fault = "client"; - originalStatusCode; - originalMessage; - constructor(opts) { - super({ - name: "ModelStreamErrorException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ModelStreamErrorException.prototype); - this.originalStatusCode = opts.originalStatusCode; - this.originalMessage = opts.originalMessage; - } -}; - -const _A = "Accept"; -const _ADE = "AccessDeniedException"; -const _AG = "ApplyGuardrail"; -const _AGR = "ApplyGuardrailRequest"; -const _AGRp = "ApplyGuardrailResponse"; -const _AIM = "AsyncInvokeMessage"; -const _AIODC = "AsyncInvokeOutputDataConfig"; -const _AIS = "AsyncInvokeSummary"; -const _AISODC = "AsyncInvokeS3OutputDataConfig"; -const _AISs = "AsyncInvokeSummaries"; -const _ATC = "AnyToolChoice"; -const _ATCu = "AutoToolChoice"; -const _B = "Body"; -const _BIPP = "BidirectionalInputPayloadPart"; -const _BOPP = "BidirectionalOutputPayloadPart"; -const _C = "Citation"; -const _CB = "ContentBlocks"; -const _CBD = "ContentBlockDelta"; -const _CBDE = "ContentBlockDeltaEvent"; -const _CBS = "ContentBlockStart"; -const _CBSE = "ContentBlockStartEvent"; -const _CBSEo = "ContentBlockStopEvent"; -const _CBo = "ContentBlock"; -const _CC = "CitationsConfig"; -const _CCB = "CitationsContentBlock"; -const _CD = "CitationsDelta"; -const _CE = "ConflictException"; -const _CGC = "CitationGeneratedContent"; -const _CGCL = "CitationGeneratedContentList"; -const _CL = "CitationLocation"; -const _CM = "ConverseMetrics"; -const _CO = "ConverseOutput"; -const _CPB = "CachePointBlock"; -const _CR = "ConverseRequest"; -const _CRo = "ConverseResponse"; -const _CS = "ConverseStream"; -const _CSC = "CitationSourceContent"; -const _CSCD = "CitationSourceContentDelta"; -const _CSCL = "CitationSourceContentList"; -const _CSCLD = "CitationSourceContentListDelta"; -const _CSM = "ConverseStreamMetrics"; -const _CSME = "ConverseStreamMetadataEvent"; -const _CSO = "ConverseStreamOutput"; -const _CSR = "ConverseStreamRequest"; -const _CSRo = "ConverseStreamResponse"; -const _CST = "ConverseStreamTrace"; -const _CT = "ConverseTrace"; -const _CTI = "CountTokensInput"; -const _CTR = "ConverseTokensRequest"; -const _CTRo = "CountTokensRequest"; -const _CTRou = "CountTokensResponse"; -const _CT_ = "Content-Type"; -const _CTo = "CountTokens"; -const _Ci = "Citations"; -const _Co = "Converse"; -const _DB = "DocumentBlock"; -const _DCB = "DocumentContentBlocks"; -const _DCBo = "DocumentContentBlock"; -const _DCL = "DocumentCharLocation"; -const _DCLo = "DocumentChunkLocation"; -const _DPL = "DocumentPageLocation"; -const _DS = "DocumentSource"; -const _GA = "GuardrailAssessment"; -const _GAI = "GetAsyncInvoke"; -const _GAIR = "GetAsyncInvokeRequest"; -const _GAIRe = "GetAsyncInvokeResponse"; -const _GAL = "GuardrailAssessmentList"; -const _GALM = "GuardrailAssessmentListMap"; -const _GAM = "GuardrailAssessmentMap"; -const _GARDSL = "GuardrailAutomatedReasoningDifferenceScenarioList"; -const _GARF = "GuardrailAutomatedReasoningFinding"; -const _GARFL = "GuardrailAutomatedReasoningFindingList"; -const _GARIF = "GuardrailAutomatedReasoningImpossibleFinding"; -const _GARIFu = "GuardrailAutomatedReasoningInvalidFinding"; -const _GARITR = "GuardrailAutomatedReasoningInputTextReference"; -const _GARITRL = "GuardrailAutomatedReasoningInputTextReferenceList"; -const _GARLW = "GuardrailAutomatedReasoningLogicWarning"; -const _GARNTF = "GuardrailAutomatedReasoningNoTranslationsFinding"; -const _GARPA = "GuardrailAutomatedReasoningPolicyAssessment"; -const _GARR = "GuardrailAutomatedReasoningRule"; -const _GARRL = "GuardrailAutomatedReasoningRuleList"; -const _GARS = "GuardrailAutomatedReasoningScenario"; -const _GARSF = "GuardrailAutomatedReasoningSatisfiableFinding"; -const _GARSL = "GuardrailAutomatedReasoningStatementList"; -const _GARSLC = "GuardrailAutomatedReasoningStatementLogicContent"; -const _GARSNLC = "GuardrailAutomatedReasoningStatementNaturalLanguageContent"; -const _GARSu = "GuardrailAutomatedReasoningStatement"; -const _GART = "GuardrailAutomatedReasoningTranslation"; -const _GARTAF = "GuardrailAutomatedReasoningTranslationAmbiguousFinding"; -const _GARTCF = "GuardrailAutomatedReasoningTooComplexFinding"; -const _GARTL = "GuardrailAutomatedReasoningTranslationList"; -const _GARTO = "GuardrailAutomatedReasoningTranslationOption"; -const _GARTOL = "GuardrailAutomatedReasoningTranslationOptionList"; -const _GARVF = "GuardrailAutomatedReasoningValidFinding"; -const _GC = "GuardrailConfiguration"; -const _GCB = "GuardrailContentBlock"; -const _GCBL = "GuardrailContentBlockList"; -const _GCCB = "GuardrailConverseContentBlock"; -const _GCF = "GuardrailContentFilter"; -const _GCFL = "GuardrailContentFilterList"; -const _GCGF = "GuardrailContextualGroundingFilter"; -const _GCGFu = "GuardrailContextualGroundingFilters"; -const _GCGPA = "GuardrailContextualGroundingPolicyAssessment"; -const _GCIB = "GuardrailConverseImageBlock"; -const _GCIS = "GuardrailConverseImageSource"; -const _GCPA = "GuardrailContentPolicyAssessment"; -const _GCTB = "GuardrailConverseTextBlock"; -const _GCW = "GuardrailCustomWord"; -const _GCWL = "GuardrailCustomWordList"; -const _GCu = "GuardrailCoverage"; -const _GIB = "GuardrailImageBlock"; -const _GIC = "GuardrailImageCoverage"; -const _GIM = "GuardrailInvocationMetrics"; -const _GIS = "GuardrailImageSource"; -const _GMW = "GuardrailManagedWord"; -const _GMWL = "GuardrailManagedWordList"; -const _GOC = "GuardrailOutputContent"; -const _GOCL = "GuardrailOutputContentList"; -const _GPEF = "GuardrailPiiEntityFilter"; -const _GPEFL = "GuardrailPiiEntityFilterList"; -const _GRF = "GuardrailRegexFilter"; -const _GRFL = "GuardrailRegexFilterList"; -const _GSC = "GuardrailStreamConfiguration"; -const _GSIPA = "GuardrailSensitiveInformationPolicyAssessment"; -const _GT = "GuardrailTopic"; -const _GTA = "GuardrailTraceAssessment"; -const _GTB = "GuardrailTextBlock"; -const _GTCC = "GuardrailTextCharactersCoverage"; -const _GTL = "GuardrailTopicList"; -const _GTPA = "GuardrailTopicPolicyAssessment"; -const _GU = "GuardrailUsage"; -const _GWPA = "GuardrailWordPolicyAssessment"; -const _IB = "ImageBlock"; -const _IC = "InferenceConfiguration"; -const _IM = "InvokeModel"; -const _IMR = "InvokeModelRequest"; -const _IMRn = "InvokeModelResponse"; -const _IMTR = "InvokeModelTokensRequest"; -const _IMWBS = "InvokeModelWithBidirectionalStream"; -const _IMWBSI = "InvokeModelWithBidirectionalStreamInput"; -const _IMWBSO = "InvokeModelWithBidirectionalStreamOutput"; -const _IMWBSR = "InvokeModelWithBidirectionalStreamRequest"; -const _IMWBSRn = "InvokeModelWithBidirectionalStreamResponse"; -const _IMWRS = "InvokeModelWithResponseStream"; -const _IMWRSR = "InvokeModelWithResponseStreamRequest"; -const _IMWRSRn = "InvokeModelWithResponseStreamResponse"; -const _IS = "ImageSource"; -const _ISE = "InternalServerException"; -const _LAI = "ListAsyncInvokes"; -const _LAIR = "ListAsyncInvokesRequest"; -const _LAIRi = "ListAsyncInvokesResponse"; -const _M = "Message"; -const _MEE = "ModelErrorException"; -const _MIP = "ModelInputPayload"; -const _MNRE = "ModelNotReadyException"; -const _MSE = "MessageStartEvent"; -const _MSEE = "ModelStreamErrorException"; -const _MSEe = "MessageStopEvent"; -const _MTE = "ModelTimeoutException"; -const _Me = "Messages"; -const _PB = "PartBody"; -const _PC = "PerformanceConfiguration"; -const _PP = "PayloadPart"; -const _PRT = "PromptRouterTrace"; -const _PVM = "PromptVariableMap"; -const _PVV = "PromptVariableValues"; -const _RCB = "ReasoningContentBlock"; -const _RCBD = "ReasoningContentBlockDelta"; -const _RM = "RequestMetadata"; -const _RNFE = "ResourceNotFoundException"; -const _RS = "ResponseStream"; -const _RTB = "ReasoningTextBlock"; -const _SAI = "StartAsyncInvoke"; -const _SAIR = "StartAsyncInvokeRequest"; -const _SAIRt = "StartAsyncInvokeResponse"; -const _SCB = "SystemContentBlocks"; -const _SCBy = "SystemContentBlock"; -const _SL = "S3Location"; -const _SQEE = "ServiceQuotaExceededException"; -const _SRB = "SearchResultBlock"; -const _SRCB = "SearchResultContentBlock"; -const _SRCBe = "SearchResultContentBlocks"; -const _SRL = "SearchResultLocation"; -const _ST = "ServiceTier"; -const _STC = "SpecificToolChoice"; -const _STy = "SystemTool"; -const _SUE = "ServiceUnavailableException"; -const _T = "Tag"; -const _TC = "ToolConfiguration"; -const _TCo = "ToolChoice"; -const _TE = "ThrottlingException"; -const _TIS = "ToolInputSchema"; -const _TL = "TagList"; -const _TRB = "ToolResultBlock"; -const _TRBD = "ToolResultBlocksDelta"; -const _TRBDo = "ToolResultBlockDelta"; -const _TRBS = "ToolResultBlockStart"; -const _TRCB = "ToolResultContentBlocks"; -const _TRCBo = "ToolResultContentBlock"; -const _TS = "ToolSpecification"; -const _TU = "TokenUsage"; -const _TUB = "ToolUseBlock"; -const _TUBD = "ToolUseBlockDelta"; -const _TUBS = "ToolUseBlockStart"; -const _To = "Tools"; -const _Too = "Tool"; -const _VB = "VideoBlock"; -const _VE = "ValidationException"; -const _VS = "VideoSource"; -const _WL = "WebLocation"; -const _XABA = "X-Amzn-Bedrock-Accept"; -const _XABCT = "X-Amzn-Bedrock-Content-Type"; -const _XABG = "X-Amzn-Bedrock-GuardrailIdentifier"; -const _XABG_ = "X-Amzn-Bedrock-GuardrailVersion"; -const _XABPL = "X-Amzn-Bedrock-PerformanceConfig-Latency"; -const _XABST = "X-Amzn-Bedrock-Service-Tier"; -const _XABT = "X-Amzn-Bedrock-Trace"; -const _a = "action"; -const _aIS = "asyncInvokeSummaries"; -const _aMRF = "additionalModelRequestFields"; -const _aMRFP = "additionalModelResponseFieldPaths"; -const _aMRFd = "additionalModelResponseFields"; -const _aR = "actionReason"; -const _aRP = "automatedReasoningPolicy"; -const _aRPU = "automatedReasoningPolicyUnits"; -const _aRPu = "automatedReasoningPolicies"; -const _ac = "accept"; -const _an = "any"; -const _as = "assessments"; -const _au = "auto"; -const _b = "bytes"; -const _bO = "bucketOwner"; -const _bo = "body"; -const _c = "client"; -const _cBD = "contentBlockDelta"; -const _cBI = "contentBlockIndex"; -const _cBS = "contentBlockStart"; -const _cBSo = "contentBlockStop"; -const _cC = "citationsContent"; -const _cFS = "claimsFalseScenario"; -const _cGP = "contextualGroundingPolicy"; -const _cGPU = "contextualGroundingPolicyUnits"; -const _cP = "contentPolicy"; -const _cPIU = "contentPolicyImageUnits"; -const _cPU = "contentPolicyUnits"; -const _cPa = "cachePoint"; -const _cR = "contradictingRules"; -const _cRIT = "cacheReadInputTokens"; -const _cRT = "clientRequestToken"; -const _cT = "contentType"; -const _cTS = "claimsTrueScenario"; -const _cW = "customWords"; -const _cWIT = "cacheWriteInputTokens"; -const _ch = "chunk"; -const _ci = "citations"; -const _cit = "citation"; -const _cl = "claims"; -const _co = "content"; -const _con = "context"; -const _conf = "confidence"; -const _conv = "converse"; -const _d = "delta"; -const _dC = "documentChar"; -const _dCo = "documentChunk"; -const _dI = "documentIndex"; -const _dP = "documentPage"; -const _dS = "differenceScenarios"; -const _de = "detected"; -const _des = "description"; -const _do = "domain"; -const _doc = "document"; -const _e = "error"; -const _eT = "endTime"; -const _en = "enabled"; -const _end = "end"; -const _f = "format"; -const _fM = "failureMessage"; -const _fS = "filterStrength"; -const _fi = "findings"; -const _fil = "filters"; -const _g = "guardrail"; -const _gC = "guardrailCoverage"; -const _gCu = "guardrailConfig"; -const _gCua = "guardContent"; -const _gI = "guardrailIdentifier"; -const _gPL = "guardrailProcessingLatency"; -const _gV = "guardrailVersion"; -const _gu = "guarded"; -const _h = "http"; -const _hE = "httpError"; -const _hH = "httpHeader"; -const _hQ = "httpQuery"; -const _i = "input"; -const _iA = "invocationArn"; -const _iAn = "inputAssessment"; -const _iC = "inferenceConfig"; -const _iM = "invocationMetrics"; -const _iMI = "invokedModelId"; -const _iMn = "invokeModel"; -const _iS = "inputSchema"; -const _iSE = "internalServerException"; -const _iT = "inputTokens"; -const _id = "identifier"; -const _im = "images"; -const _ima = "image"; -const _imp = "impossible"; -const _in = "invalid"; -const _j = "json"; -const _k = "key"; -const _kKI = "kmsKeyId"; -const _l = "location"; -const _lM = "latencyMs"; -const _lMT = "lastModifiedTime"; -const _lW = "logicWarning"; -const _la = "latency"; -const _lo = "logic"; -const _m = "message"; -const _mA = "modelArn"; -const _mI = "modelId"; -const _mIo = "modelInput"; -const _mO = "modelOutput"; -const _mR = "maxResults"; -const _mS = "messageStart"; -const _mSEE = "modelStreamErrorException"; -const _mSe = "messageStop"; -const _mT = "maxTokens"; -const _mTE = "modelTimeoutException"; -const _mWL = "managedWordLists"; -const _ma = "match"; -const _me = "messages"; -const _met = "metrics"; -const _meta = "metadata"; -const _n = "name"; -const _nL = "naturalLanguage"; -const _nT = "nextToken"; -const _nTo = "noTranslations"; -const _o = "outputs"; -const _oA = "outputAssessments"; -const _oDC = "outputDataConfig"; -const _oM = "originalMessage"; -const _oS = "outputScope"; -const _oSC = "originalStatusCode"; -const _oT = "outputTokens"; -const _op = "options"; -const _ou = "output"; -const _p = "premises"; -const _pC = "performanceConfig"; -const _pCL = "performanceConfigLatency"; -const _pE = "piiEntities"; -const _pR = "promptRouter"; -const _pV = "promptVariables"; -const _pVA = "policyVersionArn"; -const _q = "qualifiers"; -const _r = "regex"; -const _rC = "reasoningContent"; -const _rCe = "redactedContent"; -const _rM = "requestMetadata"; -const _rN = "resourceName"; -const _rT = "reasoningText"; -const _re = "regexes"; -const _ro = "role"; -const _s = "source"; -const _sB = "sortBy"; -const _sC = "sourceContent"; -const _sE = "statusEquals"; -const _sIP = "sensitiveInformationPolicy"; -const _sIPFU = "sensitiveInformationPolicyFreeUnits"; -const _sIPU = "sensitiveInformationPolicyUnits"; -const _sL = "s3Location"; -const _sO = "sortOrder"; -const _sODC = "s3OutputDataConfig"; -const _sPM = "streamProcessingMode"; -const _sR = "stopReason"; -const _sRI = "searchResultIndex"; -const _sRL = "searchResultLocation"; -const _sRe = "searchResult"; -const _sRu = "supportingRules"; -const _sS = "stopSequences"; -const _sT = "submitTime"; -const _sTA = "submitTimeAfter"; -const _sTB = "submitTimeBefore"; -const _sTe = "serviceTier"; -const _sTy = "systemTool"; -const _sU = "s3Uri"; -const _sUE = "serviceUnavailableException"; -const _sa = "satisfiable"; -const _sc = "score"; -const _se = "server"; -const _si = "signature"; -const _sm = "smithy.ts.sdk.synthetic.com.amazonaws.bedrockruntime"; -const _st = "status"; -const _sta = "start"; -const _stat = "statements"; -const _str = "stream"; -const _stre = "streaming"; -const _sy = "system"; -const _t = "type"; -const _tA = "translationAmbiguous"; -const _tC = "toolConfig"; -const _tCe = "textCharacters"; -const _tCo = "toolChoice"; -const _tCoo = "tooComplex"; -const _tE = "throttlingException"; -const _tP = "topicPolicy"; -const _tPU = "topicPolicyUnits"; -const _tPo = "topP"; -const _tR = "toolResult"; -const _tS = "toolSpec"; -const _tT = "totalTokens"; -const _tU = "toolUse"; -const _tUI = "toolUseId"; -const _ta = "tags"; -const _te = "text"; -const _tem = "temperature"; -const _th = "threshold"; -const _ti = "title"; -const _to = "total"; -const _too = "tools"; -const _tool = "tool"; -const _top = "topics"; -const _tr = "trace"; -const _tra = "translation"; -const _tran = "translations"; -const _u = "usage"; -const _uC = "untranslatedClaims"; -const _uP = "untranslatedPremises"; -const _ur = "uri"; -const _url = "url"; -const _v = "value"; -const _vE = "validationException"; -const _va = "valid"; -const _vi = "video"; -const _w = "web"; -const _wP = "wordPolicy"; -const _wPU = "wordPolicyUnits"; -const n0 = "com.amazonaws.bedrockruntime"; -var AsyncInvokeMessage = [0, n0, _AIM, 8, 0]; -var Body = [0, n0, _B, 8, 21]; -var GuardrailAutomatedReasoningStatementLogicContent = [0, n0, _GARSLC, 8, 0]; -var GuardrailAutomatedReasoningStatementNaturalLanguageContent = [0, n0, _GARSNLC, 8, 0]; -var ModelInputPayload = [0, n0, _MIP, 8, 15]; -var PartBody = [0, n0, _PB, 8, 21]; -var AccessDeniedException = [ - -3, - n0, - _ADE, - { - [_e]: _c, - [_hE]: 403, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(AccessDeniedException, AccessDeniedException$1); -var AnyToolChoice = [3, n0, _ATC, 0, [], []]; -var ApplyGuardrailRequest = [ - 3, - n0, - _AGR, - 0, - [_gI, _gV, _s, _co, _oS], - [[0, 1], [0, 1], 0, [() => GuardrailContentBlockList, 0], 0], -]; -var ApplyGuardrailResponse = [ - 3, - n0, - _AGRp, - 0, - [_u, _a, _aR, _o, _as, _gC], - [ - () => GuardrailUsage, - 0, - 0, - () => GuardrailOutputContentList, - [() => GuardrailAssessmentList, 0], - () => GuardrailCoverage, - ], -]; -var AsyncInvokeS3OutputDataConfig = [3, n0, _AISODC, 0, [_sU, _kKI, _bO], [0, 0, 0]]; -var AsyncInvokeSummary = [ - 3, - n0, - _AIS, - 0, - [_iA, _mA, _cRT, _st, _fM, _sT, _lMT, _eT, _oDC], - [0, 0, 0, 0, [() => AsyncInvokeMessage, 0], 5, 5, 5, () => AsyncInvokeOutputDataConfig], -]; -var AutoToolChoice = [3, n0, _ATCu, 0, [], []]; -var BidirectionalInputPayloadPart = [3, n0, _BIPP, 8, [_b], [[() => PartBody, 0]]]; -var BidirectionalOutputPayloadPart = [3, n0, _BOPP, 8, [_b], [[() => PartBody, 0]]]; -var CachePointBlock = [3, n0, _CPB, 0, [_t], [0]]; -var Citation = [ - 3, - n0, - _C, - 0, - [_ti, _s, _sC, _l], - [0, 0, () => CitationSourceContentList, () => CitationLocation], -]; -var CitationsConfig = [3, n0, _CC, 0, [_en], [2]]; -var CitationsContentBlock = [ - 3, - n0, - _CCB, - 0, - [_co, _ci], - [() => CitationGeneratedContentList, () => Citations], -]; -var CitationsDelta = [ - 3, - n0, - _CD, - 0, - [_ti, _s, _sC, _l], - [0, 0, () => CitationSourceContentListDelta, () => CitationLocation], -]; -var CitationSourceContentDelta = [3, n0, _CSCD, 0, [_te], [0]]; -var ConflictException = [ - -3, - n0, - _CE, - { - [_e]: _c, - [_hE]: 400, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ConflictException, ConflictException$1); -var ContentBlockDeltaEvent = [ - 3, - n0, - _CBDE, - 0, - [_d, _cBI], - [[() => ContentBlockDelta, 0], 1], -]; -var ContentBlockStartEvent = [ - 3, - n0, - _CBSE, - 0, - [_sta, _cBI], - [() => ContentBlockStart, 1], -]; -var ContentBlockStopEvent = [3, n0, _CBSEo, 0, [_cBI], [1]]; -var ConverseMetrics = [3, n0, _CM, 0, [_lM], [1]]; -var ConverseRequest = [ - 3, - n0, - _CR, - 0, - [_mI, _me, _sy, _iC, _tC, _gCu, _aMRF, _pV, _aMRFP, _rM, _pC, _sTe], - [ - [0, 1], - [() => Messages, 0], - [() => SystemContentBlocks, 0], - () => InferenceConfiguration, - () => ToolConfiguration, - () => GuardrailConfiguration, - 15, - [() => PromptVariableMap, 0], - 64 | 0, - [() => RequestMetadata, 0], - () => PerformanceConfiguration, - () => ServiceTier, - ], -]; -var ConverseResponse = [ - 3, - n0, - _CRo, - 0, - [_ou, _sR, _u, _met, _aMRFd, _tr, _pC, _sTe], - [ - [() => ConverseOutput, 0], - 0, - () => TokenUsage, - () => ConverseMetrics, - 15, - [() => ConverseTrace, 0], - () => PerformanceConfiguration, - () => ServiceTier, - ], -]; -var ConverseStreamMetadataEvent = [ - 3, - n0, - _CSME, - 0, - [_u, _met, _tr, _pC, _sTe], - [ - () => TokenUsage, - () => ConverseStreamMetrics, - [() => ConverseStreamTrace, 0], - () => PerformanceConfiguration, - () => ServiceTier, - ], -]; -var ConverseStreamMetrics = [3, n0, _CSM, 0, [_lM], [1]]; -var ConverseStreamRequest = [ - 3, - n0, - _CSR, - 0, - [_mI, _me, _sy, _iC, _tC, _gCu, _aMRF, _pV, _aMRFP, _rM, _pC, _sTe], - [ - [0, 1], - [() => Messages, 0], - [() => SystemContentBlocks, 0], - () => InferenceConfiguration, - () => ToolConfiguration, - () => GuardrailStreamConfiguration, - 15, - [() => PromptVariableMap, 0], - 64 | 0, - [() => RequestMetadata, 0], - () => PerformanceConfiguration, - () => ServiceTier, - ], -]; -var ConverseStreamResponse = [ - 3, - n0, - _CSRo, - 0, - [_str], - [[() => ConverseStreamOutput, 16]], -]; -var ConverseStreamTrace = [ - 3, - n0, - _CST, - 0, - [_g, _pR], - [[() => GuardrailTraceAssessment, 0], () => PromptRouterTrace], -]; -var ConverseTokensRequest = [ - 3, - n0, - _CTR, - 0, - [_me, _sy, _tC, _aMRF], - [[() => Messages, 0], [() => SystemContentBlocks, 0], () => ToolConfiguration, 15], -]; -var ConverseTrace = [ - 3, - n0, - _CT, - 0, - [_g, _pR], - [[() => GuardrailTraceAssessment, 0], () => PromptRouterTrace], -]; -var CountTokensRequest = [ - 3, - n0, - _CTRo, - 0, - [_mI, _i], - [ - [0, 1], - [() => CountTokensInput, 0], - ], -]; -var CountTokensResponse = [3, n0, _CTRou, 0, [_iT], [1]]; -var DocumentBlock = [ - 3, - n0, - _DB, - 0, - [_f, _n, _s, _con, _ci], - [0, 0, () => DocumentSource, 0, () => CitationsConfig], -]; -var DocumentCharLocation = [3, n0, _DCL, 0, [_dI, _sta, _end], [1, 1, 1]]; -var DocumentChunkLocation = [3, n0, _DCLo, 0, [_dI, _sta, _end], [1, 1, 1]]; -var DocumentPageLocation = [3, n0, _DPL, 0, [_dI, _sta, _end], [1, 1, 1]]; -var GetAsyncInvokeRequest = [3, n0, _GAIR, 0, [_iA], [[0, 1]]]; -var GetAsyncInvokeResponse = [ - 3, - n0, - _GAIRe, - 0, - [_iA, _mA, _cRT, _st, _fM, _sT, _lMT, _eT, _oDC], - [0, 0, 0, 0, [() => AsyncInvokeMessage, 0], 5, 5, 5, () => AsyncInvokeOutputDataConfig], -]; -var GuardrailAssessment = [ - 3, - n0, - _GA, - 0, - [_tP, _cP, _wP, _sIP, _cGP, _aRP, _iM], - [ - () => GuardrailTopicPolicyAssessment, - () => GuardrailContentPolicyAssessment, - () => GuardrailWordPolicyAssessment, - () => GuardrailSensitiveInformationPolicyAssessment, - () => GuardrailContextualGroundingPolicyAssessment, - [() => GuardrailAutomatedReasoningPolicyAssessment, 0], - () => GuardrailInvocationMetrics, - ], -]; -var GuardrailAutomatedReasoningImpossibleFinding = [ - 3, - n0, - _GARIF, - 0, - [_tra, _cR, _lW], - [ - [() => GuardrailAutomatedReasoningTranslation, 0], - () => GuardrailAutomatedReasoningRuleList, - [() => GuardrailAutomatedReasoningLogicWarning, 0], - ], -]; -var GuardrailAutomatedReasoningInputTextReference = [ - 3, - n0, - _GARITR, - 0, - [_te], - [[() => GuardrailAutomatedReasoningStatementNaturalLanguageContent, 0]], -]; -var GuardrailAutomatedReasoningInvalidFinding = [ - 3, - n0, - _GARIFu, - 0, - [_tra, _cR, _lW], - [ - [() => GuardrailAutomatedReasoningTranslation, 0], - () => GuardrailAutomatedReasoningRuleList, - [() => GuardrailAutomatedReasoningLogicWarning, 0], - ], -]; -var GuardrailAutomatedReasoningLogicWarning = [ - 3, - n0, - _GARLW, - 0, - [_t, _p, _cl], - [0, [() => GuardrailAutomatedReasoningStatementList, 0], [() => GuardrailAutomatedReasoningStatementList, 0]], -]; -var GuardrailAutomatedReasoningNoTranslationsFinding = [3, n0, _GARNTF, 0, [], []]; -var GuardrailAutomatedReasoningPolicyAssessment = [ - 3, - n0, - _GARPA, - 0, - [_fi], - [[() => GuardrailAutomatedReasoningFindingList, 0]], -]; -var GuardrailAutomatedReasoningRule = [3, n0, _GARR, 0, [_id, _pVA], [0, 0]]; -var GuardrailAutomatedReasoningSatisfiableFinding = [ - 3, - n0, - _GARSF, - 0, - [_tra, _cTS, _cFS, _lW], - [ - [() => GuardrailAutomatedReasoningTranslation, 0], - [() => GuardrailAutomatedReasoningScenario, 0], - [() => GuardrailAutomatedReasoningScenario, 0], - [() => GuardrailAutomatedReasoningLogicWarning, 0], - ], -]; -var GuardrailAutomatedReasoningScenario = [ - 3, - n0, - _GARS, - 0, - [_stat], - [[() => GuardrailAutomatedReasoningStatementList, 0]], -]; -var GuardrailAutomatedReasoningStatement = [ - 3, - n0, - _GARSu, - 0, - [_lo, _nL], - [ - [() => GuardrailAutomatedReasoningStatementLogicContent, 0], - [() => GuardrailAutomatedReasoningStatementNaturalLanguageContent, 0], - ], -]; -var GuardrailAutomatedReasoningTooComplexFinding = [3, n0, _GARTCF, 0, [], []]; -var GuardrailAutomatedReasoningTranslation = [ - 3, - n0, - _GART, - 0, - [_p, _cl, _uP, _uC, _conf], - [ - [() => GuardrailAutomatedReasoningStatementList, 0], - [() => GuardrailAutomatedReasoningStatementList, 0], - [() => GuardrailAutomatedReasoningInputTextReferenceList, 0], - [() => GuardrailAutomatedReasoningInputTextReferenceList, 0], - 1, - ], -]; -var GuardrailAutomatedReasoningTranslationAmbiguousFinding = [ - 3, - n0, - _GARTAF, - 0, - [_op, _dS], - [ - [() => GuardrailAutomatedReasoningTranslationOptionList, 0], - [() => GuardrailAutomatedReasoningDifferenceScenarioList, 0], - ], -]; -var GuardrailAutomatedReasoningTranslationOption = [ - 3, - n0, - _GARTO, - 0, - [_tran], - [[() => GuardrailAutomatedReasoningTranslationList, 0]], -]; -var GuardrailAutomatedReasoningValidFinding = [ - 3, - n0, - _GARVF, - 0, - [_tra, _cTS, _sRu, _lW], - [ - [() => GuardrailAutomatedReasoningTranslation, 0], - [() => GuardrailAutomatedReasoningScenario, 0], - () => GuardrailAutomatedReasoningRuleList, - [() => GuardrailAutomatedReasoningLogicWarning, 0], - ], -]; -var GuardrailConfiguration = [3, n0, _GC, 0, [_gI, _gV, _tr], [0, 0, 0]]; -var GuardrailContentFilter = [3, n0, _GCF, 0, [_t, _conf, _fS, _a, _de], [0, 0, 0, 0, 2]]; -var GuardrailContentPolicyAssessment = [ - 3, - n0, - _GCPA, - 0, - [_fil], - [() => GuardrailContentFilterList], -]; -var GuardrailContextualGroundingFilter = [ - 3, - n0, - _GCGF, - 0, - [_t, _th, _sc, _a, _de], - [0, 1, 1, 0, 2], -]; -var GuardrailContextualGroundingPolicyAssessment = [ - 3, - n0, - _GCGPA, - 0, - [_fil], - [() => GuardrailContextualGroundingFilters], -]; -var GuardrailConverseImageBlock = [ - 3, - n0, - _GCIB, - 8, - [_f, _s], - [0, [() => GuardrailConverseImageSource, 0]], -]; -var GuardrailConverseTextBlock = [3, n0, _GCTB, 0, [_te, _q], [0, 64 | 0]]; -var GuardrailCoverage = [ - 3, - n0, - _GCu, - 0, - [_tCe, _im], - [() => GuardrailTextCharactersCoverage, () => GuardrailImageCoverage], -]; -var GuardrailCustomWord = [3, n0, _GCW, 0, [_ma, _a, _de], [0, 0, 2]]; -var GuardrailImageBlock = [ - 3, - n0, - _GIB, - 8, - [_f, _s], - [0, [() => GuardrailImageSource, 0]], -]; -var GuardrailImageCoverage = [3, n0, _GIC, 0, [_gu, _to], [1, 1]]; -var GuardrailInvocationMetrics = [ - 3, - n0, - _GIM, - 0, - [_gPL, _u, _gC], - [1, () => GuardrailUsage, () => GuardrailCoverage], -]; -var GuardrailManagedWord = [3, n0, _GMW, 0, [_ma, _t, _a, _de], [0, 0, 0, 2]]; -var GuardrailOutputContent = [3, n0, _GOC, 0, [_te], [0]]; -var GuardrailPiiEntityFilter = [3, n0, _GPEF, 0, [_ma, _t, _a, _de], [0, 0, 0, 2]]; -var GuardrailRegexFilter = [3, n0, _GRF, 0, [_n, _ma, _r, _a, _de], [0, 0, 0, 0, 2]]; -var GuardrailSensitiveInformationPolicyAssessment = [ - 3, - n0, - _GSIPA, - 0, - [_pE, _re], - [() => GuardrailPiiEntityFilterList, () => GuardrailRegexFilterList], -]; -var GuardrailStreamConfiguration = [3, n0, _GSC, 0, [_gI, _gV, _tr, _sPM], [0, 0, 0, 0]]; -var GuardrailTextBlock = [3, n0, _GTB, 0, [_te, _q], [0, 64 | 0]]; -var GuardrailTextCharactersCoverage = [3, n0, _GTCC, 0, [_gu, _to], [1, 1]]; -var GuardrailTopic = [3, n0, _GT, 0, [_n, _t, _a, _de], [0, 0, 0, 2]]; -var GuardrailTopicPolicyAssessment = [ - 3, - n0, - _GTPA, - 0, - [_top], - [() => GuardrailTopicList], -]; -var GuardrailTraceAssessment = [ - 3, - n0, - _GTA, - 0, - [_mO, _iAn, _oA, _aR], - [64 | 0, [() => GuardrailAssessmentMap, 0], [() => GuardrailAssessmentListMap, 0], 0], -]; -var GuardrailUsage = [ - 3, - n0, - _GU, - 0, - [_tPU, _cPU, _wPU, _sIPU, _sIPFU, _cGPU, _cPIU, _aRPU, _aRPu], - [1, 1, 1, 1, 1, 1, 1, 1, 1], -]; -var GuardrailWordPolicyAssessment = [ - 3, - n0, - _GWPA, - 0, - [_cW, _mWL], - [() => GuardrailCustomWordList, () => GuardrailManagedWordList], -]; -var ImageBlock = [3, n0, _IB, 0, [_f, _s], [0, () => ImageSource]]; -var InferenceConfiguration = [3, n0, _IC, 0, [_mT, _tem, _tPo, _sS], [1, 1, 1, 64 | 0]]; -var InternalServerException = [ - -3, - n0, - _ISE, - { - [_e]: _se, - [_hE]: 500, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(InternalServerException, InternalServerException$1); -var InvokeModelRequest = [ - 3, - n0, - _IMR, - 0, - [_bo, _cT, _ac, _mI, _tr, _gI, _gV, _pCL, _sTe], - [ - [() => Body, 16], - [ - 0, - { - [_hH]: _CT_, - }, - ], - [ - 0, - { - [_hH]: _A, - }, - ], - [0, 1], - [ - 0, - { - [_hH]: _XABT, - }, - ], - [ - 0, - { - [_hH]: _XABG, - }, - ], - [ - 0, - { - [_hH]: _XABG_, - }, - ], - [ - 0, - { - [_hH]: _XABPL, - }, - ], - [ - 0, - { - [_hH]: _XABST, - }, - ], - ], -]; -var InvokeModelResponse = [ - 3, - n0, - _IMRn, - 0, - [_bo, _cT, _pCL, _sTe], - [ - [() => Body, 16], - [ - 0, - { - [_hH]: _CT_, - }, - ], - [ - 0, - { - [_hH]: _XABPL, - }, - ], - [ - 0, - { - [_hH]: _XABST, - }, - ], - ], -]; -var InvokeModelTokensRequest = [3, n0, _IMTR, 0, [_bo], [[() => Body, 0]]]; -var InvokeModelWithBidirectionalStreamRequest = [ - 3, - n0, - _IMWBSR, - 0, - [_mI, _bo], - [ - [0, 1], - [() => InvokeModelWithBidirectionalStreamInput, 16], - ], -]; -var InvokeModelWithBidirectionalStreamResponse = [ - 3, - n0, - _IMWBSRn, - 0, - [_bo], - [[() => InvokeModelWithBidirectionalStreamOutput, 16]], -]; -var InvokeModelWithResponseStreamRequest = [ - 3, - n0, - _IMWRSR, - 0, - [_bo, _cT, _ac, _mI, _tr, _gI, _gV, _pCL, _sTe], - [ - [() => Body, 16], - [ - 0, - { - [_hH]: _CT_, - }, - ], - [ - 0, - { - [_hH]: _XABA, - }, - ], - [0, 1], - [ - 0, - { - [_hH]: _XABT, - }, - ], - [ - 0, - { - [_hH]: _XABG, - }, - ], - [ - 0, - { - [_hH]: _XABG_, - }, - ], - [ - 0, - { - [_hH]: _XABPL, - }, - ], - [ - 0, - { - [_hH]: _XABST, - }, - ], - ], -]; -var InvokeModelWithResponseStreamResponse = [ - 3, - n0, - _IMWRSRn, - 0, - [_bo, _cT, _pCL, _sTe], - [ - [() => ResponseStream, 16], - [ - 0, - { - [_hH]: _XABCT, - }, - ], - [ - 0, - { - [_hH]: _XABPL, - }, - ], - [ - 0, - { - [_hH]: _XABST, - }, - ], - ], -]; -var ListAsyncInvokesRequest = [ - 3, - n0, - _LAIR, - 0, - [_sTA, _sTB, _sE, _mR, _nT, _sB, _sO], - [ - [ - 5, - { - [_hQ]: _sTA, - }, - ], - [ - 5, - { - [_hQ]: _sTB, - }, - ], - [ - 0, - { - [_hQ]: _sE, - }, - ], - [ - 1, - { - [_hQ]: _mR, - }, - ], - [ - 0, - { - [_hQ]: _nT, - }, - ], - [ - 0, - { - [_hQ]: _sB, - }, - ], - [ - 0, - { - [_hQ]: _sO, - }, - ], - ], -]; -var ListAsyncInvokesResponse = [ - 3, - n0, - _LAIRi, - 0, - [_nT, _aIS], - [0, [() => AsyncInvokeSummaries, 0]], -]; -var Message = [3, n0, _M, 0, [_ro, _co], [0, [() => ContentBlocks, 0]]]; -var MessageStartEvent = [3, n0, _MSE, 0, [_ro], [0]]; -var MessageStopEvent = [3, n0, _MSEe, 0, [_sR, _aMRFd], [0, 15]]; -var ModelErrorException = [ - -3, - n0, - _MEE, - { - [_e]: _c, - [_hE]: 424, - }, - [_m, _oSC, _rN], - [0, 1, 0], -]; -schema.TypeRegistry.for(n0).registerError(ModelErrorException, ModelErrorException$1); -var ModelNotReadyException = [ - -3, - n0, - _MNRE, - { - [_e]: _c, - [_hE]: 429, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ModelNotReadyException, ModelNotReadyException$1); -var ModelStreamErrorException = [ - -3, - n0, - _MSEE, - { - [_e]: _c, - [_hE]: 424, - }, - [_m, _oSC, _oM], - [0, 1, 0], -]; -schema.TypeRegistry.for(n0).registerError(ModelStreamErrorException, ModelStreamErrorException$1); -var ModelTimeoutException = [ - -3, - n0, - _MTE, - { - [_e]: _c, - [_hE]: 408, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ModelTimeoutException, ModelTimeoutException$1); -var PayloadPart = [3, n0, _PP, 8, [_b], [[() => PartBody, 0]]]; -var PerformanceConfiguration = [3, n0, _PC, 0, [_la], [0]]; -var PromptRouterTrace = [3, n0, _PRT, 0, [_iMI], [0]]; -var ReasoningTextBlock = [3, n0, _RTB, 8, [_te, _si], [0, 0]]; -var ResourceNotFoundException = [ - -3, - n0, - _RNFE, - { - [_e]: _c, - [_hE]: 404, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ResourceNotFoundException, ResourceNotFoundException$1); -var S3Location = [3, n0, _SL, 0, [_ur, _bO], [0, 0]]; -var SearchResultBlock = [ - 3, - n0, - _SRB, - 0, - [_s, _ti, _co, _ci], - [0, 0, () => SearchResultContentBlocks, () => CitationsConfig], -]; -var SearchResultContentBlock = [3, n0, _SRCB, 0, [_te], [0]]; -var SearchResultLocation = [3, n0, _SRL, 0, [_sRI, _sta, _end], [1, 1, 1]]; -var ServiceQuotaExceededException = [ - -3, - n0, - _SQEE, - { - [_e]: _c, - [_hE]: 400, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ServiceQuotaExceededException, ServiceQuotaExceededException$1); -var ServiceTier = [3, n0, _ST, 0, [_t], [0]]; -var ServiceUnavailableException = [ - -3, - n0, - _SUE, - { - [_e]: _se, - [_hE]: 503, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ServiceUnavailableException, ServiceUnavailableException$1); -var SpecificToolChoice = [3, n0, _STC, 0, [_n], [0]]; -var StartAsyncInvokeRequest = [ - 3, - n0, - _SAIR, - 0, - [_cRT, _mI, _mIo, _oDC, _ta], - [[0, 4], 0, [() => ModelInputPayload, 0], () => AsyncInvokeOutputDataConfig, () => TagList], -]; -var StartAsyncInvokeResponse = [3, n0, _SAIRt, 0, [_iA], [0]]; -var SystemTool = [3, n0, _STy, 0, [_n], [0]]; -var Tag = [3, n0, _T, 0, [_k, _v], [0, 0]]; -var ThrottlingException = [ - -3, - n0, - _TE, - { - [_e]: _c, - [_hE]: 429, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ThrottlingException, ThrottlingException$1); -var TokenUsage = [3, n0, _TU, 0, [_iT, _oT, _tT, _cRIT, _cWIT], [1, 1, 1, 1, 1]]; -var ToolConfiguration = [3, n0, _TC, 0, [_too, _tCo], [() => Tools, () => ToolChoice]]; -var ToolResultBlock = [ - 3, - n0, - _TRB, - 0, - [_tUI, _co, _st, _t], - [0, () => ToolResultContentBlocks, 0, 0], -]; -var ToolResultBlockStart = [3, n0, _TRBS, 0, [_tUI, _t, _st], [0, 0, 0]]; -var ToolSpecification = [3, n0, _TS, 0, [_n, _des, _iS], [0, 0, () => ToolInputSchema]]; -var ToolUseBlock = [3, n0, _TUB, 0, [_tUI, _n, _i, _t], [0, 0, 15, 0]]; -var ToolUseBlockDelta = [3, n0, _TUBD, 0, [_i], [0]]; -var ToolUseBlockStart = [3, n0, _TUBS, 0, [_tUI, _n, _t], [0, 0, 0]]; -var ValidationException = [ - -3, - n0, - _VE, - { - [_e]: _c, - [_hE]: 400, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ValidationException, ValidationException$1); -var VideoBlock = [3, n0, _VB, 0, [_f, _s], [0, () => VideoSource]]; -var WebLocation = [3, n0, _WL, 0, [_url, _do], [0, 0]]; -var BedrockRuntimeServiceException = [-3, _sm, "BedrockRuntimeServiceException", 0, [], []]; -schema.TypeRegistry.for(_sm).registerError(BedrockRuntimeServiceException, BedrockRuntimeServiceException$1); -var AsyncInvokeSummaries = [1, n0, _AISs, 0, [() => AsyncInvokeSummary, 0]]; -var CitationGeneratedContentList = [1, n0, _CGCL, 0, () => CitationGeneratedContent]; -var Citations = [1, n0, _Ci, 0, () => Citation]; -var CitationSourceContentList = [1, n0, _CSCL, 0, () => CitationSourceContent]; -var CitationSourceContentListDelta = [1, n0, _CSCLD, 0, () => CitationSourceContentDelta]; -var ContentBlocks = [1, n0, _CB, 0, [() => ContentBlock, 0]]; -var DocumentContentBlocks = [1, n0, _DCB, 0, () => DocumentContentBlock]; -var GuardrailAssessmentList = [1, n0, _GAL, 0, [() => GuardrailAssessment, 0]]; -var GuardrailAutomatedReasoningDifferenceScenarioList = [ - 1, - n0, - _GARDSL, - 0, - [() => GuardrailAutomatedReasoningScenario, 0], -]; -var GuardrailAutomatedReasoningFindingList = [ - 1, - n0, - _GARFL, - 0, - [() => GuardrailAutomatedReasoningFinding, 0], -]; -var GuardrailAutomatedReasoningInputTextReferenceList = [ - 1, - n0, - _GARITRL, - 0, - [() => GuardrailAutomatedReasoningInputTextReference, 0], -]; -var GuardrailAutomatedReasoningRuleList = [ - 1, - n0, - _GARRL, - 0, - () => GuardrailAutomatedReasoningRule, -]; -var GuardrailAutomatedReasoningStatementList = [ - 1, - n0, - _GARSL, - 0, - [() => GuardrailAutomatedReasoningStatement, 0], -]; -var GuardrailAutomatedReasoningTranslationList = [ - 1, - n0, - _GARTL, - 0, - [() => GuardrailAutomatedReasoningTranslation, 0], -]; -var GuardrailAutomatedReasoningTranslationOptionList = [ - 1, - n0, - _GARTOL, - 0, - [() => GuardrailAutomatedReasoningTranslationOption, 0], -]; -var GuardrailContentBlockList = [1, n0, _GCBL, 0, [() => GuardrailContentBlock, 0]]; -var GuardrailContentFilterList = [1, n0, _GCFL, 0, () => GuardrailContentFilter]; -var GuardrailContextualGroundingFilters = [ - 1, - n0, - _GCGFu, - 0, - () => GuardrailContextualGroundingFilter, -]; -var GuardrailCustomWordList = [1, n0, _GCWL, 0, () => GuardrailCustomWord]; -var GuardrailManagedWordList = [1, n0, _GMWL, 0, () => GuardrailManagedWord]; -var GuardrailOutputContentList = [1, n0, _GOCL, 0, () => GuardrailOutputContent]; -var GuardrailPiiEntityFilterList = [1, n0, _GPEFL, 0, () => GuardrailPiiEntityFilter]; -var GuardrailRegexFilterList = [1, n0, _GRFL, 0, () => GuardrailRegexFilter]; -var GuardrailTopicList = [1, n0, _GTL, 0, () => GuardrailTopic]; -var Messages = [1, n0, _Me, 0, [() => Message, 0]]; -var SearchResultContentBlocks = [1, n0, _SRCBe, 0, () => SearchResultContentBlock]; -var SystemContentBlocks = [1, n0, _SCB, 0, [() => SystemContentBlock, 0]]; -var TagList = [1, n0, _TL, 0, () => Tag]; -var ToolResultBlocksDelta = [1, n0, _TRBD, 0, () => ToolResultBlockDelta]; -var ToolResultContentBlocks = [1, n0, _TRCB, 0, () => ToolResultContentBlock]; -var Tools = [1, n0, _To, 0, () => Tool]; -var GuardrailAssessmentListMap = [2, n0, _GALM, 0, [0, 0], [() => GuardrailAssessmentList, 0]]; -var GuardrailAssessmentMap = [2, n0, _GAM, 0, [0, 0], [() => GuardrailAssessment, 0]]; -var PromptVariableMap = [2, n0, _PVM, 8, 0, () => PromptVariableValues]; -var RequestMetadata = [2, n0, _RM, 8, 0, 0]; -var AsyncInvokeOutputDataConfig = [ - 3, - n0, - _AIODC, - 0, - [_sODC], - [() => AsyncInvokeS3OutputDataConfig], -]; -var CitationGeneratedContent = [3, n0, _CGC, 0, [_te], [0]]; -var CitationLocation = [ - 3, - n0, - _CL, - 0, - [_w, _dC, _dP, _dCo, _sRL], - [ - () => WebLocation, - () => DocumentCharLocation, - () => DocumentPageLocation, - () => DocumentChunkLocation, - () => SearchResultLocation, - ], -]; -var CitationSourceContent = [3, n0, _CSC, 0, [_te], [0]]; -var ContentBlock = [ - 3, - n0, - _CBo, - 0, - [_te, _ima, _doc, _vi, _tU, _tR, _gCua, _cPa, _rC, _cC, _sRe], - [ - 0, - () => ImageBlock, - () => DocumentBlock, - () => VideoBlock, - () => ToolUseBlock, - () => ToolResultBlock, - [() => GuardrailConverseContentBlock, 0], - () => CachePointBlock, - [() => ReasoningContentBlock, 0], - () => CitationsContentBlock, - () => SearchResultBlock, - ], -]; -var ContentBlockDelta = [ - 3, - n0, - _CBD, - 0, - [_te, _tU, _tR, _rC, _cit], - [ - 0, - () => ToolUseBlockDelta, - () => ToolResultBlocksDelta, - [() => ReasoningContentBlockDelta, 0], - () => CitationsDelta, - ], -]; -var ContentBlockStart = [ - 3, - n0, - _CBS, - 0, - [_tU, _tR], - [() => ToolUseBlockStart, () => ToolResultBlockStart], -]; -var ConverseOutput = [3, n0, _CO, 0, [_m], [[() => Message, 0]]]; -var ConverseStreamOutput = [ - 3, - n0, - _CSO, - { - [_stre]: 1, - }, - [_mS, _cBS, _cBD, _cBSo, _mSe, _meta, _iSE, _mSEE, _vE, _tE, _sUE], - [ - () => MessageStartEvent, - () => ContentBlockStartEvent, - [() => ContentBlockDeltaEvent, 0], - () => ContentBlockStopEvent, - () => MessageStopEvent, - [() => ConverseStreamMetadataEvent, 0], - [() => InternalServerException, 0], - [() => ModelStreamErrorException, 0], - [() => ValidationException, 0], - [() => ThrottlingException, 0], - [() => ServiceUnavailableException, 0], - ], -]; -var CountTokensInput = [ - 3, - n0, - _CTI, - 0, - [_iMn, _conv], - [ - [() => InvokeModelTokensRequest, 0], - [() => ConverseTokensRequest, 0], - ], -]; -var DocumentContentBlock = [3, n0, _DCBo, 0, [_te], [0]]; -var DocumentSource = [ - 3, - n0, - _DS, - 0, - [_b, _sL, _te, _co], - [21, () => S3Location, 0, () => DocumentContentBlocks], -]; -var GuardrailAutomatedReasoningFinding = [ - 3, - n0, - _GARF, - 0, - [_va, _in, _sa, _imp, _tA, _tCoo, _nTo], - [ - [() => GuardrailAutomatedReasoningValidFinding, 0], - [() => GuardrailAutomatedReasoningInvalidFinding, 0], - [() => GuardrailAutomatedReasoningSatisfiableFinding, 0], - [() => GuardrailAutomatedReasoningImpossibleFinding, 0], - [() => GuardrailAutomatedReasoningTranslationAmbiguousFinding, 0], - () => GuardrailAutomatedReasoningTooComplexFinding, - () => GuardrailAutomatedReasoningNoTranslationsFinding, - ], -]; -var GuardrailContentBlock = [ - 3, - n0, - _GCB, - 0, - [_te, _ima], - [() => GuardrailTextBlock, [() => GuardrailImageBlock, 0]], -]; -var GuardrailConverseContentBlock = [ - 3, - n0, - _GCCB, - 0, - [_te, _ima], - [() => GuardrailConverseTextBlock, [() => GuardrailConverseImageBlock, 0]], -]; -var GuardrailConverseImageSource = [3, n0, _GCIS, 8, [_b], [21]]; -var GuardrailImageSource = [3, n0, _GIS, 8, [_b], [21]]; -var ImageSource = [3, n0, _IS, 0, [_b, _sL], [21, () => S3Location]]; -var InvokeModelWithBidirectionalStreamInput = [ - 3, - n0, - _IMWBSI, - { - [_stre]: 1, - }, - [_ch], - [[() => BidirectionalInputPayloadPart, 0]], -]; -var InvokeModelWithBidirectionalStreamOutput = [ - 3, - n0, - _IMWBSO, - { - [_stre]: 1, - }, - [_ch, _iSE, _mSEE, _vE, _tE, _mTE, _sUE], - [ - [() => BidirectionalOutputPayloadPart, 0], - [() => InternalServerException, 0], - [() => ModelStreamErrorException, 0], - [() => ValidationException, 0], - [() => ThrottlingException, 0], - [() => ModelTimeoutException, 0], - [() => ServiceUnavailableException, 0], - ], -]; -var PromptVariableValues = [3, n0, _PVV, 0, [_te], [0]]; -var ReasoningContentBlock = [ - 3, - n0, - _RCB, - 8, - [_rT, _rCe], - [[() => ReasoningTextBlock, 0], 21], -]; -var ReasoningContentBlockDelta = [3, n0, _RCBD, 8, [_te, _rCe, _si], [0, 21, 0]]; -var ResponseStream = [ - 3, - n0, - _RS, - { - [_stre]: 1, - }, - [_ch, _iSE, _mSEE, _vE, _tE, _mTE, _sUE], - [ - [() => PayloadPart, 0], - [() => InternalServerException, 0], - [() => ModelStreamErrorException, 0], - [() => ValidationException, 0], - [() => ThrottlingException, 0], - [() => ModelTimeoutException, 0], - [() => ServiceUnavailableException, 0], - ], -]; -var SystemContentBlock = [ - 3, - n0, - _SCBy, - 0, - [_te, _gCua, _cPa], - [0, [() => GuardrailConverseContentBlock, 0], () => CachePointBlock], -]; -var Tool = [ - 3, - n0, - _Too, - 0, - [_tS, _sTy, _cPa], - [() => ToolSpecification, () => SystemTool, () => CachePointBlock], -]; -var ToolChoice = [ - 3, - n0, - _TCo, - 0, - [_au, _an, _tool], - [() => AutoToolChoice, () => AnyToolChoice, () => SpecificToolChoice], -]; -var ToolInputSchema = [3, n0, _TIS, 0, [_j], [15]]; -var ToolResultBlockDelta = [3, n0, _TRBDo, 0, [_te], [0]]; -var ToolResultContentBlock = [ - 3, - n0, - _TRCBo, - 0, - [_j, _te, _ima, _doc, _vi, _sRe], - [15, 0, () => ImageBlock, () => DocumentBlock, () => VideoBlock, () => SearchResultBlock], -]; -var VideoSource = [3, n0, _VS, 0, [_b, _sL], [21, () => S3Location]]; -var ApplyGuardrail = [ - 9, - n0, - _AG, - { - [_h]: ["POST", "/guardrail/{guardrailIdentifier}/version/{guardrailVersion}/apply", 200], - }, - () => ApplyGuardrailRequest, - () => ApplyGuardrailResponse, -]; -var Converse = [ - 9, - n0, - _Co, - { - [_h]: ["POST", "/model/{modelId}/converse", 200], - }, - () => ConverseRequest, - () => ConverseResponse, -]; -var ConverseStream = [ - 9, - n0, - _CS, - { - [_h]: ["POST", "/model/{modelId}/converse-stream", 200], - }, - () => ConverseStreamRequest, - () => ConverseStreamResponse, -]; -var CountTokens = [ - 9, - n0, - _CTo, - { - [_h]: ["POST", "/model/{modelId}/count-tokens", 200], - }, - () => CountTokensRequest, - () => CountTokensResponse, -]; -var GetAsyncInvoke = [ - 9, - n0, - _GAI, - { - [_h]: ["GET", "/async-invoke/{invocationArn}", 200], - }, - () => GetAsyncInvokeRequest, - () => GetAsyncInvokeResponse, -]; -var InvokeModel = [ - 9, - n0, - _IM, - { - [_h]: ["POST", "/model/{modelId}/invoke", 200], - }, - () => InvokeModelRequest, - () => InvokeModelResponse, -]; -var InvokeModelWithBidirectionalStream = [ - 9, - n0, - _IMWBS, - { - [_h]: ["POST", "/model/{modelId}/invoke-with-bidirectional-stream", 200], - }, - () => InvokeModelWithBidirectionalStreamRequest, - () => InvokeModelWithBidirectionalStreamResponse, -]; -var InvokeModelWithResponseStream = [ - 9, - n0, - _IMWRS, - { - [_h]: ["POST", "/model/{modelId}/invoke-with-response-stream", 200], - }, - () => InvokeModelWithResponseStreamRequest, - () => InvokeModelWithResponseStreamResponse, -]; -var ListAsyncInvokes = [ - 9, - n0, - _LAI, - { - [_h]: ["GET", "/async-invoke", 200], - }, - () => ListAsyncInvokesRequest, - () => ListAsyncInvokesResponse, -]; -var StartAsyncInvoke = [ - 9, - n0, - _SAI, - { - [_h]: ["POST", "/async-invoke", 200], - }, - () => StartAsyncInvokeRequest, - () => StartAsyncInvokeResponse, -]; - -class ApplyGuardrailCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockFrontendService", "ApplyGuardrail", {}) - .n("BedrockRuntimeClient", "ApplyGuardrailCommand") - .sc(ApplyGuardrail) - .build() { -} - -class ConverseCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockFrontendService", "Converse", {}) - .n("BedrockRuntimeClient", "ConverseCommand") - .sc(Converse) - .build() { -} - -class ConverseStreamCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockFrontendService", "ConverseStream", { - eventStream: { - output: true, - }, -}) - .n("BedrockRuntimeClient", "ConverseStreamCommand") - .sc(ConverseStream) - .build() { -} - -class CountTokensCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockFrontendService", "CountTokens", {}) - .n("BedrockRuntimeClient", "CountTokensCommand") - .sc(CountTokens) - .build() { -} - -class GetAsyncInvokeCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockFrontendService", "GetAsyncInvoke", {}) - .n("BedrockRuntimeClient", "GetAsyncInvokeCommand") - .sc(GetAsyncInvoke) - .build() { -} - -class InvokeModelCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockFrontendService", "InvokeModel", {}) - .n("BedrockRuntimeClient", "InvokeModelCommand") - .sc(InvokeModel) - .build() { -} - -class InvokeModelWithBidirectionalStreamCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [ - middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions()), - middlewareEventstream.getEventStreamPlugin(config), - middlewareWebsocket.getWebSocketPlugin(config, { - headerPrefix: "x-amz-bedrock-", - }), - ]; -}) - .s("AmazonBedrockFrontendService", "InvokeModelWithBidirectionalStream", { - eventStream: { - input: true, - output: true, - }, -}) - .n("BedrockRuntimeClient", "InvokeModelWithBidirectionalStreamCommand") - .sc(InvokeModelWithBidirectionalStream) - .build() { -} - -class InvokeModelWithResponseStreamCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockFrontendService", "InvokeModelWithResponseStream", { - eventStream: { - output: true, - }, -}) - .n("BedrockRuntimeClient", "InvokeModelWithResponseStreamCommand") - .sc(InvokeModelWithResponseStream) - .build() { -} - -class ListAsyncInvokesCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockFrontendService", "ListAsyncInvokes", {}) - .n("BedrockRuntimeClient", "ListAsyncInvokesCommand") - .sc(ListAsyncInvokes) - .build() { -} - -class StartAsyncInvokeCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockFrontendService", "StartAsyncInvoke", {}) - .n("BedrockRuntimeClient", "StartAsyncInvokeCommand") - .sc(StartAsyncInvoke) - .build() { -} - -const commands = { - ApplyGuardrailCommand, - ConverseCommand, - ConverseStreamCommand, - CountTokensCommand, - GetAsyncInvokeCommand, - InvokeModelCommand, - InvokeModelWithBidirectionalStreamCommand, - InvokeModelWithResponseStreamCommand, - ListAsyncInvokesCommand, - StartAsyncInvokeCommand, -}; -class BedrockRuntime extends BedrockRuntimeClient { -} -smithyClient.createAggregatedClient(commands, BedrockRuntime); - -const paginateListAsyncInvokes = core.createPaginator(BedrockRuntimeClient, ListAsyncInvokesCommand, "nextToken", "nextToken", "maxResults"); - -const AsyncInvokeStatus = { - COMPLETED: "Completed", - FAILED: "Failed", - IN_PROGRESS: "InProgress", -}; -const SortAsyncInvocationBy = { - SUBMISSION_TIME: "SubmissionTime", -}; -const SortOrder = { - ASCENDING: "Ascending", - DESCENDING: "Descending", -}; -const GuardrailImageFormat = { - JPEG: "jpeg", - PNG: "png", -}; -const GuardrailContentQualifier = { - GROUNDING_SOURCE: "grounding_source", - GUARD_CONTENT: "guard_content", - QUERY: "query", -}; -const GuardrailOutputScope = { - FULL: "FULL", - INTERVENTIONS: "INTERVENTIONS", -}; -const GuardrailContentSource = { - INPUT: "INPUT", - OUTPUT: "OUTPUT", -}; -const GuardrailAction = { - GUARDRAIL_INTERVENED: "GUARDRAIL_INTERVENED", - NONE: "NONE", -}; -const GuardrailAutomatedReasoningLogicWarningType = { - ALWAYS_FALSE: "ALWAYS_FALSE", - ALWAYS_TRUE: "ALWAYS_TRUE", -}; -const GuardrailContentPolicyAction = { - BLOCKED: "BLOCKED", - NONE: "NONE", -}; -const GuardrailContentFilterConfidence = { - HIGH: "HIGH", - LOW: "LOW", - MEDIUM: "MEDIUM", - NONE: "NONE", -}; -const GuardrailContentFilterStrength = { - HIGH: "HIGH", - LOW: "LOW", - MEDIUM: "MEDIUM", - NONE: "NONE", -}; -const GuardrailContentFilterType = { - HATE: "HATE", - INSULTS: "INSULTS", - MISCONDUCT: "MISCONDUCT", - PROMPT_ATTACK: "PROMPT_ATTACK", - SEXUAL: "SEXUAL", - VIOLENCE: "VIOLENCE", -}; -const GuardrailContextualGroundingPolicyAction = { - BLOCKED: "BLOCKED", - NONE: "NONE", -}; -const GuardrailContextualGroundingFilterType = { - GROUNDING: "GROUNDING", - RELEVANCE: "RELEVANCE", -}; -const GuardrailSensitiveInformationPolicyAction = { - ANONYMIZED: "ANONYMIZED", - BLOCKED: "BLOCKED", - NONE: "NONE", -}; -const GuardrailPiiEntityType = { - ADDRESS: "ADDRESS", - AGE: "AGE", - AWS_ACCESS_KEY: "AWS_ACCESS_KEY", - AWS_SECRET_KEY: "AWS_SECRET_KEY", - CA_HEALTH_NUMBER: "CA_HEALTH_NUMBER", - CA_SOCIAL_INSURANCE_NUMBER: "CA_SOCIAL_INSURANCE_NUMBER", - CREDIT_DEBIT_CARD_CVV: "CREDIT_DEBIT_CARD_CVV", - CREDIT_DEBIT_CARD_EXPIRY: "CREDIT_DEBIT_CARD_EXPIRY", - CREDIT_DEBIT_CARD_NUMBER: "CREDIT_DEBIT_CARD_NUMBER", - DRIVER_ID: "DRIVER_ID", - EMAIL: "EMAIL", - INTERNATIONAL_BANK_ACCOUNT_NUMBER: "INTERNATIONAL_BANK_ACCOUNT_NUMBER", - IP_ADDRESS: "IP_ADDRESS", - LICENSE_PLATE: "LICENSE_PLATE", - MAC_ADDRESS: "MAC_ADDRESS", - NAME: "NAME", - PASSWORD: "PASSWORD", - PHONE: "PHONE", - PIN: "PIN", - SWIFT_CODE: "SWIFT_CODE", - UK_NATIONAL_HEALTH_SERVICE_NUMBER: "UK_NATIONAL_HEALTH_SERVICE_NUMBER", - UK_NATIONAL_INSURANCE_NUMBER: "UK_NATIONAL_INSURANCE_NUMBER", - UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER: "UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER", - URL: "URL", - USERNAME: "USERNAME", - US_BANK_ACCOUNT_NUMBER: "US_BANK_ACCOUNT_NUMBER", - US_BANK_ROUTING_NUMBER: "US_BANK_ROUTING_NUMBER", - US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER: "US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER", - US_PASSPORT_NUMBER: "US_PASSPORT_NUMBER", - US_SOCIAL_SECURITY_NUMBER: "US_SOCIAL_SECURITY_NUMBER", - VEHICLE_IDENTIFICATION_NUMBER: "VEHICLE_IDENTIFICATION_NUMBER", -}; -const GuardrailTopicPolicyAction = { - BLOCKED: "BLOCKED", - NONE: "NONE", -}; -const GuardrailTopicType = { - DENY: "DENY", -}; -const GuardrailWordPolicyAction = { - BLOCKED: "BLOCKED", - NONE: "NONE", -}; -const GuardrailManagedWordType = { - PROFANITY: "PROFANITY", -}; -const GuardrailTrace = { - DISABLED: "disabled", - ENABLED: "enabled", - ENABLED_FULL: "enabled_full", -}; -const CachePointType = { - DEFAULT: "default", -}; -const DocumentFormat = { - CSV: "csv", - DOC: "doc", - DOCX: "docx", - HTML: "html", - MD: "md", - PDF: "pdf", - TXT: "txt", - XLS: "xls", - XLSX: "xlsx", -}; -const GuardrailConverseImageFormat = { - JPEG: "jpeg", - PNG: "png", -}; -const GuardrailConverseContentQualifier = { - GROUNDING_SOURCE: "grounding_source", - GUARD_CONTENT: "guard_content", - QUERY: "query", -}; -const ImageFormat = { - GIF: "gif", - JPEG: "jpeg", - PNG: "png", - WEBP: "webp", -}; -const VideoFormat = { - FLV: "flv", - MKV: "mkv", - MOV: "mov", - MP4: "mp4", - MPEG: "mpeg", - MPG: "mpg", - THREE_GP: "three_gp", - WEBM: "webm", - WMV: "wmv", -}; -const ToolResultStatus = { - ERROR: "error", - SUCCESS: "success", -}; -const ToolUseType = { - SERVER_TOOL_USE: "server_tool_use", -}; -const ConversationRole = { - ASSISTANT: "assistant", - USER: "user", -}; -const PerformanceConfigLatency = { - OPTIMIZED: "optimized", - STANDARD: "standard", -}; -const ServiceTierType = { - DEFAULT: "default", - FLEX: "flex", - PRIORITY: "priority", -}; -const StopReason = { - CONTENT_FILTERED: "content_filtered", - END_TURN: "end_turn", - GUARDRAIL_INTERVENED: "guardrail_intervened", - MAX_TOKENS: "max_tokens", - MODEL_CONTEXT_WINDOW_EXCEEDED: "model_context_window_exceeded", - STOP_SEQUENCE: "stop_sequence", - TOOL_USE: "tool_use", -}; -const GuardrailStreamProcessingMode = { - ASYNC: "async", - SYNC: "sync", -}; -const Trace = { - DISABLED: "DISABLED", - ENABLED: "ENABLED", - ENABLED_FULL: "ENABLED_FULL", -}; - -Object.defineProperty(exports, "$Command", { - enumerable: true, - get: function () { return smithyClient.Command; } -}); -Object.defineProperty(exports, "__Client", { - enumerable: true, - get: function () { return smithyClient.Client; } -}); -exports.AccessDeniedException = AccessDeniedException$1; -exports.ApplyGuardrailCommand = ApplyGuardrailCommand; -exports.AsyncInvokeStatus = AsyncInvokeStatus; -exports.BedrockRuntime = BedrockRuntime; -exports.BedrockRuntimeClient = BedrockRuntimeClient; -exports.BedrockRuntimeServiceException = BedrockRuntimeServiceException$1; -exports.CachePointType = CachePointType; -exports.ConflictException = ConflictException$1; -exports.ConversationRole = ConversationRole; -exports.ConverseCommand = ConverseCommand; -exports.ConverseStreamCommand = ConverseStreamCommand; -exports.CountTokensCommand = CountTokensCommand; -exports.DocumentFormat = DocumentFormat; -exports.GetAsyncInvokeCommand = GetAsyncInvokeCommand; -exports.GuardrailAction = GuardrailAction; -exports.GuardrailAutomatedReasoningLogicWarningType = GuardrailAutomatedReasoningLogicWarningType; -exports.GuardrailContentFilterConfidence = GuardrailContentFilterConfidence; -exports.GuardrailContentFilterStrength = GuardrailContentFilterStrength; -exports.GuardrailContentFilterType = GuardrailContentFilterType; -exports.GuardrailContentPolicyAction = GuardrailContentPolicyAction; -exports.GuardrailContentQualifier = GuardrailContentQualifier; -exports.GuardrailContentSource = GuardrailContentSource; -exports.GuardrailContextualGroundingFilterType = GuardrailContextualGroundingFilterType; -exports.GuardrailContextualGroundingPolicyAction = GuardrailContextualGroundingPolicyAction; -exports.GuardrailConverseContentQualifier = GuardrailConverseContentQualifier; -exports.GuardrailConverseImageFormat = GuardrailConverseImageFormat; -exports.GuardrailImageFormat = GuardrailImageFormat; -exports.GuardrailManagedWordType = GuardrailManagedWordType; -exports.GuardrailOutputScope = GuardrailOutputScope; -exports.GuardrailPiiEntityType = GuardrailPiiEntityType; -exports.GuardrailSensitiveInformationPolicyAction = GuardrailSensitiveInformationPolicyAction; -exports.GuardrailStreamProcessingMode = GuardrailStreamProcessingMode; -exports.GuardrailTopicPolicyAction = GuardrailTopicPolicyAction; -exports.GuardrailTopicType = GuardrailTopicType; -exports.GuardrailTrace = GuardrailTrace; -exports.GuardrailWordPolicyAction = GuardrailWordPolicyAction; -exports.ImageFormat = ImageFormat; -exports.InternalServerException = InternalServerException$1; -exports.InvokeModelCommand = InvokeModelCommand; -exports.InvokeModelWithBidirectionalStreamCommand = InvokeModelWithBidirectionalStreamCommand; -exports.InvokeModelWithResponseStreamCommand = InvokeModelWithResponseStreamCommand; -exports.ListAsyncInvokesCommand = ListAsyncInvokesCommand; -exports.ModelErrorException = ModelErrorException$1; -exports.ModelNotReadyException = ModelNotReadyException$1; -exports.ModelStreamErrorException = ModelStreamErrorException$1; -exports.ModelTimeoutException = ModelTimeoutException$1; -exports.PerformanceConfigLatency = PerformanceConfigLatency; -exports.ResourceNotFoundException = ResourceNotFoundException$1; -exports.ServiceQuotaExceededException = ServiceQuotaExceededException$1; -exports.ServiceTierType = ServiceTierType; -exports.ServiceUnavailableException = ServiceUnavailableException$1; -exports.SortAsyncInvocationBy = SortAsyncInvocationBy; -exports.SortOrder = SortOrder; -exports.StartAsyncInvokeCommand = StartAsyncInvokeCommand; -exports.StopReason = StopReason; -exports.ThrottlingException = ThrottlingException$1; -exports.ToolResultStatus = ToolResultStatus; -exports.ToolUseType = ToolUseType; -exports.Trace = Trace; -exports.ValidationException = ValidationException$1; -exports.VideoFormat = VideoFormat; -exports.paginateListAsyncInvokes = paginateListAsyncInvokes; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/runtimeConfig.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/runtimeConfig.js deleted file mode 100644 index ea534e25..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/runtimeConfig.js +++ /dev/null @@ -1,83 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/runtimeConfig.shared.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/runtimeConfig.shared.js deleted file mode 100644 index 3f4816c4..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/dist-cjs/runtimeConfig.shared.js +++ /dev/null @@ -1,42 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js deleted file mode 100644 index cd52cf1a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js +++ /dev/null @@ -1,53 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js deleted file mode 100644 index cd84e7bd..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/eventstream-serde-node/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js +++ /dev/null @@ -1,132 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 52303c3b..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,169 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-cjs/index.js deleted file mode 100644 index 9f589873..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/smithy-client/dist-cjs/index.js +++ /dev/null @@ -1,589 +0,0 @@ -'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]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js deleted file mode 100644 index b06a7b87..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js +++ /dev/null @@ -1,16 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/index.js deleted file mode 100644 index c095e288..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/index.js +++ /dev/null @@ -1,19 +0,0 @@ -'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]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/toBase64.js deleted file mode 100644 index 0590ce3f..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/dist-cjs/toBase64.js +++ /dev/null @@ -1,19 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js deleted file mode 100644 index b577c9ca..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js +++ /dev/null @@ -1,20 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js deleted file mode 100644 index 3238bb77..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock-runtime/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || - Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; - -exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/auth/httpAuthSchemeProvider.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/auth/httpAuthSchemeProvider.js deleted file mode 100644 index 64710468..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/auth/httpAuthSchemeProvider.js +++ /dev/null @@ -1,64 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.resolveHttpAuthSchemeConfig = exports.defaultBedrockHttpAuthSchemeProvider = exports.defaultBedrockHttpAuthSchemeParametersProvider = void 0; -const core_1 = require("@aws-sdk/core"); -const core_2 = require("@smithy/core"); -const util_middleware_1 = require("@smithy/util-middleware"); -const defaultBedrockHttpAuthSchemeParametersProvider = 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.defaultBedrockHttpAuthSchemeParametersProvider = defaultBedrockHttpAuthSchemeParametersProvider; -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 defaultBedrockHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); - options.push(createSmithyApiHttpBearerAuthHttpAuthOption(authParameters)); - } - } - return options; -}; -exports.defaultBedrockHttpAuthSchemeProvider = defaultBedrockHttpAuthSchemeProvider; -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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/endpoint/endpointResolver.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/endpoint/endpointResolver.js deleted file mode 100644 index 7258a356..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/endpoint/endpointResolver.js +++ /dev/null @@ -1,18 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/endpoint/ruleset.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/endpoint/ruleset.js deleted file mode 100644 index a0506167..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/endpoint/ruleset.js +++ /dev/null @@ -1,7 +0,0 @@ -"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-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-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.{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.{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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/index.js deleted file mode 100644 index 543c5f12..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/index.js +++ /dev/null @@ -1,8222 +0,0 @@ -'use strict'; - -var middlewareHostHeader = require('@aws-sdk/middleware-host-header'); -var middlewareLogger = require('@aws-sdk/middleware-logger'); -var middlewareRecursionDetection = require('@aws-sdk/middleware-recursion-detection'); -var middlewareUserAgent = require('@aws-sdk/middleware-user-agent'); -var configResolver = require('@smithy/config-resolver'); -var core = require('@smithy/core'); -var schema = require('@smithy/core/schema'); -var middlewareContentLength = require('@smithy/middleware-content-length'); -var middlewareEndpoint = require('@smithy/middleware-endpoint'); -var middlewareRetry = require('@smithy/middleware-retry'); -var smithyClient = require('@smithy/smithy-client'); -var httpAuthSchemeProvider = require('./auth/httpAuthSchemeProvider'); -var runtimeConfig = require('./runtimeConfig'); -var regionConfigResolver = require('@aws-sdk/region-config-resolver'); -var protocolHttp = require('@smithy/protocol-http'); - -const resolveClientEndpointParameters = (options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - defaultSigningName: "bedrock", - }); -}; -const commonParams = { - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, -}; - -const getHttpAuthExtensionConfiguration = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - let _token = runtimeConfig.token; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } - else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - }, - setToken(token) { - _token = token; - }, - token() { - return _token; - }, - }; -}; -const resolveHttpAuthRuntimeConfig = (config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials(), - token: config.token(), - }; -}; - -const resolveRuntimeExtensions = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig), smithyClient.getDefaultExtensionConfiguration(runtimeConfig), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); -}; - -class BedrockClient extends smithyClient.Client { - config; - constructor(...[configuration]) { - const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters(_config_0); - const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1); - const _config_3 = middlewareRetry.resolveRetryConfig(_config_2); - const _config_4 = configResolver.resolveRegionConfig(_config_3); - const _config_5 = middlewareHostHeader.resolveHostHeaderConfig(_config_4); - const _config_6 = middlewareEndpoint.resolveEndpointConfig(_config_5); - const _config_7 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_6); - const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use(schema.getSchemaSerdePlugin(this.config)); - this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config)); - this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config)); - this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config)); - this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config)); - this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config)); - this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config)); - this.middlewareStack.use(core.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { - httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultBedrockHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config) => new core.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials, - "smithy.api#httpBearerAuth": config.token, - }), - })); - this.middlewareStack.use(core.getHttpSigningPlugin(this.config)); - } - destroy() { - super.destroy(); - } -} - -let BedrockServiceException$1 = class BedrockServiceException extends smithyClient.ServiceException { - constructor(options) { - super(options); - Object.setPrototypeOf(this, BedrockServiceException.prototype); - } -}; - -let AccessDeniedException$1 = class AccessDeniedException extends BedrockServiceException$1 { - name = "AccessDeniedException"; - $fault = "client"; - constructor(opts) { - super({ - name: "AccessDeniedException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, AccessDeniedException.prototype); - } -}; -let InternalServerException$1 = class InternalServerException extends BedrockServiceException$1 { - name = "InternalServerException"; - $fault = "server"; - constructor(opts) { - super({ - name: "InternalServerException", - $fault: "server", - ...opts, - }); - Object.setPrototypeOf(this, InternalServerException.prototype); - } -}; -let ResourceNotFoundException$1 = class ResourceNotFoundException extends BedrockServiceException$1 { - name = "ResourceNotFoundException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ResourceNotFoundException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ResourceNotFoundException.prototype); - } -}; -let ThrottlingException$1 = class ThrottlingException extends BedrockServiceException$1 { - name = "ThrottlingException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ThrottlingException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ThrottlingException.prototype); - } -}; -let ValidationException$1 = class ValidationException extends BedrockServiceException$1 { - name = "ValidationException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ValidationException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ValidationException.prototype); - } -}; -let ConflictException$1 = class ConflictException extends BedrockServiceException$1 { - name = "ConflictException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ConflictException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ConflictException.prototype); - } -}; -let ServiceQuotaExceededException$1 = class ServiceQuotaExceededException extends BedrockServiceException$1 { - name = "ServiceQuotaExceededException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ServiceQuotaExceededException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ServiceQuotaExceededException.prototype); - } -}; -let TooManyTagsException$1 = class TooManyTagsException extends BedrockServiceException$1 { - name = "TooManyTagsException"; - $fault = "client"; - resourceName; - constructor(opts) { - super({ - name: "TooManyTagsException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, TooManyTagsException.prototype); - this.resourceName = opts.resourceName; - } -}; -let ResourceInUseException$1 = class ResourceInUseException extends BedrockServiceException$1 { - name = "ResourceInUseException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ResourceInUseException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ResourceInUseException.prototype); - } -}; -let ServiceUnavailableException$1 = class ServiceUnavailableException extends BedrockServiceException$1 { - name = "ServiceUnavailableException"; - $fault = "server"; - constructor(opts) { - super({ - name: "ServiceUnavailableException", - $fault: "server", - ...opts, - }); - Object.setPrototypeOf(this, ServiceUnavailableException.prototype); - } -}; - -const _AA = "AgreementAvailability"; -const _ADE = "AccessDeniedException"; -const _AEC = "AutomatedEvaluationConfig"; -const _AECM = "AutomatedEvaluationCustomMetrics"; -const _AECMC = "AutomatedEvaluationCustomMetricConfig"; -const _AECMS = "AutomatedEvaluationCustomMetricSource"; -const _ARCDSL = "AutomatedReasoningCheckDifferenceScenarioList"; -const _ARCF = "AutomatedReasoningCheckFinding"; -const _ARCFL = "AutomatedReasoningCheckFindingList"; -const _ARCIF = "AutomatedReasoningCheckImpossibleFinding"; -const _ARCIFu = "AutomatedReasoningCheckInvalidFinding"; -const _ARCITR = "AutomatedReasoningCheckInputTextReference"; -const _ARCITRL = "AutomatedReasoningCheckInputTextReferenceList"; -const _ARCLW = "AutomatedReasoningCheckLogicWarning"; -const _ARCNTF = "AutomatedReasoningCheckNoTranslationsFinding"; -const _ARCR = "AutomatedReasoningCheckRule"; -const _ARCRL = "AutomatedReasoningCheckRuleList"; -const _ARCS = "AutomatedReasoningCheckScenario"; -const _ARCSF = "AutomatedReasoningCheckSatisfiableFinding"; -const _ARCT = "AutomatedReasoningCheckTranslation"; -const _ARCTAF = "AutomatedReasoningCheckTranslationAmbiguousFinding"; -const _ARCTCF = "AutomatedReasoningCheckTooComplexFinding"; -const _ARCTL = "AutomatedReasoningCheckTranslationList"; -const _ARCTO = "AutomatedReasoningCheckTranslationOption"; -const _ARCTOL = "AutomatedReasoningCheckTranslationOptionList"; -const _ARCVF = "AutomatedReasoningCheckValidFinding"; -const _ARLS = "AutomatedReasoningLogicStatement"; -const _ARLSC = "AutomatedReasoningLogicStatementContent"; -const _ARLSL = "AutomatedReasoningLogicStatementList"; -const _ARNLSC = "AutomatedReasoningNaturalLanguageStatementContent"; -const _ARPA = "AutomatedReasoningPolicyAnnotation"; -const _ARPAFNL = "AutomatedReasoningPolicyAnnotationFeedbackNaturalLanguage"; -const _ARPAIC = "AutomatedReasoningPolicyAnnotationIngestContent"; -const _ARPAL = "AutomatedReasoningPolicyAnnotationList"; -const _ARPARA = "AutomatedReasoningPolicyAddRuleAnnotation"; -const _ARPARFNLA = "AutomatedReasoningPolicyAddRuleFromNaturalLanguageAnnotation"; -const _ARPARM = "AutomatedReasoningPolicyAddRuleMutation"; -const _ARPARNL = "AutomatedReasoningPolicyAnnotationRuleNaturalLanguage"; -const _ARPATA = "AutomatedReasoningPolicyAddTypeAnnotation"; -const _ARPATM = "AutomatedReasoningPolicyAddTypeMutation"; -const _ARPATV = "AutomatedReasoningPolicyAddTypeValue"; -const _ARPAVA = "AutomatedReasoningPolicyAddVariableAnnotation"; -const _ARPAVM = "AutomatedReasoningPolicyAddVariableMutation"; -const _ARPBDB = "AutomatedReasoningPolicyBuildDocumentBlob"; -const _ARPBDD = "AutomatedReasoningPolicyBuildDocumentDescription"; -const _ARPBDN = "AutomatedReasoningPolicyBuildDocumentName"; -const _ARPBL = "AutomatedReasoningPolicyBuildLog"; -const _ARPBLE = "AutomatedReasoningPolicyBuildLogEntry"; -const _ARPBLEL = "AutomatedReasoningPolicyBuildLogEntryList"; -const _ARPBRA = "AutomatedReasoningPolicyBuildResultAssets"; -const _ARPBS = "AutomatedReasoningPolicyBuildStep"; -const _ARPBSC = "AutomatedReasoningPolicyBuildStepContext"; -const _ARPBSL = "AutomatedReasoningPolicyBuildStepList"; -const _ARPBSM = "AutomatedReasoningPolicyBuildStepMessage"; -const _ARPBSML = "AutomatedReasoningPolicyBuildStepMessageList"; -const _ARPBWD = "AutomatedReasoningPolicyBuildWorkflowDocument"; -const _ARPBWDL = "AutomatedReasoningPolicyBuildWorkflowDocumentList"; -const _ARPBWRC = "AutomatedReasoningPolicyBuildWorkflowRepairContent"; -const _ARPBWS = "AutomatedReasoningPolicyBuildWorkflowSource"; -const _ARPBWSu = "AutomatedReasoningPolicyBuildWorkflowSummary"; -const _ARPBWSut = "AutomatedReasoningPolicyBuildWorkflowSummaries"; -const _ARPD = "AutomatedReasoningPolicyDescription"; -const _ARPDE = "AutomatedReasoningPolicyDefinitionElement"; -const _ARPDQR = "AutomatedReasoningPolicyDefinitionQualityReport"; -const _ARPDR = "AutomatedReasoningPolicyDefinitionRule"; -const _ARPDRA = "AutomatedReasoningPolicyDeleteRuleAnnotation"; -const _ARPDRAE = "AutomatedReasoningPolicyDefinitionRuleAlternateExpression"; -const _ARPDRE = "AutomatedReasoningPolicyDefinitionRuleExpression"; -const _ARPDRL = "AutomatedReasoningPolicyDefinitionRuleList"; -const _ARPDRM = "AutomatedReasoningPolicyDeleteRuleMutation"; -const _ARPDRS = "AutomatedReasoningPolicyDisjointRuleSet"; -const _ARPDRSL = "AutomatedReasoningPolicyDisjointRuleSetList"; -const _ARPDT = "AutomatedReasoningPolicyDefinitionType"; -const _ARPDTA = "AutomatedReasoningPolicyDeleteTypeAnnotation"; -const _ARPDTD = "AutomatedReasoningPolicyDefinitionTypeDescription"; -const _ARPDTL = "AutomatedReasoningPolicyDefinitionTypeList"; -const _ARPDTM = "AutomatedReasoningPolicyDeleteTypeMutation"; -const _ARPDTN = "AutomatedReasoningPolicyDefinitionTypeName"; -const _ARPDTNL = "AutomatedReasoningPolicyDefinitionTypeNameList"; -const _ARPDTV = "AutomatedReasoningPolicyDefinitionTypeValue"; -const _ARPDTVD = "AutomatedReasoningPolicyDefinitionTypeValueDescription"; -const _ARPDTVL = "AutomatedReasoningPolicyDefinitionTypeValueList"; -const _ARPDTVP = "AutomatedReasoningPolicyDefinitionTypeValuePair"; -const _ARPDTVPL = "AutomatedReasoningPolicyDefinitionTypeValuePairList"; -const _ARPDTVu = "AutomatedReasoningPolicyDeleteTypeValue"; -const _ARPDV = "AutomatedReasoningPolicyDefinitionVariable"; -const _ARPDVA = "AutomatedReasoningPolicyDeleteVariableAnnotation"; -const _ARPDVD = "AutomatedReasoningPolicyDefinitionVariableDescription"; -const _ARPDVL = "AutomatedReasoningPolicyDefinitionVariableList"; -const _ARPDVM = "AutomatedReasoningPolicyDeleteVariableMutation"; -const _ARPDVN = "AutomatedReasoningPolicyDefinitionVariableName"; -const _ARPDVNL = "AutomatedReasoningPolicyDefinitionVariableNameList"; -const _ARPDu = "AutomatedReasoningPolicyDefinition"; -const _ARPGTC = "AutomatedReasoningPolicyGeneratedTestCase"; -const _ARPGTCL = "AutomatedReasoningPolicyGeneratedTestCaseList"; -const _ARPGTCu = "AutomatedReasoningPolicyGeneratedTestCases"; -const _ARPICA = "AutomatedReasoningPolicyIngestContentAnnotation"; -const _ARPM = "AutomatedReasoningPolicyMutation"; -const _ARPN = "AutomatedReasoningPolicyName"; -const _ARPP = "AutomatedReasoningPolicyPlanning"; -const _ARPS = "AutomatedReasoningPolicyScenario"; -const _ARPSAE = "AutomatedReasoningPolicyScenarioAlternateExpression"; -const _ARPSE = "AutomatedReasoningPolicyScenarioExpression"; -const _ARPSu = "AutomatedReasoningPolicySummary"; -const _ARPSut = "AutomatedReasoningPolicySummaries"; -const _ARPTC = "AutomatedReasoningPolicyTestCase"; -const _ARPTCL = "AutomatedReasoningPolicyTestCaseList"; -const _ARPTGC = "AutomatedReasoningPolicyTestGuardContent"; -const _ARPTL = "AutomatedReasoningPolicyTestList"; -const _ARPTQC = "AutomatedReasoningPolicyTestQueryContent"; -const _ARPTR = "AutomatedReasoningPolicyTestResult"; -const _ARPTVA = "AutomatedReasoningPolicyTypeValueAnnotation"; -const _ARPTVAL = "AutomatedReasoningPolicyTypeValueAnnotationList"; -const _ARPUFRFA = "AutomatedReasoningPolicyUpdateFromRuleFeedbackAnnotation"; -const _ARPUFSFA = "AutomatedReasoningPolicyUpdateFromScenarioFeedbackAnnotation"; -const _ARPURA = "AutomatedReasoningPolicyUpdateRuleAnnotation"; -const _ARPURM = "AutomatedReasoningPolicyUpdateRuleMutation"; -const _ARPUTA = "AutomatedReasoningPolicyUpdateTypeAnnotation"; -const _ARPUTM = "AutomatedReasoningPolicyUpdateTypeMutation"; -const _ARPUTV = "AutomatedReasoningPolicyUpdateTypeValue"; -const _ARPUVA = "AutomatedReasoningPolicyUpdateVariableAnnotation"; -const _ARPUVM = "AutomatedReasoningPolicyUpdateVariableMutation"; -const _ARPWTC = "AutomatedReasoningPolicyWorkflowTypeContent"; -const _BCB = "ByteContentBlob"; -const _BCD = "ByteContentDoc"; -const _BDEJ = "BatchDeleteEvaluationJob"; -const _BDEJE = "BatchDeleteEvaluationJobError"; -const _BDEJEa = "BatchDeleteEvaluationJobErrors"; -const _BDEJI = "BatchDeleteEvaluationJobItem"; -const _BDEJIa = "BatchDeleteEvaluationJobItems"; -const _BDEJR = "BatchDeleteEvaluationJobRequest"; -const _BDEJRa = "BatchDeleteEvaluationJobResponse"; -const _BEM = "BedrockEvaluatorModel"; -const _BEMe = "BedrockEvaluatorModels"; -const _CARP = "CreateAutomatedReasoningPolicy"; -const _CARPBW = "CancelAutomatedReasoningPolicyBuildWorkflow"; -const _CARPBWR = "CancelAutomatedReasoningPolicyBuildWorkflowRequest"; -const _CARPBWRa = "CancelAutomatedReasoningPolicyBuildWorkflowResponse"; -const _CARPR = "CreateAutomatedReasoningPolicyRequest"; -const _CARPRr = "CreateAutomatedReasoningPolicyResponse"; -const _CARPTC = "CreateAutomatedReasoningPolicyTestCase"; -const _CARPTCR = "CreateAutomatedReasoningPolicyTestCaseRequest"; -const _CARPTCRr = "CreateAutomatedReasoningPolicyTestCaseResponse"; -const _CARPV = "CreateAutomatedReasoningPolicyVersion"; -const _CARPVR = "CreateAutomatedReasoningPolicyVersionRequest"; -const _CARPVRr = "CreateAutomatedReasoningPolicyVersionResponse"; -const _CC = "CustomizationConfig"; -const _CCM = "CreateCustomModel"; -const _CCMD = "CreateCustomModelDeployment"; -const _CCMDR = "CreateCustomModelDeploymentRequest"; -const _CCMDRr = "CreateCustomModelDeploymentResponse"; -const _CCMR = "CreateCustomModelRequest"; -const _CCMRr = "CreateCustomModelResponse"; -const _CE = "ConflictException"; -const _CEJ = "CreateEvaluationJob"; -const _CEJR = "CreateEvaluationJobRequest"; -const _CEJRr = "CreateEvaluationJobResponse"; -const _CFMA = "CreateFoundationModelAgreement"; -const _CFMAR = "CreateFoundationModelAgreementRequest"; -const _CFMARr = "CreateFoundationModelAgreementResponse"; -const _CG = "CreateGuardrail"; -const _CGR = "CreateGuardrailRequest"; -const _CGRr = "CreateGuardrailResponse"; -const _CGV = "CreateGuardrailVersion"; -const _CGVR = "CreateGuardrailVersionRequest"; -const _CGVRr = "CreateGuardrailVersionResponse"; -const _CIP = "CreateInferenceProfile"; -const _CIPR = "CreateInferenceProfileRequest"; -const _CIPRr = "CreateInferenceProfileResponse"; -const _CMBEM = "CustomMetricBedrockEvaluatorModel"; -const _CMBEMu = "CustomMetricBedrockEvaluatorModels"; -const _CMCJ = "CreateModelCopyJob"; -const _CMCJR = "CreateModelCopyJobRequest"; -const _CMCJRr = "CreateModelCopyJobResponse"; -const _CMCJRre = "CreateModelCustomizationJobRequest"; -const _CMCJRrea = "CreateModelCustomizationJobResponse"; -const _CMCJr = "CreateModelCustomizationJob"; -const _CMD = "CustomMetricDefinition"; -const _CMDS = "CustomModelDeploymentSummary"; -const _CMDSL = "CustomModelDeploymentSummaryList"; -const _CMEMC = "CustomMetricEvaluatorModelConfig"; -const _CMIJ = "CreateModelImportJob"; -const _CMIJR = "CreateModelImportJobRequest"; -const _CMIJRr = "CreateModelImportJobResponse"; -const _CMIJRre = "CreateModelInvocationJobRequest"; -const _CMIJRrea = "CreateModelInvocationJobResponse"; -const _CMIJr = "CreateModelInvocationJob"; -const _CMME = "CreateMarketplaceModelEndpoint"; -const _CMMER = "CreateMarketplaceModelEndpointRequest"; -const _CMMERr = "CreateMarketplaceModelEndpointResponse"; -const _CMS = "CustomModelSummary"; -const _CMSL = "CustomModelSummaryList"; -const _CMU = "CustomModelUnits"; -const _CPMT = "CreateProvisionedModelThroughput"; -const _CPMTR = "CreateProvisionedModelThroughputRequest"; -const _CPMTRr = "CreateProvisionedModelThroughputResponse"; -const _CPR = "CreatePromptRouter"; -const _CPRR = "CreatePromptRouterRequest"; -const _CPRRr = "CreatePromptRouterResponse"; -const _CWC = "CloudWatchConfig"; -const _DARP = "DeleteAutomatedReasoningPolicy"; -const _DARPBW = "DeleteAutomatedReasoningPolicyBuildWorkflow"; -const _DARPBWR = "DeleteAutomatedReasoningPolicyBuildWorkflowRequest"; -const _DARPBWRe = "DeleteAutomatedReasoningPolicyBuildWorkflowResponse"; -const _DARPR = "DeleteAutomatedReasoningPolicyRequest"; -const _DARPRe = "DeleteAutomatedReasoningPolicyResponse"; -const _DARPTC = "DeleteAutomatedReasoningPolicyTestCase"; -const _DARPTCR = "DeleteAutomatedReasoningPolicyTestCaseRequest"; -const _DARPTCRe = "DeleteAutomatedReasoningPolicyTestCaseResponse"; -const _DC = "DistillationConfig"; -const _DCM = "DeleteCustomModel"; -const _DCMD = "DeleteCustomModelDeployment"; -const _DCMDR = "DeleteCustomModelDeploymentRequest"; -const _DCMDRe = "DeleteCustomModelDeploymentResponse"; -const _DCMR = "DeleteCustomModelRequest"; -const _DCMRe = "DeleteCustomModelResponse"; -const _DFMA = "DeleteFoundationModelAgreement"; -const _DFMAR = "DeleteFoundationModelAgreementRequest"; -const _DFMARe = "DeleteFoundationModelAgreementResponse"; -const _DG = "DeleteGuardrail"; -const _DGR = "DeleteGuardrailRequest"; -const _DGRe = "DeleteGuardrailResponse"; -const _DIM = "DeleteImportedModel"; -const _DIMR = "DeleteImportedModelRequest"; -const _DIMRe = "DeleteImportedModelResponse"; -const _DIP = "DeleteInferenceProfile"; -const _DIPR = "DeleteInferenceProfileRequest"; -const _DIPRe = "DeleteInferenceProfileResponse"; -const _DMILC = "DeleteModelInvocationLoggingConfiguration"; -const _DMILCR = "DeleteModelInvocationLoggingConfigurationRequest"; -const _DMILCRe = "DeleteModelInvocationLoggingConfigurationResponse"; -const _DMME = "DeleteMarketplaceModelEndpoint"; -const _DMMER = "DeleteMarketplaceModelEndpointRequest"; -const _DMMERe = "DeleteMarketplaceModelEndpointResponse"; -const _DMMERer = "DeregisterMarketplaceModelEndpointRequest"; -const _DMMERere = "DeregisterMarketplaceModelEndpointResponse"; -const _DMMEe = "DeregisterMarketplaceModelEndpoint"; -const _DPD = "DataProcessingDetails"; -const _DPMT = "DeleteProvisionedModelThroughput"; -const _DPMTR = "DeleteProvisionedModelThroughputRequest"; -const _DPMTRe = "DeleteProvisionedModelThroughputResponse"; -const _DPR = "DimensionalPriceRate"; -const _DPRR = "DeletePromptRouterRequest"; -const _DPRRe = "DeletePromptRouterResponse"; -const _DPRe = "DeletePromptRouter"; -const _EARPV = "ExportAutomatedReasoningPolicyVersion"; -const _EARPVR = "ExportAutomatedReasoningPolicyVersionRequest"; -const _EARPVRx = "ExportAutomatedReasoningPolicyVersionResponse"; -const _EBM = "EvaluationBedrockModel"; -const _EC = "EndpointConfig"; -const _ECv = "EvaluationConfig"; -const _ED = "EvaluationDataset"; -const _EDL = "EvaluationDatasetLocation"; -const _EDMC = "EvaluationDatasetMetricConfig"; -const _EDMCv = "EvaluationDatasetMetricConfigs"; -const _EDN = "EvaluationDatasetName"; -const _EIC = "EvaluationInferenceConfig"; -const _EICS = "EvaluationInferenceConfigSummary"; -const _EJD = "EvaluationJobDescription"; -const _EJI = "EvaluationJobIdentifier"; -const _EJIv = "EvaluationJobIdentifiers"; -const _EMC = "EvaluationModelConfigs"; -const _EMCS = "EvaluationModelConfigSummary"; -const _EMCv = "EvaluationModelConfig"; -const _EMCva = "EvaluatorModelConfig"; -const _EMD = "EvaluationMetricDescription"; -const _EMIP = "EvaluationModelInferenceParams"; -const _EMN = "EvaluationMetricName"; -const _EMNv = "EvaluationMetricNames"; -const _EODC = "EvaluationOutputDataConfig"; -const _EPIS = "EvaluationPrecomputedInferenceSource"; -const _EPRAGSC = "EvaluationPrecomputedRetrieveAndGenerateSourceConfig"; -const _EPRSC = "EvaluationPrecomputedRetrieveSourceConfig"; -const _EPRSCv = "EvaluationPrecomputedRagSourceConfig"; -const _ERCS = "EvaluationRagConfigSummary"; -const _ES = "EvaluationSummary"; -const _ESGC = "ExternalSourcesGenerationConfiguration"; -const _ESRAGC = "ExternalSourcesRetrieveAndGenerateConfiguration"; -const _ESv = "EvaluationSummaries"; -const _ESx = "ExternalSource"; -const _ESxt = "ExternalSources"; -const _FA = "FilterAttribute"; -const _FFR = "FieldForReranking"; -const _FFRi = "FieldsForReranking"; -const _FMD = "FoundationModelDetails"; -const _FML = "FoundationModelLifecycle"; -const _FMS = "FoundationModelSummary"; -const _FMSL = "FoundationModelSummaryList"; -const _GARP = "GuardrailAutomatedReasoningPolicy"; -const _GARPA = "GetAutomatedReasoningPolicyAnnotations"; -const _GARPAR = "GetAutomatedReasoningPolicyAnnotationsRequest"; -const _GARPARe = "GetAutomatedReasoningPolicyAnnotationsResponse"; -const _GARPBW = "GetAutomatedReasoningPolicyBuildWorkflow"; -const _GARPBWR = "GetAutomatedReasoningPolicyBuildWorkflowRequest"; -const _GARPBWRA = "GetAutomatedReasoningPolicyBuildWorkflowResultAssets"; -const _GARPBWRAR = "GetAutomatedReasoningPolicyBuildWorkflowResultAssetsRequest"; -const _GARPBWRARe = "GetAutomatedReasoningPolicyBuildWorkflowResultAssetsResponse"; -const _GARPBWRe = "GetAutomatedReasoningPolicyBuildWorkflowResponse"; -const _GARPC = "GuardrailAutomatedReasoningPolicyConfig"; -const _GARPNS = "GetAutomatedReasoningPolicyNextScenario"; -const _GARPNSR = "GetAutomatedReasoningPolicyNextScenarioRequest"; -const _GARPNSRe = "GetAutomatedReasoningPolicyNextScenarioResponse"; -const _GARPR = "GetAutomatedReasoningPolicyRequest"; -const _GARPRe = "GetAutomatedReasoningPolicyResponse"; -const _GARPTC = "GetAutomatedReasoningPolicyTestCase"; -const _GARPTCR = "GetAutomatedReasoningPolicyTestCaseRequest"; -const _GARPTCRe = "GetAutomatedReasoningPolicyTestCaseResponse"; -const _GARPTR = "GetAutomatedReasoningPolicyTestResult"; -const _GARPTRR = "GetAutomatedReasoningPolicyTestResultRequest"; -const _GARPTRRe = "GetAutomatedReasoningPolicyTestResultResponse"; -const _GARPe = "GetAutomatedReasoningPolicy"; -const _GBM = "GuardrailBlockedMessaging"; -const _GC = "GenerationConfiguration"; -const _GCF = "GuardrailContentFilter"; -const _GCFA = "GuardrailContentFilterAction"; -const _GCFC = "GuardrailContentFilterConfig"; -const _GCFCu = "GuardrailContentFiltersConfig"; -const _GCFT = "GuardrailContentFiltersTier"; -const _GCFTC = "GuardrailContentFiltersTierConfig"; -const _GCFTN = "GuardrailContentFiltersTierName"; -const _GCFu = "GuardrailContentFilters"; -const _GCGA = "GuardrailContextualGroundingAction"; -const _GCGF = "GuardrailContextualGroundingFilter"; -const _GCGFC = "GuardrailContextualGroundingFilterConfig"; -const _GCGFCu = "GuardrailContextualGroundingFiltersConfig"; -const _GCGFu = "GuardrailContextualGroundingFilters"; -const _GCGP = "GuardrailContextualGroundingPolicy"; -const _GCGPC = "GuardrailContextualGroundingPolicyConfig"; -const _GCM = "GetCustomModel"; -const _GCMD = "GetCustomModelDeployment"; -const _GCMDR = "GetCustomModelDeploymentRequest"; -const _GCMDRe = "GetCustomModelDeploymentResponse"; -const _GCMR = "GetCustomModelRequest"; -const _GCMRe = "GetCustomModelResponse"; -const _GCP = "GuardrailContentPolicy"; -const _GCPC = "GuardrailContentPolicyConfig"; -const _GCRC = "GuardrailCrossRegionConfig"; -const _GCRD = "GuardrailCrossRegionDetails"; -const _GCu = "GuardrailConfiguration"; -const _GD = "GuardrailDescription"; -const _GEJ = "GetEvaluationJob"; -const _GEJR = "GetEvaluationJobRequest"; -const _GEJRe = "GetEvaluationJobResponse"; -const _GFM = "GetFoundationModel"; -const _GFMA = "GetFoundationModelAvailability"; -const _GFMAR = "GetFoundationModelAvailabilityRequest"; -const _GFMARe = "GetFoundationModelAvailabilityResponse"; -const _GFMR = "GetFoundationModelRequest"; -const _GFMRe = "GetFoundationModelResponse"; -const _GFR = "GuardrailFailureRecommendation"; -const _GFRu = "GuardrailFailureRecommendations"; -const _GG = "GetGuardrail"; -const _GGR = "GetGuardrailRequest"; -const _GGRe = "GetGuardrailResponse"; -const _GIM = "GetImportedModel"; -const _GIMR = "GetImportedModelRequest"; -const _GIMRe = "GetImportedModelResponse"; -const _GIP = "GetInferenceProfile"; -const _GIPR = "GetInferenceProfileRequest"; -const _GIPRe = "GetInferenceProfileResponse"; -const _GM = "GuardrailModality"; -const _GMCJ = "GetModelCopyJob"; -const _GMCJR = "GetModelCopyJobRequest"; -const _GMCJRe = "GetModelCopyJobResponse"; -const _GMCJRet = "GetModelCustomizationJobRequest"; -const _GMCJReto = "GetModelCustomizationJobResponse"; -const _GMCJe = "GetModelCustomizationJob"; -const _GMIJ = "GetModelImportJob"; -const _GMIJR = "GetModelImportJobRequest"; -const _GMIJRe = "GetModelImportJobResponse"; -const _GMIJRet = "GetModelInvocationJobRequest"; -const _GMIJReto = "GetModelInvocationJobResponse"; -const _GMIJe = "GetModelInvocationJob"; -const _GMILC = "GetModelInvocationLoggingConfiguration"; -const _GMILCR = "GetModelInvocationLoggingConfigurationRequest"; -const _GMILCRe = "GetModelInvocationLoggingConfigurationResponse"; -const _GMME = "GetMarketplaceModelEndpoint"; -const _GMMER = "GetMarketplaceModelEndpointRequest"; -const _GMMERe = "GetMarketplaceModelEndpointResponse"; -const _GMW = "GuardrailManagedWords"; -const _GMWC = "GuardrailManagedWordsConfig"; -const _GMWL = "GuardrailManagedWordLists"; -const _GMWLC = "GuardrailManagedWordListsConfig"; -const _GMu = "GuardrailModalities"; -const _GN = "GuardrailName"; -const _GPE = "GuardrailPiiEntity"; -const _GPEC = "GuardrailPiiEntityConfig"; -const _GPECu = "GuardrailPiiEntitiesConfig"; -const _GPEu = "GuardrailPiiEntities"; -const _GPMT = "GetProvisionedModelThroughput"; -const _GPMTR = "GetProvisionedModelThroughputRequest"; -const _GPMTRe = "GetProvisionedModelThroughputResponse"; -const _GPR = "GetPromptRouter"; -const _GPRR = "GetPromptRouterRequest"; -const _GPRRe = "GetPromptRouterResponse"; -const _GR = "GuardrailRegex"; -const _GRC = "GuardrailRegexConfig"; -const _GRCu = "GuardrailRegexesConfig"; -const _GRu = "GuardrailRegexes"; -const _GS = "GuardrailSummary"; -const _GSIP = "GuardrailSensitiveInformationPolicy"; -const _GSIPC = "GuardrailSensitiveInformationPolicyConfig"; -const _GSR = "GuardrailStatusReason"; -const _GSRu = "GuardrailStatusReasons"; -const _GSu = "GuardrailSummaries"; -const _GT = "GuardrailTopic"; -const _GTA = "GuardrailTopicAction"; -const _GTC = "GuardrailTopicConfig"; -const _GTCu = "GuardrailTopicsConfig"; -const _GTD = "GuardrailTopicDefinition"; -const _GTE = "GuardrailTopicExample"; -const _GTEu = "GuardrailTopicExamples"; -const _GTN = "GuardrailTopicName"; -const _GTP = "GuardrailTopicPolicy"; -const _GTPC = "GuardrailTopicPolicyConfig"; -const _GTT = "GuardrailTopicsTier"; -const _GTTC = "GuardrailTopicsTierConfig"; -const _GTTN = "GuardrailTopicsTierName"; -const _GTu = "GuardrailTopics"; -const _GUCFMA = "GetUseCaseForModelAccess"; -const _GUCFMAR = "GetUseCaseForModelAccessRequest"; -const _GUCFMARe = "GetUseCaseForModelAccessResponse"; -const _GW = "GuardrailWord"; -const _GWA = "GuardrailWordAction"; -const _GWC = "GuardrailWordConfig"; -const _GWCu = "GuardrailWordsConfig"; -const _GWP = "GuardrailWordPolicy"; -const _GWPC = "GuardrailWordPolicyConfig"; -const _GWu = "GuardrailWords"; -const _HEC = "HumanEvaluationConfig"; -const _HECM = "HumanEvaluationCustomMetric"; -const _HECMu = "HumanEvaluationCustomMetrics"; -const _HTI = "HumanTaskInstructions"; -const _HWC = "HumanWorkflowConfig"; -const _I = "Identifier"; -const _IFC = "ImplicitFilterConfiguration"; -const _ILC = "InvocationLogsConfig"; -const _ILS = "InvocationLogSource"; -const _IMS = "ImportedModelSummary"; -const _IMSL = "ImportedModelSummaryList"; -const _IPD = "InferenceProfileDescription"; -const _IPM = "InferenceProfileModel"; -const _IPMS = "InferenceProfileModelSource"; -const _IPMn = "InferenceProfileModels"; -const _IPS = "InferenceProfileSummary"; -const _IPSn = "InferenceProfileSummaries"; -const _ISE = "InternalServerException"; -const _KBC = "KnowledgeBaseConfig"; -const _KBRAGC = "KnowledgeBaseRetrieveAndGenerateConfiguration"; -const _KBRC = "KnowledgeBaseRetrievalConfiguration"; -const _KBVSC = "KnowledgeBaseVectorSearchConfiguration"; -const _KIC = "KbInferenceConfig"; -const _LARP = "ListAutomatedReasoningPolicies"; -const _LARPBW = "ListAutomatedReasoningPolicyBuildWorkflows"; -const _LARPBWR = "ListAutomatedReasoningPolicyBuildWorkflowsRequest"; -const _LARPBWRi = "ListAutomatedReasoningPolicyBuildWorkflowsResponse"; -const _LARPR = "ListAutomatedReasoningPoliciesRequest"; -const _LARPRi = "ListAutomatedReasoningPoliciesResponse"; -const _LARPTC = "ListAutomatedReasoningPolicyTestCases"; -const _LARPTCR = "ListAutomatedReasoningPolicyTestCasesRequest"; -const _LARPTCRi = "ListAutomatedReasoningPolicyTestCasesResponse"; -const _LARPTR = "ListAutomatedReasoningPolicyTestResults"; -const _LARPTRR = "ListAutomatedReasoningPolicyTestResultsRequest"; -const _LARPTRRi = "ListAutomatedReasoningPolicyTestResultsResponse"; -const _LC = "LoggingConfig"; -const _LCM = "ListCustomModels"; -const _LCMD = "ListCustomModelDeployments"; -const _LCMDR = "ListCustomModelDeploymentsRequest"; -const _LCMDRi = "ListCustomModelDeploymentsResponse"; -const _LCMR = "ListCustomModelsRequest"; -const _LCMRi = "ListCustomModelsResponse"; -const _LEJ = "ListEvaluationJobs"; -const _LEJR = "ListEvaluationJobsRequest"; -const _LEJRi = "ListEvaluationJobsResponse"; -const _LFM = "ListFoundationModels"; -const _LFMAO = "ListFoundationModelAgreementOffers"; -const _LFMAOR = "ListFoundationModelAgreementOffersRequest"; -const _LFMAORi = "ListFoundationModelAgreementOffersResponse"; -const _LFMR = "ListFoundationModelsRequest"; -const _LFMRi = "ListFoundationModelsResponse"; -const _LG = "ListGuardrails"; -const _LGR = "ListGuardrailsRequest"; -const _LGRi = "ListGuardrailsResponse"; -const _LIM = "ListImportedModels"; -const _LIMR = "ListImportedModelsRequest"; -const _LIMRi = "ListImportedModelsResponse"; -const _LIP = "ListInferenceProfiles"; -const _LIPR = "ListInferenceProfilesRequest"; -const _LIPRi = "ListInferenceProfilesResponse"; -const _LMCJ = "ListModelCopyJobs"; -const _LMCJR = "ListModelCopyJobsRequest"; -const _LMCJRi = "ListModelCopyJobsResponse"; -const _LMCJRis = "ListModelCustomizationJobsRequest"; -const _LMCJRist = "ListModelCustomizationJobsResponse"; -const _LMCJi = "ListModelCustomizationJobs"; -const _LMIJ = "ListModelImportJobs"; -const _LMIJR = "ListModelImportJobsRequest"; -const _LMIJRi = "ListModelImportJobsResponse"; -const _LMIJRis = "ListModelInvocationJobsRequest"; -const _LMIJRist = "ListModelInvocationJobsResponse"; -const _LMIJi = "ListModelInvocationJobs"; -const _LMME = "ListMarketplaceModelEndpoints"; -const _LMMER = "ListMarketplaceModelEndpointsRequest"; -const _LMMERi = "ListMarketplaceModelEndpointsResponse"; -const _LPMT = "ListProvisionedModelThroughputs"; -const _LPMTR = "ListProvisionedModelThroughputsRequest"; -const _LPMTRi = "ListProvisionedModelThroughputsResponse"; -const _LPR = "ListPromptRouters"; -const _LPRR = "ListPromptRoutersRequest"; -const _LPRRi = "ListPromptRoutersResponse"; -const _LT = "LegalTerm"; -const _LTFR = "ListTagsForResource"; -const _LTFRR = "ListTagsForResourceRequest"; -const _LTFRRi = "ListTagsForResourceResponse"; -const _M = "Message"; -const _MAS = "MetadataAttributeSchema"; -const _MASL = "MetadataAttributeSchemaList"; -const _MCFR = "MetadataConfigurationForReranking"; -const _MCJS = "ModelCopyJobSummary"; -const _MCJSo = "ModelCustomizationJobSummary"; -const _MCJSod = "ModelCopyJobSummaries"; -const _MCJSode = "ModelCustomizationJobSummaries"; -const _MDS = "ModelDataSource"; -const _MIJIDC = "ModelInvocationJobInputDataConfig"; -const _MIJODC = "ModelInvocationJobOutputDataConfig"; -const _MIJS = "ModelImportJobSummary"; -const _MIJSIDC = "ModelInvocationJobS3InputDataConfig"; -const _MIJSODC = "ModelInvocationJobS3OutputDataConfig"; -const _MIJSo = "ModelInvocationJobSummary"; -const _MIJSod = "ModelImportJobSummaries"; -const _MIJSode = "ModelInvocationJobSummaries"; -const _MME = "MarketplaceModelEndpoint"; -const _MMES = "MarketplaceModelEndpointSummary"; -const _MMESa = "MarketplaceModelEndpointSummaries"; -const _MN = "MetricName"; -const _O = "Offer"; -const _OC = "OrchestrationConfiguration"; -const _ODC = "OutputDataConfig"; -const _Of = "Offers"; -const _PC = "PerformanceConfiguration"; -const _PMILC = "PutModelInvocationLoggingConfiguration"; -const _PMILCR = "PutModelInvocationLoggingConfigurationRequest"; -const _PMILCRu = "PutModelInvocationLoggingConfigurationResponse"; -const _PMS = "ProvisionedModelSummary"; -const _PMSr = "ProvisionedModelSummaries"; -const _PRD = "PromptRouterDescription"; -const _PRS = "PromptRouterSummary"; -const _PRSr = "PromptRouterSummaries"; -const _PRTM = "PromptRouterTargetModel"; -const _PRTMr = "PromptRouterTargetModels"; -const _PT = "PricingTerm"; -const _PTr = "PromptTemplate"; -const _PUCFMA = "PutUseCaseForModelAccess"; -const _PUCFMAR = "PutUseCaseForModelAccessRequest"; -const _PUCFMARu = "PutUseCaseForModelAccessResponse"; -const _QTC = "QueryTransformationConfiguration"; -const _RAGC = "RetrieveAndGenerateConfiguration"; -const _RAGCo = "RAGConfig"; -const _RC = "RetrieveConfig"; -const _RCa = "RagConfigs"; -const _RCat = "RateCard"; -const _RCo = "RoutingCriteria"; -const _RF = "RetrievalFilter"; -const _RFL = "RetrievalFilterList"; -const _RIUE = "ResourceInUseException"; -const _RMBF = "RequestMetadataBaseFilters"; -const _RMF = "RequestMetadataFilters"; -const _RMFL = "RequestMetadataFiltersList"; -const _RMM = "RequestMetadataMap"; -const _RMME = "RegisterMarketplaceModelEndpoint"; -const _RMMER = "RegisterMarketplaceModelEndpointRequest"; -const _RMMERe = "RegisterMarketplaceModelEndpointResponse"; -const _RMSMC = "RerankingMetadataSelectiveModeConfiguration"; -const _RNFE = "ResourceNotFoundException"; -const _RS = "RatingScale"; -const _RSI = "RatingScaleItem"; -const _RSIV = "RatingScaleItemValue"; -const _SARPBW = "StartAutomatedReasoningPolicyBuildWorkflow"; -const _SARPBWR = "StartAutomatedReasoningPolicyBuildWorkflowRequest"; -const _SARPBWRt = "StartAutomatedReasoningPolicyBuildWorkflowResponse"; -const _SARPTW = "StartAutomatedReasoningPolicyTestWorkflow"; -const _SARPTWR = "StartAutomatedReasoningPolicyTestWorkflowRequest"; -const _SARPTWRt = "StartAutomatedReasoningPolicyTestWorkflowResponse"; -const _SC = "S3Config"; -const _SD = "StatusDetails"; -const _SDS = "S3DataSource"; -const _SEJ = "StopEvaluationJob"; -const _SEJR = "StopEvaluationJobRequest"; -const _SEJRt = "StopEvaluationJobResponse"; -const _SMCJ = "StopModelCustomizationJob"; -const _SMCJR = "StopModelCustomizationJobRequest"; -const _SMCJRt = "StopModelCustomizationJobResponse"; -const _SME = "SageMakerEndpoint"; -const _SMIJ = "StopModelInvocationJob"; -const _SMIJR = "StopModelInvocationJobRequest"; -const _SMIJRt = "StopModelInvocationJobResponse"; -const _SOD = "S3ObjectDoc"; -const _SQEE = "ServiceQuotaExceededException"; -const _ST = "SupportTerm"; -const _SUE = "ServiceUnavailableException"; -const _T = "Tag"; -const _TD = "TermDetails"; -const _TDC = "TrainingDataConfig"; -const _TDr = "TrainingDetails"; -const _TE = "ThrottlingException"; -const _TIC = "TextInferenceConfig"; -const _TL = "TagList"; -const _TM = "TrainingMetrics"; -const _TMC = "TeacherModelConfig"; -const _TMTE = "TooManyTagsException"; -const _TPT = "TextPromptTemplate"; -const _TR = "TagResource"; -const _TRR = "TagResourceRequest"; -const _TRRa = "TagResourceResponse"; -const _UARP = "UpdateAutomatedReasoningPolicy"; -const _UARPA = "UpdateAutomatedReasoningPolicyAnnotations"; -const _UARPAR = "UpdateAutomatedReasoningPolicyAnnotationsRequest"; -const _UARPARp = "UpdateAutomatedReasoningPolicyAnnotationsResponse"; -const _UARPR = "UpdateAutomatedReasoningPolicyRequest"; -const _UARPRp = "UpdateAutomatedReasoningPolicyResponse"; -const _UARPTC = "UpdateAutomatedReasoningPolicyTestCase"; -const _UARPTCR = "UpdateAutomatedReasoningPolicyTestCaseRequest"; -const _UARPTCRp = "UpdateAutomatedReasoningPolicyTestCaseResponse"; -const _UG = "UpdateGuardrail"; -const _UGR = "UpdateGuardrailRequest"; -const _UGRp = "UpdateGuardrailResponse"; -const _UMME = "UpdateMarketplaceModelEndpoint"; -const _UMMER = "UpdateMarketplaceModelEndpointRequest"; -const _UMMERp = "UpdateMarketplaceModelEndpointResponse"; -const _UPMT = "UpdateProvisionedModelThroughput"; -const _UPMTR = "UpdateProvisionedModelThroughputRequest"; -const _UPMTRp = "UpdateProvisionedModelThroughputResponse"; -const _UR = "UntagResource"; -const _URR = "UntagResourceRequest"; -const _URRn = "UntagResourceResponse"; -const _V = "Validator"; -const _VC = "VpcConfig"; -const _VD = "ValidationDetails"; -const _VDC = "ValidationDataConfig"; -const _VE = "ValidationException"; -const _VM = "ValidatorMetric"; -const _VMa = "ValidationMetrics"; -const _VSBRC = "VectorSearchBedrockRerankingConfiguration"; -const _VSBRMC = "VectorSearchBedrockRerankingModelConfiguration"; -const _VSRC = "VectorSearchRerankingConfiguration"; -const _VT = "ValidityTerm"; -const _Va = "Validators"; -const _a = "annotation"; -const _aA = "agreementAvailability"; -const _aAn = "andAll"; -const _aD = "agreementDuration"; -const _aE = "alternateExpression"; -const _aEc = "acceptEula"; -const _aMRF = "additionalModelRequestFields"; -const _aR = "addRule"; -const _aRFNL = "addRuleFromNaturalLanguage"; -const _aRP = "automatedReasoningPolicy"; -const _aRPBWS = "automatedReasoningPolicyBuildWorkflowSummaries"; -const _aRPC = "automatedReasoningPolicyConfig"; -const _aRPS = "automatedReasoningPolicySummaries"; -const _aS = "authorizationStatus"; -const _aSH = "annotationSetHash"; -const _aT = "applicationType"; -const _aTE = "applicationTypeEquals"; -const _aTFR = "aggregatedTestFindingsResult"; -const _aTV = "addTypeValue"; -const _aTd = "addType"; -const _aTs = "assetType"; -const _aV = "addVariable"; -const _ac = "action"; -const _an = "annotations"; -const _ar = "arn"; -const _au = "automated"; -const _bC = "byteContent"; -const _bCT = "byCustomizationType"; -const _bEM = "bedrockEvaluatorModels"; -const _bIM = "blockedInputMessaging"; -const _bIT = "byInferenceType"; -const _bKBI = "bedrockKnowledgeBaseIdentifiers"; -const _bL = "buildLog"; -const _bM = "bedrockModel"; -const _bMA = "baseModelArn"; -const _bMAE = "baseModelArnEquals"; -const _bMI = "baseModelIdentifier"; -const _bMIe = "bedrockModelIdentifiers"; -const _bMN = "baseModelName"; -const _bN = "bucketName"; -const _bOM = "blockedOutputsMessaging"; -const _bOMy = "byOutputModality"; -const _bP = "byProvider"; -const _bRC = "bedrockRerankingConfiguration"; -const _bS = "buildSteps"; -const _bWA = "buildWorkflowAssets"; -const _bWI = "buildWorkflowId"; -const _bWT = "buildWorkflowType"; -const _c = "client"; -const _cA = "createdAt"; -const _cAr = "createdAfter"; -const _cB = "createdBefore"; -const _cC = "customizationConfig"; -const _cD = "commitmentDuration"; -const _cEKI = "customerEncryptionKeyId"; -const _cET = "commitmentExpirationTime"; -const _cF = "copyFrom"; -const _cFS = "claimsFalseScenario"; -const _cGP = "contextualGroundingPolicy"; -const _cGPC = "contextualGroundingPolicyConfig"; -const _cM = "customMetrics"; -const _cMA = "customModelArn"; -const _cMC = "customMetricConfig"; -const _cMD = "customMetricDefinition"; -const _cMDA = "customModelDeploymentArn"; -const _cMDI = "customModelDeploymentIdentifier"; -const _cMDN = "customModelDeploymentName"; -const _cMEMI = "customMetricsEvaluatorModelIdentifiers"; -const _cMKKI = "customModelKmsKeyId"; -const _cMN = "customModelName"; -const _cMT = "customModelTags"; -const _cMU = "customModelUnits"; -const _cMUPMC = "customModelUnitsPerModelCopy"; -const _cMUV = "customModelUnitsVersion"; -const _cP = "contentPolicy"; -const _cPC = "contentPolicyConfig"; -const _cR = "contradictingRules"; -const _cRC = "crossRegionConfig"; -const _cRD = "crossRegionDetails"; -const _cRT = "clientRequestToken"; -const _cRo = "conflictingRules"; -const _cS = "customizationsSupported"; -const _cT = "confidenceThreshold"; -const _cTA = "creationTimeAfter"; -const _cTB = "creationTimeBefore"; -const _cTS = "claimsTrueScenario"; -const _cTo = "contentType"; -const _cTr = "creationTime"; -const _cTu = "customizationType"; -const _cWC = "cloudWatchConfig"; -const _cl = "claims"; -const _co = "confidence"; -const _cod = "code"; -const _con = "context"; -const _cont = "content"; -const _d = "description"; -const _dC = "distillationConfig"; -const _dCT = "documentContentType"; -const _dD = "documentDescription"; -const _dH = "definitionHash"; -const _dL = "datasetLocation"; -const _dMA = "desiredModelArn"; -const _dMC = "datasetMetricConfigs"; -const _dMI = "desiredModelId"; -const _dMU = "desiredModelUnits"; -const _dN = "documentName"; -const _dPD = "dataProcessingDetails"; -const _dPMN = "desiredProvisionedModelName"; -const _dR = "deleteRule"; -const _dRS = "disjointRuleSets"; -const _dS = "differenceScenarios"; -const _dT = "deleteType"; -const _dTV = "deleteTypeValue"; -const _dV = "deleteVariable"; -const _da = "data"; -const _dat = "dataset"; -const _de = "definition"; -const _di = "dimension"; -const _do = "document"; -const _doc = "documents"; -const _e = "error"; -const _eA = "endpointArn"; -const _eAFR = "expectedAggregatedFindingsResult"; -const _eAn = "entitlementAvailability"; -const _eC = "evaluationConfig"; -const _eCn = "endpointConfig"; -const _eDDE = "embeddingDataDeliveryEnabled"; -const _eI = "endpointIdentifier"; -const _eJ = "evaluationJobs"; -const _eM = "errorMessage"; -const _eMC = "evaluatorModelConfig"; -const _eMI = "evaluatorModelIdentifiers"; -const _eN = "endpointName"; -const _eR = "expectedResult"; -const _eRx = "executionRole"; -const _eS = "endpointStatus"; -const _eSC = "externalSourcesConfiguration"; -const _eSM = "endpointStatusMessage"; -const _eT = "endTime"; -const _eTT = "evaluationTaskTypes"; -const _en = "entries"; -const _ena = "enabled"; -const _eq = "equals"; -const _er = "errors"; -const _ex = "expression"; -const _exa = "examples"; -const _f = "feedback"; -const _fC = "filtersConfig"; -const _fD = "formData"; -const _fDA = "flowDefinitionArn"; -const _fM = "fallbackModel"; -const _fMA = "foundationModelArn"; -const _fMAE = "foundationModelArnEquals"; -const _fMa = "failureMessage"; -const _fMai = "failureMessages"; -const _fN = "fieldName"; -const _fR = "failureRecommendations"; -const _fTE = "fieldsToExclude"; -const _fTI = "fieldsToInclude"; -const _fV = "floatValue"; -const _fi = "filters"; -const _fil = "filter"; -const _fo = "force"; -const _g = "guardrails"; -const _gA = "guardrailArn"; -const _gC = "guardContent"; -const _gCe = "generationConfiguration"; -const _gCu = "guardrailConfiguration"; -const _gI = "guardrailId"; -const _gIu = "guardrailIdentifier"; -const _gPA = "guardrailProfileArn"; -const _gPI = "guardrailProfileIdentifier"; -const _gPIu = "guardrailProfileId"; -const _gT = "greaterThan"; -const _gTC = "generatedTestCases"; -const _gTOE = "greaterThanOrEquals"; -const _gV = "guardrailVersion"; -const _h = "human"; -const _hE = "httpError"; -const _hH = "httpHeader"; -const _hP = "hyperParameters"; -const _hQ = "httpQuery"; -const _hWC = "humanWorkflowConfig"; -const _ht = "http"; -const _i = "id"; -const _iA = "inputAction"; -const _iC = "inferenceConfig"; -const _iCS = "inferenceConfigSummary"; -const _iCn = "ingestContent"; -const _iDC = "inputDataConfig"; -const _iDDE = "imageDataDeliveryEnabled"; -const _iE = "inputEnabled"; -const _iFC = "implicitFilterConfiguration"; -const _iIC = "initialInstanceCount"; -const _iJS = "invocationJobSummaries"; -const _iLC = "invocationLogsConfig"; -const _iLS = "invocationLogSource"; -const _iM = "inputModalities"; -const _iMA = "importedModelArn"; -const _iMKKA = "importedModelKmsKeyArn"; -const _iMKKI = "importedModelKmsKeyId"; -const _iMN = "importedModelName"; -const _iMT = "importedModelTags"; -const _iO = "isOwned"; -const _iP = "inferenceParams"; -const _iPA = "inferenceProfileArn"; -const _iPI = "inferenceProfileIdentifier"; -const _iPIn = "inferenceProfileId"; -const _iPN = "inferenceProfileName"; -const _iPS = "inferenceProfileSummaries"; -const _iS = "instructSupported"; -const _iSI = "inferenceSourceIdentifier"; -const _iSn = "inputStrength"; -const _iT = "instanceType"; -const _iTS = "inferenceTypesSupported"; -const _iTd = "idempotencyToken"; -const _id = "identifier"; -const _im = "impossible"; -const _in = "instructions"; -const _in_ = "in"; -const _inv = "invalid"; -const _jA = "jobArn"; -const _jD = "jobDescription"; -const _jET = "jobExpirationTime"; -const _jI = "jobIdentifier"; -const _jIo = "jobIdentifiers"; -const _jN = "jobName"; -const _jS = "jobStatus"; -const _jSo = "jobSummaries"; -const _jT = "jobTags"; -const _jTo = "jobType"; -const _k = "key"; -const _kBC = "knowledgeBaseConfiguration"; -const _kBCn = "knowledgeBaseConfig"; -const _kBI = "knowledgeBaseId"; -const _kBRC = "knowledgeBaseRetrievalConfiguration"; -const _kEK = "kmsEncryptionKey"; -const _kIC = "kbInferenceConfig"; -const _kKA = "kmsKeyArn"; -const _kKI = "kmsKeyId"; -const _kP = "keyPrefix"; -const _l = "logic"; -const _lC = "loggingConfig"; -const _lCi = "listContains"; -const _lDDSC = "largeDataDeliveryS3Config"; -const _lGN = "logGroupName"; -const _lMT = "lastModifiedTime"; -const _lT = "legalTerm"; -const _lTOE = "lessThanOrEquals"; -const _lTe = "lessThan"; -const _lUA = "lastUpdatedAt"; -const _lUASH = "lastUpdatedAnnotationSetHash"; -const _lUDH = "lastUpdatedDefinitionHash"; -const _lW = "logicWarning"; -const _la = "latency"; -const _m = "message"; -const _mA = "modelArn"; -const _mAE = "modelArnEquals"; -const _mAe = "metadataAttributes"; -const _mAo = "modelArchitecture"; -const _mC = "modelConfiguration"; -const _mCJS = "modelCopyJobSummaries"; -const _mCJSo = "modelCustomizationJobSummaries"; -const _mCS = "modelConfigSummary"; -const _mCe = "metadataConfiguration"; -const _mD = "modelDetails"; -const _mDN = "modelDeploymentName"; -const _mDS = "modelDataSource"; -const _mDSo = "modelDeploymentSummaries"; -const _mI = "modelIdentifier"; -const _mIJS = "modelImportJobSummaries"; -const _mIo = "modelId"; -const _mIod = "modelIdentifiers"; -const _mKKA = "modelKmsKeyArn"; -const _mKKI = "modelKmsKeyId"; -const _mL = "modelLifecycle"; -const _mME = "marketplaceModelEndpoint"; -const _mMEa = "marketplaceModelEndpoints"; -const _mN = "modelName"; -const _mNe = "metricNames"; -const _mR = "maxResults"; -const _mRLFI = "maxResponseLengthForInference"; -const _mS = "modelSource"; -const _mSC = "modelSourceConfig"; -const _mSE = "modelSourceEquals"; -const _mSI = "modelSourceIdentifier"; -const _mSo = "modelStatus"; -const _mSod = "modelSummaries"; -const _mT = "messageType"; -const _mTa = "maxTokens"; -const _mTo = "modelTags"; -const _mU = "modelUnits"; -const _mWL = "managedWordLists"; -const _mWLC = "managedWordListsConfig"; -const _me = "messages"; -const _mo = "models"; -const _mu = "mutation"; -const _n = "name"; -const _nC = "nameContains"; -const _nE = "notEquals"; -const _nI = "notIn"; -const _nL = "naturalLanguage"; -const _nN = "newName"; -const _nOR = "numberOfResults"; -const _nORR = "numberOfRerankedResults"; -const _nT = "nextToken"; -const _nTo = "noTranslations"; -const _nV = "newValue"; -const _o = "options"; -const _oA = "outputAction"; -const _oAI = "ownerAccountId"; -const _oAr = "orAll"; -const _oC = "orchestrationConfiguration"; -const _oDC = "outputDataConfig"; -const _oE = "outputEnabled"; -const _oI = "offerId"; -const _oM = "outputModalities"; -const _oMA = "outputModelArn"; -const _oMKKA = "outputModelKmsKeyArn"; -const _oMN = "outputModelName"; -const _oMNC = "outputModelNameContains"; -const _oS = "outputStrength"; -const _oST = "overrideSearchType"; -const _oT = "offerToken"; -const _oTf = "offerType"; -const _of = "offers"; -const _p = "premises"; -const _pA = "policyArn"; -const _pC = "performanceConfig"; -const _pD = "policyDefinition"; -const _pDR = "policyDefinitionRule"; -const _pDT = "policyDefinitionType"; -const _pDV = "policyDefinitionVariable"; -const _pE = "priorElement"; -const _pEC = "piiEntitiesConfig"; -const _pEi = "piiEntities"; -const _pI = "policyId"; -const _pIS = "precomputedInferenceSource"; -const _pISI = "precomputedInferenceSourceIdentifiers"; -const _pMA = "provisionedModelArn"; -const _pMI = "provisionedModelId"; -const _pMN = "provisionedModelName"; -const _pMS = "provisionedModelSummaries"; -const _pN = "providerName"; -const _pRA = "promptRouterArn"; -const _pRAo = "policyRepairAssets"; -const _pRN = "promptRouterName"; -const _pRS = "promptRouterSummaries"; -const _pRSC = "precomputedRagSourceConfig"; -const _pRSI = "precomputedRagSourceIdentifiers"; -const _pT = "promptTemplate"; -const _pVA = "policyVersionArn"; -const _pa = "pattern"; -const _pl = "planning"; -const _po = "policies"; -const _pr = "price"; -const _qC = "queryContent"; -const _qR = "qualityReport"; -const _qTC = "queryTransformationConfiguration"; -const _r = "rule"; -const _rA = "roleArn"; -const _rAGC = "retrieveAndGenerateConfig"; -const _rAGSC = "retrieveAndGenerateSourceConfig"; -const _rARN = "resourceARN"; -const _rAe = "regionAvailability"; -const _rC = "ruleCount"; -const _rCS = "ragConfigSummary"; -const _rCa = "rateCard"; -const _rCag = "ragConfigs"; -const _rCe = "regexesConfig"; -const _rCer = "rerankingConfiguration"; -const _rCet = "retrievalConfiguration"; -const _rCetr = "retrieveConfig"; -const _rCo = "routingCriteria"; -const _rI = "ruleId"; -const _rIa = "ragIdentifiers"; -const _rIu = "ruleIds"; -const _rM = "ratingMethod"; -const _rMF = "requestMetadataFilters"; -const _rN = "resourceName"; -const _rPD = "refundPolicyDescription"; -const _rQD = "responseQualityDifference"; -const _rS = "ratingScale"; -const _rSC = "retrieveSourceConfig"; -const _rSI = "ragSourceIdentifier"; -const _rSS = "responseStreamingSupported"; -const _re = "regexes"; -const _ru = "rules"; -const _s = "status"; -const _sAE = "sourceAccountEquals"; -const _sAI = "sourceAccountId"; -const _sB = "sortBy"; -const _sBO = "s3BucketOwner"; -const _sC = "s3Config"; -const _sCo = "sourceContent"; -const _sCt = "stringContains"; -const _sD = "statusDetails"; -const _sDS = "s3DataSource"; -const _sE = "scenarioExpression"; -const _sEKI = "s3EncryptionKeyId"; -const _sEt = "statusEquals"; -const _sGI = "securityGroupIds"; -const _sI = "subnetIds"; -const _sIDC = "s3InputDataConfig"; -const _sIF = "s3InputFormat"; -const _sIP = "sensitiveInformationPolicy"; -const _sIPC = "sensitiveInformationPolicyConfig"; -const _sL = "s3Location"; -const _sM = "statusMessage"; -const _sMA = "sourceModelArn"; -const _sMAE = "sourceModelArnEquals"; -const _sMC = "selectiveModeConfiguration"; -const _sMN = "sourceModelName"; -const _sMa = "sageMaker"; -const _sMe = "selectionMode"; -const _sO = "sortOrder"; -const _sODC = "s3OutputDataConfig"; -const _sR = "supportingRules"; -const _sRt = "statusReasons"; -const _sS = "stopSequences"; -const _sT = "sourceType"; -const _sTA = "submitTimeAfter"; -const _sTB = "submitTimeBefore"; -const _sTu = "submitTime"; -const _sTup = "supportTerm"; -const _sU = "s3Uri"; -const _sV = "stringValue"; -const _sW = "startsWith"; -const _sa = "satisfiable"; -const _sc = "scenario"; -const _se = "server"; -const _sm = "smithy.ts.sdk.synthetic.com.amazonaws.bedrock"; -const _so = "sources"; -const _st = "statements"; -const _t = "translation"; -const _tA = "translationAmbiguous"; -const _tC = "typeCount"; -const _tCI = "testCaseId"; -const _tCIe = "testCaseIds"; -const _tCe = "testCase"; -const _tCes = "testCases"; -const _tCi = "tierConfig"; -const _tCo = "topicsConfig"; -const _tCoo = "tooComplex"; -const _tD = "termDetails"; -const _tDC = "trainingDataConfig"; -const _tDDE = "textDataDeliveryEnabled"; -const _tDIH = "timeoutDurationInHours"; -const _tDr = "trainingDetails"; -const _tE = "typeEquals"; -const _tF = "testFindings"; -const _tIC = "textInferenceConfig"; -const _tK = "tagKeys"; -const _tL = "trainingLoss"; -const _tM = "trainingMetrics"; -const _tMA = "targetModelArn"; -const _tMC = "teacherModelConfig"; -const _tMI = "teacherModelIdentifier"; -const _tMKKA = "targetModelKmsKeyArn"; -const _tMN = "targetModelName"; -const _tMNC = "targetModelNameContains"; -const _tMT = "targetModelTags"; -const _tN = "typeName"; -const _tNi = "tierName"; -const _tP = "topicPolicy"; -const _tPC = "topicPolicyConfig"; -const _tPT = "textPromptTemplate"; -const _tPo = "topP"; -const _tR = "testResult"; -const _tRR = "testRunResult"; -const _tRS = "testRunStatus"; -const _tRe = "testResults"; -const _tT = "taskType"; -const _ta = "tags"; -const _te = "text"; -const _tem = "temperature"; -const _th = "threshold"; -const _ti = "tier"; -const _to = "topics"; -const _tr = "translations"; -const _ty = "type"; -const _typ = "types"; -const _u = "unit"; -const _uA = "updatedAt"; -const _uBPT = "usageBasedPricingTerm"; -const _uC = "untranslatedClaims"; -const _uFRF = "updateFromRulesFeedback"; -const _uFSF = "updateFromScenarioFeedback"; -const _uP = "untranslatedPremises"; -const _uPR = "usePromptResponse"; -const _uR = "updateRule"; -const _uT = "unusedTypes"; -const _uTV = "unusedTypeValues"; -const _uTVp = "updateTypeValue"; -const _uTp = "updateType"; -const _uV = "unusedVariables"; -const _uVp = "updateVariable"; -const _ur = "url"; -const _uri = "uri"; -const _v = "values"; -const _vC = "variableCount"; -const _vCp = "vpcConfig"; -const _vD = "validationDetails"; -const _vDC = "validationDataConfig"; -const _vDDE = "videoDataDeliveryEnabled"; -const _vL = "validationLoss"; -const _vM = "validationMetrics"; -const _vN = "valueName"; -const _vSC = "vectorSearchConfiguration"; -const _vT = "validityTerm"; -const _va = "value"; -const _val = "validators"; -const _vali = "valid"; -const _var = "variable"; -const _vari = "variables"; -const _ve = "version"; -const _vp = "vpc"; -const _w = "words"; -const _wC = "workflowContent"; -const _wCo = "wordsConfig"; -const _wP = "wordPolicy"; -const _wPC = "wordPolicyConfig"; -const _xact = "x-amz-client-token"; -const n0 = "com.amazonaws.bedrock"; -var AutomatedReasoningLogicStatementContent = [0, n0, _ARLSC, 8, 0]; -var AutomatedReasoningNaturalLanguageStatementContent = [0, n0, _ARNLSC, 8, 0]; -var AutomatedReasoningPolicyAnnotationFeedbackNaturalLanguage = [0, n0, _ARPAFNL, 8, 0]; -var AutomatedReasoningPolicyAnnotationIngestContent = [0, n0, _ARPAIC, 8, 0]; -var AutomatedReasoningPolicyAnnotationRuleNaturalLanguage = [0, n0, _ARPARNL, 8, 0]; -var AutomatedReasoningPolicyBuildDocumentBlob = [0, n0, _ARPBDB, 8, 21]; -var AutomatedReasoningPolicyBuildDocumentDescription = [0, n0, _ARPBDD, 8, 0]; -var AutomatedReasoningPolicyBuildDocumentName = [0, n0, _ARPBDN, 8, 0]; -var AutomatedReasoningPolicyDefinitionRuleAlternateExpression = [0, n0, _ARPDRAE, 8, 0]; -var AutomatedReasoningPolicyDefinitionRuleExpression = [0, n0, _ARPDRE, 8, 0]; -var AutomatedReasoningPolicyDefinitionTypeDescription = [0, n0, _ARPDTD, 8, 0]; -var AutomatedReasoningPolicyDefinitionTypeName = [0, n0, _ARPDTN, 8, 0]; -var AutomatedReasoningPolicyDefinitionTypeValueDescription = [0, n0, _ARPDTVD, 8, 0]; -var AutomatedReasoningPolicyDefinitionVariableDescription = [0, n0, _ARPDVD, 8, 0]; -var AutomatedReasoningPolicyDefinitionVariableName = [0, n0, _ARPDVN, 8, 0]; -var AutomatedReasoningPolicyDescription = [0, n0, _ARPD, 8, 0]; -var AutomatedReasoningPolicyName = [0, n0, _ARPN, 8, 0]; -var AutomatedReasoningPolicyScenarioAlternateExpression = [0, n0, _ARPSAE, 8, 0]; -var AutomatedReasoningPolicyScenarioExpression = [0, n0, _ARPSE, 8, 0]; -var AutomatedReasoningPolicyTestGuardContent = [0, n0, _ARPTGC, 8, 0]; -var AutomatedReasoningPolicyTestQueryContent = [0, n0, _ARPTQC, 8, 0]; -var ByteContentBlob = [0, n0, _BCB, 8, 21]; -var EvaluationDatasetName = [0, n0, _EDN, 8, 0]; -var EvaluationJobDescription = [0, n0, _EJD, 8, 0]; -var EvaluationJobIdentifier = [0, n0, _EJI, 8, 0]; -var EvaluationMetricDescription = [0, n0, _EMD, 8, 0]; -var EvaluationMetricName = [0, n0, _EMN, 8, 0]; -var EvaluationModelInferenceParams = [0, n0, _EMIP, 8, 0]; -var GuardrailBlockedMessaging = [0, n0, _GBM, 8, 0]; -var GuardrailContentFilterAction$1 = [0, n0, _GCFA, 8, 0]; -var GuardrailContentFiltersTierName$1 = [0, n0, _GCFTN, 8, 0]; -var GuardrailContextualGroundingAction$1 = [0, n0, _GCGA, 8, 0]; -var GuardrailDescription = [0, n0, _GD, 8, 0]; -var GuardrailFailureRecommendation = [0, n0, _GFR, 8, 0]; -var GuardrailModality$1 = [0, n0, _GM, 8, 0]; -var GuardrailName = [0, n0, _GN, 8, 0]; -var GuardrailStatusReason = [0, n0, _GSR, 8, 0]; -var GuardrailTopicAction$1 = [0, n0, _GTA, 8, 0]; -var GuardrailTopicDefinition = [0, n0, _GTD, 8, 0]; -var GuardrailTopicExample = [0, n0, _GTE, 8, 0]; -var GuardrailTopicName = [0, n0, _GTN, 8, 0]; -var GuardrailTopicsTierName$1 = [0, n0, _GTTN, 8, 0]; -var GuardrailWordAction$1 = [0, n0, _GWA, 8, 0]; -var HumanTaskInstructions = [0, n0, _HTI, 8, 0]; -var Identifier = [0, n0, _I, 8, 0]; -var InferenceProfileDescription = [0, n0, _IPD, 8, 0]; -var Message = [0, n0, _M, 8, 0]; -var MetricName = [0, n0, _MN, 8, 0]; -var PromptRouterDescription = [0, n0, _PRD, 8, 0]; -var TextPromptTemplate = [0, n0, _TPT, 8, 0]; -var AccessDeniedException = [ - -3, - n0, - _ADE, - { - [_e]: _c, - [_hE]: 403, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(AccessDeniedException, AccessDeniedException$1); -var AgreementAvailability = [3, n0, _AA, 0, [_s, _eM], [0, 0]]; -var AutomatedEvaluationConfig = [ - 3, - n0, - _AEC, - 0, - [_dMC, _eMC, _cMC], - [ - [() => EvaluationDatasetMetricConfigs, 0], - () => EvaluatorModelConfig, - [() => AutomatedEvaluationCustomMetricConfig, 0], - ], -]; -var AutomatedEvaluationCustomMetricConfig = [ - 3, - n0, - _AECMC, - 0, - [_cM, _eMC], - [[() => AutomatedEvaluationCustomMetrics, 0], () => CustomMetricEvaluatorModelConfig], -]; -var AutomatedReasoningCheckImpossibleFinding = [ - 3, - n0, - _ARCIF, - 0, - [_t, _cR, _lW], - [ - [() => AutomatedReasoningCheckTranslation, 0], - () => AutomatedReasoningCheckRuleList, - [() => AutomatedReasoningCheckLogicWarning, 0], - ], -]; -var AutomatedReasoningCheckInputTextReference = [ - 3, - n0, - _ARCITR, - 0, - [_te], - [[() => AutomatedReasoningNaturalLanguageStatementContent, 0]], -]; -var AutomatedReasoningCheckInvalidFinding = [ - 3, - n0, - _ARCIFu, - 0, - [_t, _cR, _lW], - [ - [() => AutomatedReasoningCheckTranslation, 0], - () => AutomatedReasoningCheckRuleList, - [() => AutomatedReasoningCheckLogicWarning, 0], - ], -]; -var AutomatedReasoningCheckLogicWarning = [ - 3, - n0, - _ARCLW, - 0, - [_ty, _p, _cl], - [0, [() => AutomatedReasoningLogicStatementList, 0], [() => AutomatedReasoningLogicStatementList, 0]], -]; -var AutomatedReasoningCheckNoTranslationsFinding = [3, n0, _ARCNTF, 0, [], []]; -var AutomatedReasoningCheckRule = [3, n0, _ARCR, 0, [_i, _pVA], [0, 0]]; -var AutomatedReasoningCheckSatisfiableFinding = [ - 3, - n0, - _ARCSF, - 0, - [_t, _cTS, _cFS, _lW], - [ - [() => AutomatedReasoningCheckTranslation, 0], - [() => AutomatedReasoningCheckScenario, 0], - [() => AutomatedReasoningCheckScenario, 0], - [() => AutomatedReasoningCheckLogicWarning, 0], - ], -]; -var AutomatedReasoningCheckScenario = [ - 3, - n0, - _ARCS, - 0, - [_st], - [[() => AutomatedReasoningLogicStatementList, 0]], -]; -var AutomatedReasoningCheckTooComplexFinding = [3, n0, _ARCTCF, 0, [], []]; -var AutomatedReasoningCheckTranslation = [ - 3, - n0, - _ARCT, - 0, - [_p, _cl, _uP, _uC, _co], - [ - [() => AutomatedReasoningLogicStatementList, 0], - [() => AutomatedReasoningLogicStatementList, 0], - [() => AutomatedReasoningCheckInputTextReferenceList, 0], - [() => AutomatedReasoningCheckInputTextReferenceList, 0], - 1, - ], -]; -var AutomatedReasoningCheckTranslationAmbiguousFinding = [ - 3, - n0, - _ARCTAF, - 0, - [_o, _dS], - [ - [() => AutomatedReasoningCheckTranslationOptionList, 0], - [() => AutomatedReasoningCheckDifferenceScenarioList, 0], - ], -]; -var AutomatedReasoningCheckTranslationOption = [ - 3, - n0, - _ARCTO, - 0, - [_tr], - [[() => AutomatedReasoningCheckTranslationList, 0]], -]; -var AutomatedReasoningCheckValidFinding = [ - 3, - n0, - _ARCVF, - 0, - [_t, _cTS, _sR, _lW], - [ - [() => AutomatedReasoningCheckTranslation, 0], - [() => AutomatedReasoningCheckScenario, 0], - () => AutomatedReasoningCheckRuleList, - [() => AutomatedReasoningCheckLogicWarning, 0], - ], -]; -var AutomatedReasoningLogicStatement = [ - 3, - n0, - _ARLS, - 0, - [_l, _nL], - [ - [() => AutomatedReasoningLogicStatementContent, 0], - [() => AutomatedReasoningNaturalLanguageStatementContent, 0], - ], -]; -var AutomatedReasoningPolicyAddRuleAnnotation = [ - 3, - n0, - _ARPARA, - 0, - [_ex], - [[() => AutomatedReasoningPolicyDefinitionRuleExpression, 0]], -]; -var AutomatedReasoningPolicyAddRuleFromNaturalLanguageAnnotation = [ - 3, - n0, - _ARPARFNLA, - 0, - [_nL], - [[() => AutomatedReasoningPolicyAnnotationRuleNaturalLanguage, 0]], -]; -var AutomatedReasoningPolicyAddRuleMutation = [ - 3, - n0, - _ARPARM, - 0, - [_r], - [[() => AutomatedReasoningPolicyDefinitionRule, 0]], -]; -var AutomatedReasoningPolicyAddTypeAnnotation = [ - 3, - n0, - _ARPATA, - 0, - [_n, _d, _v], - [ - [() => AutomatedReasoningPolicyDefinitionTypeName, 0], - [() => AutomatedReasoningPolicyDefinitionTypeDescription, 0], - [() => AutomatedReasoningPolicyDefinitionTypeValueList, 0], - ], -]; -var AutomatedReasoningPolicyAddTypeMutation = [ - 3, - n0, - _ARPATM, - 0, - [_ty], - [[() => AutomatedReasoningPolicyDefinitionType, 0]], -]; -var AutomatedReasoningPolicyAddTypeValue = [ - 3, - n0, - _ARPATV, - 0, - [_va, _d], - [0, [() => AutomatedReasoningPolicyDefinitionTypeValueDescription, 0]], -]; -var AutomatedReasoningPolicyAddVariableAnnotation = [ - 3, - n0, - _ARPAVA, - 0, - [_n, _ty, _d], - [ - [() => AutomatedReasoningPolicyDefinitionVariableName, 0], - [() => AutomatedReasoningPolicyDefinitionTypeName, 0], - [() => AutomatedReasoningPolicyDefinitionVariableDescription, 0], - ], -]; -var AutomatedReasoningPolicyAddVariableMutation = [ - 3, - n0, - _ARPAVM, - 0, - [_var], - [[() => AutomatedReasoningPolicyDefinitionVariable, 0]], -]; -var AutomatedReasoningPolicyBuildLog = [ - 3, - n0, - _ARPBL, - 0, - [_en], - [[() => AutomatedReasoningPolicyBuildLogEntryList, 0]], -]; -var AutomatedReasoningPolicyBuildLogEntry = [ - 3, - n0, - _ARPBLE, - 0, - [_a, _s, _bS], - [[() => AutomatedReasoningPolicyAnnotation, 0], 0, [() => AutomatedReasoningPolicyBuildStepList, 0]], -]; -var AutomatedReasoningPolicyBuildStep = [ - 3, - n0, - _ARPBS, - 0, - [_con, _pE, _me], - [ - [() => AutomatedReasoningPolicyBuildStepContext, 0], - [() => AutomatedReasoningPolicyDefinitionElement, 0], - () => AutomatedReasoningPolicyBuildStepMessageList, - ], -]; -var AutomatedReasoningPolicyBuildStepMessage = [3, n0, _ARPBSM, 0, [_m, _mT], [0, 0]]; -var AutomatedReasoningPolicyBuildWorkflowDocument = [ - 3, - n0, - _ARPBWD, - 0, - [_do, _dCT, _dN, _dD], - [ - [() => AutomatedReasoningPolicyBuildDocumentBlob, 0], - 0, - [() => AutomatedReasoningPolicyBuildDocumentName, 0], - [() => AutomatedReasoningPolicyBuildDocumentDescription, 0], - ], -]; -var AutomatedReasoningPolicyBuildWorkflowRepairContent = [ - 3, - n0, - _ARPBWRC, - 0, - [_an], - [[() => AutomatedReasoningPolicyAnnotationList, 0]], -]; -var AutomatedReasoningPolicyBuildWorkflowSource = [ - 3, - n0, - _ARPBWS, - 0, - [_pD, _wC], - [ - [() => AutomatedReasoningPolicyDefinition, 0], - [() => AutomatedReasoningPolicyWorkflowTypeContent, 0], - ], -]; -var AutomatedReasoningPolicyBuildWorkflowSummary = [ - 3, - n0, - _ARPBWSu, - 0, - [_pA, _bWI, _s, _bWT, _cA, _uA], - [0, 0, 0, 0, 5, 5], -]; -var AutomatedReasoningPolicyDefinition = [ - 3, - n0, - _ARPDu, - 0, - [_ve, _typ, _ru, _vari], - [ - 0, - [() => AutomatedReasoningPolicyDefinitionTypeList, 0], - [() => AutomatedReasoningPolicyDefinitionRuleList, 0], - [() => AutomatedReasoningPolicyDefinitionVariableList, 0], - ], -]; -var AutomatedReasoningPolicyDefinitionQualityReport = [ - 3, - n0, - _ARPDQR, - 0, - [_tC, _vC, _rC, _uT, _uTV, _uV, _cRo, _dRS], - [ - 1, - 1, - 1, - [() => AutomatedReasoningPolicyDefinitionTypeNameList, 0], - [() => AutomatedReasoningPolicyDefinitionTypeValuePairList, 0], - [() => AutomatedReasoningPolicyDefinitionVariableNameList, 0], - 64 | 0, - [() => AutomatedReasoningPolicyDisjointRuleSetList, 0], - ], -]; -var AutomatedReasoningPolicyDefinitionRule = [ - 3, - n0, - _ARPDR, - 0, - [_i, _ex, _aE], - [ - 0, - [() => AutomatedReasoningPolicyDefinitionRuleExpression, 0], - [() => AutomatedReasoningPolicyDefinitionRuleAlternateExpression, 0], - ], -]; -var AutomatedReasoningPolicyDefinitionType = [ - 3, - n0, - _ARPDT, - 0, - [_n, _d, _v], - [ - [() => AutomatedReasoningPolicyDefinitionTypeName, 0], - [() => AutomatedReasoningPolicyDefinitionTypeDescription, 0], - [() => AutomatedReasoningPolicyDefinitionTypeValueList, 0], - ], -]; -var AutomatedReasoningPolicyDefinitionTypeValue = [ - 3, - n0, - _ARPDTV, - 0, - [_va, _d], - [0, [() => AutomatedReasoningPolicyDefinitionTypeValueDescription, 0]], -]; -var AutomatedReasoningPolicyDefinitionTypeValuePair = [ - 3, - n0, - _ARPDTVP, - 0, - [_tN, _vN], - [[() => AutomatedReasoningPolicyDefinitionTypeName, 0], 0], -]; -var AutomatedReasoningPolicyDefinitionVariable = [ - 3, - n0, - _ARPDV, - 0, - [_n, _ty, _d], - [ - [() => AutomatedReasoningPolicyDefinitionVariableName, 0], - [() => AutomatedReasoningPolicyDefinitionTypeName, 0], - [() => AutomatedReasoningPolicyDefinitionVariableDescription, 0], - ], -]; -var AutomatedReasoningPolicyDeleteRuleAnnotation = [3, n0, _ARPDRA, 0, [_rI], [0]]; -var AutomatedReasoningPolicyDeleteRuleMutation = [3, n0, _ARPDRM, 0, [_i], [0]]; -var AutomatedReasoningPolicyDeleteTypeAnnotation = [ - 3, - n0, - _ARPDTA, - 0, - [_n], - [[() => AutomatedReasoningPolicyDefinitionTypeName, 0]], -]; -var AutomatedReasoningPolicyDeleteTypeMutation = [ - 3, - n0, - _ARPDTM, - 0, - [_n], - [[() => AutomatedReasoningPolicyDefinitionTypeName, 0]], -]; -var AutomatedReasoningPolicyDeleteTypeValue = [3, n0, _ARPDTVu, 0, [_va], [0]]; -var AutomatedReasoningPolicyDeleteVariableAnnotation = [ - 3, - n0, - _ARPDVA, - 0, - [_n], - [[() => AutomatedReasoningPolicyDefinitionVariableName, 0]], -]; -var AutomatedReasoningPolicyDeleteVariableMutation = [ - 3, - n0, - _ARPDVM, - 0, - [_n], - [[() => AutomatedReasoningPolicyDefinitionVariableName, 0]], -]; -var AutomatedReasoningPolicyDisjointRuleSet = [ - 3, - n0, - _ARPDRS, - 0, - [_vari, _ru], - [[() => AutomatedReasoningPolicyDefinitionVariableNameList, 0], 64 | 0], -]; -var AutomatedReasoningPolicyGeneratedTestCase = [ - 3, - n0, - _ARPGTC, - 0, - [_qC, _gC, _eAFR], - [[() => AutomatedReasoningPolicyTestQueryContent, 0], [() => AutomatedReasoningPolicyTestGuardContent, 0], 0], -]; -var AutomatedReasoningPolicyGeneratedTestCases = [ - 3, - n0, - _ARPGTCu, - 0, - [_gTC], - [[() => AutomatedReasoningPolicyGeneratedTestCaseList, 0]], -]; -var AutomatedReasoningPolicyIngestContentAnnotation = [ - 3, - n0, - _ARPICA, - 0, - [_cont], - [[() => AutomatedReasoningPolicyAnnotationIngestContent, 0]], -]; -var AutomatedReasoningPolicyPlanning = [3, n0, _ARPP, 0, [], []]; -var AutomatedReasoningPolicyScenario = [ - 3, - n0, - _ARPS, - 0, - [_ex, _aE, _rIu, _eR], - [ - [() => AutomatedReasoningPolicyScenarioExpression, 0], - [() => AutomatedReasoningPolicyScenarioAlternateExpression, 0], - 64 | 0, - 0, - ], -]; -var AutomatedReasoningPolicySummary = [ - 3, - n0, - _ARPSu, - 0, - [_pA, _n, _d, _ve, _pI, _cA, _uA], - [0, [() => AutomatedReasoningPolicyName, 0], [() => AutomatedReasoningPolicyDescription, 0], 0, 0, 5, 5], -]; -var AutomatedReasoningPolicyTestCase = [ - 3, - n0, - _ARPTC, - 0, - [_tCI, _gC, _qC, _eAFR, _cA, _uA, _cT], - [ - 0, - [() => AutomatedReasoningPolicyTestGuardContent, 0], - [() => AutomatedReasoningPolicyTestQueryContent, 0], - 0, - 5, - 5, - 1, - ], -]; -var AutomatedReasoningPolicyTestResult = [ - 3, - n0, - _ARPTR, - 0, - [_tCe, _pA, _tRS, _tF, _tRR, _aTFR, _uA], - [[() => AutomatedReasoningPolicyTestCase, 0], 0, 0, [() => AutomatedReasoningCheckFindingList, 0], 0, 0, 5], -]; -var AutomatedReasoningPolicyUpdateFromRuleFeedbackAnnotation = [ - 3, - n0, - _ARPUFRFA, - 0, - [_rIu, _f], - [64 | 0, [() => AutomatedReasoningPolicyAnnotationFeedbackNaturalLanguage, 0]], -]; -var AutomatedReasoningPolicyUpdateFromScenarioFeedbackAnnotation = [ - 3, - n0, - _ARPUFSFA, - 0, - [_rIu, _sE, _f], - [ - 64 | 0, - [() => AutomatedReasoningPolicyScenarioExpression, 0], - [() => AutomatedReasoningPolicyAnnotationFeedbackNaturalLanguage, 0], - ], -]; -var AutomatedReasoningPolicyUpdateRuleAnnotation = [ - 3, - n0, - _ARPURA, - 0, - [_rI, _ex], - [0, [() => AutomatedReasoningPolicyDefinitionRuleExpression, 0]], -]; -var AutomatedReasoningPolicyUpdateRuleMutation = [ - 3, - n0, - _ARPURM, - 0, - [_r], - [[() => AutomatedReasoningPolicyDefinitionRule, 0]], -]; -var AutomatedReasoningPolicyUpdateTypeAnnotation = [ - 3, - n0, - _ARPUTA, - 0, - [_n, _nN, _d, _v], - [ - [() => AutomatedReasoningPolicyDefinitionTypeName, 0], - [() => AutomatedReasoningPolicyDefinitionTypeName, 0], - [() => AutomatedReasoningPolicyDefinitionTypeDescription, 0], - [() => AutomatedReasoningPolicyTypeValueAnnotationList, 0], - ], -]; -var AutomatedReasoningPolicyUpdateTypeMutation = [ - 3, - n0, - _ARPUTM, - 0, - [_ty], - [[() => AutomatedReasoningPolicyDefinitionType, 0]], -]; -var AutomatedReasoningPolicyUpdateTypeValue = [ - 3, - n0, - _ARPUTV, - 0, - [_va, _nV, _d], - [0, 0, [() => AutomatedReasoningPolicyDefinitionTypeValueDescription, 0]], -]; -var AutomatedReasoningPolicyUpdateVariableAnnotation = [ - 3, - n0, - _ARPUVA, - 0, - [_n, _nN, _d], - [ - [() => AutomatedReasoningPolicyDefinitionVariableName, 0], - [() => AutomatedReasoningPolicyDefinitionVariableName, 0], - [() => AutomatedReasoningPolicyDefinitionVariableDescription, 0], - ], -]; -var AutomatedReasoningPolicyUpdateVariableMutation = [ - 3, - n0, - _ARPUVM, - 0, - [_var], - [[() => AutomatedReasoningPolicyDefinitionVariable, 0]], -]; -var BatchDeleteEvaluationJobError = [ - 3, - n0, - _BDEJE, - 0, - [_jI, _cod, _m], - [[() => EvaluationJobIdentifier, 0], 0, 0], -]; -var BatchDeleteEvaluationJobItem = [ - 3, - n0, - _BDEJI, - 0, - [_jI, _jS], - [[() => EvaluationJobIdentifier, 0], 0], -]; -var BatchDeleteEvaluationJobRequest = [ - 3, - n0, - _BDEJR, - 0, - [_jIo], - [[() => EvaluationJobIdentifiers, 0]], -]; -var BatchDeleteEvaluationJobResponse = [ - 3, - n0, - _BDEJRa, - 0, - [_er, _eJ], - [ - [() => BatchDeleteEvaluationJobErrors, 0], - [() => BatchDeleteEvaluationJobItems, 0], - ], -]; -var BedrockEvaluatorModel = [3, n0, _BEM, 0, [_mI], [0]]; -var ByteContentDoc = [ - 3, - n0, - _BCD, - 0, - [_id, _cTo, _da], - [[() => Identifier, 0], 0, [() => ByteContentBlob, 0]], -]; -var CancelAutomatedReasoningPolicyBuildWorkflowRequest = [ - 3, - n0, - _CARPBWR, - 0, - [_pA, _bWI], - [ - [0, 1], - [0, 1], - ], -]; -var CancelAutomatedReasoningPolicyBuildWorkflowResponse = [3, n0, _CARPBWRa, 0, [], []]; -var CloudWatchConfig = [3, n0, _CWC, 0, [_lGN, _rA, _lDDSC], [0, 0, () => S3Config]]; -var ConflictException = [ - -3, - n0, - _CE, - { - [_e]: _c, - [_hE]: 400, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ConflictException, ConflictException$1); -var CreateAutomatedReasoningPolicyRequest = [ - 3, - n0, - _CARPR, - 0, - [_n, _d, _cRT, _pD, _kKI, _ta], - [ - [() => AutomatedReasoningPolicyName, 0], - [() => AutomatedReasoningPolicyDescription, 0], - [0, 4], - [() => AutomatedReasoningPolicyDefinition, 0], - 0, - () => TagList, - ], -]; -var CreateAutomatedReasoningPolicyResponse = [ - 3, - n0, - _CARPRr, - 0, - [_pA, _ve, _n, _d, _dH, _cA, _uA], - [0, 0, [() => AutomatedReasoningPolicyName, 0], [() => AutomatedReasoningPolicyDescription, 0], 0, 5, 5], -]; -var CreateAutomatedReasoningPolicyTestCaseRequest = [ - 3, - n0, - _CARPTCR, - 0, - [_pA, _gC, _qC, _eAFR, _cRT, _cT], - [ - [0, 1], - [() => AutomatedReasoningPolicyTestGuardContent, 0], - [() => AutomatedReasoningPolicyTestQueryContent, 0], - 0, - [0, 4], - 1, - ], -]; -var CreateAutomatedReasoningPolicyTestCaseResponse = [ - 3, - n0, - _CARPTCRr, - 0, - [_pA, _tCI], - [0, 0], -]; -var CreateAutomatedReasoningPolicyVersionRequest = [ - 3, - n0, - _CARPVR, - 0, - [_pA, _cRT, _lUDH, _ta], - [[0, 1], [0, 4], 0, () => TagList], -]; -var CreateAutomatedReasoningPolicyVersionResponse = [ - 3, - n0, - _CARPVRr, - 0, - [_pA, _ve, _n, _d, _dH, _cA], - [0, 0, [() => AutomatedReasoningPolicyName, 0], [() => AutomatedReasoningPolicyDescription, 0], 0, 5], -]; -var CreateCustomModelDeploymentRequest = [ - 3, - n0, - _CCMDR, - 0, - [_mDN, _mA, _d, _ta, _cRT], - [0, 0, 0, () => TagList, [0, 4]], -]; -var CreateCustomModelDeploymentResponse = [3, n0, _CCMDRr, 0, [_cMDA], [0]]; -var CreateCustomModelRequest = [ - 3, - n0, - _CCMR, - 0, - [_mN, _mSC, _mKKA, _rA, _mTo, _cRT], - [0, () => ModelDataSource, 0, 0, () => TagList, [0, 4]], -]; -var CreateCustomModelResponse = [3, n0, _CCMRr, 0, [_mA], [0]]; -var CreateEvaluationJobRequest = [ - 3, - n0, - _CEJR, - 0, - [_jN, _jD, _cRT, _rA, _cEKI, _jT, _aT, _eC, _iC, _oDC], - [ - 0, - [() => EvaluationJobDescription, 0], - [0, 4], - 0, - 0, - () => TagList, - 0, - [() => EvaluationConfig, 0], - [() => EvaluationInferenceConfig, 0], - () => EvaluationOutputDataConfig, - ], -]; -var CreateEvaluationJobResponse = [3, n0, _CEJRr, 0, [_jA], [0]]; -var CreateFoundationModelAgreementRequest = [3, n0, _CFMAR, 0, [_oT, _mIo], [0, 0]]; -var CreateFoundationModelAgreementResponse = [3, n0, _CFMARr, 0, [_mIo], [0]]; -var CreateGuardrailRequest = [ - 3, - n0, - _CGR, - 0, - [_n, _d, _tPC, _cPC, _wPC, _sIPC, _cGPC, _aRPC, _cRC, _bIM, _bOM, _kKI, _ta, _cRT], - [ - [() => GuardrailName, 0], - [() => GuardrailDescription, 0], - [() => GuardrailTopicPolicyConfig, 0], - [() => GuardrailContentPolicyConfig, 0], - [() => GuardrailWordPolicyConfig, 0], - () => GuardrailSensitiveInformationPolicyConfig, - [() => GuardrailContextualGroundingPolicyConfig, 0], - () => GuardrailAutomatedReasoningPolicyConfig, - () => GuardrailCrossRegionConfig, - [() => GuardrailBlockedMessaging, 0], - [() => GuardrailBlockedMessaging, 0], - 0, - () => TagList, - [0, 4], - ], -]; -var CreateGuardrailResponse = [3, n0, _CGRr, 0, [_gI, _gA, _ve, _cA], [0, 0, 0, 5]]; -var CreateGuardrailVersionRequest = [ - 3, - n0, - _CGVR, - 0, - [_gIu, _d, _cRT], - [ - [0, 1], - [() => GuardrailDescription, 0], - [0, 4], - ], -]; -var CreateGuardrailVersionResponse = [3, n0, _CGVRr, 0, [_gI, _ve], [0, 0]]; -var CreateInferenceProfileRequest = [ - 3, - n0, - _CIPR, - 0, - [_iPN, _d, _cRT, _mS, _ta], - [0, [() => InferenceProfileDescription, 0], [0, 4], () => InferenceProfileModelSource, () => TagList], -]; -var CreateInferenceProfileResponse = [3, n0, _CIPRr, 0, [_iPA, _s], [0, 0]]; -var CreateMarketplaceModelEndpointRequest = [ - 3, - n0, - _CMMER, - 0, - [_mSI, _eCn, _aEc, _eN, _cRT, _ta], - [0, () => EndpointConfig, 2, 0, [0, 4], () => TagList], -]; -var CreateMarketplaceModelEndpointResponse = [ - 3, - n0, - _CMMERr, - 0, - [_mME], - [() => MarketplaceModelEndpoint], -]; -var CreateModelCopyJobRequest = [ - 3, - n0, - _CMCJR, - 0, - [_sMA, _tMN, _mKKI, _tMT, _cRT], - [0, 0, 0, () => TagList, [0, 4]], -]; -var CreateModelCopyJobResponse = [3, n0, _CMCJRr, 0, [_jA], [0]]; -var CreateModelCustomizationJobRequest = [ - 3, - n0, - _CMCJRre, - 0, - [_jN, _cMN, _rA, _cRT, _bMI, _cTu, _cMKKI, _jT, _cMT, _tDC, _vDC, _oDC, _hP, _vCp, _cC], - [ - 0, - 0, - 0, - [0, 4], - 0, - 0, - 0, - () => TagList, - () => TagList, - [() => TrainingDataConfig, 0], - () => ValidationDataConfig, - () => OutputDataConfig, - 128 | 0, - () => VpcConfig, - () => CustomizationConfig, - ], -]; -var CreateModelCustomizationJobResponse = [3, n0, _CMCJRrea, 0, [_jA], [0]]; -var CreateModelImportJobRequest = [ - 3, - n0, - _CMIJR, - 0, - [_jN, _iMN, _rA, _mDS, _jT, _iMT, _cRT, _vCp, _iMKKI], - [0, 0, 0, () => ModelDataSource, () => TagList, () => TagList, 0, () => VpcConfig, 0], -]; -var CreateModelImportJobResponse = [3, n0, _CMIJRr, 0, [_jA], [0]]; -var CreateModelInvocationJobRequest = [ - 3, - n0, - _CMIJRre, - 0, - [_jN, _rA, _cRT, _mIo, _iDC, _oDC, _vCp, _tDIH, _ta], - [ - 0, - 0, - [0, 4], - 0, - () => ModelInvocationJobInputDataConfig, - () => ModelInvocationJobOutputDataConfig, - () => VpcConfig, - 1, - () => TagList, - ], -]; -var CreateModelInvocationJobResponse = [3, n0, _CMIJRrea, 0, [_jA], [0]]; -var CreatePromptRouterRequest = [ - 3, - n0, - _CPRR, - 0, - [_cRT, _pRN, _mo, _d, _rCo, _fM, _ta], - [ - [0, 4], - 0, - () => PromptRouterTargetModels, - [() => PromptRouterDescription, 0], - () => RoutingCriteria, - () => PromptRouterTargetModel, - () => TagList, - ], -]; -var CreatePromptRouterResponse = [3, n0, _CPRRr, 0, [_pRA], [0]]; -var CreateProvisionedModelThroughputRequest = [ - 3, - n0, - _CPMTR, - 0, - [_cRT, _mU, _pMN, _mIo, _cD, _ta], - [[0, 4], 1, 0, 0, 0, () => TagList], -]; -var CreateProvisionedModelThroughputResponse = [3, n0, _CPMTRr, 0, [_pMA], [0]]; -var CustomMetricBedrockEvaluatorModel = [3, n0, _CMBEM, 0, [_mI], [0]]; -var CustomMetricDefinition = [ - 3, - n0, - _CMD, - 8, - [_n, _in, _rS], - [[() => MetricName, 0], 0, () => RatingScale], -]; -var CustomMetricEvaluatorModelConfig = [ - 3, - n0, - _CMEMC, - 0, - [_bEM], - [() => CustomMetricBedrockEvaluatorModels], -]; -var CustomModelDeploymentSummary = [ - 3, - n0, - _CMDS, - 0, - [_cMDA, _cMDN, _mA, _cA, _s, _lUA, _fMa], - [0, 0, 0, 5, 0, 5, 0], -]; -var CustomModelSummary = [ - 3, - n0, - _CMS, - 0, - [_mA, _mN, _cTr, _bMA, _bMN, _cTu, _oAI, _mSo], - [0, 0, 5, 0, 0, 0, 0, 0], -]; -var CustomModelUnits = [3, n0, _CMU, 0, [_cMUPMC, _cMUV], [1, 0]]; -var DataProcessingDetails = [3, n0, _DPD, 0, [_s, _cTr, _lMT], [0, 5, 5]]; -var DeleteAutomatedReasoningPolicyBuildWorkflowRequest = [ - 3, - n0, - _DARPBWR, - 0, - [_pA, _bWI, _lUA], - [ - [0, 1], - [0, 1], - [ - 5, - { - [_hQ]: _uA, - }, - ], - ], -]; -var DeleteAutomatedReasoningPolicyBuildWorkflowResponse = [3, n0, _DARPBWRe, 0, [], []]; -var DeleteAutomatedReasoningPolicyRequest = [ - 3, - n0, - _DARPR, - 0, - [_pA, _fo], - [ - [0, 1], - [ - 2, - { - [_hQ]: _fo, - }, - ], - ], -]; -var DeleteAutomatedReasoningPolicyResponse = [3, n0, _DARPRe, 0, [], []]; -var DeleteAutomatedReasoningPolicyTestCaseRequest = [ - 3, - n0, - _DARPTCR, - 0, - [_pA, _tCI, _lUA], - [ - [0, 1], - [0, 1], - [ - 5, - { - [_hQ]: _uA, - }, - ], - ], -]; -var DeleteAutomatedReasoningPolicyTestCaseResponse = [3, n0, _DARPTCRe, 0, [], []]; -var DeleteCustomModelDeploymentRequest = [3, n0, _DCMDR, 0, [_cMDI], [[0, 1]]]; -var DeleteCustomModelDeploymentResponse = [3, n0, _DCMDRe, 0, [], []]; -var DeleteCustomModelRequest = [3, n0, _DCMR, 0, [_mI], [[0, 1]]]; -var DeleteCustomModelResponse = [3, n0, _DCMRe, 0, [], []]; -var DeleteFoundationModelAgreementRequest = [3, n0, _DFMAR, 0, [_mIo], [0]]; -var DeleteFoundationModelAgreementResponse = [3, n0, _DFMARe, 0, [], []]; -var DeleteGuardrailRequest = [ - 3, - n0, - _DGR, - 0, - [_gIu, _gV], - [ - [0, 1], - [ - 0, - { - [_hQ]: _gV, - }, - ], - ], -]; -var DeleteGuardrailResponse = [3, n0, _DGRe, 0, [], []]; -var DeleteImportedModelRequest = [3, n0, _DIMR, 0, [_mI], [[0, 1]]]; -var DeleteImportedModelResponse = [3, n0, _DIMRe, 0, [], []]; -var DeleteInferenceProfileRequest = [3, n0, _DIPR, 0, [_iPI], [[0, 1]]]; -var DeleteInferenceProfileResponse = [3, n0, _DIPRe, 0, [], []]; -var DeleteMarketplaceModelEndpointRequest = [3, n0, _DMMER, 0, [_eA], [[0, 1]]]; -var DeleteMarketplaceModelEndpointResponse = [3, n0, _DMMERe, 0, [], []]; -var DeleteModelInvocationLoggingConfigurationRequest = [3, n0, _DMILCR, 0, [], []]; -var DeleteModelInvocationLoggingConfigurationResponse = [3, n0, _DMILCRe, 0, [], []]; -var DeletePromptRouterRequest = [3, n0, _DPRR, 0, [_pRA], [[0, 1]]]; -var DeletePromptRouterResponse = [3, n0, _DPRRe, 0, [], []]; -var DeleteProvisionedModelThroughputRequest = [3, n0, _DPMTR, 0, [_pMI], [[0, 1]]]; -var DeleteProvisionedModelThroughputResponse = [3, n0, _DPMTRe, 0, [], []]; -var DeregisterMarketplaceModelEndpointRequest = [3, n0, _DMMERer, 0, [_eA], [[0, 1]]]; -var DeregisterMarketplaceModelEndpointResponse = [3, n0, _DMMERere, 0, [], []]; -var DimensionalPriceRate = [3, n0, _DPR, 0, [_di, _pr, _d, _u], [0, 0, 0, 0]]; -var DistillationConfig = [3, n0, _DC, 0, [_tMC], [() => TeacherModelConfig]]; -var EvaluationBedrockModel = [ - 3, - n0, - _EBM, - 0, - [_mI, _iP, _pC], - [0, [() => EvaluationModelInferenceParams, 0], () => PerformanceConfiguration], -]; -var EvaluationDataset = [ - 3, - n0, - _ED, - 0, - [_n, _dL], - [[() => EvaluationDatasetName, 0], () => EvaluationDatasetLocation], -]; -var EvaluationDatasetMetricConfig = [ - 3, - n0, - _EDMC, - 0, - [_tT, _dat, _mNe], - [0, [() => EvaluationDataset, 0], [() => EvaluationMetricNames, 0]], -]; -var EvaluationInferenceConfigSummary = [ - 3, - n0, - _EICS, - 0, - [_mCS, _rCS], - [() => EvaluationModelConfigSummary, () => EvaluationRagConfigSummary], -]; -var EvaluationModelConfigSummary = [3, n0, _EMCS, 0, [_bMIe, _pISI], [64 | 0, 64 | 0]]; -var EvaluationOutputDataConfig = [3, n0, _EODC, 0, [_sU], [0]]; -var EvaluationPrecomputedInferenceSource = [3, n0, _EPIS, 0, [_iSI], [0]]; -var EvaluationPrecomputedRetrieveAndGenerateSourceConfig = [ - 3, - n0, - _EPRAGSC, - 0, - [_rSI], - [0], -]; -var EvaluationPrecomputedRetrieveSourceConfig = [3, n0, _EPRSC, 0, [_rSI], [0]]; -var EvaluationRagConfigSummary = [3, n0, _ERCS, 0, [_bKBI, _pRSI], [64 | 0, 64 | 0]]; -var EvaluationSummary = [ - 3, - n0, - _ES, - 0, - [_jA, _jN, _s, _cTr, _jTo, _eTT, _mIod, _rIa, _eMI, _cMEMI, _iCS, _aT], - [0, 0, 0, 5, 0, 64 | 0, 64 | 0, 64 | 0, 64 | 0, 64 | 0, () => EvaluationInferenceConfigSummary, 0], -]; -var ExportAutomatedReasoningPolicyVersionRequest = [3, n0, _EARPVR, 0, [_pA], [[0, 1]]]; -var ExportAutomatedReasoningPolicyVersionResponse = [ - 3, - n0, - _EARPVRx, - 0, - [_pD], - [[() => AutomatedReasoningPolicyDefinition, 16]], -]; -var ExternalSource = [ - 3, - n0, - _ESx, - 0, - [_sT, _sL, _bC], - [0, () => S3ObjectDoc, [() => ByteContentDoc, 0]], -]; -var ExternalSourcesGenerationConfiguration = [ - 3, - n0, - _ESGC, - 0, - [_pT, _gCu, _kIC, _aMRF], - [[() => PromptTemplate, 0], () => GuardrailConfiguration, () => KbInferenceConfig, 128 | 15], -]; -var ExternalSourcesRetrieveAndGenerateConfiguration = [ - 3, - n0, - _ESRAGC, - 0, - [_mA, _so, _gCe], - [0, [() => ExternalSources, 0], [() => ExternalSourcesGenerationConfiguration, 0]], -]; -var FieldForReranking = [3, n0, _FFR, 0, [_fN], [0]]; -var FilterAttribute = [3, n0, _FA, 0, [_k, _va], [0, 15]]; -var FoundationModelDetails = [ - 3, - n0, - _FMD, - 0, - [_mA, _mIo, _mN, _pN, _iM, _oM, _rSS, _cS, _iTS, _mL], - [0, 0, 0, 0, 64 | 0, 64 | 0, 2, 64 | 0, 64 | 0, () => FoundationModelLifecycle], -]; -var FoundationModelLifecycle = [3, n0, _FML, 0, [_s], [0]]; -var FoundationModelSummary = [ - 3, - n0, - _FMS, - 0, - [_mA, _mIo, _mN, _pN, _iM, _oM, _rSS, _cS, _iTS, _mL], - [0, 0, 0, 0, 64 | 0, 64 | 0, 2, 64 | 0, 64 | 0, () => FoundationModelLifecycle], -]; -var GenerationConfiguration = [ - 3, - n0, - _GC, - 0, - [_pT, _gCu, _kIC, _aMRF], - [[() => PromptTemplate, 0], () => GuardrailConfiguration, () => KbInferenceConfig, 128 | 15], -]; -var GetAutomatedReasoningPolicyAnnotationsRequest = [ - 3, - n0, - _GARPAR, - 0, - [_pA, _bWI], - [ - [0, 1], - [0, 1], - ], -]; -var GetAutomatedReasoningPolicyAnnotationsResponse = [ - 3, - n0, - _GARPARe, - 0, - [_pA, _n, _bWI, _an, _aSH, _uA], - [0, [() => AutomatedReasoningPolicyName, 0], 0, [() => AutomatedReasoningPolicyAnnotationList, 0], 0, 5], -]; -var GetAutomatedReasoningPolicyBuildWorkflowRequest = [ - 3, - n0, - _GARPBWR, - 0, - [_pA, _bWI], - [ - [0, 1], - [0, 1], - ], -]; -var GetAutomatedReasoningPolicyBuildWorkflowResponse = [ - 3, - n0, - _GARPBWRe, - 0, - [_pA, _bWI, _s, _bWT, _dN, _dCT, _dD, _cA, _uA], - [ - 0, - 0, - 0, - 0, - [() => AutomatedReasoningPolicyBuildDocumentName, 0], - 0, - [() => AutomatedReasoningPolicyBuildDocumentDescription, 0], - 5, - 5, - ], -]; -var GetAutomatedReasoningPolicyBuildWorkflowResultAssetsRequest = [ - 3, - n0, - _GARPBWRAR, - 0, - [_pA, _bWI, _aTs], - [ - [0, 1], - [0, 1], - [ - 0, - { - [_hQ]: _aTs, - }, - ], - ], -]; -var GetAutomatedReasoningPolicyBuildWorkflowResultAssetsResponse = [ - 3, - n0, - _GARPBWRARe, - 0, - [_pA, _bWI, _bWA], - [0, 0, [() => AutomatedReasoningPolicyBuildResultAssets, 0]], -]; -var GetAutomatedReasoningPolicyNextScenarioRequest = [ - 3, - n0, - _GARPNSR, - 0, - [_pA, _bWI], - [ - [0, 1], - [0, 1], - ], -]; -var GetAutomatedReasoningPolicyNextScenarioResponse = [ - 3, - n0, - _GARPNSRe, - 0, - [_pA, _sc], - [0, [() => AutomatedReasoningPolicyScenario, 0]], -]; -var GetAutomatedReasoningPolicyRequest = [3, n0, _GARPR, 0, [_pA], [[0, 1]]]; -var GetAutomatedReasoningPolicyResponse = [ - 3, - n0, - _GARPRe, - 0, - [_pA, _n, _ve, _pI, _d, _dH, _kKA, _cA, _uA], - [0, [() => AutomatedReasoningPolicyName, 0], 0, 0, [() => AutomatedReasoningPolicyDescription, 0], 0, 0, 5, 5], -]; -var GetAutomatedReasoningPolicyTestCaseRequest = [ - 3, - n0, - _GARPTCR, - 0, - [_pA, _tCI], - [ - [0, 1], - [0, 1], - ], -]; -var GetAutomatedReasoningPolicyTestCaseResponse = [ - 3, - n0, - _GARPTCRe, - 0, - [_pA, _tCe], - [0, [() => AutomatedReasoningPolicyTestCase, 0]], -]; -var GetAutomatedReasoningPolicyTestResultRequest = [ - 3, - n0, - _GARPTRR, - 0, - [_pA, _bWI, _tCI], - [ - [0, 1], - [0, 1], - [0, 1], - ], -]; -var GetAutomatedReasoningPolicyTestResultResponse = [ - 3, - n0, - _GARPTRRe, - 0, - [_tR], - [[() => AutomatedReasoningPolicyTestResult, 0]], -]; -var GetCustomModelDeploymentRequest = [3, n0, _GCMDR, 0, [_cMDI], [[0, 1]]]; -var GetCustomModelDeploymentResponse = [ - 3, - n0, - _GCMDRe, - 0, - [_cMDA, _mDN, _mA, _cA, _s, _d, _fMa, _lUA], - [0, 0, 0, 5, 0, 0, 0, 5], -]; -var GetCustomModelRequest = [3, n0, _GCMR, 0, [_mI], [[0, 1]]]; -var GetCustomModelResponse = [ - 3, - n0, - _GCMRe, - 0, - [_mA, _mN, _jN, _jA, _bMA, _cTu, _mKKA, _hP, _tDC, _vDC, _oDC, _tM, _vM, _cTr, _cC, _mSo, _fMa], - [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 128 | 0, - [() => TrainingDataConfig, 0], - () => ValidationDataConfig, - () => OutputDataConfig, - () => TrainingMetrics, - () => ValidationMetrics, - 5, - () => CustomizationConfig, - 0, - 0, - ], -]; -var GetEvaluationJobRequest = [ - 3, - n0, - _GEJR, - 0, - [_jI], - [[() => EvaluationJobIdentifier, 1]], -]; -var GetEvaluationJobResponse = [ - 3, - n0, - _GEJRe, - 0, - [_jN, _s, _jA, _jD, _rA, _cEKI, _jTo, _aT, _eC, _iC, _oDC, _cTr, _lMT, _fMai], - [ - 0, - 0, - 0, - [() => EvaluationJobDescription, 0], - 0, - 0, - 0, - 0, - [() => EvaluationConfig, 0], - [() => EvaluationInferenceConfig, 0], - () => EvaluationOutputDataConfig, - 5, - 5, - 64 | 0, - ], -]; -var GetFoundationModelAvailabilityRequest = [3, n0, _GFMAR, 0, [_mIo], [[0, 1]]]; -var GetFoundationModelAvailabilityResponse = [ - 3, - n0, - _GFMARe, - 0, - [_mIo, _aA, _aS, _eAn, _rAe], - [0, () => AgreementAvailability, 0, 0, 0], -]; -var GetFoundationModelRequest = [3, n0, _GFMR, 0, [_mI], [[0, 1]]]; -var GetFoundationModelResponse = [ - 3, - n0, - _GFMRe, - 0, - [_mD], - [() => FoundationModelDetails], -]; -var GetGuardrailRequest = [ - 3, - n0, - _GGR, - 0, - [_gIu, _gV], - [ - [0, 1], - [ - 0, - { - [_hQ]: _gV, - }, - ], - ], -]; -var GetGuardrailResponse = [ - 3, - n0, - _GGRe, - 0, - [_n, _d, _gI, _gA, _ve, _s, _tP, _cP, _wP, _sIP, _cGP, _aRP, _cRD, _cA, _uA, _sRt, _fR, _bIM, _bOM, _kKA], - [ - [() => GuardrailName, 0], - [() => GuardrailDescription, 0], - 0, - 0, - 0, - 0, - [() => GuardrailTopicPolicy, 0], - [() => GuardrailContentPolicy, 0], - [() => GuardrailWordPolicy, 0], - () => GuardrailSensitiveInformationPolicy, - [() => GuardrailContextualGroundingPolicy, 0], - () => GuardrailAutomatedReasoningPolicy, - () => GuardrailCrossRegionDetails, - 5, - 5, - [() => GuardrailStatusReasons, 0], - [() => GuardrailFailureRecommendations, 0], - [() => GuardrailBlockedMessaging, 0], - [() => GuardrailBlockedMessaging, 0], - 0, - ], -]; -var GetImportedModelRequest = [3, n0, _GIMR, 0, [_mI], [[0, 1]]]; -var GetImportedModelResponse = [ - 3, - n0, - _GIMRe, - 0, - [_mA, _mN, _jN, _jA, _mDS, _cTr, _mAo, _mKKA, _iS, _cMU], - [0, 0, 0, 0, () => ModelDataSource, 5, 0, 0, 2, () => CustomModelUnits], -]; -var GetInferenceProfileRequest = [3, n0, _GIPR, 0, [_iPI], [[0, 1]]]; -var GetInferenceProfileResponse = [ - 3, - n0, - _GIPRe, - 0, - [_iPN, _d, _cA, _uA, _iPA, _mo, _iPIn, _s, _ty], - [0, [() => InferenceProfileDescription, 0], 5, 5, 0, () => InferenceProfileModels, 0, 0, 0], -]; -var GetMarketplaceModelEndpointRequest = [3, n0, _GMMER, 0, [_eA], [[0, 1]]]; -var GetMarketplaceModelEndpointResponse = [ - 3, - n0, - _GMMERe, - 0, - [_mME], - [() => MarketplaceModelEndpoint], -]; -var GetModelCopyJobRequest = [3, n0, _GMCJR, 0, [_jA], [[0, 1]]]; -var GetModelCopyJobResponse = [ - 3, - n0, - _GMCJRe, - 0, - [_jA, _s, _cTr, _tMA, _tMN, _sAI, _sMA, _tMKKA, _tMT, _fMa, _sMN], - [0, 0, 5, 0, 0, 0, 0, 0, () => TagList, 0, 0], -]; -var GetModelCustomizationJobRequest = [3, n0, _GMCJRet, 0, [_jI], [[0, 1]]]; -var GetModelCustomizationJobResponse = [ - 3, - n0, - _GMCJReto, - 0, - [ - _jA, - _jN, - _oMN, - _oMA, - _cRT, - _rA, - _s, - _sD, - _fMa, - _cTr, - _lMT, - _eT, - _bMA, - _hP, - _tDC, - _vDC, - _oDC, - _cTu, - _oMKKA, - _tM, - _vM, - _vCp, - _cC, - ], - [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - () => StatusDetails, - 0, - 5, - 5, - 5, - 0, - 128 | 0, - [() => TrainingDataConfig, 0], - () => ValidationDataConfig, - () => OutputDataConfig, - 0, - 0, - () => TrainingMetrics, - () => ValidationMetrics, - () => VpcConfig, - () => CustomizationConfig, - ], -]; -var GetModelImportJobRequest = [3, n0, _GMIJR, 0, [_jI], [[0, 1]]]; -var GetModelImportJobResponse = [ - 3, - n0, - _GMIJRe, - 0, - [_jA, _jN, _iMN, _iMA, _rA, _mDS, _s, _fMa, _cTr, _lMT, _eT, _vCp, _iMKKA], - [0, 0, 0, 0, 0, () => ModelDataSource, 0, 0, 5, 5, 5, () => VpcConfig, 0], -]; -var GetModelInvocationJobRequest = [3, n0, _GMIJRet, 0, [_jI], [[0, 1]]]; -var GetModelInvocationJobResponse = [ - 3, - n0, - _GMIJReto, - 0, - [_jA, _jN, _mIo, _cRT, _rA, _s, _m, _sTu, _lMT, _eT, _iDC, _oDC, _vCp, _tDIH, _jET], - [ - 0, - 0, - 0, - 0, - 0, - 0, - [() => Message, 0], - 5, - 5, - 5, - () => ModelInvocationJobInputDataConfig, - () => ModelInvocationJobOutputDataConfig, - () => VpcConfig, - 1, - 5, - ], -]; -var GetModelInvocationLoggingConfigurationRequest = [3, n0, _GMILCR, 0, [], []]; -var GetModelInvocationLoggingConfigurationResponse = [ - 3, - n0, - _GMILCRe, - 0, - [_lC], - [() => LoggingConfig], -]; -var GetPromptRouterRequest = [3, n0, _GPRR, 0, [_pRA], [[0, 1]]]; -var GetPromptRouterResponse = [ - 3, - n0, - _GPRRe, - 0, - [_pRN, _rCo, _d, _cA, _uA, _pRA, _mo, _fM, _s, _ty], - [ - 0, - () => RoutingCriteria, - [() => PromptRouterDescription, 0], - 5, - 5, - 0, - () => PromptRouterTargetModels, - () => PromptRouterTargetModel, - 0, - 0, - ], -]; -var GetProvisionedModelThroughputRequest = [3, n0, _GPMTR, 0, [_pMI], [[0, 1]]]; -var GetProvisionedModelThroughputResponse = [ - 3, - n0, - _GPMTRe, - 0, - [_mU, _dMU, _pMN, _pMA, _mA, _dMA, _fMA, _s, _cTr, _lMT, _fMa, _cD, _cET], - [1, 1, 0, 0, 0, 0, 0, 0, 5, 5, 0, 0, 5], -]; -var GetUseCaseForModelAccessRequest = [3, n0, _GUCFMAR, 0, [], []]; -var GetUseCaseForModelAccessResponse = [3, n0, _GUCFMARe, 0, [_fD], [21]]; -var GuardrailAutomatedReasoningPolicy = [3, n0, _GARP, 0, [_po, _cT], [64 | 0, 1]]; -var GuardrailAutomatedReasoningPolicyConfig = [3, n0, _GARPC, 0, [_po, _cT], [64 | 0, 1]]; -var GuardrailConfiguration = [3, n0, _GCu, 0, [_gI, _gV], [0, 0]]; -var GuardrailContentFilter = [ - 3, - n0, - _GCF, - 0, - [_ty, _iSn, _oS, _iM, _oM, _iA, _oA, _iE, _oE], - [ - 0, - 0, - 0, - [() => GuardrailModalities, 0], - [() => GuardrailModalities, 0], - [() => GuardrailContentFilterAction$1, 0], - [() => GuardrailContentFilterAction$1, 0], - 2, - 2, - ], -]; -var GuardrailContentFilterConfig = [ - 3, - n0, - _GCFC, - 0, - [_ty, _iSn, _oS, _iM, _oM, _iA, _oA, _iE, _oE], - [ - 0, - 0, - 0, - [() => GuardrailModalities, 0], - [() => GuardrailModalities, 0], - [() => GuardrailContentFilterAction$1, 0], - [() => GuardrailContentFilterAction$1, 0], - 2, - 2, - ], -]; -var GuardrailContentFiltersTier = [ - 3, - n0, - _GCFT, - 0, - [_tNi], - [[() => GuardrailContentFiltersTierName$1, 0]], -]; -var GuardrailContentFiltersTierConfig = [ - 3, - n0, - _GCFTC, - 0, - [_tNi], - [[() => GuardrailContentFiltersTierName$1, 0]], -]; -var GuardrailContentPolicy = [ - 3, - n0, - _GCP, - 0, - [_fi, _ti], - [ - [() => GuardrailContentFilters, 0], - [() => GuardrailContentFiltersTier, 0], - ], -]; -var GuardrailContentPolicyConfig = [ - 3, - n0, - _GCPC, - 0, - [_fC, _tCi], - [ - [() => GuardrailContentFiltersConfig, 0], - [() => GuardrailContentFiltersTierConfig, 0], - ], -]; -var GuardrailContextualGroundingFilter = [ - 3, - n0, - _GCGF, - 0, - [_ty, _th, _ac, _ena], - [0, 1, [() => GuardrailContextualGroundingAction$1, 0], 2], -]; -var GuardrailContextualGroundingFilterConfig = [ - 3, - n0, - _GCGFC, - 0, - [_ty, _th, _ac, _ena], - [0, 1, [() => GuardrailContextualGroundingAction$1, 0], 2], -]; -var GuardrailContextualGroundingPolicy = [ - 3, - n0, - _GCGP, - 0, - [_fi], - [[() => GuardrailContextualGroundingFilters, 0]], -]; -var GuardrailContextualGroundingPolicyConfig = [ - 3, - n0, - _GCGPC, - 0, - [_fC], - [[() => GuardrailContextualGroundingFiltersConfig, 0]], -]; -var GuardrailCrossRegionConfig = [3, n0, _GCRC, 0, [_gPI], [0]]; -var GuardrailCrossRegionDetails = [3, n0, _GCRD, 0, [_gPIu, _gPA], [0, 0]]; -var GuardrailManagedWords = [ - 3, - n0, - _GMW, - 0, - [_ty, _iA, _oA, _iE, _oE], - [0, [() => GuardrailWordAction$1, 0], [() => GuardrailWordAction$1, 0], 2, 2], -]; -var GuardrailManagedWordsConfig = [ - 3, - n0, - _GMWC, - 0, - [_ty, _iA, _oA, _iE, _oE], - [0, [() => GuardrailWordAction$1, 0], [() => GuardrailWordAction$1, 0], 2, 2], -]; -var GuardrailPiiEntity = [ - 3, - n0, - _GPE, - 0, - [_ty, _ac, _iA, _oA, _iE, _oE], - [0, 0, 0, 0, 2, 2], -]; -var GuardrailPiiEntityConfig = [ - 3, - n0, - _GPEC, - 0, - [_ty, _ac, _iA, _oA, _iE, _oE], - [0, 0, 0, 0, 2, 2], -]; -var GuardrailRegex = [ - 3, - n0, - _GR, - 0, - [_n, _d, _pa, _ac, _iA, _oA, _iE, _oE], - [0, 0, 0, 0, 0, 0, 2, 2], -]; -var GuardrailRegexConfig = [ - 3, - n0, - _GRC, - 0, - [_n, _d, _pa, _ac, _iA, _oA, _iE, _oE], - [0, 0, 0, 0, 0, 0, 2, 2], -]; -var GuardrailSensitiveInformationPolicy = [ - 3, - n0, - _GSIP, - 0, - [_pEi, _re], - [() => GuardrailPiiEntities, () => GuardrailRegexes], -]; -var GuardrailSensitiveInformationPolicyConfig = [ - 3, - n0, - _GSIPC, - 0, - [_pEC, _rCe], - [() => GuardrailPiiEntitiesConfig, () => GuardrailRegexesConfig], -]; -var GuardrailSummary = [ - 3, - n0, - _GS, - 0, - [_i, _ar, _s, _n, _d, _ve, _cA, _uA, _cRD], - [0, 0, 0, [() => GuardrailName, 0], [() => GuardrailDescription, 0], 0, 5, 5, () => GuardrailCrossRegionDetails], -]; -var GuardrailTopic = [ - 3, - n0, - _GT, - 0, - [_n, _de, _exa, _ty, _iA, _oA, _iE, _oE], - [ - [() => GuardrailTopicName, 0], - [() => GuardrailTopicDefinition, 0], - [() => GuardrailTopicExamples, 0], - 0, - [() => GuardrailTopicAction$1, 0], - [() => GuardrailTopicAction$1, 0], - 2, - 2, - ], -]; -var GuardrailTopicConfig = [ - 3, - n0, - _GTC, - 0, - [_n, _de, _exa, _ty, _iA, _oA, _iE, _oE], - [ - [() => GuardrailTopicName, 0], - [() => GuardrailTopicDefinition, 0], - [() => GuardrailTopicExamples, 0], - 0, - [() => GuardrailTopicAction$1, 0], - [() => GuardrailTopicAction$1, 0], - 2, - 2, - ], -]; -var GuardrailTopicPolicy = [ - 3, - n0, - _GTP, - 0, - [_to, _ti], - [ - [() => GuardrailTopics, 0], - [() => GuardrailTopicsTier, 0], - ], -]; -var GuardrailTopicPolicyConfig = [ - 3, - n0, - _GTPC, - 0, - [_tCo, _tCi], - [ - [() => GuardrailTopicsConfig, 0], - [() => GuardrailTopicsTierConfig, 0], - ], -]; -var GuardrailTopicsTier = [3, n0, _GTT, 0, [_tNi], [[() => GuardrailTopicsTierName$1, 0]]]; -var GuardrailTopicsTierConfig = [ - 3, - n0, - _GTTC, - 0, - [_tNi], - [[() => GuardrailTopicsTierName$1, 0]], -]; -var GuardrailWord = [ - 3, - n0, - _GW, - 0, - [_te, _iA, _oA, _iE, _oE], - [0, [() => GuardrailWordAction$1, 0], [() => GuardrailWordAction$1, 0], 2, 2], -]; -var GuardrailWordConfig = [ - 3, - n0, - _GWC, - 0, - [_te, _iA, _oA, _iE, _oE], - [0, [() => GuardrailWordAction$1, 0], [() => GuardrailWordAction$1, 0], 2, 2], -]; -var GuardrailWordPolicy = [ - 3, - n0, - _GWP, - 0, - [_w, _mWL], - [ - [() => GuardrailWords, 0], - [() => GuardrailManagedWordLists, 0], - ], -]; -var GuardrailWordPolicyConfig = [ - 3, - n0, - _GWPC, - 0, - [_wCo, _mWLC], - [ - [() => GuardrailWordsConfig, 0], - [() => GuardrailManagedWordListsConfig, 0], - ], -]; -var HumanEvaluationConfig = [ - 3, - n0, - _HEC, - 0, - [_hWC, _cM, _dMC], - [ - [() => HumanWorkflowConfig, 0], - [() => HumanEvaluationCustomMetrics, 0], - [() => EvaluationDatasetMetricConfigs, 0], - ], -]; -var HumanEvaluationCustomMetric = [ - 3, - n0, - _HECM, - 0, - [_n, _d, _rM], - [[() => EvaluationMetricName, 0], [() => EvaluationMetricDescription, 0], 0], -]; -var HumanWorkflowConfig = [ - 3, - n0, - _HWC, - 0, - [_fDA, _in], - [0, [() => HumanTaskInstructions, 0]], -]; -var ImplicitFilterConfiguration = [ - 3, - n0, - _IFC, - 0, - [_mAe, _mA], - [[() => MetadataAttributeSchemaList, 0], 0], -]; -var ImportedModelSummary = [3, n0, _IMS, 0, [_mA, _mN, _cTr, _iS, _mAo], [0, 0, 5, 2, 0]]; -var InferenceProfileModel = [3, n0, _IPM, 0, [_mA], [0]]; -var InferenceProfileSummary = [ - 3, - n0, - _IPS, - 0, - [_iPN, _d, _cA, _uA, _iPA, _mo, _iPIn, _s, _ty], - [0, [() => InferenceProfileDescription, 0], 5, 5, 0, () => InferenceProfileModels, 0, 0, 0], -]; -var InternalServerException = [ - -3, - n0, - _ISE, - { - [_e]: _se, - [_hE]: 500, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(InternalServerException, InternalServerException$1); -var InvocationLogsConfig = [ - 3, - n0, - _ILC, - 0, - [_uPR, _iLS, _rMF], - [2, () => InvocationLogSource, [() => RequestMetadataFilters, 0]], -]; -var KbInferenceConfig = [3, n0, _KIC, 0, [_tIC], [() => TextInferenceConfig]]; -var KnowledgeBaseRetrievalConfiguration = [ - 3, - n0, - _KBRC, - 0, - [_vSC], - [[() => KnowledgeBaseVectorSearchConfiguration, 0]], -]; -var KnowledgeBaseRetrieveAndGenerateConfiguration = [ - 3, - n0, - _KBRAGC, - 0, - [_kBI, _mA, _rCet, _gCe, _oC], - [ - 0, - 0, - [() => KnowledgeBaseRetrievalConfiguration, 0], - [() => GenerationConfiguration, 0], - () => OrchestrationConfiguration, - ], -]; -var KnowledgeBaseVectorSearchConfiguration = [ - 3, - n0, - _KBVSC, - 0, - [_nOR, _oST, _fil, _iFC, _rCer], - [ - 1, - 0, - [() => RetrievalFilter, 0], - [() => ImplicitFilterConfiguration, 0], - [() => VectorSearchRerankingConfiguration, 0], - ], -]; -var LegalTerm = [3, n0, _LT, 0, [_ur], [0]]; -var ListAutomatedReasoningPoliciesRequest = [ - 3, - n0, - _LARPR, - 0, - [_pA, _nT, _mR], - [ - [ - 0, - { - [_hQ]: _pA, - }, - ], - [ - 0, - { - [_hQ]: _nT, - }, - ], - [ - 1, - { - [_hQ]: _mR, - }, - ], - ], -]; -var ListAutomatedReasoningPoliciesResponse = [ - 3, - n0, - _LARPRi, - 0, - [_aRPS, _nT], - [[() => AutomatedReasoningPolicySummaries, 0], 0], -]; -var ListAutomatedReasoningPolicyBuildWorkflowsRequest = [ - 3, - n0, - _LARPBWR, - 0, - [_pA, _nT, _mR], - [ - [0, 1], - [ - 0, - { - [_hQ]: _nT, - }, - ], - [ - 1, - { - [_hQ]: _mR, - }, - ], - ], -]; -var ListAutomatedReasoningPolicyBuildWorkflowsResponse = [ - 3, - n0, - _LARPBWRi, - 0, - [_aRPBWS, _nT], - [() => AutomatedReasoningPolicyBuildWorkflowSummaries, 0], -]; -var ListAutomatedReasoningPolicyTestCasesRequest = [ - 3, - n0, - _LARPTCR, - 0, - [_pA, _nT, _mR], - [ - [0, 1], - [ - 0, - { - [_hQ]: _nT, - }, - ], - [ - 1, - { - [_hQ]: _mR, - }, - ], - ], -]; -var ListAutomatedReasoningPolicyTestCasesResponse = [ - 3, - n0, - _LARPTCRi, - 0, - [_tCes, _nT], - [[() => AutomatedReasoningPolicyTestCaseList, 0], 0], -]; -var ListAutomatedReasoningPolicyTestResultsRequest = [ - 3, - n0, - _LARPTRR, - 0, - [_pA, _bWI, _nT, _mR], - [ - [0, 1], - [0, 1], - [ - 0, - { - [_hQ]: _nT, - }, - ], - [ - 1, - { - [_hQ]: _mR, - }, - ], - ], -]; -var ListAutomatedReasoningPolicyTestResultsResponse = [ - 3, - n0, - _LARPTRRi, - 0, - [_tRe, _nT], - [[() => AutomatedReasoningPolicyTestList, 0], 0], -]; -var ListCustomModelDeploymentsRequest = [ - 3, - n0, - _LCMDR, - 0, - [_cB, _cAr, _nC, _mR, _nT, _sB, _sO, _sEt, _mAE], - [ - [ - 5, - { - [_hQ]: _cB, - }, - ], - [ - 5, - { - [_hQ]: _cAr, - }, - ], - [ - 0, - { - [_hQ]: _nC, - }, - ], - [ - 1, - { - [_hQ]: _mR, - }, - ], - [ - 0, - { - [_hQ]: _nT, - }, - ], - [ - 0, - { - [_hQ]: _sB, - }, - ], - [ - 0, - { - [_hQ]: _sO, - }, - ], - [ - 0, - { - [_hQ]: _sEt, - }, - ], - [ - 0, - { - [_hQ]: _mAE, - }, - ], - ], -]; -var ListCustomModelDeploymentsResponse = [ - 3, - n0, - _LCMDRi, - 0, - [_nT, _mDSo], - [0, () => CustomModelDeploymentSummaryList], -]; -var ListCustomModelsRequest = [ - 3, - n0, - _LCMR, - 0, - [_cTB, _cTA, _nC, _bMAE, _fMAE, _mR, _nT, _sB, _sO, _iO, _mSo], - [ - [ - 5, - { - [_hQ]: _cTB, - }, - ], - [ - 5, - { - [_hQ]: _cTA, - }, - ], - [ - 0, - { - [_hQ]: _nC, - }, - ], - [ - 0, - { - [_hQ]: _bMAE, - }, - ], - [ - 0, - { - [_hQ]: _fMAE, - }, - ], - [ - 1, - { - [_hQ]: _mR, - }, - ], - [ - 0, - { - [_hQ]: _nT, - }, - ], - [ - 0, - { - [_hQ]: _sB, - }, - ], - [ - 0, - { - [_hQ]: _sO, - }, - ], - [ - 2, - { - [_hQ]: _iO, - }, - ], - [ - 0, - { - [_hQ]: _mSo, - }, - ], - ], -]; -var ListCustomModelsResponse = [ - 3, - n0, - _LCMRi, - 0, - [_nT, _mSod], - [0, () => CustomModelSummaryList], -]; -var ListEvaluationJobsRequest = [ - 3, - n0, - _LEJR, - 0, - [_cTA, _cTB, _sEt, _aTE, _nC, _mR, _nT, _sB, _sO], - [ - [ - 5, - { - [_hQ]: _cTA, - }, - ], - [ - 5, - { - [_hQ]: _cTB, - }, - ], - [ - 0, - { - [_hQ]: _sEt, - }, - ], - [ - 0, - { - [_hQ]: _aTE, - }, - ], - [ - 0, - { - [_hQ]: _nC, - }, - ], - [ - 1, - { - [_hQ]: _mR, - }, - ], - [ - 0, - { - [_hQ]: _nT, - }, - ], - [ - 0, - { - [_hQ]: _sB, - }, - ], - [ - 0, - { - [_hQ]: _sO, - }, - ], - ], -]; -var ListEvaluationJobsResponse = [ - 3, - n0, - _LEJRi, - 0, - [_nT, _jSo], - [0, () => EvaluationSummaries], -]; -var ListFoundationModelAgreementOffersRequest = [ - 3, - n0, - _LFMAOR, - 0, - [_mIo, _oTf], - [ - [0, 1], - [ - 0, - { - [_hQ]: _oTf, - }, - ], - ], -]; -var ListFoundationModelAgreementOffersResponse = [ - 3, - n0, - _LFMAORi, - 0, - [_mIo, _of], - [0, () => Offers], -]; -var ListFoundationModelsRequest = [ - 3, - n0, - _LFMR, - 0, - [_bP, _bCT, _bOMy, _bIT], - [ - [ - 0, - { - [_hQ]: _bP, - }, - ], - [ - 0, - { - [_hQ]: _bCT, - }, - ], - [ - 0, - { - [_hQ]: _bOMy, - }, - ], - [ - 0, - { - [_hQ]: _bIT, - }, - ], - ], -]; -var ListFoundationModelsResponse = [ - 3, - n0, - _LFMRi, - 0, - [_mSod], - [() => FoundationModelSummaryList], -]; -var ListGuardrailsRequest = [ - 3, - n0, - _LGR, - 0, - [_gIu, _mR, _nT], - [ - [ - 0, - { - [_hQ]: _gIu, - }, - ], - [ - 1, - { - [_hQ]: _mR, - }, - ], - [ - 0, - { - [_hQ]: _nT, - }, - ], - ], -]; -var ListGuardrailsResponse = [ - 3, - n0, - _LGRi, - 0, - [_g, _nT], - [[() => GuardrailSummaries, 0], 0], -]; -var ListImportedModelsRequest = [ - 3, - n0, - _LIMR, - 0, - [_cTB, _cTA, _nC, _mR, _nT, _sB, _sO], - [ - [ - 5, - { - [_hQ]: _cTB, - }, - ], - [ - 5, - { - [_hQ]: _cTA, - }, - ], - [ - 0, - { - [_hQ]: _nC, - }, - ], - [ - 1, - { - [_hQ]: _mR, - }, - ], - [ - 0, - { - [_hQ]: _nT, - }, - ], - [ - 0, - { - [_hQ]: _sB, - }, - ], - [ - 0, - { - [_hQ]: _sO, - }, - ], - ], -]; -var ListImportedModelsResponse = [ - 3, - n0, - _LIMRi, - 0, - [_nT, _mSod], - [0, () => ImportedModelSummaryList], -]; -var ListInferenceProfilesRequest = [ - 3, - n0, - _LIPR, - 0, - [_mR, _nT, _tE], - [ - [ - 1, - { - [_hQ]: _mR, - }, - ], - [ - 0, - { - [_hQ]: _nT, - }, - ], - [ - 0, - { - [_hQ]: _ty, - }, - ], - ], -]; -var ListInferenceProfilesResponse = [ - 3, - n0, - _LIPRi, - 0, - [_iPS, _nT], - [[() => InferenceProfileSummaries, 0], 0], -]; -var ListMarketplaceModelEndpointsRequest = [ - 3, - n0, - _LMMER, - 0, - [_mR, _nT, _mSE], - [ - [ - 1, - { - [_hQ]: _mR, - }, - ], - [ - 0, - { - [_hQ]: _nT, - }, - ], - [ - 0, - { - [_hQ]: _mSI, - }, - ], - ], -]; -var ListMarketplaceModelEndpointsResponse = [ - 3, - n0, - _LMMERi, - 0, - [_mMEa, _nT], - [() => MarketplaceModelEndpointSummaries, 0], -]; -var ListModelCopyJobsRequest = [ - 3, - n0, - _LMCJR, - 0, - [_cTA, _cTB, _sEt, _sAE, _sMAE, _tMNC, _mR, _nT, _sB, _sO], - [ - [ - 5, - { - [_hQ]: _cTA, - }, - ], - [ - 5, - { - [_hQ]: _cTB, - }, - ], - [ - 0, - { - [_hQ]: _sEt, - }, - ], - [ - 0, - { - [_hQ]: _sAE, - }, - ], - [ - 0, - { - [_hQ]: _sMAE, - }, - ], - [ - 0, - { - [_hQ]: _oMNC, - }, - ], - [ - 1, - { - [_hQ]: _mR, - }, - ], - [ - 0, - { - [_hQ]: _nT, - }, - ], - [ - 0, - { - [_hQ]: _sB, - }, - ], - [ - 0, - { - [_hQ]: _sO, - }, - ], - ], -]; -var ListModelCopyJobsResponse = [ - 3, - n0, - _LMCJRi, - 0, - [_nT, _mCJS], - [0, () => ModelCopyJobSummaries], -]; -var ListModelCustomizationJobsRequest = [ - 3, - n0, - _LMCJRis, - 0, - [_cTA, _cTB, _sEt, _nC, _mR, _nT, _sB, _sO], - [ - [ - 5, - { - [_hQ]: _cTA, - }, - ], - [ - 5, - { - [_hQ]: _cTB, - }, - ], - [ - 0, - { - [_hQ]: _sEt, - }, - ], - [ - 0, - { - [_hQ]: _nC, - }, - ], - [ - 1, - { - [_hQ]: _mR, - }, - ], - [ - 0, - { - [_hQ]: _nT, - }, - ], - [ - 0, - { - [_hQ]: _sB, - }, - ], - [ - 0, - { - [_hQ]: _sO, - }, - ], - ], -]; -var ListModelCustomizationJobsResponse = [ - 3, - n0, - _LMCJRist, - 0, - [_nT, _mCJSo], - [0, () => ModelCustomizationJobSummaries], -]; -var ListModelImportJobsRequest = [ - 3, - n0, - _LMIJR, - 0, - [_cTA, _cTB, _sEt, _nC, _mR, _nT, _sB, _sO], - [ - [ - 5, - { - [_hQ]: _cTA, - }, - ], - [ - 5, - { - [_hQ]: _cTB, - }, - ], - [ - 0, - { - [_hQ]: _sEt, - }, - ], - [ - 0, - { - [_hQ]: _nC, - }, - ], - [ - 1, - { - [_hQ]: _mR, - }, - ], - [ - 0, - { - [_hQ]: _nT, - }, - ], - [ - 0, - { - [_hQ]: _sB, - }, - ], - [ - 0, - { - [_hQ]: _sO, - }, - ], - ], -]; -var ListModelImportJobsResponse = [ - 3, - n0, - _LMIJRi, - 0, - [_nT, _mIJS], - [0, () => ModelImportJobSummaries], -]; -var ListModelInvocationJobsRequest = [ - 3, - n0, - _LMIJRis, - 0, - [_sTA, _sTB, _sEt, _nC, _mR, _nT, _sB, _sO], - [ - [ - 5, - { - [_hQ]: _sTA, - }, - ], - [ - 5, - { - [_hQ]: _sTB, - }, - ], - [ - 0, - { - [_hQ]: _sEt, - }, - ], - [ - 0, - { - [_hQ]: _nC, - }, - ], - [ - 1, - { - [_hQ]: _mR, - }, - ], - [ - 0, - { - [_hQ]: _nT, - }, - ], - [ - 0, - { - [_hQ]: _sB, - }, - ], - [ - 0, - { - [_hQ]: _sO, - }, - ], - ], -]; -var ListModelInvocationJobsResponse = [ - 3, - n0, - _LMIJRist, - 0, - [_nT, _iJS], - [0, [() => ModelInvocationJobSummaries, 0]], -]; -var ListPromptRoutersRequest = [ - 3, - n0, - _LPRR, - 0, - [_mR, _nT, _ty], - [ - [ - 1, - { - [_hQ]: _mR, - }, - ], - [ - 0, - { - [_hQ]: _nT, - }, - ], - [ - 0, - { - [_hQ]: _ty, - }, - ], - ], -]; -var ListPromptRoutersResponse = [ - 3, - n0, - _LPRRi, - 0, - [_pRS, _nT], - [[() => PromptRouterSummaries, 0], 0], -]; -var ListProvisionedModelThroughputsRequest = [ - 3, - n0, - _LPMTR, - 0, - [_cTA, _cTB, _sEt, _mAE, _nC, _mR, _nT, _sB, _sO], - [ - [ - 5, - { - [_hQ]: _cTA, - }, - ], - [ - 5, - { - [_hQ]: _cTB, - }, - ], - [ - 0, - { - [_hQ]: _sEt, - }, - ], - [ - 0, - { - [_hQ]: _mAE, - }, - ], - [ - 0, - { - [_hQ]: _nC, - }, - ], - [ - 1, - { - [_hQ]: _mR, - }, - ], - [ - 0, - { - [_hQ]: _nT, - }, - ], - [ - 0, - { - [_hQ]: _sB, - }, - ], - [ - 0, - { - [_hQ]: _sO, - }, - ], - ], -]; -var ListProvisionedModelThroughputsResponse = [ - 3, - n0, - _LPMTRi, - 0, - [_nT, _pMS], - [0, () => ProvisionedModelSummaries], -]; -var ListTagsForResourceRequest = [3, n0, _LTFRR, 0, [_rARN], [0]]; -var ListTagsForResourceResponse = [3, n0, _LTFRRi, 0, [_ta], [() => TagList]]; -var LoggingConfig = [ - 3, - n0, - _LC, - 0, - [_cWC, _sC, _tDDE, _iDDE, _eDDE, _vDDE], - [() => CloudWatchConfig, () => S3Config, 2, 2, 2, 2], -]; -var MarketplaceModelEndpoint = [ - 3, - n0, - _MME, - 0, - [_eA, _mSI, _s, _sM, _cA, _uA, _eCn, _eS, _eSM], - [0, 0, 0, 0, 5, 5, () => EndpointConfig, 0, 0], -]; -var MarketplaceModelEndpointSummary = [ - 3, - n0, - _MMES, - 0, - [_eA, _mSI, _s, _sM, _cA, _uA], - [0, 0, 0, 0, 5, 5], -]; -var MetadataAttributeSchema = [3, n0, _MAS, 8, [_k, _ty, _d], [0, 0, 0]]; -var MetadataConfigurationForReranking = [ - 3, - n0, - _MCFR, - 0, - [_sMe, _sMC], - [0, [() => RerankingMetadataSelectiveModeConfiguration, 0]], -]; -var ModelCopyJobSummary = [ - 3, - n0, - _MCJS, - 0, - [_jA, _s, _cTr, _tMA, _tMN, _sAI, _sMA, _tMKKA, _tMT, _fMa, _sMN], - [0, 0, 5, 0, 0, 0, 0, 0, () => TagList, 0, 0], -]; -var ModelCustomizationJobSummary = [ - 3, - n0, - _MCJSo, - 0, - [_jA, _bMA, _jN, _s, _sD, _lMT, _cTr, _eT, _cMA, _cMN, _cTu], - [0, 0, 0, 0, () => StatusDetails, 5, 5, 5, 0, 0, 0], -]; -var ModelImportJobSummary = [ - 3, - n0, - _MIJS, - 0, - [_jA, _jN, _s, _lMT, _cTr, _eT, _iMA, _iMN], - [0, 0, 0, 5, 5, 5, 0, 0], -]; -var ModelInvocationJobS3InputDataConfig = [ - 3, - n0, - _MIJSIDC, - 0, - [_sIF, _sU, _sBO], - [0, 0, 0], -]; -var ModelInvocationJobS3OutputDataConfig = [ - 3, - n0, - _MIJSODC, - 0, - [_sU, _sEKI, _sBO], - [0, 0, 0], -]; -var ModelInvocationJobSummary = [ - 3, - n0, - _MIJSo, - 0, - [_jA, _jN, _mIo, _cRT, _rA, _s, _m, _sTu, _lMT, _eT, _iDC, _oDC, _vCp, _tDIH, _jET], - [ - 0, - 0, - 0, - 0, - 0, - 0, - [() => Message, 0], - 5, - 5, - 5, - () => ModelInvocationJobInputDataConfig, - () => ModelInvocationJobOutputDataConfig, - () => VpcConfig, - 1, - 5, - ], -]; -var Offer = [3, n0, _O, 0, [_oI, _oT, _tD], [0, 0, () => TermDetails]]; -var OrchestrationConfiguration = [ - 3, - n0, - _OC, - 0, - [_qTC], - [() => QueryTransformationConfiguration], -]; -var OutputDataConfig = [3, n0, _ODC, 0, [_sU], [0]]; -var PerformanceConfiguration = [3, n0, _PC, 0, [_la], [0]]; -var PricingTerm = [3, n0, _PT, 0, [_rCa], [() => RateCard]]; -var PromptRouterSummary = [ - 3, - n0, - _PRS, - 0, - [_pRN, _rCo, _d, _cA, _uA, _pRA, _mo, _fM, _s, _ty], - [ - 0, - () => RoutingCriteria, - [() => PromptRouterDescription, 0], - 5, - 5, - 0, - () => PromptRouterTargetModels, - () => PromptRouterTargetModel, - 0, - 0, - ], -]; -var PromptRouterTargetModel = [3, n0, _PRTM, 0, [_mA], [0]]; -var PromptTemplate = [3, n0, _PTr, 0, [_tPT], [[() => TextPromptTemplate, 0]]]; -var ProvisionedModelSummary = [ - 3, - n0, - _PMS, - 0, - [_pMN, _pMA, _mA, _dMA, _fMA, _mU, _dMU, _s, _cD, _cET, _cTr, _lMT], - [0, 0, 0, 0, 0, 1, 1, 0, 0, 5, 5, 5], -]; -var PutModelInvocationLoggingConfigurationRequest = [ - 3, - n0, - _PMILCR, - 0, - [_lC], - [() => LoggingConfig], -]; -var PutModelInvocationLoggingConfigurationResponse = [3, n0, _PMILCRu, 0, [], []]; -var PutUseCaseForModelAccessRequest = [3, n0, _PUCFMAR, 0, [_fD], [21]]; -var PutUseCaseForModelAccessResponse = [3, n0, _PUCFMARu, 0, [], []]; -var QueryTransformationConfiguration = [3, n0, _QTC, 0, [_ty], [0]]; -var RatingScaleItem = [3, n0, _RSI, 0, [_de, _va], [0, () => RatingScaleItemValue]]; -var RegisterMarketplaceModelEndpointRequest = [ - 3, - n0, - _RMMER, - 0, - [_eI, _mSI], - [[0, 1], 0], -]; -var RegisterMarketplaceModelEndpointResponse = [ - 3, - n0, - _RMMERe, - 0, - [_mME], - [() => MarketplaceModelEndpoint], -]; -var RequestMetadataBaseFilters = [ - 3, - n0, - _RMBF, - 0, - [_eq, _nE], - [ - [() => RequestMetadataMap, 0], - [() => RequestMetadataMap, 0], - ], -]; -var ResourceInUseException = [ - -3, - n0, - _RIUE, - { - [_e]: _c, - [_hE]: 400, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ResourceInUseException, ResourceInUseException$1); -var ResourceNotFoundException = [ - -3, - n0, - _RNFE, - { - [_e]: _c, - [_hE]: 404, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ResourceNotFoundException, ResourceNotFoundException$1); -var RetrieveAndGenerateConfiguration = [ - 3, - n0, - _RAGC, - 0, - [_ty, _kBC, _eSC], - [ - 0, - [() => KnowledgeBaseRetrieveAndGenerateConfiguration, 0], - [() => ExternalSourcesRetrieveAndGenerateConfiguration, 0], - ], -]; -var RetrieveConfig = [ - 3, - n0, - _RC, - 0, - [_kBI, _kBRC], - [0, [() => KnowledgeBaseRetrievalConfiguration, 0]], -]; -var RoutingCriteria = [3, n0, _RCo, 0, [_rQD], [1]]; -var S3Config = [3, n0, _SC, 0, [_bN, _kP], [0, 0]]; -var S3DataSource = [3, n0, _SDS, 0, [_sU], [0]]; -var S3ObjectDoc = [3, n0, _SOD, 0, [_uri], [0]]; -var SageMakerEndpoint = [ - 3, - n0, - _SME, - 0, - [_iIC, _iT, _eRx, _kEK, _vp], - [1, 0, 0, 0, () => VpcConfig], -]; -var ServiceQuotaExceededException = [ - -3, - n0, - _SQEE, - { - [_e]: _c, - [_hE]: 400, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ServiceQuotaExceededException, ServiceQuotaExceededException$1); -var ServiceUnavailableException = [ - -3, - n0, - _SUE, - { - [_e]: _se, - [_hE]: 503, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ServiceUnavailableException, ServiceUnavailableException$1); -var StartAutomatedReasoningPolicyBuildWorkflowRequest = [ - 3, - n0, - _SARPBWR, - 0, - [_pA, _bWT, _cRT, _sCo], - [ - [0, 1], - [0, 1], - [ - 0, - { - [_hH]: _xact, - [_iTd]: 1, - }, - ], - [() => AutomatedReasoningPolicyBuildWorkflowSource, 16], - ], -]; -var StartAutomatedReasoningPolicyBuildWorkflowResponse = [ - 3, - n0, - _SARPBWRt, - 0, - [_pA, _bWI], - [0, 0], -]; -var StartAutomatedReasoningPolicyTestWorkflowRequest = [ - 3, - n0, - _SARPTWR, - 0, - [_pA, _bWI, _tCIe, _cRT], - [[0, 1], [0, 1], 64 | 0, [0, 4]], -]; -var StartAutomatedReasoningPolicyTestWorkflowResponse = [3, n0, _SARPTWRt, 0, [_pA], [0]]; -var StatusDetails = [ - 3, - n0, - _SD, - 0, - [_vD, _dPD, _tDr], - [() => ValidationDetails, () => DataProcessingDetails, () => TrainingDetails], -]; -var StopEvaluationJobRequest = [ - 3, - n0, - _SEJR, - 0, - [_jI], - [[() => EvaluationJobIdentifier, 1]], -]; -var StopEvaluationJobResponse = [3, n0, _SEJRt, 0, [], []]; -var StopModelCustomizationJobRequest = [3, n0, _SMCJR, 0, [_jI], [[0, 1]]]; -var StopModelCustomizationJobResponse = [3, n0, _SMCJRt, 0, [], []]; -var StopModelInvocationJobRequest = [3, n0, _SMIJR, 0, [_jI], [[0, 1]]]; -var StopModelInvocationJobResponse = [3, n0, _SMIJRt, 0, [], []]; -var SupportTerm = [3, n0, _ST, 0, [_rPD], [0]]; -var Tag = [3, n0, _T, 0, [_k, _va], [0, 0]]; -var TagResourceRequest = [3, n0, _TRR, 0, [_rARN, _ta], [0, () => TagList]]; -var TagResourceResponse = [3, n0, _TRRa, 0, [], []]; -var TeacherModelConfig = [3, n0, _TMC, 0, [_tMI, _mRLFI], [0, 1]]; -var TermDetails = [ - 3, - n0, - _TD, - 0, - [_uBPT, _lT, _sTup, _vT], - [() => PricingTerm, () => LegalTerm, () => SupportTerm, () => ValidityTerm], -]; -var TextInferenceConfig = [3, n0, _TIC, 0, [_tem, _tPo, _mTa, _sS], [1, 1, 1, 64 | 0]]; -var ThrottlingException = [ - -3, - n0, - _TE, - { - [_e]: _c, - [_hE]: 429, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ThrottlingException, ThrottlingException$1); -var TooManyTagsException = [ - -3, - n0, - _TMTE, - { - [_e]: _c, - [_hE]: 400, - }, - [_m, _rN], - [0, 0], -]; -schema.TypeRegistry.for(n0).registerError(TooManyTagsException, TooManyTagsException$1); -var TrainingDataConfig = [ - 3, - n0, - _TDC, - 0, - [_sU, _iLC], - [0, [() => InvocationLogsConfig, 0]], -]; -var TrainingDetails = [3, n0, _TDr, 0, [_s, _cTr, _lMT], [0, 5, 5]]; -var TrainingMetrics = [3, n0, _TM, 0, [_tL], [1]]; -var UntagResourceRequest = [3, n0, _URR, 0, [_rARN, _tK], [0, 64 | 0]]; -var UntagResourceResponse = [3, n0, _URRn, 0, [], []]; -var UpdateAutomatedReasoningPolicyAnnotationsRequest = [ - 3, - n0, - _UARPAR, - 0, - [_pA, _bWI, _an, _lUASH], - [[0, 1], [0, 1], [() => AutomatedReasoningPolicyAnnotationList, 0], 0], -]; -var UpdateAutomatedReasoningPolicyAnnotationsResponse = [ - 3, - n0, - _UARPARp, - 0, - [_pA, _bWI, _aSH, _uA], - [0, 0, 0, 5], -]; -var UpdateAutomatedReasoningPolicyRequest = [ - 3, - n0, - _UARPR, - 0, - [_pA, _pD, _n, _d], - [ - [0, 1], - [() => AutomatedReasoningPolicyDefinition, 0], - [() => AutomatedReasoningPolicyName, 0], - [() => AutomatedReasoningPolicyDescription, 0], - ], -]; -var UpdateAutomatedReasoningPolicyResponse = [ - 3, - n0, - _UARPRp, - 0, - [_pA, _n, _dH, _uA], - [0, [() => AutomatedReasoningPolicyName, 0], 0, 5], -]; -var UpdateAutomatedReasoningPolicyTestCaseRequest = [ - 3, - n0, - _UARPTCR, - 0, - [_pA, _tCI, _gC, _qC, _lUA, _eAFR, _cT, _cRT], - [ - [0, 1], - [0, 1], - [() => AutomatedReasoningPolicyTestGuardContent, 0], - [() => AutomatedReasoningPolicyTestQueryContent, 0], - 5, - 0, - 1, - [0, 4], - ], -]; -var UpdateAutomatedReasoningPolicyTestCaseResponse = [ - 3, - n0, - _UARPTCRp, - 0, - [_pA, _tCI], - [0, 0], -]; -var UpdateGuardrailRequest = [ - 3, - n0, - _UGR, - 0, - [_gIu, _n, _d, _tPC, _cPC, _wPC, _sIPC, _cGPC, _aRPC, _cRC, _bIM, _bOM, _kKI], - [ - [0, 1], - [() => GuardrailName, 0], - [() => GuardrailDescription, 0], - [() => GuardrailTopicPolicyConfig, 0], - [() => GuardrailContentPolicyConfig, 0], - [() => GuardrailWordPolicyConfig, 0], - () => GuardrailSensitiveInformationPolicyConfig, - [() => GuardrailContextualGroundingPolicyConfig, 0], - () => GuardrailAutomatedReasoningPolicyConfig, - () => GuardrailCrossRegionConfig, - [() => GuardrailBlockedMessaging, 0], - [() => GuardrailBlockedMessaging, 0], - 0, - ], -]; -var UpdateGuardrailResponse = [3, n0, _UGRp, 0, [_gI, _gA, _ve, _uA], [0, 0, 0, 5]]; -var UpdateMarketplaceModelEndpointRequest = [ - 3, - n0, - _UMMER, - 0, - [_eA, _eCn, _cRT], - [[0, 1], () => EndpointConfig, [0, 4]], -]; -var UpdateMarketplaceModelEndpointResponse = [ - 3, - n0, - _UMMERp, - 0, - [_mME], - [() => MarketplaceModelEndpoint], -]; -var UpdateProvisionedModelThroughputRequest = [ - 3, - n0, - _UPMTR, - 0, - [_pMI, _dPMN, _dMI], - [[0, 1], 0, 0], -]; -var UpdateProvisionedModelThroughputResponse = [3, n0, _UPMTRp, 0, [], []]; -var ValidationDataConfig = [3, n0, _VDC, 0, [_val], [() => Validators]]; -var ValidationDetails = [3, n0, _VD, 0, [_s, _cTr, _lMT], [0, 5, 5]]; -var ValidationException = [ - -3, - n0, - _VE, - { - [_e]: _c, - [_hE]: 400, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ValidationException, ValidationException$1); -var Validator = [3, n0, _V, 0, [_sU], [0]]; -var ValidatorMetric = [3, n0, _VM, 0, [_vL], [1]]; -var ValidityTerm = [3, n0, _VT, 0, [_aD], [0]]; -var VectorSearchBedrockRerankingConfiguration = [ - 3, - n0, - _VSBRC, - 0, - [_mC, _nORR, _mCe], - [() => VectorSearchBedrockRerankingModelConfiguration, 1, [() => MetadataConfigurationForReranking, 0]], -]; -var VectorSearchBedrockRerankingModelConfiguration = [ - 3, - n0, - _VSBRMC, - 0, - [_mA, _aMRF], - [0, 128 | 15], -]; -var VectorSearchRerankingConfiguration = [ - 3, - n0, - _VSRC, - 0, - [_ty, _bRC], - [0, [() => VectorSearchBedrockRerankingConfiguration, 0]], -]; -var VpcConfig = [3, n0, _VC, 0, [_sI, _sGI], [64 | 0, 64 | 0]]; -var BedrockServiceException = [-3, _sm, "BedrockServiceException", 0, [], []]; -schema.TypeRegistry.for(_sm).registerError(BedrockServiceException, BedrockServiceException$1); -var AutomatedEvaluationCustomMetrics = [ - 1, - n0, - _AECM, - 0, - [() => AutomatedEvaluationCustomMetricSource, 0], -]; -var AutomatedReasoningCheckDifferenceScenarioList = [ - 1, - n0, - _ARCDSL, - 0, - [() => AutomatedReasoningCheckScenario, 0], -]; -var AutomatedReasoningCheckFindingList = [ - 1, - n0, - _ARCFL, - 0, - [() => AutomatedReasoningCheckFinding, 0], -]; -var AutomatedReasoningCheckInputTextReferenceList = [ - 1, - n0, - _ARCITRL, - 0, - [() => AutomatedReasoningCheckInputTextReference, 0], -]; -var AutomatedReasoningCheckRuleList = [1, n0, _ARCRL, 0, () => AutomatedReasoningCheckRule]; -var AutomatedReasoningCheckTranslationList = [ - 1, - n0, - _ARCTL, - 0, - [() => AutomatedReasoningCheckTranslation, 0], -]; -var AutomatedReasoningCheckTranslationOptionList = [ - 1, - n0, - _ARCTOL, - 0, - [() => AutomatedReasoningCheckTranslationOption, 0], -]; -var AutomatedReasoningLogicStatementList = [ - 1, - n0, - _ARLSL, - 0, - [() => AutomatedReasoningLogicStatement, 0], -]; -var AutomatedReasoningPolicyAnnotationList = [ - 1, - n0, - _ARPAL, - 0, - [() => AutomatedReasoningPolicyAnnotation, 0], -]; -var AutomatedReasoningPolicyBuildLogEntryList = [ - 1, - n0, - _ARPBLEL, - 0, - [() => AutomatedReasoningPolicyBuildLogEntry, 0], -]; -var AutomatedReasoningPolicyBuildStepList = [ - 1, - n0, - _ARPBSL, - 0, - [() => AutomatedReasoningPolicyBuildStep, 0], -]; -var AutomatedReasoningPolicyBuildStepMessageList = [ - 1, - n0, - _ARPBSML, - 0, - () => AutomatedReasoningPolicyBuildStepMessage, -]; -var AutomatedReasoningPolicyBuildWorkflowDocumentList = [ - 1, - n0, - _ARPBWDL, - 0, - [() => AutomatedReasoningPolicyBuildWorkflowDocument, 0], -]; -var AutomatedReasoningPolicyBuildWorkflowSummaries = [ - 1, - n0, - _ARPBWSut, - 0, - () => AutomatedReasoningPolicyBuildWorkflowSummary, -]; -var AutomatedReasoningPolicyDefinitionRuleList = [ - 1, - n0, - _ARPDRL, - 0, - [() => AutomatedReasoningPolicyDefinitionRule, 0], -]; -var AutomatedReasoningPolicyDefinitionTypeList = [ - 1, - n0, - _ARPDTL, - 0, - [() => AutomatedReasoningPolicyDefinitionType, 0], -]; -var AutomatedReasoningPolicyDefinitionTypeNameList = [ - 1, - n0, - _ARPDTNL, - 0, - [() => AutomatedReasoningPolicyDefinitionTypeName, 0], -]; -var AutomatedReasoningPolicyDefinitionTypeValueList = [ - 1, - n0, - _ARPDTVL, - 0, - [() => AutomatedReasoningPolicyDefinitionTypeValue, 0], -]; -var AutomatedReasoningPolicyDefinitionTypeValuePairList = [ - 1, - n0, - _ARPDTVPL, - 0, - [() => AutomatedReasoningPolicyDefinitionTypeValuePair, 0], -]; -var AutomatedReasoningPolicyDefinitionVariableList = [ - 1, - n0, - _ARPDVL, - 0, - [() => AutomatedReasoningPolicyDefinitionVariable, 0], -]; -var AutomatedReasoningPolicyDefinitionVariableNameList = [ - 1, - n0, - _ARPDVNL, - 0, - [() => AutomatedReasoningPolicyDefinitionVariableName, 0], -]; -var AutomatedReasoningPolicyDisjointRuleSetList = [ - 1, - n0, - _ARPDRSL, - 0, - [() => AutomatedReasoningPolicyDisjointRuleSet, 0], -]; -var AutomatedReasoningPolicyGeneratedTestCaseList = [ - 1, - n0, - _ARPGTCL, - 0, - [() => AutomatedReasoningPolicyGeneratedTestCase, 0], -]; -var AutomatedReasoningPolicySummaries = [ - 1, - n0, - _ARPSut, - 0, - [() => AutomatedReasoningPolicySummary, 0], -]; -var AutomatedReasoningPolicyTestCaseList = [ - 1, - n0, - _ARPTCL, - 0, - [() => AutomatedReasoningPolicyTestCase, 0], -]; -var AutomatedReasoningPolicyTestList = [ - 1, - n0, - _ARPTL, - 0, - [() => AutomatedReasoningPolicyTestResult, 0], -]; -var AutomatedReasoningPolicyTypeValueAnnotationList = [ - 1, - n0, - _ARPTVAL, - 0, - [() => AutomatedReasoningPolicyTypeValueAnnotation, 0], -]; -var BatchDeleteEvaluationJobErrors = [ - 1, - n0, - _BDEJEa, - 0, - [() => BatchDeleteEvaluationJobError, 0], -]; -var BatchDeleteEvaluationJobItems = [ - 1, - n0, - _BDEJIa, - 0, - [() => BatchDeleteEvaluationJobItem, 0], -]; -var BedrockEvaluatorModels = [1, n0, _BEMe, 0, () => BedrockEvaluatorModel]; -var CustomMetricBedrockEvaluatorModels = [ - 1, - n0, - _CMBEMu, - 0, - () => CustomMetricBedrockEvaluatorModel, -]; -var CustomModelDeploymentSummaryList = [1, n0, _CMDSL, 0, () => CustomModelDeploymentSummary]; -var CustomModelSummaryList = [1, n0, _CMSL, 0, () => CustomModelSummary]; -var EvaluationDatasetMetricConfigs = [ - 1, - n0, - _EDMCv, - 0, - [() => EvaluationDatasetMetricConfig, 0], -]; -var EvaluationJobIdentifiers = [1, n0, _EJIv, 0, [() => EvaluationJobIdentifier, 0]]; -var EvaluationMetricNames = [1, n0, _EMNv, 0, [() => EvaluationMetricName, 0]]; -var EvaluationModelConfigs = [1, n0, _EMC, 0, [() => EvaluationModelConfig, 0]]; -var EvaluationSummaries = [1, n0, _ESv, 0, () => EvaluationSummary]; -var ExternalSources = [1, n0, _ESxt, 0, [() => ExternalSource, 0]]; -var FieldsForReranking = [1, n0, _FFRi, 8, () => FieldForReranking]; -var FoundationModelSummaryList = [1, n0, _FMSL, 0, () => FoundationModelSummary]; -var GuardrailContentFilters = [1, n0, _GCFu, 0, [() => GuardrailContentFilter, 0]]; -var GuardrailContentFiltersConfig = [ - 1, - n0, - _GCFCu, - 0, - [() => GuardrailContentFilterConfig, 0], -]; -var GuardrailContextualGroundingFilters = [ - 1, - n0, - _GCGFu, - 0, - [() => GuardrailContextualGroundingFilter, 0], -]; -var GuardrailContextualGroundingFiltersConfig = [ - 1, - n0, - _GCGFCu, - 0, - [() => GuardrailContextualGroundingFilterConfig, 0], -]; -var GuardrailFailureRecommendations = [ - 1, - n0, - _GFRu, - 0, - [() => GuardrailFailureRecommendation, 0], -]; -var GuardrailManagedWordLists = [1, n0, _GMWL, 0, [() => GuardrailManagedWords, 0]]; -var GuardrailManagedWordListsConfig = [ - 1, - n0, - _GMWLC, - 0, - [() => GuardrailManagedWordsConfig, 0], -]; -var GuardrailModalities = [1, n0, _GMu, 0, [() => GuardrailModality$1, 0]]; -var GuardrailPiiEntities = [1, n0, _GPEu, 0, () => GuardrailPiiEntity]; -var GuardrailPiiEntitiesConfig = [1, n0, _GPECu, 0, () => GuardrailPiiEntityConfig]; -var GuardrailRegexes = [1, n0, _GRu, 0, () => GuardrailRegex]; -var GuardrailRegexesConfig = [1, n0, _GRCu, 0, () => GuardrailRegexConfig]; -var GuardrailStatusReasons = [1, n0, _GSRu, 0, [() => GuardrailStatusReason, 0]]; -var GuardrailSummaries = [1, n0, _GSu, 0, [() => GuardrailSummary, 0]]; -var GuardrailTopicExamples = [1, n0, _GTEu, 0, [() => GuardrailTopicExample, 0]]; -var GuardrailTopics = [1, n0, _GTu, 0, [() => GuardrailTopic, 0]]; -var GuardrailTopicsConfig = [1, n0, _GTCu, 0, [() => GuardrailTopicConfig, 0]]; -var GuardrailWords = [1, n0, _GWu, 0, [() => GuardrailWord, 0]]; -var GuardrailWordsConfig = [1, n0, _GWCu, 0, [() => GuardrailWordConfig, 0]]; -var HumanEvaluationCustomMetrics = [1, n0, _HECMu, 0, [() => HumanEvaluationCustomMetric, 0]]; -var ImportedModelSummaryList = [1, n0, _IMSL, 0, () => ImportedModelSummary]; -var InferenceProfileModels = [1, n0, _IPMn, 0, () => InferenceProfileModel]; -var InferenceProfileSummaries = [1, n0, _IPSn, 0, [() => InferenceProfileSummary, 0]]; -var MarketplaceModelEndpointSummaries = [ - 1, - n0, - _MMESa, - 0, - () => MarketplaceModelEndpointSummary, -]; -var MetadataAttributeSchemaList = [1, n0, _MASL, 0, [() => MetadataAttributeSchema, 0]]; -var ModelCopyJobSummaries = [1, n0, _MCJSod, 0, () => ModelCopyJobSummary]; -var ModelCustomizationJobSummaries = [1, n0, _MCJSode, 0, () => ModelCustomizationJobSummary]; -var ModelImportJobSummaries = [1, n0, _MIJSod, 0, () => ModelImportJobSummary]; -var ModelInvocationJobSummaries = [1, n0, _MIJSode, 0, [() => ModelInvocationJobSummary, 0]]; -var Offers = [1, n0, _Of, 0, () => Offer]; -var PromptRouterSummaries = [1, n0, _PRSr, 0, [() => PromptRouterSummary, 0]]; -var PromptRouterTargetModels = [1, n0, _PRTMr, 0, () => PromptRouterTargetModel]; -var ProvisionedModelSummaries = [1, n0, _PMSr, 0, () => ProvisionedModelSummary]; -var RagConfigs = [1, n0, _RCa, 0, [() => RAGConfig, 0]]; -var RateCard = [1, n0, _RCat, 0, () => DimensionalPriceRate]; -var RatingScale = [1, n0, _RS, 0, () => RatingScaleItem]; -var RequestMetadataFiltersList = [1, n0, _RMFL, 0, [() => RequestMetadataBaseFilters, 0]]; -var RetrievalFilterList = [1, n0, _RFL, 0, [() => RetrievalFilter, 0]]; -var TagList = [1, n0, _TL, 0, () => Tag]; -var ValidationMetrics = [1, n0, _VMa, 0, () => ValidatorMetric]; -var Validators = [1, n0, _Va, 0, () => Validator]; -var RequestMetadataMap = [2, n0, _RMM, 8, 0, 0]; -var AutomatedEvaluationCustomMetricSource = [ - 3, - n0, - _AECMS, - 0, - [_cMD], - [[() => CustomMetricDefinition, 0]], -]; -var AutomatedReasoningCheckFinding = [ - 3, - n0, - _ARCF, - 0, - [_vali, _inv, _sa, _im, _tA, _tCoo, _nTo], - [ - [() => AutomatedReasoningCheckValidFinding, 0], - [() => AutomatedReasoningCheckInvalidFinding, 0], - [() => AutomatedReasoningCheckSatisfiableFinding, 0], - [() => AutomatedReasoningCheckImpossibleFinding, 0], - [() => AutomatedReasoningCheckTranslationAmbiguousFinding, 0], - () => AutomatedReasoningCheckTooComplexFinding, - () => AutomatedReasoningCheckNoTranslationsFinding, - ], -]; -var AutomatedReasoningPolicyAnnotation = [ - 3, - n0, - _ARPA, - 0, - [_aTd, _uTp, _dT, _aV, _uVp, _dV, _aR, _uR, _dR, _aRFNL, _uFRF, _uFSF, _iCn], - [ - [() => AutomatedReasoningPolicyAddTypeAnnotation, 0], - [() => AutomatedReasoningPolicyUpdateTypeAnnotation, 0], - [() => AutomatedReasoningPolicyDeleteTypeAnnotation, 0], - [() => AutomatedReasoningPolicyAddVariableAnnotation, 0], - [() => AutomatedReasoningPolicyUpdateVariableAnnotation, 0], - [() => AutomatedReasoningPolicyDeleteVariableAnnotation, 0], - [() => AutomatedReasoningPolicyAddRuleAnnotation, 0], - [() => AutomatedReasoningPolicyUpdateRuleAnnotation, 0], - () => AutomatedReasoningPolicyDeleteRuleAnnotation, - [() => AutomatedReasoningPolicyAddRuleFromNaturalLanguageAnnotation, 0], - [() => AutomatedReasoningPolicyUpdateFromRuleFeedbackAnnotation, 0], - [() => AutomatedReasoningPolicyUpdateFromScenarioFeedbackAnnotation, 0], - [() => AutomatedReasoningPolicyIngestContentAnnotation, 0], - ], -]; -var AutomatedReasoningPolicyBuildResultAssets = [ - 3, - n0, - _ARPBRA, - 0, - [_pD, _qR, _bL, _gTC], - [ - [() => AutomatedReasoningPolicyDefinition, 0], - [() => AutomatedReasoningPolicyDefinitionQualityReport, 0], - [() => AutomatedReasoningPolicyBuildLog, 0], - [() => AutomatedReasoningPolicyGeneratedTestCases, 0], - ], -]; -var AutomatedReasoningPolicyBuildStepContext = [ - 3, - n0, - _ARPBSC, - 0, - [_pl, _mu], - [() => AutomatedReasoningPolicyPlanning, [() => AutomatedReasoningPolicyMutation, 0]], -]; -var AutomatedReasoningPolicyDefinitionElement = [ - 3, - n0, - _ARPDE, - 0, - [_pDV, _pDT, _pDR], - [ - [() => AutomatedReasoningPolicyDefinitionVariable, 0], - [() => AutomatedReasoningPolicyDefinitionType, 0], - [() => AutomatedReasoningPolicyDefinitionRule, 0], - ], -]; -var AutomatedReasoningPolicyMutation = [ - 3, - n0, - _ARPM, - 0, - [_aTd, _uTp, _dT, _aV, _uVp, _dV, _aR, _uR, _dR], - [ - [() => AutomatedReasoningPolicyAddTypeMutation, 0], - [() => AutomatedReasoningPolicyUpdateTypeMutation, 0], - [() => AutomatedReasoningPolicyDeleteTypeMutation, 0], - [() => AutomatedReasoningPolicyAddVariableMutation, 0], - [() => AutomatedReasoningPolicyUpdateVariableMutation, 0], - [() => AutomatedReasoningPolicyDeleteVariableMutation, 0], - [() => AutomatedReasoningPolicyAddRuleMutation, 0], - [() => AutomatedReasoningPolicyUpdateRuleMutation, 0], - () => AutomatedReasoningPolicyDeleteRuleMutation, - ], -]; -var AutomatedReasoningPolicyTypeValueAnnotation = [ - 3, - n0, - _ARPTVA, - 0, - [_aTV, _uTVp, _dTV], - [ - [() => AutomatedReasoningPolicyAddTypeValue, 0], - [() => AutomatedReasoningPolicyUpdateTypeValue, 0], - () => AutomatedReasoningPolicyDeleteTypeValue, - ], -]; -var AutomatedReasoningPolicyWorkflowTypeContent = [ - 3, - n0, - _ARPWTC, - 0, - [_doc, _pRAo], - [ - [() => AutomatedReasoningPolicyBuildWorkflowDocumentList, 0], - [() => AutomatedReasoningPolicyBuildWorkflowRepairContent, 0], - ], -]; -var CustomizationConfig = [3, n0, _CC, 0, [_dC], [() => DistillationConfig]]; -var EndpointConfig = [3, n0, _EC, 0, [_sMa], [() => SageMakerEndpoint]]; -var EvaluationConfig = [ - 3, - n0, - _ECv, - 0, - [_au, _h], - [ - [() => AutomatedEvaluationConfig, 0], - [() => HumanEvaluationConfig, 0], - ], -]; -var EvaluationDatasetLocation = [3, n0, _EDL, 0, [_sU], [0]]; -var EvaluationInferenceConfig = [ - 3, - n0, - _EIC, - 0, - [_mo, _rCag], - [ - [() => EvaluationModelConfigs, 0], - [() => RagConfigs, 0], - ], -]; -var EvaluationModelConfig = [ - 3, - n0, - _EMCv, - 0, - [_bM, _pIS], - [[() => EvaluationBedrockModel, 0], () => EvaluationPrecomputedInferenceSource], -]; -var EvaluationPrecomputedRagSourceConfig = [ - 3, - n0, - _EPRSCv, - 0, - [_rSC, _rAGSC], - [() => EvaluationPrecomputedRetrieveSourceConfig, () => EvaluationPrecomputedRetrieveAndGenerateSourceConfig], -]; -var EvaluatorModelConfig = [3, n0, _EMCva, 0, [_bEM], [() => BedrockEvaluatorModels]]; -var InferenceProfileModelSource = [3, n0, _IPMS, 0, [_cF], [0]]; -var InvocationLogSource = [3, n0, _ILS, 0, [_sU], [0]]; -var KnowledgeBaseConfig = [ - 3, - n0, - _KBC, - 0, - [_rCetr, _rAGC], - [ - [() => RetrieveConfig, 0], - [() => RetrieveAndGenerateConfiguration, 0], - ], -]; -var ModelDataSource = [3, n0, _MDS, 0, [_sDS], [() => S3DataSource]]; -var ModelInvocationJobInputDataConfig = [ - 3, - n0, - _MIJIDC, - 0, - [_sIDC], - [() => ModelInvocationJobS3InputDataConfig], -]; -var ModelInvocationJobOutputDataConfig = [ - 3, - n0, - _MIJODC, - 0, - [_sODC], - [() => ModelInvocationJobS3OutputDataConfig], -]; -var RAGConfig = [ - 3, - n0, - _RAGCo, - 0, - [_kBCn, _pRSC], - [[() => KnowledgeBaseConfig, 0], () => EvaluationPrecomputedRagSourceConfig], -]; -var RatingScaleItemValue = [3, n0, _RSIV, 0, [_sV, _fV], [0, 1]]; -var RequestMetadataFilters = [ - 3, - n0, - _RMF, - 0, - [_eq, _nE, _aAn, _oAr], - [ - [() => RequestMetadataMap, 0], - [() => RequestMetadataMap, 0], - [() => RequestMetadataFiltersList, 0], - [() => RequestMetadataFiltersList, 0], - ], -]; -var RerankingMetadataSelectiveModeConfiguration = [ - 3, - n0, - _RMSMC, - 0, - [_fTI, _fTE], - [ - [() => FieldsForReranking, 0], - [() => FieldsForReranking, 0], - ], -]; -var RetrievalFilter = [ - 3, - n0, - _RF, - 8, - [_eq, _nE, _gT, _gTOE, _lTe, _lTOE, _in_, _nI, _sW, _lCi, _sCt, _aAn, _oAr], - [ - () => FilterAttribute, - () => FilterAttribute, - () => FilterAttribute, - () => FilterAttribute, - () => FilterAttribute, - () => FilterAttribute, - () => FilterAttribute, - () => FilterAttribute, - () => FilterAttribute, - () => FilterAttribute, - () => FilterAttribute, - [() => RetrievalFilterList, 0], - [() => RetrievalFilterList, 0], - ], -]; -var BatchDeleteEvaluationJob = [ - 9, - n0, - _BDEJ, - { - [_ht]: ["POST", "/evaluation-jobs/batch-delete", 202], - }, - () => BatchDeleteEvaluationJobRequest, - () => BatchDeleteEvaluationJobResponse, -]; -var CancelAutomatedReasoningPolicyBuildWorkflow = [ - 9, - n0, - _CARPBW, - { - [_ht]: ["POST", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/cancel", 202], - }, - () => CancelAutomatedReasoningPolicyBuildWorkflowRequest, - () => CancelAutomatedReasoningPolicyBuildWorkflowResponse, -]; -var CreateAutomatedReasoningPolicy = [ - 9, - n0, - _CARP, - { - [_ht]: ["POST", "/automated-reasoning-policies", 200], - }, - () => CreateAutomatedReasoningPolicyRequest, - () => CreateAutomatedReasoningPolicyResponse, -]; -var CreateAutomatedReasoningPolicyTestCase = [ - 9, - n0, - _CARPTC, - { - [_ht]: ["POST", "/automated-reasoning-policies/{policyArn}/test-cases", 200], - }, - () => CreateAutomatedReasoningPolicyTestCaseRequest, - () => CreateAutomatedReasoningPolicyTestCaseResponse, -]; -var CreateAutomatedReasoningPolicyVersion = [ - 9, - n0, - _CARPV, - { - [_ht]: ["POST", "/automated-reasoning-policies/{policyArn}/versions", 200], - }, - () => CreateAutomatedReasoningPolicyVersionRequest, - () => CreateAutomatedReasoningPolicyVersionResponse, -]; -var CreateCustomModel = [ - 9, - n0, - _CCM, - { - [_ht]: ["POST", "/custom-models/create-custom-model", 202], - }, - () => CreateCustomModelRequest, - () => CreateCustomModelResponse, -]; -var CreateCustomModelDeployment = [ - 9, - n0, - _CCMD, - { - [_ht]: ["POST", "/model-customization/custom-model-deployments", 202], - }, - () => CreateCustomModelDeploymentRequest, - () => CreateCustomModelDeploymentResponse, -]; -var CreateEvaluationJob = [ - 9, - n0, - _CEJ, - { - [_ht]: ["POST", "/evaluation-jobs", 202], - }, - () => CreateEvaluationJobRequest, - () => CreateEvaluationJobResponse, -]; -var CreateFoundationModelAgreement = [ - 9, - n0, - _CFMA, - { - [_ht]: ["POST", "/create-foundation-model-agreement", 202], - }, - () => CreateFoundationModelAgreementRequest, - () => CreateFoundationModelAgreementResponse, -]; -var CreateGuardrail = [ - 9, - n0, - _CG, - { - [_ht]: ["POST", "/guardrails", 202], - }, - () => CreateGuardrailRequest, - () => CreateGuardrailResponse, -]; -var CreateGuardrailVersion = [ - 9, - n0, - _CGV, - { - [_ht]: ["POST", "/guardrails/{guardrailIdentifier}", 202], - }, - () => CreateGuardrailVersionRequest, - () => CreateGuardrailVersionResponse, -]; -var CreateInferenceProfile = [ - 9, - n0, - _CIP, - { - [_ht]: ["POST", "/inference-profiles", 201], - }, - () => CreateInferenceProfileRequest, - () => CreateInferenceProfileResponse, -]; -var CreateMarketplaceModelEndpoint = [ - 9, - n0, - _CMME, - { - [_ht]: ["POST", "/marketplace-model/endpoints", 200], - }, - () => CreateMarketplaceModelEndpointRequest, - () => CreateMarketplaceModelEndpointResponse, -]; -var CreateModelCopyJob = [ - 9, - n0, - _CMCJ, - { - [_ht]: ["POST", "/model-copy-jobs", 201], - }, - () => CreateModelCopyJobRequest, - () => CreateModelCopyJobResponse, -]; -var CreateModelCustomizationJob = [ - 9, - n0, - _CMCJr, - { - [_ht]: ["POST", "/model-customization-jobs", 201], - }, - () => CreateModelCustomizationJobRequest, - () => CreateModelCustomizationJobResponse, -]; -var CreateModelImportJob = [ - 9, - n0, - _CMIJ, - { - [_ht]: ["POST", "/model-import-jobs", 201], - }, - () => CreateModelImportJobRequest, - () => CreateModelImportJobResponse, -]; -var CreateModelInvocationJob = [ - 9, - n0, - _CMIJr, - { - [_ht]: ["POST", "/model-invocation-job", 200], - }, - () => CreateModelInvocationJobRequest, - () => CreateModelInvocationJobResponse, -]; -var CreatePromptRouter = [ - 9, - n0, - _CPR, - { - [_ht]: ["POST", "/prompt-routers", 200], - }, - () => CreatePromptRouterRequest, - () => CreatePromptRouterResponse, -]; -var CreateProvisionedModelThroughput = [ - 9, - n0, - _CPMT, - { - [_ht]: ["POST", "/provisioned-model-throughput", 201], - }, - () => CreateProvisionedModelThroughputRequest, - () => CreateProvisionedModelThroughputResponse, -]; -var DeleteAutomatedReasoningPolicy = [ - 9, - n0, - _DARP, - { - [_ht]: ["DELETE", "/automated-reasoning-policies/{policyArn}", 202], - }, - () => DeleteAutomatedReasoningPolicyRequest, - () => DeleteAutomatedReasoningPolicyResponse, -]; -var DeleteAutomatedReasoningPolicyBuildWorkflow = [ - 9, - n0, - _DARPBW, - { - [_ht]: ["DELETE", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}", 202], - }, - () => DeleteAutomatedReasoningPolicyBuildWorkflowRequest, - () => DeleteAutomatedReasoningPolicyBuildWorkflowResponse, -]; -var DeleteAutomatedReasoningPolicyTestCase = [ - 9, - n0, - _DARPTC, - { - [_ht]: ["DELETE", "/automated-reasoning-policies/{policyArn}/test-cases/{testCaseId}", 202], - }, - () => DeleteAutomatedReasoningPolicyTestCaseRequest, - () => DeleteAutomatedReasoningPolicyTestCaseResponse, -]; -var DeleteCustomModel = [ - 9, - n0, - _DCM, - { - [_ht]: ["DELETE", "/custom-models/{modelIdentifier}", 200], - }, - () => DeleteCustomModelRequest, - () => DeleteCustomModelResponse, -]; -var DeleteCustomModelDeployment = [ - 9, - n0, - _DCMD, - { - [_ht]: ["DELETE", "/model-customization/custom-model-deployments/{customModelDeploymentIdentifier}", 200], - }, - () => DeleteCustomModelDeploymentRequest, - () => DeleteCustomModelDeploymentResponse, -]; -var DeleteFoundationModelAgreement = [ - 9, - n0, - _DFMA, - { - [_ht]: ["POST", "/delete-foundation-model-agreement", 202], - }, - () => DeleteFoundationModelAgreementRequest, - () => DeleteFoundationModelAgreementResponse, -]; -var DeleteGuardrail = [ - 9, - n0, - _DG, - { - [_ht]: ["DELETE", "/guardrails/{guardrailIdentifier}", 202], - }, - () => DeleteGuardrailRequest, - () => DeleteGuardrailResponse, -]; -var DeleteImportedModel = [ - 9, - n0, - _DIM, - { - [_ht]: ["DELETE", "/imported-models/{modelIdentifier}", 200], - }, - () => DeleteImportedModelRequest, - () => DeleteImportedModelResponse, -]; -var DeleteInferenceProfile = [ - 9, - n0, - _DIP, - { - [_ht]: ["DELETE", "/inference-profiles/{inferenceProfileIdentifier}", 200], - }, - () => DeleteInferenceProfileRequest, - () => DeleteInferenceProfileResponse, -]; -var DeleteMarketplaceModelEndpoint = [ - 9, - n0, - _DMME, - { - [_ht]: ["DELETE", "/marketplace-model/endpoints/{endpointArn}", 200], - }, - () => DeleteMarketplaceModelEndpointRequest, - () => DeleteMarketplaceModelEndpointResponse, -]; -var DeleteModelInvocationLoggingConfiguration = [ - 9, - n0, - _DMILC, - { - [_ht]: ["DELETE", "/logging/modelinvocations", 200], - }, - () => DeleteModelInvocationLoggingConfigurationRequest, - () => DeleteModelInvocationLoggingConfigurationResponse, -]; -var DeletePromptRouter = [ - 9, - n0, - _DPRe, - { - [_ht]: ["DELETE", "/prompt-routers/{promptRouterArn}", 200], - }, - () => DeletePromptRouterRequest, - () => DeletePromptRouterResponse, -]; -var DeleteProvisionedModelThroughput = [ - 9, - n0, - _DPMT, - { - [_ht]: ["DELETE", "/provisioned-model-throughput/{provisionedModelId}", 200], - }, - () => DeleteProvisionedModelThroughputRequest, - () => DeleteProvisionedModelThroughputResponse, -]; -var DeregisterMarketplaceModelEndpoint = [ - 9, - n0, - _DMMEe, - { - [_ht]: ["DELETE", "/marketplace-model/endpoints/{endpointArn}/registration", 200], - }, - () => DeregisterMarketplaceModelEndpointRequest, - () => DeregisterMarketplaceModelEndpointResponse, -]; -var ExportAutomatedReasoningPolicyVersion = [ - 9, - n0, - _EARPV, - { - [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/export", 200], - }, - () => ExportAutomatedReasoningPolicyVersionRequest, - () => ExportAutomatedReasoningPolicyVersionResponse, -]; -var GetAutomatedReasoningPolicy = [ - 9, - n0, - _GARPe, - { - [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}", 200], - }, - () => GetAutomatedReasoningPolicyRequest, - () => GetAutomatedReasoningPolicyResponse, -]; -var GetAutomatedReasoningPolicyAnnotations = [ - 9, - n0, - _GARPA, - { - [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/annotations", 200], - }, - () => GetAutomatedReasoningPolicyAnnotationsRequest, - () => GetAutomatedReasoningPolicyAnnotationsResponse, -]; -var GetAutomatedReasoningPolicyBuildWorkflow = [ - 9, - n0, - _GARPBW, - { - [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}", 200], - }, - () => GetAutomatedReasoningPolicyBuildWorkflowRequest, - () => GetAutomatedReasoningPolicyBuildWorkflowResponse, -]; -var GetAutomatedReasoningPolicyBuildWorkflowResultAssets = [ - 9, - n0, - _GARPBWRA, - { - [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/result-assets", 200], - }, - () => GetAutomatedReasoningPolicyBuildWorkflowResultAssetsRequest, - () => GetAutomatedReasoningPolicyBuildWorkflowResultAssetsResponse, -]; -var GetAutomatedReasoningPolicyNextScenario = [ - 9, - n0, - _GARPNS, - { - [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/scenarios", 200], - }, - () => GetAutomatedReasoningPolicyNextScenarioRequest, - () => GetAutomatedReasoningPolicyNextScenarioResponse, -]; -var GetAutomatedReasoningPolicyTestCase = [ - 9, - n0, - _GARPTC, - { - [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/test-cases/{testCaseId}", 200], - }, - () => GetAutomatedReasoningPolicyTestCaseRequest, - () => GetAutomatedReasoningPolicyTestCaseResponse, -]; -var GetAutomatedReasoningPolicyTestResult = [ - 9, - n0, - _GARPTR, - { - [_ht]: [ - "GET", - "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/test-cases/{testCaseId}/test-results", - 200, - ], - }, - () => GetAutomatedReasoningPolicyTestResultRequest, - () => GetAutomatedReasoningPolicyTestResultResponse, -]; -var GetCustomModel = [ - 9, - n0, - _GCM, - { - [_ht]: ["GET", "/custom-models/{modelIdentifier}", 200], - }, - () => GetCustomModelRequest, - () => GetCustomModelResponse, -]; -var GetCustomModelDeployment = [ - 9, - n0, - _GCMD, - { - [_ht]: ["GET", "/model-customization/custom-model-deployments/{customModelDeploymentIdentifier}", 200], - }, - () => GetCustomModelDeploymentRequest, - () => GetCustomModelDeploymentResponse, -]; -var GetEvaluationJob = [ - 9, - n0, - _GEJ, - { - [_ht]: ["GET", "/evaluation-jobs/{jobIdentifier}", 200], - }, - () => GetEvaluationJobRequest, - () => GetEvaluationJobResponse, -]; -var GetFoundationModel = [ - 9, - n0, - _GFM, - { - [_ht]: ["GET", "/foundation-models/{modelIdentifier}", 200], - }, - () => GetFoundationModelRequest, - () => GetFoundationModelResponse, -]; -var GetFoundationModelAvailability = [ - 9, - n0, - _GFMA, - { - [_ht]: ["GET", "/foundation-model-availability/{modelId}", 200], - }, - () => GetFoundationModelAvailabilityRequest, - () => GetFoundationModelAvailabilityResponse, -]; -var GetGuardrail = [ - 9, - n0, - _GG, - { - [_ht]: ["GET", "/guardrails/{guardrailIdentifier}", 200], - }, - () => GetGuardrailRequest, - () => GetGuardrailResponse, -]; -var GetImportedModel = [ - 9, - n0, - _GIM, - { - [_ht]: ["GET", "/imported-models/{modelIdentifier}", 200], - }, - () => GetImportedModelRequest, - () => GetImportedModelResponse, -]; -var GetInferenceProfile = [ - 9, - n0, - _GIP, - { - [_ht]: ["GET", "/inference-profiles/{inferenceProfileIdentifier}", 200], - }, - () => GetInferenceProfileRequest, - () => GetInferenceProfileResponse, -]; -var GetMarketplaceModelEndpoint = [ - 9, - n0, - _GMME, - { - [_ht]: ["GET", "/marketplace-model/endpoints/{endpointArn}", 200], - }, - () => GetMarketplaceModelEndpointRequest, - () => GetMarketplaceModelEndpointResponse, -]; -var GetModelCopyJob = [ - 9, - n0, - _GMCJ, - { - [_ht]: ["GET", "/model-copy-jobs/{jobArn}", 200], - }, - () => GetModelCopyJobRequest, - () => GetModelCopyJobResponse, -]; -var GetModelCustomizationJob = [ - 9, - n0, - _GMCJe, - { - [_ht]: ["GET", "/model-customization-jobs/{jobIdentifier}", 200], - }, - () => GetModelCustomizationJobRequest, - () => GetModelCustomizationJobResponse, -]; -var GetModelImportJob = [ - 9, - n0, - _GMIJ, - { - [_ht]: ["GET", "/model-import-jobs/{jobIdentifier}", 200], - }, - () => GetModelImportJobRequest, - () => GetModelImportJobResponse, -]; -var GetModelInvocationJob = [ - 9, - n0, - _GMIJe, - { - [_ht]: ["GET", "/model-invocation-job/{jobIdentifier}", 200], - }, - () => GetModelInvocationJobRequest, - () => GetModelInvocationJobResponse, -]; -var GetModelInvocationLoggingConfiguration = [ - 9, - n0, - _GMILC, - { - [_ht]: ["GET", "/logging/modelinvocations", 200], - }, - () => GetModelInvocationLoggingConfigurationRequest, - () => GetModelInvocationLoggingConfigurationResponse, -]; -var GetPromptRouter = [ - 9, - n0, - _GPR, - { - [_ht]: ["GET", "/prompt-routers/{promptRouterArn}", 200], - }, - () => GetPromptRouterRequest, - () => GetPromptRouterResponse, -]; -var GetProvisionedModelThroughput = [ - 9, - n0, - _GPMT, - { - [_ht]: ["GET", "/provisioned-model-throughput/{provisionedModelId}", 200], - }, - () => GetProvisionedModelThroughputRequest, - () => GetProvisionedModelThroughputResponse, -]; -var GetUseCaseForModelAccess = [ - 9, - n0, - _GUCFMA, - { - [_ht]: ["GET", "/use-case-for-model-access", 200], - }, - () => GetUseCaseForModelAccessRequest, - () => GetUseCaseForModelAccessResponse, -]; -var ListAutomatedReasoningPolicies = [ - 9, - n0, - _LARP, - { - [_ht]: ["GET", "/automated-reasoning-policies", 200], - }, - () => ListAutomatedReasoningPoliciesRequest, - () => ListAutomatedReasoningPoliciesResponse, -]; -var ListAutomatedReasoningPolicyBuildWorkflows = [ - 9, - n0, - _LARPBW, - { - [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/build-workflows", 200], - }, - () => ListAutomatedReasoningPolicyBuildWorkflowsRequest, - () => ListAutomatedReasoningPolicyBuildWorkflowsResponse, -]; -var ListAutomatedReasoningPolicyTestCases = [ - 9, - n0, - _LARPTC, - { - [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/test-cases", 200], - }, - () => ListAutomatedReasoningPolicyTestCasesRequest, - () => ListAutomatedReasoningPolicyTestCasesResponse, -]; -var ListAutomatedReasoningPolicyTestResults = [ - 9, - n0, - _LARPTR, - { - [_ht]: ["GET", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/test-results", 200], - }, - () => ListAutomatedReasoningPolicyTestResultsRequest, - () => ListAutomatedReasoningPolicyTestResultsResponse, -]; -var ListCustomModelDeployments = [ - 9, - n0, - _LCMD, - { - [_ht]: ["GET", "/model-customization/custom-model-deployments", 200], - }, - () => ListCustomModelDeploymentsRequest, - () => ListCustomModelDeploymentsResponse, -]; -var ListCustomModels = [ - 9, - n0, - _LCM, - { - [_ht]: ["GET", "/custom-models", 200], - }, - () => ListCustomModelsRequest, - () => ListCustomModelsResponse, -]; -var ListEvaluationJobs = [ - 9, - n0, - _LEJ, - { - [_ht]: ["GET", "/evaluation-jobs", 200], - }, - () => ListEvaluationJobsRequest, - () => ListEvaluationJobsResponse, -]; -var ListFoundationModelAgreementOffers = [ - 9, - n0, - _LFMAO, - { - [_ht]: ["GET", "/list-foundation-model-agreement-offers/{modelId}", 200], - }, - () => ListFoundationModelAgreementOffersRequest, - () => ListFoundationModelAgreementOffersResponse, -]; -var ListFoundationModels = [ - 9, - n0, - _LFM, - { - [_ht]: ["GET", "/foundation-models", 200], - }, - () => ListFoundationModelsRequest, - () => ListFoundationModelsResponse, -]; -var ListGuardrails = [ - 9, - n0, - _LG, - { - [_ht]: ["GET", "/guardrails", 200], - }, - () => ListGuardrailsRequest, - () => ListGuardrailsResponse, -]; -var ListImportedModels = [ - 9, - n0, - _LIM, - { - [_ht]: ["GET", "/imported-models", 200], - }, - () => ListImportedModelsRequest, - () => ListImportedModelsResponse, -]; -var ListInferenceProfiles = [ - 9, - n0, - _LIP, - { - [_ht]: ["GET", "/inference-profiles", 200], - }, - () => ListInferenceProfilesRequest, - () => ListInferenceProfilesResponse, -]; -var ListMarketplaceModelEndpoints = [ - 9, - n0, - _LMME, - { - [_ht]: ["GET", "/marketplace-model/endpoints", 200], - }, - () => ListMarketplaceModelEndpointsRequest, - () => ListMarketplaceModelEndpointsResponse, -]; -var ListModelCopyJobs = [ - 9, - n0, - _LMCJ, - { - [_ht]: ["GET", "/model-copy-jobs", 200], - }, - () => ListModelCopyJobsRequest, - () => ListModelCopyJobsResponse, -]; -var ListModelCustomizationJobs = [ - 9, - n0, - _LMCJi, - { - [_ht]: ["GET", "/model-customization-jobs", 200], - }, - () => ListModelCustomizationJobsRequest, - () => ListModelCustomizationJobsResponse, -]; -var ListModelImportJobs = [ - 9, - n0, - _LMIJ, - { - [_ht]: ["GET", "/model-import-jobs", 200], - }, - () => ListModelImportJobsRequest, - () => ListModelImportJobsResponse, -]; -var ListModelInvocationJobs = [ - 9, - n0, - _LMIJi, - { - [_ht]: ["GET", "/model-invocation-jobs", 200], - }, - () => ListModelInvocationJobsRequest, - () => ListModelInvocationJobsResponse, -]; -var ListPromptRouters = [ - 9, - n0, - _LPR, - { - [_ht]: ["GET", "/prompt-routers", 200], - }, - () => ListPromptRoutersRequest, - () => ListPromptRoutersResponse, -]; -var ListProvisionedModelThroughputs = [ - 9, - n0, - _LPMT, - { - [_ht]: ["GET", "/provisioned-model-throughputs", 200], - }, - () => ListProvisionedModelThroughputsRequest, - () => ListProvisionedModelThroughputsResponse, -]; -var ListTagsForResource = [ - 9, - n0, - _LTFR, - { - [_ht]: ["POST", "/listTagsForResource", 200], - }, - () => ListTagsForResourceRequest, - () => ListTagsForResourceResponse, -]; -var PutModelInvocationLoggingConfiguration = [ - 9, - n0, - _PMILC, - { - [_ht]: ["PUT", "/logging/modelinvocations", 200], - }, - () => PutModelInvocationLoggingConfigurationRequest, - () => PutModelInvocationLoggingConfigurationResponse, -]; -var PutUseCaseForModelAccess = [ - 9, - n0, - _PUCFMA, - { - [_ht]: ["POST", "/use-case-for-model-access", 201], - }, - () => PutUseCaseForModelAccessRequest, - () => PutUseCaseForModelAccessResponse, -]; -var RegisterMarketplaceModelEndpoint = [ - 9, - n0, - _RMME, - { - [_ht]: ["POST", "/marketplace-model/endpoints/{endpointIdentifier}/registration", 200], - }, - () => RegisterMarketplaceModelEndpointRequest, - () => RegisterMarketplaceModelEndpointResponse, -]; -var StartAutomatedReasoningPolicyBuildWorkflow = [ - 9, - n0, - _SARPBW, - { - [_ht]: ["POST", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowType}/start", 200], - }, - () => StartAutomatedReasoningPolicyBuildWorkflowRequest, - () => StartAutomatedReasoningPolicyBuildWorkflowResponse, -]; -var StartAutomatedReasoningPolicyTestWorkflow = [ - 9, - n0, - _SARPTW, - { - [_ht]: ["POST", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/test-workflows", 200], - }, - () => StartAutomatedReasoningPolicyTestWorkflowRequest, - () => StartAutomatedReasoningPolicyTestWorkflowResponse, -]; -var StopEvaluationJob = [ - 9, - n0, - _SEJ, - { - [_ht]: ["POST", "/evaluation-job/{jobIdentifier}/stop", 200], - }, - () => StopEvaluationJobRequest, - () => StopEvaluationJobResponse, -]; -var StopModelCustomizationJob = [ - 9, - n0, - _SMCJ, - { - [_ht]: ["POST", "/model-customization-jobs/{jobIdentifier}/stop", 200], - }, - () => StopModelCustomizationJobRequest, - () => StopModelCustomizationJobResponse, -]; -var StopModelInvocationJob = [ - 9, - n0, - _SMIJ, - { - [_ht]: ["POST", "/model-invocation-job/{jobIdentifier}/stop", 200], - }, - () => StopModelInvocationJobRequest, - () => StopModelInvocationJobResponse, -]; -var TagResource = [ - 9, - n0, - _TR, - { - [_ht]: ["POST", "/tagResource", 200], - }, - () => TagResourceRequest, - () => TagResourceResponse, -]; -var UntagResource = [ - 9, - n0, - _UR, - { - [_ht]: ["POST", "/untagResource", 200], - }, - () => UntagResourceRequest, - () => UntagResourceResponse, -]; -var UpdateAutomatedReasoningPolicy = [ - 9, - n0, - _UARP, - { - [_ht]: ["PATCH", "/automated-reasoning-policies/{policyArn}", 200], - }, - () => UpdateAutomatedReasoningPolicyRequest, - () => UpdateAutomatedReasoningPolicyResponse, -]; -var UpdateAutomatedReasoningPolicyAnnotations = [ - 9, - n0, - _UARPA, - { - [_ht]: ["PATCH", "/automated-reasoning-policies/{policyArn}/build-workflows/{buildWorkflowId}/annotations", 200], - }, - () => UpdateAutomatedReasoningPolicyAnnotationsRequest, - () => UpdateAutomatedReasoningPolicyAnnotationsResponse, -]; -var UpdateAutomatedReasoningPolicyTestCase = [ - 9, - n0, - _UARPTC, - { - [_ht]: ["PATCH", "/automated-reasoning-policies/{policyArn}/test-cases/{testCaseId}", 200], - }, - () => UpdateAutomatedReasoningPolicyTestCaseRequest, - () => UpdateAutomatedReasoningPolicyTestCaseResponse, -]; -var UpdateGuardrail = [ - 9, - n0, - _UG, - { - [_ht]: ["PUT", "/guardrails/{guardrailIdentifier}", 202], - }, - () => UpdateGuardrailRequest, - () => UpdateGuardrailResponse, -]; -var UpdateMarketplaceModelEndpoint = [ - 9, - n0, - _UMME, - { - [_ht]: ["PATCH", "/marketplace-model/endpoints/{endpointArn}", 200], - }, - () => UpdateMarketplaceModelEndpointRequest, - () => UpdateMarketplaceModelEndpointResponse, -]; -var UpdateProvisionedModelThroughput = [ - 9, - n0, - _UPMT, - { - [_ht]: ["PATCH", "/provisioned-model-throughput/{provisionedModelId}", 200], - }, - () => UpdateProvisionedModelThroughputRequest, - () => UpdateProvisionedModelThroughputResponse, -]; - -class BatchDeleteEvaluationJobCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "BatchDeleteEvaluationJob", {}) - .n("BedrockClient", "BatchDeleteEvaluationJobCommand") - .sc(BatchDeleteEvaluationJob) - .build() { -} - -class CancelAutomatedReasoningPolicyBuildWorkflowCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "CancelAutomatedReasoningPolicyBuildWorkflow", {}) - .n("BedrockClient", "CancelAutomatedReasoningPolicyBuildWorkflowCommand") - .sc(CancelAutomatedReasoningPolicyBuildWorkflow) - .build() { -} - -class CreateAutomatedReasoningPolicyCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "CreateAutomatedReasoningPolicy", {}) - .n("BedrockClient", "CreateAutomatedReasoningPolicyCommand") - .sc(CreateAutomatedReasoningPolicy) - .build() { -} - -class CreateAutomatedReasoningPolicyTestCaseCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "CreateAutomatedReasoningPolicyTestCase", {}) - .n("BedrockClient", "CreateAutomatedReasoningPolicyTestCaseCommand") - .sc(CreateAutomatedReasoningPolicyTestCase) - .build() { -} - -class CreateAutomatedReasoningPolicyVersionCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "CreateAutomatedReasoningPolicyVersion", {}) - .n("BedrockClient", "CreateAutomatedReasoningPolicyVersionCommand") - .sc(CreateAutomatedReasoningPolicyVersion) - .build() { -} - -class CreateCustomModelCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "CreateCustomModel", {}) - .n("BedrockClient", "CreateCustomModelCommand") - .sc(CreateCustomModel) - .build() { -} - -class CreateCustomModelDeploymentCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "CreateCustomModelDeployment", {}) - .n("BedrockClient", "CreateCustomModelDeploymentCommand") - .sc(CreateCustomModelDeployment) - .build() { -} - -class CreateEvaluationJobCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "CreateEvaluationJob", {}) - .n("BedrockClient", "CreateEvaluationJobCommand") - .sc(CreateEvaluationJob) - .build() { -} - -class CreateFoundationModelAgreementCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "CreateFoundationModelAgreement", {}) - .n("BedrockClient", "CreateFoundationModelAgreementCommand") - .sc(CreateFoundationModelAgreement) - .build() { -} - -class CreateGuardrailCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "CreateGuardrail", {}) - .n("BedrockClient", "CreateGuardrailCommand") - .sc(CreateGuardrail) - .build() { -} - -class CreateGuardrailVersionCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "CreateGuardrailVersion", {}) - .n("BedrockClient", "CreateGuardrailVersionCommand") - .sc(CreateGuardrailVersion) - .build() { -} - -class CreateInferenceProfileCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "CreateInferenceProfile", {}) - .n("BedrockClient", "CreateInferenceProfileCommand") - .sc(CreateInferenceProfile) - .build() { -} - -class CreateMarketplaceModelEndpointCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "CreateMarketplaceModelEndpoint", {}) - .n("BedrockClient", "CreateMarketplaceModelEndpointCommand") - .sc(CreateMarketplaceModelEndpoint) - .build() { -} - -class CreateModelCopyJobCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "CreateModelCopyJob", {}) - .n("BedrockClient", "CreateModelCopyJobCommand") - .sc(CreateModelCopyJob) - .build() { -} - -class CreateModelCustomizationJobCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "CreateModelCustomizationJob", {}) - .n("BedrockClient", "CreateModelCustomizationJobCommand") - .sc(CreateModelCustomizationJob) - .build() { -} - -class CreateModelImportJobCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "CreateModelImportJob", {}) - .n("BedrockClient", "CreateModelImportJobCommand") - .sc(CreateModelImportJob) - .build() { -} - -class CreateModelInvocationJobCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "CreateModelInvocationJob", {}) - .n("BedrockClient", "CreateModelInvocationJobCommand") - .sc(CreateModelInvocationJob) - .build() { -} - -class CreatePromptRouterCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "CreatePromptRouter", {}) - .n("BedrockClient", "CreatePromptRouterCommand") - .sc(CreatePromptRouter) - .build() { -} - -class CreateProvisionedModelThroughputCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "CreateProvisionedModelThroughput", {}) - .n("BedrockClient", "CreateProvisionedModelThroughputCommand") - .sc(CreateProvisionedModelThroughput) - .build() { -} - -class DeleteAutomatedReasoningPolicyBuildWorkflowCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "DeleteAutomatedReasoningPolicyBuildWorkflow", {}) - .n("BedrockClient", "DeleteAutomatedReasoningPolicyBuildWorkflowCommand") - .sc(DeleteAutomatedReasoningPolicyBuildWorkflow) - .build() { -} - -class DeleteAutomatedReasoningPolicyCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "DeleteAutomatedReasoningPolicy", {}) - .n("BedrockClient", "DeleteAutomatedReasoningPolicyCommand") - .sc(DeleteAutomatedReasoningPolicy) - .build() { -} - -class DeleteAutomatedReasoningPolicyTestCaseCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "DeleteAutomatedReasoningPolicyTestCase", {}) - .n("BedrockClient", "DeleteAutomatedReasoningPolicyTestCaseCommand") - .sc(DeleteAutomatedReasoningPolicyTestCase) - .build() { -} - -class DeleteCustomModelCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "DeleteCustomModel", {}) - .n("BedrockClient", "DeleteCustomModelCommand") - .sc(DeleteCustomModel) - .build() { -} - -class DeleteCustomModelDeploymentCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "DeleteCustomModelDeployment", {}) - .n("BedrockClient", "DeleteCustomModelDeploymentCommand") - .sc(DeleteCustomModelDeployment) - .build() { -} - -class DeleteFoundationModelAgreementCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "DeleteFoundationModelAgreement", {}) - .n("BedrockClient", "DeleteFoundationModelAgreementCommand") - .sc(DeleteFoundationModelAgreement) - .build() { -} - -class DeleteGuardrailCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "DeleteGuardrail", {}) - .n("BedrockClient", "DeleteGuardrailCommand") - .sc(DeleteGuardrail) - .build() { -} - -class DeleteImportedModelCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "DeleteImportedModel", {}) - .n("BedrockClient", "DeleteImportedModelCommand") - .sc(DeleteImportedModel) - .build() { -} - -class DeleteInferenceProfileCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "DeleteInferenceProfile", {}) - .n("BedrockClient", "DeleteInferenceProfileCommand") - .sc(DeleteInferenceProfile) - .build() { -} - -class DeleteMarketplaceModelEndpointCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "DeleteMarketplaceModelEndpoint", {}) - .n("BedrockClient", "DeleteMarketplaceModelEndpointCommand") - .sc(DeleteMarketplaceModelEndpoint) - .build() { -} - -class DeleteModelInvocationLoggingConfigurationCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "DeleteModelInvocationLoggingConfiguration", {}) - .n("BedrockClient", "DeleteModelInvocationLoggingConfigurationCommand") - .sc(DeleteModelInvocationLoggingConfiguration) - .build() { -} - -class DeletePromptRouterCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "DeletePromptRouter", {}) - .n("BedrockClient", "DeletePromptRouterCommand") - .sc(DeletePromptRouter) - .build() { -} - -class DeleteProvisionedModelThroughputCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "DeleteProvisionedModelThroughput", {}) - .n("BedrockClient", "DeleteProvisionedModelThroughputCommand") - .sc(DeleteProvisionedModelThroughput) - .build() { -} - -class DeregisterMarketplaceModelEndpointCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "DeregisterMarketplaceModelEndpoint", {}) - .n("BedrockClient", "DeregisterMarketplaceModelEndpointCommand") - .sc(DeregisterMarketplaceModelEndpoint) - .build() { -} - -class ExportAutomatedReasoningPolicyVersionCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ExportAutomatedReasoningPolicyVersion", {}) - .n("BedrockClient", "ExportAutomatedReasoningPolicyVersionCommand") - .sc(ExportAutomatedReasoningPolicyVersion) - .build() { -} - -class GetAutomatedReasoningPolicyAnnotationsCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicyAnnotations", {}) - .n("BedrockClient", "GetAutomatedReasoningPolicyAnnotationsCommand") - .sc(GetAutomatedReasoningPolicyAnnotations) - .build() { -} - -class GetAutomatedReasoningPolicyBuildWorkflowCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicyBuildWorkflow", {}) - .n("BedrockClient", "GetAutomatedReasoningPolicyBuildWorkflowCommand") - .sc(GetAutomatedReasoningPolicyBuildWorkflow) - .build() { -} - -class GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicyBuildWorkflowResultAssets", {}) - .n("BedrockClient", "GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand") - .sc(GetAutomatedReasoningPolicyBuildWorkflowResultAssets) - .build() { -} - -class GetAutomatedReasoningPolicyCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicy", {}) - .n("BedrockClient", "GetAutomatedReasoningPolicyCommand") - .sc(GetAutomatedReasoningPolicy) - .build() { -} - -class GetAutomatedReasoningPolicyNextScenarioCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicyNextScenario", {}) - .n("BedrockClient", "GetAutomatedReasoningPolicyNextScenarioCommand") - .sc(GetAutomatedReasoningPolicyNextScenario) - .build() { -} - -class GetAutomatedReasoningPolicyTestCaseCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicyTestCase", {}) - .n("BedrockClient", "GetAutomatedReasoningPolicyTestCaseCommand") - .sc(GetAutomatedReasoningPolicyTestCase) - .build() { -} - -class GetAutomatedReasoningPolicyTestResultCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetAutomatedReasoningPolicyTestResult", {}) - .n("BedrockClient", "GetAutomatedReasoningPolicyTestResultCommand") - .sc(GetAutomatedReasoningPolicyTestResult) - .build() { -} - -class GetCustomModelCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetCustomModel", {}) - .n("BedrockClient", "GetCustomModelCommand") - .sc(GetCustomModel) - .build() { -} - -class GetCustomModelDeploymentCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetCustomModelDeployment", {}) - .n("BedrockClient", "GetCustomModelDeploymentCommand") - .sc(GetCustomModelDeployment) - .build() { -} - -class GetEvaluationJobCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetEvaluationJob", {}) - .n("BedrockClient", "GetEvaluationJobCommand") - .sc(GetEvaluationJob) - .build() { -} - -class GetFoundationModelAvailabilityCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetFoundationModelAvailability", {}) - .n("BedrockClient", "GetFoundationModelAvailabilityCommand") - .sc(GetFoundationModelAvailability) - .build() { -} - -class GetFoundationModelCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetFoundationModel", {}) - .n("BedrockClient", "GetFoundationModelCommand") - .sc(GetFoundationModel) - .build() { -} - -class GetGuardrailCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetGuardrail", {}) - .n("BedrockClient", "GetGuardrailCommand") - .sc(GetGuardrail) - .build() { -} - -class GetImportedModelCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetImportedModel", {}) - .n("BedrockClient", "GetImportedModelCommand") - .sc(GetImportedModel) - .build() { -} - -class GetInferenceProfileCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetInferenceProfile", {}) - .n("BedrockClient", "GetInferenceProfileCommand") - .sc(GetInferenceProfile) - .build() { -} - -class GetMarketplaceModelEndpointCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetMarketplaceModelEndpoint", {}) - .n("BedrockClient", "GetMarketplaceModelEndpointCommand") - .sc(GetMarketplaceModelEndpoint) - .build() { -} - -class GetModelCopyJobCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetModelCopyJob", {}) - .n("BedrockClient", "GetModelCopyJobCommand") - .sc(GetModelCopyJob) - .build() { -} - -class GetModelCustomizationJobCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetModelCustomizationJob", {}) - .n("BedrockClient", "GetModelCustomizationJobCommand") - .sc(GetModelCustomizationJob) - .build() { -} - -class GetModelImportJobCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetModelImportJob", {}) - .n("BedrockClient", "GetModelImportJobCommand") - .sc(GetModelImportJob) - .build() { -} - -class GetModelInvocationJobCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetModelInvocationJob", {}) - .n("BedrockClient", "GetModelInvocationJobCommand") - .sc(GetModelInvocationJob) - .build() { -} - -class GetModelInvocationLoggingConfigurationCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetModelInvocationLoggingConfiguration", {}) - .n("BedrockClient", "GetModelInvocationLoggingConfigurationCommand") - .sc(GetModelInvocationLoggingConfiguration) - .build() { -} - -class GetPromptRouterCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetPromptRouter", {}) - .n("BedrockClient", "GetPromptRouterCommand") - .sc(GetPromptRouter) - .build() { -} - -class GetProvisionedModelThroughputCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetProvisionedModelThroughput", {}) - .n("BedrockClient", "GetProvisionedModelThroughputCommand") - .sc(GetProvisionedModelThroughput) - .build() { -} - -class GetUseCaseForModelAccessCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "GetUseCaseForModelAccess", {}) - .n("BedrockClient", "GetUseCaseForModelAccessCommand") - .sc(GetUseCaseForModelAccess) - .build() { -} - -class ListAutomatedReasoningPoliciesCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ListAutomatedReasoningPolicies", {}) - .n("BedrockClient", "ListAutomatedReasoningPoliciesCommand") - .sc(ListAutomatedReasoningPolicies) - .build() { -} - -class ListAutomatedReasoningPolicyBuildWorkflowsCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ListAutomatedReasoningPolicyBuildWorkflows", {}) - .n("BedrockClient", "ListAutomatedReasoningPolicyBuildWorkflowsCommand") - .sc(ListAutomatedReasoningPolicyBuildWorkflows) - .build() { -} - -class ListAutomatedReasoningPolicyTestCasesCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ListAutomatedReasoningPolicyTestCases", {}) - .n("BedrockClient", "ListAutomatedReasoningPolicyTestCasesCommand") - .sc(ListAutomatedReasoningPolicyTestCases) - .build() { -} - -class ListAutomatedReasoningPolicyTestResultsCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ListAutomatedReasoningPolicyTestResults", {}) - .n("BedrockClient", "ListAutomatedReasoningPolicyTestResultsCommand") - .sc(ListAutomatedReasoningPolicyTestResults) - .build() { -} - -class ListCustomModelDeploymentsCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ListCustomModelDeployments", {}) - .n("BedrockClient", "ListCustomModelDeploymentsCommand") - .sc(ListCustomModelDeployments) - .build() { -} - -class ListCustomModelsCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ListCustomModels", {}) - .n("BedrockClient", "ListCustomModelsCommand") - .sc(ListCustomModels) - .build() { -} - -class ListEvaluationJobsCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ListEvaluationJobs", {}) - .n("BedrockClient", "ListEvaluationJobsCommand") - .sc(ListEvaluationJobs) - .build() { -} - -class ListFoundationModelAgreementOffersCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ListFoundationModelAgreementOffers", {}) - .n("BedrockClient", "ListFoundationModelAgreementOffersCommand") - .sc(ListFoundationModelAgreementOffers) - .build() { -} - -class ListFoundationModelsCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ListFoundationModels", {}) - .n("BedrockClient", "ListFoundationModelsCommand") - .sc(ListFoundationModels) - .build() { -} - -class ListGuardrailsCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ListGuardrails", {}) - .n("BedrockClient", "ListGuardrailsCommand") - .sc(ListGuardrails) - .build() { -} - -class ListImportedModelsCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ListImportedModels", {}) - .n("BedrockClient", "ListImportedModelsCommand") - .sc(ListImportedModels) - .build() { -} - -class ListInferenceProfilesCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ListInferenceProfiles", {}) - .n("BedrockClient", "ListInferenceProfilesCommand") - .sc(ListInferenceProfiles) - .build() { -} - -class ListMarketplaceModelEndpointsCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ListMarketplaceModelEndpoints", {}) - .n("BedrockClient", "ListMarketplaceModelEndpointsCommand") - .sc(ListMarketplaceModelEndpoints) - .build() { -} - -class ListModelCopyJobsCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ListModelCopyJobs", {}) - .n("BedrockClient", "ListModelCopyJobsCommand") - .sc(ListModelCopyJobs) - .build() { -} - -class ListModelCustomizationJobsCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ListModelCustomizationJobs", {}) - .n("BedrockClient", "ListModelCustomizationJobsCommand") - .sc(ListModelCustomizationJobs) - .build() { -} - -class ListModelImportJobsCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ListModelImportJobs", {}) - .n("BedrockClient", "ListModelImportJobsCommand") - .sc(ListModelImportJobs) - .build() { -} - -class ListModelInvocationJobsCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ListModelInvocationJobs", {}) - .n("BedrockClient", "ListModelInvocationJobsCommand") - .sc(ListModelInvocationJobs) - .build() { -} - -class ListPromptRoutersCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ListPromptRouters", {}) - .n("BedrockClient", "ListPromptRoutersCommand") - .sc(ListPromptRouters) - .build() { -} - -class ListProvisionedModelThroughputsCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ListProvisionedModelThroughputs", {}) - .n("BedrockClient", "ListProvisionedModelThroughputsCommand") - .sc(ListProvisionedModelThroughputs) - .build() { -} - -class ListTagsForResourceCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "ListTagsForResource", {}) - .n("BedrockClient", "ListTagsForResourceCommand") - .sc(ListTagsForResource) - .build() { -} - -class PutModelInvocationLoggingConfigurationCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "PutModelInvocationLoggingConfiguration", {}) - .n("BedrockClient", "PutModelInvocationLoggingConfigurationCommand") - .sc(PutModelInvocationLoggingConfiguration) - .build() { -} - -class PutUseCaseForModelAccessCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "PutUseCaseForModelAccess", {}) - .n("BedrockClient", "PutUseCaseForModelAccessCommand") - .sc(PutUseCaseForModelAccess) - .build() { -} - -class RegisterMarketplaceModelEndpointCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "RegisterMarketplaceModelEndpoint", {}) - .n("BedrockClient", "RegisterMarketplaceModelEndpointCommand") - .sc(RegisterMarketplaceModelEndpoint) - .build() { -} - -class StartAutomatedReasoningPolicyBuildWorkflowCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "StartAutomatedReasoningPolicyBuildWorkflow", {}) - .n("BedrockClient", "StartAutomatedReasoningPolicyBuildWorkflowCommand") - .sc(StartAutomatedReasoningPolicyBuildWorkflow) - .build() { -} - -class StartAutomatedReasoningPolicyTestWorkflowCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "StartAutomatedReasoningPolicyTestWorkflow", {}) - .n("BedrockClient", "StartAutomatedReasoningPolicyTestWorkflowCommand") - .sc(StartAutomatedReasoningPolicyTestWorkflow) - .build() { -} - -class StopEvaluationJobCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "StopEvaluationJob", {}) - .n("BedrockClient", "StopEvaluationJobCommand") - .sc(StopEvaluationJob) - .build() { -} - -class StopModelCustomizationJobCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "StopModelCustomizationJob", {}) - .n("BedrockClient", "StopModelCustomizationJobCommand") - .sc(StopModelCustomizationJob) - .build() { -} - -class StopModelInvocationJobCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "StopModelInvocationJob", {}) - .n("BedrockClient", "StopModelInvocationJobCommand") - .sc(StopModelInvocationJob) - .build() { -} - -class TagResourceCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "TagResource", {}) - .n("BedrockClient", "TagResourceCommand") - .sc(TagResource) - .build() { -} - -class UntagResourceCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "UntagResource", {}) - .n("BedrockClient", "UntagResourceCommand") - .sc(UntagResource) - .build() { -} - -class UpdateAutomatedReasoningPolicyAnnotationsCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "UpdateAutomatedReasoningPolicyAnnotations", {}) - .n("BedrockClient", "UpdateAutomatedReasoningPolicyAnnotationsCommand") - .sc(UpdateAutomatedReasoningPolicyAnnotations) - .build() { -} - -class UpdateAutomatedReasoningPolicyCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "UpdateAutomatedReasoningPolicy", {}) - .n("BedrockClient", "UpdateAutomatedReasoningPolicyCommand") - .sc(UpdateAutomatedReasoningPolicy) - .build() { -} - -class UpdateAutomatedReasoningPolicyTestCaseCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "UpdateAutomatedReasoningPolicyTestCase", {}) - .n("BedrockClient", "UpdateAutomatedReasoningPolicyTestCaseCommand") - .sc(UpdateAutomatedReasoningPolicyTestCase) - .build() { -} - -class UpdateGuardrailCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "UpdateGuardrail", {}) - .n("BedrockClient", "UpdateGuardrailCommand") - .sc(UpdateGuardrail) - .build() { -} - -class UpdateMarketplaceModelEndpointCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "UpdateMarketplaceModelEndpoint", {}) - .n("BedrockClient", "UpdateMarketplaceModelEndpointCommand") - .sc(UpdateMarketplaceModelEndpoint) - .build() { -} - -class UpdateProvisionedModelThroughputCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AmazonBedrockControlPlaneService", "UpdateProvisionedModelThroughput", {}) - .n("BedrockClient", "UpdateProvisionedModelThroughputCommand") - .sc(UpdateProvisionedModelThroughput) - .build() { -} - -const commands = { - BatchDeleteEvaluationJobCommand, - CancelAutomatedReasoningPolicyBuildWorkflowCommand, - CreateAutomatedReasoningPolicyCommand, - CreateAutomatedReasoningPolicyTestCaseCommand, - CreateAutomatedReasoningPolicyVersionCommand, - CreateCustomModelCommand, - CreateCustomModelDeploymentCommand, - CreateEvaluationJobCommand, - CreateFoundationModelAgreementCommand, - CreateGuardrailCommand, - CreateGuardrailVersionCommand, - CreateInferenceProfileCommand, - CreateMarketplaceModelEndpointCommand, - CreateModelCopyJobCommand, - CreateModelCustomizationJobCommand, - CreateModelImportJobCommand, - CreateModelInvocationJobCommand, - CreatePromptRouterCommand, - CreateProvisionedModelThroughputCommand, - DeleteAutomatedReasoningPolicyCommand, - DeleteAutomatedReasoningPolicyBuildWorkflowCommand, - DeleteAutomatedReasoningPolicyTestCaseCommand, - DeleteCustomModelCommand, - DeleteCustomModelDeploymentCommand, - DeleteFoundationModelAgreementCommand, - DeleteGuardrailCommand, - DeleteImportedModelCommand, - DeleteInferenceProfileCommand, - DeleteMarketplaceModelEndpointCommand, - DeleteModelInvocationLoggingConfigurationCommand, - DeletePromptRouterCommand, - DeleteProvisionedModelThroughputCommand, - DeregisterMarketplaceModelEndpointCommand, - ExportAutomatedReasoningPolicyVersionCommand, - GetAutomatedReasoningPolicyCommand, - GetAutomatedReasoningPolicyAnnotationsCommand, - GetAutomatedReasoningPolicyBuildWorkflowCommand, - GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand, - GetAutomatedReasoningPolicyNextScenarioCommand, - GetAutomatedReasoningPolicyTestCaseCommand, - GetAutomatedReasoningPolicyTestResultCommand, - GetCustomModelCommand, - GetCustomModelDeploymentCommand, - GetEvaluationJobCommand, - GetFoundationModelCommand, - GetFoundationModelAvailabilityCommand, - GetGuardrailCommand, - GetImportedModelCommand, - GetInferenceProfileCommand, - GetMarketplaceModelEndpointCommand, - GetModelCopyJobCommand, - GetModelCustomizationJobCommand, - GetModelImportJobCommand, - GetModelInvocationJobCommand, - GetModelInvocationLoggingConfigurationCommand, - GetPromptRouterCommand, - GetProvisionedModelThroughputCommand, - GetUseCaseForModelAccessCommand, - ListAutomatedReasoningPoliciesCommand, - ListAutomatedReasoningPolicyBuildWorkflowsCommand, - ListAutomatedReasoningPolicyTestCasesCommand, - ListAutomatedReasoningPolicyTestResultsCommand, - ListCustomModelDeploymentsCommand, - ListCustomModelsCommand, - ListEvaluationJobsCommand, - ListFoundationModelAgreementOffersCommand, - ListFoundationModelsCommand, - ListGuardrailsCommand, - ListImportedModelsCommand, - ListInferenceProfilesCommand, - ListMarketplaceModelEndpointsCommand, - ListModelCopyJobsCommand, - ListModelCustomizationJobsCommand, - ListModelImportJobsCommand, - ListModelInvocationJobsCommand, - ListPromptRoutersCommand, - ListProvisionedModelThroughputsCommand, - ListTagsForResourceCommand, - PutModelInvocationLoggingConfigurationCommand, - PutUseCaseForModelAccessCommand, - RegisterMarketplaceModelEndpointCommand, - StartAutomatedReasoningPolicyBuildWorkflowCommand, - StartAutomatedReasoningPolicyTestWorkflowCommand, - StopEvaluationJobCommand, - StopModelCustomizationJobCommand, - StopModelInvocationJobCommand, - TagResourceCommand, - UntagResourceCommand, - UpdateAutomatedReasoningPolicyCommand, - UpdateAutomatedReasoningPolicyAnnotationsCommand, - UpdateAutomatedReasoningPolicyTestCaseCommand, - UpdateGuardrailCommand, - UpdateMarketplaceModelEndpointCommand, - UpdateProvisionedModelThroughputCommand, -}; -class Bedrock extends BedrockClient { -} -smithyClient.createAggregatedClient(commands, Bedrock); - -const paginateListAutomatedReasoningPolicies = core.createPaginator(BedrockClient, ListAutomatedReasoningPoliciesCommand, "nextToken", "nextToken", "maxResults"); - -const paginateListAutomatedReasoningPolicyBuildWorkflows = core.createPaginator(BedrockClient, ListAutomatedReasoningPolicyBuildWorkflowsCommand, "nextToken", "nextToken", "maxResults"); - -const paginateListAutomatedReasoningPolicyTestCases = core.createPaginator(BedrockClient, ListAutomatedReasoningPolicyTestCasesCommand, "nextToken", "nextToken", "maxResults"); - -const paginateListAutomatedReasoningPolicyTestResults = core.createPaginator(BedrockClient, ListAutomatedReasoningPolicyTestResultsCommand, "nextToken", "nextToken", "maxResults"); - -const paginateListCustomModelDeployments = core.createPaginator(BedrockClient, ListCustomModelDeploymentsCommand, "nextToken", "nextToken", "maxResults"); - -const paginateListCustomModels = core.createPaginator(BedrockClient, ListCustomModelsCommand, "nextToken", "nextToken", "maxResults"); - -const paginateListEvaluationJobs = core.createPaginator(BedrockClient, ListEvaluationJobsCommand, "nextToken", "nextToken", "maxResults"); - -const paginateListGuardrails = core.createPaginator(BedrockClient, ListGuardrailsCommand, "nextToken", "nextToken", "maxResults"); - -const paginateListImportedModels = core.createPaginator(BedrockClient, ListImportedModelsCommand, "nextToken", "nextToken", "maxResults"); - -const paginateListInferenceProfiles = core.createPaginator(BedrockClient, ListInferenceProfilesCommand, "nextToken", "nextToken", "maxResults"); - -const paginateListMarketplaceModelEndpoints = core.createPaginator(BedrockClient, ListMarketplaceModelEndpointsCommand, "nextToken", "nextToken", "maxResults"); - -const paginateListModelCopyJobs = core.createPaginator(BedrockClient, ListModelCopyJobsCommand, "nextToken", "nextToken", "maxResults"); - -const paginateListModelCustomizationJobs = core.createPaginator(BedrockClient, ListModelCustomizationJobsCommand, "nextToken", "nextToken", "maxResults"); - -const paginateListModelImportJobs = core.createPaginator(BedrockClient, ListModelImportJobsCommand, "nextToken", "nextToken", "maxResults"); - -const paginateListModelInvocationJobs = core.createPaginator(BedrockClient, ListModelInvocationJobsCommand, "nextToken", "nextToken", "maxResults"); - -const paginateListPromptRouters = core.createPaginator(BedrockClient, ListPromptRoutersCommand, "nextToken", "nextToken", "maxResults"); - -const paginateListProvisionedModelThroughputs = core.createPaginator(BedrockClient, ListProvisionedModelThroughputsCommand, "nextToken", "nextToken", "maxResults"); - -const AgreementStatus = { - AVAILABLE: "AVAILABLE", - ERROR: "ERROR", - NOT_AVAILABLE: "NOT_AVAILABLE", - PENDING: "PENDING", -}; -const AutomatedReasoningCheckResult = { - IMPOSSIBLE: "IMPOSSIBLE", - INVALID: "INVALID", - NO_TRANSLATION: "NO_TRANSLATION", - SATISFIABLE: "SATISFIABLE", - TOO_COMPLEX: "TOO_COMPLEX", - TRANSLATION_AMBIGUOUS: "TRANSLATION_AMBIGUOUS", - VALID: "VALID", -}; -const AutomatedReasoningPolicyBuildWorkflowType = { - IMPORT_POLICY: "IMPORT_POLICY", - INGEST_CONTENT: "INGEST_CONTENT", - REFINE_POLICY: "REFINE_POLICY", -}; -const AutomatedReasoningPolicyBuildDocumentContentType = { - PDF: "pdf", - TEXT: "txt", -}; -const AutomatedReasoningPolicyBuildWorkflowStatus = { - BUILDING: "BUILDING", - CANCELLED: "CANCELLED", - CANCEL_REQUESTED: "CANCEL_REQUESTED", - COMPLETED: "COMPLETED", - FAILED: "FAILED", - PREPROCESSING: "PREPROCESSING", - SCHEDULED: "SCHEDULED", - TESTING: "TESTING", -}; -const AutomatedReasoningPolicyBuildResultAssetType = { - BUILD_LOG: "BUILD_LOG", - GENERATED_TEST_CASES: "GENERATED_TEST_CASES", - POLICY_DEFINITION: "POLICY_DEFINITION", - QUALITY_REPORT: "QUALITY_REPORT", -}; -const AutomatedReasoningPolicyBuildMessageType = { - ERROR: "ERROR", - INFO: "INFO", - WARNING: "WARNING", -}; -const AutomatedReasoningPolicyAnnotationStatus = { - APPLIED: "APPLIED", - FAILED: "FAILED", -}; -const AutomatedReasoningCheckLogicWarningType = { - ALWAYS_FALSE: "ALWAYS_FALSE", - ALWAYS_TRUE: "ALWAYS_TRUE", -}; -const AutomatedReasoningPolicyTestRunResult = { - FAILED: "FAILED", - PASSED: "PASSED", -}; -const AutomatedReasoningPolicyTestRunStatus = { - COMPLETED: "COMPLETED", - FAILED: "FAILED", - IN_PROGRESS: "IN_PROGRESS", - NOT_STARTED: "NOT_STARTED", - SCHEDULED: "SCHEDULED", -}; -const Status = { - INCOMPATIBLE_ENDPOINT: "INCOMPATIBLE_ENDPOINT", - REGISTERED: "REGISTERED", -}; -const CustomModelDeploymentStatus = { - ACTIVE: "Active", - CREATING: "Creating", - FAILED: "Failed", -}; -const SortModelsBy = { - CREATION_TIME: "CreationTime", -}; -const SortOrder = { - ASCENDING: "Ascending", - DESCENDING: "Descending", -}; -const CustomizationType = { - CONTINUED_PRE_TRAINING: "CONTINUED_PRE_TRAINING", - DISTILLATION: "DISTILLATION", - FINE_TUNING: "FINE_TUNING", - IMPORTED: "IMPORTED", -}; -const ModelStatus = { - ACTIVE: "Active", - CREATING: "Creating", - FAILED: "Failed", -}; -const EvaluationJobStatus = { - COMPLETED: "Completed", - DELETING: "Deleting", - FAILED: "Failed", - IN_PROGRESS: "InProgress", - STOPPED: "Stopped", - STOPPING: "Stopping", -}; -const ApplicationType = { - MODEL_EVALUATION: "ModelEvaluation", - RAG_EVALUATION: "RagEvaluation", -}; -const EvaluationTaskType = { - CLASSIFICATION: "Classification", - CUSTOM: "Custom", - GENERATION: "Generation", - QUESTION_AND_ANSWER: "QuestionAndAnswer", - SUMMARIZATION: "Summarization", -}; -const PerformanceConfigLatency = { - OPTIMIZED: "optimized", - STANDARD: "standard", -}; -const ExternalSourceType = { - BYTE_CONTENT: "BYTE_CONTENT", - S3: "S3", -}; -const QueryTransformationType = { - QUERY_DECOMPOSITION: "QUERY_DECOMPOSITION", -}; -const AttributeType = { - BOOLEAN: "BOOLEAN", - NUMBER: "NUMBER", - STRING: "STRING", - STRING_LIST: "STRING_LIST", -}; -const SearchType = { - HYBRID: "HYBRID", - SEMANTIC: "SEMANTIC", -}; -const RerankingMetadataSelectionMode = { - ALL: "ALL", - SELECTIVE: "SELECTIVE", -}; -const VectorSearchRerankingConfigurationType = { - BEDROCK_RERANKING_MODEL: "BEDROCK_RERANKING_MODEL", -}; -const RetrieveAndGenerateType = { - EXTERNAL_SOURCES: "EXTERNAL_SOURCES", - KNOWLEDGE_BASE: "KNOWLEDGE_BASE", -}; -const EvaluationJobType = { - AUTOMATED: "Automated", - HUMAN: "Human", -}; -const SortJobsBy = { - CREATION_TIME: "CreationTime", -}; -const GuardrailContentFilterAction = { - BLOCK: "BLOCK", - NONE: "NONE", -}; -const GuardrailModality = { - IMAGE: "IMAGE", - TEXT: "TEXT", -}; -const GuardrailFilterStrength = { - HIGH: "HIGH", - LOW: "LOW", - MEDIUM: "MEDIUM", - NONE: "NONE", -}; -const GuardrailContentFilterType = { - HATE: "HATE", - INSULTS: "INSULTS", - MISCONDUCT: "MISCONDUCT", - PROMPT_ATTACK: "PROMPT_ATTACK", - SEXUAL: "SEXUAL", - VIOLENCE: "VIOLENCE", -}; -const GuardrailContentFiltersTierName = { - CLASSIC: "CLASSIC", - STANDARD: "STANDARD", -}; -const GuardrailContextualGroundingAction = { - BLOCK: "BLOCK", - NONE: "NONE", -}; -const GuardrailContextualGroundingFilterType = { - GROUNDING: "GROUNDING", - RELEVANCE: "RELEVANCE", -}; -const GuardrailSensitiveInformationAction = { - ANONYMIZE: "ANONYMIZE", - BLOCK: "BLOCK", - NONE: "NONE", -}; -const GuardrailPiiEntityType = { - ADDRESS: "ADDRESS", - AGE: "AGE", - AWS_ACCESS_KEY: "AWS_ACCESS_KEY", - AWS_SECRET_KEY: "AWS_SECRET_KEY", - CA_HEALTH_NUMBER: "CA_HEALTH_NUMBER", - CA_SOCIAL_INSURANCE_NUMBER: "CA_SOCIAL_INSURANCE_NUMBER", - CREDIT_DEBIT_CARD_CVV: "CREDIT_DEBIT_CARD_CVV", - CREDIT_DEBIT_CARD_EXPIRY: "CREDIT_DEBIT_CARD_EXPIRY", - CREDIT_DEBIT_CARD_NUMBER: "CREDIT_DEBIT_CARD_NUMBER", - DRIVER_ID: "DRIVER_ID", - EMAIL: "EMAIL", - INTERNATIONAL_BANK_ACCOUNT_NUMBER: "INTERNATIONAL_BANK_ACCOUNT_NUMBER", - IP_ADDRESS: "IP_ADDRESS", - LICENSE_PLATE: "LICENSE_PLATE", - MAC_ADDRESS: "MAC_ADDRESS", - NAME: "NAME", - PASSWORD: "PASSWORD", - PHONE: "PHONE", - PIN: "PIN", - SWIFT_CODE: "SWIFT_CODE", - UK_NATIONAL_HEALTH_SERVICE_NUMBER: "UK_NATIONAL_HEALTH_SERVICE_NUMBER", - UK_NATIONAL_INSURANCE_NUMBER: "UK_NATIONAL_INSURANCE_NUMBER", - UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER: "UK_UNIQUE_TAXPAYER_REFERENCE_NUMBER", - URL: "URL", - USERNAME: "USERNAME", - US_BANK_ACCOUNT_NUMBER: "US_BANK_ACCOUNT_NUMBER", - US_BANK_ROUTING_NUMBER: "US_BANK_ROUTING_NUMBER", - US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER: "US_INDIVIDUAL_TAX_IDENTIFICATION_NUMBER", - US_PASSPORT_NUMBER: "US_PASSPORT_NUMBER", - US_SOCIAL_SECURITY_NUMBER: "US_SOCIAL_SECURITY_NUMBER", - VEHICLE_IDENTIFICATION_NUMBER: "VEHICLE_IDENTIFICATION_NUMBER", -}; -const GuardrailTopicsTierName = { - CLASSIC: "CLASSIC", - STANDARD: "STANDARD", -}; -const GuardrailTopicAction = { - BLOCK: "BLOCK", - NONE: "NONE", -}; -const GuardrailTopicType = { - DENY: "DENY", -}; -const GuardrailWordAction = { - BLOCK: "BLOCK", - NONE: "NONE", -}; -const GuardrailManagedWordsType = { - PROFANITY: "PROFANITY", -}; -const GuardrailStatus = { - CREATING: "CREATING", - DELETING: "DELETING", - FAILED: "FAILED", - READY: "READY", - UPDATING: "UPDATING", - VERSIONING: "VERSIONING", -}; -const InferenceProfileStatus = { - ACTIVE: "ACTIVE", -}; -const InferenceProfileType = { - APPLICATION: "APPLICATION", - SYSTEM_DEFINED: "SYSTEM_DEFINED", -}; -const ModelCopyJobStatus = { - COMPLETED: "Completed", - FAILED: "Failed", - IN_PROGRESS: "InProgress", -}; -const ModelImportJobStatus = { - COMPLETED: "Completed", - FAILED: "Failed", - IN_PROGRESS: "InProgress", -}; -const S3InputFormat = { - JSONL: "JSONL", -}; -const ModelInvocationJobStatus = { - COMPLETED: "Completed", - EXPIRED: "Expired", - FAILED: "Failed", - IN_PROGRESS: "InProgress", - PARTIALLY_COMPLETED: "PartiallyCompleted", - SCHEDULED: "Scheduled", - STOPPED: "Stopped", - STOPPING: "Stopping", - SUBMITTED: "Submitted", - VALIDATING: "Validating", -}; -const ModelCustomization = { - CONTINUED_PRE_TRAINING: "CONTINUED_PRE_TRAINING", - DISTILLATION: "DISTILLATION", - FINE_TUNING: "FINE_TUNING", -}; -const InferenceType = { - ON_DEMAND: "ON_DEMAND", - PROVISIONED: "PROVISIONED", -}; -const ModelModality = { - EMBEDDING: "EMBEDDING", - IMAGE: "IMAGE", - TEXT: "TEXT", -}; -const FoundationModelLifecycleStatus = { - ACTIVE: "ACTIVE", - LEGACY: "LEGACY", -}; -const PromptRouterStatus = { - AVAILABLE: "AVAILABLE", -}; -const PromptRouterType = { - CUSTOM: "custom", - DEFAULT: "default", -}; -const CommitmentDuration = { - ONE_MONTH: "OneMonth", - SIX_MONTHS: "SixMonths", -}; -const ProvisionedModelStatus = { - CREATING: "Creating", - FAILED: "Failed", - IN_SERVICE: "InService", - UPDATING: "Updating", -}; -const SortByProvisionedModels = { - CREATION_TIME: "CreationTime", -}; -const AuthorizationStatus = { - AUTHORIZED: "AUTHORIZED", - NOT_AUTHORIZED: "NOT_AUTHORIZED", -}; -const EntitlementAvailability = { - AVAILABLE: "AVAILABLE", - NOT_AVAILABLE: "NOT_AVAILABLE", -}; -const RegionAvailability = { - AVAILABLE: "AVAILABLE", - NOT_AVAILABLE: "NOT_AVAILABLE", -}; -const OfferType = { - ALL: "ALL", - PUBLIC: "PUBLIC", -}; -const ModelCustomizationJobStatus = { - COMPLETED: "Completed", - FAILED: "Failed", - IN_PROGRESS: "InProgress", - STOPPED: "Stopped", - STOPPING: "Stopping", -}; -const JobStatusDetails = { - COMPLETED: "Completed", - FAILED: "Failed", - IN_PROGRESS: "InProgress", - NOT_STARTED: "NotStarted", - STOPPED: "Stopped", - STOPPING: "Stopping", -}; -const FineTuningJobStatus = { - COMPLETED: "Completed", - FAILED: "Failed", - IN_PROGRESS: "InProgress", - STOPPED: "Stopped", - STOPPING: "Stopping", -}; - -Object.defineProperty(exports, "$Command", { - enumerable: true, - get: function () { return smithyClient.Command; } -}); -Object.defineProperty(exports, "__Client", { - enumerable: true, - get: function () { return smithyClient.Client; } -}); -exports.AccessDeniedException = AccessDeniedException$1; -exports.AgreementStatus = AgreementStatus; -exports.ApplicationType = ApplicationType; -exports.AttributeType = AttributeType; -exports.AuthorizationStatus = AuthorizationStatus; -exports.AutomatedReasoningCheckLogicWarningType = AutomatedReasoningCheckLogicWarningType; -exports.AutomatedReasoningCheckResult = AutomatedReasoningCheckResult; -exports.AutomatedReasoningPolicyAnnotationStatus = AutomatedReasoningPolicyAnnotationStatus; -exports.AutomatedReasoningPolicyBuildDocumentContentType = AutomatedReasoningPolicyBuildDocumentContentType; -exports.AutomatedReasoningPolicyBuildMessageType = AutomatedReasoningPolicyBuildMessageType; -exports.AutomatedReasoningPolicyBuildResultAssetType = AutomatedReasoningPolicyBuildResultAssetType; -exports.AutomatedReasoningPolicyBuildWorkflowStatus = AutomatedReasoningPolicyBuildWorkflowStatus; -exports.AutomatedReasoningPolicyBuildWorkflowType = AutomatedReasoningPolicyBuildWorkflowType; -exports.AutomatedReasoningPolicyTestRunResult = AutomatedReasoningPolicyTestRunResult; -exports.AutomatedReasoningPolicyTestRunStatus = AutomatedReasoningPolicyTestRunStatus; -exports.BatchDeleteEvaluationJobCommand = BatchDeleteEvaluationJobCommand; -exports.Bedrock = Bedrock; -exports.BedrockClient = BedrockClient; -exports.BedrockServiceException = BedrockServiceException$1; -exports.CancelAutomatedReasoningPolicyBuildWorkflowCommand = CancelAutomatedReasoningPolicyBuildWorkflowCommand; -exports.CommitmentDuration = CommitmentDuration; -exports.ConflictException = ConflictException$1; -exports.CreateAutomatedReasoningPolicyCommand = CreateAutomatedReasoningPolicyCommand; -exports.CreateAutomatedReasoningPolicyTestCaseCommand = CreateAutomatedReasoningPolicyTestCaseCommand; -exports.CreateAutomatedReasoningPolicyVersionCommand = CreateAutomatedReasoningPolicyVersionCommand; -exports.CreateCustomModelCommand = CreateCustomModelCommand; -exports.CreateCustomModelDeploymentCommand = CreateCustomModelDeploymentCommand; -exports.CreateEvaluationJobCommand = CreateEvaluationJobCommand; -exports.CreateFoundationModelAgreementCommand = CreateFoundationModelAgreementCommand; -exports.CreateGuardrailCommand = CreateGuardrailCommand; -exports.CreateGuardrailVersionCommand = CreateGuardrailVersionCommand; -exports.CreateInferenceProfileCommand = CreateInferenceProfileCommand; -exports.CreateMarketplaceModelEndpointCommand = CreateMarketplaceModelEndpointCommand; -exports.CreateModelCopyJobCommand = CreateModelCopyJobCommand; -exports.CreateModelCustomizationJobCommand = CreateModelCustomizationJobCommand; -exports.CreateModelImportJobCommand = CreateModelImportJobCommand; -exports.CreateModelInvocationJobCommand = CreateModelInvocationJobCommand; -exports.CreatePromptRouterCommand = CreatePromptRouterCommand; -exports.CreateProvisionedModelThroughputCommand = CreateProvisionedModelThroughputCommand; -exports.CustomModelDeploymentStatus = CustomModelDeploymentStatus; -exports.CustomizationType = CustomizationType; -exports.DeleteAutomatedReasoningPolicyBuildWorkflowCommand = DeleteAutomatedReasoningPolicyBuildWorkflowCommand; -exports.DeleteAutomatedReasoningPolicyCommand = DeleteAutomatedReasoningPolicyCommand; -exports.DeleteAutomatedReasoningPolicyTestCaseCommand = DeleteAutomatedReasoningPolicyTestCaseCommand; -exports.DeleteCustomModelCommand = DeleteCustomModelCommand; -exports.DeleteCustomModelDeploymentCommand = DeleteCustomModelDeploymentCommand; -exports.DeleteFoundationModelAgreementCommand = DeleteFoundationModelAgreementCommand; -exports.DeleteGuardrailCommand = DeleteGuardrailCommand; -exports.DeleteImportedModelCommand = DeleteImportedModelCommand; -exports.DeleteInferenceProfileCommand = DeleteInferenceProfileCommand; -exports.DeleteMarketplaceModelEndpointCommand = DeleteMarketplaceModelEndpointCommand; -exports.DeleteModelInvocationLoggingConfigurationCommand = DeleteModelInvocationLoggingConfigurationCommand; -exports.DeletePromptRouterCommand = DeletePromptRouterCommand; -exports.DeleteProvisionedModelThroughputCommand = DeleteProvisionedModelThroughputCommand; -exports.DeregisterMarketplaceModelEndpointCommand = DeregisterMarketplaceModelEndpointCommand; -exports.EntitlementAvailability = EntitlementAvailability; -exports.EvaluationJobStatus = EvaluationJobStatus; -exports.EvaluationJobType = EvaluationJobType; -exports.EvaluationTaskType = EvaluationTaskType; -exports.ExportAutomatedReasoningPolicyVersionCommand = ExportAutomatedReasoningPolicyVersionCommand; -exports.ExternalSourceType = ExternalSourceType; -exports.FineTuningJobStatus = FineTuningJobStatus; -exports.FoundationModelLifecycleStatus = FoundationModelLifecycleStatus; -exports.GetAutomatedReasoningPolicyAnnotationsCommand = GetAutomatedReasoningPolicyAnnotationsCommand; -exports.GetAutomatedReasoningPolicyBuildWorkflowCommand = GetAutomatedReasoningPolicyBuildWorkflowCommand; -exports.GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand = GetAutomatedReasoningPolicyBuildWorkflowResultAssetsCommand; -exports.GetAutomatedReasoningPolicyCommand = GetAutomatedReasoningPolicyCommand; -exports.GetAutomatedReasoningPolicyNextScenarioCommand = GetAutomatedReasoningPolicyNextScenarioCommand; -exports.GetAutomatedReasoningPolicyTestCaseCommand = GetAutomatedReasoningPolicyTestCaseCommand; -exports.GetAutomatedReasoningPolicyTestResultCommand = GetAutomatedReasoningPolicyTestResultCommand; -exports.GetCustomModelCommand = GetCustomModelCommand; -exports.GetCustomModelDeploymentCommand = GetCustomModelDeploymentCommand; -exports.GetEvaluationJobCommand = GetEvaluationJobCommand; -exports.GetFoundationModelAvailabilityCommand = GetFoundationModelAvailabilityCommand; -exports.GetFoundationModelCommand = GetFoundationModelCommand; -exports.GetGuardrailCommand = GetGuardrailCommand; -exports.GetImportedModelCommand = GetImportedModelCommand; -exports.GetInferenceProfileCommand = GetInferenceProfileCommand; -exports.GetMarketplaceModelEndpointCommand = GetMarketplaceModelEndpointCommand; -exports.GetModelCopyJobCommand = GetModelCopyJobCommand; -exports.GetModelCustomizationJobCommand = GetModelCustomizationJobCommand; -exports.GetModelImportJobCommand = GetModelImportJobCommand; -exports.GetModelInvocationJobCommand = GetModelInvocationJobCommand; -exports.GetModelInvocationLoggingConfigurationCommand = GetModelInvocationLoggingConfigurationCommand; -exports.GetPromptRouterCommand = GetPromptRouterCommand; -exports.GetProvisionedModelThroughputCommand = GetProvisionedModelThroughputCommand; -exports.GetUseCaseForModelAccessCommand = GetUseCaseForModelAccessCommand; -exports.GuardrailContentFilterAction = GuardrailContentFilterAction; -exports.GuardrailContentFilterType = GuardrailContentFilterType; -exports.GuardrailContentFiltersTierName = GuardrailContentFiltersTierName; -exports.GuardrailContextualGroundingAction = GuardrailContextualGroundingAction; -exports.GuardrailContextualGroundingFilterType = GuardrailContextualGroundingFilterType; -exports.GuardrailFilterStrength = GuardrailFilterStrength; -exports.GuardrailManagedWordsType = GuardrailManagedWordsType; -exports.GuardrailModality = GuardrailModality; -exports.GuardrailPiiEntityType = GuardrailPiiEntityType; -exports.GuardrailSensitiveInformationAction = GuardrailSensitiveInformationAction; -exports.GuardrailStatus = GuardrailStatus; -exports.GuardrailTopicAction = GuardrailTopicAction; -exports.GuardrailTopicType = GuardrailTopicType; -exports.GuardrailTopicsTierName = GuardrailTopicsTierName; -exports.GuardrailWordAction = GuardrailWordAction; -exports.InferenceProfileStatus = InferenceProfileStatus; -exports.InferenceProfileType = InferenceProfileType; -exports.InferenceType = InferenceType; -exports.InternalServerException = InternalServerException$1; -exports.JobStatusDetails = JobStatusDetails; -exports.ListAutomatedReasoningPoliciesCommand = ListAutomatedReasoningPoliciesCommand; -exports.ListAutomatedReasoningPolicyBuildWorkflowsCommand = ListAutomatedReasoningPolicyBuildWorkflowsCommand; -exports.ListAutomatedReasoningPolicyTestCasesCommand = ListAutomatedReasoningPolicyTestCasesCommand; -exports.ListAutomatedReasoningPolicyTestResultsCommand = ListAutomatedReasoningPolicyTestResultsCommand; -exports.ListCustomModelDeploymentsCommand = ListCustomModelDeploymentsCommand; -exports.ListCustomModelsCommand = ListCustomModelsCommand; -exports.ListEvaluationJobsCommand = ListEvaluationJobsCommand; -exports.ListFoundationModelAgreementOffersCommand = ListFoundationModelAgreementOffersCommand; -exports.ListFoundationModelsCommand = ListFoundationModelsCommand; -exports.ListGuardrailsCommand = ListGuardrailsCommand; -exports.ListImportedModelsCommand = ListImportedModelsCommand; -exports.ListInferenceProfilesCommand = ListInferenceProfilesCommand; -exports.ListMarketplaceModelEndpointsCommand = ListMarketplaceModelEndpointsCommand; -exports.ListModelCopyJobsCommand = ListModelCopyJobsCommand; -exports.ListModelCustomizationJobsCommand = ListModelCustomizationJobsCommand; -exports.ListModelImportJobsCommand = ListModelImportJobsCommand; -exports.ListModelInvocationJobsCommand = ListModelInvocationJobsCommand; -exports.ListPromptRoutersCommand = ListPromptRoutersCommand; -exports.ListProvisionedModelThroughputsCommand = ListProvisionedModelThroughputsCommand; -exports.ListTagsForResourceCommand = ListTagsForResourceCommand; -exports.ModelCopyJobStatus = ModelCopyJobStatus; -exports.ModelCustomization = ModelCustomization; -exports.ModelCustomizationJobStatus = ModelCustomizationJobStatus; -exports.ModelImportJobStatus = ModelImportJobStatus; -exports.ModelInvocationJobStatus = ModelInvocationJobStatus; -exports.ModelModality = ModelModality; -exports.ModelStatus = ModelStatus; -exports.OfferType = OfferType; -exports.PerformanceConfigLatency = PerformanceConfigLatency; -exports.PromptRouterStatus = PromptRouterStatus; -exports.PromptRouterType = PromptRouterType; -exports.ProvisionedModelStatus = ProvisionedModelStatus; -exports.PutModelInvocationLoggingConfigurationCommand = PutModelInvocationLoggingConfigurationCommand; -exports.PutUseCaseForModelAccessCommand = PutUseCaseForModelAccessCommand; -exports.QueryTransformationType = QueryTransformationType; -exports.RegionAvailability = RegionAvailability; -exports.RegisterMarketplaceModelEndpointCommand = RegisterMarketplaceModelEndpointCommand; -exports.RerankingMetadataSelectionMode = RerankingMetadataSelectionMode; -exports.ResourceInUseException = ResourceInUseException$1; -exports.ResourceNotFoundException = ResourceNotFoundException$1; -exports.RetrieveAndGenerateType = RetrieveAndGenerateType; -exports.S3InputFormat = S3InputFormat; -exports.SearchType = SearchType; -exports.ServiceQuotaExceededException = ServiceQuotaExceededException$1; -exports.ServiceUnavailableException = ServiceUnavailableException$1; -exports.SortByProvisionedModels = SortByProvisionedModels; -exports.SortJobsBy = SortJobsBy; -exports.SortModelsBy = SortModelsBy; -exports.SortOrder = SortOrder; -exports.StartAutomatedReasoningPolicyBuildWorkflowCommand = StartAutomatedReasoningPolicyBuildWorkflowCommand; -exports.StartAutomatedReasoningPolicyTestWorkflowCommand = StartAutomatedReasoningPolicyTestWorkflowCommand; -exports.Status = Status; -exports.StopEvaluationJobCommand = StopEvaluationJobCommand; -exports.StopModelCustomizationJobCommand = StopModelCustomizationJobCommand; -exports.StopModelInvocationJobCommand = StopModelInvocationJobCommand; -exports.TagResourceCommand = TagResourceCommand; -exports.ThrottlingException = ThrottlingException$1; -exports.TooManyTagsException = TooManyTagsException$1; -exports.UntagResourceCommand = UntagResourceCommand; -exports.UpdateAutomatedReasoningPolicyAnnotationsCommand = UpdateAutomatedReasoningPolicyAnnotationsCommand; -exports.UpdateAutomatedReasoningPolicyCommand = UpdateAutomatedReasoningPolicyCommand; -exports.UpdateAutomatedReasoningPolicyTestCaseCommand = UpdateAutomatedReasoningPolicyTestCaseCommand; -exports.UpdateGuardrailCommand = UpdateGuardrailCommand; -exports.UpdateMarketplaceModelEndpointCommand = UpdateMarketplaceModelEndpointCommand; -exports.UpdateProvisionedModelThroughputCommand = UpdateProvisionedModelThroughputCommand; -exports.ValidationException = ValidationException$1; -exports.VectorSearchRerankingConfigurationType = VectorSearchRerankingConfigurationType; -exports.paginateListAutomatedReasoningPolicies = paginateListAutomatedReasoningPolicies; -exports.paginateListAutomatedReasoningPolicyBuildWorkflows = paginateListAutomatedReasoningPolicyBuildWorkflows; -exports.paginateListAutomatedReasoningPolicyTestCases = paginateListAutomatedReasoningPolicyTestCases; -exports.paginateListAutomatedReasoningPolicyTestResults = paginateListAutomatedReasoningPolicyTestResults; -exports.paginateListCustomModelDeployments = paginateListCustomModelDeployments; -exports.paginateListCustomModels = paginateListCustomModels; -exports.paginateListEvaluationJobs = paginateListEvaluationJobs; -exports.paginateListGuardrails = paginateListGuardrails; -exports.paginateListImportedModels = paginateListImportedModels; -exports.paginateListInferenceProfiles = paginateListInferenceProfiles; -exports.paginateListMarketplaceModelEndpoints = paginateListMarketplaceModelEndpoints; -exports.paginateListModelCopyJobs = paginateListModelCopyJobs; -exports.paginateListModelCustomizationJobs = paginateListModelCustomizationJobs; -exports.paginateListModelImportJobs = paginateListModelImportJobs; -exports.paginateListModelInvocationJobs = paginateListModelInvocationJobs; -exports.paginateListPromptRouters = paginateListPromptRouters; -exports.paginateListProvisionedModelThroughputs = paginateListProvisionedModelThroughputs; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/runtimeConfig.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/runtimeConfig.js deleted file mode 100644 index ee8b6f27..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/runtimeConfig.js +++ /dev/null @@ -1,79 +0,0 @@ -"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 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 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 }), - 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.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), - 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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/runtimeConfig.shared.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/runtimeConfig.shared.js deleted file mode 100644 index cf4b9ba3..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock/dist-cjs/runtimeConfig.shared.js +++ /dev/null @@ -1,42 +0,0 @@ -"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-04-20", - 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.defaultBedrockHttpAuthSchemeProvider, - 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.bedrock" }), - serviceId: config?.serviceId ?? "Bedrock", - urlParser: config?.urlParser ?? url_parser_1.parseUrl, - utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, - utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 52303c3b..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,169 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-cjs/index.js deleted file mode 100644 index 9f589873..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/smithy-client/dist-cjs/index.js +++ /dev/null @@ -1,589 +0,0 @@ -'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]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js deleted file mode 100644 index b06a7b87..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js +++ /dev/null @@ -1,16 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/index.js deleted file mode 100644 index c095e288..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/index.js +++ /dev/null @@ -1,19 +0,0 @@ -'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]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/toBase64.js deleted file mode 100644 index 0590ce3f..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/dist-cjs/toBase64.js +++ /dev/null @@ -1,19 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js deleted file mode 100644 index b577c9ca..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js +++ /dev/null @@ -1,20 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js deleted file mode 100644 index 3238bb77..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-bedrock/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || - Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; - -exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/auth/httpAuthSchemeProvider.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/auth/httpAuthSchemeProvider.js deleted file mode 100644 index 5f7bb744..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/auth/httpAuthSchemeProvider.js +++ /dev/null @@ -1,68 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.resolveHttpAuthSchemeConfig = exports.defaultCognitoIdentityHttpAuthSchemeProvider = exports.defaultCognitoIdentityHttpAuthSchemeParametersProvider = void 0; -const core_1 = require("@aws-sdk/core"); -const util_middleware_1 = require("@smithy/util-middleware"); -const defaultCognitoIdentityHttpAuthSchemeParametersProvider = 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.defaultCognitoIdentityHttpAuthSchemeParametersProvider = defaultCognitoIdentityHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "cognito-identity", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth", - }; -} -const defaultCognitoIdentityHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "GetCredentialsForIdentity": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - case "GetId": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - case "GetOpenIdToken": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - case "UnlinkIdentity": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); - } - } - return options; -}; -exports.defaultCognitoIdentityHttpAuthSchemeProvider = defaultCognitoIdentityHttpAuthSchemeProvider; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); - return Object.assign(config_0, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), - }); -}; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/endpoint/endpointResolver.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/endpoint/endpointResolver.js deleted file mode 100644 index 7258a356..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/endpoint/endpointResolver.js +++ /dev/null @@ -1,18 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/endpoint/ruleset.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/endpoint/ruleset.js deleted file mode 100644 index e1510fa2..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/endpoint/ruleset.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ruleSet = void 0; -const w = "required", x = "fn", y = "argv", z = "ref"; -const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = "getAttr", i = "stringEquals", j = { [w]: false, "type": "string" }, k = { [w]: true, "default": false, "type": "boolean" }, l = { [z]: "Endpoint" }, m = { [x]: c, [y]: [{ [z]: "UseFIPS" }, true] }, n = { [x]: c, [y]: [{ [z]: "UseDualStack" }, true] }, o = {}, p = { [z]: "Region" }, q = { [x]: h, [y]: [{ [z]: g }, "supportsFIPS"] }, r = { [z]: g }, s = { [x]: c, [y]: [true, { [x]: h, [y]: [r, "supportsDualStack"] }] }, t = [m], u = [n], v = [p]; -const _data = { version: "1.0", parameters: { Region: j, UseDualStack: k, UseFIPS: k, Endpoint: j }, rules: [{ conditions: [{ [x]: b, [y]: [l] }], rules: [{ conditions: t, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: u, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: l, properties: o, headers: o }, type: e }], type: f }, { conditions: [{ [x]: b, [y]: v }], rules: [{ conditions: [{ [x]: "aws.partition", [y]: v, assign: g }], rules: [{ conditions: [m, n], rules: [{ conditions: [{ [x]: c, [y]: [a, q] }, s], rules: [{ conditions: [{ [x]: i, [y]: [p, "us-east-1"] }], endpoint: { url: "https://cognito-identity-fips.us-east-1.amazonaws.com", properties: o, headers: o }, type: e }, { conditions: [{ [x]: i, [y]: [p, "us-east-2"] }], endpoint: { url: "https://cognito-identity-fips.us-east-2.amazonaws.com", properties: o, headers: o }, type: e }, { conditions: [{ [x]: i, [y]: [p, "us-west-1"] }], endpoint: { url: "https://cognito-identity-fips.us-west-1.amazonaws.com", properties: o, headers: o }, type: e }, { conditions: [{ [x]: i, [y]: [p, "us-west-2"] }], endpoint: { url: "https://cognito-identity-fips.us-west-2.amazonaws.com", properties: o, headers: o }, type: e }, { endpoint: { url: "https://cognito-identity-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: o, headers: o }, type: e }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: t, rules: [{ conditions: [{ [x]: c, [y]: [q, a] }], rules: [{ endpoint: { url: "https://cognito-identity-fips.{Region}.{PartitionResult#dnsSuffix}", properties: o, headers: o }, type: e }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: u, rules: [{ conditions: [s], rules: [{ conditions: [{ [x]: i, [y]: ["aws", { [x]: h, [y]: [r, "name"] }] }], endpoint: { url: "https://cognito-identity.{Region}.amazonaws.com", properties: o, headers: o }, type: e }, { endpoint: { url: "https://cognito-identity.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: o, headers: o }, type: e }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { endpoint: { url: "https://cognito-identity.{Region}.{PartitionResult#dnsSuffix}", properties: o, headers: o }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; -exports.ruleSet = _data; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/index.js deleted file mode 100644 index dd92a297..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/index.js +++ /dev/null @@ -1,1266 +0,0 @@ -'use strict'; - -var middlewareHostHeader = require('@aws-sdk/middleware-host-header'); -var middlewareLogger = require('@aws-sdk/middleware-logger'); -var middlewareRecursionDetection = require('@aws-sdk/middleware-recursion-detection'); -var middlewareUserAgent = require('@aws-sdk/middleware-user-agent'); -var configResolver = require('@smithy/config-resolver'); -var core = require('@smithy/core'); -var schema = require('@smithy/core/schema'); -var middlewareContentLength = require('@smithy/middleware-content-length'); -var middlewareEndpoint = require('@smithy/middleware-endpoint'); -var middlewareRetry = require('@smithy/middleware-retry'); -var smithyClient = require('@smithy/smithy-client'); -var httpAuthSchemeProvider = require('./auth/httpAuthSchemeProvider'); -var runtimeConfig = require('./runtimeConfig'); -var regionConfigResolver = require('@aws-sdk/region-config-resolver'); -var protocolHttp = require('@smithy/protocol-http'); - -const resolveClientEndpointParameters = (options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - defaultSigningName: "cognito-identity", - }); -}; -const commonParams = { - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, -}; - -const getHttpAuthExtensionConfiguration = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } - else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - }, - }; -}; -const resolveHttpAuthRuntimeConfig = (config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials(), - }; -}; - -const resolveRuntimeExtensions = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig), smithyClient.getDefaultExtensionConfiguration(runtimeConfig), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); -}; - -class CognitoIdentityClient extends smithyClient.Client { - config; - constructor(...[configuration]) { - const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters(_config_0); - const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1); - const _config_3 = middlewareRetry.resolveRetryConfig(_config_2); - const _config_4 = configResolver.resolveRegionConfig(_config_3); - const _config_5 = middlewareHostHeader.resolveHostHeaderConfig(_config_4); - const _config_6 = middlewareEndpoint.resolveEndpointConfig(_config_5); - const _config_7 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_6); - const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use(schema.getSchemaSerdePlugin(this.config)); - this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config)); - this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config)); - this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config)); - this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config)); - this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config)); - this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config)); - this.middlewareStack.use(core.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { - httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultCognitoIdentityHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config) => new core.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials, - }), - })); - this.middlewareStack.use(core.getHttpSigningPlugin(this.config)); - } - destroy() { - super.destroy(); - } -} - -let CognitoIdentityServiceException$1 = class CognitoIdentityServiceException extends smithyClient.ServiceException { - constructor(options) { - super(options); - Object.setPrototypeOf(this, CognitoIdentityServiceException.prototype); - } -}; - -let InternalErrorException$1 = class InternalErrorException extends CognitoIdentityServiceException$1 { - name = "InternalErrorException"; - $fault = "server"; - constructor(opts) { - super({ - name: "InternalErrorException", - $fault: "server", - ...opts, - }); - Object.setPrototypeOf(this, InternalErrorException.prototype); - } -}; -let InvalidParameterException$1 = class InvalidParameterException extends CognitoIdentityServiceException$1 { - name = "InvalidParameterException"; - $fault = "client"; - constructor(opts) { - super({ - name: "InvalidParameterException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, InvalidParameterException.prototype); - } -}; -let LimitExceededException$1 = class LimitExceededException extends CognitoIdentityServiceException$1 { - name = "LimitExceededException"; - $fault = "client"; - constructor(opts) { - super({ - name: "LimitExceededException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, LimitExceededException.prototype); - } -}; -let NotAuthorizedException$1 = class NotAuthorizedException extends CognitoIdentityServiceException$1 { - name = "NotAuthorizedException"; - $fault = "client"; - constructor(opts) { - super({ - name: "NotAuthorizedException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, NotAuthorizedException.prototype); - } -}; -let ResourceConflictException$1 = class ResourceConflictException extends CognitoIdentityServiceException$1 { - name = "ResourceConflictException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ResourceConflictException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ResourceConflictException.prototype); - } -}; -let TooManyRequestsException$1 = class TooManyRequestsException extends CognitoIdentityServiceException$1 { - name = "TooManyRequestsException"; - $fault = "client"; - constructor(opts) { - super({ - name: "TooManyRequestsException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, TooManyRequestsException.prototype); - } -}; -let ResourceNotFoundException$1 = class ResourceNotFoundException extends CognitoIdentityServiceException$1 { - name = "ResourceNotFoundException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ResourceNotFoundException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ResourceNotFoundException.prototype); - } -}; -let ExternalServiceException$1 = class ExternalServiceException extends CognitoIdentityServiceException$1 { - name = "ExternalServiceException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ExternalServiceException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ExternalServiceException.prototype); - } -}; -let InvalidIdentityPoolConfigurationException$1 = class InvalidIdentityPoolConfigurationException extends CognitoIdentityServiceException$1 { - name = "InvalidIdentityPoolConfigurationException"; - $fault = "client"; - constructor(opts) { - super({ - name: "InvalidIdentityPoolConfigurationException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, InvalidIdentityPoolConfigurationException.prototype); - } -}; -let DeveloperUserAlreadyRegisteredException$1 = class DeveloperUserAlreadyRegisteredException extends CognitoIdentityServiceException$1 { - name = "DeveloperUserAlreadyRegisteredException"; - $fault = "client"; - constructor(opts) { - super({ - name: "DeveloperUserAlreadyRegisteredException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, DeveloperUserAlreadyRegisteredException.prototype); - } -}; -let ConcurrentModificationException$1 = class ConcurrentModificationException extends CognitoIdentityServiceException$1 { - name = "ConcurrentModificationException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ConcurrentModificationException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ConcurrentModificationException.prototype); - } -}; - -const _ACF = "AllowClassicFlow"; -const _AI = "AccountId"; -const _AKI = "AccessKeyId"; -const _ARR = "AmbiguousRoleResolution"; -const _AUI = "AllowUnauthenticatedIdentities"; -const _C = "Credentials"; -const _CD = "CreationDate"; -const _CI = "ClientId"; -const _CIP = "CognitoIdentityProvider"; -const _CIPI = "CreateIdentityPoolInput"; -const _CIPL = "CognitoIdentityProviderList"; -const _CIPo = "CognitoIdentityProviders"; -const _CIPr = "CreateIdentityPool"; -const _CME = "ConcurrentModificationException"; -const _CRA = "CustomRoleArn"; -const _Cl = "Claim"; -const _DI = "DeleteIdentities"; -const _DII = "DeleteIdentitiesInput"; -const _DIIe = "DescribeIdentityInput"; -const _DIP = "DeleteIdentityPool"; -const _DIPI = "DeleteIdentityPoolInput"; -const _DIPIe = "DescribeIdentityPoolInput"; -const _DIPe = "DescribeIdentityPool"; -const _DIR = "DeleteIdentitiesResponse"; -const _DIe = "DescribeIdentity"; -const _DPN = "DeveloperProviderName"; -const _DUARE = "DeveloperUserAlreadyRegisteredException"; -const _DUI = "DeveloperUserIdentifier"; -const _DUIL = "DeveloperUserIdentifierList"; -const _DUIe = "DestinationUserIdentifier"; -const _E = "Expiration"; -const _EC = "ErrorCode"; -const _ESE = "ExternalServiceException"; -const _GCFI = "GetCredentialsForIdentity"; -const _GCFII = "GetCredentialsForIdentityInput"; -const _GCFIR = "GetCredentialsForIdentityResponse"; -const _GI = "GetId"; -const _GII = "GetIdInput"; -const _GIPR = "GetIdentityPoolRoles"; -const _GIPRI = "GetIdentityPoolRolesInput"; -const _GIPRR = "GetIdentityPoolRolesResponse"; -const _GIR = "GetIdResponse"; -const _GOIT = "GetOpenIdToken"; -const _GOITFDI = "GetOpenIdTokenForDeveloperIdentity"; -const _GOITFDII = "GetOpenIdTokenForDeveloperIdentityInput"; -const _GOITFDIR = "GetOpenIdTokenForDeveloperIdentityResponse"; -const _GOITI = "GetOpenIdTokenInput"; -const _GOITR = "GetOpenIdTokenResponse"; -const _GPTAM = "GetPrincipalTagAttributeMap"; -const _GPTAMI = "GetPrincipalTagAttributeMapInput"; -const _GPTAMR = "GetPrincipalTagAttributeMapResponse"; -const _HD = "HideDisabled"; -const _I = "Identities"; -const _ID = "IdentityDescription"; -const _IEE = "InternalErrorException"; -const _II = "IdentityId"; -const _IIPCE = "InvalidIdentityPoolConfigurationException"; -const _IITD = "IdentityIdsToDelete"; -const _IL = "IdentitiesList"; -const _IP = "IdentityPool"; -const _IPE = "InvalidParameterException"; -const _IPI = "IdentityPoolId"; -const _IPL = "IdentityPoolsList"; -const _IPN = "IdentityPoolName"; -const _IPNd = "IdentityProviderName"; -const _IPSD = "IdentityPoolShortDescription"; -const _IPT = "IdentityProviderToken"; -const _IPTd = "IdentityPoolTags"; -const _IPd = "IdentityPools"; -const _L = "Logins"; -const _LDI = "LookupDeveloperIdentity"; -const _LDII = "LookupDeveloperIdentityInput"; -const _LDIR = "LookupDeveloperIdentityResponse"; -const _LEE = "LimitExceededException"; -const _LI = "ListIdentities"; -const _LII = "ListIdentitiesInput"; -const _LIP = "ListIdentityPools"; -const _LIPI = "ListIdentityPoolsInput"; -const _LIPR = "ListIdentityPoolsResponse"; -const _LIR = "ListIdentitiesResponse"; -const _LM = "LoginsMap"; -const _LMD = "LastModifiedDate"; -const _LTFR = "ListTagsForResource"; -const _LTFRI = "ListTagsForResourceInput"; -const _LTFRR = "ListTagsForResourceResponse"; -const _LTR = "LoginsToRemove"; -const _MDI = "MergeDeveloperIdentities"; -const _MDII = "MergeDeveloperIdentitiesInput"; -const _MDIR = "MergeDeveloperIdentitiesResponse"; -const _MR = "MaxResults"; -const _MRL = "MappingRulesList"; -const _MRa = "MappingRule"; -const _MT = "MatchType"; -const _NAE = "NotAuthorizedException"; -const _NT = "NextToken"; -const _OICPARN = "OpenIdConnectProviderARNs"; -const _OIDCT = "OIDCToken"; -const _PN = "ProviderName"; -const _PT = "PrincipalTags"; -const _R = "Roles"; -const _RA = "ResourceArn"; -const _RARN = "RoleARN"; -const _RC = "RulesConfiguration"; -const _RCE = "ResourceConflictException"; -const _RCT = "RulesConfigurationType"; -const _RM = "RoleMappings"; -const _RMM = "RoleMappingMap"; -const _RMo = "RoleMapping"; -const _RNFE = "ResourceNotFoundException"; -const _Ru = "Rules"; -const _SIPR = "SetIdentityPoolRoles"; -const _SIPRI = "SetIdentityPoolRolesInput"; -const _SK = "SecretKey"; -const _SKS = "SecretKeyString"; -const _SLP = "SupportedLoginProviders"; -const _SPARN = "SamlProviderARNs"; -const _SPTAM = "SetPrincipalTagAttributeMap"; -const _SPTAMI = "SetPrincipalTagAttributeMapInput"; -const _SPTAMR = "SetPrincipalTagAttributeMapResponse"; -const _SSTC = "ServerSideTokenCheck"; -const _ST = "SessionToken"; -const _SUI = "SourceUserIdentifier"; -const _T = "Token"; -const _TD = "TokenDuration"; -const _TK = "TagKeys"; -const _TMRE = "TooManyRequestsException"; -const _TR = "TagResource"; -const _TRI = "TagResourceInput"; -const _TRR = "TagResourceResponse"; -const _Ta = "Tags"; -const _Ty = "Type"; -const _UD = "UseDefaults"; -const _UDI = "UnlinkDeveloperIdentity"; -const _UDII = "UnlinkDeveloperIdentityInput"; -const _UI = "UnlinkIdentity"; -const _UII = "UnprocessedIdentityIds"; -const _UIIL = "UnprocessedIdentityIdList"; -const _UIIn = "UnlinkIdentityInput"; -const _UIInp = "UnprocessedIdentityId"; -const _UIP = "UpdateIdentityPool"; -const _UR = "UntagResource"; -const _URI = "UntagResourceInput"; -const _URR = "UntagResourceResponse"; -const _V = "Value"; -const _c = "client"; -const _e = "error"; -const _hE = "httpError"; -const _m = "message"; -const _s = "server"; -const _sm = "smithy.ts.sdk.synthetic.com.amazonaws.cognitoidentity"; -const n0 = "com.amazonaws.cognitoidentity"; -var IdentityProviderToken = [0, n0, _IPT, 8, 0]; -var OIDCToken = [0, n0, _OIDCT, 8, 0]; -var SecretKeyString = [0, n0, _SKS, 8, 0]; -var CognitoIdentityProvider = [3, n0, _CIP, 0, [_PN, _CI, _SSTC], [0, 0, 2]]; -var ConcurrentModificationException = [ - -3, - n0, - _CME, - { - [_e]: _c, - [_hE]: 400, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ConcurrentModificationException, ConcurrentModificationException$1); -var CreateIdentityPoolInput = [ - 3, - n0, - _CIPI, - 0, - [_IPN, _AUI, _ACF, _SLP, _DPN, _OICPARN, _CIPo, _SPARN, _IPTd], - [0, 2, 2, 128 | 0, 0, 64 | 0, () => CognitoIdentityProviderList, 64 | 0, 128 | 0], -]; -var Credentials = [ - 3, - n0, - _C, - 0, - [_AKI, _SK, _ST, _E], - [0, [() => SecretKeyString, 0], 0, 4], -]; -var DeleteIdentitiesInput = [3, n0, _DII, 0, [_IITD], [64 | 0]]; -var DeleteIdentitiesResponse = [ - 3, - n0, - _DIR, - 0, - [_UII], - [() => UnprocessedIdentityIdList], -]; -var DeleteIdentityPoolInput = [3, n0, _DIPI, 0, [_IPI], [0]]; -var DescribeIdentityInput = [3, n0, _DIIe, 0, [_II], [0]]; -var DescribeIdentityPoolInput = [3, n0, _DIPIe, 0, [_IPI], [0]]; -var DeveloperUserAlreadyRegisteredException = [ - -3, - n0, - _DUARE, - { - [_e]: _c, - [_hE]: 400, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(DeveloperUserAlreadyRegisteredException, DeveloperUserAlreadyRegisteredException$1); -var ExternalServiceException = [ - -3, - n0, - _ESE, - { - [_e]: _c, - [_hE]: 400, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ExternalServiceException, ExternalServiceException$1); -var GetCredentialsForIdentityInput = [ - 3, - n0, - _GCFII, - 0, - [_II, _L, _CRA], - [0, [() => LoginsMap, 0], 0], -]; -var GetCredentialsForIdentityResponse = [ - 3, - n0, - _GCFIR, - 0, - [_II, _C], - [0, [() => Credentials, 0]], -]; -var GetIdentityPoolRolesInput = [3, n0, _GIPRI, 0, [_IPI], [0]]; -var GetIdentityPoolRolesResponse = [ - 3, - n0, - _GIPRR, - 0, - [_IPI, _R, _RM], - [0, 128 | 0, () => RoleMappingMap], -]; -var GetIdInput = [3, n0, _GII, 0, [_AI, _IPI, _L], [0, 0, [() => LoginsMap, 0]]]; -var GetIdResponse = [3, n0, _GIR, 0, [_II], [0]]; -var GetOpenIdTokenForDeveloperIdentityInput = [ - 3, - n0, - _GOITFDII, - 0, - [_IPI, _II, _L, _PT, _TD], - [0, 0, [() => LoginsMap, 0], 128 | 0, 1], -]; -var GetOpenIdTokenForDeveloperIdentityResponse = [ - 3, - n0, - _GOITFDIR, - 0, - [_II, _T], - [0, [() => OIDCToken, 0]], -]; -var GetOpenIdTokenInput = [3, n0, _GOITI, 0, [_II, _L], [0, [() => LoginsMap, 0]]]; -var GetOpenIdTokenResponse = [3, n0, _GOITR, 0, [_II, _T], [0, [() => OIDCToken, 0]]]; -var GetPrincipalTagAttributeMapInput = [3, n0, _GPTAMI, 0, [_IPI, _IPNd], [0, 0]]; -var GetPrincipalTagAttributeMapResponse = [ - 3, - n0, - _GPTAMR, - 0, - [_IPI, _IPNd, _UD, _PT], - [0, 0, 2, 128 | 0], -]; -var IdentityDescription = [3, n0, _ID, 0, [_II, _L, _CD, _LMD], [0, 64 | 0, 4, 4]]; -var IdentityPool = [ - 3, - n0, - _IP, - 0, - [_IPI, _IPN, _AUI, _ACF, _SLP, _DPN, _OICPARN, _CIPo, _SPARN, _IPTd], - [0, 0, 2, 2, 128 | 0, 0, 64 | 0, () => CognitoIdentityProviderList, 64 | 0, 128 | 0], -]; -var IdentityPoolShortDescription = [3, n0, _IPSD, 0, [_IPI, _IPN], [0, 0]]; -var InternalErrorException = [ - -3, - n0, - _IEE, - { - [_e]: _s, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(InternalErrorException, InternalErrorException$1); -var InvalidIdentityPoolConfigurationException = [ - -3, - n0, - _IIPCE, - { - [_e]: _c, - [_hE]: 400, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(InvalidIdentityPoolConfigurationException, InvalidIdentityPoolConfigurationException$1); -var InvalidParameterException = [ - -3, - n0, - _IPE, - { - [_e]: _c, - [_hE]: 400, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(InvalidParameterException, InvalidParameterException$1); -var LimitExceededException = [ - -3, - n0, - _LEE, - { - [_e]: _c, - [_hE]: 400, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(LimitExceededException, LimitExceededException$1); -var ListIdentitiesInput = [3, n0, _LII, 0, [_IPI, _MR, _NT, _HD], [0, 1, 0, 2]]; -var ListIdentitiesResponse = [ - 3, - n0, - _LIR, - 0, - [_IPI, _I, _NT], - [0, () => IdentitiesList, 0], -]; -var ListIdentityPoolsInput = [3, n0, _LIPI, 0, [_MR, _NT], [1, 0]]; -var ListIdentityPoolsResponse = [ - 3, - n0, - _LIPR, - 0, - [_IPd, _NT], - [() => IdentityPoolsList, 0], -]; -var ListTagsForResourceInput = [3, n0, _LTFRI, 0, [_RA], [0]]; -var ListTagsForResourceResponse = [3, n0, _LTFRR, 0, [_Ta], [128 | 0]]; -var LookupDeveloperIdentityInput = [ - 3, - n0, - _LDII, - 0, - [_IPI, _II, _DUI, _MR, _NT], - [0, 0, 0, 1, 0], -]; -var LookupDeveloperIdentityResponse = [ - 3, - n0, - _LDIR, - 0, - [_II, _DUIL, _NT], - [0, 64 | 0, 0], -]; -var MappingRule = [3, n0, _MRa, 0, [_Cl, _MT, _V, _RARN], [0, 0, 0, 0]]; -var MergeDeveloperIdentitiesInput = [ - 3, - n0, - _MDII, - 0, - [_SUI, _DUIe, _DPN, _IPI], - [0, 0, 0, 0], -]; -var MergeDeveloperIdentitiesResponse = [3, n0, _MDIR, 0, [_II], [0]]; -var NotAuthorizedException = [ - -3, - n0, - _NAE, - { - [_e]: _c, - [_hE]: 403, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(NotAuthorizedException, NotAuthorizedException$1); -var ResourceConflictException = [ - -3, - n0, - _RCE, - { - [_e]: _c, - [_hE]: 409, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ResourceConflictException, ResourceConflictException$1); -var ResourceNotFoundException = [ - -3, - n0, - _RNFE, - { - [_e]: _c, - [_hE]: 404, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ResourceNotFoundException, ResourceNotFoundException$1); -var RoleMapping = [ - 3, - n0, - _RMo, - 0, - [_Ty, _ARR, _RC], - [0, 0, () => RulesConfigurationType], -]; -var RulesConfigurationType = [3, n0, _RCT, 0, [_Ru], [() => MappingRulesList]]; -var SetIdentityPoolRolesInput = [ - 3, - n0, - _SIPRI, - 0, - [_IPI, _R, _RM], - [0, 128 | 0, () => RoleMappingMap], -]; -var SetPrincipalTagAttributeMapInput = [ - 3, - n0, - _SPTAMI, - 0, - [_IPI, _IPNd, _UD, _PT], - [0, 0, 2, 128 | 0], -]; -var SetPrincipalTagAttributeMapResponse = [ - 3, - n0, - _SPTAMR, - 0, - [_IPI, _IPNd, _UD, _PT], - [0, 0, 2, 128 | 0], -]; -var TagResourceInput = [3, n0, _TRI, 0, [_RA, _Ta], [0, 128 | 0]]; -var TagResourceResponse = [3, n0, _TRR, 0, [], []]; -var TooManyRequestsException = [ - -3, - n0, - _TMRE, - { - [_e]: _c, - [_hE]: 429, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(TooManyRequestsException, TooManyRequestsException$1); -var UnlinkDeveloperIdentityInput = [ - 3, - n0, - _UDII, - 0, - [_II, _IPI, _DPN, _DUI], - [0, 0, 0, 0], -]; -var UnlinkIdentityInput = [ - 3, - n0, - _UIIn, - 0, - [_II, _L, _LTR], - [0, [() => LoginsMap, 0], 64 | 0], -]; -var UnprocessedIdentityId = [3, n0, _UIInp, 0, [_II, _EC], [0, 0]]; -var UntagResourceInput = [3, n0, _URI, 0, [_RA, _TK], [0, 64 | 0]]; -var UntagResourceResponse = [3, n0, _URR, 0, [], []]; -var __Unit = "unit"; -var CognitoIdentityServiceException = [-3, _sm, "CognitoIdentityServiceException", 0, [], []]; -schema.TypeRegistry.for(_sm).registerError(CognitoIdentityServiceException, CognitoIdentityServiceException$1); -var CognitoIdentityProviderList = [1, n0, _CIPL, 0, () => CognitoIdentityProvider]; -var IdentitiesList = [1, n0, _IL, 0, () => IdentityDescription]; -var IdentityPoolsList = [1, n0, _IPL, 0, () => IdentityPoolShortDescription]; -var MappingRulesList = [1, n0, _MRL, 0, () => MappingRule]; -var UnprocessedIdentityIdList = [1, n0, _UIIL, 0, () => UnprocessedIdentityId]; -var LoginsMap = [2, n0, _LM, 0, [0, 0], [() => IdentityProviderToken, 0]]; -var RoleMappingMap = [2, n0, _RMM, 0, 0, () => RoleMapping]; -var CreateIdentityPool = [ - 9, - n0, - _CIPr, - 0, - () => CreateIdentityPoolInput, - () => IdentityPool, -]; -var DeleteIdentities = [ - 9, - n0, - _DI, - 0, - () => DeleteIdentitiesInput, - () => DeleteIdentitiesResponse, -]; -var DeleteIdentityPool = [9, n0, _DIP, 0, () => DeleteIdentityPoolInput, () => __Unit]; -var DescribeIdentity = [ - 9, - n0, - _DIe, - 0, - () => DescribeIdentityInput, - () => IdentityDescription, -]; -var DescribeIdentityPool = [ - 9, - n0, - _DIPe, - 0, - () => DescribeIdentityPoolInput, - () => IdentityPool, -]; -var GetCredentialsForIdentity = [ - 9, - n0, - _GCFI, - 0, - () => GetCredentialsForIdentityInput, - () => GetCredentialsForIdentityResponse, -]; -var GetId = [9, n0, _GI, 0, () => GetIdInput, () => GetIdResponse]; -var GetIdentityPoolRoles = [ - 9, - n0, - _GIPR, - 0, - () => GetIdentityPoolRolesInput, - () => GetIdentityPoolRolesResponse, -]; -var GetOpenIdToken = [ - 9, - n0, - _GOIT, - 0, - () => GetOpenIdTokenInput, - () => GetOpenIdTokenResponse, -]; -var GetOpenIdTokenForDeveloperIdentity = [ - 9, - n0, - _GOITFDI, - 0, - () => GetOpenIdTokenForDeveloperIdentityInput, - () => GetOpenIdTokenForDeveloperIdentityResponse, -]; -var GetPrincipalTagAttributeMap = [ - 9, - n0, - _GPTAM, - 0, - () => GetPrincipalTagAttributeMapInput, - () => GetPrincipalTagAttributeMapResponse, -]; -var ListIdentities = [ - 9, - n0, - _LI, - 0, - () => ListIdentitiesInput, - () => ListIdentitiesResponse, -]; -var ListIdentityPools = [ - 9, - n0, - _LIP, - 0, - () => ListIdentityPoolsInput, - () => ListIdentityPoolsResponse, -]; -var ListTagsForResource = [ - 9, - n0, - _LTFR, - 0, - () => ListTagsForResourceInput, - () => ListTagsForResourceResponse, -]; -var LookupDeveloperIdentity = [ - 9, - n0, - _LDI, - 0, - () => LookupDeveloperIdentityInput, - () => LookupDeveloperIdentityResponse, -]; -var MergeDeveloperIdentities = [ - 9, - n0, - _MDI, - 0, - () => MergeDeveloperIdentitiesInput, - () => MergeDeveloperIdentitiesResponse, -]; -var SetIdentityPoolRoles = [ - 9, - n0, - _SIPR, - 0, - () => SetIdentityPoolRolesInput, - () => __Unit, -]; -var SetPrincipalTagAttributeMap = [ - 9, - n0, - _SPTAM, - 0, - () => SetPrincipalTagAttributeMapInput, - () => SetPrincipalTagAttributeMapResponse, -]; -var TagResource = [9, n0, _TR, 0, () => TagResourceInput, () => TagResourceResponse]; -var UnlinkDeveloperIdentity = [ - 9, - n0, - _UDI, - 0, - () => UnlinkDeveloperIdentityInput, - () => __Unit, -]; -var UnlinkIdentity = [9, n0, _UI, 0, () => UnlinkIdentityInput, () => __Unit]; -var UntagResource = [ - 9, - n0, - _UR, - 0, - () => UntagResourceInput, - () => UntagResourceResponse, -]; -var UpdateIdentityPool = [9, n0, _UIP, 0, () => IdentityPool, () => IdentityPool]; - -class CreateIdentityPoolCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "CreateIdentityPool", {}) - .n("CognitoIdentityClient", "CreateIdentityPoolCommand") - .sc(CreateIdentityPool) - .build() { -} - -class DeleteIdentitiesCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "DeleteIdentities", {}) - .n("CognitoIdentityClient", "DeleteIdentitiesCommand") - .sc(DeleteIdentities) - .build() { -} - -class DeleteIdentityPoolCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "DeleteIdentityPool", {}) - .n("CognitoIdentityClient", "DeleteIdentityPoolCommand") - .sc(DeleteIdentityPool) - .build() { -} - -class DescribeIdentityCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "DescribeIdentity", {}) - .n("CognitoIdentityClient", "DescribeIdentityCommand") - .sc(DescribeIdentity) - .build() { -} - -class DescribeIdentityPoolCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "DescribeIdentityPool", {}) - .n("CognitoIdentityClient", "DescribeIdentityPoolCommand") - .sc(DescribeIdentityPool) - .build() { -} - -class GetCredentialsForIdentityCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "GetCredentialsForIdentity", {}) - .n("CognitoIdentityClient", "GetCredentialsForIdentityCommand") - .sc(GetCredentialsForIdentity) - .build() { -} - -class GetIdCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "GetId", {}) - .n("CognitoIdentityClient", "GetIdCommand") - .sc(GetId) - .build() { -} - -class GetIdentityPoolRolesCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "GetIdentityPoolRoles", {}) - .n("CognitoIdentityClient", "GetIdentityPoolRolesCommand") - .sc(GetIdentityPoolRoles) - .build() { -} - -class GetOpenIdTokenCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "GetOpenIdToken", {}) - .n("CognitoIdentityClient", "GetOpenIdTokenCommand") - .sc(GetOpenIdToken) - .build() { -} - -class GetOpenIdTokenForDeveloperIdentityCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "GetOpenIdTokenForDeveloperIdentity", {}) - .n("CognitoIdentityClient", "GetOpenIdTokenForDeveloperIdentityCommand") - .sc(GetOpenIdTokenForDeveloperIdentity) - .build() { -} - -class GetPrincipalTagAttributeMapCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "GetPrincipalTagAttributeMap", {}) - .n("CognitoIdentityClient", "GetPrincipalTagAttributeMapCommand") - .sc(GetPrincipalTagAttributeMap) - .build() { -} - -class ListIdentitiesCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "ListIdentities", {}) - .n("CognitoIdentityClient", "ListIdentitiesCommand") - .sc(ListIdentities) - .build() { -} - -class ListIdentityPoolsCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "ListIdentityPools", {}) - .n("CognitoIdentityClient", "ListIdentityPoolsCommand") - .sc(ListIdentityPools) - .build() { -} - -class ListTagsForResourceCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "ListTagsForResource", {}) - .n("CognitoIdentityClient", "ListTagsForResourceCommand") - .sc(ListTagsForResource) - .build() { -} - -class LookupDeveloperIdentityCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "LookupDeveloperIdentity", {}) - .n("CognitoIdentityClient", "LookupDeveloperIdentityCommand") - .sc(LookupDeveloperIdentity) - .build() { -} - -class MergeDeveloperIdentitiesCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "MergeDeveloperIdentities", {}) - .n("CognitoIdentityClient", "MergeDeveloperIdentitiesCommand") - .sc(MergeDeveloperIdentities) - .build() { -} - -class SetIdentityPoolRolesCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "SetIdentityPoolRoles", {}) - .n("CognitoIdentityClient", "SetIdentityPoolRolesCommand") - .sc(SetIdentityPoolRoles) - .build() { -} - -class SetPrincipalTagAttributeMapCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "SetPrincipalTagAttributeMap", {}) - .n("CognitoIdentityClient", "SetPrincipalTagAttributeMapCommand") - .sc(SetPrincipalTagAttributeMap) - .build() { -} - -class TagResourceCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "TagResource", {}) - .n("CognitoIdentityClient", "TagResourceCommand") - .sc(TagResource) - .build() { -} - -class UnlinkDeveloperIdentityCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "UnlinkDeveloperIdentity", {}) - .n("CognitoIdentityClient", "UnlinkDeveloperIdentityCommand") - .sc(UnlinkDeveloperIdentity) - .build() { -} - -class UnlinkIdentityCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "UnlinkIdentity", {}) - .n("CognitoIdentityClient", "UnlinkIdentityCommand") - .sc(UnlinkIdentity) - .build() { -} - -class UntagResourceCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "UntagResource", {}) - .n("CognitoIdentityClient", "UntagResourceCommand") - .sc(UntagResource) - .build() { -} - -class UpdateIdentityPoolCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSCognitoIdentityService", "UpdateIdentityPool", {}) - .n("CognitoIdentityClient", "UpdateIdentityPoolCommand") - .sc(UpdateIdentityPool) - .build() { -} - -const commands = { - CreateIdentityPoolCommand, - DeleteIdentitiesCommand, - DeleteIdentityPoolCommand, - DescribeIdentityCommand, - DescribeIdentityPoolCommand, - GetCredentialsForIdentityCommand, - GetIdCommand, - GetIdentityPoolRolesCommand, - GetOpenIdTokenCommand, - GetOpenIdTokenForDeveloperIdentityCommand, - GetPrincipalTagAttributeMapCommand, - ListIdentitiesCommand, - ListIdentityPoolsCommand, - ListTagsForResourceCommand, - LookupDeveloperIdentityCommand, - MergeDeveloperIdentitiesCommand, - SetIdentityPoolRolesCommand, - SetPrincipalTagAttributeMapCommand, - TagResourceCommand, - UnlinkDeveloperIdentityCommand, - UnlinkIdentityCommand, - UntagResourceCommand, - UpdateIdentityPoolCommand, -}; -class CognitoIdentity extends CognitoIdentityClient { -} -smithyClient.createAggregatedClient(commands, CognitoIdentity); - -const paginateListIdentityPools = core.createPaginator(CognitoIdentityClient, ListIdentityPoolsCommand, "NextToken", "NextToken", "MaxResults"); - -const AmbiguousRoleResolutionType = { - AUTHENTICATED_ROLE: "AuthenticatedRole", - DENY: "Deny", -}; -const ErrorCode = { - ACCESS_DENIED: "AccessDenied", - INTERNAL_SERVER_ERROR: "InternalServerError", -}; -const MappingRuleMatchType = { - CONTAINS: "Contains", - EQUALS: "Equals", - NOT_EQUAL: "NotEqual", - STARTS_WITH: "StartsWith", -}; -const RoleMappingType = { - RULES: "Rules", - TOKEN: "Token", -}; - -Object.defineProperty(exports, "$Command", { - enumerable: true, - get: function () { return smithyClient.Command; } -}); -Object.defineProperty(exports, "__Client", { - enumerable: true, - get: function () { return smithyClient.Client; } -}); -exports.AmbiguousRoleResolutionType = AmbiguousRoleResolutionType; -exports.CognitoIdentity = CognitoIdentity; -exports.CognitoIdentityClient = CognitoIdentityClient; -exports.CognitoIdentityServiceException = CognitoIdentityServiceException$1; -exports.ConcurrentModificationException = ConcurrentModificationException$1; -exports.CreateIdentityPoolCommand = CreateIdentityPoolCommand; -exports.DeleteIdentitiesCommand = DeleteIdentitiesCommand; -exports.DeleteIdentityPoolCommand = DeleteIdentityPoolCommand; -exports.DescribeIdentityCommand = DescribeIdentityCommand; -exports.DescribeIdentityPoolCommand = DescribeIdentityPoolCommand; -exports.DeveloperUserAlreadyRegisteredException = DeveloperUserAlreadyRegisteredException$1; -exports.ErrorCode = ErrorCode; -exports.ExternalServiceException = ExternalServiceException$1; -exports.GetCredentialsForIdentityCommand = GetCredentialsForIdentityCommand; -exports.GetIdCommand = GetIdCommand; -exports.GetIdentityPoolRolesCommand = GetIdentityPoolRolesCommand; -exports.GetOpenIdTokenCommand = GetOpenIdTokenCommand; -exports.GetOpenIdTokenForDeveloperIdentityCommand = GetOpenIdTokenForDeveloperIdentityCommand; -exports.GetPrincipalTagAttributeMapCommand = GetPrincipalTagAttributeMapCommand; -exports.InternalErrorException = InternalErrorException$1; -exports.InvalidIdentityPoolConfigurationException = InvalidIdentityPoolConfigurationException$1; -exports.InvalidParameterException = InvalidParameterException$1; -exports.LimitExceededException = LimitExceededException$1; -exports.ListIdentitiesCommand = ListIdentitiesCommand; -exports.ListIdentityPoolsCommand = ListIdentityPoolsCommand; -exports.ListTagsForResourceCommand = ListTagsForResourceCommand; -exports.LookupDeveloperIdentityCommand = LookupDeveloperIdentityCommand; -exports.MappingRuleMatchType = MappingRuleMatchType; -exports.MergeDeveloperIdentitiesCommand = MergeDeveloperIdentitiesCommand; -exports.NotAuthorizedException = NotAuthorizedException$1; -exports.ResourceConflictException = ResourceConflictException$1; -exports.ResourceNotFoundException = ResourceNotFoundException$1; -exports.RoleMappingType = RoleMappingType; -exports.SetIdentityPoolRolesCommand = SetIdentityPoolRolesCommand; -exports.SetPrincipalTagAttributeMapCommand = SetPrincipalTagAttributeMapCommand; -exports.TagResourceCommand = TagResourceCommand; -exports.TooManyRequestsException = TooManyRequestsException$1; -exports.UnlinkDeveloperIdentityCommand = UnlinkDeveloperIdentityCommand; -exports.UnlinkIdentityCommand = UnlinkIdentityCommand; -exports.UntagResourceCommand = UntagResourceCommand; -exports.UpdateIdentityPoolCommand = UpdateIdentityPoolCommand; -exports.paginateListIdentityPools = paginateListIdentityPools; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/runtimeConfig.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/runtimeConfig.js deleted file mode 100644 index d4031116..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/runtimeConfig.js +++ /dev/null @@ -1,56 +0,0 @@ -"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 util_user_agent_node_1 = require("@aws-sdk/util-user-agent-node"); -const config_resolver_1 = require("@smithy/config-resolver"); -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, - }; - 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 }), - 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.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), - 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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/runtimeConfig.shared.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/runtimeConfig.shared.js deleted file mode 100644 index e58de461..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/dist-cjs/runtimeConfig.shared.js +++ /dev/null @@ -1,47 +0,0 @@ -"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: "2014-06-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.defaultCognitoIdentityHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - logger: config?.logger ?? new smithy_client_1.NoOpLogger(), - protocol: config?.protocol ?? - new protocols_1.AwsJson1_1Protocol({ - defaultNamespace: "com.amazonaws.cognitoidentity", - serviceTarget: "AWSCognitoIdentityService", - awsQueryCompatible: false, - }), - serviceId: config?.serviceId ?? "Cognito Identity", - urlParser: config?.urlParser ?? url_parser_1.parseUrl, - utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, - utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 52303c3b..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,169 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/smithy-client/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/smithy-client/dist-cjs/index.js deleted file mode 100644 index 9f589873..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/smithy-client/dist-cjs/index.js +++ /dev/null @@ -1,589 +0,0 @@ -'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]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js deleted file mode 100644 index b06a7b87..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js +++ /dev/null @@ -1,16 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/index.js deleted file mode 100644 index c095e288..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/index.js +++ /dev/null @@ -1,19 +0,0 @@ -'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]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/toBase64.js deleted file mode 100644 index 0590ce3f..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/dist-cjs/toBase64.js +++ /dev/null @@ -1,19 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js deleted file mode 100644 index b577c9ca..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js +++ /dev/null @@ -1,20 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js deleted file mode 100644 index 3238bb77..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-cognito-identity/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || - Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; - -exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/auth/httpAuthSchemeProvider.js b/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/auth/httpAuthSchemeProvider.js deleted file mode 100644 index 2c256eea..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/auth/httpAuthSchemeProvider.js +++ /dev/null @@ -1,68 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.resolveHttpAuthSchemeConfig = exports.defaultSSOHttpAuthSchemeProvider = exports.defaultSSOHttpAuthSchemeParametersProvider = void 0; -const core_1 = require("@aws-sdk/core"); -const util_middleware_1 = require("@smithy/util-middleware"); -const defaultSSOHttpAuthSchemeParametersProvider = 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.defaultSSOHttpAuthSchemeParametersProvider = defaultSSOHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "awsssoportal", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth", - }; -} -const defaultSSOHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "GetRoleCredentials": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - case "ListAccountRoles": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - case "ListAccounts": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - case "Logout": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); - } - } - return options; -}; -exports.defaultSSOHttpAuthSchemeProvider = defaultSSOHttpAuthSchemeProvider; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); - return Object.assign(config_0, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), - }); -}; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/endpointResolver.js b/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/endpointResolver.js deleted file mode 100644 index 7258a356..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/endpointResolver.js +++ /dev/null @@ -1,18 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/ruleset.js b/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/ruleset.js deleted file mode 100644 index 28d8f332..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/endpoint/ruleset.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ruleSet = void 0; -const u = "required", v = "fn", w = "argv", x = "ref"; -const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = "getAttr", i = { [u]: false, "type": "string" }, j = { [u]: true, "default": false, "type": "boolean" }, k = { [x]: "Endpoint" }, l = { [v]: c, [w]: [{ [x]: "UseFIPS" }, true] }, m = { [v]: c, [w]: [{ [x]: "UseDualStack" }, true] }, n = {}, o = { [v]: h, [w]: [{ [x]: g }, "supportsFIPS"] }, p = { [x]: g }, q = { [v]: c, [w]: [true, { [v]: h, [w]: [p, "supportsDualStack"] }] }, r = [l], s = [m], t = [{ [x]: "Region" }]; -const _data = { version: "1.0", parameters: { Region: i, UseDualStack: j, UseFIPS: j, Endpoint: i }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: r, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: s, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e }], type: f }, { conditions: [{ [v]: b, [w]: t }], rules: [{ conditions: [{ [v]: "aws.partition", [w]: t, assign: g }], rules: [{ conditions: [l, m], rules: [{ conditions: [{ [v]: c, [w]: [a, o] }, q], rules: [{ endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: r, rules: [{ conditions: [{ [v]: c, [w]: [o, a] }], rules: [{ conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h, [w]: [p, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://portal.sso.{Region}.amazonaws.com", properties: n, headers: n }, type: e }, { endpoint: { url: "https://portal.sso-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: s, rules: [{ conditions: [q], rules: [{ endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { endpoint: { url: "https://portal.sso.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; -exports.ruleSet = _data; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/index.js deleted file mode 100644 index e03d1267..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/index.js +++ /dev/null @@ -1,514 +0,0 @@ -'use strict'; - -var middlewareHostHeader = require('@aws-sdk/middleware-host-header'); -var middlewareLogger = require('@aws-sdk/middleware-logger'); -var middlewareRecursionDetection = require('@aws-sdk/middleware-recursion-detection'); -var middlewareUserAgent = require('@aws-sdk/middleware-user-agent'); -var configResolver = require('@smithy/config-resolver'); -var core = require('@smithy/core'); -var schema = require('@smithy/core/schema'); -var middlewareContentLength = require('@smithy/middleware-content-length'); -var middlewareEndpoint = require('@smithy/middleware-endpoint'); -var middlewareRetry = require('@smithy/middleware-retry'); -var smithyClient = require('@smithy/smithy-client'); -var httpAuthSchemeProvider = require('./auth/httpAuthSchemeProvider'); -var runtimeConfig = require('./runtimeConfig'); -var regionConfigResolver = require('@aws-sdk/region-config-resolver'); -var protocolHttp = require('@smithy/protocol-http'); - -const resolveClientEndpointParameters = (options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - defaultSigningName: "awsssoportal", - }); -}; -const commonParams = { - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, -}; - -const getHttpAuthExtensionConfiguration = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } - else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - }, - }; -}; -const resolveHttpAuthRuntimeConfig = (config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials(), - }; -}; - -const resolveRuntimeExtensions = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig), smithyClient.getDefaultExtensionConfiguration(runtimeConfig), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); -}; - -class SSOClient extends smithyClient.Client { - config; - constructor(...[configuration]) { - const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters(_config_0); - const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1); - const _config_3 = middlewareRetry.resolveRetryConfig(_config_2); - const _config_4 = configResolver.resolveRegionConfig(_config_3); - const _config_5 = middlewareHostHeader.resolveHostHeaderConfig(_config_4); - const _config_6 = middlewareEndpoint.resolveEndpointConfig(_config_5); - const _config_7 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_6); - const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use(schema.getSchemaSerdePlugin(this.config)); - this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config)); - this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config)); - this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config)); - this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config)); - this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config)); - this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config)); - this.middlewareStack.use(core.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { - httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultSSOHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config) => new core.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials, - }), - })); - this.middlewareStack.use(core.getHttpSigningPlugin(this.config)); - } - destroy() { - super.destroy(); - } -} - -let SSOServiceException$1 = class SSOServiceException extends smithyClient.ServiceException { - constructor(options) { - super(options); - Object.setPrototypeOf(this, SSOServiceException.prototype); - } -}; - -let InvalidRequestException$1 = class InvalidRequestException extends SSOServiceException$1 { - name = "InvalidRequestException"; - $fault = "client"; - constructor(opts) { - super({ - name: "InvalidRequestException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, InvalidRequestException.prototype); - } -}; -let ResourceNotFoundException$1 = class ResourceNotFoundException extends SSOServiceException$1 { - name = "ResourceNotFoundException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ResourceNotFoundException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ResourceNotFoundException.prototype); - } -}; -let TooManyRequestsException$1 = class TooManyRequestsException extends SSOServiceException$1 { - name = "TooManyRequestsException"; - $fault = "client"; - constructor(opts) { - super({ - name: "TooManyRequestsException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, TooManyRequestsException.prototype); - } -}; -let UnauthorizedException$1 = class UnauthorizedException extends SSOServiceException$1 { - name = "UnauthorizedException"; - $fault = "client"; - constructor(opts) { - super({ - name: "UnauthorizedException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, UnauthorizedException.prototype); - } -}; - -const _AI = "AccountInfo"; -const _ALT = "AccountListType"; -const _ATT = "AccessTokenType"; -const _GRC = "GetRoleCredentials"; -const _GRCR = "GetRoleCredentialsRequest"; -const _GRCRe = "GetRoleCredentialsResponse"; -const _IRE = "InvalidRequestException"; -const _L = "Logout"; -const _LA = "ListAccounts"; -const _LAR = "ListAccountsRequest"; -const _LARR = "ListAccountRolesRequest"; -const _LARRi = "ListAccountRolesResponse"; -const _LARi = "ListAccountsResponse"; -const _LARis = "ListAccountRoles"; -const _LR = "LogoutRequest"; -const _RC = "RoleCredentials"; -const _RI = "RoleInfo"; -const _RLT = "RoleListType"; -const _RNFE = "ResourceNotFoundException"; -const _SAKT = "SecretAccessKeyType"; -const _STT = "SessionTokenType"; -const _TMRE = "TooManyRequestsException"; -const _UE = "UnauthorizedException"; -const _aI = "accountId"; -const _aKI = "accessKeyId"; -const _aL = "accountList"; -const _aN = "accountName"; -const _aT = "accessToken"; -const _ai = "account_id"; -const _c = "client"; -const _e = "error"; -const _eA = "emailAddress"; -const _ex = "expiration"; -const _h = "http"; -const _hE = "httpError"; -const _hH = "httpHeader"; -const _hQ = "httpQuery"; -const _m = "message"; -const _mR = "maxResults"; -const _mr = "max_result"; -const _nT = "nextToken"; -const _nt = "next_token"; -const _rC = "roleCredentials"; -const _rL = "roleList"; -const _rN = "roleName"; -const _rn = "role_name"; -const _s = "smithy.ts.sdk.synthetic.com.amazonaws.sso"; -const _sAK = "secretAccessKey"; -const _sT = "sessionToken"; -const _xasbt = "x-amz-sso_bearer_token"; -const n0 = "com.amazonaws.sso"; -var AccessTokenType = [0, n0, _ATT, 8, 0]; -var SecretAccessKeyType = [0, n0, _SAKT, 8, 0]; -var SessionTokenType = [0, n0, _STT, 8, 0]; -var AccountInfo = [3, n0, _AI, 0, [_aI, _aN, _eA], [0, 0, 0]]; -var GetRoleCredentialsRequest = [ - 3, - n0, - _GRCR, - 0, - [_rN, _aI, _aT], - [ - [ - 0, - { - [_hQ]: _rn, - }, - ], - [ - 0, - { - [_hQ]: _ai, - }, - ], - [ - () => AccessTokenType, - { - [_hH]: _xasbt, - }, - ], - ], -]; -var GetRoleCredentialsResponse = [3, n0, _GRCRe, 0, [_rC], [[() => RoleCredentials, 0]]]; -var InvalidRequestException = [ - -3, - n0, - _IRE, - { - [_e]: _c, - [_hE]: 400, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(InvalidRequestException, InvalidRequestException$1); -var ListAccountRolesRequest = [ - 3, - n0, - _LARR, - 0, - [_nT, _mR, _aT, _aI], - [ - [ - 0, - { - [_hQ]: _nt, - }, - ], - [ - 1, - { - [_hQ]: _mr, - }, - ], - [ - () => AccessTokenType, - { - [_hH]: _xasbt, - }, - ], - [ - 0, - { - [_hQ]: _ai, - }, - ], - ], -]; -var ListAccountRolesResponse = [3, n0, _LARRi, 0, [_nT, _rL], [0, () => RoleListType]]; -var ListAccountsRequest = [ - 3, - n0, - _LAR, - 0, - [_nT, _mR, _aT], - [ - [ - 0, - { - [_hQ]: _nt, - }, - ], - [ - 1, - { - [_hQ]: _mr, - }, - ], - [ - () => AccessTokenType, - { - [_hH]: _xasbt, - }, - ], - ], -]; -var ListAccountsResponse = [3, n0, _LARi, 0, [_nT, _aL], [0, () => AccountListType]]; -var LogoutRequest = [ - 3, - n0, - _LR, - 0, - [_aT], - [ - [ - () => AccessTokenType, - { - [_hH]: _xasbt, - }, - ], - ], -]; -var ResourceNotFoundException = [ - -3, - n0, - _RNFE, - { - [_e]: _c, - [_hE]: 404, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ResourceNotFoundException, ResourceNotFoundException$1); -var RoleCredentials = [ - 3, - n0, - _RC, - 0, - [_aKI, _sAK, _sT, _ex], - [0, [() => SecretAccessKeyType, 0], [() => SessionTokenType, 0], 1], -]; -var RoleInfo = [3, n0, _RI, 0, [_rN, _aI], [0, 0]]; -var TooManyRequestsException = [ - -3, - n0, - _TMRE, - { - [_e]: _c, - [_hE]: 429, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(TooManyRequestsException, TooManyRequestsException$1); -var UnauthorizedException = [ - -3, - n0, - _UE, - { - [_e]: _c, - [_hE]: 401, - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(UnauthorizedException, UnauthorizedException$1); -var __Unit = "unit"; -var SSOServiceException = [-3, _s, "SSOServiceException", 0, [], []]; -schema.TypeRegistry.for(_s).registerError(SSOServiceException, SSOServiceException$1); -var AccountListType = [1, n0, _ALT, 0, () => AccountInfo]; -var RoleListType = [1, n0, _RLT, 0, () => RoleInfo]; -var GetRoleCredentials = [ - 9, - n0, - _GRC, - { - [_h]: ["GET", "/federation/credentials", 200], - }, - () => GetRoleCredentialsRequest, - () => GetRoleCredentialsResponse, -]; -var ListAccountRoles = [ - 9, - n0, - _LARis, - { - [_h]: ["GET", "/assignment/roles", 200], - }, - () => ListAccountRolesRequest, - () => ListAccountRolesResponse, -]; -var ListAccounts = [ - 9, - n0, - _LA, - { - [_h]: ["GET", "/assignment/accounts", 200], - }, - () => ListAccountsRequest, - () => ListAccountsResponse, -]; -var Logout = [ - 9, - n0, - _L, - { - [_h]: ["POST", "/logout", 200], - }, - () => LogoutRequest, - () => __Unit, -]; - -class GetRoleCredentialsCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("SWBPortalService", "GetRoleCredentials", {}) - .n("SSOClient", "GetRoleCredentialsCommand") - .sc(GetRoleCredentials) - .build() { -} - -class ListAccountRolesCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("SWBPortalService", "ListAccountRoles", {}) - .n("SSOClient", "ListAccountRolesCommand") - .sc(ListAccountRoles) - .build() { -} - -class ListAccountsCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("SWBPortalService", "ListAccounts", {}) - .n("SSOClient", "ListAccountsCommand") - .sc(ListAccounts) - .build() { -} - -class LogoutCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("SWBPortalService", "Logout", {}) - .n("SSOClient", "LogoutCommand") - .sc(Logout) - .build() { -} - -const commands = { - GetRoleCredentialsCommand, - ListAccountRolesCommand, - ListAccountsCommand, - LogoutCommand, -}; -class SSO extends SSOClient { -} -smithyClient.createAggregatedClient(commands, SSO); - -const paginateListAccountRoles = core.createPaginator(SSOClient, ListAccountRolesCommand, "nextToken", "nextToken", "maxResults"); - -const paginateListAccounts = core.createPaginator(SSOClient, ListAccountsCommand, "nextToken", "nextToken", "maxResults"); - -Object.defineProperty(exports, "$Command", { - enumerable: true, - get: function () { return smithyClient.Command; } -}); -Object.defineProperty(exports, "__Client", { - enumerable: true, - get: function () { return smithyClient.Client; } -}); -exports.GetRoleCredentialsCommand = GetRoleCredentialsCommand; -exports.InvalidRequestException = InvalidRequestException$1; -exports.ListAccountRolesCommand = ListAccountRolesCommand; -exports.ListAccountsCommand = ListAccountsCommand; -exports.LogoutCommand = LogoutCommand; -exports.ResourceNotFoundException = ResourceNotFoundException$1; -exports.SSO = SSO; -exports.SSOClient = SSOClient; -exports.SSOServiceException = SSOServiceException$1; -exports.TooManyRequestsException = TooManyRequestsException$1; -exports.UnauthorizedException = UnauthorizedException$1; -exports.paginateListAccountRoles = paginateListAccountRoles; -exports.paginateListAccounts = paginateListAccounts; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.js b/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.js deleted file mode 100644 index ecc8dd2f..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.js +++ /dev/null @@ -1,54 +0,0 @@ -"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 util_user_agent_node_1 = require("@aws-sdk/util-user-agent-node"); -const config_resolver_1 = require("@smithy/config-resolver"); -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, - }; - 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, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? - (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), - 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.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), - 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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.shared.js b/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.shared.js deleted file mode 100644 index 4f73148f..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sso/dist-cjs/runtimeConfig.shared.js +++ /dev/null @@ -1,42 +0,0 @@ -"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: "2019-06-10", - 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.defaultSSOHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - logger: config?.logger ?? new smithy_client_1.NoOpLogger(), - protocol: config?.protocol ?? new protocols_1.AwsRestJsonProtocol({ defaultNamespace: "com.amazonaws.sso" }), - serviceId: config?.serviceId ?? "SSO", - urlParser: config?.urlParser ?? url_parser_1.parseUrl, - utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, - utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 52303c3b..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,169 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/smithy-client/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/smithy-client/dist-cjs/index.js deleted file mode 100644 index 9f589873..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/smithy-client/dist-cjs/index.js +++ /dev/null @@ -1,589 +0,0 @@ -'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]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js deleted file mode 100644 index b06a7b87..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js +++ /dev/null @@ -1,16 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/index.js deleted file mode 100644 index c095e288..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/index.js +++ /dev/null @@ -1,19 +0,0 @@ -'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]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/toBase64.js deleted file mode 100644 index 0590ce3f..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/dist-cjs/toBase64.js +++ /dev/null @@ -1,19 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js deleted file mode 100644 index b577c9ca..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js +++ /dev/null @@ -1,20 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js deleted file mode 100644 index 3238bb77..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sso/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || - Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; - -exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/STSClient.js b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/STSClient.js deleted file mode 100644 index 879af8b9..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/STSClient.js +++ /dev/null @@ -1,54 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.STSClient = exports.__Client = void 0; -const middleware_host_header_1 = require("@aws-sdk/middleware-host-header"); -const middleware_logger_1 = require("@aws-sdk/middleware-logger"); -const middleware_recursion_detection_1 = require("@aws-sdk/middleware-recursion-detection"); -const middleware_user_agent_1 = require("@aws-sdk/middleware-user-agent"); -const config_resolver_1 = require("@smithy/config-resolver"); -const core_1 = require("@smithy/core"); -const schema_1 = require("@smithy/core/schema"); -const middleware_content_length_1 = require("@smithy/middleware-content-length"); -const middleware_endpoint_1 = require("@smithy/middleware-endpoint"); -const middleware_retry_1 = require("@smithy/middleware-retry"); -const smithy_client_1 = require("@smithy/smithy-client"); -Object.defineProperty(exports, "__Client", { enumerable: true, get: function () { return smithy_client_1.Client; } }); -const httpAuthSchemeProvider_1 = require("./auth/httpAuthSchemeProvider"); -const EndpointParameters_1 = require("./endpoint/EndpointParameters"); -const runtimeConfig_1 = require("./runtimeConfig"); -const runtimeExtensions_1 = require("./runtimeExtensions"); -class STSClient extends smithy_client_1.Client { - config; - constructor(...[configuration]) { - const _config_0 = (0, runtimeConfig_1.getRuntimeConfig)(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = (0, EndpointParameters_1.resolveClientEndpointParameters)(_config_0); - const _config_2 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, middleware_retry_1.resolveRetryConfig)(_config_2); - const _config_4 = (0, config_resolver_1.resolveRegionConfig)(_config_3); - const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_5); - const _config_7 = (0, httpAuthSchemeProvider_1.resolveHttpAuthSchemeConfig)(_config_6); - const _config_8 = (0, runtimeExtensions_1.resolveRuntimeExtensions)(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use((0, schema_1.getSchemaSerdePlugin)(this.config)); - this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config)); - this.middlewareStack.use((0, middleware_retry_1.getRetryPlugin)(this.config)); - this.middlewareStack.use((0, middleware_content_length_1.getContentLengthPlugin)(this.config)); - this.middlewareStack.use((0, middleware_host_header_1.getHostHeaderPlugin)(this.config)); - this.middlewareStack.use((0, middleware_logger_1.getLoggerPlugin)(this.config)); - this.middlewareStack.use((0, middleware_recursion_detection_1.getRecursionDetectionPlugin)(this.config)); - this.middlewareStack.use((0, core_1.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { - httpAuthSchemeParametersProvider: httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config) => new core_1.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials, - }), - })); - this.middlewareStack.use((0, core_1.getHttpSigningPlugin)(this.config)); - } - destroy() { - super.destroy(); - } -} -exports.STSClient = STSClient; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/auth/httpAuthExtensionConfiguration.js b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/auth/httpAuthExtensionConfiguration.js deleted file mode 100644 index 239095e0..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/auth/httpAuthExtensionConfiguration.js +++ /dev/null @@ -1,43 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.resolveHttpAuthRuntimeConfig = exports.getHttpAuthExtensionConfiguration = void 0; -const getHttpAuthExtensionConfiguration = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } - else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - }, - }; -}; -exports.getHttpAuthExtensionConfiguration = getHttpAuthExtensionConfiguration; -const resolveHttpAuthRuntimeConfig = (config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials(), - }; -}; -exports.resolveHttpAuthRuntimeConfig = resolveHttpAuthRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/auth/httpAuthSchemeProvider.js b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/auth/httpAuthSchemeProvider.js deleted file mode 100644 index d5cb1131..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/auth/httpAuthSchemeProvider.js +++ /dev/null @@ -1,66 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.resolveHttpAuthSchemeConfig = exports.resolveStsAuthConfig = exports.defaultSTSHttpAuthSchemeProvider = exports.defaultSTSHttpAuthSchemeParametersProvider = void 0; -const core_1 = require("@aws-sdk/core"); -const util_middleware_1 = require("@smithy/util-middleware"); -const STSClient_1 = require("../STSClient"); -const defaultSTSHttpAuthSchemeParametersProvider = 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.defaultSTSHttpAuthSchemeParametersProvider = defaultSTSHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "sts", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth", - }; -} -const defaultSTSHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "AssumeRoleWithSAML": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - case "AssumeRoleWithWebIdentity": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); - } - } - return options; -}; -exports.defaultSTSHttpAuthSchemeProvider = defaultSTSHttpAuthSchemeProvider; -const resolveStsAuthConfig = (input) => Object.assign(input, { - stsClientCtor: STSClient_1.STSClient, -}); -exports.resolveStsAuthConfig = resolveStsAuthConfig; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, exports.resolveStsAuthConfig)(config); - const config_1 = (0, core_1.resolveAwsSdkSigV4Config)(config_0); - return Object.assign(config_1, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), - }); -}; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/EndpointParameters.js b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/EndpointParameters.js deleted file mode 100644 index 3aec6a5e..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/EndpointParameters.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.commonParams = exports.resolveClientEndpointParameters = void 0; -const resolveClientEndpointParameters = (options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - useGlobalEndpoint: options.useGlobalEndpoint ?? false, - defaultSigningName: "sts", - }); -}; -exports.resolveClientEndpointParameters = resolveClientEndpointParameters; -exports.commonParams = { - UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, -}; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/endpointResolver.js b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/endpointResolver.js deleted file mode 100644 index 6bfb6e90..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/endpointResolver.js +++ /dev/null @@ -1,18 +0,0 @@ -"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", "UseGlobalEndpoint"], -}); -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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/ruleset.js b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/ruleset.js deleted file mode 100644 index a5e5cf2a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/endpoint/ruleset.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ruleSet = void 0; -const F = "required", G = "type", H = "fn", I = "argv", J = "ref"; -const a = false, b = true, c = "booleanEquals", d = "stringEquals", e = "sigv4", f = "sts", g = "us-east-1", h = "endpoint", i = "https://sts.{Region}.{PartitionResult#dnsSuffix}", j = "tree", k = "error", l = "getAttr", m = { [F]: false, [G]: "string" }, n = { [F]: true, "default": false, [G]: "boolean" }, o = { [J]: "Endpoint" }, p = { [H]: "isSet", [I]: [{ [J]: "Region" }] }, q = { [J]: "Region" }, r = { [H]: "aws.partition", [I]: [q], "assign": "PartitionResult" }, s = { [J]: "UseFIPS" }, t = { [J]: "UseDualStack" }, u = { "url": "https://sts.amazonaws.com", "properties": { "authSchemes": [{ "name": e, "signingName": f, "signingRegion": g }] }, "headers": {} }, v = {}, w = { "conditions": [{ [H]: d, [I]: [q, "aws-global"] }], [h]: u, [G]: h }, x = { [H]: c, [I]: [s, true] }, y = { [H]: c, [I]: [t, true] }, z = { [H]: l, [I]: [{ [J]: "PartitionResult" }, "supportsFIPS"] }, A = { [J]: "PartitionResult" }, B = { [H]: c, [I]: [true, { [H]: l, [I]: [A, "supportsDualStack"] }] }, C = [{ [H]: "isSet", [I]: [o] }], D = [x], E = [y]; -const _data = { version: "1.0", parameters: { Region: m, UseDualStack: n, UseFIPS: n, Endpoint: m, UseGlobalEndpoint: n }, rules: [{ conditions: [{ [H]: c, [I]: [{ [J]: "UseGlobalEndpoint" }, b] }, { [H]: "not", [I]: C }, p, r, { [H]: c, [I]: [s, a] }, { [H]: c, [I]: [t, a] }], rules: [{ conditions: [{ [H]: d, [I]: [q, "ap-northeast-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-south-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-southeast-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-southeast-2"] }], endpoint: u, [G]: h }, w, { conditions: [{ [H]: d, [I]: [q, "ca-central-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-central-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-north-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-2"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-3"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "sa-east-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, g] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-east-2"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-west-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-west-2"] }], endpoint: u, [G]: h }, { endpoint: { url: i, properties: { authSchemes: [{ name: e, signingName: f, signingRegion: "{Region}" }] }, headers: v }, [G]: h }], [G]: j }, { conditions: C, rules: [{ conditions: D, error: "Invalid Configuration: FIPS and custom endpoint are not supported", [G]: k }, { conditions: E, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", [G]: k }, { endpoint: { url: o, properties: v, headers: v }, [G]: h }], [G]: j }, { conditions: [p], rules: [{ conditions: [r], rules: [{ conditions: [x, y], rules: [{ conditions: [{ [H]: c, [I]: [b, z] }, B], rules: [{ endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", [G]: k }], [G]: j }, { conditions: D, rules: [{ conditions: [{ [H]: c, [I]: [z, b] }], rules: [{ conditions: [{ [H]: d, [I]: [{ [H]: l, [I]: [A, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://sts.{Region}.amazonaws.com", properties: v, headers: v }, [G]: h }, { endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "FIPS is enabled but this partition does not support FIPS", [G]: k }], [G]: j }, { conditions: E, rules: [{ conditions: [B], rules: [{ endpoint: { url: "https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "DualStack is enabled but this partition does not support DualStack", [G]: k }], [G]: j }, w, { endpoint: { url: i, properties: v, headers: v }, [G]: h }], [G]: j }], [G]: j }, { error: "Invalid Configuration: Missing Region", [G]: k }] }; -exports.ruleSet = _data; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/index.js deleted file mode 100644 index 62b019bc..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/index.js +++ /dev/null @@ -1,947 +0,0 @@ -'use strict'; - -var STSClient = require('./STSClient'); -var smithyClient = require('@smithy/smithy-client'); -var middlewareEndpoint = require('@smithy/middleware-endpoint'); -var EndpointParameters = require('./endpoint/EndpointParameters'); -var schema = require('@smithy/core/schema'); -var client = require('@aws-sdk/core/client'); -var regionConfigResolver = require('@aws-sdk/region-config-resolver'); - -let STSServiceException$1 = class STSServiceException extends smithyClient.ServiceException { - constructor(options) { - super(options); - Object.setPrototypeOf(this, STSServiceException.prototype); - } -}; - -let ExpiredTokenException$1 = class ExpiredTokenException extends STSServiceException$1 { - name = "ExpiredTokenException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ExpiredTokenException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ExpiredTokenException.prototype); - } -}; -let MalformedPolicyDocumentException$1 = class MalformedPolicyDocumentException extends STSServiceException$1 { - name = "MalformedPolicyDocumentException"; - $fault = "client"; - constructor(opts) { - super({ - name: "MalformedPolicyDocumentException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, MalformedPolicyDocumentException.prototype); - } -}; -let PackedPolicyTooLargeException$1 = class PackedPolicyTooLargeException extends STSServiceException$1 { - name = "PackedPolicyTooLargeException"; - $fault = "client"; - constructor(opts) { - super({ - name: "PackedPolicyTooLargeException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, PackedPolicyTooLargeException.prototype); - } -}; -let RegionDisabledException$1 = class RegionDisabledException extends STSServiceException$1 { - name = "RegionDisabledException"; - $fault = "client"; - constructor(opts) { - super({ - name: "RegionDisabledException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, RegionDisabledException.prototype); - } -}; -let IDPRejectedClaimException$1 = class IDPRejectedClaimException extends STSServiceException$1 { - name = "IDPRejectedClaimException"; - $fault = "client"; - constructor(opts) { - super({ - name: "IDPRejectedClaimException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, IDPRejectedClaimException.prototype); - } -}; -let InvalidIdentityTokenException$1 = class InvalidIdentityTokenException extends STSServiceException$1 { - name = "InvalidIdentityTokenException"; - $fault = "client"; - constructor(opts) { - super({ - name: "InvalidIdentityTokenException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, InvalidIdentityTokenException.prototype); - } -}; -let IDPCommunicationErrorException$1 = class IDPCommunicationErrorException extends STSServiceException$1 { - name = "IDPCommunicationErrorException"; - $fault = "client"; - constructor(opts) { - super({ - name: "IDPCommunicationErrorException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, IDPCommunicationErrorException.prototype); - } -}; -let InvalidAuthorizationMessageException$1 = class InvalidAuthorizationMessageException extends STSServiceException$1 { - name = "InvalidAuthorizationMessageException"; - $fault = "client"; - constructor(opts) { - super({ - name: "InvalidAuthorizationMessageException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, InvalidAuthorizationMessageException.prototype); - } -}; -let ExpiredTradeInTokenException$1 = class ExpiredTradeInTokenException extends STSServiceException$1 { - name = "ExpiredTradeInTokenException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ExpiredTradeInTokenException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ExpiredTradeInTokenException.prototype); - } -}; -let JWTPayloadSizeExceededException$1 = class JWTPayloadSizeExceededException extends STSServiceException$1 { - name = "JWTPayloadSizeExceededException"; - $fault = "client"; - constructor(opts) { - super({ - name: "JWTPayloadSizeExceededException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, JWTPayloadSizeExceededException.prototype); - } -}; -let OutboundWebIdentityFederationDisabledException$1 = class OutboundWebIdentityFederationDisabledException extends STSServiceException$1 { - name = "OutboundWebIdentityFederationDisabledException"; - $fault = "client"; - constructor(opts) { - super({ - name: "OutboundWebIdentityFederationDisabledException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, OutboundWebIdentityFederationDisabledException.prototype); - } -}; -let SessionDurationEscalationException$1 = class SessionDurationEscalationException extends STSServiceException$1 { - name = "SessionDurationEscalationException"; - $fault = "client"; - constructor(opts) { - super({ - name: "SessionDurationEscalationException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, SessionDurationEscalationException.prototype); - } -}; - -const _A = "Arn"; -const _AKI = "AccessKeyId"; -const _AP = "AssumedPrincipal"; -const _AR = "AssumeRole"; -const _ARI = "AssumedRoleId"; -const _ARR = "AssumeRoleRequest"; -const _ARRs = "AssumeRoleResponse"; -const _ARRss = "AssumeRootRequest"; -const _ARRssu = "AssumeRootResponse"; -const _ARU = "AssumedRoleUser"; -const _ARWSAML = "AssumeRoleWithSAML"; -const _ARWSAMLR = "AssumeRoleWithSAMLRequest"; -const _ARWSAMLRs = "AssumeRoleWithSAMLResponse"; -const _ARWWI = "AssumeRoleWithWebIdentity"; -const _ARWWIR = "AssumeRoleWithWebIdentityRequest"; -const _ARWWIRs = "AssumeRoleWithWebIdentityResponse"; -const _ARs = "AssumeRoot"; -const _Ac = "Account"; -const _Au = "Audience"; -const _C = "Credentials"; -const _CA = "ContextAssertion"; -const _DAM = "DecodeAuthorizationMessage"; -const _DAMR = "DecodeAuthorizationMessageRequest"; -const _DAMRe = "DecodeAuthorizationMessageResponse"; -const _DM = "DecodedMessage"; -const _DS = "DurationSeconds"; -const _E = "Expiration"; -const _EI = "ExternalId"; -const _EM = "EncodedMessage"; -const _ETE = "ExpiredTokenException"; -const _ETITE = "ExpiredTradeInTokenException"; -const _FU = "FederatedUser"; -const _FUI = "FederatedUserId"; -const _GAKI = "GetAccessKeyInfo"; -const _GAKIR = "GetAccessKeyInfoRequest"; -const _GAKIRe = "GetAccessKeyInfoResponse"; -const _GCI = "GetCallerIdentity"; -const _GCIR = "GetCallerIdentityRequest"; -const _GCIRe = "GetCallerIdentityResponse"; -const _GDAT = "GetDelegatedAccessToken"; -const _GDATR = "GetDelegatedAccessTokenRequest"; -const _GDATRe = "GetDelegatedAccessTokenResponse"; -const _GFT = "GetFederationToken"; -const _GFTR = "GetFederationTokenRequest"; -const _GFTRe = "GetFederationTokenResponse"; -const _GST = "GetSessionToken"; -const _GSTR = "GetSessionTokenRequest"; -const _GSTRe = "GetSessionTokenResponse"; -const _GWIT = "GetWebIdentityToken"; -const _GWITR = "GetWebIdentityTokenRequest"; -const _GWITRe = "GetWebIdentityTokenResponse"; -const _I = "Issuer"; -const _IAME = "InvalidAuthorizationMessageException"; -const _IDPCEE = "IDPCommunicationErrorException"; -const _IDPRCE = "IDPRejectedClaimException"; -const _IITE = "InvalidIdentityTokenException"; -const _JWTPSEE = "JWTPayloadSizeExceededException"; -const _K = "Key"; -const _MPDE = "MalformedPolicyDocumentException"; -const _N = "Name"; -const _NQ = "NameQualifier"; -const _OWIFDE = "OutboundWebIdentityFederationDisabledException"; -const _P = "Policy"; -const _PA = "PolicyArns"; -const _PAr = "PrincipalArn"; -const _PAro = "ProviderArn"; -const _PC = "ProvidedContexts"; -const _PCLT = "ProvidedContextsListType"; -const _PCr = "ProvidedContext"; -const _PDT = "PolicyDescriptorType"; -const _PI = "ProviderId"; -const _PPS = "PackedPolicySize"; -const _PPTLE = "PackedPolicyTooLargeException"; -const _Pr = "Provider"; -const _RA = "RoleArn"; -const _RDE = "RegionDisabledException"; -const _RSN = "RoleSessionName"; -const _S = "Subject"; -const _SA = "SigningAlgorithm"; -const _SAK = "SecretAccessKey"; -const _SAMLA = "SAMLAssertion"; -const _SAMLAT = "SAMLAssertionType"; -const _SDEE = "SessionDurationEscalationException"; -const _SFWIT = "SubjectFromWebIdentityToken"; -const _SI = "SourceIdentity"; -const _SN = "SerialNumber"; -const _ST = "SubjectType"; -const _STe = "SessionToken"; -const _T = "Tags"; -const _TC = "TokenCode"; -const _TIT = "TradeInToken"; -const _TP = "TargetPrincipal"; -const _TPA = "TaskPolicyArn"; -const _TTK = "TransitiveTagKeys"; -const _Ta = "Tag"; -const _UI = "UserId"; -const _V = "Value"; -const _WIT = "WebIdentityToken"; -const _a = "arn"; -const _aKST = "accessKeySecretType"; -const _aQE = "awsQueryError"; -const _c = "client"; -const _cTT = "clientTokenType"; -const _e = "error"; -const _hE = "httpError"; -const _m = "message"; -const _pDLT = "policyDescriptorListType"; -const _s = "smithy.ts.sdk.synthetic.com.amazonaws.sts"; -const _tITT = "tradeInTokenType"; -const _tLT = "tagListType"; -const _wITT = "webIdentityTokenType"; -const n0 = "com.amazonaws.sts"; -var accessKeySecretType = [0, n0, _aKST, 8, 0]; -var clientTokenType = [0, n0, _cTT, 8, 0]; -var SAMLAssertionType = [0, n0, _SAMLAT, 8, 0]; -var tradeInTokenType = [0, n0, _tITT, 8, 0]; -var webIdentityTokenType = [0, n0, _wITT, 8, 0]; -var AssumedRoleUser = [3, n0, _ARU, 0, [_ARI, _A], [0, 0]]; -var AssumeRoleRequest = [ - 3, - n0, - _ARR, - 0, - [_RA, _RSN, _PA, _P, _DS, _T, _TTK, _EI, _SN, _TC, _SI, _PC], - [0, 0, () => policyDescriptorListType, 0, 1, () => tagListType, 64 | 0, 0, 0, 0, 0, () => ProvidedContextsListType], -]; -var AssumeRoleResponse = [ - 3, - n0, - _ARRs, - 0, - [_C, _ARU, _PPS, _SI], - [[() => Credentials, 0], () => AssumedRoleUser, 1, 0], -]; -var AssumeRoleWithSAMLRequest = [ - 3, - n0, - _ARWSAMLR, - 0, - [_RA, _PAr, _SAMLA, _PA, _P, _DS], - [0, 0, [() => SAMLAssertionType, 0], () => policyDescriptorListType, 0, 1], -]; -var AssumeRoleWithSAMLResponse = [ - 3, - n0, - _ARWSAMLRs, - 0, - [_C, _ARU, _PPS, _S, _ST, _I, _Au, _NQ, _SI], - [[() => Credentials, 0], () => AssumedRoleUser, 1, 0, 0, 0, 0, 0, 0], -]; -var AssumeRoleWithWebIdentityRequest = [ - 3, - n0, - _ARWWIR, - 0, - [_RA, _RSN, _WIT, _PI, _PA, _P, _DS], - [0, 0, [() => clientTokenType, 0], 0, () => policyDescriptorListType, 0, 1], -]; -var AssumeRoleWithWebIdentityResponse = [ - 3, - n0, - _ARWWIRs, - 0, - [_C, _SFWIT, _ARU, _PPS, _Pr, _Au, _SI], - [[() => Credentials, 0], 0, () => AssumedRoleUser, 1, 0, 0, 0], -]; -var AssumeRootRequest = [ - 3, - n0, - _ARRss, - 0, - [_TP, _TPA, _DS], - [0, () => PolicyDescriptorType, 1], -]; -var AssumeRootResponse = [3, n0, _ARRssu, 0, [_C, _SI], [[() => Credentials, 0], 0]]; -var Credentials = [ - 3, - n0, - _C, - 0, - [_AKI, _SAK, _STe, _E], - [0, [() => accessKeySecretType, 0], 0, 4], -]; -var DecodeAuthorizationMessageRequest = [3, n0, _DAMR, 0, [_EM], [0]]; -var DecodeAuthorizationMessageResponse = [3, n0, _DAMRe, 0, [_DM], [0]]; -var ExpiredTokenException = [ - -3, - n0, - _ETE, - { - [_e]: _c, - [_hE]: 400, - [_aQE]: [`ExpiredTokenException`, 400], - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ExpiredTokenException, ExpiredTokenException$1); -var ExpiredTradeInTokenException = [ - -3, - n0, - _ETITE, - { - [_e]: _c, - [_hE]: 400, - [_aQE]: [`ExpiredTradeInTokenException`, 400], - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ExpiredTradeInTokenException, ExpiredTradeInTokenException$1); -var FederatedUser = [3, n0, _FU, 0, [_FUI, _A], [0, 0]]; -var GetAccessKeyInfoRequest = [3, n0, _GAKIR, 0, [_AKI], [0]]; -var GetAccessKeyInfoResponse = [3, n0, _GAKIRe, 0, [_Ac], [0]]; -var GetCallerIdentityRequest = [3, n0, _GCIR, 0, [], []]; -var GetCallerIdentityResponse = [3, n0, _GCIRe, 0, [_UI, _Ac, _A], [0, 0, 0]]; -var GetDelegatedAccessTokenRequest = [ - 3, - n0, - _GDATR, - 0, - [_TIT], - [[() => tradeInTokenType, 0]], -]; -var GetDelegatedAccessTokenResponse = [ - 3, - n0, - _GDATRe, - 0, - [_C, _PPS, _AP], - [[() => Credentials, 0], 1, 0], -]; -var GetFederationTokenRequest = [ - 3, - n0, - _GFTR, - 0, - [_N, _P, _PA, _DS, _T], - [0, 0, () => policyDescriptorListType, 1, () => tagListType], -]; -var GetFederationTokenResponse = [ - 3, - n0, - _GFTRe, - 0, - [_C, _FU, _PPS], - [[() => Credentials, 0], () => FederatedUser, 1], -]; -var GetSessionTokenRequest = [3, n0, _GSTR, 0, [_DS, _SN, _TC], [1, 0, 0]]; -var GetSessionTokenResponse = [3, n0, _GSTRe, 0, [_C], [[() => Credentials, 0]]]; -var GetWebIdentityTokenRequest = [ - 3, - n0, - _GWITR, - 0, - [_Au, _DS, _SA, _T], - [64 | 0, 1, 0, () => tagListType], -]; -var GetWebIdentityTokenResponse = [ - 3, - n0, - _GWITRe, - 0, - [_WIT, _E], - [[() => webIdentityTokenType, 0], 4], -]; -var IDPCommunicationErrorException = [ - -3, - n0, - _IDPCEE, - { - [_e]: _c, - [_hE]: 400, - [_aQE]: [`IDPCommunicationError`, 400], - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(IDPCommunicationErrorException, IDPCommunicationErrorException$1); -var IDPRejectedClaimException = [ - -3, - n0, - _IDPRCE, - { - [_e]: _c, - [_hE]: 403, - [_aQE]: [`IDPRejectedClaim`, 403], - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(IDPRejectedClaimException, IDPRejectedClaimException$1); -var InvalidAuthorizationMessageException = [ - -3, - n0, - _IAME, - { - [_e]: _c, - [_hE]: 400, - [_aQE]: [`InvalidAuthorizationMessageException`, 400], - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(InvalidAuthorizationMessageException, InvalidAuthorizationMessageException$1); -var InvalidIdentityTokenException = [ - -3, - n0, - _IITE, - { - [_e]: _c, - [_hE]: 400, - [_aQE]: [`InvalidIdentityToken`, 400], - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(InvalidIdentityTokenException, InvalidIdentityTokenException$1); -var JWTPayloadSizeExceededException = [ - -3, - n0, - _JWTPSEE, - { - [_e]: _c, - [_hE]: 400, - [_aQE]: [`JWTPayloadSizeExceededException`, 400], - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(JWTPayloadSizeExceededException, JWTPayloadSizeExceededException$1); -var MalformedPolicyDocumentException = [ - -3, - n0, - _MPDE, - { - [_e]: _c, - [_hE]: 400, - [_aQE]: [`MalformedPolicyDocument`, 400], - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(MalformedPolicyDocumentException, MalformedPolicyDocumentException$1); -var OutboundWebIdentityFederationDisabledException = [ - -3, - n0, - _OWIFDE, - { - [_e]: _c, - [_hE]: 403, - [_aQE]: [`OutboundWebIdentityFederationDisabledException`, 403], - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(OutboundWebIdentityFederationDisabledException, OutboundWebIdentityFederationDisabledException$1); -var PackedPolicyTooLargeException = [ - -3, - n0, - _PPTLE, - { - [_e]: _c, - [_hE]: 400, - [_aQE]: [`PackedPolicyTooLarge`, 400], - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(PackedPolicyTooLargeException, PackedPolicyTooLargeException$1); -var PolicyDescriptorType = [3, n0, _PDT, 0, [_a], [0]]; -var ProvidedContext = [3, n0, _PCr, 0, [_PAro, _CA], [0, 0]]; -var RegionDisabledException = [ - -3, - n0, - _RDE, - { - [_e]: _c, - [_hE]: 403, - [_aQE]: [`RegionDisabledException`, 403], - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(RegionDisabledException, RegionDisabledException$1); -var SessionDurationEscalationException = [ - -3, - n0, - _SDEE, - { - [_e]: _c, - [_hE]: 403, - [_aQE]: [`SessionDurationEscalationException`, 403], - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(SessionDurationEscalationException, SessionDurationEscalationException$1); -var Tag = [3, n0, _Ta, 0, [_K, _V], [0, 0]]; -var STSServiceException = [-3, _s, "STSServiceException", 0, [], []]; -schema.TypeRegistry.for(_s).registerError(STSServiceException, STSServiceException$1); -var policyDescriptorListType = [1, n0, _pDLT, 0, () => PolicyDescriptorType]; -var ProvidedContextsListType = [1, n0, _PCLT, 0, () => ProvidedContext]; -var tagListType = [1, n0, _tLT, 0, () => Tag]; -var AssumeRole = [9, n0, _AR, 0, () => AssumeRoleRequest, () => AssumeRoleResponse]; -var AssumeRoleWithSAML = [ - 9, - n0, - _ARWSAML, - 0, - () => AssumeRoleWithSAMLRequest, - () => AssumeRoleWithSAMLResponse, -]; -var AssumeRoleWithWebIdentity = [ - 9, - n0, - _ARWWI, - 0, - () => AssumeRoleWithWebIdentityRequest, - () => AssumeRoleWithWebIdentityResponse, -]; -var AssumeRoot = [9, n0, _ARs, 0, () => AssumeRootRequest, () => AssumeRootResponse]; -var DecodeAuthorizationMessage = [ - 9, - n0, - _DAM, - 0, - () => DecodeAuthorizationMessageRequest, - () => DecodeAuthorizationMessageResponse, -]; -var GetAccessKeyInfo = [ - 9, - n0, - _GAKI, - 0, - () => GetAccessKeyInfoRequest, - () => GetAccessKeyInfoResponse, -]; -var GetCallerIdentity = [ - 9, - n0, - _GCI, - 0, - () => GetCallerIdentityRequest, - () => GetCallerIdentityResponse, -]; -var GetDelegatedAccessToken = [ - 9, - n0, - _GDAT, - 0, - () => GetDelegatedAccessTokenRequest, - () => GetDelegatedAccessTokenResponse, -]; -var GetFederationToken = [ - 9, - n0, - _GFT, - 0, - () => GetFederationTokenRequest, - () => GetFederationTokenResponse, -]; -var GetSessionToken = [ - 9, - n0, - _GST, - 0, - () => GetSessionTokenRequest, - () => GetSessionTokenResponse, -]; -var GetWebIdentityToken = [ - 9, - n0, - _GWIT, - 0, - () => GetWebIdentityTokenRequest, - () => GetWebIdentityTokenResponse, -]; - -class AssumeRoleCommand extends smithyClient.Command - .classBuilder() - .ep(EndpointParameters.commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}) - .n("STSClient", "AssumeRoleCommand") - .sc(AssumeRole) - .build() { -} - -class AssumeRoleWithSAMLCommand extends smithyClient.Command - .classBuilder() - .ep(EndpointParameters.commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithSAML", {}) - .n("STSClient", "AssumeRoleWithSAMLCommand") - .sc(AssumeRoleWithSAML) - .build() { -} - -class AssumeRoleWithWebIdentityCommand extends smithyClient.Command - .classBuilder() - .ep(EndpointParameters.commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}) - .n("STSClient", "AssumeRoleWithWebIdentityCommand") - .sc(AssumeRoleWithWebIdentity) - .build() { -} - -class AssumeRootCommand extends smithyClient.Command - .classBuilder() - .ep(EndpointParameters.commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSSecurityTokenServiceV20110615", "AssumeRoot", {}) - .n("STSClient", "AssumeRootCommand") - .sc(AssumeRoot) - .build() { -} - -class DecodeAuthorizationMessageCommand extends smithyClient.Command - .classBuilder() - .ep(EndpointParameters.commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSSecurityTokenServiceV20110615", "DecodeAuthorizationMessage", {}) - .n("STSClient", "DecodeAuthorizationMessageCommand") - .sc(DecodeAuthorizationMessage) - .build() { -} - -class GetAccessKeyInfoCommand extends smithyClient.Command - .classBuilder() - .ep(EndpointParameters.commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSSecurityTokenServiceV20110615", "GetAccessKeyInfo", {}) - .n("STSClient", "GetAccessKeyInfoCommand") - .sc(GetAccessKeyInfo) - .build() { -} - -class GetCallerIdentityCommand extends smithyClient.Command - .classBuilder() - .ep(EndpointParameters.commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSSecurityTokenServiceV20110615", "GetCallerIdentity", {}) - .n("STSClient", "GetCallerIdentityCommand") - .sc(GetCallerIdentity) - .build() { -} - -class GetDelegatedAccessTokenCommand extends smithyClient.Command - .classBuilder() - .ep(EndpointParameters.commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSSecurityTokenServiceV20110615", "GetDelegatedAccessToken", {}) - .n("STSClient", "GetDelegatedAccessTokenCommand") - .sc(GetDelegatedAccessToken) - .build() { -} - -class GetFederationTokenCommand extends smithyClient.Command - .classBuilder() - .ep(EndpointParameters.commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSSecurityTokenServiceV20110615", "GetFederationToken", {}) - .n("STSClient", "GetFederationTokenCommand") - .sc(GetFederationToken) - .build() { -} - -class GetSessionTokenCommand extends smithyClient.Command - .classBuilder() - .ep(EndpointParameters.commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSSecurityTokenServiceV20110615", "GetSessionToken", {}) - .n("STSClient", "GetSessionTokenCommand") - .sc(GetSessionToken) - .build() { -} - -class GetWebIdentityTokenCommand extends smithyClient.Command - .classBuilder() - .ep(EndpointParameters.commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSSecurityTokenServiceV20110615", "GetWebIdentityToken", {}) - .n("STSClient", "GetWebIdentityTokenCommand") - .sc(GetWebIdentityToken) - .build() { -} - -const commands = { - AssumeRoleCommand, - AssumeRoleWithSAMLCommand, - AssumeRoleWithWebIdentityCommand, - AssumeRootCommand, - DecodeAuthorizationMessageCommand, - GetAccessKeyInfoCommand, - GetCallerIdentityCommand, - GetDelegatedAccessTokenCommand, - GetFederationTokenCommand, - GetSessionTokenCommand, - GetWebIdentityTokenCommand, -}; -class STS extends STSClient.STSClient { -} -smithyClient.createAggregatedClient(commands, STS); - -const getAccountIdFromAssumedRoleUser = (assumedRoleUser) => { - if (typeof assumedRoleUser?.Arn === "string") { - const arnComponents = assumedRoleUser.Arn.split(":"); - if (arnComponents.length > 4 && arnComponents[4] !== "") { - return arnComponents[4]; - } - } - return undefined; -}; -const resolveRegion = async (_region, _parentRegion, credentialProviderLogger, loaderConfig = {}) => { - const region = typeof _region === "function" ? await _region() : _region; - const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion; - const stsDefaultRegion = await regionConfigResolver.stsRegionDefaultResolver(loaderConfig)(); - credentialProviderLogger?.debug?.("@aws-sdk/client-sts::resolveRegion", "accepting first of:", `${region} (credential provider clientConfig)`, `${parentRegion} (contextual client)`, `${stsDefaultRegion} (STS default: AWS_REGION, profile region, or us-east-1)`); - return region ?? parentRegion ?? stsDefaultRegion; -}; -const getDefaultRoleAssumer$1 = (stsOptions, STSClient) => { - let stsClient; - let closureSourceCreds; - return async (sourceCreds, params) => { - closureSourceCreds = sourceCreds; - if (!stsClient) { - const { logger = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId, } = stsOptions; - const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, { - logger, - profile, - }); - const isCompatibleRequestHandler = !isH2(requestHandler); - stsClient = new STSClient({ - ...stsOptions, - userAgentAppId, - profile, - credentialDefaultProvider: () => async () => closureSourceCreds, - region: resolvedRegion, - requestHandler: isCompatibleRequestHandler ? requestHandler : undefined, - logger: logger, - }); - } - const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleCommand(params)); - if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) { - throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`); - } - const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser); - const credentials = { - accessKeyId: Credentials.AccessKeyId, - secretAccessKey: Credentials.SecretAccessKey, - sessionToken: Credentials.SessionToken, - expiration: Credentials.Expiration, - ...(Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope }), - ...(accountId && { accountId }), - }; - client.setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i"); - return credentials; - }; -}; -const getDefaultRoleAssumerWithWebIdentity$1 = (stsOptions, STSClient) => { - let stsClient; - return async (params) => { - if (!stsClient) { - const { logger = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId, } = stsOptions; - const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, { - logger, - profile, - }); - const isCompatibleRequestHandler = !isH2(requestHandler); - stsClient = new STSClient({ - ...stsOptions, - userAgentAppId, - profile, - region: resolvedRegion, - requestHandler: isCompatibleRequestHandler ? requestHandler : undefined, - logger: logger, - }); - } - const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params)); - if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) { - throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`); - } - const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser); - const credentials = { - accessKeyId: Credentials.AccessKeyId, - secretAccessKey: Credentials.SecretAccessKey, - sessionToken: Credentials.SessionToken, - expiration: Credentials.Expiration, - ...(Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope }), - ...(accountId && { accountId }), - }; - if (accountId) { - client.setCredentialFeature(credentials, "RESOLVED_ACCOUNT_ID", "T"); - } - client.setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k"); - return credentials; - }; -}; -const isH2 = (requestHandler) => { - return requestHandler?.metadata?.handlerProtocol === "h2"; -}; - -const getCustomizableStsClientCtor = (baseCtor, customizations) => { - if (!customizations) - return baseCtor; - else - return class CustomizableSTSClient extends baseCtor { - constructor(config) { - super(config); - for (const customization of customizations) { - this.middlewareStack.use(customization); - } - } - }; -}; -const getDefaultRoleAssumer = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumer$1(stsOptions, getCustomizableStsClientCtor(STSClient.STSClient, stsPlugins)); -const getDefaultRoleAssumerWithWebIdentity = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity$1(stsOptions, getCustomizableStsClientCtor(STSClient.STSClient, stsPlugins)); -const decorateDefaultCredentialProvider = (provider) => (input) => provider({ - roleAssumer: getDefaultRoleAssumer(input), - roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity(input), - ...input, -}); - -Object.defineProperty(exports, "$Command", { - enumerable: true, - get: function () { return smithyClient.Command; } -}); -exports.AssumeRoleCommand = AssumeRoleCommand; -exports.AssumeRoleWithSAMLCommand = AssumeRoleWithSAMLCommand; -exports.AssumeRoleWithWebIdentityCommand = AssumeRoleWithWebIdentityCommand; -exports.AssumeRootCommand = AssumeRootCommand; -exports.DecodeAuthorizationMessageCommand = DecodeAuthorizationMessageCommand; -exports.ExpiredTokenException = ExpiredTokenException$1; -exports.ExpiredTradeInTokenException = ExpiredTradeInTokenException$1; -exports.GetAccessKeyInfoCommand = GetAccessKeyInfoCommand; -exports.GetCallerIdentityCommand = GetCallerIdentityCommand; -exports.GetDelegatedAccessTokenCommand = GetDelegatedAccessTokenCommand; -exports.GetFederationTokenCommand = GetFederationTokenCommand; -exports.GetSessionTokenCommand = GetSessionTokenCommand; -exports.GetWebIdentityTokenCommand = GetWebIdentityTokenCommand; -exports.IDPCommunicationErrorException = IDPCommunicationErrorException$1; -exports.IDPRejectedClaimException = IDPRejectedClaimException$1; -exports.InvalidAuthorizationMessageException = InvalidAuthorizationMessageException$1; -exports.InvalidIdentityTokenException = InvalidIdentityTokenException$1; -exports.JWTPayloadSizeExceededException = JWTPayloadSizeExceededException$1; -exports.MalformedPolicyDocumentException = MalformedPolicyDocumentException$1; -exports.OutboundWebIdentityFederationDisabledException = OutboundWebIdentityFederationDisabledException$1; -exports.PackedPolicyTooLargeException = PackedPolicyTooLargeException$1; -exports.RegionDisabledException = RegionDisabledException$1; -exports.STS = STS; -exports.STSServiceException = STSServiceException$1; -exports.SessionDurationEscalationException = SessionDurationEscalationException$1; -exports.decorateDefaultCredentialProvider = decorateDefaultCredentialProvider; -exports.getDefaultRoleAssumer = getDefaultRoleAssumer; -exports.getDefaultRoleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity; -Object.keys(STSClient).forEach(function (k) { - if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { - enumerable: true, - get: function () { return STSClient[k]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeConfig.js b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeConfig.js deleted file mode 100644 index 7d39d101..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeConfig.js +++ /dev/null @@ -1,70 +0,0 @@ -"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 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 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, - }; - 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 }), - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || - (async (idProps) => await (0, credential_provider_node_1.defaultProvider)(idProps?.__config || {})()), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - 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.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), - 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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeConfig.shared.js b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeConfig.shared.js deleted file mode 100644 index 5291d67e..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeConfig.shared.js +++ /dev/null @@ -1,47 +0,0 @@ -"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: "2011-06-15", - 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.defaultSTSHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - logger: config?.logger ?? new smithy_client_1.NoOpLogger(), - protocol: config?.protocol ?? - new protocols_1.AwsQueryProtocol({ - defaultNamespace: "com.amazonaws.sts", - xmlNamespace: "https://sts.amazonaws.com/doc/2011-06-15/", - version: "2011-06-15", - }), - serviceId: config?.serviceId ?? "STS", - urlParser: config?.urlParser ?? url_parser_1.parseUrl, - utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, - utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeExtensions.js b/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeExtensions.js deleted file mode 100644 index a50ebec3..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sts/dist-cjs/runtimeExtensions.js +++ /dev/null @@ -1,13 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.resolveRuntimeExtensions = void 0; -const region_config_resolver_1 = require("@aws-sdk/region-config-resolver"); -const protocol_http_1 = require("@smithy/protocol-http"); -const smithy_client_1 = require("@smithy/smithy-client"); -const httpAuthExtensionConfiguration_1 = require("./auth/httpAuthExtensionConfiguration"); -const resolveRuntimeExtensions = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, smithy_client_1.getDefaultExtensionConfiguration)(runtimeConfig), (0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig), (0, httpAuthExtensionConfiguration_1.getHttpAuthExtensionConfiguration)(runtimeConfig)); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, (0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, smithy_client_1.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), (0, httpAuthExtensionConfiguration_1.resolveHttpAuthRuntimeConfig)(extensionConfiguration)); -}; -exports.resolveRuntimeExtensions = resolveRuntimeExtensions; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 52303c3b..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,169 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-cjs/index.js deleted file mode 100644 index 9f589873..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/smithy-client/dist-cjs/index.js +++ /dev/null @@ -1,589 +0,0 @@ -'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]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js deleted file mode 100644 index b06a7b87..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js +++ /dev/null @@ -1,16 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/index.js deleted file mode 100644 index c095e288..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/index.js +++ /dev/null @@ -1,19 +0,0 @@ -'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]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/toBase64.js deleted file mode 100644 index 0590ce3f..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/dist-cjs/toBase64.js +++ /dev/null @@ -1,19 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js deleted file mode 100644 index b577c9ca..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js +++ /dev/null @@ -1,20 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js deleted file mode 100644 index 3238bb77..00000000 --- a/claude-code-source/node_modules/@aws-sdk/client-sts/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || - Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; - -exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/index.js deleted file mode 100644 index 6cda67ed..00000000 --- a/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/index.js +++ /dev/null @@ -1,2000 +0,0 @@ -'use strict'; - -var protocolHttp = require('@smithy/protocol-http'); -var core = require('@smithy/core'); -var propertyProvider = require('@smithy/property-provider'); -var client = require('@aws-sdk/core/client'); -var signatureV4 = require('@smithy/signature-v4'); -var cbor = require('@smithy/core/cbor'); -var schema = require('@smithy/core/schema'); -var smithyClient = require('@smithy/smithy-client'); -var protocols = require('@smithy/core/protocols'); -var serde = require('@smithy/core/serde'); -var utilBase64 = require('@smithy/util-base64'); -var utilUtf8 = require('@smithy/util-utf8'); -var xmlBuilder = require('@aws-sdk/xml-builder'); - -const state = { - warningEmitted: false, -}; -const emitWarningIfUnsupportedVersion = (version) => { - if (version && !state.warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 18) { - state.warningEmitted = true; - process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will -no longer support Node.js 16.x on January 6, 2025. - -To continue receiving updates to AWS services, bug fixes, and security -updates please upgrade to a supported Node.js LTS version. - -More information can be found at: https://a.co/74kJMmI`); - } -}; - -function setCredentialFeature(credentials, feature, value) { - if (!credentials.$source) { - credentials.$source = {}; - } - credentials.$source[feature] = value; - return credentials; -} - -function setFeature(context, feature, value) { - if (!context.__aws_sdk_context) { - context.__aws_sdk_context = { - features: {}, - }; - } - else if (!context.__aws_sdk_context.features) { - context.__aws_sdk_context.features = {}; - } - context.__aws_sdk_context.features[feature] = value; -} - -function setTokenFeature(token, feature, value) { - if (!token.$source) { - token.$source = {}; - } - token.$source[feature] = value; - return token; -} - -const getDateHeader = (response) => protocolHttp.HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : undefined; - -const getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset); - -const isClockSkewed = (clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 300000; - -const getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => { - const clockTimeInMs = Date.parse(clockTime); - if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) { - return clockTimeInMs - Date.now(); - } - return currentSystemClockOffset; -}; - -const throwSigningPropertyError = (name, property) => { - if (!property) { - throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`); - } - return property; -}; -const validateSigningProperties = async (signingProperties) => { - const context = throwSigningPropertyError("context", signingProperties.context); - const config = throwSigningPropertyError("config", signingProperties.config); - const authScheme = context.endpointV2?.properties?.authSchemes?.[0]; - const signerFunction = throwSigningPropertyError("signer", config.signer); - const signer = await signerFunction(authScheme); - const signingRegion = signingProperties?.signingRegion; - const signingRegionSet = signingProperties?.signingRegionSet; - const signingName = signingProperties?.signingName; - return { - config, - signer, - signingRegion, - signingRegionSet, - signingName, - }; -}; -class AwsSdkSigV4Signer { - async sign(httpRequest, identity, signingProperties) { - if (!protocolHttp.HttpRequest.isInstance(httpRequest)) { - throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); - } - const validatedProps = await validateSigningProperties(signingProperties); - const { config, signer } = validatedProps; - let { signingRegion, signingName } = validatedProps; - const handlerExecutionContext = signingProperties.context; - if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) { - const [first, second] = handlerExecutionContext.authSchemes; - if (first?.name === "sigv4a" && second?.name === "sigv4") { - signingRegion = second?.signingRegion ?? signingRegion; - signingName = second?.signingName ?? signingName; - } - } - const signedRequest = await signer.sign(httpRequest, { - signingDate: getSkewCorrectedDate(config.systemClockOffset), - signingRegion: signingRegion, - signingService: signingName, - }); - return signedRequest; - } - errorHandler(signingProperties) { - return (error) => { - const serverTime = error.ServerTime ?? getDateHeader(error.$response); - if (serverTime) { - const config = throwSigningPropertyError("config", signingProperties.config); - const initialSystemClockOffset = config.systemClockOffset; - config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset); - const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset; - if (clockSkewCorrected && error.$metadata) { - error.$metadata.clockSkewCorrected = true; - } - } - throw error; - }; - } - successHandler(httpResponse, signingProperties) { - const dateHeader = getDateHeader(httpResponse); - if (dateHeader) { - const config = throwSigningPropertyError("config", signingProperties.config); - config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset); - } - } -} -const AWSSDKSigV4Signer = AwsSdkSigV4Signer; - -class AwsSdkSigV4ASigner extends AwsSdkSigV4Signer { - async sign(httpRequest, identity, signingProperties) { - if (!protocolHttp.HttpRequest.isInstance(httpRequest)) { - throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); - } - const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties(signingProperties); - const configResolvedSigningRegionSet = await config.sigv4aSigningRegionSet?.(); - const multiRegionOverride = (configResolvedSigningRegionSet ?? - signingRegionSet ?? [signingRegion]).join(","); - const signedRequest = await signer.sign(httpRequest, { - signingDate: getSkewCorrectedDate(config.systemClockOffset), - signingRegion: multiRegionOverride, - signingService: signingName, - }); - return signedRequest; - } -} - -const getArrayForCommaSeparatedString = (str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : []; - -const getBearerTokenEnvKey = (signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`; - -const NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE"; -const NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference"; -const NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = { - environmentVariableSelector: (env, options) => { - if (options?.signingName) { - const bearerTokenKey = getBearerTokenEnvKey(options.signingName); - if (bearerTokenKey in env) - return ["httpBearerAuth"]; - } - if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env)) - return undefined; - return getArrayForCommaSeparatedString(env[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]); - }, - configFileSelector: (profile) => { - if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile)) - return undefined; - return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]); - }, - default: [], -}; - -const resolveAwsSdkSigV4AConfig = (config) => { - config.sigv4aSigningRegionSet = core.normalizeProvider(config.sigv4aSigningRegionSet); - return config; -}; -const NODE_SIGV4A_CONFIG_OPTIONS = { - environmentVariableSelector(env) { - if (env.AWS_SIGV4A_SIGNING_REGION_SET) { - return env.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_) => _.trim()); - } - throw new propertyProvider.ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", { - tryNextLink: true, - }); - }, - configFileSelector(profile) { - if (profile.sigv4a_signing_region_set) { - return (profile.sigv4a_signing_region_set ?? "").split(",").map((_) => _.trim()); - } - throw new propertyProvider.ProviderError("sigv4a_signing_region_set not set in profile.", { - tryNextLink: true, - }); - }, - default: undefined, -}; - -const resolveAwsSdkSigV4Config = (config) => { - let inputCredentials = config.credentials; - let isUserSupplied = !!config.credentials; - let resolvedCredentials = undefined; - Object.defineProperty(config, "credentials", { - set(credentials) { - if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) { - isUserSupplied = true; - } - inputCredentials = credentials; - const memoizedProvider = normalizeCredentialProvider(config, { - credentials: inputCredentials, - credentialDefaultProvider: config.credentialDefaultProvider, - }); - const boundProvider = bindCallerConfig(config, memoizedProvider); - if (isUserSupplied && !boundProvider.attributed) { - resolvedCredentials = async (options) => boundProvider(options).then((creds) => client.setCredentialFeature(creds, "CREDENTIALS_CODE", "e")); - resolvedCredentials.memoized = boundProvider.memoized; - resolvedCredentials.configBound = boundProvider.configBound; - resolvedCredentials.attributed = true; - } - else { - resolvedCredentials = boundProvider; - } - }, - get() { - return resolvedCredentials; - }, - enumerable: true, - configurable: true, - }); - config.credentials = inputCredentials; - const { signingEscapePath = true, systemClockOffset = config.systemClockOffset || 0, sha256, } = config; - let signer; - if (config.signer) { - signer = core.normalizeProvider(config.signer); - } - else if (config.regionInfoProvider) { - signer = () => core.normalizeProvider(config.region)() - .then(async (region) => [ - (await config.regionInfoProvider(region, { - useFipsEndpoint: await config.useFipsEndpoint(), - useDualstackEndpoint: await config.useDualstackEndpoint(), - })) || {}, - region, - ]) - .then(([regionInfo, region]) => { - const { signingRegion, signingService } = regionInfo; - config.signingRegion = config.signingRegion || signingRegion || region; - config.signingName = config.signingName || signingService || config.serviceId; - const params = { - ...config, - credentials: config.credentials, - region: config.signingRegion, - service: config.signingName, - sha256, - uriEscapePath: signingEscapePath, - }; - const SignerCtor = config.signerConstructor || signatureV4.SignatureV4; - return new SignerCtor(params); - }); - } - else { - signer = async (authScheme) => { - authScheme = Object.assign({}, { - name: "sigv4", - signingName: config.signingName || config.defaultSigningName, - signingRegion: await core.normalizeProvider(config.region)(), - properties: {}, - }, authScheme); - const signingRegion = authScheme.signingRegion; - const signingService = authScheme.signingName; - config.signingRegion = config.signingRegion || signingRegion; - config.signingName = config.signingName || signingService || config.serviceId; - const params = { - ...config, - credentials: config.credentials, - region: config.signingRegion, - service: config.signingName, - sha256, - uriEscapePath: signingEscapePath, - }; - const SignerCtor = config.signerConstructor || signatureV4.SignatureV4; - return new SignerCtor(params); - }; - } - const resolvedConfig = Object.assign(config, { - systemClockOffset, - signingEscapePath, - signer, - }); - return resolvedConfig; -}; -const resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config; -function normalizeCredentialProvider(config, { credentials, credentialDefaultProvider, }) { - let credentialsProvider; - if (credentials) { - if (!credentials?.memoized) { - credentialsProvider = core.memoizeIdentityProvider(credentials, core.isIdentityExpired, core.doesIdentityRequireRefresh); - } - else { - credentialsProvider = credentials; - } - } - else { - if (credentialDefaultProvider) { - credentialsProvider = core.normalizeProvider(credentialDefaultProvider(Object.assign({}, config, { - parentClientConfig: config, - }))); - } - else { - credentialsProvider = async () => { - throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured."); - }; - } - } - credentialsProvider.memoized = true; - return credentialsProvider; -} -function bindCallerConfig(config, credentialsProvider) { - if (credentialsProvider.configBound) { - return credentialsProvider; - } - const fn = async (options) => credentialsProvider({ ...options, callerClientConfig: config }); - fn.memoized = credentialsProvider.memoized; - fn.configBound = true; - return fn; -} - -class ProtocolLib { - queryCompat; - constructor(queryCompat = false) { - this.queryCompat = queryCompat; - } - resolveRestContentType(defaultContentType, inputSchema) { - const members = inputSchema.getMemberSchemas(); - const httpPayloadMember = Object.values(members).find((m) => { - return !!m.getMergedTraits().httpPayload; - }); - if (httpPayloadMember) { - const mediaType = httpPayloadMember.getMergedTraits().mediaType; - if (mediaType) { - return mediaType; - } - else if (httpPayloadMember.isStringSchema()) { - return "text/plain"; - } - else if (httpPayloadMember.isBlobSchema()) { - return "application/octet-stream"; - } - else { - return defaultContentType; - } - } - else if (!inputSchema.isUnitSchema()) { - const hasBody = Object.values(members).find((m) => { - const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits(); - const noPrefixHeaders = httpPrefixHeaders === void 0; - return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && noPrefixHeaders; - }); - if (hasBody) { - return defaultContentType; - } - } - } - async getErrorSchemaOrThrowBaseException(errorIdentifier, defaultNamespace, response, dataObject, metadata, getErrorSchema) { - let namespace = defaultNamespace; - let errorName = errorIdentifier; - if (errorIdentifier.includes("#")) { - [namespace, errorName] = errorIdentifier.split("#"); - } - const errorMetadata = { - $metadata: metadata, - $fault: response.statusCode < 500 ? "client" : "server", - }; - const registry = schema.TypeRegistry.for(namespace); - try { - const errorSchema = getErrorSchema?.(registry, errorName) ?? registry.getSchema(errorIdentifier); - return { errorSchema, errorMetadata }; - } - catch (e) { - dataObject.message = dataObject.message ?? dataObject.Message ?? "UnknownError"; - const synthetic = schema.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace); - const baseExceptionSchema = synthetic.getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = synthetic.getErrorCtor(baseExceptionSchema) ?? Error; - throw this.decorateServiceException(Object.assign(new ErrorCtor({ name: errorName }), errorMetadata), dataObject); - } - throw this.decorateServiceException(Object.assign(new Error(errorName), errorMetadata), dataObject); - } - } - decorateServiceException(exception, additions = {}) { - if (this.queryCompat) { - const msg = exception.Message ?? additions.Message; - const error = smithyClient.decorateServiceException(exception, additions); - if (msg) { - error.Message = msg; - error.message = msg; - } - return error; - } - return smithyClient.decorateServiceException(exception, additions); - } - setQueryCompatError(output, response) { - const queryErrorHeader = response.headers?.["x-amzn-query-error"]; - if (output !== undefined && queryErrorHeader != null) { - const [Code, Type] = queryErrorHeader.split(";"); - const entries = Object.entries(output); - const Error = { - Code, - Type, - }; - Object.assign(output, Error); - for (const [k, v] of entries) { - Error[k] = v; - } - delete Error.__type; - output.Error = Error; - } - } - queryCompatOutput(queryCompatErrorData, errorData) { - if (queryCompatErrorData.Error) { - errorData.Error = queryCompatErrorData.Error; - } - if (queryCompatErrorData.Type) { - errorData.Type = queryCompatErrorData.Type; - } - if (queryCompatErrorData.Code) { - errorData.Code = queryCompatErrorData.Code; - } - } -} - -class AwsSmithyRpcV2CborProtocol extends cbor.SmithyRpcV2CborProtocol { - awsQueryCompatible; - mixin; - constructor({ defaultNamespace, awsQueryCompatible, }) { - super({ defaultNamespace }); - this.awsQueryCompatible = !!awsQueryCompatible; - this.mixin = new ProtocolLib(this.awsQueryCompatible); - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (this.awsQueryCompatible) { - request.headers["x-amzn-query-mode"] = "true"; - } - return request; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - if (this.awsQueryCompatible) { - this.mixin.setQueryCompatError(dataObject, response); - } - const errorName = cbor.loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown"; - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorName, this.options.defaultNamespace, response, dataObject, metadata); - const ns = schema.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const ErrorCtor = schema.TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; - const exception = new ErrorCtor(message); - const output = {}; - for (const [name, member] of ns.structIterator()) { - output[name] = this.deserializer.readValue(member, dataObject[name]); - } - if (this.awsQueryCompatible) { - this.mixin.queryCompatOutput(dataObject, output); - } - throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { - $fault: ns.getMergedTraits().error, - message, - }, output), dataObject); - } -} - -const _toStr = (val) => { - if (val == null) { - return val; - } - if (typeof val === "number" || typeof val === "bigint") { - const warning = new Error(`Received number ${val} where a string was expected.`); - warning.name = "Warning"; - console.warn(warning); - return String(val); - } - if (typeof val === "boolean") { - const warning = new Error(`Received boolean ${val} where a string was expected.`); - warning.name = "Warning"; - console.warn(warning); - return String(val); - } - return val; -}; -const _toBool = (val) => { - if (val == null) { - return val; - } - if (typeof val === "string") { - const lowercase = val.toLowerCase(); - if (val !== "" && lowercase !== "false" && lowercase !== "true") { - const warning = new Error(`Received string "${val}" where a boolean was expected.`); - warning.name = "Warning"; - console.warn(warning); - } - return val !== "" && lowercase !== "false"; - } - return val; -}; -const _toNum = (val) => { - if (val == null) { - return val; - } - if (typeof val === "string") { - const num = Number(val); - if (num.toString() !== val) { - const warning = new Error(`Received string "${val}" where a number was expected.`); - warning.name = "Warning"; - console.warn(warning); - return val; - } - return num; - } - return val; -}; - -class SerdeContextConfig { - serdeContext; - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - } -} - -function jsonReviver(key, value, context) { - if (context?.source) { - const numericString = context.source; - if (typeof value === "number") { - if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER || numericString !== String(value)) { - const isFractional = numericString.includes("."); - if (isFractional) { - return new serde.NumericValue(numericString, "bigDecimal"); - } - else { - return BigInt(numericString); - } - } - } - } - return value; -} - -const collectBodyString = (streamBody, context) => smithyClient.collectBody(streamBody, context).then((body) => (context?.utf8Encoder ?? utilUtf8.toUtf8)(body)); - -const parseJsonBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { - if (encoded.length) { - try { - return JSON.parse(encoded); - } - catch (e) { - if (e?.name === "SyntaxError") { - Object.defineProperty(e, "$responseBodyText", { - value: encoded, - }); - } - throw e; - } - } - return {}; -}); -const parseJsonErrorBody = async (errorBody, context) => { - const value = await parseJsonBody(errorBody, context); - value.message = value.message ?? value.Message; - return value; -}; -const loadRestJsonErrorCode = (output, data) => { - const findKey = (object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase()); - const sanitizeErrorCode = (rawValue) => { - let cleanValue = rawValue; - if (typeof cleanValue === "number") { - cleanValue = cleanValue.toString(); - } - if (cleanValue.indexOf(",") >= 0) { - cleanValue = cleanValue.split(",")[0]; - } - if (cleanValue.indexOf(":") >= 0) { - cleanValue = cleanValue.split(":")[0]; - } - if (cleanValue.indexOf("#") >= 0) { - cleanValue = cleanValue.split("#")[1]; - } - return cleanValue; - }; - const headerKey = findKey(output.headers, "x-amzn-errortype"); - if (headerKey !== undefined) { - return sanitizeErrorCode(output.headers[headerKey]); - } - if (data && typeof data === "object") { - const codeKey = findKey(data, "code"); - if (codeKey && data[codeKey] !== undefined) { - return sanitizeErrorCode(data[codeKey]); - } - if (data["__type"] !== undefined) { - return sanitizeErrorCode(data["__type"]); - } - } -}; - -class JsonShapeDeserializer extends SerdeContextConfig { - settings; - constructor(settings) { - super(); - this.settings = settings; - } - async read(schema, data) { - return this._read(schema, typeof data === "string" ? JSON.parse(data, jsonReviver) : await parseJsonBody(data, this.serdeContext)); - } - readObject(schema, data) { - return this._read(schema, data); - } - _read(schema$1, value) { - const isObject = value !== null && typeof value === "object"; - const ns = schema.NormalizedSchema.of(schema$1); - if (ns.isListSchema() && Array.isArray(value)) { - const listMember = ns.getValueSchema(); - const out = []; - const sparse = !!ns.getMergedTraits().sparse; - for (const item of value) { - if (sparse || item != null) { - out.push(this._read(listMember, item)); - } - } - return out; - } - else if (ns.isMapSchema() && isObject) { - const mapMember = ns.getValueSchema(); - const out = {}; - const sparse = !!ns.getMergedTraits().sparse; - for (const [_k, _v] of Object.entries(value)) { - if (sparse || _v != null) { - out[_k] = this._read(mapMember, _v); - } - } - return out; - } - else if (ns.isStructSchema() && isObject) { - const out = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - const fromKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; - const deserializedValue = this._read(memberSchema, value[fromKey]); - if (deserializedValue != null) { - out[memberName] = deserializedValue; - } - } - return out; - } - if (ns.isBlobSchema() && typeof value === "string") { - return utilBase64.fromBase64(value); - } - const mediaType = ns.getMergedTraits().mediaType; - if (ns.isStringSchema() && typeof value === "string" && mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - return serde.LazyJsonString.from(value); - } - } - if (ns.isTimestampSchema() && value != null) { - const format = protocols.determineTimestampFormat(ns, this.settings); - switch (format) { - case 5: - return serde.parseRfc3339DateTimeWithOffset(value); - case 6: - return serde.parseRfc7231DateTime(value); - case 7: - return serde.parseEpochTimestamp(value); - default: - console.warn("Missing timestamp format, parsing value with Date constructor:", value); - return new Date(value); - } - } - if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { - return BigInt(value); - } - if (ns.isBigDecimalSchema() && value != undefined) { - if (value instanceof serde.NumericValue) { - return value; - } - const untyped = value; - if (untyped.type === "bigDecimal" && "string" in untyped) { - return new serde.NumericValue(untyped.string, untyped.type); - } - return new serde.NumericValue(String(value), "bigDecimal"); - } - if (ns.isNumericSchema() && typeof value === "string") { - switch (value) { - case "Infinity": - return Infinity; - case "-Infinity": - return -Infinity; - case "NaN": - return NaN; - } - } - if (ns.isDocumentSchema()) { - if (isObject) { - const out = Array.isArray(value) ? [] : {}; - for (const [k, v] of Object.entries(value)) { - if (v instanceof serde.NumericValue) { - out[k] = v; - } - else { - out[k] = this._read(ns, v); - } - } - return out; - } - else { - return structuredClone(value); - } - } - return value; - } -} - -const NUMERIC_CONTROL_CHAR = String.fromCharCode(925); -class JsonReplacer { - values = new Map(); - counter = 0; - stage = 0; - createReplacer() { - if (this.stage === 1) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer already created."); - } - if (this.stage === 2) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); - } - this.stage = 1; - return (key, value) => { - if (value instanceof serde.NumericValue) { - const v = `${NUMERIC_CONTROL_CHAR + "nv" + this.counter++}_` + value.string; - this.values.set(`"${v}"`, value.string); - return v; - } - if (typeof value === "bigint") { - const s = value.toString(); - const v = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s; - this.values.set(`"${v}"`, s); - return v; - } - return value; - }; - } - replaceInJson(json) { - if (this.stage === 0) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet."); - } - if (this.stage === 2) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); - } - this.stage = 2; - if (this.counter === 0) { - return json; - } - for (const [key, value] of this.values) { - json = json.replace(key, value); - } - return json; - } -} - -class JsonShapeSerializer extends SerdeContextConfig { - settings; - buffer; - rootSchema; - constructor(settings) { - super(); - this.settings = settings; - } - write(schema$1, value) { - this.rootSchema = schema.NormalizedSchema.of(schema$1); - this.buffer = this._write(this.rootSchema, value); - } - writeDiscriminatedDocument(schema$1, value) { - this.write(schema$1, value); - if (typeof this.buffer === "object") { - this.buffer.__type = schema.NormalizedSchema.of(schema$1).getName(true); - } - } - flush() { - const { rootSchema } = this; - this.rootSchema = undefined; - if (rootSchema?.isStructSchema() || rootSchema?.isDocumentSchema()) { - const replacer = new JsonReplacer(); - return replacer.replaceInJson(JSON.stringify(this.buffer, replacer.createReplacer(), 0)); - } - return this.buffer; - } - _write(schema$1, value, container) { - const isObject = value !== null && typeof value === "object"; - const ns = schema.NormalizedSchema.of(schema$1); - if (ns.isListSchema() && Array.isArray(value)) { - const listMember = ns.getValueSchema(); - const out = []; - const sparse = !!ns.getMergedTraits().sparse; - for (const item of value) { - if (sparse || item != null) { - out.push(this._write(listMember, item)); - } - } - return out; - } - else if (ns.isMapSchema() && isObject) { - const mapMember = ns.getValueSchema(); - const out = {}; - const sparse = !!ns.getMergedTraits().sparse; - for (const [_k, _v] of Object.entries(value)) { - if (sparse || _v != null) { - out[_k] = this._write(mapMember, _v); - } - } - return out; - } - else if (ns.isStructSchema() && isObject) { - const out = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - const targetKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; - const serializableValue = this._write(memberSchema, value[memberName], ns); - if (serializableValue !== undefined) { - out[targetKey] = serializableValue; - } - } - return out; - } - if (value === null && container?.isStructSchema()) { - return void 0; - } - if ((ns.isBlobSchema() && (value instanceof Uint8Array || typeof value === "string")) || - (ns.isDocumentSchema() && value instanceof Uint8Array)) { - if (ns === this.rootSchema) { - return value; - } - return (this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value); - } - if ((ns.isTimestampSchema() || ns.isDocumentSchema()) && value instanceof Date) { - const format = protocols.determineTimestampFormat(ns, this.settings); - switch (format) { - case 5: - return value.toISOString().replace(".000Z", "Z"); - case 6: - return serde.dateToUtcString(value); - case 7: - return value.getTime() / 1000; - default: - console.warn("Missing timestamp format, using epoch seconds", value); - return value.getTime() / 1000; - } - } - if (ns.isNumericSchema() && typeof value === "number") { - if (Math.abs(value) === Infinity || isNaN(value)) { - return String(value); - } - } - if (ns.isStringSchema()) { - if (typeof value === "undefined" && ns.isIdempotencyToken()) { - return serde.generateIdempotencyToken(); - } - const mediaType = ns.getMergedTraits().mediaType; - if (value != null && mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - return serde.LazyJsonString.from(value); - } - } - } - if (ns.isDocumentSchema()) { - if (isObject) { - const out = Array.isArray(value) ? [] : {}; - for (const [k, v] of Object.entries(value)) { - if (v instanceof serde.NumericValue) { - out[k] = v; - } - else { - out[k] = this._write(ns, v); - } - } - return out; - } - else { - return structuredClone(value); - } - } - return value; - } -} - -class JsonCodec extends SerdeContextConfig { - settings; - constructor(settings) { - super(); - this.settings = settings; - } - createSerializer() { - const serializer = new JsonShapeSerializer(this.settings); - serializer.setSerdeContext(this.serdeContext); - return serializer; - } - createDeserializer() { - const deserializer = new JsonShapeDeserializer(this.settings); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; - } -} - -class AwsJsonRpcProtocol extends protocols.RpcProtocol { - serializer; - deserializer; - serviceTarget; - codec; - mixin; - awsQueryCompatible; - constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, }) { - super({ - defaultNamespace, - }); - this.serviceTarget = serviceTarget; - this.codec = new JsonCodec({ - timestampFormat: { - useTrait: true, - default: 7, - }, - jsonName: false, - }); - this.serializer = this.codec.createSerializer(); - this.deserializer = this.codec.createDeserializer(); - this.awsQueryCompatible = !!awsQueryCompatible; - this.mixin = new ProtocolLib(this.awsQueryCompatible); - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (!request.path.endsWith("/")) { - request.path += "/"; - } - Object.assign(request.headers, { - "content-type": `application/x-amz-json-${this.getJsonRpcVersion()}`, - "x-amz-target": `${this.serviceTarget}.${operationSchema.name}`, - }); - if (this.awsQueryCompatible) { - request.headers["x-amzn-query-mode"] = "true"; - } - if (schema.deref(operationSchema.input) === "unit" || !request.body) { - request.body = "{}"; - } - return request; - } - getPayloadCodec() { - return this.codec; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - if (this.awsQueryCompatible) { - this.mixin.setQueryCompatError(dataObject, response); - } - const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); - const ns = schema.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const ErrorCtor = schema.TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; - const exception = new ErrorCtor(message); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().jsonName ?? name; - output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); - } - if (this.awsQueryCompatible) { - this.mixin.queryCompatOutput(dataObject, output); - } - throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { - $fault: ns.getMergedTraits().error, - message, - }, output), dataObject); - } -} - -class AwsJson1_0Protocol extends AwsJsonRpcProtocol { - constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, }) { - super({ - defaultNamespace, - serviceTarget, - awsQueryCompatible, - }); - } - getShapeId() { - return "aws.protocols#awsJson1_0"; - } - getJsonRpcVersion() { - return "1.0"; - } - getDefaultContentType() { - return "application/x-amz-json-1.0"; - } -} - -class AwsJson1_1Protocol extends AwsJsonRpcProtocol { - constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, }) { - super({ - defaultNamespace, - serviceTarget, - awsQueryCompatible, - }); - } - getShapeId() { - return "aws.protocols#awsJson1_1"; - } - getJsonRpcVersion() { - return "1.1"; - } - getDefaultContentType() { - return "application/x-amz-json-1.1"; - } -} - -class AwsRestJsonProtocol extends protocols.HttpBindingProtocol { - serializer; - deserializer; - codec; - mixin = new ProtocolLib(); - constructor({ defaultNamespace }) { - super({ - defaultNamespace, - }); - const settings = { - timestampFormat: { - useTrait: true, - default: 7, - }, - httpBindings: true, - jsonName: true, - }; - this.codec = new JsonCodec(settings); - this.serializer = new protocols.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); - this.deserializer = new protocols.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); - } - getShapeId() { - return "aws.protocols#restJson1"; - } - getPayloadCodec() { - return this.codec; - } - setSerdeContext(serdeContext) { - this.codec.setSerdeContext(serdeContext); - super.setSerdeContext(serdeContext); - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - const inputSchema = schema.NormalizedSchema.of(operationSchema.input); - if (!request.headers["content-type"]) { - const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); - if (contentType) { - request.headers["content-type"] = contentType; - } - } - if (request.body == null && request.headers["content-type"] === this.getDefaultContentType()) { - request.body = "{}"; - } - return request; - } - async deserializeResponse(operationSchema, context, response) { - const output = await super.deserializeResponse(operationSchema, context, response); - const outputSchema = schema.NormalizedSchema.of(operationSchema.output); - for (const [name, member] of outputSchema.structIterator()) { - if (member.getMemberTraits().httpPayload && !(name in output)) { - output[name] = null; - } - } - return output; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); - const ns = schema.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const ErrorCtor = schema.TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; - const exception = new ErrorCtor(message); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().jsonName ?? name; - output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); - } - throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { - $fault: ns.getMergedTraits().error, - message, - }, output), dataObject); - } - getDefaultContentType() { - return "application/json"; - } -} - -const awsExpectUnion = (value) => { - if (value == null) { - return undefined; - } - if (typeof value === "object" && "__type" in value) { - delete value.__type; - } - return smithyClient.expectUnion(value); -}; - -class XmlShapeDeserializer extends SerdeContextConfig { - settings; - stringDeserializer; - constructor(settings) { - super(); - this.settings = settings; - this.stringDeserializer = new protocols.FromStringShapeDeserializer(settings); - } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - this.stringDeserializer.setSerdeContext(serdeContext); - } - read(schema$1, bytes, key) { - const ns = schema.NormalizedSchema.of(schema$1); - const memberSchemas = ns.getMemberSchemas(); - const isEventPayload = ns.isStructSchema() && - ns.isMemberSchema() && - !!Object.values(memberSchemas).find((memberNs) => { - return !!memberNs.getMemberTraits().eventPayload; - }); - if (isEventPayload) { - const output = {}; - const memberName = Object.keys(memberSchemas)[0]; - const eventMemberSchema = memberSchemas[memberName]; - if (eventMemberSchema.isBlobSchema()) { - output[memberName] = bytes; - } - else { - output[memberName] = this.read(memberSchemas[memberName], bytes); - } - return output; - } - const xmlString = (this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8)(bytes); - const parsedObject = this.parseXml(xmlString); - return this.readSchema(schema$1, key ? parsedObject[key] : parsedObject); - } - readSchema(_schema, value) { - const ns = schema.NormalizedSchema.of(_schema); - if (ns.isUnitSchema()) { - return; - } - const traits = ns.getMergedTraits(); - if (ns.isListSchema() && !Array.isArray(value)) { - return this.readSchema(ns, [value]); - } - if (value == null) { - return value; - } - if (typeof value === "object") { - const sparse = !!traits.sparse; - const flat = !!traits.xmlFlattened; - if (ns.isListSchema()) { - const listValue = ns.getValueSchema(); - const buffer = []; - const sourceKey = listValue.getMergedTraits().xmlName ?? "member"; - const source = flat ? value : (value[0] ?? value)[sourceKey]; - const sourceArray = Array.isArray(source) ? source : [source]; - for (const v of sourceArray) { - if (v != null || sparse) { - buffer.push(this.readSchema(listValue, v)); - } - } - return buffer; - } - const buffer = {}; - if (ns.isMapSchema()) { - const keyNs = ns.getKeySchema(); - const memberNs = ns.getValueSchema(); - let entries; - if (flat) { - entries = Array.isArray(value) ? value : [value]; - } - else { - entries = Array.isArray(value.entry) ? value.entry : [value.entry]; - } - const keyProperty = keyNs.getMergedTraits().xmlName ?? "key"; - const valueProperty = memberNs.getMergedTraits().xmlName ?? "value"; - for (const entry of entries) { - const key = entry[keyProperty]; - const value = entry[valueProperty]; - if (value != null || sparse) { - buffer[key] = this.readSchema(memberNs, value); - } - } - return buffer; - } - if (ns.isStructSchema()) { - for (const [memberName, memberSchema] of ns.structIterator()) { - const memberTraits = memberSchema.getMergedTraits(); - const xmlObjectKey = !memberTraits.httpPayload - ? memberSchema.getMemberTraits().xmlName ?? memberName - : memberTraits.xmlName ?? memberSchema.getName(); - if (value[xmlObjectKey] != null) { - buffer[memberName] = this.readSchema(memberSchema, value[xmlObjectKey]); - } - } - return buffer; - } - if (ns.isDocumentSchema()) { - return value; - } - throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns.getName(true)}`); - } - if (ns.isListSchema()) { - return []; - } - if (ns.isMapSchema() || ns.isStructSchema()) { - return {}; - } - return this.stringDeserializer.read(ns, value); - } - parseXml(xml) { - if (xml.length) { - let parsedObj; - try { - parsedObj = xmlBuilder.parseXML(xml); - } - catch (e) { - if (e && typeof e === "object") { - Object.defineProperty(e, "$responseBodyText", { - value: xml, - }); - } - throw e; - } - const textNodeName = "#text"; - const key = Object.keys(parsedObj)[0]; - const parsedObjToReturn = parsedObj[key]; - if (parsedObjToReturn[textNodeName]) { - parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; - delete parsedObjToReturn[textNodeName]; - } - return smithyClient.getValueFromTextNode(parsedObjToReturn); - } - return {}; - } -} - -class QueryShapeSerializer extends SerdeContextConfig { - settings; - buffer; - constructor(settings) { - super(); - this.settings = settings; - } - write(schema$1, value, prefix = "") { - if (this.buffer === undefined) { - this.buffer = ""; - } - const ns = schema.NormalizedSchema.of(schema$1); - if (prefix && !prefix.endsWith(".")) { - prefix += "."; - } - if (ns.isBlobSchema()) { - if (typeof value === "string" || value instanceof Uint8Array) { - this.writeKey(prefix); - this.writeValue((this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value)); - } - } - else if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isStringSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(String(value)); - } - else if (ns.isIdempotencyToken()) { - this.writeKey(prefix); - this.writeValue(serde.generateIdempotencyToken()); - } - } - else if (ns.isBigIntegerSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(String(value)); - } - } - else if (ns.isBigDecimalSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(value instanceof serde.NumericValue ? value.string : String(value)); - } - } - else if (ns.isTimestampSchema()) { - if (value instanceof Date) { - this.writeKey(prefix); - const format = protocols.determineTimestampFormat(ns, this.settings); - switch (format) { - case 5: - this.writeValue(value.toISOString().replace(".000Z", "Z")); - break; - case 6: - this.writeValue(smithyClient.dateToUtcString(value)); - break; - case 7: - this.writeValue(String(value.getTime() / 1000)); - break; - } - } - } - else if (ns.isDocumentSchema()) { - throw new Error(`@aws-sdk/core/protocols - QuerySerializer unsupported document type ${ns.getName(true)}`); - } - else if (ns.isListSchema()) { - if (Array.isArray(value)) { - if (value.length === 0) { - if (this.settings.serializeEmptyLists) { - this.writeKey(prefix); - this.writeValue(""); - } - } - else { - const member = ns.getValueSchema(); - const flat = this.settings.flattenLists || ns.getMergedTraits().xmlFlattened; - let i = 1; - for (const item of value) { - if (item == null) { - continue; - } - const suffix = this.getKey("member", member.getMergedTraits().xmlName); - const key = flat ? `${prefix}${i}` : `${prefix}${suffix}.${i}`; - this.write(member, item, key); - ++i; - } - } - } - } - else if (ns.isMapSchema()) { - if (value && typeof value === "object") { - const keySchema = ns.getKeySchema(); - const memberSchema = ns.getValueSchema(); - const flat = ns.getMergedTraits().xmlFlattened; - let i = 1; - for (const [k, v] of Object.entries(value)) { - if (v == null) { - continue; - } - const keySuffix = this.getKey("key", keySchema.getMergedTraits().xmlName); - const key = flat ? `${prefix}${i}.${keySuffix}` : `${prefix}entry.${i}.${keySuffix}`; - const valueSuffix = this.getKey("value", memberSchema.getMergedTraits().xmlName); - const valueKey = flat ? `${prefix}${i}.${valueSuffix}` : `${prefix}entry.${i}.${valueSuffix}`; - this.write(keySchema, k, key); - this.write(memberSchema, v, valueKey); - ++i; - } - } - } - else if (ns.isStructSchema()) { - if (value && typeof value === "object") { - for (const [memberName, member] of ns.structIterator()) { - if (value[memberName] == null && !member.isIdempotencyToken()) { - continue; - } - const suffix = this.getKey(memberName, member.getMergedTraits().xmlName); - const key = `${prefix}${suffix}`; - this.write(member, value[memberName], key); - } - } - } - else if (ns.isUnitSchema()) ; - else { - throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${ns.getName(true)}`); - } - } - flush() { - if (this.buffer === undefined) { - throw new Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer."); - } - const str = this.buffer; - delete this.buffer; - return str; - } - getKey(memberName, xmlName) { - const key = xmlName ?? memberName; - if (this.settings.capitalizeKeys) { - return key[0].toUpperCase() + key.slice(1); - } - return key; - } - writeKey(key) { - if (key.endsWith(".")) { - key = key.slice(0, key.length - 1); - } - this.buffer += `&${protocols.extendedEncodeURIComponent(key)}=`; - } - writeValue(value) { - this.buffer += protocols.extendedEncodeURIComponent(value); - } -} - -class AwsQueryProtocol extends protocols.RpcProtocol { - options; - serializer; - deserializer; - mixin = new ProtocolLib(); - constructor(options) { - super({ - defaultNamespace: options.defaultNamespace, - }); - this.options = options; - const settings = { - timestampFormat: { - useTrait: true, - default: 5, - }, - httpBindings: false, - xmlNamespace: options.xmlNamespace, - serviceNamespace: options.defaultNamespace, - serializeEmptyLists: true, - }; - this.serializer = new QueryShapeSerializer(settings); - this.deserializer = new XmlShapeDeserializer(settings); - } - getShapeId() { - return "aws.protocols#awsQuery"; - } - setSerdeContext(serdeContext) { - this.serializer.setSerdeContext(serdeContext); - this.deserializer.setSerdeContext(serdeContext); - } - getPayloadCodec() { - throw new Error("AWSQuery protocol has no payload codec."); - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (!request.path.endsWith("/")) { - request.path += "/"; - } - Object.assign(request.headers, { - "content-type": `application/x-www-form-urlencoded`, - }); - if (schema.deref(operationSchema.input) === "unit" || !request.body) { - request.body = ""; - } - const action = operationSchema.name.split("#")[1] ?? operationSchema.name; - request.body = `Action=${action}&Version=${this.options.version}` + request.body; - if (request.body.endsWith("&")) { - request.body = request.body.slice(-1); - } - return request; - } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = schema.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes = await protocols.collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(15, bytes)); - } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; - } - const shortName = operationSchema.name.split("#")[1] ?? operationSchema.name; - const awsQueryResultKey = ns.isStructSchema() && this.useNestedResult() ? shortName + "Result" : undefined; - const bytes = await protocols.collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(ns, bytes, awsQueryResultKey)); - } - const output = { - $metadata: this.deserializeMetadata(response), - ...dataObject, - }; - return output; - } - useNestedResult() { - return true; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = this.loadQueryErrorCode(response, dataObject) ?? "Unknown"; - const errorData = this.loadQueryError(dataObject); - const message = this.loadQueryErrorMessage(dataObject); - errorData.message = message; - errorData.Error = { - Type: errorData.Type, - Code: errorData.Code, - Message: message, - }; - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, errorData, metadata, (registry, errorName) => { - try { - return registry.getSchema(errorName); - } - catch (e) { - return registry.find((schema$1) => schema.NormalizedSchema.of(schema$1).getMergedTraits().awsQueryError?.[0] === errorName); - } - }); - const ns = schema.NormalizedSchema.of(errorSchema); - const ErrorCtor = schema.TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; - const exception = new ErrorCtor(message); - const output = { - Error: errorData.Error, - }; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().xmlName ?? name; - const value = errorData[target] ?? dataObject[target]; - output[name] = this.deserializer.readSchema(member, value); - } - throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { - $fault: ns.getMergedTraits().error, - message, - }, output), dataObject); - } - loadQueryErrorCode(output, data) { - const code = (data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error)?.Code; - if (code !== undefined) { - return code; - } - if (output.statusCode == 404) { - return "NotFound"; - } - } - loadQueryError(data) { - return data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error; - } - loadQueryErrorMessage(data) { - const errorData = this.loadQueryError(data); - return errorData?.message ?? errorData?.Message ?? data.message ?? data.Message ?? "Unknown"; - } - getDefaultContentType() { - return "application/x-www-form-urlencoded"; - } -} - -class AwsEc2QueryProtocol extends AwsQueryProtocol { - options; - constructor(options) { - super(options); - this.options = options; - const ec2Settings = { - capitalizeKeys: true, - flattenLists: true, - serializeEmptyLists: false, - }; - Object.assign(this.serializer.settings, ec2Settings); - } - useNestedResult() { - return false; - } -} - -const parseXmlBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { - if (encoded.length) { - let parsedObj; - try { - parsedObj = xmlBuilder.parseXML(encoded); - } - catch (e) { - if (e && typeof e === "object") { - Object.defineProperty(e, "$responseBodyText", { - value: encoded, - }); - } - throw e; - } - const textNodeName = "#text"; - const key = Object.keys(parsedObj)[0]; - const parsedObjToReturn = parsedObj[key]; - if (parsedObjToReturn[textNodeName]) { - parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; - delete parsedObjToReturn[textNodeName]; - } - return smithyClient.getValueFromTextNode(parsedObjToReturn); - } - return {}; -}); -const parseXmlErrorBody = async (errorBody, context) => { - const value = await parseXmlBody(errorBody, context); - if (value.Error) { - value.Error.message = value.Error.message ?? value.Error.Message; - } - return value; -}; -const loadRestXmlErrorCode = (output, data) => { - if (data?.Error?.Code !== undefined) { - return data.Error.Code; - } - if (data?.Code !== undefined) { - return data.Code; - } - if (output.statusCode == 404) { - return "NotFound"; - } -}; - -class XmlShapeSerializer extends SerdeContextConfig { - settings; - stringBuffer; - byteBuffer; - buffer; - constructor(settings) { - super(); - this.settings = settings; - } - write(schema$1, value) { - const ns = schema.NormalizedSchema.of(schema$1); - if (ns.isStringSchema() && typeof value === "string") { - this.stringBuffer = value; - } - else if (ns.isBlobSchema()) { - this.byteBuffer = - "byteLength" in value - ? value - : (this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(value); - } - else { - this.buffer = this.writeStruct(ns, value, undefined); - const traits = ns.getMergedTraits(); - if (traits.httpPayload && !traits.xmlName) { - this.buffer.withName(ns.getName()); - } - } - } - flush() { - if (this.byteBuffer !== undefined) { - const bytes = this.byteBuffer; - delete this.byteBuffer; - return bytes; - } - if (this.stringBuffer !== undefined) { - const str = this.stringBuffer; - delete this.stringBuffer; - return str; - } - const buffer = this.buffer; - if (this.settings.xmlNamespace) { - if (!buffer?.attributes?.["xmlns"]) { - buffer.addAttribute("xmlns", this.settings.xmlNamespace); - } - } - delete this.buffer; - return buffer.toString(); - } - writeStruct(ns, value, parentXmlns) { - const traits = ns.getMergedTraits(); - const name = ns.isMemberSchema() && !traits.httpPayload - ? ns.getMemberTraits().xmlName ?? ns.getMemberName() - : traits.xmlName ?? ns.getName(); - if (!name || !ns.isStructSchema()) { - throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns.getName(true)}.`); - } - const structXmlNode = xmlBuilder.XmlNode.of(name); - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); - for (const [memberName, memberSchema] of ns.structIterator()) { - const val = value[memberName]; - if (val != null || memberSchema.isIdempotencyToken()) { - if (memberSchema.getMergedTraits().xmlAttribute) { - structXmlNode.addAttribute(memberSchema.getMergedTraits().xmlName ?? memberName, this.writeSimple(memberSchema, val)); - continue; - } - if (memberSchema.isListSchema()) { - this.writeList(memberSchema, val, structXmlNode, xmlns); - } - else if (memberSchema.isMapSchema()) { - this.writeMap(memberSchema, val, structXmlNode, xmlns); - } - else if (memberSchema.isStructSchema()) { - structXmlNode.addChildNode(this.writeStruct(memberSchema, val, xmlns)); - } - else { - const memberNode = xmlBuilder.XmlNode.of(memberSchema.getMergedTraits().xmlName ?? memberSchema.getMemberName()); - this.writeSimpleInto(memberSchema, val, memberNode, xmlns); - structXmlNode.addChildNode(memberNode); - } - } - } - if (xmlns) { - structXmlNode.addAttribute(xmlnsAttr, xmlns); - } - return structXmlNode; - } - writeList(listMember, array, container, parentXmlns) { - if (!listMember.isMemberSchema()) { - throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${listMember.getName(true)}`); - } - const listTraits = listMember.getMergedTraits(); - const listValueSchema = listMember.getValueSchema(); - const listValueTraits = listValueSchema.getMergedTraits(); - const sparse = !!listValueTraits.sparse; - const flat = !!listTraits.xmlFlattened; - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(listMember, parentXmlns); - const writeItem = (container, value) => { - if (listValueSchema.isListSchema()) { - this.writeList(listValueSchema, Array.isArray(value) ? value : [value], container, xmlns); - } - else if (listValueSchema.isMapSchema()) { - this.writeMap(listValueSchema, value, container, xmlns); - } - else if (listValueSchema.isStructSchema()) { - const struct = this.writeStruct(listValueSchema, value, xmlns); - container.addChildNode(struct.withName(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member")); - } - else { - const listItemNode = xmlBuilder.XmlNode.of(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member"); - this.writeSimpleInto(listValueSchema, value, listItemNode, xmlns); - container.addChildNode(listItemNode); - } - }; - if (flat) { - for (const value of array) { - if (sparse || value != null) { - writeItem(container, value); - } - } - } - else { - const listNode = xmlBuilder.XmlNode.of(listTraits.xmlName ?? listMember.getMemberName()); - if (xmlns) { - listNode.addAttribute(xmlnsAttr, xmlns); - } - for (const value of array) { - if (sparse || value != null) { - writeItem(listNode, value); - } - } - container.addChildNode(listNode); - } - } - writeMap(mapMember, map, container, parentXmlns, containerIsMap = false) { - if (!mapMember.isMemberSchema()) { - throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${mapMember.getName(true)}`); - } - const mapTraits = mapMember.getMergedTraits(); - const mapKeySchema = mapMember.getKeySchema(); - const mapKeyTraits = mapKeySchema.getMergedTraits(); - const keyTag = mapKeyTraits.xmlName ?? "key"; - const mapValueSchema = mapMember.getValueSchema(); - const mapValueTraits = mapValueSchema.getMergedTraits(); - const valueTag = mapValueTraits.xmlName ?? "value"; - const sparse = !!mapValueTraits.sparse; - const flat = !!mapTraits.xmlFlattened; - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(mapMember, parentXmlns); - const addKeyValue = (entry, key, val) => { - const keyNode = xmlBuilder.XmlNode.of(keyTag, key); - const [keyXmlnsAttr, keyXmlns] = this.getXmlnsAttribute(mapKeySchema, xmlns); - if (keyXmlns) { - keyNode.addAttribute(keyXmlnsAttr, keyXmlns); - } - entry.addChildNode(keyNode); - let valueNode = xmlBuilder.XmlNode.of(valueTag); - if (mapValueSchema.isListSchema()) { - this.writeList(mapValueSchema, val, valueNode, xmlns); - } - else if (mapValueSchema.isMapSchema()) { - this.writeMap(mapValueSchema, val, valueNode, xmlns, true); - } - else if (mapValueSchema.isStructSchema()) { - valueNode = this.writeStruct(mapValueSchema, val, xmlns); - } - else { - this.writeSimpleInto(mapValueSchema, val, valueNode, xmlns); - } - entry.addChildNode(valueNode); - }; - if (flat) { - for (const [key, val] of Object.entries(map)) { - if (sparse || val != null) { - const entry = xmlBuilder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); - addKeyValue(entry, key, val); - container.addChildNode(entry); - } - } - } - else { - let mapNode; - if (!containerIsMap) { - mapNode = xmlBuilder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); - if (xmlns) { - mapNode.addAttribute(xmlnsAttr, xmlns); - } - container.addChildNode(mapNode); - } - for (const [key, val] of Object.entries(map)) { - if (sparse || val != null) { - const entry = xmlBuilder.XmlNode.of("entry"); - addKeyValue(entry, key, val); - (containerIsMap ? container : mapNode).addChildNode(entry); - } - } - } - } - writeSimple(_schema, value) { - if (null === value) { - throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value."); - } - const ns = schema.NormalizedSchema.of(_schema); - let nodeContents = null; - if (value && typeof value === "object") { - if (ns.isBlobSchema()) { - nodeContents = (this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value); - } - else if (ns.isTimestampSchema() && value instanceof Date) { - const format = protocols.determineTimestampFormat(ns, this.settings); - switch (format) { - case 5: - nodeContents = value.toISOString().replace(".000Z", "Z"); - break; - case 6: - nodeContents = smithyClient.dateToUtcString(value); - break; - case 7: - nodeContents = String(value.getTime() / 1000); - break; - default: - console.warn("Missing timestamp format, using http date", value); - nodeContents = smithyClient.dateToUtcString(value); - break; - } - } - else if (ns.isBigDecimalSchema() && value) { - if (value instanceof serde.NumericValue) { - return value.string; - } - return String(value); - } - else if (ns.isMapSchema() || ns.isListSchema()) { - throw new Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead."); - } - else { - throw new Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns.getName(true)}`); - } - } - if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { - nodeContents = String(value); - } - if (ns.isStringSchema()) { - if (value === undefined && ns.isIdempotencyToken()) { - nodeContents = serde.generateIdempotencyToken(); - } - else { - nodeContents = String(value); - } - } - if (nodeContents === null) { - throw new Error(`Unhandled schema-value pair ${ns.getName(true)}=${value}`); - } - return nodeContents; - } - writeSimpleInto(_schema, value, into, parentXmlns) { - const nodeContents = this.writeSimple(_schema, value); - const ns = schema.NormalizedSchema.of(_schema); - const content = new xmlBuilder.XmlText(nodeContents); - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); - if (xmlns) { - into.addAttribute(xmlnsAttr, xmlns); - } - into.addChildNode(content); - } - getXmlnsAttribute(ns, parentXmlns) { - const traits = ns.getMergedTraits(); - const [prefix, xmlns] = traits.xmlNamespace ?? []; - if (xmlns && xmlns !== parentXmlns) { - return [prefix ? `xmlns:${prefix}` : "xmlns", xmlns]; - } - return [void 0, void 0]; - } -} - -class XmlCodec extends SerdeContextConfig { - settings; - constructor(settings) { - super(); - this.settings = settings; - } - createSerializer() { - const serializer = new XmlShapeSerializer(this.settings); - serializer.setSerdeContext(this.serdeContext); - return serializer; - } - createDeserializer() { - const deserializer = new XmlShapeDeserializer(this.settings); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; - } -} - -class AwsRestXmlProtocol extends protocols.HttpBindingProtocol { - codec; - serializer; - deserializer; - mixin = new ProtocolLib(); - constructor(options) { - super(options); - const settings = { - timestampFormat: { - useTrait: true, - default: 5, - }, - httpBindings: true, - xmlNamespace: options.xmlNamespace, - serviceNamespace: options.defaultNamespace, - }; - this.codec = new XmlCodec(settings); - this.serializer = new protocols.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); - this.deserializer = new protocols.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); - } - getPayloadCodec() { - return this.codec; - } - getShapeId() { - return "aws.protocols#restXml"; - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - const inputSchema = schema.NormalizedSchema.of(operationSchema.input); - if (!request.headers["content-type"]) { - const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); - if (contentType) { - request.headers["content-type"] = contentType; - } - } - if (request.headers["content-type"] === this.getDefaultContentType()) { - if (typeof request.body === "string") { - request.body = '' + request.body; - } - } - return request; - } - async deserializeResponse(operationSchema, context, response) { - return super.deserializeResponse(operationSchema, context, response); - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestXmlErrorCode(response, dataObject) ?? "Unknown"; - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); - const ns = schema.NormalizedSchema.of(errorSchema); - const message = dataObject.Error?.message ?? dataObject.Error?.Message ?? dataObject.message ?? dataObject.Message ?? "Unknown"; - const ErrorCtor = schema.TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; - const exception = new ErrorCtor(message); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().xmlName ?? name; - const value = dataObject.Error?.[target] ?? dataObject[target]; - output[name] = this.codec.createDeserializer().readSchema(member, value); - } - throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { - $fault: ns.getMergedTraits().error, - message, - }, output), dataObject); - } - getDefaultContentType() { - return "application/xml"; - } -} - -exports.AWSSDKSigV4Signer = AWSSDKSigV4Signer; -exports.AwsEc2QueryProtocol = AwsEc2QueryProtocol; -exports.AwsJson1_0Protocol = AwsJson1_0Protocol; -exports.AwsJson1_1Protocol = AwsJson1_1Protocol; -exports.AwsJsonRpcProtocol = AwsJsonRpcProtocol; -exports.AwsQueryProtocol = AwsQueryProtocol; -exports.AwsRestJsonProtocol = AwsRestJsonProtocol; -exports.AwsRestXmlProtocol = AwsRestXmlProtocol; -exports.AwsSdkSigV4ASigner = AwsSdkSigV4ASigner; -exports.AwsSdkSigV4Signer = AwsSdkSigV4Signer; -exports.AwsSmithyRpcV2CborProtocol = AwsSmithyRpcV2CborProtocol; -exports.JsonCodec = JsonCodec; -exports.JsonShapeDeserializer = JsonShapeDeserializer; -exports.JsonShapeSerializer = JsonShapeSerializer; -exports.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = NODE_AUTH_SCHEME_PREFERENCE_OPTIONS; -exports.NODE_SIGV4A_CONFIG_OPTIONS = NODE_SIGV4A_CONFIG_OPTIONS; -exports.XmlCodec = XmlCodec; -exports.XmlShapeDeserializer = XmlShapeDeserializer; -exports.XmlShapeSerializer = XmlShapeSerializer; -exports._toBool = _toBool; -exports._toNum = _toNum; -exports._toStr = _toStr; -exports.awsExpectUnion = awsExpectUnion; -exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; -exports.getBearerTokenEnvKey = getBearerTokenEnvKey; -exports.loadRestJsonErrorCode = loadRestJsonErrorCode; -exports.loadRestXmlErrorCode = loadRestXmlErrorCode; -exports.parseJsonBody = parseJsonBody; -exports.parseJsonErrorBody = parseJsonErrorBody; -exports.parseXmlBody = parseXmlBody; -exports.parseXmlErrorBody = parseXmlErrorBody; -exports.resolveAWSSDKSigV4Config = resolveAWSSDKSigV4Config; -exports.resolveAwsSdkSigV4AConfig = resolveAwsSdkSigV4AConfig; -exports.resolveAwsSdkSigV4Config = resolveAwsSdkSigV4Config; -exports.setCredentialFeature = setCredentialFeature; -exports.setFeature = setFeature; -exports.setTokenFeature = setTokenFeature; -exports.state = state; -exports.validateSigningProperties = validateSigningProperties; diff --git a/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/client/index.js b/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/client/index.js deleted file mode 100644 index 5c8510e6..00000000 --- a/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/client/index.js +++ /dev/null @@ -1,51 +0,0 @@ -'use strict'; - -const state = { - warningEmitted: false, -}; -const emitWarningIfUnsupportedVersion = (version) => { - if (version && !state.warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 18) { - state.warningEmitted = true; - process.emitWarning(`NodeDeprecationWarning: The AWS SDK for JavaScript (v3) will -no longer support Node.js 16.x on January 6, 2025. - -To continue receiving updates to AWS services, bug fixes, and security -updates please upgrade to a supported Node.js LTS version. - -More information can be found at: https://a.co/74kJMmI`); - } -}; - -function setCredentialFeature(credentials, feature, value) { - if (!credentials.$source) { - credentials.$source = {}; - } - credentials.$source[feature] = value; - return credentials; -} - -function setFeature(context, feature, value) { - if (!context.__aws_sdk_context) { - context.__aws_sdk_context = { - features: {}, - }; - } - else if (!context.__aws_sdk_context.features) { - context.__aws_sdk_context.features = {}; - } - context.__aws_sdk_context.features[feature] = value; -} - -function setTokenFeature(token, feature, value) { - if (!token.$source) { - token.$source = {}; - } - token.$source[feature] = value; - return token; -} - -exports.emitWarningIfUnsupportedVersion = emitWarningIfUnsupportedVersion; -exports.setCredentialFeature = setCredentialFeature; -exports.setFeature = setFeature; -exports.setTokenFeature = setTokenFeature; -exports.state = state; diff --git a/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/httpAuthSchemes/index.js b/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/httpAuthSchemes/index.js deleted file mode 100644 index 229f37b0..00000000 --- a/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/httpAuthSchemes/index.js +++ /dev/null @@ -1,299 +0,0 @@ -'use strict'; - -var protocolHttp = require('@smithy/protocol-http'); -var core = require('@smithy/core'); -var propertyProvider = require('@smithy/property-provider'); -var client = require('@aws-sdk/core/client'); -var signatureV4 = require('@smithy/signature-v4'); - -const getDateHeader = (response) => protocolHttp.HttpResponse.isInstance(response) ? response.headers?.date ?? response.headers?.Date : undefined; - -const getSkewCorrectedDate = (systemClockOffset) => new Date(Date.now() + systemClockOffset); - -const isClockSkewed = (clockTime, systemClockOffset) => Math.abs(getSkewCorrectedDate(systemClockOffset).getTime() - clockTime) >= 300000; - -const getUpdatedSystemClockOffset = (clockTime, currentSystemClockOffset) => { - const clockTimeInMs = Date.parse(clockTime); - if (isClockSkewed(clockTimeInMs, currentSystemClockOffset)) { - return clockTimeInMs - Date.now(); - } - return currentSystemClockOffset; -}; - -const throwSigningPropertyError = (name, property) => { - if (!property) { - throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`); - } - return property; -}; -const validateSigningProperties = async (signingProperties) => { - const context = throwSigningPropertyError("context", signingProperties.context); - const config = throwSigningPropertyError("config", signingProperties.config); - const authScheme = context.endpointV2?.properties?.authSchemes?.[0]; - const signerFunction = throwSigningPropertyError("signer", config.signer); - const signer = await signerFunction(authScheme); - const signingRegion = signingProperties?.signingRegion; - const signingRegionSet = signingProperties?.signingRegionSet; - const signingName = signingProperties?.signingName; - return { - config, - signer, - signingRegion, - signingRegionSet, - signingName, - }; -}; -class AwsSdkSigV4Signer { - async sign(httpRequest, identity, signingProperties) { - if (!protocolHttp.HttpRequest.isInstance(httpRequest)) { - throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); - } - const validatedProps = await validateSigningProperties(signingProperties); - const { config, signer } = validatedProps; - let { signingRegion, signingName } = validatedProps; - const handlerExecutionContext = signingProperties.context; - if (handlerExecutionContext?.authSchemes?.length ?? 0 > 1) { - const [first, second] = handlerExecutionContext.authSchemes; - if (first?.name === "sigv4a" && second?.name === "sigv4") { - signingRegion = second?.signingRegion ?? signingRegion; - signingName = second?.signingName ?? signingName; - } - } - const signedRequest = await signer.sign(httpRequest, { - signingDate: getSkewCorrectedDate(config.systemClockOffset), - signingRegion: signingRegion, - signingService: signingName, - }); - return signedRequest; - } - errorHandler(signingProperties) { - return (error) => { - const serverTime = error.ServerTime ?? getDateHeader(error.$response); - if (serverTime) { - const config = throwSigningPropertyError("config", signingProperties.config); - const initialSystemClockOffset = config.systemClockOffset; - config.systemClockOffset = getUpdatedSystemClockOffset(serverTime, config.systemClockOffset); - const clockSkewCorrected = config.systemClockOffset !== initialSystemClockOffset; - if (clockSkewCorrected && error.$metadata) { - error.$metadata.clockSkewCorrected = true; - } - } - throw error; - }; - } - successHandler(httpResponse, signingProperties) { - const dateHeader = getDateHeader(httpResponse); - if (dateHeader) { - const config = throwSigningPropertyError("config", signingProperties.config); - config.systemClockOffset = getUpdatedSystemClockOffset(dateHeader, config.systemClockOffset); - } - } -} -const AWSSDKSigV4Signer = AwsSdkSigV4Signer; - -class AwsSdkSigV4ASigner extends AwsSdkSigV4Signer { - async sign(httpRequest, identity, signingProperties) { - if (!protocolHttp.HttpRequest.isInstance(httpRequest)) { - throw new Error("The request is not an instance of `HttpRequest` and cannot be signed"); - } - const { config, signer, signingRegion, signingRegionSet, signingName } = await validateSigningProperties(signingProperties); - const configResolvedSigningRegionSet = await config.sigv4aSigningRegionSet?.(); - const multiRegionOverride = (configResolvedSigningRegionSet ?? - signingRegionSet ?? [signingRegion]).join(","); - const signedRequest = await signer.sign(httpRequest, { - signingDate: getSkewCorrectedDate(config.systemClockOffset), - signingRegion: multiRegionOverride, - signingService: signingName, - }); - return signedRequest; - } -} - -const getArrayForCommaSeparatedString = (str) => typeof str === "string" && str.length > 0 ? str.split(",").map((item) => item.trim()) : []; - -const getBearerTokenEnvKey = (signingName) => `AWS_BEARER_TOKEN_${signingName.replace(/[\s-]/g, "_").toUpperCase()}`; - -const NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY = "AWS_AUTH_SCHEME_PREFERENCE"; -const NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY = "auth_scheme_preference"; -const NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = { - environmentVariableSelector: (env, options) => { - if (options?.signingName) { - const bearerTokenKey = getBearerTokenEnvKey(options.signingName); - if (bearerTokenKey in env) - return ["httpBearerAuth"]; - } - if (!(NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY in env)) - return undefined; - return getArrayForCommaSeparatedString(env[NODE_AUTH_SCHEME_PREFERENCE_ENV_KEY]); - }, - configFileSelector: (profile) => { - if (!(NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY in profile)) - return undefined; - return getArrayForCommaSeparatedString(profile[NODE_AUTH_SCHEME_PREFERENCE_CONFIG_KEY]); - }, - default: [], -}; - -const resolveAwsSdkSigV4AConfig = (config) => { - config.sigv4aSigningRegionSet = core.normalizeProvider(config.sigv4aSigningRegionSet); - return config; -}; -const NODE_SIGV4A_CONFIG_OPTIONS = { - environmentVariableSelector(env) { - if (env.AWS_SIGV4A_SIGNING_REGION_SET) { - return env.AWS_SIGV4A_SIGNING_REGION_SET.split(",").map((_) => _.trim()); - } - throw new propertyProvider.ProviderError("AWS_SIGV4A_SIGNING_REGION_SET not set in env.", { - tryNextLink: true, - }); - }, - configFileSelector(profile) { - if (profile.sigv4a_signing_region_set) { - return (profile.sigv4a_signing_region_set ?? "").split(",").map((_) => _.trim()); - } - throw new propertyProvider.ProviderError("sigv4a_signing_region_set not set in profile.", { - tryNextLink: true, - }); - }, - default: undefined, -}; - -const resolveAwsSdkSigV4Config = (config) => { - let inputCredentials = config.credentials; - let isUserSupplied = !!config.credentials; - let resolvedCredentials = undefined; - Object.defineProperty(config, "credentials", { - set(credentials) { - if (credentials && credentials !== inputCredentials && credentials !== resolvedCredentials) { - isUserSupplied = true; - } - inputCredentials = credentials; - const memoizedProvider = normalizeCredentialProvider(config, { - credentials: inputCredentials, - credentialDefaultProvider: config.credentialDefaultProvider, - }); - const boundProvider = bindCallerConfig(config, memoizedProvider); - if (isUserSupplied && !boundProvider.attributed) { - resolvedCredentials = async (options) => boundProvider(options).then((creds) => client.setCredentialFeature(creds, "CREDENTIALS_CODE", "e")); - resolvedCredentials.memoized = boundProvider.memoized; - resolvedCredentials.configBound = boundProvider.configBound; - resolvedCredentials.attributed = true; - } - else { - resolvedCredentials = boundProvider; - } - }, - get() { - return resolvedCredentials; - }, - enumerable: true, - configurable: true, - }); - config.credentials = inputCredentials; - const { signingEscapePath = true, systemClockOffset = config.systemClockOffset || 0, sha256, } = config; - let signer; - if (config.signer) { - signer = core.normalizeProvider(config.signer); - } - else if (config.regionInfoProvider) { - signer = () => core.normalizeProvider(config.region)() - .then(async (region) => [ - (await config.regionInfoProvider(region, { - useFipsEndpoint: await config.useFipsEndpoint(), - useDualstackEndpoint: await config.useDualstackEndpoint(), - })) || {}, - region, - ]) - .then(([regionInfo, region]) => { - const { signingRegion, signingService } = regionInfo; - config.signingRegion = config.signingRegion || signingRegion || region; - config.signingName = config.signingName || signingService || config.serviceId; - const params = { - ...config, - credentials: config.credentials, - region: config.signingRegion, - service: config.signingName, - sha256, - uriEscapePath: signingEscapePath, - }; - const SignerCtor = config.signerConstructor || signatureV4.SignatureV4; - return new SignerCtor(params); - }); - } - else { - signer = async (authScheme) => { - authScheme = Object.assign({}, { - name: "sigv4", - signingName: config.signingName || config.defaultSigningName, - signingRegion: await core.normalizeProvider(config.region)(), - properties: {}, - }, authScheme); - const signingRegion = authScheme.signingRegion; - const signingService = authScheme.signingName; - config.signingRegion = config.signingRegion || signingRegion; - config.signingName = config.signingName || signingService || config.serviceId; - const params = { - ...config, - credentials: config.credentials, - region: config.signingRegion, - service: config.signingName, - sha256, - uriEscapePath: signingEscapePath, - }; - const SignerCtor = config.signerConstructor || signatureV4.SignatureV4; - return new SignerCtor(params); - }; - } - const resolvedConfig = Object.assign(config, { - systemClockOffset, - signingEscapePath, - signer, - }); - return resolvedConfig; -}; -const resolveAWSSDKSigV4Config = resolveAwsSdkSigV4Config; -function normalizeCredentialProvider(config, { credentials, credentialDefaultProvider, }) { - let credentialsProvider; - if (credentials) { - if (!credentials?.memoized) { - credentialsProvider = core.memoizeIdentityProvider(credentials, core.isIdentityExpired, core.doesIdentityRequireRefresh); - } - else { - credentialsProvider = credentials; - } - } - else { - if (credentialDefaultProvider) { - credentialsProvider = core.normalizeProvider(credentialDefaultProvider(Object.assign({}, config, { - parentClientConfig: config, - }))); - } - else { - credentialsProvider = async () => { - throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured."); - }; - } - } - credentialsProvider.memoized = true; - return credentialsProvider; -} -function bindCallerConfig(config, credentialsProvider) { - if (credentialsProvider.configBound) { - return credentialsProvider; - } - const fn = async (options) => credentialsProvider({ ...options, callerClientConfig: config }); - fn.memoized = credentialsProvider.memoized; - fn.configBound = true; - return fn; -} - -exports.AWSSDKSigV4Signer = AWSSDKSigV4Signer; -exports.AwsSdkSigV4ASigner = AwsSdkSigV4ASigner; -exports.AwsSdkSigV4Signer = AwsSdkSigV4Signer; -exports.NODE_AUTH_SCHEME_PREFERENCE_OPTIONS = NODE_AUTH_SCHEME_PREFERENCE_OPTIONS; -exports.NODE_SIGV4A_CONFIG_OPTIONS = NODE_SIGV4A_CONFIG_OPTIONS; -exports.getBearerTokenEnvKey = getBearerTokenEnvKey; -exports.resolveAWSSDKSigV4Config = resolveAWSSDKSigV4Config; -exports.resolveAwsSdkSigV4AConfig = resolveAwsSdkSigV4AConfig; -exports.resolveAwsSdkSigV4Config = resolveAwsSdkSigV4Config; -exports.validateSigningProperties = validateSigningProperties; diff --git a/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/protocols/index.js b/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/protocols/index.js deleted file mode 100644 index c0e99791..00000000 --- a/claude-code-source/node_modules/@aws-sdk/core/dist-cjs/submodules/protocols/index.js +++ /dev/null @@ -1,1655 +0,0 @@ -'use strict'; - -var cbor = require('@smithy/core/cbor'); -var schema = require('@smithy/core/schema'); -var smithyClient = require('@smithy/smithy-client'); -var protocols = require('@smithy/core/protocols'); -var serde = require('@smithy/core/serde'); -var utilBase64 = require('@smithy/util-base64'); -var utilUtf8 = require('@smithy/util-utf8'); -var xmlBuilder = require('@aws-sdk/xml-builder'); - -class ProtocolLib { - queryCompat; - constructor(queryCompat = false) { - this.queryCompat = queryCompat; - } - resolveRestContentType(defaultContentType, inputSchema) { - const members = inputSchema.getMemberSchemas(); - const httpPayloadMember = Object.values(members).find((m) => { - return !!m.getMergedTraits().httpPayload; - }); - if (httpPayloadMember) { - const mediaType = httpPayloadMember.getMergedTraits().mediaType; - if (mediaType) { - return mediaType; - } - else if (httpPayloadMember.isStringSchema()) { - return "text/plain"; - } - else if (httpPayloadMember.isBlobSchema()) { - return "application/octet-stream"; - } - else { - return defaultContentType; - } - } - else if (!inputSchema.isUnitSchema()) { - const hasBody = Object.values(members).find((m) => { - const { httpQuery, httpQueryParams, httpHeader, httpLabel, httpPrefixHeaders } = m.getMergedTraits(); - const noPrefixHeaders = httpPrefixHeaders === void 0; - return !httpQuery && !httpQueryParams && !httpHeader && !httpLabel && noPrefixHeaders; - }); - if (hasBody) { - return defaultContentType; - } - } - } - async getErrorSchemaOrThrowBaseException(errorIdentifier, defaultNamespace, response, dataObject, metadata, getErrorSchema) { - let namespace = defaultNamespace; - let errorName = errorIdentifier; - if (errorIdentifier.includes("#")) { - [namespace, errorName] = errorIdentifier.split("#"); - } - const errorMetadata = { - $metadata: metadata, - $fault: response.statusCode < 500 ? "client" : "server", - }; - const registry = schema.TypeRegistry.for(namespace); - try { - const errorSchema = getErrorSchema?.(registry, errorName) ?? registry.getSchema(errorIdentifier); - return { errorSchema, errorMetadata }; - } - catch (e) { - dataObject.message = dataObject.message ?? dataObject.Message ?? "UnknownError"; - const synthetic = schema.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace); - const baseExceptionSchema = synthetic.getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = synthetic.getErrorCtor(baseExceptionSchema) ?? Error; - throw this.decorateServiceException(Object.assign(new ErrorCtor({ name: errorName }), errorMetadata), dataObject); - } - throw this.decorateServiceException(Object.assign(new Error(errorName), errorMetadata), dataObject); - } - } - decorateServiceException(exception, additions = {}) { - if (this.queryCompat) { - const msg = exception.Message ?? additions.Message; - const error = smithyClient.decorateServiceException(exception, additions); - if (msg) { - error.Message = msg; - error.message = msg; - } - return error; - } - return smithyClient.decorateServiceException(exception, additions); - } - setQueryCompatError(output, response) { - const queryErrorHeader = response.headers?.["x-amzn-query-error"]; - if (output !== undefined && queryErrorHeader != null) { - const [Code, Type] = queryErrorHeader.split(";"); - const entries = Object.entries(output); - const Error = { - Code, - Type, - }; - Object.assign(output, Error); - for (const [k, v] of entries) { - Error[k] = v; - } - delete Error.__type; - output.Error = Error; - } - } - queryCompatOutput(queryCompatErrorData, errorData) { - if (queryCompatErrorData.Error) { - errorData.Error = queryCompatErrorData.Error; - } - if (queryCompatErrorData.Type) { - errorData.Type = queryCompatErrorData.Type; - } - if (queryCompatErrorData.Code) { - errorData.Code = queryCompatErrorData.Code; - } - } -} - -class AwsSmithyRpcV2CborProtocol extends cbor.SmithyRpcV2CborProtocol { - awsQueryCompatible; - mixin; - constructor({ defaultNamespace, awsQueryCompatible, }) { - super({ defaultNamespace }); - this.awsQueryCompatible = !!awsQueryCompatible; - this.mixin = new ProtocolLib(this.awsQueryCompatible); - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (this.awsQueryCompatible) { - request.headers["x-amzn-query-mode"] = "true"; - } - return request; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - if (this.awsQueryCompatible) { - this.mixin.setQueryCompatError(dataObject, response); - } - const errorName = cbor.loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown"; - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorName, this.options.defaultNamespace, response, dataObject, metadata); - const ns = schema.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const ErrorCtor = schema.TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; - const exception = new ErrorCtor(message); - const output = {}; - for (const [name, member] of ns.structIterator()) { - output[name] = this.deserializer.readValue(member, dataObject[name]); - } - if (this.awsQueryCompatible) { - this.mixin.queryCompatOutput(dataObject, output); - } - throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { - $fault: ns.getMergedTraits().error, - message, - }, output), dataObject); - } -} - -const _toStr = (val) => { - if (val == null) { - return val; - } - if (typeof val === "number" || typeof val === "bigint") { - const warning = new Error(`Received number ${val} where a string was expected.`); - warning.name = "Warning"; - console.warn(warning); - return String(val); - } - if (typeof val === "boolean") { - const warning = new Error(`Received boolean ${val} where a string was expected.`); - warning.name = "Warning"; - console.warn(warning); - return String(val); - } - return val; -}; -const _toBool = (val) => { - if (val == null) { - return val; - } - if (typeof val === "string") { - const lowercase = val.toLowerCase(); - if (val !== "" && lowercase !== "false" && lowercase !== "true") { - const warning = new Error(`Received string "${val}" where a boolean was expected.`); - warning.name = "Warning"; - console.warn(warning); - } - return val !== "" && lowercase !== "false"; - } - return val; -}; -const _toNum = (val) => { - if (val == null) { - return val; - } - if (typeof val === "string") { - const num = Number(val); - if (num.toString() !== val) { - const warning = new Error(`Received string "${val}" where a number was expected.`); - warning.name = "Warning"; - console.warn(warning); - return val; - } - return num; - } - return val; -}; - -class SerdeContextConfig { - serdeContext; - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - } -} - -function jsonReviver(key, value, context) { - if (context?.source) { - const numericString = context.source; - if (typeof value === "number") { - if (value > Number.MAX_SAFE_INTEGER || value < Number.MIN_SAFE_INTEGER || numericString !== String(value)) { - const isFractional = numericString.includes("."); - if (isFractional) { - return new serde.NumericValue(numericString, "bigDecimal"); - } - else { - return BigInt(numericString); - } - } - } - } - return value; -} - -const collectBodyString = (streamBody, context) => smithyClient.collectBody(streamBody, context).then((body) => (context?.utf8Encoder ?? utilUtf8.toUtf8)(body)); - -const parseJsonBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { - if (encoded.length) { - try { - return JSON.parse(encoded); - } - catch (e) { - if (e?.name === "SyntaxError") { - Object.defineProperty(e, "$responseBodyText", { - value: encoded, - }); - } - throw e; - } - } - return {}; -}); -const parseJsonErrorBody = async (errorBody, context) => { - const value = await parseJsonBody(errorBody, context); - value.message = value.message ?? value.Message; - return value; -}; -const loadRestJsonErrorCode = (output, data) => { - const findKey = (object, key) => Object.keys(object).find((k) => k.toLowerCase() === key.toLowerCase()); - const sanitizeErrorCode = (rawValue) => { - let cleanValue = rawValue; - if (typeof cleanValue === "number") { - cleanValue = cleanValue.toString(); - } - if (cleanValue.indexOf(",") >= 0) { - cleanValue = cleanValue.split(",")[0]; - } - if (cleanValue.indexOf(":") >= 0) { - cleanValue = cleanValue.split(":")[0]; - } - if (cleanValue.indexOf("#") >= 0) { - cleanValue = cleanValue.split("#")[1]; - } - return cleanValue; - }; - const headerKey = findKey(output.headers, "x-amzn-errortype"); - if (headerKey !== undefined) { - return sanitizeErrorCode(output.headers[headerKey]); - } - if (data && typeof data === "object") { - const codeKey = findKey(data, "code"); - if (codeKey && data[codeKey] !== undefined) { - return sanitizeErrorCode(data[codeKey]); - } - if (data["__type"] !== undefined) { - return sanitizeErrorCode(data["__type"]); - } - } -}; - -class JsonShapeDeserializer extends SerdeContextConfig { - settings; - constructor(settings) { - super(); - this.settings = settings; - } - async read(schema, data) { - return this._read(schema, typeof data === "string" ? JSON.parse(data, jsonReviver) : await parseJsonBody(data, this.serdeContext)); - } - readObject(schema, data) { - return this._read(schema, data); - } - _read(schema$1, value) { - const isObject = value !== null && typeof value === "object"; - const ns = schema.NormalizedSchema.of(schema$1); - if (ns.isListSchema() && Array.isArray(value)) { - const listMember = ns.getValueSchema(); - const out = []; - const sparse = !!ns.getMergedTraits().sparse; - for (const item of value) { - if (sparse || item != null) { - out.push(this._read(listMember, item)); - } - } - return out; - } - else if (ns.isMapSchema() && isObject) { - const mapMember = ns.getValueSchema(); - const out = {}; - const sparse = !!ns.getMergedTraits().sparse; - for (const [_k, _v] of Object.entries(value)) { - if (sparse || _v != null) { - out[_k] = this._read(mapMember, _v); - } - } - return out; - } - else if (ns.isStructSchema() && isObject) { - const out = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - const fromKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; - const deserializedValue = this._read(memberSchema, value[fromKey]); - if (deserializedValue != null) { - out[memberName] = deserializedValue; - } - } - return out; - } - if (ns.isBlobSchema() && typeof value === "string") { - return utilBase64.fromBase64(value); - } - const mediaType = ns.getMergedTraits().mediaType; - if (ns.isStringSchema() && typeof value === "string" && mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - return serde.LazyJsonString.from(value); - } - } - if (ns.isTimestampSchema() && value != null) { - const format = protocols.determineTimestampFormat(ns, this.settings); - switch (format) { - case 5: - return serde.parseRfc3339DateTimeWithOffset(value); - case 6: - return serde.parseRfc7231DateTime(value); - case 7: - return serde.parseEpochTimestamp(value); - default: - console.warn("Missing timestamp format, parsing value with Date constructor:", value); - return new Date(value); - } - } - if (ns.isBigIntegerSchema() && (typeof value === "number" || typeof value === "string")) { - return BigInt(value); - } - if (ns.isBigDecimalSchema() && value != undefined) { - if (value instanceof serde.NumericValue) { - return value; - } - const untyped = value; - if (untyped.type === "bigDecimal" && "string" in untyped) { - return new serde.NumericValue(untyped.string, untyped.type); - } - return new serde.NumericValue(String(value), "bigDecimal"); - } - if (ns.isNumericSchema() && typeof value === "string") { - switch (value) { - case "Infinity": - return Infinity; - case "-Infinity": - return -Infinity; - case "NaN": - return NaN; - } - } - if (ns.isDocumentSchema()) { - if (isObject) { - const out = Array.isArray(value) ? [] : {}; - for (const [k, v] of Object.entries(value)) { - if (v instanceof serde.NumericValue) { - out[k] = v; - } - else { - out[k] = this._read(ns, v); - } - } - return out; - } - else { - return structuredClone(value); - } - } - return value; - } -} - -const NUMERIC_CONTROL_CHAR = String.fromCharCode(925); -class JsonReplacer { - values = new Map(); - counter = 0; - stage = 0; - createReplacer() { - if (this.stage === 1) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer already created."); - } - if (this.stage === 2) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); - } - this.stage = 1; - return (key, value) => { - if (value instanceof serde.NumericValue) { - const v = `${NUMERIC_CONTROL_CHAR + "nv" + this.counter++}_` + value.string; - this.values.set(`"${v}"`, value.string); - return v; - } - if (typeof value === "bigint") { - const s = value.toString(); - const v = `${NUMERIC_CONTROL_CHAR + "b" + this.counter++}_` + s; - this.values.set(`"${v}"`, s); - return v; - } - return value; - }; - } - replaceInJson(json) { - if (this.stage === 0) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet."); - } - if (this.stage === 2) { - throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted."); - } - this.stage = 2; - if (this.counter === 0) { - return json; - } - for (const [key, value] of this.values) { - json = json.replace(key, value); - } - return json; - } -} - -class JsonShapeSerializer extends SerdeContextConfig { - settings; - buffer; - rootSchema; - constructor(settings) { - super(); - this.settings = settings; - } - write(schema$1, value) { - this.rootSchema = schema.NormalizedSchema.of(schema$1); - this.buffer = this._write(this.rootSchema, value); - } - writeDiscriminatedDocument(schema$1, value) { - this.write(schema$1, value); - if (typeof this.buffer === "object") { - this.buffer.__type = schema.NormalizedSchema.of(schema$1).getName(true); - } - } - flush() { - const { rootSchema } = this; - this.rootSchema = undefined; - if (rootSchema?.isStructSchema() || rootSchema?.isDocumentSchema()) { - const replacer = new JsonReplacer(); - return replacer.replaceInJson(JSON.stringify(this.buffer, replacer.createReplacer(), 0)); - } - return this.buffer; - } - _write(schema$1, value, container) { - const isObject = value !== null && typeof value === "object"; - const ns = schema.NormalizedSchema.of(schema$1); - if (ns.isListSchema() && Array.isArray(value)) { - const listMember = ns.getValueSchema(); - const out = []; - const sparse = !!ns.getMergedTraits().sparse; - for (const item of value) { - if (sparse || item != null) { - out.push(this._write(listMember, item)); - } - } - return out; - } - else if (ns.isMapSchema() && isObject) { - const mapMember = ns.getValueSchema(); - const out = {}; - const sparse = !!ns.getMergedTraits().sparse; - for (const [_k, _v] of Object.entries(value)) { - if (sparse || _v != null) { - out[_k] = this._write(mapMember, _v); - } - } - return out; - } - else if (ns.isStructSchema() && isObject) { - const out = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - const targetKey = this.settings.jsonName ? memberSchema.getMergedTraits().jsonName ?? memberName : memberName; - const serializableValue = this._write(memberSchema, value[memberName], ns); - if (serializableValue !== undefined) { - out[targetKey] = serializableValue; - } - } - return out; - } - if (value === null && container?.isStructSchema()) { - return void 0; - } - if ((ns.isBlobSchema() && (value instanceof Uint8Array || typeof value === "string")) || - (ns.isDocumentSchema() && value instanceof Uint8Array)) { - if (ns === this.rootSchema) { - return value; - } - return (this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value); - } - if ((ns.isTimestampSchema() || ns.isDocumentSchema()) && value instanceof Date) { - const format = protocols.determineTimestampFormat(ns, this.settings); - switch (format) { - case 5: - return value.toISOString().replace(".000Z", "Z"); - case 6: - return serde.dateToUtcString(value); - case 7: - return value.getTime() / 1000; - default: - console.warn("Missing timestamp format, using epoch seconds", value); - return value.getTime() / 1000; - } - } - if (ns.isNumericSchema() && typeof value === "number") { - if (Math.abs(value) === Infinity || isNaN(value)) { - return String(value); - } - } - if (ns.isStringSchema()) { - if (typeof value === "undefined" && ns.isIdempotencyToken()) { - return serde.generateIdempotencyToken(); - } - const mediaType = ns.getMergedTraits().mediaType; - if (value != null && mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - return serde.LazyJsonString.from(value); - } - } - } - if (ns.isDocumentSchema()) { - if (isObject) { - const out = Array.isArray(value) ? [] : {}; - for (const [k, v] of Object.entries(value)) { - if (v instanceof serde.NumericValue) { - out[k] = v; - } - else { - out[k] = this._write(ns, v); - } - } - return out; - } - else { - return structuredClone(value); - } - } - return value; - } -} - -class JsonCodec extends SerdeContextConfig { - settings; - constructor(settings) { - super(); - this.settings = settings; - } - createSerializer() { - const serializer = new JsonShapeSerializer(this.settings); - serializer.setSerdeContext(this.serdeContext); - return serializer; - } - createDeserializer() { - const deserializer = new JsonShapeDeserializer(this.settings); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; - } -} - -class AwsJsonRpcProtocol extends protocols.RpcProtocol { - serializer; - deserializer; - serviceTarget; - codec; - mixin; - awsQueryCompatible; - constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, }) { - super({ - defaultNamespace, - }); - this.serviceTarget = serviceTarget; - this.codec = new JsonCodec({ - timestampFormat: { - useTrait: true, - default: 7, - }, - jsonName: false, - }); - this.serializer = this.codec.createSerializer(); - this.deserializer = this.codec.createDeserializer(); - this.awsQueryCompatible = !!awsQueryCompatible; - this.mixin = new ProtocolLib(this.awsQueryCompatible); - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (!request.path.endsWith("/")) { - request.path += "/"; - } - Object.assign(request.headers, { - "content-type": `application/x-amz-json-${this.getJsonRpcVersion()}`, - "x-amz-target": `${this.serviceTarget}.${operationSchema.name}`, - }); - if (this.awsQueryCompatible) { - request.headers["x-amzn-query-mode"] = "true"; - } - if (schema.deref(operationSchema.input) === "unit" || !request.body) { - request.body = "{}"; - } - return request; - } - getPayloadCodec() { - return this.codec; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - if (this.awsQueryCompatible) { - this.mixin.setQueryCompatError(dataObject, response); - } - const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); - const ns = schema.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const ErrorCtor = schema.TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; - const exception = new ErrorCtor(message); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().jsonName ?? name; - output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); - } - if (this.awsQueryCompatible) { - this.mixin.queryCompatOutput(dataObject, output); - } - throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { - $fault: ns.getMergedTraits().error, - message, - }, output), dataObject); - } -} - -class AwsJson1_0Protocol extends AwsJsonRpcProtocol { - constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, }) { - super({ - defaultNamespace, - serviceTarget, - awsQueryCompatible, - }); - } - getShapeId() { - return "aws.protocols#awsJson1_0"; - } - getJsonRpcVersion() { - return "1.0"; - } - getDefaultContentType() { - return "application/x-amz-json-1.0"; - } -} - -class AwsJson1_1Protocol extends AwsJsonRpcProtocol { - constructor({ defaultNamespace, serviceTarget, awsQueryCompatible, }) { - super({ - defaultNamespace, - serviceTarget, - awsQueryCompatible, - }); - } - getShapeId() { - return "aws.protocols#awsJson1_1"; - } - getJsonRpcVersion() { - return "1.1"; - } - getDefaultContentType() { - return "application/x-amz-json-1.1"; - } -} - -class AwsRestJsonProtocol extends protocols.HttpBindingProtocol { - serializer; - deserializer; - codec; - mixin = new ProtocolLib(); - constructor({ defaultNamespace }) { - super({ - defaultNamespace, - }); - const settings = { - timestampFormat: { - useTrait: true, - default: 7, - }, - httpBindings: true, - jsonName: true, - }; - this.codec = new JsonCodec(settings); - this.serializer = new protocols.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); - this.deserializer = new protocols.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); - } - getShapeId() { - return "aws.protocols#restJson1"; - } - getPayloadCodec() { - return this.codec; - } - setSerdeContext(serdeContext) { - this.codec.setSerdeContext(serdeContext); - super.setSerdeContext(serdeContext); - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - const inputSchema = schema.NormalizedSchema.of(operationSchema.input); - if (!request.headers["content-type"]) { - const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); - if (contentType) { - request.headers["content-type"] = contentType; - } - } - if (request.body == null && request.headers["content-type"] === this.getDefaultContentType()) { - request.body = "{}"; - } - return request; - } - async deserializeResponse(operationSchema, context, response) { - const output = await super.deserializeResponse(operationSchema, context, response); - const outputSchema = schema.NormalizedSchema.of(operationSchema.output); - for (const [name, member] of outputSchema.structIterator()) { - if (member.getMemberTraits().httpPayload && !(name in output)) { - output[name] = null; - } - } - return output; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestJsonErrorCode(response, dataObject) ?? "Unknown"; - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); - const ns = schema.NormalizedSchema.of(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const ErrorCtor = schema.TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; - const exception = new ErrorCtor(message); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().jsonName ?? name; - output[name] = this.codec.createDeserializer().readObject(member, dataObject[target]); - } - throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { - $fault: ns.getMergedTraits().error, - message, - }, output), dataObject); - } - getDefaultContentType() { - return "application/json"; - } -} - -const awsExpectUnion = (value) => { - if (value == null) { - return undefined; - } - if (typeof value === "object" && "__type" in value) { - delete value.__type; - } - return smithyClient.expectUnion(value); -}; - -class XmlShapeDeserializer extends SerdeContextConfig { - settings; - stringDeserializer; - constructor(settings) { - super(); - this.settings = settings; - this.stringDeserializer = new protocols.FromStringShapeDeserializer(settings); - } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - this.stringDeserializer.setSerdeContext(serdeContext); - } - read(schema$1, bytes, key) { - const ns = schema.NormalizedSchema.of(schema$1); - const memberSchemas = ns.getMemberSchemas(); - const isEventPayload = ns.isStructSchema() && - ns.isMemberSchema() && - !!Object.values(memberSchemas).find((memberNs) => { - return !!memberNs.getMemberTraits().eventPayload; - }); - if (isEventPayload) { - const output = {}; - const memberName = Object.keys(memberSchemas)[0]; - const eventMemberSchema = memberSchemas[memberName]; - if (eventMemberSchema.isBlobSchema()) { - output[memberName] = bytes; - } - else { - output[memberName] = this.read(memberSchemas[memberName], bytes); - } - return output; - } - const xmlString = (this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8)(bytes); - const parsedObject = this.parseXml(xmlString); - return this.readSchema(schema$1, key ? parsedObject[key] : parsedObject); - } - readSchema(_schema, value) { - const ns = schema.NormalizedSchema.of(_schema); - if (ns.isUnitSchema()) { - return; - } - const traits = ns.getMergedTraits(); - if (ns.isListSchema() && !Array.isArray(value)) { - return this.readSchema(ns, [value]); - } - if (value == null) { - return value; - } - if (typeof value === "object") { - const sparse = !!traits.sparse; - const flat = !!traits.xmlFlattened; - if (ns.isListSchema()) { - const listValue = ns.getValueSchema(); - const buffer = []; - const sourceKey = listValue.getMergedTraits().xmlName ?? "member"; - const source = flat ? value : (value[0] ?? value)[sourceKey]; - const sourceArray = Array.isArray(source) ? source : [source]; - for (const v of sourceArray) { - if (v != null || sparse) { - buffer.push(this.readSchema(listValue, v)); - } - } - return buffer; - } - const buffer = {}; - if (ns.isMapSchema()) { - const keyNs = ns.getKeySchema(); - const memberNs = ns.getValueSchema(); - let entries; - if (flat) { - entries = Array.isArray(value) ? value : [value]; - } - else { - entries = Array.isArray(value.entry) ? value.entry : [value.entry]; - } - const keyProperty = keyNs.getMergedTraits().xmlName ?? "key"; - const valueProperty = memberNs.getMergedTraits().xmlName ?? "value"; - for (const entry of entries) { - const key = entry[keyProperty]; - const value = entry[valueProperty]; - if (value != null || sparse) { - buffer[key] = this.readSchema(memberNs, value); - } - } - return buffer; - } - if (ns.isStructSchema()) { - for (const [memberName, memberSchema] of ns.structIterator()) { - const memberTraits = memberSchema.getMergedTraits(); - const xmlObjectKey = !memberTraits.httpPayload - ? memberSchema.getMemberTraits().xmlName ?? memberName - : memberTraits.xmlName ?? memberSchema.getName(); - if (value[xmlObjectKey] != null) { - buffer[memberName] = this.readSchema(memberSchema, value[xmlObjectKey]); - } - } - return buffer; - } - if (ns.isDocumentSchema()) { - return value; - } - throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns.getName(true)}`); - } - if (ns.isListSchema()) { - return []; - } - if (ns.isMapSchema() || ns.isStructSchema()) { - return {}; - } - return this.stringDeserializer.read(ns, value); - } - parseXml(xml) { - if (xml.length) { - let parsedObj; - try { - parsedObj = xmlBuilder.parseXML(xml); - } - catch (e) { - if (e && typeof e === "object") { - Object.defineProperty(e, "$responseBodyText", { - value: xml, - }); - } - throw e; - } - const textNodeName = "#text"; - const key = Object.keys(parsedObj)[0]; - const parsedObjToReturn = parsedObj[key]; - if (parsedObjToReturn[textNodeName]) { - parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; - delete parsedObjToReturn[textNodeName]; - } - return smithyClient.getValueFromTextNode(parsedObjToReturn); - } - return {}; - } -} - -class QueryShapeSerializer extends SerdeContextConfig { - settings; - buffer; - constructor(settings) { - super(); - this.settings = settings; - } - write(schema$1, value, prefix = "") { - if (this.buffer === undefined) { - this.buffer = ""; - } - const ns = schema.NormalizedSchema.of(schema$1); - if (prefix && !prefix.endsWith(".")) { - prefix += "."; - } - if (ns.isBlobSchema()) { - if (typeof value === "string" || value instanceof Uint8Array) { - this.writeKey(prefix); - this.writeValue((this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value)); - } - } - else if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isStringSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(String(value)); - } - else if (ns.isIdempotencyToken()) { - this.writeKey(prefix); - this.writeValue(serde.generateIdempotencyToken()); - } - } - else if (ns.isBigIntegerSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(String(value)); - } - } - else if (ns.isBigDecimalSchema()) { - if (value != null) { - this.writeKey(prefix); - this.writeValue(value instanceof serde.NumericValue ? value.string : String(value)); - } - } - else if (ns.isTimestampSchema()) { - if (value instanceof Date) { - this.writeKey(prefix); - const format = protocols.determineTimestampFormat(ns, this.settings); - switch (format) { - case 5: - this.writeValue(value.toISOString().replace(".000Z", "Z")); - break; - case 6: - this.writeValue(smithyClient.dateToUtcString(value)); - break; - case 7: - this.writeValue(String(value.getTime() / 1000)); - break; - } - } - } - else if (ns.isDocumentSchema()) { - throw new Error(`@aws-sdk/core/protocols - QuerySerializer unsupported document type ${ns.getName(true)}`); - } - else if (ns.isListSchema()) { - if (Array.isArray(value)) { - if (value.length === 0) { - if (this.settings.serializeEmptyLists) { - this.writeKey(prefix); - this.writeValue(""); - } - } - else { - const member = ns.getValueSchema(); - const flat = this.settings.flattenLists || ns.getMergedTraits().xmlFlattened; - let i = 1; - for (const item of value) { - if (item == null) { - continue; - } - const suffix = this.getKey("member", member.getMergedTraits().xmlName); - const key = flat ? `${prefix}${i}` : `${prefix}${suffix}.${i}`; - this.write(member, item, key); - ++i; - } - } - } - } - else if (ns.isMapSchema()) { - if (value && typeof value === "object") { - const keySchema = ns.getKeySchema(); - const memberSchema = ns.getValueSchema(); - const flat = ns.getMergedTraits().xmlFlattened; - let i = 1; - for (const [k, v] of Object.entries(value)) { - if (v == null) { - continue; - } - const keySuffix = this.getKey("key", keySchema.getMergedTraits().xmlName); - const key = flat ? `${prefix}${i}.${keySuffix}` : `${prefix}entry.${i}.${keySuffix}`; - const valueSuffix = this.getKey("value", memberSchema.getMergedTraits().xmlName); - const valueKey = flat ? `${prefix}${i}.${valueSuffix}` : `${prefix}entry.${i}.${valueSuffix}`; - this.write(keySchema, k, key); - this.write(memberSchema, v, valueKey); - ++i; - } - } - } - else if (ns.isStructSchema()) { - if (value && typeof value === "object") { - for (const [memberName, member] of ns.structIterator()) { - if (value[memberName] == null && !member.isIdempotencyToken()) { - continue; - } - const suffix = this.getKey(memberName, member.getMergedTraits().xmlName); - const key = `${prefix}${suffix}`; - this.write(member, value[memberName], key); - } - } - } - else if (ns.isUnitSchema()) ; - else { - throw new Error(`@aws-sdk/core/protocols - QuerySerializer unrecognized schema type ${ns.getName(true)}`); - } - } - flush() { - if (this.buffer === undefined) { - throw new Error("@aws-sdk/core/protocols - QuerySerializer cannot flush with nothing written to buffer."); - } - const str = this.buffer; - delete this.buffer; - return str; - } - getKey(memberName, xmlName) { - const key = xmlName ?? memberName; - if (this.settings.capitalizeKeys) { - return key[0].toUpperCase() + key.slice(1); - } - return key; - } - writeKey(key) { - if (key.endsWith(".")) { - key = key.slice(0, key.length - 1); - } - this.buffer += `&${protocols.extendedEncodeURIComponent(key)}=`; - } - writeValue(value) { - this.buffer += protocols.extendedEncodeURIComponent(value); - } -} - -class AwsQueryProtocol extends protocols.RpcProtocol { - options; - serializer; - deserializer; - mixin = new ProtocolLib(); - constructor(options) { - super({ - defaultNamespace: options.defaultNamespace, - }); - this.options = options; - const settings = { - timestampFormat: { - useTrait: true, - default: 5, - }, - httpBindings: false, - xmlNamespace: options.xmlNamespace, - serviceNamespace: options.defaultNamespace, - serializeEmptyLists: true, - }; - this.serializer = new QueryShapeSerializer(settings); - this.deserializer = new XmlShapeDeserializer(settings); - } - getShapeId() { - return "aws.protocols#awsQuery"; - } - setSerdeContext(serdeContext) { - this.serializer.setSerdeContext(serdeContext); - this.deserializer.setSerdeContext(serdeContext); - } - getPayloadCodec() { - throw new Error("AWSQuery protocol has no payload codec."); - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - if (!request.path.endsWith("/")) { - request.path += "/"; - } - Object.assign(request.headers, { - "content-type": `application/x-www-form-urlencoded`, - }); - if (schema.deref(operationSchema.input) === "unit" || !request.body) { - request.body = ""; - } - const action = operationSchema.name.split("#")[1] ?? operationSchema.name; - request.body = `Action=${action}&Version=${this.options.version}` + request.body; - if (request.body.endsWith("&")) { - request.body = request.body.slice(-1); - } - return request; - } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = schema.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes = await protocols.collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(15, bytes)); - } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; - } - const shortName = operationSchema.name.split("#")[1] ?? operationSchema.name; - const awsQueryResultKey = ns.isStructSchema() && this.useNestedResult() ? shortName + "Result" : undefined; - const bytes = await protocols.collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(ns, bytes, awsQueryResultKey)); - } - const output = { - $metadata: this.deserializeMetadata(response), - ...dataObject, - }; - return output; - } - useNestedResult() { - return true; - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = this.loadQueryErrorCode(response, dataObject) ?? "Unknown"; - const errorData = this.loadQueryError(dataObject); - const message = this.loadQueryErrorMessage(dataObject); - errorData.message = message; - errorData.Error = { - Type: errorData.Type, - Code: errorData.Code, - Message: message, - }; - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, errorData, metadata, (registry, errorName) => { - try { - return registry.getSchema(errorName); - } - catch (e) { - return registry.find((schema$1) => schema.NormalizedSchema.of(schema$1).getMergedTraits().awsQueryError?.[0] === errorName); - } - }); - const ns = schema.NormalizedSchema.of(errorSchema); - const ErrorCtor = schema.TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; - const exception = new ErrorCtor(message); - const output = { - Error: errorData.Error, - }; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().xmlName ?? name; - const value = errorData[target] ?? dataObject[target]; - output[name] = this.deserializer.readSchema(member, value); - } - throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { - $fault: ns.getMergedTraits().error, - message, - }, output), dataObject); - } - loadQueryErrorCode(output, data) { - const code = (data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error)?.Code; - if (code !== undefined) { - return code; - } - if (output.statusCode == 404) { - return "NotFound"; - } - } - loadQueryError(data) { - return data.Errors?.[0]?.Error ?? data.Errors?.Error ?? data.Error; - } - loadQueryErrorMessage(data) { - const errorData = this.loadQueryError(data); - return errorData?.message ?? errorData?.Message ?? data.message ?? data.Message ?? "Unknown"; - } - getDefaultContentType() { - return "application/x-www-form-urlencoded"; - } -} - -class AwsEc2QueryProtocol extends AwsQueryProtocol { - options; - constructor(options) { - super(options); - this.options = options; - const ec2Settings = { - capitalizeKeys: true, - flattenLists: true, - serializeEmptyLists: false, - }; - Object.assign(this.serializer.settings, ec2Settings); - } - useNestedResult() { - return false; - } -} - -const parseXmlBody = (streamBody, context) => collectBodyString(streamBody, context).then((encoded) => { - if (encoded.length) { - let parsedObj; - try { - parsedObj = xmlBuilder.parseXML(encoded); - } - catch (e) { - if (e && typeof e === "object") { - Object.defineProperty(e, "$responseBodyText", { - value: encoded, - }); - } - throw e; - } - const textNodeName = "#text"; - const key = Object.keys(parsedObj)[0]; - const parsedObjToReturn = parsedObj[key]; - if (parsedObjToReturn[textNodeName]) { - parsedObjToReturn[key] = parsedObjToReturn[textNodeName]; - delete parsedObjToReturn[textNodeName]; - } - return smithyClient.getValueFromTextNode(parsedObjToReturn); - } - return {}; -}); -const parseXmlErrorBody = async (errorBody, context) => { - const value = await parseXmlBody(errorBody, context); - if (value.Error) { - value.Error.message = value.Error.message ?? value.Error.Message; - } - return value; -}; -const loadRestXmlErrorCode = (output, data) => { - if (data?.Error?.Code !== undefined) { - return data.Error.Code; - } - if (data?.Code !== undefined) { - return data.Code; - } - if (output.statusCode == 404) { - return "NotFound"; - } -}; - -class XmlShapeSerializer extends SerdeContextConfig { - settings; - stringBuffer; - byteBuffer; - buffer; - constructor(settings) { - super(); - this.settings = settings; - } - write(schema$1, value) { - const ns = schema.NormalizedSchema.of(schema$1); - if (ns.isStringSchema() && typeof value === "string") { - this.stringBuffer = value; - } - else if (ns.isBlobSchema()) { - this.byteBuffer = - "byteLength" in value - ? value - : (this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(value); - } - else { - this.buffer = this.writeStruct(ns, value, undefined); - const traits = ns.getMergedTraits(); - if (traits.httpPayload && !traits.xmlName) { - this.buffer.withName(ns.getName()); - } - } - } - flush() { - if (this.byteBuffer !== undefined) { - const bytes = this.byteBuffer; - delete this.byteBuffer; - return bytes; - } - if (this.stringBuffer !== undefined) { - const str = this.stringBuffer; - delete this.stringBuffer; - return str; - } - const buffer = this.buffer; - if (this.settings.xmlNamespace) { - if (!buffer?.attributes?.["xmlns"]) { - buffer.addAttribute("xmlns", this.settings.xmlNamespace); - } - } - delete this.buffer; - return buffer.toString(); - } - writeStruct(ns, value, parentXmlns) { - const traits = ns.getMergedTraits(); - const name = ns.isMemberSchema() && !traits.httpPayload - ? ns.getMemberTraits().xmlName ?? ns.getMemberName() - : traits.xmlName ?? ns.getName(); - if (!name || !ns.isStructSchema()) { - throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns.getName(true)}.`); - } - const structXmlNode = xmlBuilder.XmlNode.of(name); - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); - for (const [memberName, memberSchema] of ns.structIterator()) { - const val = value[memberName]; - if (val != null || memberSchema.isIdempotencyToken()) { - if (memberSchema.getMergedTraits().xmlAttribute) { - structXmlNode.addAttribute(memberSchema.getMergedTraits().xmlName ?? memberName, this.writeSimple(memberSchema, val)); - continue; - } - if (memberSchema.isListSchema()) { - this.writeList(memberSchema, val, structXmlNode, xmlns); - } - else if (memberSchema.isMapSchema()) { - this.writeMap(memberSchema, val, structXmlNode, xmlns); - } - else if (memberSchema.isStructSchema()) { - structXmlNode.addChildNode(this.writeStruct(memberSchema, val, xmlns)); - } - else { - const memberNode = xmlBuilder.XmlNode.of(memberSchema.getMergedTraits().xmlName ?? memberSchema.getMemberName()); - this.writeSimpleInto(memberSchema, val, memberNode, xmlns); - structXmlNode.addChildNode(memberNode); - } - } - } - if (xmlns) { - structXmlNode.addAttribute(xmlnsAttr, xmlns); - } - return structXmlNode; - } - writeList(listMember, array, container, parentXmlns) { - if (!listMember.isMemberSchema()) { - throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${listMember.getName(true)}`); - } - const listTraits = listMember.getMergedTraits(); - const listValueSchema = listMember.getValueSchema(); - const listValueTraits = listValueSchema.getMergedTraits(); - const sparse = !!listValueTraits.sparse; - const flat = !!listTraits.xmlFlattened; - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(listMember, parentXmlns); - const writeItem = (container, value) => { - if (listValueSchema.isListSchema()) { - this.writeList(listValueSchema, Array.isArray(value) ? value : [value], container, xmlns); - } - else if (listValueSchema.isMapSchema()) { - this.writeMap(listValueSchema, value, container, xmlns); - } - else if (listValueSchema.isStructSchema()) { - const struct = this.writeStruct(listValueSchema, value, xmlns); - container.addChildNode(struct.withName(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member")); - } - else { - const listItemNode = xmlBuilder.XmlNode.of(flat ? listTraits.xmlName ?? listMember.getMemberName() : listValueTraits.xmlName ?? "member"); - this.writeSimpleInto(listValueSchema, value, listItemNode, xmlns); - container.addChildNode(listItemNode); - } - }; - if (flat) { - for (const value of array) { - if (sparse || value != null) { - writeItem(container, value); - } - } - } - else { - const listNode = xmlBuilder.XmlNode.of(listTraits.xmlName ?? listMember.getMemberName()); - if (xmlns) { - listNode.addAttribute(xmlnsAttr, xmlns); - } - for (const value of array) { - if (sparse || value != null) { - writeItem(listNode, value); - } - } - container.addChildNode(listNode); - } - } - writeMap(mapMember, map, container, parentXmlns, containerIsMap = false) { - if (!mapMember.isMemberSchema()) { - throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${mapMember.getName(true)}`); - } - const mapTraits = mapMember.getMergedTraits(); - const mapKeySchema = mapMember.getKeySchema(); - const mapKeyTraits = mapKeySchema.getMergedTraits(); - const keyTag = mapKeyTraits.xmlName ?? "key"; - const mapValueSchema = mapMember.getValueSchema(); - const mapValueTraits = mapValueSchema.getMergedTraits(); - const valueTag = mapValueTraits.xmlName ?? "value"; - const sparse = !!mapValueTraits.sparse; - const flat = !!mapTraits.xmlFlattened; - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(mapMember, parentXmlns); - const addKeyValue = (entry, key, val) => { - const keyNode = xmlBuilder.XmlNode.of(keyTag, key); - const [keyXmlnsAttr, keyXmlns] = this.getXmlnsAttribute(mapKeySchema, xmlns); - if (keyXmlns) { - keyNode.addAttribute(keyXmlnsAttr, keyXmlns); - } - entry.addChildNode(keyNode); - let valueNode = xmlBuilder.XmlNode.of(valueTag); - if (mapValueSchema.isListSchema()) { - this.writeList(mapValueSchema, val, valueNode, xmlns); - } - else if (mapValueSchema.isMapSchema()) { - this.writeMap(mapValueSchema, val, valueNode, xmlns, true); - } - else if (mapValueSchema.isStructSchema()) { - valueNode = this.writeStruct(mapValueSchema, val, xmlns); - } - else { - this.writeSimpleInto(mapValueSchema, val, valueNode, xmlns); - } - entry.addChildNode(valueNode); - }; - if (flat) { - for (const [key, val] of Object.entries(map)) { - if (sparse || val != null) { - const entry = xmlBuilder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); - addKeyValue(entry, key, val); - container.addChildNode(entry); - } - } - } - else { - let mapNode; - if (!containerIsMap) { - mapNode = xmlBuilder.XmlNode.of(mapTraits.xmlName ?? mapMember.getMemberName()); - if (xmlns) { - mapNode.addAttribute(xmlnsAttr, xmlns); - } - container.addChildNode(mapNode); - } - for (const [key, val] of Object.entries(map)) { - if (sparse || val != null) { - const entry = xmlBuilder.XmlNode.of("entry"); - addKeyValue(entry, key, val); - (containerIsMap ? container : mapNode).addChildNode(entry); - } - } - } - } - writeSimple(_schema, value) { - if (null === value) { - throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value."); - } - const ns = schema.NormalizedSchema.of(_schema); - let nodeContents = null; - if (value && typeof value === "object") { - if (ns.isBlobSchema()) { - nodeContents = (this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value); - } - else if (ns.isTimestampSchema() && value instanceof Date) { - const format = protocols.determineTimestampFormat(ns, this.settings); - switch (format) { - case 5: - nodeContents = value.toISOString().replace(".000Z", "Z"); - break; - case 6: - nodeContents = smithyClient.dateToUtcString(value); - break; - case 7: - nodeContents = String(value.getTime() / 1000); - break; - default: - console.warn("Missing timestamp format, using http date", value); - nodeContents = smithyClient.dateToUtcString(value); - break; - } - } - else if (ns.isBigDecimalSchema() && value) { - if (value instanceof serde.NumericValue) { - return value.string; - } - return String(value); - } - else if (ns.isMapSchema() || ns.isListSchema()) { - throw new Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead."); - } - else { - throw new Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns.getName(true)}`); - } - } - if (ns.isBooleanSchema() || ns.isNumericSchema() || ns.isBigIntegerSchema() || ns.isBigDecimalSchema()) { - nodeContents = String(value); - } - if (ns.isStringSchema()) { - if (value === undefined && ns.isIdempotencyToken()) { - nodeContents = serde.generateIdempotencyToken(); - } - else { - nodeContents = String(value); - } - } - if (nodeContents === null) { - throw new Error(`Unhandled schema-value pair ${ns.getName(true)}=${value}`); - } - return nodeContents; - } - writeSimpleInto(_schema, value, into, parentXmlns) { - const nodeContents = this.writeSimple(_schema, value); - const ns = schema.NormalizedSchema.of(_schema); - const content = new xmlBuilder.XmlText(nodeContents); - const [xmlnsAttr, xmlns] = this.getXmlnsAttribute(ns, parentXmlns); - if (xmlns) { - into.addAttribute(xmlnsAttr, xmlns); - } - into.addChildNode(content); - } - getXmlnsAttribute(ns, parentXmlns) { - const traits = ns.getMergedTraits(); - const [prefix, xmlns] = traits.xmlNamespace ?? []; - if (xmlns && xmlns !== parentXmlns) { - return [prefix ? `xmlns:${prefix}` : "xmlns", xmlns]; - } - return [void 0, void 0]; - } -} - -class XmlCodec extends SerdeContextConfig { - settings; - constructor(settings) { - super(); - this.settings = settings; - } - createSerializer() { - const serializer = new XmlShapeSerializer(this.settings); - serializer.setSerdeContext(this.serdeContext); - return serializer; - } - createDeserializer() { - const deserializer = new XmlShapeDeserializer(this.settings); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; - } -} - -class AwsRestXmlProtocol extends protocols.HttpBindingProtocol { - codec; - serializer; - deserializer; - mixin = new ProtocolLib(); - constructor(options) { - super(options); - const settings = { - timestampFormat: { - useTrait: true, - default: 5, - }, - httpBindings: true, - xmlNamespace: options.xmlNamespace, - serviceNamespace: options.defaultNamespace, - }; - this.codec = new XmlCodec(settings); - this.serializer = new protocols.HttpInterceptingShapeSerializer(this.codec.createSerializer(), settings); - this.deserializer = new protocols.HttpInterceptingShapeDeserializer(this.codec.createDeserializer(), settings); - } - getPayloadCodec() { - return this.codec; - } - getShapeId() { - return "aws.protocols#restXml"; - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - const inputSchema = schema.NormalizedSchema.of(operationSchema.input); - if (!request.headers["content-type"]) { - const contentType = this.mixin.resolveRestContentType(this.getDefaultContentType(), inputSchema); - if (contentType) { - request.headers["content-type"] = contentType; - } - } - if (request.headers["content-type"] === this.getDefaultContentType()) { - if (typeof request.body === "string") { - request.body = '' + request.body; - } - } - return request; - } - async deserializeResponse(operationSchema, context, response) { - return super.deserializeResponse(operationSchema, context, response); - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorIdentifier = loadRestXmlErrorCode(response, dataObject) ?? "Unknown"; - const { errorSchema, errorMetadata } = await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier, this.options.defaultNamespace, response, dataObject, metadata); - const ns = schema.NormalizedSchema.of(errorSchema); - const message = dataObject.Error?.message ?? dataObject.Error?.Message ?? dataObject.message ?? dataObject.Message ?? "Unknown"; - const ErrorCtor = schema.TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema) ?? Error; - const exception = new ErrorCtor(message); - await this.deserializeHttpMessage(errorSchema, context, response, dataObject); - const output = {}; - for (const [name, member] of ns.structIterator()) { - const target = member.getMergedTraits().xmlName ?? name; - const value = dataObject.Error?.[target] ?? dataObject[target]; - output[name] = this.codec.createDeserializer().readSchema(member, value); - } - throw this.mixin.decorateServiceException(Object.assign(exception, errorMetadata, { - $fault: ns.getMergedTraits().error, - message, - }, output), dataObject); - } - getDefaultContentType() { - return "application/xml"; - } -} - -exports.AwsEc2QueryProtocol = AwsEc2QueryProtocol; -exports.AwsJson1_0Protocol = AwsJson1_0Protocol; -exports.AwsJson1_1Protocol = AwsJson1_1Protocol; -exports.AwsJsonRpcProtocol = AwsJsonRpcProtocol; -exports.AwsQueryProtocol = AwsQueryProtocol; -exports.AwsRestJsonProtocol = AwsRestJsonProtocol; -exports.AwsRestXmlProtocol = AwsRestXmlProtocol; -exports.AwsSmithyRpcV2CborProtocol = AwsSmithyRpcV2CborProtocol; -exports.JsonCodec = JsonCodec; -exports.JsonShapeDeserializer = JsonShapeDeserializer; -exports.JsonShapeSerializer = JsonShapeSerializer; -exports.XmlCodec = XmlCodec; -exports.XmlShapeDeserializer = XmlShapeDeserializer; -exports.XmlShapeSerializer = XmlShapeSerializer; -exports._toBool = _toBool; -exports._toNum = _toNum; -exports._toStr = _toStr; -exports.awsExpectUnion = awsExpectUnion; -exports.loadRestJsonErrorCode = loadRestJsonErrorCode; -exports.loadRestXmlErrorCode = loadRestXmlErrorCode; -exports.parseJsonBody = parseJsonBody; -exports.parseJsonErrorBody = parseJsonErrorBody; -exports.parseXmlBody = parseXmlBody; -exports.parseXmlErrorBody = parseXmlErrorBody; diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 52303c3b..00000000 --- a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,169 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-cjs/index.js deleted file mode 100644 index 362d7f30..00000000 --- a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/dist-cjs/index.js +++ /dev/null @@ -1,556 +0,0 @@ -'use strict'; - -var utilHexEncoding = require('@smithy/util-hex-encoding'); -var utilUtf8 = require('@smithy/util-utf8'); -var isArrayBuffer = require('@smithy/is-array-buffer'); -var protocolHttp = require('@smithy/protocol-http'); -var utilMiddleware = require('@smithy/util-middleware'); -var utilUriEscape = require('@smithy/util-uri-escape'); - -const ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm"; -const CREDENTIAL_QUERY_PARAM = "X-Amz-Credential"; -const AMZ_DATE_QUERY_PARAM = "X-Amz-Date"; -const SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders"; -const EXPIRES_QUERY_PARAM = "X-Amz-Expires"; -const SIGNATURE_QUERY_PARAM = "X-Amz-Signature"; -const TOKEN_QUERY_PARAM = "X-Amz-Security-Token"; -const REGION_SET_PARAM = "X-Amz-Region-Set"; -const AUTH_HEADER = "authorization"; -const AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase(); -const DATE_HEADER = "date"; -const GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER]; -const SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase(); -const SHA256_HEADER = "x-amz-content-sha256"; -const TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase(); -const HOST_HEADER = "host"; -const ALWAYS_UNSIGNABLE_HEADERS = { - authorization: true, - "cache-control": true, - connection: true, - expect: true, - from: true, - "keep-alive": true, - "max-forwards": true, - pragma: true, - referer: true, - te: true, - trailer: true, - "transfer-encoding": true, - upgrade: true, - "user-agent": true, - "x-amzn-trace-id": true, -}; -const PROXY_HEADER_PATTERN = /^proxy-/; -const SEC_HEADER_PATTERN = /^sec-/; -const UNSIGNABLE_PATTERNS = [/^proxy-/i, /^sec-/i]; -const ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256"; -const ALGORITHM_IDENTIFIER_V4A = "AWS4-ECDSA-P256-SHA256"; -const EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD"; -const UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; -const MAX_CACHE_SIZE = 50; -const KEY_TYPE_IDENTIFIER = "aws4_request"; -const MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7; - -const signingKeyCache = {}; -const cacheQueue = []; -const createScope = (shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`; -const getSigningKey = async (sha256Constructor, credentials, shortDate, region, service) => { - const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId); - const cacheKey = `${shortDate}:${region}:${service}:${utilHexEncoding.toHex(credsHash)}:${credentials.sessionToken}`; - if (cacheKey in signingKeyCache) { - return signingKeyCache[cacheKey]; - } - cacheQueue.push(cacheKey); - while (cacheQueue.length > MAX_CACHE_SIZE) { - delete signingKeyCache[cacheQueue.shift()]; - } - let key = `AWS4${credentials.secretAccessKey}`; - for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) { - key = await hmac(sha256Constructor, key, signable); - } - return (signingKeyCache[cacheKey] = key); -}; -const clearCredentialCache = () => { - cacheQueue.length = 0; - Object.keys(signingKeyCache).forEach((cacheKey) => { - delete signingKeyCache[cacheKey]; - }); -}; -const hmac = (ctor, secret, data) => { - const hash = new ctor(secret); - hash.update(utilUtf8.toUint8Array(data)); - return hash.digest(); -}; - -const getCanonicalHeaders = ({ headers }, unsignableHeaders, signableHeaders) => { - const canonical = {}; - for (const headerName of Object.keys(headers).sort()) { - if (headers[headerName] == undefined) { - continue; - } - const canonicalHeaderName = headerName.toLowerCase(); - if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || - unsignableHeaders?.has(canonicalHeaderName) || - PROXY_HEADER_PATTERN.test(canonicalHeaderName) || - SEC_HEADER_PATTERN.test(canonicalHeaderName)) { - if (!signableHeaders || (signableHeaders && !signableHeaders.has(canonicalHeaderName))) { - continue; - } - } - canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " "); - } - return canonical; -}; - -const getPayloadHash = async ({ headers, body }, hashConstructor) => { - for (const headerName of Object.keys(headers)) { - if (headerName.toLowerCase() === SHA256_HEADER) { - return headers[headerName]; - } - } - if (body == undefined) { - return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; - } - else if (typeof body === "string" || ArrayBuffer.isView(body) || isArrayBuffer.isArrayBuffer(body)) { - const hashCtor = new hashConstructor(); - hashCtor.update(utilUtf8.toUint8Array(body)); - return utilHexEncoding.toHex(await hashCtor.digest()); - } - return UNSIGNED_PAYLOAD; -}; - -class HeaderFormatter { - format(headers) { - const chunks = []; - for (const headerName of Object.keys(headers)) { - const bytes = utilUtf8.fromUtf8(headerName); - chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); - } - const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); - let position = 0; - for (const chunk of chunks) { - out.set(chunk, position); - position += chunk.byteLength; - } - return out; - } - formatHeaderValue(header) { - switch (header.type) { - case "boolean": - return Uint8Array.from([header.value ? 0 : 1]); - case "byte": - return Uint8Array.from([2, header.value]); - case "short": - const shortView = new DataView(new ArrayBuffer(3)); - shortView.setUint8(0, 3); - shortView.setInt16(1, header.value, false); - return new Uint8Array(shortView.buffer); - case "integer": - const intView = new DataView(new ArrayBuffer(5)); - intView.setUint8(0, 4); - intView.setInt32(1, header.value, false); - return new Uint8Array(intView.buffer); - case "long": - const longBytes = new Uint8Array(9); - longBytes[0] = 5; - longBytes.set(header.value.bytes, 1); - return longBytes; - case "binary": - const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); - binView.setUint8(0, 6); - binView.setUint16(1, header.value.byteLength, false); - const binBytes = new Uint8Array(binView.buffer); - binBytes.set(header.value, 3); - return binBytes; - case "string": - const utf8Bytes = utilUtf8.fromUtf8(header.value); - const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); - strView.setUint8(0, 7); - strView.setUint16(1, utf8Bytes.byteLength, false); - const strBytes = new Uint8Array(strView.buffer); - strBytes.set(utf8Bytes, 3); - return strBytes; - case "timestamp": - const tsBytes = new Uint8Array(9); - tsBytes[0] = 8; - tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); - return tsBytes; - case "uuid": - if (!UUID_PATTERN.test(header.value)) { - throw new Error(`Invalid UUID received: ${header.value}`); - } - const uuidBytes = new Uint8Array(17); - uuidBytes[0] = 9; - uuidBytes.set(utilHexEncoding.fromHex(header.value.replace(/\-/g, "")), 1); - return uuidBytes; - } - } -} -const UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; -class Int64 { - bytes; - constructor(bytes) { - this.bytes = bytes; - if (bytes.byteLength !== 8) { - throw new Error("Int64 buffers must be exactly 8 bytes"); - } - } - static fromNumber(number) { - if (number > 9_223_372_036_854_775_807 || number < -9223372036854776e3) { - throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); - } - const bytes = new Uint8Array(8); - for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { - bytes[i] = remaining; - } - if (number < 0) { - negate(bytes); - } - return new Int64(bytes); - } - valueOf() { - const bytes = this.bytes.slice(0); - const negative = bytes[0] & 0b10000000; - if (negative) { - negate(bytes); - } - return parseInt(utilHexEncoding.toHex(bytes), 16) * (negative ? -1 : 1); - } - toString() { - return String(this.valueOf()); - } -} -function negate(bytes) { - for (let i = 0; i < 8; i++) { - bytes[i] ^= 0xff; - } - for (let i = 7; i > -1; i--) { - bytes[i]++; - if (bytes[i] !== 0) - break; - } -} - -const hasHeader = (soughtHeader, headers) => { - soughtHeader = soughtHeader.toLowerCase(); - for (const headerName of Object.keys(headers)) { - if (soughtHeader === headerName.toLowerCase()) { - return true; - } - } - return false; -}; - -const moveHeadersToQuery = (request, options = {}) => { - const { headers, query = {} } = protocolHttp.HttpRequest.clone(request); - for (const name of Object.keys(headers)) { - const lname = name.toLowerCase(); - if ((lname.slice(0, 6) === "x-amz-" && !options.unhoistableHeaders?.has(lname)) || - options.hoistableHeaders?.has(lname)) { - query[name] = headers[name]; - delete headers[name]; - } - } - return { - ...request, - headers, - query, - }; -}; - -const prepareRequest = (request) => { - request = protocolHttp.HttpRequest.clone(request); - for (const headerName of Object.keys(request.headers)) { - if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) { - delete request.headers[headerName]; - } - } - return request; -}; - -const getCanonicalQuery = ({ query = {} }) => { - const keys = []; - const serialized = {}; - for (const key of Object.keys(query)) { - if (key.toLowerCase() === SIGNATURE_HEADER) { - continue; - } - const encodedKey = utilUriEscape.escapeUri(key); - keys.push(encodedKey); - const value = query[key]; - if (typeof value === "string") { - serialized[encodedKey] = `${encodedKey}=${utilUriEscape.escapeUri(value)}`; - } - else if (Array.isArray(value)) { - serialized[encodedKey] = value - .slice(0) - .reduce((encoded, value) => encoded.concat([`${encodedKey}=${utilUriEscape.escapeUri(value)}`]), []) - .sort() - .join("&"); - } - } - return keys - .sort() - .map((key) => serialized[key]) - .filter((serialized) => serialized) - .join("&"); -}; - -const iso8601 = (time) => toDate(time) - .toISOString() - .replace(/\.\d{3}Z$/, "Z"); -const toDate = (time) => { - if (typeof time === "number") { - return new Date(time * 1000); - } - if (typeof time === "string") { - if (Number(time)) { - return new Date(Number(time) * 1000); - } - return new Date(time); - } - return time; -}; - -class SignatureV4Base { - service; - regionProvider; - credentialProvider; - sha256; - uriEscapePath; - applyChecksum; - constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true, }) { - this.service = service; - this.sha256 = sha256; - this.uriEscapePath = uriEscapePath; - this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true; - this.regionProvider = utilMiddleware.normalizeProvider(region); - this.credentialProvider = utilMiddleware.normalizeProvider(credentials); - } - createCanonicalRequest(request, canonicalHeaders, payloadHash) { - const sortedHeaders = Object.keys(canonicalHeaders).sort(); - return `${request.method} -${this.getCanonicalPath(request)} -${getCanonicalQuery(request)} -${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")} - -${sortedHeaders.join(";")} -${payloadHash}`; - } - async createStringToSign(longDate, credentialScope, canonicalRequest, algorithmIdentifier) { - const hash = new this.sha256(); - hash.update(utilUtf8.toUint8Array(canonicalRequest)); - const hashedRequest = await hash.digest(); - return `${algorithmIdentifier} -${longDate} -${credentialScope} -${utilHexEncoding.toHex(hashedRequest)}`; - } - getCanonicalPath({ path }) { - if (this.uriEscapePath) { - const normalizedPathSegments = []; - for (const pathSegment of path.split("/")) { - if (pathSegment?.length === 0) - continue; - if (pathSegment === ".") - continue; - if (pathSegment === "..") { - normalizedPathSegments.pop(); - } - else { - normalizedPathSegments.push(pathSegment); - } - } - const normalizedPath = `${path?.startsWith("/") ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && path?.endsWith("/") ? "/" : ""}`; - const doubleEncoded = utilUriEscape.escapeUri(normalizedPath); - return doubleEncoded.replace(/%2F/g, "/"); - } - return path; - } - validateResolvedCredentials(credentials) { - if (typeof credentials !== "object" || - typeof credentials.accessKeyId !== "string" || - typeof credentials.secretAccessKey !== "string") { - throw new Error("Resolved credential object is not valid"); - } - } - formatDate(now) { - const longDate = iso8601(now).replace(/[\-:]/g, ""); - return { - longDate, - shortDate: longDate.slice(0, 8), - }; - } - getCanonicalHeaderList(headers) { - return Object.keys(headers).sort().join(";"); - } -} - -class SignatureV4 extends SignatureV4Base { - headerFormatter = new HeaderFormatter(); - constructor({ applyChecksum, credentials, region, service, sha256, uriEscapePath = true, }) { - super({ - applyChecksum, - credentials, - region, - service, - sha256, - uriEscapePath, - }); - } - async presign(originalRequest, options = {}) { - const { signingDate = new Date(), expiresIn = 3600, unsignableHeaders, unhoistableHeaders, signableHeaders, hoistableHeaders, signingRegion, signingService, } = options; - const credentials = await this.credentialProvider(); - this.validateResolvedCredentials(credentials); - const region = signingRegion ?? (await this.regionProvider()); - const { longDate, shortDate } = this.formatDate(signingDate); - if (expiresIn > MAX_PRESIGNED_TTL) { - return Promise.reject("Signature version 4 presigned URLs" + " must have an expiration date less than one week in" + " the future"); - } - const scope = createScope(shortDate, region, signingService ?? this.service); - const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders, hoistableHeaders }); - if (credentials.sessionToken) { - request.query[TOKEN_QUERY_PARAM] = credentials.sessionToken; - } - request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER; - request.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`; - request.query[AMZ_DATE_QUERY_PARAM] = longDate; - request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10); - const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); - request.query[SIGNED_HEADERS_QUERY_PARAM] = this.getCanonicalHeaderList(canonicalHeaders); - request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256))); - return request; - } - async sign(toSign, options) { - if (typeof toSign === "string") { - return this.signString(toSign, options); - } - else if (toSign.headers && toSign.payload) { - return this.signEvent(toSign, options); - } - else if (toSign.message) { - return this.signMessage(toSign, options); - } - else { - return this.signRequest(toSign, options); - } - } - async signEvent({ headers, payload }, { signingDate = new Date(), priorSignature, signingRegion, signingService }) { - const region = signingRegion ?? (await this.regionProvider()); - const { shortDate, longDate } = this.formatDate(signingDate); - const scope = createScope(shortDate, region, signingService ?? this.service); - const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256); - const hash = new this.sha256(); - hash.update(headers); - const hashedHeaders = utilHexEncoding.toHex(await hash.digest()); - const stringToSign = [ - EVENT_ALGORITHM_IDENTIFIER, - longDate, - scope, - priorSignature, - hashedHeaders, - hashedPayload, - ].join("\n"); - return this.signString(stringToSign, { signingDate, signingRegion: region, signingService }); - } - async signMessage(signableMessage, { signingDate = new Date(), signingRegion, signingService }) { - const promise = this.signEvent({ - headers: this.headerFormatter.format(signableMessage.message.headers), - payload: signableMessage.message.body, - }, { - signingDate, - signingRegion, - signingService, - priorSignature: signableMessage.priorSignature, - }); - return promise.then((signature) => { - return { message: signableMessage.message, signature }; - }); - } - async signString(stringToSign, { signingDate = new Date(), signingRegion, signingService } = {}) { - const credentials = await this.credentialProvider(); - this.validateResolvedCredentials(credentials); - const region = signingRegion ?? (await this.regionProvider()); - const { shortDate } = this.formatDate(signingDate); - const hash = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService)); - hash.update(utilUtf8.toUint8Array(stringToSign)); - return utilHexEncoding.toHex(await hash.digest()); - } - async signRequest(requestToSign, { signingDate = new Date(), signableHeaders, unsignableHeaders, signingRegion, signingService, } = {}) { - const credentials = await this.credentialProvider(); - this.validateResolvedCredentials(credentials); - const region = signingRegion ?? (await this.regionProvider()); - const request = prepareRequest(requestToSign); - const { longDate, shortDate } = this.formatDate(signingDate); - const scope = createScope(shortDate, region, signingService ?? this.service); - request.headers[AMZ_DATE_HEADER] = longDate; - if (credentials.sessionToken) { - request.headers[TOKEN_HEADER] = credentials.sessionToken; - } - const payloadHash = await getPayloadHash(request, this.sha256); - if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) { - request.headers[SHA256_HEADER] = payloadHash; - } - const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); - const signature = await this.getSignature(longDate, scope, this.getSigningKey(credentials, region, shortDate, signingService), this.createCanonicalRequest(request, canonicalHeaders, payloadHash)); - request.headers[AUTH_HEADER] = - `${ALGORITHM_IDENTIFIER} ` + - `Credential=${credentials.accessKeyId}/${scope}, ` + - `SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, ` + - `Signature=${signature}`; - return request; - } - async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) { - const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest, ALGORITHM_IDENTIFIER); - const hash = new this.sha256(await keyPromise); - hash.update(utilUtf8.toUint8Array(stringToSign)); - return utilHexEncoding.toHex(await hash.digest()); - } - getSigningKey(credentials, region, shortDate, service) { - return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service); - } -} - -const signatureV4aContainer = { - SignatureV4a: null, -}; - -exports.ALGORITHM_IDENTIFIER = ALGORITHM_IDENTIFIER; -exports.ALGORITHM_IDENTIFIER_V4A = ALGORITHM_IDENTIFIER_V4A; -exports.ALGORITHM_QUERY_PARAM = ALGORITHM_QUERY_PARAM; -exports.ALWAYS_UNSIGNABLE_HEADERS = ALWAYS_UNSIGNABLE_HEADERS; -exports.AMZ_DATE_HEADER = AMZ_DATE_HEADER; -exports.AMZ_DATE_QUERY_PARAM = AMZ_DATE_QUERY_PARAM; -exports.AUTH_HEADER = AUTH_HEADER; -exports.CREDENTIAL_QUERY_PARAM = CREDENTIAL_QUERY_PARAM; -exports.DATE_HEADER = DATE_HEADER; -exports.EVENT_ALGORITHM_IDENTIFIER = EVENT_ALGORITHM_IDENTIFIER; -exports.EXPIRES_QUERY_PARAM = EXPIRES_QUERY_PARAM; -exports.GENERATED_HEADERS = GENERATED_HEADERS; -exports.HOST_HEADER = HOST_HEADER; -exports.KEY_TYPE_IDENTIFIER = KEY_TYPE_IDENTIFIER; -exports.MAX_CACHE_SIZE = MAX_CACHE_SIZE; -exports.MAX_PRESIGNED_TTL = MAX_PRESIGNED_TTL; -exports.PROXY_HEADER_PATTERN = PROXY_HEADER_PATTERN; -exports.REGION_SET_PARAM = REGION_SET_PARAM; -exports.SEC_HEADER_PATTERN = SEC_HEADER_PATTERN; -exports.SHA256_HEADER = SHA256_HEADER; -exports.SIGNATURE_HEADER = SIGNATURE_HEADER; -exports.SIGNATURE_QUERY_PARAM = SIGNATURE_QUERY_PARAM; -exports.SIGNED_HEADERS_QUERY_PARAM = SIGNED_HEADERS_QUERY_PARAM; -exports.SignatureV4 = SignatureV4; -exports.SignatureV4Base = SignatureV4Base; -exports.TOKEN_HEADER = TOKEN_HEADER; -exports.TOKEN_QUERY_PARAM = TOKEN_QUERY_PARAM; -exports.UNSIGNABLE_PATTERNS = UNSIGNABLE_PATTERNS; -exports.UNSIGNED_PAYLOAD = UNSIGNED_PAYLOAD; -exports.clearCredentialCache = clearCredentialCache; -exports.createScope = createScope; -exports.getCanonicalHeaders = getCanonicalHeaders; -exports.getCanonicalQuery = getCanonicalQuery; -exports.getPayloadHash = getPayloadHash; -exports.getSigningKey = getSigningKey; -exports.hasHeader = hasHeader; -exports.moveHeadersToQuery = moveHeadersToQuery; -exports.prepareRequest = prepareRequest; -exports.signatureV4aContainer = signatureV4aContainer; diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/is-array-buffer/dist-cjs/index.js deleted file mode 100644 index 3238bb77..00000000 --- a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/is-array-buffer/dist-cjs/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || - Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; - -exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js deleted file mode 100644 index 6d1eb2d1..00000000 --- a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -const SHORT_TO_HEX = {}; -const HEX_TO_SHORT = {}; -for (let i = 0; i < 256; i++) { - let encodedByte = i.toString(16).toLowerCase(); - if (encodedByte.length === 1) { - encodedByte = `0${encodedByte}`; - } - SHORT_TO_HEX[i] = encodedByte; - HEX_TO_SHORT[encodedByte] = i; -} -function fromHex(encoded) { - if (encoded.length % 2 !== 0) { - throw new Error("Hex encoded strings must have an even number length"); - } - const out = new Uint8Array(encoded.length / 2); - for (let i = 0; i < encoded.length; i += 2) { - const encodedByte = encoded.slice(i, i + 2).toLowerCase(); - if (encodedByte in HEX_TO_SHORT) { - out[i / 2] = HEX_TO_SHORT[encodedByte]; - } - else { - throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); - } - } - return out; -} -function toHex(bytes) { - let out = ""; - for (let i = 0; i < bytes.byteLength; i++) { - out += SHORT_TO_HEX[bytes[i]]; - } - return out; -} - -exports.fromHex = fromHex; -exports.toHex = toHex; diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/util-uri-escape/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/util-uri-escape/dist-cjs/index.js deleted file mode 100644 index 11f942c3..00000000 --- a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/signature-v4/node_modules/@smithy/util-uri-escape/dist-cjs/index.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -const escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode); -const hexEncode = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`; - -const escapeUriPath = (uri) => uri.split("/").map(escapeUri).join("/"); - -exports.escapeUri = escapeUri; -exports.escapeUriPath = escapeUriPath; diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/smithy-client/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/smithy-client/dist-cjs/index.js deleted file mode 100644 index 9f589873..00000000 --- a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/smithy-client/dist-cjs/index.js +++ /dev/null @@ -1,589 +0,0 @@ -'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]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js deleted file mode 100644 index b06a7b87..00000000 --- a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js +++ /dev/null @@ -1,16 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/index.js deleted file mode 100644 index c095e288..00000000 --- a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/index.js +++ /dev/null @@ -1,19 +0,0 @@ -'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]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/toBase64.js deleted file mode 100644 index 0590ce3f..00000000 --- a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/dist-cjs/toBase64.js +++ /dev/null @@ -1,19 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js deleted file mode 100644 index b577c9ca..00000000 --- a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js +++ /dev/null @@ -1,20 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js deleted file mode 100644 index 3238bb77..00000000 --- a/claude-code-source/node_modules/@aws-sdk/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || - Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; - -exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-cjs/index.js deleted file mode 100644 index 536f926f..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-cjs/index.js +++ /dev/null @@ -1,204 +0,0 @@ -'use strict'; - -var propertyProvider = require('@smithy/property-provider'); - -function resolveLogins(logins) { - return Promise.all(Object.keys(logins).reduce((arr, name) => { - const tokenOrProvider = logins[name]; - if (typeof tokenOrProvider === "string") { - arr.push([name, tokenOrProvider]); - } - else { - arr.push(tokenOrProvider().then((token) => [name, token])); - } - return arr; - }, [])).then((resolvedPairs) => resolvedPairs.reduce((logins, [key, value]) => { - logins[key] = value; - return logins; - }, {})); -} - -function fromCognitoIdentity(parameters) { - return async (awsIdentityProperties) => { - parameters.logger?.debug("@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity"); - const { GetCredentialsForIdentityCommand, CognitoIdentityClient } = await Promise.resolve().then(function () { return require('./loadCognitoIdentity-BPNvueUJ.js'); }); - const fromConfigs = (property) => parameters.clientConfig?.[property] ?? - parameters.parentClientConfig?.[property] ?? - awsIdentityProperties?.callerClientConfig?.[property]; - const { Credentials: { AccessKeyId = throwOnMissingAccessKeyId(parameters.logger), Expiration, SecretKey = throwOnMissingSecretKey(parameters.logger), SessionToken, } = throwOnMissingCredentials(parameters.logger), } = await (parameters.client ?? - new CognitoIdentityClient(Object.assign({}, parameters.clientConfig ?? {}, { - region: fromConfigs("region"), - profile: fromConfigs("profile"), - userAgentAppId: fromConfigs("userAgentAppId"), - }))).send(new GetCredentialsForIdentityCommand({ - CustomRoleArn: parameters.customRoleArn, - IdentityId: parameters.identityId, - Logins: parameters.logins ? await resolveLogins(parameters.logins) : undefined, - })); - return { - identityId: parameters.identityId, - accessKeyId: AccessKeyId, - secretAccessKey: SecretKey, - sessionToken: SessionToken, - expiration: Expiration, - }; - }; -} -function throwOnMissingAccessKeyId(logger) { - throw new propertyProvider.CredentialsProviderError("Response from Amazon Cognito contained no access key ID", { logger }); -} -function throwOnMissingCredentials(logger) { - throw new propertyProvider.CredentialsProviderError("Response from Amazon Cognito contained no credentials", { logger }); -} -function throwOnMissingSecretKey(logger) { - throw new propertyProvider.CredentialsProviderError("Response from Amazon Cognito contained no secret key", { logger }); -} - -const STORE_NAME = "IdentityIds"; -class IndexedDbStorage { - dbName; - constructor(dbName = "aws:cognito-identity-ids") { - this.dbName = dbName; - } - getItem(key) { - return this.withObjectStore("readonly", (store) => { - const req = store.get(key); - return new Promise((resolve) => { - req.onerror = () => resolve(null); - req.onsuccess = () => resolve(req.result ? req.result.value : null); - }); - }).catch(() => null); - } - removeItem(key) { - return this.withObjectStore("readwrite", (store) => { - const req = store.delete(key); - return new Promise((resolve, reject) => { - req.onerror = () => reject(req.error); - req.onsuccess = () => resolve(); - }); - }); - } - setItem(id, value) { - return this.withObjectStore("readwrite", (store) => { - const req = store.put({ id, value }); - return new Promise((resolve, reject) => { - req.onerror = () => reject(req.error); - req.onsuccess = () => resolve(); - }); - }); - } - getDb() { - const openDbRequest = self.indexedDB.open(this.dbName, 1); - return new Promise((resolve, reject) => { - openDbRequest.onsuccess = () => { - resolve(openDbRequest.result); - }; - openDbRequest.onerror = () => { - reject(openDbRequest.error); - }; - openDbRequest.onblocked = () => { - reject(new Error("Unable to access DB")); - }; - openDbRequest.onupgradeneeded = () => { - const db = openDbRequest.result; - db.onerror = () => { - reject(new Error("Failed to create object store")); - }; - db.createObjectStore(STORE_NAME, { keyPath: "id" }); - }; - }); - } - withObjectStore(mode, action) { - return this.getDb().then((db) => { - const tx = db.transaction(STORE_NAME, mode); - tx.oncomplete = () => db.close(); - return new Promise((resolve, reject) => { - tx.onerror = () => reject(tx.error); - resolve(action(tx.objectStore(STORE_NAME))); - }).catch((err) => { - db.close(); - throw err; - }); - }); - } -} - -class InMemoryStorage { - store; - constructor(store = {}) { - this.store = store; - } - getItem(key) { - if (key in this.store) { - return this.store[key]; - } - return null; - } - removeItem(key) { - delete this.store[key]; - } - setItem(key, value) { - this.store[key] = value; - } -} - -const inMemoryStorage = new InMemoryStorage(); -function localStorage() { - if (typeof self === "object" && self.indexedDB) { - return new IndexedDbStorage(); - } - if (typeof window === "object" && window.localStorage) { - return window.localStorage; - } - return inMemoryStorage; -} - -function fromCognitoIdentityPool({ accountId, cache = localStorage(), client, clientConfig, customRoleArn, identityPoolId, logins, userIdentifier = !logins || Object.keys(logins).length === 0 ? "ANONYMOUS" : undefined, logger, parentClientConfig, }) { - logger?.debug("@aws-sdk/credential-provider-cognito-identity - fromCognitoIdentity"); - const cacheKey = userIdentifier - ? `aws:cognito-identity-credentials:${identityPoolId}:${userIdentifier}` - : undefined; - let provider = async (awsIdentityProperties) => { - const { GetIdCommand, CognitoIdentityClient } = await Promise.resolve().then(function () { return require('./loadCognitoIdentity-BPNvueUJ.js'); }); - const fromConfigs = (property) => clientConfig?.[property] ?? - parentClientConfig?.[property] ?? - awsIdentityProperties?.callerClientConfig?.[property]; - const _client = client ?? - new CognitoIdentityClient(Object.assign({}, clientConfig ?? {}, { - region: fromConfigs("region"), - profile: fromConfigs("profile"), - userAgentAppId: fromConfigs("userAgentAppId"), - })); - let identityId = (cacheKey && (await cache.getItem(cacheKey))); - if (!identityId) { - const { IdentityId = throwOnMissingId(logger) } = await _client.send(new GetIdCommand({ - AccountId: accountId, - IdentityPoolId: identityPoolId, - Logins: logins ? await resolveLogins(logins) : undefined, - })); - identityId = IdentityId; - if (cacheKey) { - Promise.resolve(cache.setItem(cacheKey, identityId)).catch(() => { }); - } - } - provider = fromCognitoIdentity({ - client: _client, - customRoleArn, - logins, - identityId, - }); - return provider(awsIdentityProperties); - }; - return (awsIdentityProperties) => provider(awsIdentityProperties).catch(async (err) => { - if (cacheKey) { - Promise.resolve(cache.removeItem(cacheKey)).catch(() => { }); - } - throw err; - }); -} -function throwOnMissingId(logger) { - throw new propertyProvider.CredentialsProviderError("Response from Amazon Cognito contained no identity ID", { logger }); -} - -exports.fromCognitoIdentity = fromCognitoIdentity; -exports.fromCognitoIdentityPool = fromCognitoIdentityPool; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-cjs/loadCognitoIdentity-BPNvueUJ.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-cjs/loadCognitoIdentity-BPNvueUJ.js deleted file mode 100644 index 0170766a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-cognito-identity/dist-cjs/loadCognitoIdentity-BPNvueUJ.js +++ /dev/null @@ -1,18 +0,0 @@ -'use strict'; - -var clientCognitoIdentity = require('@aws-sdk/client-cognito-identity'); - - - -Object.defineProperty(exports, "CognitoIdentityClient", { - enumerable: true, - get: function () { return clientCognitoIdentity.CognitoIdentityClient; } -}); -Object.defineProperty(exports, "GetCredentialsForIdentityCommand", { - enumerable: true, - get: function () { return clientCognitoIdentity.GetCredentialsForIdentityCommand; } -}); -Object.defineProperty(exports, "GetIdCommand", { - enumerable: true, - get: function () { return clientCognitoIdentity.GetIdCommand; } -}); diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-env/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-env/dist-cjs/index.js deleted file mode 100644 index 74d76aac..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-env/dist-cjs/index.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -var client = require('@aws-sdk/core/client'); -var propertyProvider = require('@smithy/property-provider'); - -const ENV_KEY = "AWS_ACCESS_KEY_ID"; -const ENV_SECRET = "AWS_SECRET_ACCESS_KEY"; -const ENV_SESSION = "AWS_SESSION_TOKEN"; -const ENV_EXPIRATION = "AWS_CREDENTIAL_EXPIRATION"; -const ENV_CREDENTIAL_SCOPE = "AWS_CREDENTIAL_SCOPE"; -const ENV_ACCOUNT_ID = "AWS_ACCOUNT_ID"; -const fromEnv = (init) => async () => { - init?.logger?.debug("@aws-sdk/credential-provider-env - fromEnv"); - const accessKeyId = process.env[ENV_KEY]; - const secretAccessKey = process.env[ENV_SECRET]; - const sessionToken = process.env[ENV_SESSION]; - const expiry = process.env[ENV_EXPIRATION]; - const credentialScope = process.env[ENV_CREDENTIAL_SCOPE]; - const accountId = process.env[ENV_ACCOUNT_ID]; - if (accessKeyId && secretAccessKey) { - const credentials = { - accessKeyId, - secretAccessKey, - ...(sessionToken && { sessionToken }), - ...(expiry && { expiration: new Date(expiry) }), - ...(credentialScope && { credentialScope }), - ...(accountId && { accountId }), - }; - client.setCredentialFeature(credentials, "CREDENTIALS_ENV_VARS", "g"); - return credentials; - } - throw new propertyProvider.CredentialsProviderError("Unable to find environment variable credentials.", { logger: init?.logger }); -}; - -exports.ENV_ACCOUNT_ID = ENV_ACCOUNT_ID; -exports.ENV_CREDENTIAL_SCOPE = ENV_CREDENTIAL_SCOPE; -exports.ENV_EXPIRATION = ENV_EXPIRATION; -exports.ENV_KEY = ENV_KEY; -exports.ENV_SECRET = ENV_SECRET; -exports.ENV_SESSION = ENV_SESSION; -exports.fromEnv = fromEnv; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/checkUrl.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/checkUrl.js deleted file mode 100644 index c4adb5f9..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/checkUrl.js +++ /dev/null @@ -1,46 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.checkUrl = void 0; -const property_provider_1 = require("@smithy/property-provider"); -const LOOPBACK_CIDR_IPv4 = "127.0.0.0/8"; -const LOOPBACK_CIDR_IPv6 = "::1/128"; -const ECS_CONTAINER_HOST = "169.254.170.2"; -const EKS_CONTAINER_HOST_IPv4 = "169.254.170.23"; -const EKS_CONTAINER_HOST_IPv6 = "[fd00:ec2::23]"; -const checkUrl = (url, logger) => { - if (url.protocol === "https:") { - return; - } - if (url.hostname === ECS_CONTAINER_HOST || - url.hostname === EKS_CONTAINER_HOST_IPv4 || - url.hostname === EKS_CONTAINER_HOST_IPv6) { - return; - } - if (url.hostname.includes("[")) { - if (url.hostname === "[::1]" || url.hostname === "[0000:0000:0000:0000:0000:0000:0000:0001]") { - return; - } - } - else { - if (url.hostname === "localhost") { - return; - } - const ipComponents = url.hostname.split("."); - const inRange = (component) => { - const num = parseInt(component, 10); - return 0 <= num && num <= 255; - }; - if (ipComponents[0] === "127" && - inRange(ipComponents[1]) && - inRange(ipComponents[2]) && - inRange(ipComponents[3]) && - ipComponents.length === 4) { - return; - } - } - throw new property_provider_1.CredentialsProviderError(`URL not accepted. It must either be HTTPS or match one of the following: - - loopback CIDR 127.0.0.0/8 or [::1/128] - - ECS container host 169.254.170.2 - - EKS container host 169.254.170.23 or [fd00:ec2::23]`, { logger }); -}; -exports.checkUrl = checkUrl; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/fromHttp.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/fromHttp.js deleted file mode 100644 index ea602512..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/fromHttp.js +++ /dev/null @@ -1,70 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromHttp = void 0; -const tslib_1 = require("tslib"); -const client_1 = require("@aws-sdk/core/client"); -const node_http_handler_1 = require("@smithy/node-http-handler"); -const property_provider_1 = require("@smithy/property-provider"); -const promises_1 = tslib_1.__importDefault(require("fs/promises")); -const checkUrl_1 = require("./checkUrl"); -const requestHelpers_1 = require("./requestHelpers"); -const retry_wrapper_1 = require("./retry-wrapper"); -const AWS_CONTAINER_CREDENTIALS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; -const DEFAULT_LINK_LOCAL_HOST = "http://169.254.170.2"; -const AWS_CONTAINER_CREDENTIALS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; -const AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE = "AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE"; -const AWS_CONTAINER_AUTHORIZATION_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; -const fromHttp = (options = {}) => { - options.logger?.debug("@aws-sdk/credential-provider-http - fromHttp"); - let host; - const relative = options.awsContainerCredentialsRelativeUri ?? process.env[AWS_CONTAINER_CREDENTIALS_RELATIVE_URI]; - const full = options.awsContainerCredentialsFullUri ?? process.env[AWS_CONTAINER_CREDENTIALS_FULL_URI]; - const token = options.awsContainerAuthorizationToken ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN]; - const tokenFile = options.awsContainerAuthorizationTokenFile ?? process.env[AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE]; - const warn = options.logger?.constructor?.name === "NoOpLogger" || !options.logger?.warn - ? console.warn - : options.logger.warn.bind(options.logger); - if (relative && full) { - warn("@aws-sdk/credential-provider-http: " + - "you have set both awsContainerCredentialsRelativeUri and awsContainerCredentialsFullUri."); - warn("awsContainerCredentialsFullUri will take precedence."); - } - if (token && tokenFile) { - warn("@aws-sdk/credential-provider-http: " + - "you have set both awsContainerAuthorizationToken and awsContainerAuthorizationTokenFile."); - warn("awsContainerAuthorizationToken will take precedence."); - } - if (full) { - host = full; - } - else if (relative) { - host = `${DEFAULT_LINK_LOCAL_HOST}${relative}`; - } - else { - throw new property_provider_1.CredentialsProviderError(`No HTTP credential provider host provided. -Set AWS_CONTAINER_CREDENTIALS_FULL_URI or AWS_CONTAINER_CREDENTIALS_RELATIVE_URI.`, { logger: options.logger }); - } - const url = new URL(host); - (0, checkUrl_1.checkUrl)(url, options.logger); - const requestHandler = node_http_handler_1.NodeHttpHandler.create({ - requestTimeout: options.timeout ?? 1000, - connectionTimeout: options.timeout ?? 1000, - }); - return (0, retry_wrapper_1.retryWrapper)(async () => { - const request = (0, requestHelpers_1.createGetRequest)(url); - if (token) { - request.headers.Authorization = token; - } - else if (tokenFile) { - request.headers.Authorization = (await promises_1.default.readFile(tokenFile)).toString(); - } - try { - const result = await requestHandler.handle(request); - return (0, requestHelpers_1.getCredentials)(result.response).then((creds) => (0, client_1.setCredentialFeature)(creds, "CREDENTIALS_HTTP", "z")); - } - catch (e) { - throw new property_provider_1.CredentialsProviderError(String(e), { logger: options.logger }); - } - }, options.maxRetries ?? 3, options.timeout ?? 1000); -}; -exports.fromHttp = fromHttp; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/requestHelpers.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/requestHelpers.js deleted file mode 100644 index 48159a32..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/requestHelpers.js +++ /dev/null @@ -1,53 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createGetRequest = createGetRequest; -exports.getCredentials = getCredentials; -const property_provider_1 = require("@smithy/property-provider"); -const protocol_http_1 = require("@smithy/protocol-http"); -const smithy_client_1 = require("@smithy/smithy-client"); -const util_stream_1 = require("@smithy/util-stream"); -function createGetRequest(url) { - return new protocol_http_1.HttpRequest({ - protocol: url.protocol, - hostname: url.hostname, - port: Number(url.port), - path: url.pathname, - query: Array.from(url.searchParams.entries()).reduce((acc, [k, v]) => { - acc[k] = v; - return acc; - }, {}), - fragment: url.hash, - }); -} -async function getCredentials(response, logger) { - const stream = (0, util_stream_1.sdkStreamMixin)(response.body); - const str = await stream.transformToString(); - if (response.statusCode === 200) { - const parsed = JSON.parse(str); - if (typeof parsed.AccessKeyId !== "string" || - typeof parsed.SecretAccessKey !== "string" || - typeof parsed.Token !== "string" || - typeof parsed.Expiration !== "string") { - throw new property_provider_1.CredentialsProviderError("HTTP credential provider response not of the required format, an object matching: " + - "{ AccessKeyId: string, SecretAccessKey: string, Token: string, Expiration: string(rfc3339) }", { logger }); - } - return { - accessKeyId: parsed.AccessKeyId, - secretAccessKey: parsed.SecretAccessKey, - sessionToken: parsed.Token, - expiration: (0, smithy_client_1.parseRfc3339DateTime)(parsed.Expiration), - }; - } - if (response.statusCode >= 400 && response.statusCode < 500) { - let parsedBody = {}; - try { - parsedBody = JSON.parse(str); - } - catch (e) { } - throw Object.assign(new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }), { - Code: parsedBody.Code, - Message: parsedBody.Message, - }); - } - throw new property_provider_1.CredentialsProviderError(`Server responded with status: ${response.statusCode}`, { logger }); -} diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/retry-wrapper.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/retry-wrapper.js deleted file mode 100644 index b99b2efa..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/fromHttp/retry-wrapper.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.retryWrapper = void 0; -const retryWrapper = (toRetry, maxRetries, delayMs) => { - return async () => { - for (let i = 0; i < maxRetries; ++i) { - try { - return await toRetry(); - } - catch (e) { - await new Promise((resolve) => setTimeout(resolve, delayMs)); - } - } - return await toRetry(); - }; -}; -exports.retryWrapper = retryWrapper; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/index.js deleted file mode 100644 index 0286ea03..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/dist-cjs/index.js +++ /dev/null @@ -1,5 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromHttp = void 0; -var fromHttp_1 = require("./fromHttp/fromHttp"); -Object.defineProperty(exports, "fromHttp", { enumerable: true, get: function () { return fromHttp_1.fromHttp; } }); diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 52303c3b..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,169 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-cjs/index.js deleted file mode 100644 index 9f589873..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/smithy-client/dist-cjs/index.js +++ /dev/null @@ -1,589 +0,0 @@ -'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]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-http/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js deleted file mode 100644 index 84cef661..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-ini/dist-cjs/index.js +++ /dev/null @@ -1,226 +0,0 @@ -'use strict'; - -var sharedIniFileLoader = require('@smithy/shared-ini-file-loader'); -var propertyProvider = require('@smithy/property-provider'); -var client = require('@aws-sdk/core/client'); -var credentialProviderLogin = require('@aws-sdk/credential-provider-login'); - -const resolveCredentialSource = (credentialSource, profileName, logger) => { - const sourceProvidersMap = { - EcsContainer: async (options) => { - const { fromHttp } = await import('@aws-sdk/credential-provider-http'); - const { fromContainerMetadata } = await import('@smithy/credential-provider-imds'); - logger?.debug("@aws-sdk/credential-provider-ini - credential_source is EcsContainer"); - return async () => propertyProvider.chain(fromHttp(options ?? {}), fromContainerMetadata(options))().then(setNamedProvider); - }, - Ec2InstanceMetadata: async (options) => { - logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Ec2InstanceMetadata"); - const { fromInstanceMetadata } = await import('@smithy/credential-provider-imds'); - return async () => fromInstanceMetadata(options)().then(setNamedProvider); - }, - Environment: async (options) => { - logger?.debug("@aws-sdk/credential-provider-ini - credential_source is Environment"); - const { fromEnv } = await import('@aws-sdk/credential-provider-env'); - return async () => fromEnv(options)().then(setNamedProvider); - }, - }; - if (credentialSource in sourceProvidersMap) { - return sourceProvidersMap[credentialSource]; - } - else { - throw new propertyProvider.CredentialsProviderError(`Unsupported credential source in profile ${profileName}. Got ${credentialSource}, ` + - `expected EcsContainer or Ec2InstanceMetadata or Environment.`, { logger }); - } -}; -const setNamedProvider = (creds) => client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_NAMED_PROVIDER", "p"); - -const isAssumeRoleProfile = (arg, { profile = "default", logger } = {}) => { - return (Boolean(arg) && - typeof arg === "object" && - typeof arg.role_arn === "string" && - ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1 && - ["undefined", "string"].indexOf(typeof arg.external_id) > -1 && - ["undefined", "string"].indexOf(typeof arg.mfa_serial) > -1 && - (isAssumeRoleWithSourceProfile(arg, { profile, logger }) || isCredentialSourceProfile(arg, { profile, logger }))); -}; -const isAssumeRoleWithSourceProfile = (arg, { profile, logger }) => { - const withSourceProfile = typeof arg.source_profile === "string" && typeof arg.credential_source === "undefined"; - if (withSourceProfile) { - logger?.debug?.(` ${profile} isAssumeRoleWithSourceProfile source_profile=${arg.source_profile}`); - } - return withSourceProfile; -}; -const isCredentialSourceProfile = (arg, { profile, logger }) => { - const withProviderProfile = typeof arg.credential_source === "string" && typeof arg.source_profile === "undefined"; - if (withProviderProfile) { - logger?.debug?.(` ${profile} isCredentialSourceProfile credential_source=${arg.credential_source}`); - } - return withProviderProfile; -}; -const resolveAssumeRoleCredentials = async (profileName, profiles, options, visitedProfiles = {}, resolveProfileData) => { - options.logger?.debug("@aws-sdk/credential-provider-ini - resolveAssumeRoleCredentials (STS)"); - const profileData = profiles[profileName]; - const { source_profile, region } = profileData; - if (!options.roleAssumer) { - const { getDefaultRoleAssumer } = await import('@aws-sdk/nested-clients/sts'); - options.roleAssumer = getDefaultRoleAssumer({ - ...options.clientConfig, - credentialProviderLogger: options.logger, - parentClientConfig: { - ...options?.parentClientConfig, - region: region ?? options?.parentClientConfig?.region, - }, - }, options.clientPlugins); - } - if (source_profile && source_profile in visitedProfiles) { - throw new propertyProvider.CredentialsProviderError(`Detected a cycle attempting to resolve credentials for profile` + - ` ${sharedIniFileLoader.getProfileName(options)}. Profiles visited: ` + - Object.keys(visitedProfiles).join(", "), { logger: options.logger }); - } - options.logger?.debug(`@aws-sdk/credential-provider-ini - finding credential resolver using ${source_profile ? `source_profile=[${source_profile}]` : `profile=[${profileName}]`}`); - const sourceCredsProvider = source_profile - ? resolveProfileData(source_profile, profiles, options, { - ...visitedProfiles, - [source_profile]: true, - }, isCredentialSourceWithoutRoleArn(profiles[source_profile] ?? {})) - : (await resolveCredentialSource(profileData.credential_source, profileName, options.logger)(options))(); - if (isCredentialSourceWithoutRoleArn(profileData)) { - return sourceCredsProvider.then((creds) => client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o")); - } - else { - const params = { - RoleArn: profileData.role_arn, - RoleSessionName: profileData.role_session_name || `aws-sdk-js-${Date.now()}`, - ExternalId: profileData.external_id, - DurationSeconds: parseInt(profileData.duration_seconds || "3600", 10), - }; - const { mfa_serial } = profileData; - if (mfa_serial) { - if (!options.mfaCodeProvider) { - throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} requires multi-factor authentication, but no MFA code callback was provided.`, { logger: options.logger, tryNextLink: false }); - } - params.SerialNumber = mfa_serial; - params.TokenCode = await options.mfaCodeProvider(mfa_serial); - } - const sourceCreds = await sourceCredsProvider; - return options.roleAssumer(sourceCreds, params).then((creds) => client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SOURCE_PROFILE", "o")); - } -}; -const isCredentialSourceWithoutRoleArn = (section) => { - return !section.role_arn && !!section.credential_source; -}; - -const isLoginProfile = (data) => { - return Boolean(data && data.login_session); -}; -const resolveLoginCredentials = async (profileName, options) => { - const credentials = await credentialProviderLogin.fromLoginCredentials({ - ...options, - profile: profileName, - })(); - return client.setCredentialFeature(credentials, "CREDENTIALS_PROFILE_LOGIN", "AC"); -}; - -const isProcessProfile = (arg) => Boolean(arg) && typeof arg === "object" && typeof arg.credential_process === "string"; -const resolveProcessCredentials = async (options, profile) => import('@aws-sdk/credential-provider-process').then(({ fromProcess }) => fromProcess({ - ...options, - profile, -})().then((creds) => client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_PROCESS", "v"))); - -const resolveSsoCredentials = async (profile, profileData, options = {}) => { - const { fromSSO } = await import('@aws-sdk/credential-provider-sso'); - return fromSSO({ - profile, - logger: options.logger, - parentClientConfig: options.parentClientConfig, - clientConfig: options.clientConfig, - })().then((creds) => { - if (profileData.sso_session) { - return client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SSO", "r"); - } - else { - return client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_SSO_LEGACY", "t"); - } - }); -}; -const isSsoProfile = (arg) => arg && - (typeof arg.sso_start_url === "string" || - typeof arg.sso_account_id === "string" || - typeof arg.sso_session === "string" || - typeof arg.sso_region === "string" || - typeof arg.sso_role_name === "string"); - -const isStaticCredsProfile = (arg) => Boolean(arg) && - typeof arg === "object" && - typeof arg.aws_access_key_id === "string" && - typeof arg.aws_secret_access_key === "string" && - ["undefined", "string"].indexOf(typeof arg.aws_session_token) > -1 && - ["undefined", "string"].indexOf(typeof arg.aws_account_id) > -1; -const resolveStaticCredentials = async (profile, options) => { - options?.logger?.debug("@aws-sdk/credential-provider-ini - resolveStaticCredentials"); - const credentials = { - accessKeyId: profile.aws_access_key_id, - secretAccessKey: profile.aws_secret_access_key, - sessionToken: profile.aws_session_token, - ...(profile.aws_credential_scope && { credentialScope: profile.aws_credential_scope }), - ...(profile.aws_account_id && { accountId: profile.aws_account_id }), - }; - return client.setCredentialFeature(credentials, "CREDENTIALS_PROFILE", "n"); -}; - -const isWebIdentityProfile = (arg) => Boolean(arg) && - typeof arg === "object" && - typeof arg.web_identity_token_file === "string" && - typeof arg.role_arn === "string" && - ["undefined", "string"].indexOf(typeof arg.role_session_name) > -1; -const resolveWebIdentityCredentials = async (profile, options) => import('@aws-sdk/credential-provider-web-identity').then(({ fromTokenFile }) => fromTokenFile({ - webIdentityTokenFile: profile.web_identity_token_file, - roleArn: profile.role_arn, - roleSessionName: profile.role_session_name, - roleAssumerWithWebIdentity: options.roleAssumerWithWebIdentity, - logger: options.logger, - parentClientConfig: options.parentClientConfig, -})().then((creds) => client.setCredentialFeature(creds, "CREDENTIALS_PROFILE_STS_WEB_ID_TOKEN", "q"))); - -const resolveProfileData = async (profileName, profiles, options, visitedProfiles = {}, isAssumeRoleRecursiveCall = false) => { - const data = profiles[profileName]; - if (Object.keys(visitedProfiles).length > 0 && isStaticCredsProfile(data)) { - return resolveStaticCredentials(data, options); - } - if (isAssumeRoleRecursiveCall || isAssumeRoleProfile(data, { profile: profileName, logger: options.logger })) { - return resolveAssumeRoleCredentials(profileName, profiles, options, visitedProfiles, resolveProfileData); - } - if (isStaticCredsProfile(data)) { - return resolveStaticCredentials(data, options); - } - if (isWebIdentityProfile(data)) { - return resolveWebIdentityCredentials(data, options); - } - if (isProcessProfile(data)) { - return resolveProcessCredentials(options, profileName); - } - if (isSsoProfile(data)) { - return await resolveSsoCredentials(profileName, data, options); - } - if (isLoginProfile(data)) { - return resolveLoginCredentials(profileName, options); - } - throw new propertyProvider.CredentialsProviderError(`Could not resolve credentials using profile: [${profileName}] in configuration/credentials file(s).`, { logger: options.logger }); -}; - -const fromIni = (_init = {}) => async ({ callerClientConfig } = {}) => { - const init = { - ..._init, - parentClientConfig: { - ...callerClientConfig, - ..._init.parentClientConfig, - }, - }; - init.logger?.debug("@aws-sdk/credential-provider-ini - fromIni"); - const profiles = await sharedIniFileLoader.parseKnownFiles(init); - return resolveProfileData(sharedIniFileLoader.getProfileName({ - profile: _init.profile ?? callerClientConfig?.profile, - }), profiles, init); -}; - -exports.fromIni = fromIni; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-login/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-login/dist-cjs/index.js deleted file mode 100644 index 487bc23a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-login/dist-cjs/index.js +++ /dev/null @@ -1,286 +0,0 @@ -'use strict'; - -var client = require('@aws-sdk/core/client'); -var propertyProvider = require('@smithy/property-provider'); -var sharedIniFileLoader = require('@smithy/shared-ini-file-loader'); -var protocolHttp = require('@smithy/protocol-http'); -var node_crypto = require('node:crypto'); -var node_fs = require('node:fs'); -var node_os = require('node:os'); -var node_path = require('node:path'); - -class LoginCredentialsFetcher { - profileData; - init; - callerClientConfig; - static REFRESH_THRESHOLD = 5 * 60 * 1000; - constructor(profileData, init, callerClientConfig) { - this.profileData = profileData; - this.init = init; - this.callerClientConfig = callerClientConfig; - } - async loadCredentials() { - const token = await this.loadToken(); - if (!token) { - throw new propertyProvider.CredentialsProviderError(`Failed to load a token for session ${this.loginSession}, please re-authenticate using aws login`, { tryNextLink: false, logger: this.logger }); - } - const accessToken = token.accessToken; - const now = Date.now(); - const expiryTime = new Date(accessToken.expiresAt).getTime(); - const timeUntilExpiry = expiryTime - now; - if (timeUntilExpiry <= LoginCredentialsFetcher.REFRESH_THRESHOLD) { - return this.refresh(token); - } - return { - accessKeyId: accessToken.accessKeyId, - secretAccessKey: accessToken.secretAccessKey, - sessionToken: accessToken.sessionToken, - accountId: accessToken.accountId, - expiration: new Date(accessToken.expiresAt), - }; - } - get logger() { - return this.init?.logger; - } - get loginSession() { - return this.profileData.login_session; - } - async refresh(token) { - const { SigninClient, CreateOAuth2TokenCommand } = await import('@aws-sdk/nested-clients/signin'); - const { logger, userAgentAppId } = this.callerClientConfig ?? {}; - const isH2 = (requestHandler) => { - return requestHandler?.metadata?.handlerProtocol === "h2"; - }; - const requestHandler = isH2(this.callerClientConfig?.requestHandler) - ? undefined - : this.callerClientConfig?.requestHandler; - const region = this.profileData.region ?? (await this.callerClientConfig?.region?.()) ?? process.env.AWS_REGION; - const client = new SigninClient({ - credentials: { - accessKeyId: "", - secretAccessKey: "", - }, - region, - requestHandler, - logger, - userAgentAppId, - ...this.init?.clientConfig, - }); - this.createDPoPInterceptor(client.middlewareStack); - const commandInput = { - tokenInput: { - clientId: token.clientId, - refreshToken: token.refreshToken, - grantType: "refresh_token", - }, - }; - try { - const response = await client.send(new CreateOAuth2TokenCommand(commandInput)); - const { accessKeyId, secretAccessKey, sessionToken } = response.tokenOutput?.accessToken ?? {}; - const { refreshToken, expiresIn } = response.tokenOutput ?? {}; - if (!accessKeyId || !secretAccessKey || !sessionToken || !refreshToken) { - throw new propertyProvider.CredentialsProviderError("Token refresh response missing required fields", { - logger: this.logger, - tryNextLink: false, - }); - } - const expiresInMs = (expiresIn ?? 900) * 1000; - const expiration = new Date(Date.now() + expiresInMs); - const updatedToken = { - ...token, - accessToken: { - ...token.accessToken, - accessKeyId: accessKeyId, - secretAccessKey: secretAccessKey, - sessionToken: sessionToken, - expiresAt: expiration.toISOString(), - }, - refreshToken: refreshToken, - }; - await this.saveToken(updatedToken); - const newAccessToken = updatedToken.accessToken; - return { - accessKeyId: newAccessToken.accessKeyId, - secretAccessKey: newAccessToken.secretAccessKey, - sessionToken: newAccessToken.sessionToken, - accountId: newAccessToken.accountId, - expiration, - }; - } - catch (error) { - if (error.name === "AccessDeniedException") { - const errorType = error.error; - let message; - switch (errorType) { - case "TOKEN_EXPIRED": - message = "Your session has expired. Please reauthenticate."; - break; - case "USER_CREDENTIALS_CHANGED": - message = - "Unable to refresh credentials because of a change in your password. Please reauthenticate with your new password."; - break; - case "INSUFFICIENT_PERMISSIONS": - message = - "Unable to refresh credentials due to insufficient permissions. You may be missing permission for the 'CreateOAuth2Token' action."; - break; - default: - message = `Failed to refresh token: ${String(error)}. Please re-authenticate using \`aws login\``; - } - throw new propertyProvider.CredentialsProviderError(message, { logger: this.logger, tryNextLink: false }); - } - throw new propertyProvider.CredentialsProviderError(`Failed to refresh token: ${String(error)}. Please re-authenticate using aws login`, { logger: this.logger }); - } - } - async loadToken() { - const tokenFilePath = this.getTokenFilePath(); - try { - let tokenData; - try { - tokenData = await sharedIniFileLoader.readFile(tokenFilePath, { ignoreCache: this.init?.ignoreCache }); - } - catch { - tokenData = await node_fs.promises.readFile(tokenFilePath, "utf8"); - } - const token = JSON.parse(tokenData); - const missingFields = ["accessToken", "clientId", "refreshToken", "dpopKey"].filter((k) => !token[k]); - if (!token.accessToken?.accountId) { - missingFields.push("accountId"); - } - if (missingFields.length > 0) { - throw new propertyProvider.CredentialsProviderError(`Token validation failed, missing fields: ${missingFields.join(", ")}`, { - logger: this.logger, - tryNextLink: false, - }); - } - return token; - } - catch (error) { - throw new propertyProvider.CredentialsProviderError(`Failed to load token from ${tokenFilePath}: ${String(error)}`, { - logger: this.logger, - tryNextLink: false, - }); - } - } - async saveToken(token) { - const tokenFilePath = this.getTokenFilePath(); - const directory = node_path.dirname(tokenFilePath); - try { - await node_fs.promises.mkdir(directory, { recursive: true }); - } - catch (error) { - } - await node_fs.promises.writeFile(tokenFilePath, JSON.stringify(token, null, 2), "utf8"); - } - getTokenFilePath() { - const directory = process.env.AWS_LOGIN_CACHE_DIRECTORY ?? node_path.join(node_os.homedir(), ".aws", "login", "cache"); - const loginSessionBytes = Buffer.from(this.loginSession, "utf8"); - const loginSessionSha256 = node_crypto.createHash("sha256").update(loginSessionBytes).digest("hex"); - return node_path.join(directory, `${loginSessionSha256}.json`); - } - derToRawSignature(derSignature) { - let offset = 2; - if (derSignature[offset] !== 0x02) { - throw new Error("Invalid DER signature"); - } - offset++; - const rLength = derSignature[offset++]; - let r = derSignature.subarray(offset, offset + rLength); - offset += rLength; - if (derSignature[offset] !== 0x02) { - throw new Error("Invalid DER signature"); - } - offset++; - const sLength = derSignature[offset++]; - let s = derSignature.subarray(offset, offset + sLength); - r = r[0] === 0x00 ? r.subarray(1) : r; - s = s[0] === 0x00 ? s.subarray(1) : s; - const rPadded = Buffer.concat([Buffer.alloc(32 - r.length), r]); - const sPadded = Buffer.concat([Buffer.alloc(32 - s.length), s]); - return Buffer.concat([rPadded, sPadded]); - } - createDPoPInterceptor(middlewareStack) { - middlewareStack.add((next) => async (args) => { - if (protocolHttp.HttpRequest.isInstance(args.request)) { - const request = args.request; - const actualEndpoint = `${request.protocol}//${request.hostname}${request.port ? `:${request.port}` : ""}${request.path}`; - const dpop = await this.generateDpop(request.method, actualEndpoint); - request.headers = { - ...request.headers, - DPoP: dpop, - }; - } - return next(args); - }, { - step: "finalizeRequest", - name: "dpopInterceptor", - override: true, - }); - } - async generateDpop(method = "POST", endpoint) { - const token = await this.loadToken(); - try { - const privateKey = node_crypto.createPrivateKey({ - key: token.dpopKey, - format: "pem", - type: "sec1", - }); - const publicKey = node_crypto.createPublicKey(privateKey); - const publicDer = publicKey.export({ format: "der", type: "spki" }); - let pointStart = -1; - for (let i = 0; i < publicDer.length; i++) { - if (publicDer[i] === 0x04) { - pointStart = i; - break; - } - } - const x = publicDer.slice(pointStart + 1, pointStart + 33); - const y = publicDer.slice(pointStart + 33, pointStart + 65); - const header = { - alg: "ES256", - typ: "dpop+jwt", - jwk: { - kty: "EC", - crv: "P-256", - x: x.toString("base64url"), - y: y.toString("base64url"), - }, - }; - const payload = { - jti: crypto.randomUUID(), - htm: method, - htu: endpoint, - iat: Math.floor(Date.now() / 1000), - }; - const headerB64 = Buffer.from(JSON.stringify(header)).toString("base64url"); - const payloadB64 = Buffer.from(JSON.stringify(payload)).toString("base64url"); - const message = `${headerB64}.${payloadB64}`; - const asn1Signature = node_crypto.sign("sha256", Buffer.from(message), privateKey); - const rawSignature = this.derToRawSignature(asn1Signature); - const signatureB64 = rawSignature.toString("base64url"); - return `${message}.${signatureB64}`; - } - catch (error) { - throw new propertyProvider.CredentialsProviderError(`Failed to generate Dpop proof: ${error instanceof Error ? error.message : String(error)}`, { logger: this.logger, tryNextLink: false }); - } - } -} - -const fromLoginCredentials = (init) => async ({ callerClientConfig } = {}) => { - init?.logger?.debug?.("@aws-sdk/credential-providers - fromLoginCredentials"); - const profiles = await sharedIniFileLoader.parseKnownFiles(init || {}); - const profileName = sharedIniFileLoader.getProfileName({ - profile: init?.profile ?? callerClientConfig?.profile, - }); - const profile = profiles[profileName]; - if (!profile?.login_session) { - throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} does not contain login_session.`, { - tryNextLink: true, - logger: init?.logger, - }); - } - const fetcher = new LoginCredentialsFetcher(profile, init, callerClientConfig); - const credentials = await fetcher.loadCredentials(); - return client.setCredentialFeature(credentials, "CREDENTIALS_LOGIN", "AD"); -}; - -exports.fromLoginCredentials = fromLoginCredentials; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-login/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-login/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 52303c3b..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-login/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,169 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-login/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-login/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-login/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js deleted file mode 100644 index 64c1ae9d..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-node/dist-cjs/index.js +++ /dev/null @@ -1,150 +0,0 @@ -'use strict'; - -var credentialProviderEnv = require('@aws-sdk/credential-provider-env'); -var propertyProvider = require('@smithy/property-provider'); -var sharedIniFileLoader = require('@smithy/shared-ini-file-loader'); - -const ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; -const remoteProvider = async (init) => { - const { ENV_CMDS_FULL_URI, ENV_CMDS_RELATIVE_URI, fromContainerMetadata, fromInstanceMetadata } = await import('@smithy/credential-provider-imds'); - if (process.env[ENV_CMDS_RELATIVE_URI] || process.env[ENV_CMDS_FULL_URI]) { - init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromHttp/fromContainerMetadata"); - const { fromHttp } = await import('@aws-sdk/credential-provider-http'); - return propertyProvider.chain(fromHttp(init), fromContainerMetadata(init)); - } - if (process.env[ENV_IMDS_DISABLED] && process.env[ENV_IMDS_DISABLED] !== "false") { - return async () => { - throw new propertyProvider.CredentialsProviderError("EC2 Instance Metadata Service access disabled", { logger: init.logger }); - }; - } - init.logger?.debug("@aws-sdk/credential-provider-node - remoteProvider::fromInstanceMetadata"); - return fromInstanceMetadata(init); -}; - -function memoizeChain(providers, treatAsExpired) { - const chain = internalCreateChain(providers); - let activeLock; - let passiveLock; - let credentials; - const provider = async (options) => { - if (options?.forceRefresh) { - return await chain(options); - } - if (credentials?.expiration) { - if (credentials?.expiration?.getTime() < Date.now()) { - credentials = undefined; - } - } - if (activeLock) { - await activeLock; - } - else if (!credentials || treatAsExpired?.(credentials)) { - if (credentials) { - if (!passiveLock) { - passiveLock = chain(options).then((c) => { - credentials = c; - passiveLock = undefined; - }); - } - } - else { - activeLock = chain(options).then((c) => { - credentials = c; - activeLock = undefined; - }); - return provider(options); - } - } - return credentials; - }; - return provider; -} -const internalCreateChain = (providers) => async (awsIdentityProperties) => { - let lastProviderError; - for (const provider of providers) { - try { - return await provider(awsIdentityProperties); - } - catch (err) { - lastProviderError = err; - if (err?.tryNextLink) { - continue; - } - throw err; - } - } - throw lastProviderError; -}; - -let multipleCredentialSourceWarningEmitted = false; -const defaultProvider = (init = {}) => memoizeChain([ - async () => { - const profile = init.profile ?? process.env[sharedIniFileLoader.ENV_PROFILE]; - if (profile) { - const envStaticCredentialsAreSet = process.env[credentialProviderEnv.ENV_KEY] && process.env[credentialProviderEnv.ENV_SECRET]; - if (envStaticCredentialsAreSet) { - if (!multipleCredentialSourceWarningEmitted) { - const warnFn = init.logger?.warn && init.logger?.constructor?.name !== "NoOpLogger" - ? init.logger.warn.bind(init.logger) - : console.warn; - warnFn(`@aws-sdk/credential-provider-node - defaultProvider::fromEnv WARNING: - Multiple credential sources detected: - Both AWS_PROFILE and the pair AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY static credentials are set. - This SDK will proceed with the AWS_PROFILE value. - - However, a future version may change this behavior to prefer the ENV static credentials. - Please ensure that your environment only sets either the AWS_PROFILE or the - AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY pair. -`); - multipleCredentialSourceWarningEmitted = true; - } - } - throw new propertyProvider.CredentialsProviderError("AWS_PROFILE is set, skipping fromEnv provider.", { - logger: init.logger, - tryNextLink: true, - }); - } - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromEnv"); - return credentialProviderEnv.fromEnv(init)(); - }, - async (awsIdentityProperties) => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromSSO"); - const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; - if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { - throw new propertyProvider.CredentialsProviderError("Skipping SSO provider in default chain (inputs do not include SSO fields).", { logger: init.logger }); - } - const { fromSSO } = await import('@aws-sdk/credential-provider-sso'); - return fromSSO(init)(awsIdentityProperties); - }, - async (awsIdentityProperties) => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromIni"); - const { fromIni } = await import('@aws-sdk/credential-provider-ini'); - return fromIni(init)(awsIdentityProperties); - }, - async (awsIdentityProperties) => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromProcess"); - const { fromProcess } = await import('@aws-sdk/credential-provider-process'); - return fromProcess(init)(awsIdentityProperties); - }, - async (awsIdentityProperties) => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::fromTokenFile"); - const { fromTokenFile } = await import('@aws-sdk/credential-provider-web-identity'); - return fromTokenFile(init)(awsIdentityProperties); - }, - async () => { - init.logger?.debug("@aws-sdk/credential-provider-node - defaultProvider::remoteProvider"); - return (await remoteProvider(init))(); - }, - async () => { - throw new propertyProvider.CredentialsProviderError("Could not load credentials from any providers", { - tryNextLink: false, - logger: init.logger, - }); - }, -], credentialsTreatedAsExpired); -const credentialsWillNeedRefresh = (credentials) => credentials?.expiration !== undefined; -const credentialsTreatedAsExpired = (credentials) => credentials?.expiration !== undefined && credentials.expiration.getTime() - Date.now() < 300000; - -exports.credentialsTreatedAsExpired = credentialsTreatedAsExpired; -exports.credentialsWillNeedRefresh = credentialsWillNeedRefresh; -exports.defaultProvider = defaultProvider; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-process/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-process/dist-cjs/index.js deleted file mode 100644 index 911fd4c5..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-process/dist-cjs/index.js +++ /dev/null @@ -1,79 +0,0 @@ -'use strict'; - -var sharedIniFileLoader = require('@smithy/shared-ini-file-loader'); -var propertyProvider = require('@smithy/property-provider'); -var child_process = require('child_process'); -var util = require('util'); -var client = require('@aws-sdk/core/client'); - -const getValidatedProcessCredentials = (profileName, data, profiles) => { - if (data.Version !== 1) { - throw Error(`Profile ${profileName} credential_process did not return Version 1.`); - } - if (data.AccessKeyId === undefined || data.SecretAccessKey === undefined) { - throw Error(`Profile ${profileName} credential_process returned invalid credentials.`); - } - if (data.Expiration) { - const currentTime = new Date(); - const expireTime = new Date(data.Expiration); - if (expireTime < currentTime) { - throw Error(`Profile ${profileName} credential_process returned expired credentials.`); - } - } - let accountId = data.AccountId; - if (!accountId && profiles?.[profileName]?.aws_account_id) { - accountId = profiles[profileName].aws_account_id; - } - const credentials = { - accessKeyId: data.AccessKeyId, - secretAccessKey: data.SecretAccessKey, - ...(data.SessionToken && { sessionToken: data.SessionToken }), - ...(data.Expiration && { expiration: new Date(data.Expiration) }), - ...(data.CredentialScope && { credentialScope: data.CredentialScope }), - ...(accountId && { accountId }), - }; - client.setCredentialFeature(credentials, "CREDENTIALS_PROCESS", "w"); - return credentials; -}; - -const resolveProcessCredentials = async (profileName, profiles, logger) => { - const profile = profiles[profileName]; - if (profiles[profileName]) { - const credentialProcess = profile["credential_process"]; - if (credentialProcess !== undefined) { - const execPromise = util.promisify(sharedIniFileLoader.externalDataInterceptor?.getTokenRecord?.().exec ?? child_process.exec); - try { - const { stdout } = await execPromise(credentialProcess); - let data; - try { - data = JSON.parse(stdout.trim()); - } - catch { - throw Error(`Profile ${profileName} credential_process returned invalid JSON.`); - } - return getValidatedProcessCredentials(profileName, data, profiles); - } - catch (error) { - throw new propertyProvider.CredentialsProviderError(error.message, { logger }); - } - } - else { - throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} did not contain credential_process.`, { logger }); - } - } - else { - throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} could not be found in shared credentials file.`, { - logger, - }); - } -}; - -const fromProcess = (init = {}) => async ({ callerClientConfig } = {}) => { - init.logger?.debug("@aws-sdk/credential-provider-process - fromProcess"); - const profiles = await sharedIniFileLoader.parseKnownFiles(init); - return resolveProcessCredentials(sharedIniFileLoader.getProfileName({ - profile: init.profile ?? callerClientConfig?.profile, - }), profiles, init.logger); -}; - -exports.fromProcess = fromProcess; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js deleted file mode 100644 index f9f0324e..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/index.js +++ /dev/null @@ -1,190 +0,0 @@ -'use strict'; - -var propertyProvider = require('@smithy/property-provider'); -var sharedIniFileLoader = require('@smithy/shared-ini-file-loader'); -var client = require('@aws-sdk/core/client'); -var tokenProviders = require('@aws-sdk/token-providers'); - -const isSsoProfile = (arg) => arg && - (typeof arg.sso_start_url === "string" || - typeof arg.sso_account_id === "string" || - typeof arg.sso_session === "string" || - typeof arg.sso_region === "string" || - typeof arg.sso_role_name === "string"); - -const SHOULD_FAIL_CREDENTIAL_CHAIN = false; -const resolveSSOCredentials = async ({ ssoStartUrl, ssoSession, ssoAccountId, ssoRegion, ssoRoleName, ssoClient, clientConfig, parentClientConfig, profile, filepath, configFilepath, ignoreCache, logger, }) => { - let token; - const refreshMessage = `To refresh this SSO session run aws sso login with the corresponding profile.`; - if (ssoSession) { - try { - const _token = await tokenProviders.fromSso({ - profile, - filepath, - configFilepath, - ignoreCache, - })(); - token = { - accessToken: _token.token, - expiresAt: new Date(_token.expiration).toISOString(), - }; - } - catch (e) { - throw new propertyProvider.CredentialsProviderError(e.message, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger, - }); - } - } - else { - try { - token = await sharedIniFileLoader.getSSOTokenFromFile(ssoStartUrl); - } - catch (e) { - throw new propertyProvider.CredentialsProviderError(`The SSO session associated with this profile is invalid. ${refreshMessage}`, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger, - }); - } - } - if (new Date(token.expiresAt).getTime() - Date.now() <= 0) { - throw new propertyProvider.CredentialsProviderError(`The SSO session associated with this profile has expired. ${refreshMessage}`, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger, - }); - } - const { accessToken } = token; - const { SSOClient, GetRoleCredentialsCommand } = await Promise.resolve().then(function () { return require('./loadSso-CVy8iqsZ.js'); }); - const sso = ssoClient || - new SSOClient(Object.assign({}, clientConfig ?? {}, { - logger: clientConfig?.logger ?? parentClientConfig?.logger, - region: clientConfig?.region ?? ssoRegion, - userAgentAppId: clientConfig?.userAgentAppId ?? parentClientConfig?.userAgentAppId, - })); - let ssoResp; - try { - ssoResp = await sso.send(new GetRoleCredentialsCommand({ - accountId: ssoAccountId, - roleName: ssoRoleName, - accessToken, - })); - } - catch (e) { - throw new propertyProvider.CredentialsProviderError(e, { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger, - }); - } - const { roleCredentials: { accessKeyId, secretAccessKey, sessionToken, expiration, credentialScope, accountId } = {}, } = ssoResp; - if (!accessKeyId || !secretAccessKey || !sessionToken || !expiration) { - throw new propertyProvider.CredentialsProviderError("SSO returns an invalid temporary credential.", { - tryNextLink: SHOULD_FAIL_CREDENTIAL_CHAIN, - logger, - }); - } - const credentials = { - accessKeyId, - secretAccessKey, - sessionToken, - expiration: new Date(expiration), - ...(credentialScope && { credentialScope }), - ...(accountId && { accountId }), - }; - if (ssoSession) { - client.setCredentialFeature(credentials, "CREDENTIALS_SSO", "s"); - } - else { - client.setCredentialFeature(credentials, "CREDENTIALS_SSO_LEGACY", "u"); - } - return credentials; -}; - -const validateSsoProfile = (profile, logger) => { - const { sso_start_url, sso_account_id, sso_region, sso_role_name } = profile; - if (!sso_start_url || !sso_account_id || !sso_region || !sso_role_name) { - throw new propertyProvider.CredentialsProviderError(`Profile is configured with invalid SSO credentials. Required parameters "sso_account_id", ` + - `"sso_region", "sso_role_name", "sso_start_url". Got ${Object.keys(profile).join(", ")}\nReference: https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html`, { tryNextLink: false, logger }); - } - return profile; -}; - -const fromSSO = (init = {}) => async ({ callerClientConfig } = {}) => { - init.logger?.debug("@aws-sdk/credential-provider-sso - fromSSO"); - const { ssoStartUrl, ssoAccountId, ssoRegion, ssoRoleName, ssoSession } = init; - const { ssoClient } = init; - const profileName = sharedIniFileLoader.getProfileName({ - profile: init.profile ?? callerClientConfig?.profile, - }); - if (!ssoStartUrl && !ssoAccountId && !ssoRegion && !ssoRoleName && !ssoSession) { - const profiles = await sharedIniFileLoader.parseKnownFiles(init); - const profile = profiles[profileName]; - if (!profile) { - throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} was not found.`, { logger: init.logger }); - } - if (!isSsoProfile(profile)) { - throw new propertyProvider.CredentialsProviderError(`Profile ${profileName} is not configured with SSO credentials.`, { - logger: init.logger, - }); - } - if (profile?.sso_session) { - const ssoSessions = await sharedIniFileLoader.loadSsoSessionData(init); - const session = ssoSessions[profile.sso_session]; - const conflictMsg = ` configurations in profile ${profileName} and sso-session ${profile.sso_session}`; - if (ssoRegion && ssoRegion !== session.sso_region) { - throw new propertyProvider.CredentialsProviderError(`Conflicting SSO region` + conflictMsg, { - tryNextLink: false, - logger: init.logger, - }); - } - if (ssoStartUrl && ssoStartUrl !== session.sso_start_url) { - throw new propertyProvider.CredentialsProviderError(`Conflicting SSO start_url` + conflictMsg, { - tryNextLink: false, - logger: init.logger, - }); - } - profile.sso_region = session.sso_region; - profile.sso_start_url = session.sso_start_url; - } - const { sso_start_url, sso_account_id, sso_region, sso_role_name, sso_session } = validateSsoProfile(profile, init.logger); - return resolveSSOCredentials({ - ssoStartUrl: sso_start_url, - ssoSession: sso_session, - ssoAccountId: sso_account_id, - ssoRegion: sso_region, - ssoRoleName: sso_role_name, - ssoClient: ssoClient, - clientConfig: init.clientConfig, - parentClientConfig: init.parentClientConfig, - profile: profileName, - filepath: init.filepath, - configFilepath: init.configFilepath, - ignoreCache: init.ignoreCache, - logger: init.logger, - }); - } - else if (!ssoStartUrl || !ssoAccountId || !ssoRegion || !ssoRoleName) { - throw new propertyProvider.CredentialsProviderError("Incomplete configuration. The fromSSO() argument hash must include " + - '"ssoStartUrl", "ssoAccountId", "ssoRegion", "ssoRoleName"', { tryNextLink: false, logger: init.logger }); - } - else { - return resolveSSOCredentials({ - ssoStartUrl, - ssoSession, - ssoAccountId, - ssoRegion, - ssoRoleName, - ssoClient, - clientConfig: init.clientConfig, - parentClientConfig: init.parentClientConfig, - profile: profileName, - filepath: init.filepath, - configFilepath: init.configFilepath, - ignoreCache: init.ignoreCache, - logger: init.logger, - }); - } -}; - -exports.fromSSO = fromSSO; -exports.isSsoProfile = isSsoProfile; -exports.validateSsoProfile = validateSsoProfile; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/loadSso-CVy8iqsZ.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/loadSso-CVy8iqsZ.js deleted file mode 100644 index 93eb944f..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-sso/dist-cjs/loadSso-CVy8iqsZ.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var clientSso = require('@aws-sdk/client-sso'); - - - -Object.defineProperty(exports, "GetRoleCredentialsCommand", { - enumerable: true, - get: function () { return clientSso.GetRoleCredentialsCommand; } -}); -Object.defineProperty(exports, "SSOClient", { - enumerable: true, - get: function () { return clientSso.SSOClient; } -}); diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromTokenFile.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromTokenFile.js deleted file mode 100644 index e541fdb1..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromTokenFile.js +++ /dev/null @@ -1,34 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromTokenFile = void 0; -const client_1 = require("@aws-sdk/core/client"); -const property_provider_1 = require("@smithy/property-provider"); -const shared_ini_file_loader_1 = require("@smithy/shared-ini-file-loader"); -const fs_1 = require("fs"); -const fromWebToken_1 = require("./fromWebToken"); -const ENV_TOKEN_FILE = "AWS_WEB_IDENTITY_TOKEN_FILE"; -const ENV_ROLE_ARN = "AWS_ROLE_ARN"; -const ENV_ROLE_SESSION_NAME = "AWS_ROLE_SESSION_NAME"; -const fromTokenFile = (init = {}) => async (awsIdentityProperties) => { - init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromTokenFile"); - const webIdentityTokenFile = init?.webIdentityTokenFile ?? process.env[ENV_TOKEN_FILE]; - const roleArn = init?.roleArn ?? process.env[ENV_ROLE_ARN]; - const roleSessionName = init?.roleSessionName ?? process.env[ENV_ROLE_SESSION_NAME]; - if (!webIdentityTokenFile || !roleArn) { - throw new property_provider_1.CredentialsProviderError("Web identity configuration not specified", { - logger: init.logger, - }); - } - const credentials = await (0, fromWebToken_1.fromWebToken)({ - ...init, - webIdentityToken: shared_ini_file_loader_1.externalDataInterceptor?.getTokenRecord?.()[webIdentityTokenFile] ?? - (0, fs_1.readFileSync)(webIdentityTokenFile, { encoding: "ascii" }), - roleArn, - roleSessionName, - })(awsIdentityProperties); - if (webIdentityTokenFile === process.env[ENV_TOKEN_FILE]) { - (0, client_1.setCredentialFeature)(credentials, "CREDENTIALS_ENV_VARS_STS_WEB_ID_TOKEN", "h"); - } - return credentials; -}; -exports.fromTokenFile = fromTokenFile; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromWebToken.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromWebToken.js deleted file mode 100644 index b92af292..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/fromWebToken.js +++ /dev/null @@ -1,62 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromWebToken = void 0; -const fromWebToken = (init) => async (awsIdentityProperties) => { - init.logger?.debug("@aws-sdk/credential-provider-web-identity - fromWebToken"); - const { roleArn, roleSessionName, webIdentityToken, providerId, policyArns, policy, durationSeconds } = init; - let { roleAssumerWithWebIdentity } = init; - if (!roleAssumerWithWebIdentity) { - const { getDefaultRoleAssumerWithWebIdentity } = await Promise.resolve().then(() => __importStar(require("@aws-sdk/nested-clients/sts"))); - roleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity({ - ...init.clientConfig, - credentialProviderLogger: init.logger, - parentClientConfig: { - ...awsIdentityProperties?.callerClientConfig, - ...init.parentClientConfig, - }, - }, init.clientPlugins); - } - return roleAssumerWithWebIdentity({ - RoleArn: roleArn, - RoleSessionName: roleSessionName ?? `aws-sdk-js-session-${Date.now()}`, - WebIdentityToken: webIdentityToken, - ProviderId: providerId, - PolicyArns: policyArns, - Policy: policy, - DurationSeconds: durationSeconds, - }); -}; -exports.fromWebToken = fromWebToken; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/index.js deleted file mode 100644 index 7f405954..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-provider-web-identity/dist-cjs/index.js +++ /dev/null @@ -1,19 +0,0 @@ -'use strict'; - -var fromTokenFile = require('./fromTokenFile'); -var fromWebToken = require('./fromWebToken'); - - - -Object.keys(fromTokenFile).forEach(function (k) { - if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { - enumerable: true, - get: function () { return fromTokenFile[k]; } - }); -}); -Object.keys(fromWebToken).forEach(function (k) { - if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { - enumerable: true, - get: function () { return fromWebToken[k]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/createCredentialChain.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/createCredentialChain.js deleted file mode 100644 index 3488e1be..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/createCredentialChain.js +++ /dev/null @@ -1,45 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.propertyProviderChain = exports.createCredentialChain = void 0; -const property_provider_1 = require("@smithy/property-provider"); -const createCredentialChain = (...credentialProviders) => { - let expireAfter = -1; - const baseFunction = async (awsIdentityProperties) => { - const credentials = await (0, exports.propertyProviderChain)(...credentialProviders)(awsIdentityProperties); - if (!credentials.expiration && expireAfter !== -1) { - credentials.expiration = new Date(Date.now() + expireAfter); - } - return credentials; - }; - const withOptions = Object.assign(baseFunction, { - expireAfter(milliseconds) { - if (milliseconds < 5 * 60_000) { - throw new Error("@aws-sdk/credential-providers - createCredentialChain(...).expireAfter(ms) may not be called with a duration lower than five minutes."); - } - expireAfter = milliseconds; - return withOptions; - }, - }); - return withOptions; -}; -exports.createCredentialChain = createCredentialChain; -const propertyProviderChain = (...providers) => async (awsIdentityProperties) => { - if (providers.length === 0) { - throw new property_provider_1.ProviderError("No providers in chain", { tryNextLink: false }); - } - let lastProviderError; - for (const provider of providers) { - try { - return await provider(awsIdentityProperties); - } - catch (err) { - lastProviderError = err; - if (err?.tryNextLink) { - continue; - } - throw err; - } - } - throw lastProviderError; -}; -exports.propertyProviderChain = propertyProviderChain; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromCognitoIdentity.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromCognitoIdentity.js deleted file mode 100644 index 9e56e01d..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromCognitoIdentity.js +++ /dev/null @@ -1,8 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromCognitoIdentity = void 0; -const credential_provider_cognito_identity_1 = require("@aws-sdk/credential-provider-cognito-identity"); -const fromCognitoIdentity = (options) => (0, credential_provider_cognito_identity_1.fromCognitoIdentity)({ - ...options, -}); -exports.fromCognitoIdentity = fromCognitoIdentity; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromCognitoIdentityPool.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromCognitoIdentityPool.js deleted file mode 100644 index ed20c1d8..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromCognitoIdentityPool.js +++ /dev/null @@ -1,8 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromCognitoIdentityPool = void 0; -const credential_provider_cognito_identity_1 = require("@aws-sdk/credential-provider-cognito-identity"); -const fromCognitoIdentityPool = (options) => (0, credential_provider_cognito_identity_1.fromCognitoIdentityPool)({ - ...options, -}); -exports.fromCognitoIdentityPool = fromCognitoIdentityPool; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromContainerMetadata.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromContainerMetadata.js deleted file mode 100644 index 343bf80c..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromContainerMetadata.js +++ /dev/null @@ -1,9 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromContainerMetadata = void 0; -const credential_provider_imds_1 = require("@smithy/credential-provider-imds"); -const fromContainerMetadata = (init) => { - init?.logger?.debug("@smithy/credential-provider-imds", "fromContainerMetadata"); - return (0, credential_provider_imds_1.fromContainerMetadata)(init); -}; -exports.fromContainerMetadata = fromContainerMetadata; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromEnv.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromEnv.js deleted file mode 100644 index b3e82a6f..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromEnv.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromEnv = void 0; -const credential_provider_env_1 = require("@aws-sdk/credential-provider-env"); -const fromEnv = (init) => (0, credential_provider_env_1.fromEnv)(init); -exports.fromEnv = fromEnv; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromIni.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromIni.js deleted file mode 100644 index 139107ac..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromIni.js +++ /dev/null @@ -1,8 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromIni = void 0; -const credential_provider_ini_1 = require("@aws-sdk/credential-provider-ini"); -const fromIni = (init = {}) => (0, credential_provider_ini_1.fromIni)({ - ...init, -}); -exports.fromIni = fromIni; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromInstanceMetadata.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromInstanceMetadata.js deleted file mode 100644 index 57f70d04..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromInstanceMetadata.js +++ /dev/null @@ -1,10 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromInstanceMetadata = void 0; -const client_1 = require("@aws-sdk/core/client"); -const credential_provider_imds_1 = require("@smithy/credential-provider-imds"); -const fromInstanceMetadata = (init) => { - init?.logger?.debug("@smithy/credential-provider-imds", "fromInstanceMetadata"); - return async () => (0, credential_provider_imds_1.fromInstanceMetadata)(init)().then((creds) => (0, client_1.setCredentialFeature)(creds, "CREDENTIALS_IMDS", "0")); -}; -exports.fromInstanceMetadata = fromInstanceMetadata; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromLoginCredentials.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromLoginCredentials.js deleted file mode 100644 index c0d1ad61..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromLoginCredentials.js +++ /dev/null @@ -1,8 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromLoginCredentials = void 0; -const credential_provider_login_1 = require("@aws-sdk/credential-provider-login"); -const fromLoginCredentials = (init) => (0, credential_provider_login_1.fromLoginCredentials)({ - ...init, -}); -exports.fromLoginCredentials = fromLoginCredentials; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromNodeProviderChain.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromNodeProviderChain.js deleted file mode 100644 index 4082387a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromNodeProviderChain.js +++ /dev/null @@ -1,8 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromNodeProviderChain = void 0; -const credential_provider_node_1 = require("@aws-sdk/credential-provider-node"); -const fromNodeProviderChain = (init = {}) => (0, credential_provider_node_1.defaultProvider)({ - ...init, -}); -exports.fromNodeProviderChain = fromNodeProviderChain; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromProcess.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromProcess.js deleted file mode 100644 index 58a65abd..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromProcess.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromProcess = void 0; -const credential_provider_process_1 = require("@aws-sdk/credential-provider-process"); -const fromProcess = (init) => (0, credential_provider_process_1.fromProcess)(init); -exports.fromProcess = fromProcess; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromSSO.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromSSO.js deleted file mode 100644 index 7cf0fb4a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromSSO.js +++ /dev/null @@ -1,8 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromSSO = void 0; -const credential_provider_sso_1 = require("@aws-sdk/credential-provider-sso"); -const fromSSO = (init = {}) => { - return (0, credential_provider_sso_1.fromSSO)({ ...init }); -}; -exports.fromSSO = fromSSO; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTemporaryCredentials.base.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTemporaryCredentials.base.js deleted file mode 100644 index 0648aed3..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTemporaryCredentials.base.js +++ /dev/null @@ -1,155 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || (function () { - var ownKeys = function(o) { - ownKeys = Object.getOwnPropertyNames || function (o) { - var ar = []; - for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; - return ar; - }; - return ownKeys(o); - }; - return function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); - __setModuleDefault(result, mod); - return result; - }; -})(); -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromTemporaryCredentials = void 0; -const core_1 = require("@smithy/core"); -const property_provider_1 = require("@smithy/property-provider"); -const ASSUME_ROLE_DEFAULT_REGION = "us-east-1"; -const fromTemporaryCredentials = (options, credentialDefaultProvider, regionProvider) => { - let stsClient; - return async (awsIdentityProperties = {}) => { - const { callerClientConfig } = awsIdentityProperties; - const profile = options.clientConfig?.profile ?? callerClientConfig?.profile; - const logger = options.logger ?? callerClientConfig?.logger; - logger?.debug("@aws-sdk/credential-providers - fromTemporaryCredentials (STS)"); - const params = { ...options.params, RoleSessionName: options.params.RoleSessionName ?? "aws-sdk-js-" + Date.now() }; - if (params?.SerialNumber) { - if (!options.mfaCodeProvider) { - throw new property_provider_1.CredentialsProviderError(`Temporary credential requires multi-factor authentication, but no MFA code callback was provided.`, { - tryNextLink: false, - logger, - }); - } - params.TokenCode = await options.mfaCodeProvider(params?.SerialNumber); - } - const { AssumeRoleCommand, STSClient } = await Promise.resolve().then(() => __importStar(require("./loadSts"))); - if (!stsClient) { - const defaultCredentialsOrError = typeof credentialDefaultProvider === "function" ? credentialDefaultProvider() : undefined; - const credentialSources = [ - options.masterCredentials, - options.clientConfig?.credentials, - void callerClientConfig?.credentials, - callerClientConfig?.credentialDefaultProvider?.(), - defaultCredentialsOrError, - ]; - let credentialSource = "STS client default credentials"; - if (credentialSources[0]) { - credentialSource = "options.masterCredentials"; - } - else if (credentialSources[1]) { - credentialSource = "options.clientConfig.credentials"; - } - else if (credentialSources[2]) { - credentialSource = "caller client's credentials"; - throw new Error("fromTemporaryCredentials recursion in callerClientConfig.credentials"); - } - else if (credentialSources[3]) { - credentialSource = "caller client's credentialDefaultProvider"; - } - else if (credentialSources[4]) { - credentialSource = "AWS SDK default credentials"; - } - const regionSources = [ - options.clientConfig?.region, - callerClientConfig?.region, - await regionProvider?.({ - profile, - }), - ASSUME_ROLE_DEFAULT_REGION, - ]; - let regionSource = "default partition's default region"; - if (regionSources[0]) { - regionSource = "options.clientConfig.region"; - } - else if (regionSources[1]) { - regionSource = "caller client's region"; - } - else if (regionSources[2]) { - regionSource = "file or env region"; - } - const requestHandlerSources = [ - filterRequestHandler(options.clientConfig?.requestHandler), - filterRequestHandler(callerClientConfig?.requestHandler), - ]; - let requestHandlerSource = "STS default requestHandler"; - if (requestHandlerSources[0]) { - requestHandlerSource = "options.clientConfig.requestHandler"; - } - else if (requestHandlerSources[1]) { - requestHandlerSource = "caller client's requestHandler"; - } - logger?.debug?.(`@aws-sdk/credential-providers - fromTemporaryCredentials STS client init with ` + - `${regionSource}=${await (0, core_1.normalizeProvider)(coalesce(regionSources))()}, ${credentialSource}, ${requestHandlerSource}.`); - stsClient = new STSClient({ - userAgentAppId: callerClientConfig?.userAgentAppId, - ...options.clientConfig, - credentials: coalesce(credentialSources), - logger, - profile, - region: coalesce(regionSources), - requestHandler: coalesce(requestHandlerSources), - }); - } - if (options.clientPlugins) { - for (const plugin of options.clientPlugins) { - stsClient.middlewareStack.use(plugin); - } - } - const { Credentials } = await stsClient.send(new AssumeRoleCommand(params)); - if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) { - throw new property_provider_1.CredentialsProviderError(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`, { - logger, - }); - } - return { - accessKeyId: Credentials.AccessKeyId, - secretAccessKey: Credentials.SecretAccessKey, - sessionToken: Credentials.SessionToken, - expiration: Credentials.Expiration, - credentialScope: Credentials.CredentialScope, - }; - }; -}; -exports.fromTemporaryCredentials = fromTemporaryCredentials; -const filterRequestHandler = (requestHandler) => { - return requestHandler?.metadata?.handlerProtocol === "h2" ? undefined : requestHandler; -}; -const coalesce = (args) => { - for (const item of args) { - if (item !== undefined) { - return item; - } - } -}; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTemporaryCredentials.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTemporaryCredentials.js deleted file mode 100644 index 5cc665e6..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTemporaryCredentials.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromTemporaryCredentials = void 0; -const config_resolver_1 = require("@smithy/config-resolver"); -const node_config_provider_1 = require("@smithy/node-config-provider"); -const fromNodeProviderChain_1 = require("./fromNodeProviderChain"); -const fromTemporaryCredentials_base_1 = require("./fromTemporaryCredentials.base"); -const fromTemporaryCredentials = (options) => { - return (0, fromTemporaryCredentials_base_1.fromTemporaryCredentials)(options, fromNodeProviderChain_1.fromNodeProviderChain, async ({ profile = process.env.AWS_PROFILE }) => (0, node_config_provider_1.loadConfig)({ - environmentVariableSelector: (env) => env.AWS_REGION, - configFileSelector: (profileData) => { - return profileData.region; - }, - default: () => undefined, - }, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, profile })()); -}; -exports.fromTemporaryCredentials = fromTemporaryCredentials; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTokenFile.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTokenFile.js deleted file mode 100644 index 66164b31..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromTokenFile.js +++ /dev/null @@ -1,8 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromTokenFile = void 0; -const credential_provider_web_identity_1 = require("@aws-sdk/credential-provider-web-identity"); -const fromTokenFile = (init = {}) => (0, credential_provider_web_identity_1.fromTokenFile)({ - ...init, -}); -exports.fromTokenFile = fromTokenFile; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromWebToken.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromWebToken.js deleted file mode 100644 index 729cc111..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/fromWebToken.js +++ /dev/null @@ -1,8 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromWebToken = void 0; -const credential_provider_web_identity_1 = require("@aws-sdk/credential-provider-web-identity"); -const fromWebToken = (init) => (0, credential_provider_web_identity_1.fromWebToken)({ - ...init, -}); -exports.fromWebToken = fromWebToken; diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/index.js deleted file mode 100644 index a5a5f611..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/index.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.fromHttp = void 0; -const tslib_1 = require("tslib"); -tslib_1.__exportStar(require("./createCredentialChain"), exports); -tslib_1.__exportStar(require("./fromCognitoIdentity"), exports); -tslib_1.__exportStar(require("./fromCognitoIdentityPool"), exports); -tslib_1.__exportStar(require("./fromContainerMetadata"), exports); -tslib_1.__exportStar(require("./fromEnv"), exports); -var credential_provider_http_1 = require("@aws-sdk/credential-provider-http"); -Object.defineProperty(exports, "fromHttp", { enumerable: true, get: function () { return credential_provider_http_1.fromHttp; } }); -tslib_1.__exportStar(require("./fromIni"), exports); -tslib_1.__exportStar(require("./fromInstanceMetadata"), exports); -tslib_1.__exportStar(require("./fromLoginCredentials"), exports); -tslib_1.__exportStar(require("./fromNodeProviderChain"), exports); -tslib_1.__exportStar(require("./fromProcess"), exports); -tslib_1.__exportStar(require("./fromSSO"), exports); -tslib_1.__exportStar(require("./fromTemporaryCredentials"), exports); -tslib_1.__exportStar(require("./fromTokenFile"), exports); -tslib_1.__exportStar(require("./fromWebToken"), exports); diff --git a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/loadSts.js b/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/loadSts.js deleted file mode 100644 index 67e912ca..00000000 --- a/claude-code-source/node_modules/@aws-sdk/credential-providers/dist-cjs/loadSts.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.STSClient = exports.AssumeRoleCommand = void 0; -const sts_1 = require("@aws-sdk/nested-clients/sts"); -Object.defineProperty(exports, "AssumeRoleCommand", { enumerable: true, get: function () { return sts_1.AssumeRoleCommand; } }); -Object.defineProperty(exports, "STSClient", { enumerable: true, get: function () { return sts_1.STSClient; } }); diff --git a/claude-code-source/node_modules/@aws-sdk/eventstream-handler-node/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/eventstream-handler-node/dist-cjs/index.js deleted file mode 100644 index 464093ae..00000000 --- a/claude-code-source/node_modules/@aws-sdk/eventstream-handler-node/dist-cjs/index.js +++ /dev/null @@ -1,108 +0,0 @@ -'use strict'; - -var eventstreamCodec = require('@smithy/eventstream-codec'); -var stream = require('stream'); - -class EventSigningStream extends stream.Transform { - priorSignature; - messageSigner; - eventStreamCodec; - systemClockOffsetProvider; - constructor(options) { - super({ - autoDestroy: true, - readableObjectMode: true, - writableObjectMode: true, - ...options, - }); - this.priorSignature = options.priorSignature; - this.eventStreamCodec = options.eventStreamCodec; - this.messageSigner = options.messageSigner; - this.systemClockOffsetProvider = options.systemClockOffsetProvider; - } - async _transform(chunk, encoding, callback) { - try { - const now = new Date(Date.now() + (await this.systemClockOffsetProvider())); - const dateHeader = { - ":date": { type: "timestamp", value: now }, - }; - const signedMessage = await this.messageSigner.sign({ - message: { - body: chunk, - headers: dateHeader, - }, - priorSignature: this.priorSignature, - }, { - signingDate: now, - }); - this.priorSignature = signedMessage.signature; - const serializedSigned = this.eventStreamCodec.encode({ - headers: { - ...dateHeader, - ":chunk-signature": { - type: "binary", - value: getSignatureBinary(signedMessage.signature), - }, - }, - body: chunk, - }); - this.push(serializedSigned); - return callback(); - } - catch (err) { - callback(err); - } - } -} -function getSignatureBinary(signature) { - const buf = Buffer.from(signature, "hex"); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); -} - -class EventStreamPayloadHandler { - messageSigner; - eventStreamCodec; - systemClockOffsetProvider; - constructor(options) { - this.messageSigner = options.messageSigner; - this.eventStreamCodec = new eventstreamCodec.EventStreamCodec(options.utf8Encoder, options.utf8Decoder); - this.systemClockOffsetProvider = async () => options.systemClockOffset ?? 0; - } - async handle(next, args, context = {}) { - const request = args.request; - const { body: payload, query } = request; - if (!(payload instanceof stream.Readable)) { - throw new Error("Eventstream payload must be a Readable stream."); - } - const payloadStream = payload; - request.body = new stream.PassThrough({ - objectMode: true, - }); - const match = request.headers?.authorization?.match(/Signature=([\w]+)$/); - const priorSignature = match?.[1] ?? query?.["X-Amz-Signature"] ?? ""; - const signingStream = new EventSigningStream({ - priorSignature, - eventStreamCodec: this.eventStreamCodec, - messageSigner: await this.messageSigner(), - systemClockOffsetProvider: this.systemClockOffsetProvider, - }); - stream.pipeline(payloadStream, signingStream, request.body, (err) => { - if (err) { - throw err; - } - }); - let result; - try { - result = await next(args); - } - catch (e) { - request.body.end(); - throw e; - } - return result; - } -} - -const eventStreamPayloadHandlerProvider = (options) => new EventStreamPayloadHandler(options); - -exports.eventStreamPayloadHandlerProvider = eventStreamPayloadHandlerProvider; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-eventstream/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-eventstream/dist-cjs/index.js deleted file mode 100644 index bb03bb05..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-eventstream/dist-cjs/index.js +++ /dev/null @@ -1,65 +0,0 @@ -'use strict'; - -var protocolHttp = require('@smithy/protocol-http'); - -function resolveEventStreamConfig(input) { - const eventSigner = input.signer; - const messageSigner = input.signer; - const newInput = Object.assign(input, { - eventSigner, - messageSigner, - }); - const eventStreamPayloadHandler = newInput.eventStreamPayloadHandlerProvider(newInput); - return Object.assign(newInput, { - eventStreamPayloadHandler, - }); -} - -const eventStreamHandlingMiddleware = (options) => (next, context) => async (args) => { - const { request } = args; - if (!protocolHttp.HttpRequest.isInstance(request)) - return next(args); - return options.eventStreamPayloadHandler.handle(next, args, context); -}; -const eventStreamHandlingMiddlewareOptions = { - tags: ["EVENT_STREAM", "SIGNATURE", "HANDLE"], - name: "eventStreamHandlingMiddleware", - relation: "after", - toMiddleware: "awsAuthMiddleware", - override: true, -}; - -const eventStreamHeaderMiddleware = (next) => async (args) => { - const { request } = args; - if (!protocolHttp.HttpRequest.isInstance(request)) - return next(args); - request.headers = { - ...request.headers, - "content-type": "application/vnd.amazon.eventstream", - "x-amz-content-sha256": "STREAMING-AWS4-HMAC-SHA256-EVENTS", - }; - return next({ - ...args, - request, - }); -}; -const eventStreamHeaderMiddlewareOptions = { - step: "build", - tags: ["EVENT_STREAM", "HEADER", "CONTENT_TYPE", "CONTENT_SHA256"], - name: "eventStreamHeaderMiddleware", - override: true, -}; - -const getEventStreamPlugin = (options) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo(eventStreamHandlingMiddleware(options), eventStreamHandlingMiddlewareOptions); - clientStack.add(eventStreamHeaderMiddleware, eventStreamHeaderMiddlewareOptions); - }, -}); - -exports.eventStreamHandlingMiddleware = eventStreamHandlingMiddleware; -exports.eventStreamHandlingMiddlewareOptions = eventStreamHandlingMiddlewareOptions; -exports.eventStreamHeaderMiddleware = eventStreamHeaderMiddleware; -exports.eventStreamHeaderMiddlewareOptions = eventStreamHeaderMiddlewareOptions; -exports.getEventStreamPlugin = getEventStreamPlugin; -exports.resolveEventStreamConfig = resolveEventStreamConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-eventstream/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-eventstream/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 52303c3b..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-eventstream/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,169 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-eventstream/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-eventstream/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-eventstream/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-host-header/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-host-header/dist-cjs/index.js deleted file mode 100644 index 2dc022c3..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-host-header/dist-cjs/index.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -var protocolHttp = require('@smithy/protocol-http'); - -function resolveHostHeaderConfig(input) { - return input; -} -const hostHeaderMiddleware = (options) => (next) => async (args) => { - if (!protocolHttp.HttpRequest.isInstance(args.request)) - return next(args); - const { request } = args; - const { handlerProtocol = "" } = options.requestHandler.metadata || {}; - if (handlerProtocol.indexOf("h2") >= 0 && !request.headers[":authority"]) { - delete request.headers["host"]; - request.headers[":authority"] = request.hostname + (request.port ? ":" + request.port : ""); - } - else if (!request.headers["host"]) { - let host = request.hostname; - if (request.port != null) - host += `:${request.port}`; - request.headers["host"] = host; - } - return next(args); -}; -const hostHeaderMiddlewareOptions = { - name: "hostHeaderMiddleware", - step: "build", - priority: "low", - tags: ["HOST"], - override: true, -}; -const getHostHeaderPlugin = (options) => ({ - applyToStack: (clientStack) => { - clientStack.add(hostHeaderMiddleware(options), hostHeaderMiddlewareOptions); - }, -}); - -exports.getHostHeaderPlugin = getHostHeaderPlugin; -exports.hostHeaderMiddleware = hostHeaderMiddleware; -exports.hostHeaderMiddlewareOptions = hostHeaderMiddlewareOptions; -exports.resolveHostHeaderConfig = resolveHostHeaderConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 52303c3b..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,169 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-host-header/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js deleted file mode 100644 index 584a4faa..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-logger/dist-cjs/index.js +++ /dev/null @@ -1,48 +0,0 @@ -'use strict'; - -const loggerMiddleware = () => (next, context) => async (args) => { - try { - const response = await next(args); - const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; - const { overrideInputFilterSensitiveLog, overrideOutputFilterSensitiveLog } = dynamoDbDocumentClientOptions; - const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; - const outputFilterSensitiveLog = overrideOutputFilterSensitiveLog ?? context.outputFilterSensitiveLog; - const { $metadata, ...outputWithoutMetadata } = response.output; - logger?.info?.({ - clientName, - commandName, - input: inputFilterSensitiveLog(args.input), - output: outputFilterSensitiveLog(outputWithoutMetadata), - metadata: $metadata, - }); - return response; - } - catch (error) { - const { clientName, commandName, logger, dynamoDbDocumentClientOptions = {} } = context; - const { overrideInputFilterSensitiveLog } = dynamoDbDocumentClientOptions; - const inputFilterSensitiveLog = overrideInputFilterSensitiveLog ?? context.inputFilterSensitiveLog; - logger?.error?.({ - clientName, - commandName, - input: inputFilterSensitiveLog(args.input), - error, - metadata: error.$metadata, - }); - throw error; - } -}; -const loggerMiddlewareOptions = { - name: "loggerMiddleware", - tags: ["LOGGER"], - step: "initialize", - override: true, -}; -const getLoggerPlugin = (options) => ({ - applyToStack: (clientStack) => { - clientStack.add(loggerMiddleware(), loggerMiddlewareOptions); - }, -}); - -exports.getLoggerPlugin = getLoggerPlugin; -exports.loggerMiddleware = loggerMiddleware; -exports.loggerMiddlewareOptions = loggerMiddlewareOptions; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/index.js deleted file mode 100644 index eb8ff04c..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/index.js +++ /dev/null @@ -1,25 +0,0 @@ -'use strict'; - -var recursionDetectionMiddleware = require('./recursionDetectionMiddleware'); - -const recursionDetectionMiddlewareOptions = { - step: "build", - tags: ["RECURSION_DETECTION"], - name: "recursionDetectionMiddleware", - override: true, - priority: "low", -}; - -const getRecursionDetectionPlugin = (options) => ({ - applyToStack: (clientStack) => { - clientStack.add(recursionDetectionMiddleware.recursionDetectionMiddleware(), recursionDetectionMiddlewareOptions); - }, -}); - -exports.getRecursionDetectionPlugin = getRecursionDetectionPlugin; -Object.keys(recursionDetectionMiddleware).forEach(function (k) { - if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { - enumerable: true, - get: function () { return recursionDetectionMiddleware[k]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/recursionDetectionMiddleware.js b/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/recursionDetectionMiddleware.js deleted file mode 100644 index 1300be08..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/dist-cjs/recursionDetectionMiddleware.js +++ /dev/null @@ -1,33 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.recursionDetectionMiddleware = void 0; -const lambda_invoke_store_1 = require("@aws/lambda-invoke-store"); -const protocol_http_1 = require("@smithy/protocol-http"); -const TRACE_ID_HEADER_NAME = "X-Amzn-Trace-Id"; -const ENV_LAMBDA_FUNCTION_NAME = "AWS_LAMBDA_FUNCTION_NAME"; -const ENV_TRACE_ID = "_X_AMZN_TRACE_ID"; -const recursionDetectionMiddleware = () => (next) => async (args) => { - const { request } = args; - if (!protocol_http_1.HttpRequest.isInstance(request)) { - return next(args); - } - const traceIdHeader = Object.keys(request.headers ?? {}).find((h) => h.toLowerCase() === TRACE_ID_HEADER_NAME.toLowerCase()) ?? - TRACE_ID_HEADER_NAME; - if (request.headers.hasOwnProperty(traceIdHeader)) { - return next(args); - } - const functionName = process.env[ENV_LAMBDA_FUNCTION_NAME]; - const traceIdFromEnv = process.env[ENV_TRACE_ID]; - const invokeStore = await lambda_invoke_store_1.InvokeStore.getInstanceAsync(); - const traceIdFromInvokeStore = invokeStore?.getXRayTraceId(); - const traceId = traceIdFromInvokeStore ?? traceIdFromEnv; - const nonEmptyString = (str) => typeof str === "string" && str.length > 0; - if (nonEmptyString(functionName) && nonEmptyString(traceId)) { - request.headers[TRACE_ID_HEADER_NAME] = traceId; - } - return next({ - ...args, - request, - }); -}; -exports.recursionDetectionMiddleware = recursionDetectionMiddleware; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 52303c3b..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,169 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-recursion-detection/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-user-agent/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-user-agent/dist-cjs/index.js deleted file mode 100644 index d5c19882..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-user-agent/dist-cjs/index.js +++ /dev/null @@ -1,194 +0,0 @@ -'use strict'; - -var core = require('@smithy/core'); -var utilEndpoints = require('@aws-sdk/util-endpoints'); -var protocolHttp = require('@smithy/protocol-http'); -var core$1 = require('@aws-sdk/core'); - -const DEFAULT_UA_APP_ID = undefined; -function isValidUserAgentAppId(appId) { - if (appId === undefined) { - return true; - } - return typeof appId === "string" && appId.length <= 50; -} -function resolveUserAgentConfig(input) { - const normalizedAppIdProvider = core.normalizeProvider(input.userAgentAppId ?? DEFAULT_UA_APP_ID); - const { customUserAgent } = input; - return Object.assign(input, { - customUserAgent: typeof customUserAgent === "string" ? [[customUserAgent]] : customUserAgent, - userAgentAppId: async () => { - const appId = await normalizedAppIdProvider(); - if (!isValidUserAgentAppId(appId)) { - const logger = input.logger?.constructor?.name === "NoOpLogger" || !input.logger ? console : input.logger; - if (typeof appId !== "string") { - logger?.warn("userAgentAppId must be a string or undefined."); - } - else if (appId.length > 50) { - logger?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters."); - } - } - return appId; - }, - }); -} - -const ACCOUNT_ID_ENDPOINT_REGEX = /\d{12}\.ddb/; -async function checkFeatures(context, config, args) { - const request = args.request; - if (request?.headers?.["smithy-protocol"] === "rpc-v2-cbor") { - core$1.setFeature(context, "PROTOCOL_RPC_V2_CBOR", "M"); - } - if (typeof config.retryStrategy === "function") { - const retryStrategy = await config.retryStrategy(); - if (typeof retryStrategy.acquireInitialRetryToken === "function") { - if (retryStrategy.constructor?.name?.includes("Adaptive")) { - core$1.setFeature(context, "RETRY_MODE_ADAPTIVE", "F"); - } - else { - core$1.setFeature(context, "RETRY_MODE_STANDARD", "E"); - } - } - else { - core$1.setFeature(context, "RETRY_MODE_LEGACY", "D"); - } - } - if (typeof config.accountIdEndpointMode === "function") { - const endpointV2 = context.endpointV2; - if (String(endpointV2?.url?.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)) { - core$1.setFeature(context, "ACCOUNT_ID_ENDPOINT", "O"); - } - switch (await config.accountIdEndpointMode?.()) { - case "disabled": - core$1.setFeature(context, "ACCOUNT_ID_MODE_DISABLED", "Q"); - break; - case "preferred": - core$1.setFeature(context, "ACCOUNT_ID_MODE_PREFERRED", "P"); - break; - case "required": - core$1.setFeature(context, "ACCOUNT_ID_MODE_REQUIRED", "R"); - break; - } - } - const identity = context.__smithy_context?.selectedHttpAuthScheme?.identity; - if (identity?.$source) { - const credentials = identity; - if (credentials.accountId) { - core$1.setFeature(context, "RESOLVED_ACCOUNT_ID", "T"); - } - for (const [key, value] of Object.entries(credentials.$source ?? {})) { - core$1.setFeature(context, key, value); - } - } -} - -const USER_AGENT = "user-agent"; -const X_AMZ_USER_AGENT = "x-amz-user-agent"; -const SPACE = " "; -const UA_NAME_SEPARATOR = "/"; -const UA_NAME_ESCAPE_REGEX = /[^!$%&'*+\-.^_`|~\w]/g; -const UA_VALUE_ESCAPE_REGEX = /[^!$%&'*+\-.^_`|~\w#]/g; -const UA_ESCAPE_CHAR = "-"; - -const BYTE_LIMIT = 1024; -function encodeFeatures(features) { - let buffer = ""; - for (const key in features) { - const val = features[key]; - if (buffer.length + val.length + 1 <= BYTE_LIMIT) { - if (buffer.length) { - buffer += "," + val; - } - else { - buffer += val; - } - continue; - } - break; - } - return buffer; -} - -const userAgentMiddleware = (options) => (next, context) => async (args) => { - const { request } = args; - if (!protocolHttp.HttpRequest.isInstance(request)) { - return next(args); - } - const { headers } = request; - const userAgent = context?.userAgent?.map(escapeUserAgent) || []; - const defaultUserAgent = (await options.defaultUserAgentProvider()).map(escapeUserAgent); - await checkFeatures(context, options, args); - const awsContext = context; - defaultUserAgent.push(`m/${encodeFeatures(Object.assign({}, context.__smithy_context?.features, awsContext.__aws_sdk_context?.features))}`); - const customUserAgent = options?.customUserAgent?.map(escapeUserAgent) || []; - const appId = await options.userAgentAppId(); - if (appId) { - defaultUserAgent.push(escapeUserAgent([`app`, `${appId}`])); - } - const prefix = utilEndpoints.getUserAgentPrefix(); - const sdkUserAgentValue = (prefix ? [prefix] : []) - .concat([...defaultUserAgent, ...userAgent, ...customUserAgent]) - .join(SPACE); - const normalUAValue = [ - ...defaultUserAgent.filter((section) => section.startsWith("aws-sdk-")), - ...customUserAgent, - ].join(SPACE); - if (options.runtime !== "browser") { - if (normalUAValue) { - headers[X_AMZ_USER_AGENT] = headers[X_AMZ_USER_AGENT] - ? `${headers[USER_AGENT]} ${normalUAValue}` - : normalUAValue; - } - headers[USER_AGENT] = sdkUserAgentValue; - } - else { - headers[X_AMZ_USER_AGENT] = sdkUserAgentValue; - } - return next({ - ...args, - request, - }); -}; -const escapeUserAgent = (userAgentPair) => { - const name = userAgentPair[0] - .split(UA_NAME_SEPARATOR) - .map((part) => part.replace(UA_NAME_ESCAPE_REGEX, UA_ESCAPE_CHAR)) - .join(UA_NAME_SEPARATOR); - const version = userAgentPair[1]?.replace(UA_VALUE_ESCAPE_REGEX, UA_ESCAPE_CHAR); - const prefixSeparatorIndex = name.indexOf(UA_NAME_SEPARATOR); - const prefix = name.substring(0, prefixSeparatorIndex); - let uaName = name.substring(prefixSeparatorIndex + 1); - if (prefix === "api") { - uaName = uaName.toLowerCase(); - } - return [prefix, uaName, version] - .filter((item) => item && item.length > 0) - .reduce((acc, item, index) => { - switch (index) { - case 0: - return item; - case 1: - return `${acc}/${item}`; - default: - return `${acc}#${item}`; - } - }, ""); -}; -const getUserAgentMiddlewareOptions = { - name: "getUserAgentMiddleware", - step: "build", - priority: "low", - tags: ["SET_USER_AGENT", "USER_AGENT"], - override: true, -}; -const getUserAgentPlugin = (config) => ({ - applyToStack: (clientStack) => { - clientStack.add(userAgentMiddleware(config), getUserAgentMiddlewareOptions); - }, -}); - -exports.DEFAULT_UA_APP_ID = DEFAULT_UA_APP_ID; -exports.getUserAgentMiddlewareOptions = getUserAgentMiddlewareOptions; -exports.getUserAgentPlugin = getUserAgentPlugin; -exports.resolveUserAgentConfig = resolveUserAgentConfig; -exports.userAgentMiddleware = userAgentMiddleware; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 52303c3b..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,169 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-user-agent/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/dist-cjs/index.js deleted file mode 100644 index d287b222..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/dist-cjs/index.js +++ /dev/null @@ -1,347 +0,0 @@ -'use strict'; - -var eventstreamCodec = require('@smithy/eventstream-codec'); -var utilHexEncoding = require('@smithy/util-hex-encoding'); -var protocolHttp = require('@smithy/protocol-http'); -var utilFormatUrl = require('@aws-sdk/util-format-url'); -var eventstreamSerdeBrowser = require('@smithy/eventstream-serde-browser'); -var fetchHttpHandler = require('@smithy/fetch-http-handler'); - -const getEventSigningTransformStream = (initialSignature, messageSigner, eventStreamCodec, systemClockOffsetProvider) => { - let priorSignature = initialSignature; - const transformer = { - start() { }, - async transform(chunk, controller) { - try { - const now = new Date(Date.now() + (await systemClockOffsetProvider())); - const dateHeader = { - ":date": { type: "timestamp", value: now }, - }; - const signedMessage = await messageSigner.sign({ - message: { - body: chunk, - headers: dateHeader, - }, - priorSignature: priorSignature, - }, { - signingDate: now, - }); - priorSignature = signedMessage.signature; - const serializedSigned = eventStreamCodec.encode({ - headers: { - ...dateHeader, - ":chunk-signature": { - type: "binary", - value: utilHexEncoding.fromHex(signedMessage.signature), - }, - }, - body: chunk, - }); - controller.enqueue(serializedSigned); - } - catch (error) { - controller.error(error); - } - }, - }; - return new TransformStream({ ...transformer }); -}; - -class EventStreamPayloadHandler { - messageSigner; - eventStreamCodec; - systemClockOffsetProvider; - constructor(options) { - this.messageSigner = options.messageSigner; - this.eventStreamCodec = new eventstreamCodec.EventStreamCodec(options.utf8Encoder, options.utf8Decoder); - this.systemClockOffsetProvider = async () => options.systemClockOffset ?? 0; - } - async handle(next, args, context = {}) { - const request = args.request; - const { body: payload, headers, query } = request; - if (!(payload instanceof ReadableStream)) { - throw new Error("Eventstream payload must be a ReadableStream."); - } - const placeHolderStream = new TransformStream(); - request.body = placeHolderStream.readable; - let result; - try { - result = await next(args); - } - catch (e) { - request.body.cancel(); - throw e; - } - const match = (headers["authorization"] || "").match(/Signature=([\w]+)$/); - const priorSignature = (match || [])[1] || (query && query["X-Amz-Signature"]) || ""; - const signingStream = getEventSigningTransformStream(priorSignature, await this.messageSigner(), this.eventStreamCodec, this.systemClockOffsetProvider); - const signedPayload = payload.pipeThrough(signingStream); - signedPayload.pipeThrough(placeHolderStream); - return result; - } -} - -const eventStreamPayloadHandlerProvider = (options) => new EventStreamPayloadHandler(options); - -const injectSessionIdMiddleware = () => (next) => async (args) => { - const requestParams = { - ...args.input, - }; - const response = await next(args); - const output = response.output; - if (requestParams.SessionId && output.SessionId == null) { - output.SessionId = requestParams.SessionId; - } - return response; -}; -const injectSessionIdMiddlewareOptions = { - step: "initialize", - name: "injectSessionIdMiddleware", - tags: ["WEBSOCKET", "EVENT_STREAM"], - override: true, -}; - -const websocketEndpointMiddleware = (config, options) => (next) => (args) => { - const { request } = args; - if (protocolHttp.HttpRequest.isInstance(request) && - config.requestHandler.metadata?.handlerProtocol?.toLowerCase().includes("websocket")) { - request.protocol = "wss:"; - request.method = "GET"; - request.path = `${request.path}-websocket`; - const { headers } = request; - delete headers["content-type"]; - delete headers["x-amz-content-sha256"]; - for (const name of Object.keys(headers)) { - if (name.indexOf(options.headerPrefix) === 0) { - const chunkedName = name.replace(options.headerPrefix, ""); - request.query[chunkedName] = headers[name]; - } - } - if (headers["x-amz-user-agent"]) { - request.query["user-agent"] = headers["x-amz-user-agent"]; - } - request.headers = { host: headers.host ?? request.hostname }; - } - return next(args); -}; -const websocketEndpointMiddlewareOptions = { - name: "websocketEndpointMiddleware", - tags: ["WEBSOCKET", "EVENT_STREAM"], - relation: "after", - toMiddleware: "eventStreamHeaderMiddleware", - override: true, -}; - -const getWebSocketPlugin = (config, options) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo(websocketEndpointMiddleware(config, options), websocketEndpointMiddlewareOptions); - clientStack.add(injectSessionIdMiddleware(), injectSessionIdMiddlewareOptions); - }, -}); - -const isWebSocketRequest = (request) => request.protocol === "ws:" || request.protocol === "wss:"; - -class WebsocketSignatureV4 { - signer; - constructor(options) { - this.signer = options.signer; - } - presign(originalRequest, options = {}) { - return this.signer.presign(originalRequest, options); - } - async sign(toSign, options) { - if (protocolHttp.HttpRequest.isInstance(toSign) && isWebSocketRequest(toSign)) { - const signedRequest = await this.signer.presign({ ...toSign, body: "" }, { - ...options, - expiresIn: 60, - unsignableHeaders: new Set(Object.keys(toSign.headers).filter((header) => header !== "host")), - }); - return { - ...signedRequest, - body: toSign.body, - }; - } - else { - return this.signer.sign(toSign, options); - } - } -} - -const resolveWebSocketConfig = (input) => { - const { signer } = input; - return Object.assign(input, { - signer: async (authScheme) => { - const signerObj = await signer(authScheme); - if (validateSigner(signerObj)) { - return new WebsocketSignatureV4({ signer: signerObj }); - } - throw new Error("Expected WebsocketSignatureV4 signer, please check the client constructor."); - }, - }); -}; -const validateSigner = (signer) => !!signer; - -const DEFAULT_WS_CONNECTION_TIMEOUT_MS = 2000; -class WebSocketFetchHandler { - metadata = { - handlerProtocol: "websocket/h1.1", - }; - config; - configPromise; - httpHandler; - sockets = {}; - static create(instanceOrOptions, httpHandler = new fetchHttpHandler.FetchHttpHandler()) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new WebSocketFetchHandler(instanceOrOptions, httpHandler); - } - constructor(options, httpHandler = new fetchHttpHandler.FetchHttpHandler()) { - this.httpHandler = httpHandler; - if (typeof options === "function") { - this.config = {}; - this.configPromise = options().then((opts) => (this.config = opts ?? {})); - } - else { - this.config = options ?? {}; - this.configPromise = Promise.resolve(this.config); - } - } - destroy() { - for (const [key, sockets] of Object.entries(this.sockets)) { - for (const socket of sockets) { - socket.close(1000, `Socket closed through destroy() call`); - } - delete this.sockets[key]; - } - } - async handle(request) { - if (!isWebSocketRequest(request)) { - return this.httpHandler.handle(request); - } - const url = utilFormatUrl.formatUrl(request); - const socket = new WebSocket(url); - if (!this.sockets[url]) { - this.sockets[url] = []; - } - this.sockets[url].push(socket); - socket.binaryType = "arraybuffer"; - this.config = await this.configPromise; - const { connectionTimeout = DEFAULT_WS_CONNECTION_TIMEOUT_MS } = this.config; - await this.waitForReady(socket, connectionTimeout); - const { body } = request; - const bodyStream = getIterator(body); - const asyncIterable = this.connect(socket, bodyStream); - const outputPayload = toReadableStream(asyncIterable); - return { - response: new protocolHttp.HttpResponse({ - statusCode: 200, - body: outputPayload, - }), - }; - } - updateHttpClientConfig(key, value) { - this.configPromise = this.configPromise.then((config) => { - config[key] = value; - return config; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } - removeNotUsableSockets(url) { - this.sockets[url] = (this.sockets[url] ?? []).filter((socket) => ![WebSocket.CLOSING, WebSocket.CLOSED].includes(socket.readyState)); - } - waitForReady(socket, connectionTimeout) { - return new Promise((resolve, reject) => { - const timeout = setTimeout(() => { - this.removeNotUsableSockets(socket.url); - reject({ - $metadata: { - httpStatusCode: 500, - }, - }); - }, connectionTimeout); - socket.onopen = () => { - clearTimeout(timeout); - resolve(); - }; - }); - } - connect(socket, data) { - let streamError = undefined; - let socketErrorOccurred = false; - let reject = () => { }; - let resolve = () => { }; - socket.onmessage = (event) => { - resolve({ - done: false, - value: new Uint8Array(event.data), - }); - }; - socket.onerror = (error) => { - socketErrorOccurred = true; - socket.close(); - reject(error); - }; - socket.onclose = () => { - this.removeNotUsableSockets(socket.url); - if (socketErrorOccurred) - return; - if (streamError) { - reject(streamError); - } - else { - resolve({ - done: true, - value: undefined, - }); - } - }; - const outputStream = { - [Symbol.asyncIterator]: () => ({ - next: () => { - return new Promise((_resolve, _reject) => { - resolve = _resolve; - reject = _reject; - }); - }, - }), - }; - const send = async () => { - try { - for await (const inputChunk of data) { - socket.send(inputChunk); - } - } - catch (err) { - streamError = err; - } - finally { - socket.close(1000); - } - }; - send(); - return outputStream; - } -} -const getIterator = (stream) => { - if (stream[Symbol.asyncIterator]) { - return stream; - } - if (isReadableStream(stream)) { - return eventstreamSerdeBrowser.readableStreamtoIterable(stream); - } - return { - [Symbol.asyncIterator]: async function* () { - yield stream; - }, - }; -}; -const toReadableStream = (asyncIterable) => typeof ReadableStream === "function" ? eventstreamSerdeBrowser.iterableToReadableStream(asyncIterable) : asyncIterable; -const isReadableStream = (payload) => typeof ReadableStream === "function" && payload instanceof ReadableStream; - -exports.WebSocketFetchHandler = WebSocketFetchHandler; -exports.eventStreamPayloadHandlerProvider = eventStreamPayloadHandlerProvider; -exports.getWebSocketPlugin = getWebSocketPlugin; -exports.resolveWebSocketConfig = resolveWebSocketConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js deleted file mode 100644 index e6673dc8..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js +++ /dev/null @@ -1,216 +0,0 @@ -'use strict'; - -var protocolHttp = require('@smithy/protocol-http'); -var querystringBuilder = require('@smithy/querystring-builder'); -var utilBase64 = require('@smithy/util-base64'); - -function createRequest(url, requestOptions) { - return new Request(url, requestOptions); -} - -function requestTimeout(timeoutInMs = 0) { - return new Promise((resolve, reject) => { - if (timeoutInMs) { - setTimeout(() => { - const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); - timeoutError.name = "TimeoutError"; - reject(timeoutError); - }, timeoutInMs); - } - }); -} - -const keepAliveSupport = { - supported: undefined, -}; -class FetchHttpHandler { - config; - configProvider; - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new FetchHttpHandler(instanceOrOptions); - } - constructor(options) { - if (typeof options === "function") { - this.configProvider = options().then((opts) => opts || {}); - } - else { - this.config = options ?? {}; - this.configProvider = Promise.resolve(this.config); - } - if (keepAliveSupport.supported === undefined) { - keepAliveSupport.supported = Boolean(typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]")); - } - } - destroy() { - } - async handle(request, { abortSignal, requestTimeout: requestTimeout$1 } = {}) { - if (!this.config) { - this.config = await this.configProvider; - } - const requestTimeoutInMs = requestTimeout$1 ?? this.config.requestTimeout; - const keepAlive = this.config.keepAlive === true; - const credentials = this.config.credentials; - if (abortSignal?.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - return Promise.reject(abortError); - } - let path = request.path; - const queryString = querystringBuilder.buildQueryString(request.query || {}); - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const { port, method } = request; - const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; - const body = method === "GET" || method === "HEAD" ? undefined : request.body; - const requestOptions = { - body, - headers: new Headers(request.headers), - method: method, - credentials, - }; - if (this.config?.cache) { - requestOptions.cache = this.config.cache; - } - if (body) { - requestOptions.duplex = "half"; - } - if (typeof AbortController !== "undefined") { - requestOptions.signal = abortSignal; - } - if (keepAliveSupport.supported) { - requestOptions.keepalive = keepAlive; - } - if (typeof this.config.requestInit === "function") { - Object.assign(requestOptions, this.config.requestInit(request)); - } - let removeSignalEventListener = () => { }; - const fetchRequest = createRequest(url, requestOptions); - const raceOfPromises = [ - fetch(fetchRequest).then((response) => { - const fetchHeaders = response.headers; - const transformedHeaders = {}; - for (const pair of fetchHeaders.entries()) { - transformedHeaders[pair[0]] = pair[1]; - } - const hasReadableStream = response.body != undefined; - if (!hasReadableStream) { - return response.blob().then((body) => ({ - response: new protocolHttp.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body, - }), - })); - } - return { - response: new protocolHttp.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: response.body, - }), - }; - }), - requestTimeout(requestTimeoutInMs), - ]; - if (abortSignal) { - raceOfPromises.push(new Promise((resolve, reject) => { - const onAbort = () => { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }; - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - removeSignalEventListener = () => signal.removeEventListener("abort", onAbort); - } - else { - abortSignal.onabort = onAbort; - } - })); - } - return Promise.race(raceOfPromises).finally(removeSignalEventListener); - } - updateHttpClientConfig(key, value) { - this.config = undefined; - this.configProvider = this.configProvider.then((config) => { - config[key] = value; - return config; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } -} - -const streamCollector = async (stream) => { - if ((typeof Blob === "function" && stream instanceof Blob) || stream.constructor?.name === "Blob") { - if (Blob.prototype.arrayBuffer !== undefined) { - return new Uint8Array(await stream.arrayBuffer()); - } - return collectBlob(stream); - } - return collectStream(stream); -}; -async function collectBlob(blob) { - const base64 = await readToBase64(blob); - const arrayBuffer = utilBase64.fromBase64(base64); - return new Uint8Array(arrayBuffer); -} -async function collectStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; - } - isDone = done; - } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; - } - return collected; -} -function readToBase64(blob) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onloadend = () => { - if (reader.readyState !== 2) { - return reject(new Error("Reader aborted too early")); - } - const result = (reader.result ?? ""); - const commaIndex = result.indexOf(","); - const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; - resolve(result.substring(dataOffset)); - }; - reader.onabort = () => reject(new Error("Read aborted")); - reader.onerror = () => reject(reader.error); - reader.readAsDataURL(blob); - }); -} - -exports.FetchHttpHandler = FetchHttpHandler; -exports.keepAliveSupport = keepAliveSupport; -exports.streamCollector = streamCollector; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js deleted file mode 100644 index f245489f..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -var utilUriEscape = require('@smithy/util-uri-escape'); - -function buildQueryString(query) { - const parts = []; - for (let key of Object.keys(query).sort()) { - const value = query[key]; - key = utilUriEscape.escapeUri(key); - if (Array.isArray(value)) { - for (let i = 0, iLen = value.length; i < iLen; i++) { - parts.push(`${key}=${utilUriEscape.escapeUri(value[i])}`); - } - } - else { - let qsEntry = key; - if (value || typeof value === "string") { - qsEntry += `=${utilUriEscape.escapeUri(value)}`; - } - parts.push(qsEntry); - } - } - return parts.join("&"); -} - -exports.buildQueryString = buildQueryString; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js deleted file mode 100644 index 11f942c3..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -const escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode); -const hexEncode = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`; - -const escapeUriPath = (uri) => uri.split("/").map(escapeUri).join("/"); - -exports.escapeUri = escapeUri; -exports.escapeUriPath = escapeUriPath; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js deleted file mode 100644 index b06a7b87..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js +++ /dev/null @@ -1,16 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/index.js deleted file mode 100644 index c095e288..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/index.js +++ /dev/null @@ -1,19 +0,0 @@ -'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]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/toBase64.js deleted file mode 100644 index 0590ce3f..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/toBase64.js +++ /dev/null @@ -1,19 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js deleted file mode 100644 index b577c9ca..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js +++ /dev/null @@ -1,20 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js deleted file mode 100644 index 3238bb77..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || - Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; - -exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 52303c3b..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,169 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js deleted file mode 100644 index 6d1eb2d1..00000000 --- a/claude-code-source/node_modules/@aws-sdk/middleware-websocket/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -const SHORT_TO_HEX = {}; -const HEX_TO_SHORT = {}; -for (let i = 0; i < 256; i++) { - let encodedByte = i.toString(16).toLowerCase(); - if (encodedByte.length === 1) { - encodedByte = `0${encodedByte}`; - } - SHORT_TO_HEX[i] = encodedByte; - HEX_TO_SHORT[encodedByte] = i; -} -function fromHex(encoded) { - if (encoded.length % 2 !== 0) { - throw new Error("Hex encoded strings must have an even number length"); - } - const out = new Uint8Array(encoded.length / 2); - for (let i = 0; i < encoded.length; i += 2) { - const encodedByte = encoded.slice(i, i + 2).toLowerCase(); - if (encodedByte in HEX_TO_SHORT) { - out[i / 2] = HEX_TO_SHORT[encodedByte]; - } - else { - throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); - } - } - return out; -} -function toHex(bytes) { - let out = ""; - for (let i = 0; i < bytes.byteLength; i++) { - out += SHORT_TO_HEX[bytes[i]]; - } - return out; -} - -exports.fromHex = fromHex; -exports.toHex = toHex; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/auth/httpAuthSchemeProvider.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/auth/httpAuthSchemeProvider.js deleted file mode 100644 index 024a9fd2..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/auth/httpAuthSchemeProvider.js +++ /dev/null @@ -1,56 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.resolveHttpAuthSchemeConfig = exports.defaultSigninHttpAuthSchemeProvider = exports.defaultSigninHttpAuthSchemeParametersProvider = void 0; -const core_1 = require("@aws-sdk/core"); -const util_middleware_1 = require("@smithy/util-middleware"); -const defaultSigninHttpAuthSchemeParametersProvider = 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.defaultSigninHttpAuthSchemeParametersProvider = defaultSigninHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "signin", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth", - }; -} -const defaultSigninHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "CreateOAuth2Token": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); - } - } - return options; -}; -exports.defaultSigninHttpAuthSchemeProvider = defaultSigninHttpAuthSchemeProvider; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); - return Object.assign(config_0, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), - }); -}; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/endpoint/endpointResolver.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/endpoint/endpointResolver.js deleted file mode 100644 index 7258a356..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/endpoint/endpointResolver.js +++ /dev/null @@ -1,18 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/endpoint/ruleset.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/endpoint/ruleset.js deleted file mode 100644 index 278a0726..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/endpoint/ruleset.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ruleSet = void 0; -const u = "required", v = "fn", w = "argv", x = "ref"; -const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = "stringEquals", i = { [u]: true, "default": false, "type": "boolean" }, j = { [u]: false, "type": "string" }, k = { [x]: "Endpoint" }, l = { [v]: c, [w]: [{ [x]: "UseFIPS" }, true] }, m = { [v]: c, [w]: [{ [x]: "UseDualStack" }, true] }, n = {}, o = { [v]: "getAttr", [w]: [{ [x]: g }, "name"] }, p = { [v]: c, [w]: [{ [x]: "UseFIPS" }, false] }, q = { [v]: c, [w]: [{ [x]: "UseDualStack" }, false] }, r = { [v]: "getAttr", [w]: [{ [x]: g }, "supportsFIPS"] }, s = { [v]: c, [w]: [true, { [v]: "getAttr", [w]: [{ [x]: g }, "supportsDualStack"] }] }, t = [{ [x]: "Region" }]; -const _data = { version: "1.0", parameters: { UseDualStack: i, UseFIPS: i, Endpoint: j, Region: j }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: [l], error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { rules: [{ conditions: [m], error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e }], type: f }], type: f }, { rules: [{ conditions: [{ [v]: b, [w]: t }], rules: [{ conditions: [{ [v]: "aws.partition", [w]: t, assign: g }], rules: [{ conditions: [{ [v]: h, [w]: [o, "aws"] }, p, q], endpoint: { url: "https://{Region}.signin.aws.amazon.com", properties: n, headers: n }, type: e }, { conditions: [{ [v]: h, [w]: [o, "aws-cn"] }, p, q], endpoint: { url: "https://{Region}.signin.amazonaws.cn", properties: n, headers: n }, type: e }, { conditions: [{ [v]: h, [w]: [o, "aws-us-gov"] }, p, q], endpoint: { url: "https://{Region}.signin.amazonaws-us-gov.com", properties: n, headers: n }, type: e }, { conditions: [l, m], rules: [{ conditions: [{ [v]: c, [w]: [a, r] }, s], rules: [{ endpoint: { url: "https://signin-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: [l, q], rules: [{ conditions: [{ [v]: c, [w]: [r, a] }], rules: [{ endpoint: { url: "https://signin-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: [p, m], rules: [{ conditions: [s], rules: [{ endpoint: { url: "https://signin.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { endpoint: { url: "https://signin.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }], type: f }] }; -exports.ruleSet = _data; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/index.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/index.js deleted file mode 100644 index 6092f313..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/index.js +++ /dev/null @@ -1,439 +0,0 @@ -'use strict'; - -var middlewareHostHeader = require('@aws-sdk/middleware-host-header'); -var middlewareLogger = require('@aws-sdk/middleware-logger'); -var middlewareRecursionDetection = require('@aws-sdk/middleware-recursion-detection'); -var middlewareUserAgent = require('@aws-sdk/middleware-user-agent'); -var configResolver = require('@smithy/config-resolver'); -var core = require('@smithy/core'); -var schema = require('@smithy/core/schema'); -var middlewareContentLength = require('@smithy/middleware-content-length'); -var middlewareEndpoint = require('@smithy/middleware-endpoint'); -var middlewareRetry = require('@smithy/middleware-retry'); -var smithyClient = require('@smithy/smithy-client'); -var httpAuthSchemeProvider = require('./auth/httpAuthSchemeProvider'); -var runtimeConfig = require('./runtimeConfig'); -var regionConfigResolver = require('@aws-sdk/region-config-resolver'); -var protocolHttp = require('@smithy/protocol-http'); - -const resolveClientEndpointParameters = (options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - defaultSigningName: "signin", - }); -}; -const commonParams = { - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, -}; - -const getHttpAuthExtensionConfiguration = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } - else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - }, - }; -}; -const resolveHttpAuthRuntimeConfig = (config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials(), - }; -}; - -const resolveRuntimeExtensions = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig), smithyClient.getDefaultExtensionConfiguration(runtimeConfig), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); -}; - -class SigninClient extends smithyClient.Client { - config; - constructor(...[configuration]) { - const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters(_config_0); - const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1); - const _config_3 = middlewareRetry.resolveRetryConfig(_config_2); - const _config_4 = configResolver.resolveRegionConfig(_config_3); - const _config_5 = middlewareHostHeader.resolveHostHeaderConfig(_config_4); - const _config_6 = middlewareEndpoint.resolveEndpointConfig(_config_5); - const _config_7 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_6); - const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use(schema.getSchemaSerdePlugin(this.config)); - this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config)); - this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config)); - this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config)); - this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config)); - this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config)); - this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config)); - this.middlewareStack.use(core.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { - httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultSigninHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config) => new core.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials, - }), - })); - this.middlewareStack.use(core.getHttpSigningPlugin(this.config)); - } - destroy() { - super.destroy(); - } -} - -let SigninServiceException$1 = class SigninServiceException extends smithyClient.ServiceException { - constructor(options) { - super(options); - Object.setPrototypeOf(this, SigninServiceException.prototype); - } -}; - -let AccessDeniedException$1 = class AccessDeniedException extends SigninServiceException$1 { - name = "AccessDeniedException"; - $fault = "client"; - error; - constructor(opts) { - super({ - name: "AccessDeniedException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, AccessDeniedException.prototype); - this.error = opts.error; - } -}; -let InternalServerException$1 = class InternalServerException extends SigninServiceException$1 { - name = "InternalServerException"; - $fault = "server"; - error; - constructor(opts) { - super({ - name: "InternalServerException", - $fault: "server", - ...opts, - }); - Object.setPrototypeOf(this, InternalServerException.prototype); - this.error = opts.error; - } -}; -let TooManyRequestsError$1 = class TooManyRequestsError extends SigninServiceException$1 { - name = "TooManyRequestsError"; - $fault = "client"; - error; - constructor(opts) { - super({ - name: "TooManyRequestsError", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, TooManyRequestsError.prototype); - this.error = opts.error; - } -}; -let ValidationException$1 = class ValidationException extends SigninServiceException$1 { - name = "ValidationException"; - $fault = "client"; - error; - constructor(opts) { - super({ - name: "ValidationException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ValidationException.prototype); - this.error = opts.error; - } -}; - -const _ADE = "AccessDeniedException"; -const _AT = "AccessToken"; -const _COAT = "CreateOAuth2Token"; -const _COATR = "CreateOAuth2TokenRequest"; -const _COATRB = "CreateOAuth2TokenRequestBody"; -const _COATRBr = "CreateOAuth2TokenResponseBody"; -const _COATRr = "CreateOAuth2TokenResponse"; -const _ISE = "InternalServerException"; -const _RT = "RefreshToken"; -const _TMRE = "TooManyRequestsError"; -const _VE = "ValidationException"; -const _aKI = "accessKeyId"; -const _aT = "accessToken"; -const _c = "client"; -const _cI = "clientId"; -const _cV = "codeVerifier"; -const _co = "code"; -const _e = "error"; -const _eI = "expiresIn"; -const _gT = "grantType"; -const _h = "http"; -const _hE = "httpError"; -const _iT = "idToken"; -const _jN = "jsonName"; -const _m = "message"; -const _rT = "refreshToken"; -const _rU = "redirectUri"; -const _s = "server"; -const _sAK = "secretAccessKey"; -const _sT = "sessionToken"; -const _sm = "smithy.ts.sdk.synthetic.com.amazonaws.signin"; -const _tI = "tokenInput"; -const _tO = "tokenOutput"; -const _tT = "tokenType"; -const n0 = "com.amazonaws.signin"; -var RefreshToken = [0, n0, _RT, 8, 0]; -var AccessDeniedException = [ - -3, - n0, - _ADE, - { - [_e]: _c, - }, - [_e, _m], - [0, 0], -]; -schema.TypeRegistry.for(n0).registerError(AccessDeniedException, AccessDeniedException$1); -var AccessToken = [ - 3, - n0, - _AT, - 8, - [_aKI, _sAK, _sT], - [ - [ - 0, - { - [_jN]: _aKI, - }, - ], - [ - 0, - { - [_jN]: _sAK, - }, - ], - [ - 0, - { - [_jN]: _sT, - }, - ], - ], -]; -var CreateOAuth2TokenRequest = [ - 3, - n0, - _COATR, - 0, - [_tI], - [[() => CreateOAuth2TokenRequestBody, 16]], -]; -var CreateOAuth2TokenRequestBody = [ - 3, - n0, - _COATRB, - 0, - [_cI, _gT, _co, _rU, _cV, _rT], - [ - [ - 0, - { - [_jN]: _cI, - }, - ], - [ - 0, - { - [_jN]: _gT, - }, - ], - 0, - [ - 0, - { - [_jN]: _rU, - }, - ], - [ - 0, - { - [_jN]: _cV, - }, - ], - [ - () => RefreshToken, - { - [_jN]: _rT, - }, - ], - ], -]; -var CreateOAuth2TokenResponse = [ - 3, - n0, - _COATRr, - 0, - [_tO], - [[() => CreateOAuth2TokenResponseBody, 16]], -]; -var CreateOAuth2TokenResponseBody = [ - 3, - n0, - _COATRBr, - 0, - [_aT, _tT, _eI, _rT, _iT], - [ - [ - () => AccessToken, - { - [_jN]: _aT, - }, - ], - [ - 0, - { - [_jN]: _tT, - }, - ], - [ - 1, - { - [_jN]: _eI, - }, - ], - [ - () => RefreshToken, - { - [_jN]: _rT, - }, - ], - [ - 0, - { - [_jN]: _iT, - }, - ], - ], -]; -var InternalServerException = [ - -3, - n0, - _ISE, - { - [_e]: _s, - [_hE]: 500, - }, - [_e, _m], - [0, 0], -]; -schema.TypeRegistry.for(n0).registerError(InternalServerException, InternalServerException$1); -var TooManyRequestsError = [ - -3, - n0, - _TMRE, - { - [_e]: _c, - [_hE]: 429, - }, - [_e, _m], - [0, 0], -]; -schema.TypeRegistry.for(n0).registerError(TooManyRequestsError, TooManyRequestsError$1); -var ValidationException = [ - -3, - n0, - _VE, - { - [_e]: _c, - [_hE]: 400, - }, - [_e, _m], - [0, 0], -]; -schema.TypeRegistry.for(n0).registerError(ValidationException, ValidationException$1); -var SigninServiceException = [-3, _sm, "SigninServiceException", 0, [], []]; -schema.TypeRegistry.for(_sm).registerError(SigninServiceException, SigninServiceException$1); -var CreateOAuth2Token = [ - 9, - n0, - _COAT, - { - [_h]: ["POST", "/v1/token", 200], - }, - () => CreateOAuth2TokenRequest, - () => CreateOAuth2TokenResponse, -]; - -class CreateOAuth2TokenCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("Signin", "CreateOAuth2Token", {}) - .n("SigninClient", "CreateOAuth2TokenCommand") - .sc(CreateOAuth2Token) - .build() { -} - -const commands = { - CreateOAuth2TokenCommand, -}; -class Signin extends SigninClient { -} -smithyClient.createAggregatedClient(commands, Signin); - -const OAuth2ErrorCode = { - AUTHCODE_EXPIRED: "AUTHCODE_EXPIRED", - INSUFFICIENT_PERMISSIONS: "INSUFFICIENT_PERMISSIONS", - INVALID_REQUEST: "INVALID_REQUEST", - SERVER_ERROR: "server_error", - TOKEN_EXPIRED: "TOKEN_EXPIRED", - USER_CREDENTIALS_CHANGED: "USER_CREDENTIALS_CHANGED", -}; - -Object.defineProperty(exports, "$Command", { - enumerable: true, - get: function () { return smithyClient.Command; } -}); -Object.defineProperty(exports, "__Client", { - enumerable: true, - get: function () { return smithyClient.Client; } -}); -exports.AccessDeniedException = AccessDeniedException$1; -exports.CreateOAuth2TokenCommand = CreateOAuth2TokenCommand; -exports.InternalServerException = InternalServerException$1; -exports.OAuth2ErrorCode = OAuth2ErrorCode; -exports.Signin = Signin; -exports.SigninClient = SigninClient; -exports.SigninServiceException = SigninServiceException$1; -exports.TooManyRequestsError = TooManyRequestsError$1; -exports.ValidationException = ValidationException$1; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/runtimeConfig.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/runtimeConfig.js deleted file mode 100644 index 5c617933..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/runtimeConfig.js +++ /dev/null @@ -1,54 +0,0 @@ -"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 util_user_agent_node_1 = require("@aws-sdk/util-user-agent-node"); -const config_resolver_1 = require("@smithy/config-resolver"); -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, - }; - 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, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? - (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), - 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.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), - 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; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/runtimeConfig.shared.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/runtimeConfig.shared.js deleted file mode 100644 index 79f18c72..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/signin/runtimeConfig.shared.js +++ /dev/null @@ -1,42 +0,0 @@ -"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-01-01", - 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.defaultSigninHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - logger: config?.logger ?? new smithy_client_1.NoOpLogger(), - protocol: config?.protocol ?? new protocols_1.AwsRestJsonProtocol({ defaultNamespace: "com.amazonaws.signin" }), - serviceId: config?.serviceId ?? "Signin", - urlParser: config?.urlParser ?? url_parser_1.parseUrl, - utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, - utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/auth/httpAuthSchemeProvider.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/auth/httpAuthSchemeProvider.js deleted file mode 100644 index 7a9f28a4..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/auth/httpAuthSchemeProvider.js +++ /dev/null @@ -1,56 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.resolveHttpAuthSchemeConfig = exports.defaultSSOOIDCHttpAuthSchemeProvider = exports.defaultSSOOIDCHttpAuthSchemeParametersProvider = void 0; -const core_1 = require("@aws-sdk/core"); -const util_middleware_1 = require("@smithy/util-middleware"); -const defaultSSOOIDCHttpAuthSchemeParametersProvider = 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.defaultSSOOIDCHttpAuthSchemeParametersProvider = defaultSSOOIDCHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "sso-oauth", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth", - }; -} -const defaultSSOOIDCHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "CreateToken": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); - } - } - return options; -}; -exports.defaultSSOOIDCHttpAuthSchemeProvider = defaultSSOOIDCHttpAuthSchemeProvider; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, core_1.resolveAwsSdkSigV4Config)(config); - return Object.assign(config_0, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), - }); -}; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/endpoint/endpointResolver.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/endpoint/endpointResolver.js deleted file mode 100644 index 7258a356..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/endpoint/endpointResolver.js +++ /dev/null @@ -1,18 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/endpoint/ruleset.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/endpoint/ruleset.js deleted file mode 100644 index 492b2264..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/endpoint/ruleset.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ruleSet = void 0; -const u = "required", v = "fn", w = "argv", x = "ref"; -const a = true, b = "isSet", c = "booleanEquals", d = "error", e = "endpoint", f = "tree", g = "PartitionResult", h = "getAttr", i = { [u]: false, "type": "string" }, j = { [u]: true, "default": false, "type": "boolean" }, k = { [x]: "Endpoint" }, l = { [v]: c, [w]: [{ [x]: "UseFIPS" }, true] }, m = { [v]: c, [w]: [{ [x]: "UseDualStack" }, true] }, n = {}, o = { [v]: h, [w]: [{ [x]: g }, "supportsFIPS"] }, p = { [x]: g }, q = { [v]: c, [w]: [true, { [v]: h, [w]: [p, "supportsDualStack"] }] }, r = [l], s = [m], t = [{ [x]: "Region" }]; -const _data = { version: "1.0", parameters: { Region: i, UseDualStack: j, UseFIPS: j, Endpoint: i }, rules: [{ conditions: [{ [v]: b, [w]: [k] }], rules: [{ conditions: r, error: "Invalid Configuration: FIPS and custom endpoint are not supported", type: d }, { conditions: s, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", type: d }, { endpoint: { url: k, properties: n, headers: n }, type: e }], type: f }, { conditions: [{ [v]: b, [w]: t }], rules: [{ conditions: [{ [v]: "aws.partition", [w]: t, assign: g }], rules: [{ conditions: [l, m], rules: [{ conditions: [{ [v]: c, [w]: [a, o] }, q], rules: [{ endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", type: d }], type: f }, { conditions: r, rules: [{ conditions: [{ [v]: c, [w]: [o, a] }], rules: [{ conditions: [{ [v]: "stringEquals", [w]: [{ [v]: h, [w]: [p, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://oidc.{Region}.amazonaws.com", properties: n, headers: n }, type: e }, { endpoint: { url: "https://oidc-fips.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "FIPS is enabled but this partition does not support FIPS", type: d }], type: f }, { conditions: s, rules: [{ conditions: [q], rules: [{ endpoint: { url: "https://oidc.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: n, headers: n }, type: e }], type: f }, { error: "DualStack is enabled but this partition does not support DualStack", type: d }], type: f }, { endpoint: { url: "https://oidc.{Region}.{PartitionResult#dnsSuffix}", properties: n, headers: n }, type: e }], type: f }], type: f }, { error: "Invalid Configuration: Missing Region", type: d }] }; -exports.ruleSet = _data; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/index.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/index.js deleted file mode 100644 index 61db06a2..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/index.js +++ /dev/null @@ -1,561 +0,0 @@ -'use strict'; - -var middlewareHostHeader = require('@aws-sdk/middleware-host-header'); -var middlewareLogger = require('@aws-sdk/middleware-logger'); -var middlewareRecursionDetection = require('@aws-sdk/middleware-recursion-detection'); -var middlewareUserAgent = require('@aws-sdk/middleware-user-agent'); -var configResolver = require('@smithy/config-resolver'); -var core = require('@smithy/core'); -var schema = require('@smithy/core/schema'); -var middlewareContentLength = require('@smithy/middleware-content-length'); -var middlewareEndpoint = require('@smithy/middleware-endpoint'); -var middlewareRetry = require('@smithy/middleware-retry'); -var smithyClient = require('@smithy/smithy-client'); -var httpAuthSchemeProvider = require('./auth/httpAuthSchemeProvider'); -var runtimeConfig = require('./runtimeConfig'); -var regionConfigResolver = require('@aws-sdk/region-config-resolver'); -var protocolHttp = require('@smithy/protocol-http'); - -const resolveClientEndpointParameters = (options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - defaultSigningName: "sso-oauth", - }); -}; -const commonParams = { - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, -}; - -const getHttpAuthExtensionConfiguration = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } - else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - }, - }; -}; -const resolveHttpAuthRuntimeConfig = (config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials(), - }; -}; - -const resolveRuntimeExtensions = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign(regionConfigResolver.getAwsRegionExtensionConfiguration(runtimeConfig), smithyClient.getDefaultExtensionConfiguration(runtimeConfig), protocolHttp.getHttpHandlerExtensionConfiguration(runtimeConfig), getHttpAuthExtensionConfiguration(runtimeConfig)); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, regionConfigResolver.resolveAwsRegionExtensionConfiguration(extensionConfiguration), smithyClient.resolveDefaultRuntimeConfig(extensionConfiguration), protocolHttp.resolveHttpHandlerRuntimeConfig(extensionConfiguration), resolveHttpAuthRuntimeConfig(extensionConfiguration)); -}; - -class SSOOIDCClient extends smithyClient.Client { - config; - constructor(...[configuration]) { - const _config_0 = runtimeConfig.getRuntimeConfig(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = resolveClientEndpointParameters(_config_0); - const _config_2 = middlewareUserAgent.resolveUserAgentConfig(_config_1); - const _config_3 = middlewareRetry.resolveRetryConfig(_config_2); - const _config_4 = configResolver.resolveRegionConfig(_config_3); - const _config_5 = middlewareHostHeader.resolveHostHeaderConfig(_config_4); - const _config_6 = middlewareEndpoint.resolveEndpointConfig(_config_5); - const _config_7 = httpAuthSchemeProvider.resolveHttpAuthSchemeConfig(_config_6); - const _config_8 = resolveRuntimeExtensions(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use(schema.getSchemaSerdePlugin(this.config)); - this.middlewareStack.use(middlewareUserAgent.getUserAgentPlugin(this.config)); - this.middlewareStack.use(middlewareRetry.getRetryPlugin(this.config)); - this.middlewareStack.use(middlewareContentLength.getContentLengthPlugin(this.config)); - this.middlewareStack.use(middlewareHostHeader.getHostHeaderPlugin(this.config)); - this.middlewareStack.use(middlewareLogger.getLoggerPlugin(this.config)); - this.middlewareStack.use(middlewareRecursionDetection.getRecursionDetectionPlugin(this.config)); - this.middlewareStack.use(core.getHttpAuthSchemeEndpointRuleSetPlugin(this.config, { - httpAuthSchemeParametersProvider: httpAuthSchemeProvider.defaultSSOOIDCHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config) => new core.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials, - }), - })); - this.middlewareStack.use(core.getHttpSigningPlugin(this.config)); - } - destroy() { - super.destroy(); - } -} - -let SSOOIDCServiceException$1 = class SSOOIDCServiceException extends smithyClient.ServiceException { - constructor(options) { - super(options); - Object.setPrototypeOf(this, SSOOIDCServiceException.prototype); - } -}; - -let AccessDeniedException$1 = class AccessDeniedException extends SSOOIDCServiceException$1 { - name = "AccessDeniedException"; - $fault = "client"; - error; - reason; - error_description; - constructor(opts) { - super({ - name: "AccessDeniedException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, AccessDeniedException.prototype); - this.error = opts.error; - this.reason = opts.reason; - this.error_description = opts.error_description; - } -}; -let AuthorizationPendingException$1 = class AuthorizationPendingException extends SSOOIDCServiceException$1 { - name = "AuthorizationPendingException"; - $fault = "client"; - error; - error_description; - constructor(opts) { - super({ - name: "AuthorizationPendingException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, AuthorizationPendingException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -let ExpiredTokenException$1 = class ExpiredTokenException extends SSOOIDCServiceException$1 { - name = "ExpiredTokenException"; - $fault = "client"; - error; - error_description; - constructor(opts) { - super({ - name: "ExpiredTokenException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ExpiredTokenException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -let InternalServerException$1 = class InternalServerException extends SSOOIDCServiceException$1 { - name = "InternalServerException"; - $fault = "server"; - error; - error_description; - constructor(opts) { - super({ - name: "InternalServerException", - $fault: "server", - ...opts, - }); - Object.setPrototypeOf(this, InternalServerException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -let InvalidClientException$1 = class InvalidClientException extends SSOOIDCServiceException$1 { - name = "InvalidClientException"; - $fault = "client"; - error; - error_description; - constructor(opts) { - super({ - name: "InvalidClientException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, InvalidClientException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -let InvalidGrantException$1 = class InvalidGrantException extends SSOOIDCServiceException$1 { - name = "InvalidGrantException"; - $fault = "client"; - error; - error_description; - constructor(opts) { - super({ - name: "InvalidGrantException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, InvalidGrantException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -let InvalidRequestException$1 = class InvalidRequestException extends SSOOIDCServiceException$1 { - name = "InvalidRequestException"; - $fault = "client"; - error; - reason; - error_description; - constructor(opts) { - super({ - name: "InvalidRequestException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, InvalidRequestException.prototype); - this.error = opts.error; - this.reason = opts.reason; - this.error_description = opts.error_description; - } -}; -let InvalidScopeException$1 = class InvalidScopeException extends SSOOIDCServiceException$1 { - name = "InvalidScopeException"; - $fault = "client"; - error; - error_description; - constructor(opts) { - super({ - name: "InvalidScopeException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, InvalidScopeException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -let SlowDownException$1 = class SlowDownException extends SSOOIDCServiceException$1 { - name = "SlowDownException"; - $fault = "client"; - error; - error_description; - constructor(opts) { - super({ - name: "SlowDownException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, SlowDownException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -let UnauthorizedClientException$1 = class UnauthorizedClientException extends SSOOIDCServiceException$1 { - name = "UnauthorizedClientException"; - $fault = "client"; - error; - error_description; - constructor(opts) { - super({ - name: "UnauthorizedClientException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, UnauthorizedClientException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; -let UnsupportedGrantTypeException$1 = class UnsupportedGrantTypeException extends SSOOIDCServiceException$1 { - name = "UnsupportedGrantTypeException"; - $fault = "client"; - error; - error_description; - constructor(opts) { - super({ - name: "UnsupportedGrantTypeException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, UnsupportedGrantTypeException.prototype); - this.error = opts.error; - this.error_description = opts.error_description; - } -}; - -const _ADE = "AccessDeniedException"; -const _APE = "AuthorizationPendingException"; -const _AT = "AccessToken"; -const _CS = "ClientSecret"; -const _CT = "CreateToken"; -const _CTR = "CreateTokenRequest"; -const _CTRr = "CreateTokenResponse"; -const _CV = "CodeVerifier"; -const _ETE = "ExpiredTokenException"; -const _ICE = "InvalidClientException"; -const _IGE = "InvalidGrantException"; -const _IRE = "InvalidRequestException"; -const _ISE = "InternalServerException"; -const _ISEn = "InvalidScopeException"; -const _IT = "IdToken"; -const _RT = "RefreshToken"; -const _SDE = "SlowDownException"; -const _UCE = "UnauthorizedClientException"; -const _UGTE = "UnsupportedGrantTypeException"; -const _aT = "accessToken"; -const _c = "client"; -const _cI = "clientId"; -const _cS = "clientSecret"; -const _cV = "codeVerifier"; -const _co = "code"; -const _dC = "deviceCode"; -const _e = "error"; -const _eI = "expiresIn"; -const _ed = "error_description"; -const _gT = "grantType"; -const _h = "http"; -const _hE = "httpError"; -const _iT = "idToken"; -const _r = "reason"; -const _rT = "refreshToken"; -const _rU = "redirectUri"; -const _s = "scope"; -const _se = "server"; -const _sm = "smithy.ts.sdk.synthetic.com.amazonaws.ssooidc"; -const _tT = "tokenType"; -const n0 = "com.amazonaws.ssooidc"; -var AccessToken = [0, n0, _AT, 8, 0]; -var ClientSecret = [0, n0, _CS, 8, 0]; -var CodeVerifier = [0, n0, _CV, 8, 0]; -var IdToken = [0, n0, _IT, 8, 0]; -var RefreshToken = [0, n0, _RT, 8, 0]; -var AccessDeniedException = [ - -3, - n0, - _ADE, - { - [_e]: _c, - [_hE]: 400, - }, - [_e, _r, _ed], - [0, 0, 0], -]; -schema.TypeRegistry.for(n0).registerError(AccessDeniedException, AccessDeniedException$1); -var AuthorizationPendingException = [ - -3, - n0, - _APE, - { - [_e]: _c, - [_hE]: 400, - }, - [_e, _ed], - [0, 0], -]; -schema.TypeRegistry.for(n0).registerError(AuthorizationPendingException, AuthorizationPendingException$1); -var CreateTokenRequest = [ - 3, - n0, - _CTR, - 0, - [_cI, _cS, _gT, _dC, _co, _rT, _s, _rU, _cV], - [0, [() => ClientSecret, 0], 0, 0, 0, [() => RefreshToken, 0], 64 | 0, 0, [() => CodeVerifier, 0]], -]; -var CreateTokenResponse = [ - 3, - n0, - _CTRr, - 0, - [_aT, _tT, _eI, _rT, _iT], - [[() => AccessToken, 0], 0, 1, [() => RefreshToken, 0], [() => IdToken, 0]], -]; -var ExpiredTokenException = [ - -3, - n0, - _ETE, - { - [_e]: _c, - [_hE]: 400, - }, - [_e, _ed], - [0, 0], -]; -schema.TypeRegistry.for(n0).registerError(ExpiredTokenException, ExpiredTokenException$1); -var InternalServerException = [ - -3, - n0, - _ISE, - { - [_e]: _se, - [_hE]: 500, - }, - [_e, _ed], - [0, 0], -]; -schema.TypeRegistry.for(n0).registerError(InternalServerException, InternalServerException$1); -var InvalidClientException = [ - -3, - n0, - _ICE, - { - [_e]: _c, - [_hE]: 401, - }, - [_e, _ed], - [0, 0], -]; -schema.TypeRegistry.for(n0).registerError(InvalidClientException, InvalidClientException$1); -var InvalidGrantException = [ - -3, - n0, - _IGE, - { - [_e]: _c, - [_hE]: 400, - }, - [_e, _ed], - [0, 0], -]; -schema.TypeRegistry.for(n0).registerError(InvalidGrantException, InvalidGrantException$1); -var InvalidRequestException = [ - -3, - n0, - _IRE, - { - [_e]: _c, - [_hE]: 400, - }, - [_e, _r, _ed], - [0, 0, 0], -]; -schema.TypeRegistry.for(n0).registerError(InvalidRequestException, InvalidRequestException$1); -var InvalidScopeException = [ - -3, - n0, - _ISEn, - { - [_e]: _c, - [_hE]: 400, - }, - [_e, _ed], - [0, 0], -]; -schema.TypeRegistry.for(n0).registerError(InvalidScopeException, InvalidScopeException$1); -var SlowDownException = [ - -3, - n0, - _SDE, - { - [_e]: _c, - [_hE]: 400, - }, - [_e, _ed], - [0, 0], -]; -schema.TypeRegistry.for(n0).registerError(SlowDownException, SlowDownException$1); -var UnauthorizedClientException = [ - -3, - n0, - _UCE, - { - [_e]: _c, - [_hE]: 400, - }, - [_e, _ed], - [0, 0], -]; -schema.TypeRegistry.for(n0).registerError(UnauthorizedClientException, UnauthorizedClientException$1); -var UnsupportedGrantTypeException = [ - -3, - n0, - _UGTE, - { - [_e]: _c, - [_hE]: 400, - }, - [_e, _ed], - [0, 0], -]; -schema.TypeRegistry.for(n0).registerError(UnsupportedGrantTypeException, UnsupportedGrantTypeException$1); -var SSOOIDCServiceException = [-3, _sm, "SSOOIDCServiceException", 0, [], []]; -schema.TypeRegistry.for(_sm).registerError(SSOOIDCServiceException, SSOOIDCServiceException$1); -var CreateToken = [ - 9, - n0, - _CT, - { - [_h]: ["POST", "/token", 200], - }, - () => CreateTokenRequest, - () => CreateTokenResponse, -]; - -class CreateTokenCommand extends smithyClient.Command - .classBuilder() - .ep(commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSSSOOIDCService", "CreateToken", {}) - .n("SSOOIDCClient", "CreateTokenCommand") - .sc(CreateToken) - .build() { -} - -const commands = { - CreateTokenCommand, -}; -class SSOOIDC extends SSOOIDCClient { -} -smithyClient.createAggregatedClient(commands, SSOOIDC); - -const AccessDeniedExceptionReason = { - KMS_ACCESS_DENIED: "KMS_AccessDeniedException", -}; -const InvalidRequestExceptionReason = { - KMS_DISABLED_KEY: "KMS_DisabledException", - KMS_INVALID_KEY_USAGE: "KMS_InvalidKeyUsageException", - KMS_INVALID_STATE: "KMS_InvalidStateException", - KMS_KEY_NOT_FOUND: "KMS_NotFoundException", -}; - -Object.defineProperty(exports, "$Command", { - enumerable: true, - get: function () { return smithyClient.Command; } -}); -Object.defineProperty(exports, "__Client", { - enumerable: true, - get: function () { return smithyClient.Client; } -}); -exports.AccessDeniedException = AccessDeniedException$1; -exports.AccessDeniedExceptionReason = AccessDeniedExceptionReason; -exports.AuthorizationPendingException = AuthorizationPendingException$1; -exports.CreateTokenCommand = CreateTokenCommand; -exports.ExpiredTokenException = ExpiredTokenException$1; -exports.InternalServerException = InternalServerException$1; -exports.InvalidClientException = InvalidClientException$1; -exports.InvalidGrantException = InvalidGrantException$1; -exports.InvalidRequestException = InvalidRequestException$1; -exports.InvalidRequestExceptionReason = InvalidRequestExceptionReason; -exports.InvalidScopeException = InvalidScopeException$1; -exports.SSOOIDC = SSOOIDC; -exports.SSOOIDCClient = SSOOIDCClient; -exports.SSOOIDCServiceException = SSOOIDCServiceException$1; -exports.SlowDownException = SlowDownException$1; -exports.UnauthorizedClientException = UnauthorizedClientException$1; -exports.UnsupportedGrantTypeException = UnsupportedGrantTypeException$1; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/runtimeConfig.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/runtimeConfig.js deleted file mode 100644 index 5c617933..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/runtimeConfig.js +++ /dev/null @@ -1,54 +0,0 @@ -"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 util_user_agent_node_1 = require("@aws-sdk/util-user-agent-node"); -const config_resolver_1 = require("@smithy/config-resolver"); -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, - }; - 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, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? - (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), - 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.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), - 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; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/runtimeConfig.shared.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/runtimeConfig.shared.js deleted file mode 100644 index 0e7a44f9..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sso-oidc/runtimeConfig.shared.js +++ /dev/null @@ -1,42 +0,0 @@ -"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: "2019-06-10", - 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.defaultSSOOIDCHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - logger: config?.logger ?? new smithy_client_1.NoOpLogger(), - protocol: config?.protocol ?? new protocols_1.AwsRestJsonProtocol({ defaultNamespace: "com.amazonaws.ssooidc" }), - serviceId: config?.serviceId ?? "SSO OIDC", - urlParser: config?.urlParser ?? url_parser_1.parseUrl, - utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, - utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/STSClient.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/STSClient.js deleted file mode 100644 index 879af8b9..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/STSClient.js +++ /dev/null @@ -1,54 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.STSClient = exports.__Client = void 0; -const middleware_host_header_1 = require("@aws-sdk/middleware-host-header"); -const middleware_logger_1 = require("@aws-sdk/middleware-logger"); -const middleware_recursion_detection_1 = require("@aws-sdk/middleware-recursion-detection"); -const middleware_user_agent_1 = require("@aws-sdk/middleware-user-agent"); -const config_resolver_1 = require("@smithy/config-resolver"); -const core_1 = require("@smithy/core"); -const schema_1 = require("@smithy/core/schema"); -const middleware_content_length_1 = require("@smithy/middleware-content-length"); -const middleware_endpoint_1 = require("@smithy/middleware-endpoint"); -const middleware_retry_1 = require("@smithy/middleware-retry"); -const smithy_client_1 = require("@smithy/smithy-client"); -Object.defineProperty(exports, "__Client", { enumerable: true, get: function () { return smithy_client_1.Client; } }); -const httpAuthSchemeProvider_1 = require("./auth/httpAuthSchemeProvider"); -const EndpointParameters_1 = require("./endpoint/EndpointParameters"); -const runtimeConfig_1 = require("./runtimeConfig"); -const runtimeExtensions_1 = require("./runtimeExtensions"); -class STSClient extends smithy_client_1.Client { - config; - constructor(...[configuration]) { - const _config_0 = (0, runtimeConfig_1.getRuntimeConfig)(configuration || {}); - super(_config_0); - this.initConfig = _config_0; - const _config_1 = (0, EndpointParameters_1.resolveClientEndpointParameters)(_config_0); - const _config_2 = (0, middleware_user_agent_1.resolveUserAgentConfig)(_config_1); - const _config_3 = (0, middleware_retry_1.resolveRetryConfig)(_config_2); - const _config_4 = (0, config_resolver_1.resolveRegionConfig)(_config_3); - const _config_5 = (0, middleware_host_header_1.resolveHostHeaderConfig)(_config_4); - const _config_6 = (0, middleware_endpoint_1.resolveEndpointConfig)(_config_5); - const _config_7 = (0, httpAuthSchemeProvider_1.resolveHttpAuthSchemeConfig)(_config_6); - const _config_8 = (0, runtimeExtensions_1.resolveRuntimeExtensions)(_config_7, configuration?.extensions || []); - this.config = _config_8; - this.middlewareStack.use((0, schema_1.getSchemaSerdePlugin)(this.config)); - this.middlewareStack.use((0, middleware_user_agent_1.getUserAgentPlugin)(this.config)); - this.middlewareStack.use((0, middleware_retry_1.getRetryPlugin)(this.config)); - this.middlewareStack.use((0, middleware_content_length_1.getContentLengthPlugin)(this.config)); - this.middlewareStack.use((0, middleware_host_header_1.getHostHeaderPlugin)(this.config)); - this.middlewareStack.use((0, middleware_logger_1.getLoggerPlugin)(this.config)); - this.middlewareStack.use((0, middleware_recursion_detection_1.getRecursionDetectionPlugin)(this.config)); - this.middlewareStack.use((0, core_1.getHttpAuthSchemeEndpointRuleSetPlugin)(this.config, { - httpAuthSchemeParametersProvider: httpAuthSchemeProvider_1.defaultSTSHttpAuthSchemeParametersProvider, - identityProviderConfigProvider: async (config) => new core_1.DefaultIdentityProviderConfig({ - "aws.auth#sigv4": config.credentials, - }), - })); - this.middlewareStack.use((0, core_1.getHttpSigningPlugin)(this.config)); - } - destroy() { - super.destroy(); - } -} -exports.STSClient = STSClient; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/auth/httpAuthExtensionConfiguration.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/auth/httpAuthExtensionConfiguration.js deleted file mode 100644 index 239095e0..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/auth/httpAuthExtensionConfiguration.js +++ /dev/null @@ -1,43 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.resolveHttpAuthRuntimeConfig = exports.getHttpAuthExtensionConfiguration = void 0; -const getHttpAuthExtensionConfiguration = (runtimeConfig) => { - const _httpAuthSchemes = runtimeConfig.httpAuthSchemes; - let _httpAuthSchemeProvider = runtimeConfig.httpAuthSchemeProvider; - let _credentials = runtimeConfig.credentials; - return { - setHttpAuthScheme(httpAuthScheme) { - const index = _httpAuthSchemes.findIndex((scheme) => scheme.schemeId === httpAuthScheme.schemeId); - if (index === -1) { - _httpAuthSchemes.push(httpAuthScheme); - } - else { - _httpAuthSchemes.splice(index, 1, httpAuthScheme); - } - }, - httpAuthSchemes() { - return _httpAuthSchemes; - }, - setHttpAuthSchemeProvider(httpAuthSchemeProvider) { - _httpAuthSchemeProvider = httpAuthSchemeProvider; - }, - httpAuthSchemeProvider() { - return _httpAuthSchemeProvider; - }, - setCredentials(credentials) { - _credentials = credentials; - }, - credentials() { - return _credentials; - }, - }; -}; -exports.getHttpAuthExtensionConfiguration = getHttpAuthExtensionConfiguration; -const resolveHttpAuthRuntimeConfig = (config) => { - return { - httpAuthSchemes: config.httpAuthSchemes(), - httpAuthSchemeProvider: config.httpAuthSchemeProvider(), - credentials: config.credentials(), - }; -}; -exports.resolveHttpAuthRuntimeConfig = resolveHttpAuthRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/auth/httpAuthSchemeProvider.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/auth/httpAuthSchemeProvider.js deleted file mode 100644 index 842241a7..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/auth/httpAuthSchemeProvider.js +++ /dev/null @@ -1,62 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.resolveHttpAuthSchemeConfig = exports.resolveStsAuthConfig = exports.defaultSTSHttpAuthSchemeProvider = exports.defaultSTSHttpAuthSchemeParametersProvider = void 0; -const core_1 = require("@aws-sdk/core"); -const util_middleware_1 = require("@smithy/util-middleware"); -const STSClient_1 = require("../STSClient"); -const defaultSTSHttpAuthSchemeParametersProvider = 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.defaultSTSHttpAuthSchemeParametersProvider = defaultSTSHttpAuthSchemeParametersProvider; -function createAwsAuthSigv4HttpAuthOption(authParameters) { - return { - schemeId: "aws.auth#sigv4", - signingProperties: { - name: "sts", - region: authParameters.region, - }, - propertiesExtractor: (config, context) => ({ - signingProperties: { - config, - context, - }, - }), - }; -} -function createSmithyApiNoAuthHttpAuthOption(authParameters) { - return { - schemeId: "smithy.api#noAuth", - }; -} -const defaultSTSHttpAuthSchemeProvider = (authParameters) => { - const options = []; - switch (authParameters.operation) { - case "AssumeRoleWithWebIdentity": { - options.push(createSmithyApiNoAuthHttpAuthOption(authParameters)); - break; - } - default: { - options.push(createAwsAuthSigv4HttpAuthOption(authParameters)); - } - } - return options; -}; -exports.defaultSTSHttpAuthSchemeProvider = defaultSTSHttpAuthSchemeProvider; -const resolveStsAuthConfig = (input) => Object.assign(input, { - stsClientCtor: STSClient_1.STSClient, -}); -exports.resolveStsAuthConfig = resolveStsAuthConfig; -const resolveHttpAuthSchemeConfig = (config) => { - const config_0 = (0, exports.resolveStsAuthConfig)(config); - const config_1 = (0, core_1.resolveAwsSdkSigV4Config)(config_0); - return Object.assign(config_1, { - authSchemePreference: (0, util_middleware_1.normalizeProvider)(config.authSchemePreference ?? []), - }); -}; -exports.resolveHttpAuthSchemeConfig = resolveHttpAuthSchemeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/EndpointParameters.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/EndpointParameters.js deleted file mode 100644 index 3aec6a5e..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/EndpointParameters.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.commonParams = exports.resolveClientEndpointParameters = void 0; -const resolveClientEndpointParameters = (options) => { - return Object.assign(options, { - useDualstackEndpoint: options.useDualstackEndpoint ?? false, - useFipsEndpoint: options.useFipsEndpoint ?? false, - useGlobalEndpoint: options.useGlobalEndpoint ?? false, - defaultSigningName: "sts", - }); -}; -exports.resolveClientEndpointParameters = resolveClientEndpointParameters; -exports.commonParams = { - UseGlobalEndpoint: { type: "builtInParams", name: "useGlobalEndpoint" }, - UseFIPS: { type: "builtInParams", name: "useFipsEndpoint" }, - Endpoint: { type: "builtInParams", name: "endpoint" }, - Region: { type: "builtInParams", name: "region" }, - UseDualStack: { type: "builtInParams", name: "useDualstackEndpoint" }, -}; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/endpointResolver.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/endpointResolver.js deleted file mode 100644 index 6bfb6e90..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/endpointResolver.js +++ /dev/null @@ -1,18 +0,0 @@ -"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", "UseGlobalEndpoint"], -}); -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; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/ruleset.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/ruleset.js deleted file mode 100644 index a5e5cf2a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/endpoint/ruleset.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ruleSet = void 0; -const F = "required", G = "type", H = "fn", I = "argv", J = "ref"; -const a = false, b = true, c = "booleanEquals", d = "stringEquals", e = "sigv4", f = "sts", g = "us-east-1", h = "endpoint", i = "https://sts.{Region}.{PartitionResult#dnsSuffix}", j = "tree", k = "error", l = "getAttr", m = { [F]: false, [G]: "string" }, n = { [F]: true, "default": false, [G]: "boolean" }, o = { [J]: "Endpoint" }, p = { [H]: "isSet", [I]: [{ [J]: "Region" }] }, q = { [J]: "Region" }, r = { [H]: "aws.partition", [I]: [q], "assign": "PartitionResult" }, s = { [J]: "UseFIPS" }, t = { [J]: "UseDualStack" }, u = { "url": "https://sts.amazonaws.com", "properties": { "authSchemes": [{ "name": e, "signingName": f, "signingRegion": g }] }, "headers": {} }, v = {}, w = { "conditions": [{ [H]: d, [I]: [q, "aws-global"] }], [h]: u, [G]: h }, x = { [H]: c, [I]: [s, true] }, y = { [H]: c, [I]: [t, true] }, z = { [H]: l, [I]: [{ [J]: "PartitionResult" }, "supportsFIPS"] }, A = { [J]: "PartitionResult" }, B = { [H]: c, [I]: [true, { [H]: l, [I]: [A, "supportsDualStack"] }] }, C = [{ [H]: "isSet", [I]: [o] }], D = [x], E = [y]; -const _data = { version: "1.0", parameters: { Region: m, UseDualStack: n, UseFIPS: n, Endpoint: m, UseGlobalEndpoint: n }, rules: [{ conditions: [{ [H]: c, [I]: [{ [J]: "UseGlobalEndpoint" }, b] }, { [H]: "not", [I]: C }, p, r, { [H]: c, [I]: [s, a] }, { [H]: c, [I]: [t, a] }], rules: [{ conditions: [{ [H]: d, [I]: [q, "ap-northeast-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-south-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-southeast-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "ap-southeast-2"] }], endpoint: u, [G]: h }, w, { conditions: [{ [H]: d, [I]: [q, "ca-central-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-central-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-north-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-2"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "eu-west-3"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "sa-east-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, g] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-east-2"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-west-1"] }], endpoint: u, [G]: h }, { conditions: [{ [H]: d, [I]: [q, "us-west-2"] }], endpoint: u, [G]: h }, { endpoint: { url: i, properties: { authSchemes: [{ name: e, signingName: f, signingRegion: "{Region}" }] }, headers: v }, [G]: h }], [G]: j }, { conditions: C, rules: [{ conditions: D, error: "Invalid Configuration: FIPS and custom endpoint are not supported", [G]: k }, { conditions: E, error: "Invalid Configuration: Dualstack and custom endpoint are not supported", [G]: k }, { endpoint: { url: o, properties: v, headers: v }, [G]: h }], [G]: j }, { conditions: [p], rules: [{ conditions: [r], rules: [{ conditions: [x, y], rules: [{ conditions: [{ [H]: c, [I]: [b, z] }, B], rules: [{ endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "FIPS and DualStack are enabled, but this partition does not support one or both", [G]: k }], [G]: j }, { conditions: D, rules: [{ conditions: [{ [H]: c, [I]: [z, b] }], rules: [{ conditions: [{ [H]: d, [I]: [{ [H]: l, [I]: [A, "name"] }, "aws-us-gov"] }], endpoint: { url: "https://sts.{Region}.amazonaws.com", properties: v, headers: v }, [G]: h }, { endpoint: { url: "https://sts-fips.{Region}.{PartitionResult#dnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "FIPS is enabled but this partition does not support FIPS", [G]: k }], [G]: j }, { conditions: E, rules: [{ conditions: [B], rules: [{ endpoint: { url: "https://sts.{Region}.{PartitionResult#dualStackDnsSuffix}", properties: v, headers: v }, [G]: h }], [G]: j }, { error: "DualStack is enabled but this partition does not support DualStack", [G]: k }], [G]: j }, w, { endpoint: { url: i, properties: v, headers: v }, [G]: h }], [G]: j }], [G]: j }, { error: "Invalid Configuration: Missing Region", [G]: k }] }; -exports.ruleSet = _data; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/index.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/index.js deleted file mode 100644 index 115f95a7..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/index.js +++ /dev/null @@ -1,488 +0,0 @@ -'use strict'; - -var STSClient = require('./STSClient'); -var smithyClient = require('@smithy/smithy-client'); -var middlewareEndpoint = require('@smithy/middleware-endpoint'); -var EndpointParameters = require('./endpoint/EndpointParameters'); -var schema = require('@smithy/core/schema'); -var client = require('@aws-sdk/core/client'); -var regionConfigResolver = require('@aws-sdk/region-config-resolver'); - -let STSServiceException$1 = class STSServiceException extends smithyClient.ServiceException { - constructor(options) { - super(options); - Object.setPrototypeOf(this, STSServiceException.prototype); - } -}; - -let ExpiredTokenException$1 = class ExpiredTokenException extends STSServiceException$1 { - name = "ExpiredTokenException"; - $fault = "client"; - constructor(opts) { - super({ - name: "ExpiredTokenException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, ExpiredTokenException.prototype); - } -}; -let MalformedPolicyDocumentException$1 = class MalformedPolicyDocumentException extends STSServiceException$1 { - name = "MalformedPolicyDocumentException"; - $fault = "client"; - constructor(opts) { - super({ - name: "MalformedPolicyDocumentException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, MalformedPolicyDocumentException.prototype); - } -}; -let PackedPolicyTooLargeException$1 = class PackedPolicyTooLargeException extends STSServiceException$1 { - name = "PackedPolicyTooLargeException"; - $fault = "client"; - constructor(opts) { - super({ - name: "PackedPolicyTooLargeException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, PackedPolicyTooLargeException.prototype); - } -}; -let RegionDisabledException$1 = class RegionDisabledException extends STSServiceException$1 { - name = "RegionDisabledException"; - $fault = "client"; - constructor(opts) { - super({ - name: "RegionDisabledException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, RegionDisabledException.prototype); - } -}; -let IDPRejectedClaimException$1 = class IDPRejectedClaimException extends STSServiceException$1 { - name = "IDPRejectedClaimException"; - $fault = "client"; - constructor(opts) { - super({ - name: "IDPRejectedClaimException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, IDPRejectedClaimException.prototype); - } -}; -let InvalidIdentityTokenException$1 = class InvalidIdentityTokenException extends STSServiceException$1 { - name = "InvalidIdentityTokenException"; - $fault = "client"; - constructor(opts) { - super({ - name: "InvalidIdentityTokenException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, InvalidIdentityTokenException.prototype); - } -}; -let IDPCommunicationErrorException$1 = class IDPCommunicationErrorException extends STSServiceException$1 { - name = "IDPCommunicationErrorException"; - $fault = "client"; - constructor(opts) { - super({ - name: "IDPCommunicationErrorException", - $fault: "client", - ...opts, - }); - Object.setPrototypeOf(this, IDPCommunicationErrorException.prototype); - } -}; - -const _A = "Arn"; -const _AKI = "AccessKeyId"; -const _AR = "AssumeRole"; -const _ARI = "AssumedRoleId"; -const _ARR = "AssumeRoleRequest"; -const _ARRs = "AssumeRoleResponse"; -const _ARU = "AssumedRoleUser"; -const _ARWWI = "AssumeRoleWithWebIdentity"; -const _ARWWIR = "AssumeRoleWithWebIdentityRequest"; -const _ARWWIRs = "AssumeRoleWithWebIdentityResponse"; -const _Au = "Audience"; -const _C = "Credentials"; -const _CA = "ContextAssertion"; -const _DS = "DurationSeconds"; -const _E = "Expiration"; -const _EI = "ExternalId"; -const _ETE = "ExpiredTokenException"; -const _IDPCEE = "IDPCommunicationErrorException"; -const _IDPRCE = "IDPRejectedClaimException"; -const _IITE = "InvalidIdentityTokenException"; -const _K = "Key"; -const _MPDE = "MalformedPolicyDocumentException"; -const _P = "Policy"; -const _PA = "PolicyArns"; -const _PAr = "ProviderArn"; -const _PC = "ProvidedContexts"; -const _PCLT = "ProvidedContextsListType"; -const _PCr = "ProvidedContext"; -const _PDT = "PolicyDescriptorType"; -const _PI = "ProviderId"; -const _PPS = "PackedPolicySize"; -const _PPTLE = "PackedPolicyTooLargeException"; -const _Pr = "Provider"; -const _RA = "RoleArn"; -const _RDE = "RegionDisabledException"; -const _RSN = "RoleSessionName"; -const _SAK = "SecretAccessKey"; -const _SFWIT = "SubjectFromWebIdentityToken"; -const _SI = "SourceIdentity"; -const _SN = "SerialNumber"; -const _ST = "SessionToken"; -const _T = "Tags"; -const _TC = "TokenCode"; -const _TTK = "TransitiveTagKeys"; -const _Ta = "Tag"; -const _V = "Value"; -const _WIT = "WebIdentityToken"; -const _a = "arn"; -const _aKST = "accessKeySecretType"; -const _aQE = "awsQueryError"; -const _c = "client"; -const _cTT = "clientTokenType"; -const _e = "error"; -const _hE = "httpError"; -const _m = "message"; -const _pDLT = "policyDescriptorListType"; -const _s = "smithy.ts.sdk.synthetic.com.amazonaws.sts"; -const _tLT = "tagListType"; -const n0 = "com.amazonaws.sts"; -var accessKeySecretType = [0, n0, _aKST, 8, 0]; -var clientTokenType = [0, n0, _cTT, 8, 0]; -var AssumedRoleUser = [3, n0, _ARU, 0, [_ARI, _A], [0, 0]]; -var AssumeRoleRequest = [ - 3, - n0, - _ARR, - 0, - [_RA, _RSN, _PA, _P, _DS, _T, _TTK, _EI, _SN, _TC, _SI, _PC], - [0, 0, () => policyDescriptorListType, 0, 1, () => tagListType, 64 | 0, 0, 0, 0, 0, () => ProvidedContextsListType], -]; -var AssumeRoleResponse = [ - 3, - n0, - _ARRs, - 0, - [_C, _ARU, _PPS, _SI], - [[() => Credentials, 0], () => AssumedRoleUser, 1, 0], -]; -var AssumeRoleWithWebIdentityRequest = [ - 3, - n0, - _ARWWIR, - 0, - [_RA, _RSN, _WIT, _PI, _PA, _P, _DS], - [0, 0, [() => clientTokenType, 0], 0, () => policyDescriptorListType, 0, 1], -]; -var AssumeRoleWithWebIdentityResponse = [ - 3, - n0, - _ARWWIRs, - 0, - [_C, _SFWIT, _ARU, _PPS, _Pr, _Au, _SI], - [[() => Credentials, 0], 0, () => AssumedRoleUser, 1, 0, 0, 0], -]; -var Credentials = [ - 3, - n0, - _C, - 0, - [_AKI, _SAK, _ST, _E], - [0, [() => accessKeySecretType, 0], 0, 4], -]; -var ExpiredTokenException = [ - -3, - n0, - _ETE, - { - [_e]: _c, - [_hE]: 400, - [_aQE]: [`ExpiredTokenException`, 400], - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(ExpiredTokenException, ExpiredTokenException$1); -var IDPCommunicationErrorException = [ - -3, - n0, - _IDPCEE, - { - [_e]: _c, - [_hE]: 400, - [_aQE]: [`IDPCommunicationError`, 400], - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(IDPCommunicationErrorException, IDPCommunicationErrorException$1); -var IDPRejectedClaimException = [ - -3, - n0, - _IDPRCE, - { - [_e]: _c, - [_hE]: 403, - [_aQE]: [`IDPRejectedClaim`, 403], - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(IDPRejectedClaimException, IDPRejectedClaimException$1); -var InvalidIdentityTokenException = [ - -3, - n0, - _IITE, - { - [_e]: _c, - [_hE]: 400, - [_aQE]: [`InvalidIdentityToken`, 400], - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(InvalidIdentityTokenException, InvalidIdentityTokenException$1); -var MalformedPolicyDocumentException = [ - -3, - n0, - _MPDE, - { - [_e]: _c, - [_hE]: 400, - [_aQE]: [`MalformedPolicyDocument`, 400], - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(MalformedPolicyDocumentException, MalformedPolicyDocumentException$1); -var PackedPolicyTooLargeException = [ - -3, - n0, - _PPTLE, - { - [_e]: _c, - [_hE]: 400, - [_aQE]: [`PackedPolicyTooLarge`, 400], - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(PackedPolicyTooLargeException, PackedPolicyTooLargeException$1); -var PolicyDescriptorType = [3, n0, _PDT, 0, [_a], [0]]; -var ProvidedContext = [3, n0, _PCr, 0, [_PAr, _CA], [0, 0]]; -var RegionDisabledException = [ - -3, - n0, - _RDE, - { - [_e]: _c, - [_hE]: 403, - [_aQE]: [`RegionDisabledException`, 403], - }, - [_m], - [0], -]; -schema.TypeRegistry.for(n0).registerError(RegionDisabledException, RegionDisabledException$1); -var Tag = [3, n0, _Ta, 0, [_K, _V], [0, 0]]; -var STSServiceException = [-3, _s, "STSServiceException", 0, [], []]; -schema.TypeRegistry.for(_s).registerError(STSServiceException, STSServiceException$1); -var policyDescriptorListType = [1, n0, _pDLT, 0, () => PolicyDescriptorType]; -var ProvidedContextsListType = [1, n0, _PCLT, 0, () => ProvidedContext]; -var tagListType = [1, n0, _tLT, 0, () => Tag]; -var AssumeRole = [9, n0, _AR, 0, () => AssumeRoleRequest, () => AssumeRoleResponse]; -var AssumeRoleWithWebIdentity = [ - 9, - n0, - _ARWWI, - 0, - () => AssumeRoleWithWebIdentityRequest, - () => AssumeRoleWithWebIdentityResponse, -]; - -class AssumeRoleCommand extends smithyClient.Command - .classBuilder() - .ep(EndpointParameters.commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSSecurityTokenServiceV20110615", "AssumeRole", {}) - .n("STSClient", "AssumeRoleCommand") - .sc(AssumeRole) - .build() { -} - -class AssumeRoleWithWebIdentityCommand extends smithyClient.Command - .classBuilder() - .ep(EndpointParameters.commonParams) - .m(function (Command, cs, config, o) { - return [middlewareEndpoint.getEndpointPlugin(config, Command.getEndpointParameterInstructions())]; -}) - .s("AWSSecurityTokenServiceV20110615", "AssumeRoleWithWebIdentity", {}) - .n("STSClient", "AssumeRoleWithWebIdentityCommand") - .sc(AssumeRoleWithWebIdentity) - .build() { -} - -const commands = { - AssumeRoleCommand, - AssumeRoleWithWebIdentityCommand, -}; -class STS extends STSClient.STSClient { -} -smithyClient.createAggregatedClient(commands, STS); - -const getAccountIdFromAssumedRoleUser = (assumedRoleUser) => { - if (typeof assumedRoleUser?.Arn === "string") { - const arnComponents = assumedRoleUser.Arn.split(":"); - if (arnComponents.length > 4 && arnComponents[4] !== "") { - return arnComponents[4]; - } - } - return undefined; -}; -const resolveRegion = async (_region, _parentRegion, credentialProviderLogger, loaderConfig = {}) => { - const region = typeof _region === "function" ? await _region() : _region; - const parentRegion = typeof _parentRegion === "function" ? await _parentRegion() : _parentRegion; - const stsDefaultRegion = await regionConfigResolver.stsRegionDefaultResolver(loaderConfig)(); - credentialProviderLogger?.debug?.("@aws-sdk/client-sts::resolveRegion", "accepting first of:", `${region} (credential provider clientConfig)`, `${parentRegion} (contextual client)`, `${stsDefaultRegion} (STS default: AWS_REGION, profile region, or us-east-1)`); - return region ?? parentRegion ?? stsDefaultRegion; -}; -const getDefaultRoleAssumer$1 = (stsOptions, STSClient) => { - let stsClient; - let closureSourceCreds; - return async (sourceCreds, params) => { - closureSourceCreds = sourceCreds; - if (!stsClient) { - const { logger = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId, } = stsOptions; - const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, { - logger, - profile, - }); - const isCompatibleRequestHandler = !isH2(requestHandler); - stsClient = new STSClient({ - ...stsOptions, - userAgentAppId, - profile, - credentialDefaultProvider: () => async () => closureSourceCreds, - region: resolvedRegion, - requestHandler: isCompatibleRequestHandler ? requestHandler : undefined, - logger: logger, - }); - } - const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleCommand(params)); - if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) { - throw new Error(`Invalid response from STS.assumeRole call with role ${params.RoleArn}`); - } - const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser); - const credentials = { - accessKeyId: Credentials.AccessKeyId, - secretAccessKey: Credentials.SecretAccessKey, - sessionToken: Credentials.SessionToken, - expiration: Credentials.Expiration, - ...(Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope }), - ...(accountId && { accountId }), - }; - client.setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE", "i"); - return credentials; - }; -}; -const getDefaultRoleAssumerWithWebIdentity$1 = (stsOptions, STSClient) => { - let stsClient; - return async (params) => { - if (!stsClient) { - const { logger = stsOptions?.parentClientConfig?.logger, profile = stsOptions?.parentClientConfig?.profile, region, requestHandler = stsOptions?.parentClientConfig?.requestHandler, credentialProviderLogger, userAgentAppId = stsOptions?.parentClientConfig?.userAgentAppId, } = stsOptions; - const resolvedRegion = await resolveRegion(region, stsOptions?.parentClientConfig?.region, credentialProviderLogger, { - logger, - profile, - }); - const isCompatibleRequestHandler = !isH2(requestHandler); - stsClient = new STSClient({ - ...stsOptions, - userAgentAppId, - profile, - region: resolvedRegion, - requestHandler: isCompatibleRequestHandler ? requestHandler : undefined, - logger: logger, - }); - } - const { Credentials, AssumedRoleUser } = await stsClient.send(new AssumeRoleWithWebIdentityCommand(params)); - if (!Credentials || !Credentials.AccessKeyId || !Credentials.SecretAccessKey) { - throw new Error(`Invalid response from STS.assumeRoleWithWebIdentity call with role ${params.RoleArn}`); - } - const accountId = getAccountIdFromAssumedRoleUser(AssumedRoleUser); - const credentials = { - accessKeyId: Credentials.AccessKeyId, - secretAccessKey: Credentials.SecretAccessKey, - sessionToken: Credentials.SessionToken, - expiration: Credentials.Expiration, - ...(Credentials.CredentialScope && { credentialScope: Credentials.CredentialScope }), - ...(accountId && { accountId }), - }; - if (accountId) { - client.setCredentialFeature(credentials, "RESOLVED_ACCOUNT_ID", "T"); - } - client.setCredentialFeature(credentials, "CREDENTIALS_STS_ASSUME_ROLE_WEB_ID", "k"); - return credentials; - }; -}; -const isH2 = (requestHandler) => { - return requestHandler?.metadata?.handlerProtocol === "h2"; -}; - -const getCustomizableStsClientCtor = (baseCtor, customizations) => { - if (!customizations) - return baseCtor; - else - return class CustomizableSTSClient extends baseCtor { - constructor(config) { - super(config); - for (const customization of customizations) { - this.middlewareStack.use(customization); - } - } - }; -}; -const getDefaultRoleAssumer = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumer$1(stsOptions, getCustomizableStsClientCtor(STSClient.STSClient, stsPlugins)); -const getDefaultRoleAssumerWithWebIdentity = (stsOptions = {}, stsPlugins) => getDefaultRoleAssumerWithWebIdentity$1(stsOptions, getCustomizableStsClientCtor(STSClient.STSClient, stsPlugins)); -const decorateDefaultCredentialProvider = (provider) => (input) => provider({ - roleAssumer: getDefaultRoleAssumer(input), - roleAssumerWithWebIdentity: getDefaultRoleAssumerWithWebIdentity(input), - ...input, -}); - -Object.defineProperty(exports, "$Command", { - enumerable: true, - get: function () { return smithyClient.Command; } -}); -exports.AssumeRoleCommand = AssumeRoleCommand; -exports.AssumeRoleWithWebIdentityCommand = AssumeRoleWithWebIdentityCommand; -exports.ExpiredTokenException = ExpiredTokenException$1; -exports.IDPCommunicationErrorException = IDPCommunicationErrorException$1; -exports.IDPRejectedClaimException = IDPRejectedClaimException$1; -exports.InvalidIdentityTokenException = InvalidIdentityTokenException$1; -exports.MalformedPolicyDocumentException = MalformedPolicyDocumentException$1; -exports.PackedPolicyTooLargeException = PackedPolicyTooLargeException$1; -exports.RegionDisabledException = RegionDisabledException$1; -exports.STS = STS; -exports.STSServiceException = STSServiceException$1; -exports.decorateDefaultCredentialProvider = decorateDefaultCredentialProvider; -exports.getDefaultRoleAssumer = getDefaultRoleAssumer; -exports.getDefaultRoleAssumerWithWebIdentity = getDefaultRoleAssumerWithWebIdentity; -Object.keys(STSClient).forEach(function (k) { - if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { - enumerable: true, - get: function () { return STSClient[k]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeConfig.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeConfig.js deleted file mode 100644 index d98dd500..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeConfig.js +++ /dev/null @@ -1,68 +0,0 @@ -"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 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 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, - }; - 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, - defaultUserAgentProvider: config?.defaultUserAgentProvider ?? - (0, util_user_agent_node_1.createDefaultUserAgentProvider)({ serviceId: clientSharedValues.serviceId, clientVersion: package_json_1.default.version }), - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4") || - (async (idProps) => await config.credentialDefaultProvider(idProps?.__config || {})()), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - 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.NodeHttpHandler.create(config?.requestHandler ?? defaultConfigProvider), - 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; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeConfig.shared.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeConfig.shared.js deleted file mode 100644 index 5291d67e..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeConfig.shared.js +++ /dev/null @@ -1,47 +0,0 @@ -"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: "2011-06-15", - 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.defaultSTSHttpAuthSchemeProvider, - httpAuthSchemes: config?.httpAuthSchemes ?? [ - { - schemeId: "aws.auth#sigv4", - identityProvider: (ipc) => ipc.getIdentityProvider("aws.auth#sigv4"), - signer: new core_1.AwsSdkSigV4Signer(), - }, - { - schemeId: "smithy.api#noAuth", - identityProvider: (ipc) => ipc.getIdentityProvider("smithy.api#noAuth") || (async () => ({})), - signer: new core_2.NoAuthSigner(), - }, - ], - logger: config?.logger ?? new smithy_client_1.NoOpLogger(), - protocol: config?.protocol ?? - new protocols_1.AwsQueryProtocol({ - defaultNamespace: "com.amazonaws.sts", - xmlNamespace: "https://sts.amazonaws.com/doc/2011-06-15/", - version: "2011-06-15", - }), - serviceId: config?.serviceId ?? "STS", - urlParser: config?.urlParser ?? url_parser_1.parseUrl, - utf8Decoder: config?.utf8Decoder ?? util_utf8_1.fromUtf8, - utf8Encoder: config?.utf8Encoder ?? util_utf8_1.toUtf8, - }; -}; -exports.getRuntimeConfig = getRuntimeConfig; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeExtensions.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeExtensions.js deleted file mode 100644 index a50ebec3..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/dist-cjs/submodules/sts/runtimeExtensions.js +++ /dev/null @@ -1,13 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.resolveRuntimeExtensions = void 0; -const region_config_resolver_1 = require("@aws-sdk/region-config-resolver"); -const protocol_http_1 = require("@smithy/protocol-http"); -const smithy_client_1 = require("@smithy/smithy-client"); -const httpAuthExtensionConfiguration_1 = require("./auth/httpAuthExtensionConfiguration"); -const resolveRuntimeExtensions = (runtimeConfig, extensions) => { - const extensionConfiguration = Object.assign((0, region_config_resolver_1.getAwsRegionExtensionConfiguration)(runtimeConfig), (0, smithy_client_1.getDefaultExtensionConfiguration)(runtimeConfig), (0, protocol_http_1.getHttpHandlerExtensionConfiguration)(runtimeConfig), (0, httpAuthExtensionConfiguration_1.getHttpAuthExtensionConfiguration)(runtimeConfig)); - extensions.forEach((extension) => extension.configure(extensionConfiguration)); - return Object.assign(runtimeConfig, (0, region_config_resolver_1.resolveAwsRegionExtensionConfiguration)(extensionConfiguration), (0, smithy_client_1.resolveDefaultRuntimeConfig)(extensionConfiguration), (0, protocol_http_1.resolveHttpHandlerRuntimeConfig)(extensionConfiguration), (0, httpAuthExtensionConfiguration_1.resolveHttpAuthRuntimeConfig)(extensionConfiguration)); -}; -exports.resolveRuntimeExtensions = resolveRuntimeExtensions; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 52303c3b..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,169 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/smithy-client/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/smithy-client/dist-cjs/index.js deleted file mode 100644 index 9f589873..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/smithy-client/dist-cjs/index.js +++ /dev/null @@ -1,589 +0,0 @@ -'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]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js deleted file mode 100644 index b06a7b87..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js +++ /dev/null @@ -1,16 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/index.js deleted file mode 100644 index c095e288..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/index.js +++ /dev/null @@ -1,19 +0,0 @@ -'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]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/toBase64.js deleted file mode 100644 index 0590ce3f..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/dist-cjs/toBase64.js +++ /dev/null @@ -1,19 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js deleted file mode 100644 index b577c9ca..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js +++ /dev/null @@ -1,20 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js deleted file mode 100644 index 3238bb77..00000000 --- a/claude-code-source/node_modules/@aws-sdk/nested-clients/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || - Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; - -exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js deleted file mode 100644 index 89a2b7f2..00000000 --- a/claude-code-source/node_modules/@aws-sdk/region-config-resolver/dist-cjs/index.js +++ /dev/null @@ -1,49 +0,0 @@ -'use strict'; - -var configResolver = require('@smithy/config-resolver'); -var stsRegionDefaultResolver = require('./regionConfig/stsRegionDefaultResolver'); - -const getAwsRegionExtensionConfiguration = (runtimeConfig) => { - return { - setRegion(region) { - runtimeConfig.region = region; - }, - region() { - return runtimeConfig.region; - }, - }; -}; -const resolveAwsRegionExtensionConfiguration = (awsRegionExtensionConfiguration) => { - return { - region: awsRegionExtensionConfiguration.region(), - }; -}; - -Object.defineProperty(exports, "NODE_REGION_CONFIG_FILE_OPTIONS", { - enumerable: true, - get: function () { return configResolver.NODE_REGION_CONFIG_FILE_OPTIONS; } -}); -Object.defineProperty(exports, "NODE_REGION_CONFIG_OPTIONS", { - enumerable: true, - get: function () { return configResolver.NODE_REGION_CONFIG_OPTIONS; } -}); -Object.defineProperty(exports, "REGION_ENV_NAME", { - enumerable: true, - get: function () { return configResolver.REGION_ENV_NAME; } -}); -Object.defineProperty(exports, "REGION_INI_NAME", { - enumerable: true, - get: function () { return configResolver.REGION_INI_NAME; } -}); -Object.defineProperty(exports, "resolveRegionConfig", { - enumerable: true, - get: function () { return configResolver.resolveRegionConfig; } -}); -exports.getAwsRegionExtensionConfiguration = getAwsRegionExtensionConfiguration; -exports.resolveAwsRegionExtensionConfiguration = resolveAwsRegionExtensionConfiguration; -Object.keys(stsRegionDefaultResolver).forEach(function (k) { - if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { - enumerable: true, - get: function () { return stsRegionDefaultResolver[k]; } - }); -}); diff --git a/claude-code-source/node_modules/@aws-sdk/region-config-resolver/dist-cjs/regionConfig/stsRegionDefaultResolver.js b/claude-code-source/node_modules/@aws-sdk/region-config-resolver/dist-cjs/regionConfig/stsRegionDefaultResolver.js deleted file mode 100644 index 30d06fbd..00000000 --- a/claude-code-source/node_modules/@aws-sdk/region-config-resolver/dist-cjs/regionConfig/stsRegionDefaultResolver.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.warning = void 0; -exports.stsRegionDefaultResolver = stsRegionDefaultResolver; -const config_resolver_1 = require("@smithy/config-resolver"); -const node_config_provider_1 = require("@smithy/node-config-provider"); -function stsRegionDefaultResolver(loaderConfig = {}) { - return (0, node_config_provider_1.loadConfig)({ - ...config_resolver_1.NODE_REGION_CONFIG_OPTIONS, - async default() { - if (!exports.warning.silence) { - console.warn("@aws-sdk - WARN - default STS region of us-east-1 used. See @aws-sdk/credential-providers README and set a region explicitly."); - } - return "us-east-1"; - }, - }, { ...config_resolver_1.NODE_REGION_CONFIG_FILE_OPTIONS, ...loaderConfig }); -} -exports.warning = { - silence: false, -}; diff --git a/claude-code-source/node_modules/@aws-sdk/token-providers/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/token-providers/dist-cjs/index.js deleted file mode 100644 index eff14c07..00000000 --- a/claude-code-source/node_modules/@aws-sdk/token-providers/dist-cjs/index.js +++ /dev/null @@ -1,164 +0,0 @@ -'use strict'; - -var client = require('@aws-sdk/core/client'); -var httpAuthSchemes = require('@aws-sdk/core/httpAuthSchemes'); -var propertyProvider = require('@smithy/property-provider'); -var sharedIniFileLoader = require('@smithy/shared-ini-file-loader'); -var fs = require('fs'); - -const fromEnvSigningName = ({ logger, signingName } = {}) => async () => { - logger?.debug?.("@aws-sdk/token-providers - fromEnvSigningName"); - if (!signingName) { - throw new propertyProvider.TokenProviderError("Please pass 'signingName' to compute environment variable key", { logger }); - } - const bearerTokenKey = httpAuthSchemes.getBearerTokenEnvKey(signingName); - if (!(bearerTokenKey in process.env)) { - throw new propertyProvider.TokenProviderError(`Token not present in '${bearerTokenKey}' environment variable`, { logger }); - } - const token = { token: process.env[bearerTokenKey] }; - client.setTokenFeature(token, "BEARER_SERVICE_ENV_VARS", "3"); - return token; -}; - -const EXPIRE_WINDOW_MS = 5 * 60 * 1000; -const REFRESH_MESSAGE = `To refresh this SSO session run 'aws sso login' with the corresponding profile.`; - -const getSsoOidcClient = async (ssoRegion, init = {}) => { - const { SSOOIDCClient } = await import('@aws-sdk/nested-clients/sso-oidc'); - const coalesce = (prop) => init.clientConfig?.[prop] ?? init.parentClientConfig?.[prop]; - const ssoOidcClient = new SSOOIDCClient(Object.assign({}, init.clientConfig ?? {}, { - region: ssoRegion ?? init.clientConfig?.region, - logger: coalesce("logger"), - userAgentAppId: coalesce("userAgentAppId"), - })); - return ssoOidcClient; -}; - -const getNewSsoOidcToken = async (ssoToken, ssoRegion, init = {}) => { - const { CreateTokenCommand } = await import('@aws-sdk/nested-clients/sso-oidc'); - const ssoOidcClient = await getSsoOidcClient(ssoRegion, init); - return ssoOidcClient.send(new CreateTokenCommand({ - clientId: ssoToken.clientId, - clientSecret: ssoToken.clientSecret, - refreshToken: ssoToken.refreshToken, - grantType: "refresh_token", - })); -}; - -const validateTokenExpiry = (token) => { - if (token.expiration && token.expiration.getTime() < Date.now()) { - throw new propertyProvider.TokenProviderError(`Token is expired. ${REFRESH_MESSAGE}`, false); - } -}; - -const validateTokenKey = (key, value, forRefresh = false) => { - if (typeof value === "undefined") { - throw new propertyProvider.TokenProviderError(`Value not present for '${key}' in SSO Token${forRefresh ? ". Cannot refresh" : ""}. ${REFRESH_MESSAGE}`, false); - } -}; - -const { writeFile } = fs.promises; -const writeSSOTokenToFile = (id, ssoToken) => { - const tokenFilepath = sharedIniFileLoader.getSSOTokenFilepath(id); - const tokenString = JSON.stringify(ssoToken, null, 2); - return writeFile(tokenFilepath, tokenString); -}; - -const lastRefreshAttemptTime = new Date(0); -const fromSso = (_init = {}) => async ({ callerClientConfig } = {}) => { - const init = { - ..._init, - parentClientConfig: { - ...callerClientConfig, - ..._init.parentClientConfig, - }, - }; - init.logger?.debug("@aws-sdk/token-providers - fromSso"); - const profiles = await sharedIniFileLoader.parseKnownFiles(init); - const profileName = sharedIniFileLoader.getProfileName({ - profile: init.profile ?? callerClientConfig?.profile, - }); - const profile = profiles[profileName]; - if (!profile) { - throw new propertyProvider.TokenProviderError(`Profile '${profileName}' could not be found in shared credentials file.`, false); - } - else if (!profile["sso_session"]) { - throw new propertyProvider.TokenProviderError(`Profile '${profileName}' is missing required property 'sso_session'.`); - } - const ssoSessionName = profile["sso_session"]; - const ssoSessions = await sharedIniFileLoader.loadSsoSessionData(init); - const ssoSession = ssoSessions[ssoSessionName]; - if (!ssoSession) { - throw new propertyProvider.TokenProviderError(`Sso session '${ssoSessionName}' could not be found in shared credentials file.`, false); - } - for (const ssoSessionRequiredKey of ["sso_start_url", "sso_region"]) { - if (!ssoSession[ssoSessionRequiredKey]) { - throw new propertyProvider.TokenProviderError(`Sso session '${ssoSessionName}' is missing required property '${ssoSessionRequiredKey}'.`, false); - } - } - ssoSession["sso_start_url"]; - const ssoRegion = ssoSession["sso_region"]; - let ssoToken; - try { - ssoToken = await sharedIniFileLoader.getSSOTokenFromFile(ssoSessionName); - } - catch (e) { - throw new propertyProvider.TokenProviderError(`The SSO session token associated with profile=${profileName} was not found or is invalid. ${REFRESH_MESSAGE}`, false); - } - validateTokenKey("accessToken", ssoToken.accessToken); - validateTokenKey("expiresAt", ssoToken.expiresAt); - const { accessToken, expiresAt } = ssoToken; - const existingToken = { token: accessToken, expiration: new Date(expiresAt) }; - if (existingToken.expiration.getTime() - Date.now() > EXPIRE_WINDOW_MS) { - return existingToken; - } - if (Date.now() - lastRefreshAttemptTime.getTime() < 30 * 1000) { - validateTokenExpiry(existingToken); - return existingToken; - } - validateTokenKey("clientId", ssoToken.clientId, true); - validateTokenKey("clientSecret", ssoToken.clientSecret, true); - validateTokenKey("refreshToken", ssoToken.refreshToken, true); - try { - lastRefreshAttemptTime.setTime(Date.now()); - const newSsoOidcToken = await getNewSsoOidcToken(ssoToken, ssoRegion, init); - validateTokenKey("accessToken", newSsoOidcToken.accessToken); - validateTokenKey("expiresIn", newSsoOidcToken.expiresIn); - const newTokenExpiration = new Date(Date.now() + newSsoOidcToken.expiresIn * 1000); - try { - await writeSSOTokenToFile(ssoSessionName, { - ...ssoToken, - accessToken: newSsoOidcToken.accessToken, - expiresAt: newTokenExpiration.toISOString(), - refreshToken: newSsoOidcToken.refreshToken, - }); - } - catch (error) { - } - return { - token: newSsoOidcToken.accessToken, - expiration: newTokenExpiration, - }; - } - catch (error) { - validateTokenExpiry(existingToken); - return existingToken; - } -}; - -const fromStatic = ({ token, logger }) => async () => { - logger?.debug("@aws-sdk/token-providers - fromStatic"); - if (!token || !token.token) { - throw new propertyProvider.TokenProviderError(`Please pass a valid token to fromStatic`, false); - } - return token; -}; - -const nodeProvider = (init = {}) => propertyProvider.memoize(propertyProvider.chain(fromSso(init), async () => { - throw new propertyProvider.TokenProviderError("Could not load token from any providers", false); -}), (token) => token.expiration !== undefined && token.expiration.getTime() - Date.now() < 300000, (token) => token.expiration !== undefined); - -exports.fromEnvSigningName = fromEnvSigningName; -exports.fromSso = fromSso; -exports.fromStatic = fromStatic; -exports.nodeProvider = nodeProvider; diff --git a/claude-code-source/node_modules/@aws-sdk/util-endpoints/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/util-endpoints/dist-cjs/index.js deleted file mode 100644 index db973005..00000000 --- a/claude-code-source/node_modules/@aws-sdk/util-endpoints/dist-cjs/index.js +++ /dev/null @@ -1,415 +0,0 @@ -'use strict'; - -var utilEndpoints = require('@smithy/util-endpoints'); -var urlParser = require('@smithy/url-parser'); - -const isVirtualHostableS3Bucket = (value, allowSubDomains = false) => { - if (allowSubDomains) { - for (const label of value.split(".")) { - if (!isVirtualHostableS3Bucket(label)) { - return false; - } - } - return true; - } - if (!utilEndpoints.isValidHostLabel(value)) { - return false; - } - if (value.length < 3 || value.length > 63) { - return false; - } - if (value !== value.toLowerCase()) { - return false; - } - if (utilEndpoints.isIpAddress(value)) { - return false; - } - return true; -}; - -const ARN_DELIMITER = ":"; -const RESOURCE_DELIMITER = "/"; -const parseArn = (value) => { - const segments = value.split(ARN_DELIMITER); - if (segments.length < 6) - return null; - const [arn, partition, service, region, accountId, ...resourcePath] = segments; - if (arn !== "arn" || partition === "" || service === "" || resourcePath.join(ARN_DELIMITER) === "") - return null; - const resourceId = resourcePath.map((resource) => resource.split(RESOURCE_DELIMITER)).flat(); - return { - partition, - service, - region, - accountId, - resourceId, - }; -}; - -var partitions = [ - { - id: "aws", - outputs: { - dnsSuffix: "amazonaws.com", - dualStackDnsSuffix: "api.aws", - implicitGlobalRegion: "us-east-1", - name: "aws", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$", - regions: { - "af-south-1": { - description: "Africa (Cape Town)" - }, - "ap-east-1": { - description: "Asia Pacific (Hong Kong)" - }, - "ap-east-2": { - description: "Asia Pacific (Taipei)" - }, - "ap-northeast-1": { - description: "Asia Pacific (Tokyo)" - }, - "ap-northeast-2": { - description: "Asia Pacific (Seoul)" - }, - "ap-northeast-3": { - description: "Asia Pacific (Osaka)" - }, - "ap-south-1": { - description: "Asia Pacific (Mumbai)" - }, - "ap-south-2": { - description: "Asia Pacific (Hyderabad)" - }, - "ap-southeast-1": { - description: "Asia Pacific (Singapore)" - }, - "ap-southeast-2": { - description: "Asia Pacific (Sydney)" - }, - "ap-southeast-3": { - description: "Asia Pacific (Jakarta)" - }, - "ap-southeast-4": { - description: "Asia Pacific (Melbourne)" - }, - "ap-southeast-5": { - description: "Asia Pacific (Malaysia)" - }, - "ap-southeast-6": { - description: "Asia Pacific (New Zealand)" - }, - "ap-southeast-7": { - description: "Asia Pacific (Thailand)" - }, - "aws-global": { - description: "aws global region" - }, - "ca-central-1": { - description: "Canada (Central)" - }, - "ca-west-1": { - description: "Canada West (Calgary)" - }, - "eu-central-1": { - description: "Europe (Frankfurt)" - }, - "eu-central-2": { - description: "Europe (Zurich)" - }, - "eu-north-1": { - description: "Europe (Stockholm)" - }, - "eu-south-1": { - description: "Europe (Milan)" - }, - "eu-south-2": { - description: "Europe (Spain)" - }, - "eu-west-1": { - description: "Europe (Ireland)" - }, - "eu-west-2": { - description: "Europe (London)" - }, - "eu-west-3": { - description: "Europe (Paris)" - }, - "il-central-1": { - description: "Israel (Tel Aviv)" - }, - "me-central-1": { - description: "Middle East (UAE)" - }, - "me-south-1": { - description: "Middle East (Bahrain)" - }, - "mx-central-1": { - description: "Mexico (Central)" - }, - "sa-east-1": { - description: "South America (Sao Paulo)" - }, - "us-east-1": { - description: "US East (N. Virginia)" - }, - "us-east-2": { - description: "US East (Ohio)" - }, - "us-west-1": { - description: "US West (N. California)" - }, - "us-west-2": { - description: "US West (Oregon)" - } - } - }, - { - id: "aws-cn", - outputs: { - dnsSuffix: "amazonaws.com.cn", - dualStackDnsSuffix: "api.amazonwebservices.com.cn", - implicitGlobalRegion: "cn-northwest-1", - name: "aws-cn", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^cn\\-\\w+\\-\\d+$", - regions: { - "aws-cn-global": { - description: "aws-cn global region" - }, - "cn-north-1": { - description: "China (Beijing)" - }, - "cn-northwest-1": { - description: "China (Ningxia)" - } - } - }, - { - id: "aws-eusc", - outputs: { - dnsSuffix: "amazonaws.eu", - dualStackDnsSuffix: "api.amazonwebservices.eu", - implicitGlobalRegion: "eusc-de-east-1", - name: "aws-eusc", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^eusc\\-(de)\\-\\w+\\-\\d+$", - regions: { - "eusc-de-east-1": { - description: "EU (Germany)" - } - } - }, - { - id: "aws-iso", - outputs: { - dnsSuffix: "c2s.ic.gov", - dualStackDnsSuffix: "api.aws.ic.gov", - implicitGlobalRegion: "us-iso-east-1", - name: "aws-iso", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^us\\-iso\\-\\w+\\-\\d+$", - regions: { - "aws-iso-global": { - description: "aws-iso global region" - }, - "us-iso-east-1": { - description: "US ISO East" - }, - "us-iso-west-1": { - description: "US ISO WEST" - } - } - }, - { - id: "aws-iso-b", - outputs: { - dnsSuffix: "sc2s.sgov.gov", - dualStackDnsSuffix: "api.aws.scloud", - implicitGlobalRegion: "us-isob-east-1", - name: "aws-iso-b", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^us\\-isob\\-\\w+\\-\\d+$", - regions: { - "aws-iso-b-global": { - description: "aws-iso-b global region" - }, - "us-isob-east-1": { - description: "US ISOB East (Ohio)" - }, - "us-isob-west-1": { - description: "US ISOB West" - } - } - }, - { - id: "aws-iso-e", - outputs: { - dnsSuffix: "cloud.adc-e.uk", - dualStackDnsSuffix: "api.cloud-aws.adc-e.uk", - implicitGlobalRegion: "eu-isoe-west-1", - name: "aws-iso-e", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^eu\\-isoe\\-\\w+\\-\\d+$", - regions: { - "aws-iso-e-global": { - description: "aws-iso-e global region" - }, - "eu-isoe-west-1": { - description: "EU ISOE West" - } - } - }, - { - id: "aws-iso-f", - outputs: { - dnsSuffix: "csp.hci.ic.gov", - dualStackDnsSuffix: "api.aws.hci.ic.gov", - implicitGlobalRegion: "us-isof-south-1", - name: "aws-iso-f", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^us\\-isof\\-\\w+\\-\\d+$", - regions: { - "aws-iso-f-global": { - description: "aws-iso-f global region" - }, - "us-isof-east-1": { - description: "US ISOF EAST" - }, - "us-isof-south-1": { - description: "US ISOF SOUTH" - } - } - }, - { - id: "aws-us-gov", - outputs: { - dnsSuffix: "amazonaws.com", - dualStackDnsSuffix: "api.aws", - implicitGlobalRegion: "us-gov-west-1", - name: "aws-us-gov", - supportsDualStack: true, - supportsFIPS: true - }, - regionRegex: "^us\\-gov\\-\\w+\\-\\d+$", - regions: { - "aws-us-gov-global": { - description: "aws-us-gov global region" - }, - "us-gov-east-1": { - description: "AWS GovCloud (US-East)" - }, - "us-gov-west-1": { - description: "AWS GovCloud (US-West)" - } - } - } -]; -var version = "1.1"; -var partitionsInfo = { - partitions: partitions, - version: version -}; - -let selectedPartitionsInfo = partitionsInfo; -let selectedUserAgentPrefix = ""; -const partition = (value) => { - const { partitions } = selectedPartitionsInfo; - for (const partition of partitions) { - const { regions, outputs } = partition; - for (const [region, regionData] of Object.entries(regions)) { - if (region === value) { - return { - ...outputs, - ...regionData, - }; - } - } - } - for (const partition of partitions) { - const { regionRegex, outputs } = partition; - if (new RegExp(regionRegex).test(value)) { - return { - ...outputs, - }; - } - } - const DEFAULT_PARTITION = partitions.find((partition) => partition.id === "aws"); - if (!DEFAULT_PARTITION) { - throw new Error("Provided region was not found in the partition array or regex," + - " and default partition with id 'aws' doesn't exist."); - } - return { - ...DEFAULT_PARTITION.outputs, - }; -}; -const setPartitionInfo = (partitionsInfo, userAgentPrefix = "") => { - selectedPartitionsInfo = partitionsInfo; - selectedUserAgentPrefix = userAgentPrefix; -}; -const useDefaultPartitionInfo = () => { - setPartitionInfo(partitionsInfo, ""); -}; -const getUserAgentPrefix = () => selectedUserAgentPrefix; - -const awsEndpointFunctions = { - isVirtualHostableS3Bucket: isVirtualHostableS3Bucket, - parseArn: parseArn, - partition: partition, -}; -utilEndpoints.customEndpointFunctions.aws = awsEndpointFunctions; - -const resolveDefaultAwsRegionalEndpointsConfig = (input) => { - if (typeof input.endpointProvider !== "function") { - throw new Error("@aws-sdk/util-endpoint - endpointProvider and endpoint missing in config for this client."); - } - const { endpoint } = input; - if (endpoint === undefined) { - input.endpoint = async () => { - return toEndpointV1(input.endpointProvider({ - Region: typeof input.region === "function" ? await input.region() : input.region, - UseDualStack: typeof input.useDualstackEndpoint === "function" - ? await input.useDualstackEndpoint() - : input.useDualstackEndpoint, - UseFIPS: typeof input.useFipsEndpoint === "function" ? await input.useFipsEndpoint() : input.useFipsEndpoint, - Endpoint: undefined, - }, { logger: input.logger })); - }; - } - return input; -}; -const toEndpointV1 = (endpoint) => urlParser.parseUrl(endpoint.url); - -Object.defineProperty(exports, "EndpointError", { - enumerable: true, - get: function () { return utilEndpoints.EndpointError; } -}); -Object.defineProperty(exports, "isIpAddress", { - enumerable: true, - get: function () { return utilEndpoints.isIpAddress; } -}); -Object.defineProperty(exports, "resolveEndpoint", { - enumerable: true, - get: function () { return utilEndpoints.resolveEndpoint; } -}); -exports.awsEndpointFunctions = awsEndpointFunctions; -exports.getUserAgentPrefix = getUserAgentPrefix; -exports.partition = partition; -exports.resolveDefaultAwsRegionalEndpointsConfig = resolveDefaultAwsRegionalEndpointsConfig; -exports.setPartitionInfo = setPartitionInfo; -exports.toEndpointV1 = toEndpointV1; -exports.useDefaultPartitionInfo = useDefaultPartitionInfo; diff --git a/claude-code-source/node_modules/@aws-sdk/util-format-url/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/util-format-url/dist-cjs/index.js deleted file mode 100644 index de16777f..00000000 --- a/claude-code-source/node_modules/@aws-sdk/util-format-url/dist-cjs/index.js +++ /dev/null @@ -1,34 +0,0 @@ -'use strict'; - -var querystringBuilder = require('@smithy/querystring-builder'); - -function formatUrl(request) { - const { port, query } = request; - let { protocol, path, hostname } = request; - if (protocol && protocol.slice(-1) !== ":") { - protocol += ":"; - } - if (port) { - hostname += `:${port}`; - } - if (path && path.charAt(0) !== "/") { - path = `/${path}`; - } - let queryString = query ? querystringBuilder.buildQueryString(query) : ""; - if (queryString && queryString[0] !== "?") { - queryString = `?${queryString}`; - } - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - let fragment = ""; - if (request.fragment) { - fragment = `#${request.fragment}`; - } - return `${protocol}//${auth}${hostname}${path}${queryString}${fragment}`; -} - -exports.formatUrl = formatUrl; diff --git a/claude-code-source/node_modules/@aws-sdk/util-format-url/node_modules/@smithy/querystring-builder/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/util-format-url/node_modules/@smithy/querystring-builder/dist-cjs/index.js deleted file mode 100644 index f245489f..00000000 --- a/claude-code-source/node_modules/@aws-sdk/util-format-url/node_modules/@smithy/querystring-builder/dist-cjs/index.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -var utilUriEscape = require('@smithy/util-uri-escape'); - -function buildQueryString(query) { - const parts = []; - for (let key of Object.keys(query).sort()) { - const value = query[key]; - key = utilUriEscape.escapeUri(key); - if (Array.isArray(value)) { - for (let i = 0, iLen = value.length; i < iLen; i++) { - parts.push(`${key}=${utilUriEscape.escapeUri(value[i])}`); - } - } - else { - let qsEntry = key; - if (value || typeof value === "string") { - qsEntry += `=${utilUriEscape.escapeUri(value)}`; - } - parts.push(qsEntry); - } - } - return parts.join("&"); -} - -exports.buildQueryString = buildQueryString; diff --git a/claude-code-source/node_modules/@aws-sdk/util-format-url/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/util-format-url/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js deleted file mode 100644 index 11f942c3..00000000 --- a/claude-code-source/node_modules/@aws-sdk/util-format-url/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -const escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode); -const hexEncode = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`; - -const escapeUriPath = (uri) => uri.split("/").map(escapeUri).join("/"); - -exports.escapeUri = escapeUri; -exports.escapeUriPath = escapeUriPath; diff --git a/claude-code-source/node_modules/@aws-sdk/util-user-agent-node/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/util-user-agent-node/dist-cjs/index.js deleted file mode 100644 index c7dc6fa3..00000000 --- a/claude-code-source/node_modules/@aws-sdk/util-user-agent-node/dist-cjs/index.js +++ /dev/null @@ -1,58 +0,0 @@ -'use strict'; - -var os = require('os'); -var process = require('process'); -var middlewareUserAgent = require('@aws-sdk/middleware-user-agent'); - -const crtAvailability = { - isCrtAvailable: false, -}; - -const isCrtAvailable = () => { - if (crtAvailability.isCrtAvailable) { - return ["md/crt-avail"]; - } - return null; -}; - -const createDefaultUserAgentProvider = ({ serviceId, clientVersion }) => { - return async (config) => { - const sections = [ - ["aws-sdk-js", clientVersion], - ["ua", "2.1"], - [`os/${os.platform()}`, os.release()], - ["lang/js"], - ["md/nodejs", `${process.versions.node}`], - ]; - const crtAvailable = isCrtAvailable(); - if (crtAvailable) { - sections.push(crtAvailable); - } - if (serviceId) { - sections.push([`api/${serviceId}`, clientVersion]); - } - if (process.env.AWS_EXECUTION_ENV) { - sections.push([`exec-env/${process.env.AWS_EXECUTION_ENV}`]); - } - const appId = await config?.userAgentAppId?.(); - const resolvedUserAgent = appId ? [...sections, [`app/${appId}`]] : [...sections]; - return resolvedUserAgent; - }; -}; -const defaultUserAgent = createDefaultUserAgentProvider; - -const UA_APP_ID_ENV_NAME = "AWS_SDK_UA_APP_ID"; -const UA_APP_ID_INI_NAME = "sdk_ua_app_id"; -const UA_APP_ID_INI_NAME_DEPRECATED = "sdk-ua-app-id"; -const NODE_APP_ID_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => env[UA_APP_ID_ENV_NAME], - configFileSelector: (profile) => profile[UA_APP_ID_INI_NAME] ?? profile[UA_APP_ID_INI_NAME_DEPRECATED], - default: middlewareUserAgent.DEFAULT_UA_APP_ID, -}; - -exports.NODE_APP_ID_CONFIG_OPTIONS = NODE_APP_ID_CONFIG_OPTIONS; -exports.UA_APP_ID_ENV_NAME = UA_APP_ID_ENV_NAME; -exports.UA_APP_ID_INI_NAME = UA_APP_ID_INI_NAME; -exports.createDefaultUserAgentProvider = createDefaultUserAgentProvider; -exports.crtAvailability = crtAvailability; -exports.defaultUserAgent = defaultUserAgent; diff --git a/claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/index.js deleted file mode 100644 index e5960876..00000000 --- a/claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/index.js +++ /dev/null @@ -1,9 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.toUtf8 = exports.fromUtf8 = void 0; -const pureJs_1 = require("./pureJs"); -const whatwgEncodingApi_1 = require("./whatwgEncodingApi"); -const fromUtf8 = (input) => typeof TextEncoder === "function" ? (0, whatwgEncodingApi_1.fromUtf8)(input) : (0, pureJs_1.fromUtf8)(input); -exports.fromUtf8 = fromUtf8; -const toUtf8 = (input) => typeof TextDecoder === "function" ? (0, whatwgEncodingApi_1.toUtf8)(input) : (0, pureJs_1.toUtf8)(input); -exports.toUtf8 = toUtf8; diff --git a/claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/pureJs.js b/claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/pureJs.js deleted file mode 100644 index 0361b761..00000000 --- a/claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/pureJs.js +++ /dev/null @@ -1,47 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.toUtf8 = exports.fromUtf8 = void 0; -const fromUtf8 = (input) => { - const bytes = []; - for (let i = 0, len = input.length; i < len; i++) { - const value = input.charCodeAt(i); - if (value < 0x80) { - bytes.push(value); - } - else if (value < 0x800) { - bytes.push((value >> 6) | 0b11000000, (value & 0b111111) | 0b10000000); - } - else if (i + 1 < input.length && (value & 0xfc00) === 0xd800 && (input.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { - const surrogatePair = 0x10000 + ((value & 0b1111111111) << 10) + (input.charCodeAt(++i) & 0b1111111111); - bytes.push((surrogatePair >> 18) | 0b11110000, ((surrogatePair >> 12) & 0b111111) | 0b10000000, ((surrogatePair >> 6) & 0b111111) | 0b10000000, (surrogatePair & 0b111111) | 0b10000000); - } - else { - bytes.push((value >> 12) | 0b11100000, ((value >> 6) & 0b111111) | 0b10000000, (value & 0b111111) | 0b10000000); - } - } - return Uint8Array.from(bytes); -}; -exports.fromUtf8 = fromUtf8; -const toUtf8 = (input) => { - let decoded = ""; - for (let i = 0, len = input.length; i < len; i++) { - const byte = input[i]; - if (byte < 0x80) { - decoded += String.fromCharCode(byte); - } - else if (0b11000000 <= byte && byte < 0b11100000) { - const nextByte = input[++i]; - decoded += String.fromCharCode(((byte & 0b11111) << 6) | (nextByte & 0b111111)); - } - else if (0b11110000 <= byte && byte < 0b101101101) { - const surrogatePair = [byte, input[++i], input[++i], input[++i]]; - const encoded = "%" + surrogatePair.map((byteValue) => byteValue.toString(16)).join("%"); - decoded += decodeURIComponent(encoded); - } - else { - decoded += String.fromCharCode(((byte & 0b1111) << 12) | ((input[++i] & 0b111111) << 6) | (input[++i] & 0b111111)); - } - } - return decoded; -}; -exports.toUtf8 = toUtf8; diff --git a/claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/whatwgEncodingApi.js b/claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/whatwgEncodingApi.js deleted file mode 100644 index b17f4906..00000000 --- a/claude-code-source/node_modules/@aws-sdk/util-utf8-browser/dist-cjs/whatwgEncodingApi.js +++ /dev/null @@ -1,11 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.toUtf8 = exports.fromUtf8 = void 0; -function fromUtf8(input) { - return new TextEncoder().encode(input); -} -exports.fromUtf8 = fromUtf8; -function toUtf8(input) { - return new TextDecoder("utf-8").decode(input); -} -exports.toUtf8 = toUtf8; diff --git a/claude-code-source/node_modules/@aws-sdk/xml-builder/dist-cjs/index.js b/claude-code-source/node_modules/@aws-sdk/xml-builder/dist-cjs/index.js deleted file mode 100644 index c4f4bad4..00000000 --- a/claude-code-source/node_modules/@aws-sdk/xml-builder/dist-cjs/index.js +++ /dev/null @@ -1,124 +0,0 @@ -'use strict'; - -var xmlParser = require('./xml-parser'); - -function escapeAttribute(value) { - return value.replace(/&/g, "&").replace(//g, ">").replace(/"/g, """); -} - -function escapeElement(value) { - return value - .replace(/&/g, "&") - .replace(/"/g, """) - .replace(/'/g, "'") - .replace(//g, ">") - .replace(/\r/g, " ") - .replace(/\n/g, " ") - .replace(/\u0085/g, "…") - .replace(/\u2028/, "
"); -} - -class XmlText { - value; - constructor(value) { - this.value = value; - } - toString() { - return escapeElement("" + this.value); - } -} - -class XmlNode { - name; - children; - attributes = {}; - static of(name, childText, withName) { - const node = new XmlNode(name); - if (childText !== undefined) { - node.addChildNode(new XmlText(childText)); - } - if (withName !== undefined) { - node.withName(withName); - } - return node; - } - constructor(name, children = []) { - this.name = name; - this.children = children; - } - withName(name) { - this.name = name; - return this; - } - addAttribute(name, value) { - this.attributes[name] = value; - return this; - } - addChildNode(child) { - this.children.push(child); - return this; - } - removeAttribute(name) { - delete this.attributes[name]; - return this; - } - n(name) { - this.name = name; - return this; - } - c(child) { - this.children.push(child); - return this; - } - a(name, value) { - if (value != null) { - this.attributes[name] = value; - } - return this; - } - cc(input, field, withName = field) { - if (input[field] != null) { - const node = XmlNode.of(field, input[field]).withName(withName); - this.c(node); - } - } - l(input, listName, memberName, valueProvider) { - if (input[listName] != null) { - const nodes = valueProvider(); - nodes.map((node) => { - node.withName(memberName); - this.c(node); - }); - } - } - lc(input, listName, memberName, valueProvider) { - if (input[listName] != null) { - const nodes = valueProvider(); - const containerNode = new XmlNode(memberName); - nodes.map((node) => { - containerNode.c(node); - }); - this.c(containerNode); - } - } - toString() { - const hasChildren = Boolean(this.children.length); - let xmlText = `<${this.name}`; - const attributes = this.attributes; - for (const attributeName of Object.keys(attributes)) { - const attribute = attributes[attributeName]; - if (attribute != null) { - xmlText += ` ${attributeName}="${escapeAttribute("" + attribute)}"`; - } - } - return (xmlText += !hasChildren ? "/>" : `>${this.children.map((c) => c.toString()).join("")}`); - } -} - -Object.defineProperty(exports, "parseXML", { - enumerable: true, - get: function () { return xmlParser.parseXML; } -}); -exports.XmlNode = XmlNode; -exports.XmlText = XmlText; diff --git a/claude-code-source/node_modules/@aws-sdk/xml-builder/dist-cjs/xml-parser.js b/claude-code-source/node_modules/@aws-sdk/xml-builder/dist-cjs/xml-parser.js deleted file mode 100644 index e6866350..00000000 --- a/claude-code-source/node_modules/@aws-sdk/xml-builder/dist-cjs/xml-parser.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.parseXML = parseXML; -const fast_xml_parser_1 = require("fast-xml-parser"); -const parser = new fast_xml_parser_1.XMLParser({ - attributeNamePrefix: "", - htmlEntities: true, - ignoreAttributes: false, - ignoreDeclaration: true, - parseTagValue: false, - trimValues: false, - tagValueProcessor: (_, val) => (val.trim() === "" && val.includes("\n") ? "" : undefined), -}); -parser.addEntity("#xD", "\r"); -parser.addEntity("#10", "\n"); -function parseXML(xmlString) { - return parser.parse(xmlString, true); -} diff --git a/claude-code-source/node_modules/@aws/lambda-invoke-store/dist-cjs/invoke-store.js b/claude-code-source/node_modules/@aws/lambda-invoke-store/dist-cjs/invoke-store.js deleted file mode 100644 index fa336606..00000000 --- a/claude-code-source/node_modules/@aws/lambda-invoke-store/dist-cjs/invoke-store.js +++ /dev/null @@ -1,124 +0,0 @@ -'use strict'; - -const PROTECTED_KEYS = { - REQUEST_ID: Symbol.for("_AWS_LAMBDA_REQUEST_ID"), - X_RAY_TRACE_ID: Symbol.for("_AWS_LAMBDA_X_RAY_TRACE_ID"), - TENANT_ID: Symbol.for("_AWS_LAMBDA_TENANT_ID"), -}; -const NO_GLOBAL_AWS_LAMBDA = ["true", "1"].includes(process.env?.AWS_LAMBDA_NODEJS_NO_GLOBAL_AWSLAMBDA ?? ""); -if (!NO_GLOBAL_AWS_LAMBDA) { - globalThis.awslambda = globalThis.awslambda || {}; -} -class InvokeStoreBase { - static PROTECTED_KEYS = PROTECTED_KEYS; - isProtectedKey(key) { - return Object.values(PROTECTED_KEYS).includes(key); - } - getRequestId() { - return this.get(PROTECTED_KEYS.REQUEST_ID) ?? "-"; - } - getXRayTraceId() { - return this.get(PROTECTED_KEYS.X_RAY_TRACE_ID); - } - getTenantId() { - return this.get(PROTECTED_KEYS.TENANT_ID); - } -} -class InvokeStoreSingle extends InvokeStoreBase { - currentContext; - getContext() { - return this.currentContext; - } - hasContext() { - return this.currentContext !== undefined; - } - get(key) { - return this.currentContext?.[key]; - } - set(key, value) { - if (this.isProtectedKey(key)) { - throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`); - } - this.currentContext = this.currentContext || {}; - this.currentContext[key] = value; - } - run(context, fn) { - this.currentContext = context; - try { - return fn(); - } - finally { - this.currentContext = undefined; - } - } -} -class InvokeStoreMulti extends InvokeStoreBase { - als; - static async create() { - const instance = new InvokeStoreMulti(); - const asyncHooks = await import('node:async_hooks'); - instance.als = new asyncHooks.AsyncLocalStorage(); - return instance; - } - getContext() { - return this.als.getStore(); - } - hasContext() { - return this.als.getStore() !== undefined; - } - get(key) { - return this.als.getStore()?.[key]; - } - set(key, value) { - if (this.isProtectedKey(key)) { - throw new Error(`Cannot modify protected Lambda context field: ${String(key)}`); - } - const store = this.als.getStore(); - if (!store) { - throw new Error("No context available"); - } - store[key] = value; - } - run(context, fn) { - return this.als.run(context, fn); - } -} -exports.InvokeStore = void 0; -(function (InvokeStore) { - let instance = null; - async function getInstanceAsync() { - if (!instance) { - instance = (async () => { - const isMulti = "AWS_LAMBDA_MAX_CONCURRENCY" in process.env; - const newInstance = isMulti - ? await InvokeStoreMulti.create() - : new InvokeStoreSingle(); - if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda?.InvokeStore) { - return globalThis.awslambda.InvokeStore; - } - else if (!NO_GLOBAL_AWS_LAMBDA && globalThis.awslambda) { - globalThis.awslambda.InvokeStore = newInstance; - return newInstance; - } - else { - return newInstance; - } - })(); - } - return instance; - } - InvokeStore.getInstanceAsync = getInstanceAsync; - InvokeStore._testing = process.env.AWS_LAMBDA_BENCHMARK_MODE === "1" - ? { - reset: () => { - instance = null; - if (globalThis.awslambda?.InvokeStore) { - delete globalThis.awslambda.InvokeStore; - } - globalThis.awslambda = {}; - }, - } - : undefined; -})(exports.InvokeStore || (exports.InvokeStore = {})); - -exports.InvokeStoreBase = InvokeStoreBase; diff --git a/claude-code-source/node_modules/@azure/abort-controller/dist/esm/AbortError.js b/claude-code-source/node_modules/@azure/abort-controller/dist/esm/AbortError.js deleted file mode 100644 index 3ae9745c..00000000 --- a/claude-code-source/node_modules/@azure/abort-controller/dist/esm/AbortError.js +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -/** - * This error is thrown when an asynchronous operation has been aborted. - * Check for this error by testing the `name` that the name property of the - * error matches `"AbortError"`. - * - * @example - * ```ts - * const controller = new AbortController(); - * controller.abort(); - * try { - * doAsyncWork(controller.signal) - * } catch (e) { - * if (e.name === 'AbortError') { - * // handle abort error here. - * } - * } - * ``` - */ -export class AbortError extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; - } -} -//# sourceMappingURL=AbortError.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/abort-controller/dist/esm/index.js b/claude-code-source/node_modules/@azure/abort-controller/dist/esm/index.js deleted file mode 100644 index 68c507cd..00000000 --- a/claude-code-source/node_modules/@azure/abort-controller/dist/esm/index.js +++ /dev/null @@ -1,4 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT license. -export { AbortError } from "./AbortError.js"; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/commonjs/state.js b/claude-code-source/node_modules/@azure/core-client/dist/commonjs/state.js deleted file mode 100644 index b9e48ae3..00000000 --- a/claude-code-source/node_modules/@azure/core-client/dist/commonjs/state.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.state = void 0; -/** - * Holds the singleton operationRequestMap, to be shared across CJS and ESM imports. - */ -exports.state = { - operationRequestMap: new WeakMap(), -}; -//# sourceMappingURL=state-cjs.cjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/deserializationPolicy.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/deserializationPolicy.js deleted file mode 100644 index 97e36024..00000000 --- a/claude-code-source/node_modules/@azure/core-client/dist/esm/deserializationPolicy.js +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { XML_CHARKEY } from "./interfaces.js"; -import { RestError } from "@azure/core-rest-pipeline"; -import { MapperTypeNames } from "./serializer.js"; -import { getOperationRequestInfo } from "./operationHelpers.js"; -const defaultJsonContentTypes = ["application/json", "text/json"]; -const defaultXmlContentTypes = ["application/xml", "application/atom+xml"]; -/** - * The programmatic identifier of the deserializationPolicy. - */ -export const deserializationPolicyName = "deserializationPolicy"; -/** - * This policy handles parsing out responses according to OperationSpecs on the request. - */ -export function deserializationPolicy(options = {}) { - var _a, _b, _c, _d, _e, _f, _g; - const jsonContentTypes = (_b = (_a = options.expectedContentTypes) === null || _a === void 0 ? void 0 : _a.json) !== null && _b !== void 0 ? _b : defaultJsonContentTypes; - const xmlContentTypes = (_d = (_c = options.expectedContentTypes) === null || _c === void 0 ? void 0 : _c.xml) !== null && _d !== void 0 ? _d : defaultXmlContentTypes; - const parseXML = options.parseXML; - const serializerOptions = options.serializerOptions; - const updatedOptions = { - xml: { - rootName: (_e = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _e !== void 0 ? _e : "", - includeRoot: (_f = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _f !== void 0 ? _f : false, - xmlCharKey: (_g = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _g !== void 0 ? _g : XML_CHARKEY, - }, - }; - return { - name: deserializationPolicyName, - async sendRequest(request, next) { - const response = await next(request); - return deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, updatedOptions, parseXML); - }, - }; -} -function getOperationResponseMap(parsedResponse) { - let result; - const request = parsedResponse.request; - const operationInfo = getOperationRequestInfo(request); - const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec; - if (operationSpec) { - if (!(operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter)) { - result = operationSpec.responses[parsedResponse.status]; - } - else { - result = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationResponseGetter(operationSpec, parsedResponse); - } - } - return result; -} -function shouldDeserializeResponse(parsedResponse) { - const request = parsedResponse.request; - const operationInfo = getOperationRequestInfo(request); - const shouldDeserialize = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.shouldDeserialize; - let result; - if (shouldDeserialize === undefined) { - result = true; - } - else if (typeof shouldDeserialize === "boolean") { - result = shouldDeserialize; - } - else { - result = shouldDeserialize(parsedResponse); - } - return result; -} -async function deserializeResponseBody(jsonContentTypes, xmlContentTypes, response, options, parseXML) { - const parsedResponse = await parse(jsonContentTypes, xmlContentTypes, response, options, parseXML); - if (!shouldDeserializeResponse(parsedResponse)) { - return parsedResponse; - } - const operationInfo = getOperationRequestInfo(parsedResponse.request); - const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec; - if (!operationSpec || !operationSpec.responses) { - return parsedResponse; - } - const responseSpec = getOperationResponseMap(parsedResponse); - const { error, shouldReturnResponse } = handleErrorResponse(parsedResponse, operationSpec, responseSpec, options); - if (error) { - throw error; - } - else if (shouldReturnResponse) { - return parsedResponse; - } - // An operation response spec does exist for current status code, so - // use it to deserialize the response. - if (responseSpec) { - if (responseSpec.bodyMapper) { - let valueToDeserialize = parsedResponse.parsedBody; - if (operationSpec.isXML && responseSpec.bodyMapper.type.name === MapperTypeNames.Sequence) { - valueToDeserialize = - typeof valueToDeserialize === "object" - ? valueToDeserialize[responseSpec.bodyMapper.xmlElementName] - : []; - } - try { - parsedResponse.parsedBody = operationSpec.serializer.deserialize(responseSpec.bodyMapper, valueToDeserialize, "operationRes.parsedBody", options); - } - catch (deserializeError) { - const restError = new RestError(`Error ${deserializeError} occurred in deserializing the responseBody - ${parsedResponse.bodyAsText}`, { - statusCode: parsedResponse.status, - request: parsedResponse.request, - response: parsedResponse, - }); - throw restError; - } - } - else if (operationSpec.httpMethod === "HEAD") { - // head methods never have a body, but we return a boolean to indicate presence/absence of the resource - parsedResponse.parsedBody = response.status >= 200 && response.status < 300; - } - if (responseSpec.headersMapper) { - parsedResponse.parsedHeaders = operationSpec.serializer.deserialize(responseSpec.headersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders", { xml: {}, ignoreUnknownProperties: true }); - } - } - return parsedResponse; -} -function isOperationSpecEmpty(operationSpec) { - const expectedStatusCodes = Object.keys(operationSpec.responses); - return (expectedStatusCodes.length === 0 || - (expectedStatusCodes.length === 1 && expectedStatusCodes[0] === "default")); -} -function handleErrorResponse(parsedResponse, operationSpec, responseSpec, options) { - var _a, _b, _c, _d, _e; - const isSuccessByStatus = 200 <= parsedResponse.status && parsedResponse.status < 300; - const isExpectedStatusCode = isOperationSpecEmpty(operationSpec) - ? isSuccessByStatus - : !!responseSpec; - if (isExpectedStatusCode) { - if (responseSpec) { - if (!responseSpec.isError) { - return { error: null, shouldReturnResponse: false }; - } - } - else { - return { error: null, shouldReturnResponse: false }; - } - } - const errorResponseSpec = responseSpec !== null && responseSpec !== void 0 ? responseSpec : operationSpec.responses.default; - const initialErrorMessage = ((_a = parsedResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(parsedResponse.status)) - ? `Unexpected status code: ${parsedResponse.status}` - : parsedResponse.bodyAsText; - const error = new RestError(initialErrorMessage, { - statusCode: parsedResponse.status, - request: parsedResponse.request, - response: parsedResponse, - }); - // If the item failed but there's no error spec or default spec to deserialize the error, - // and the parsed body doesn't look like an error object, - // we should fail so we just throw the parsed response - if (!errorResponseSpec && - !(((_c = (_b = parsedResponse.parsedBody) === null || _b === void 0 ? void 0 : _b.error) === null || _c === void 0 ? void 0 : _c.code) && ((_e = (_d = parsedResponse.parsedBody) === null || _d === void 0 ? void 0 : _d.error) === null || _e === void 0 ? void 0 : _e.message))) { - throw error; - } - const defaultBodyMapper = errorResponseSpec === null || errorResponseSpec === void 0 ? void 0 : errorResponseSpec.bodyMapper; - const defaultHeadersMapper = errorResponseSpec === null || errorResponseSpec === void 0 ? void 0 : errorResponseSpec.headersMapper; - try { - // If error response has a body, try to deserialize it using default body mapper. - // Then try to extract error code & message from it - if (parsedResponse.parsedBody) { - const parsedBody = parsedResponse.parsedBody; - let deserializedError; - if (defaultBodyMapper) { - let valueToDeserialize = parsedBody; - if (operationSpec.isXML && defaultBodyMapper.type.name === MapperTypeNames.Sequence) { - valueToDeserialize = []; - const elementName = defaultBodyMapper.xmlElementName; - if (typeof parsedBody === "object" && elementName) { - valueToDeserialize = parsedBody[elementName]; - } - } - deserializedError = operationSpec.serializer.deserialize(defaultBodyMapper, valueToDeserialize, "error.response.parsedBody", options); - } - const internalError = parsedBody.error || deserializedError || parsedBody; - error.code = internalError.code; - if (internalError.message) { - error.message = internalError.message; - } - if (defaultBodyMapper) { - error.response.parsedBody = deserializedError; - } - } - // If error response has headers, try to deserialize it using default header mapper - if (parsedResponse.headers && defaultHeadersMapper) { - error.response.parsedHeaders = - operationSpec.serializer.deserialize(defaultHeadersMapper, parsedResponse.headers.toJSON(), "operationRes.parsedHeaders"); - } - } - catch (defaultError) { - error.message = `Error "${defaultError.message}" occurred in deserializing the responseBody - "${parsedResponse.bodyAsText}" for the default response.`; - } - return { error, shouldReturnResponse: false }; -} -async function parse(jsonContentTypes, xmlContentTypes, operationResponse, opts, parseXML) { - var _a; - if (!((_a = operationResponse.request.streamResponseStatusCodes) === null || _a === void 0 ? void 0 : _a.has(operationResponse.status)) && - operationResponse.bodyAsText) { - const text = operationResponse.bodyAsText; - const contentType = operationResponse.headers.get("Content-Type") || ""; - const contentComponents = !contentType - ? [] - : contentType.split(";").map((component) => component.toLowerCase()); - try { - if (contentComponents.length === 0 || - contentComponents.some((component) => jsonContentTypes.indexOf(component) !== -1)) { - operationResponse.parsedBody = JSON.parse(text); - return operationResponse; - } - else if (contentComponents.some((component) => xmlContentTypes.indexOf(component) !== -1)) { - if (!parseXML) { - throw new Error("Parsing XML not supported."); - } - const body = await parseXML(text, opts.xml); - operationResponse.parsedBody = body; - return operationResponse; - } - } - catch (err) { - const msg = `Error "${err}" occurred while parsing the response body - ${operationResponse.bodyAsText}.`; - const errCode = err.code || RestError.PARSE_ERROR; - const e = new RestError(msg, { - code: errCode, - statusCode: operationResponse.status, - request: operationResponse.request, - response: operationResponse, - }); - throw e; - } - } - return operationResponse; -} -//# sourceMappingURL=deserializationPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/httpClientCache.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/httpClientCache.js deleted file mode 100644 index ff112d09..00000000 --- a/claude-code-source/node_modules/@azure/core-client/dist/esm/httpClientCache.js +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createDefaultHttpClient } from "@azure/core-rest-pipeline"; -let cachedHttpClient; -export function getCachedDefaultHttpClient() { - if (!cachedHttpClient) { - cachedHttpClient = createDefaultHttpClient(); - } - return cachedHttpClient; -} -//# sourceMappingURL=httpClientCache.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/index.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/index.js deleted file mode 100644 index 128a2a37..00000000 --- a/claude-code-source/node_modules/@azure/core-client/dist/esm/index.js +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -export { createSerializer, MapperTypeNames } from "./serializer.js"; -export { ServiceClient } from "./serviceClient.js"; -export { createClientPipeline } from "./pipeline.js"; -export { XML_ATTRKEY, XML_CHARKEY, } from "./interfaces.js"; -export { deserializationPolicy, deserializationPolicyName, } from "./deserializationPolicy.js"; -export { serializationPolicy, serializationPolicyName, } from "./serializationPolicy.js"; -export { authorizeRequestOnClaimChallenge } from "./authorizeRequestOnClaimChallenge.js"; -export { authorizeRequestOnTenantChallenge } from "./authorizeRequestOnTenantChallenge.js"; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/interfaceHelpers.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/interfaceHelpers.js deleted file mode 100644 index ba232f86..00000000 --- a/claude-code-source/node_modules/@azure/core-client/dist/esm/interfaceHelpers.js +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { MapperTypeNames } from "./serializer.js"; -/** - * Gets the list of status codes for streaming responses. - * @internal - */ -export function getStreamingResponseStatusCodes(operationSpec) { - const result = new Set(); - for (const statusCode in operationSpec.responses) { - const operationResponse = operationSpec.responses[statusCode]; - if (operationResponse.bodyMapper && - operationResponse.bodyMapper.type.name === MapperTypeNames.Stream) { - result.add(Number(statusCode)); - } - } - return result; -} -/** - * Get the path to this parameter's value as a dotted string (a.b.c). - * @param parameter - The parameter to get the path string for. - * @returns The path to this parameter's value as a dotted string. - * @internal - */ -export function getPathStringFromParameter(parameter) { - const { parameterPath, mapper } = parameter; - let result; - if (typeof parameterPath === "string") { - result = parameterPath; - } - else if (Array.isArray(parameterPath)) { - result = parameterPath.join("."); - } - else { - result = mapper.serializedName; - } - return result; -} -//# sourceMappingURL=interfaceHelpers.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/interfaces.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/interfaces.js deleted file mode 100644 index da2b4255..00000000 --- a/claude-code-source/node_modules/@azure/core-client/dist/esm/interfaces.js +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * Default key used to access the XML attributes. - */ -export const XML_ATTRKEY = "$"; -/** - * Default key used to access the XML value content. - */ -export const XML_CHARKEY = "_"; -//# sourceMappingURL=interfaces.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/log.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/log.js deleted file mode 100644 index 98be3c8e..00000000 --- a/claude-code-source/node_modules/@azure/core-client/dist/esm/log.js +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createClientLogger } from "@azure/logger"; -export const logger = createClientLogger("core-client"); -//# sourceMappingURL=log.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/operationHelpers.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/operationHelpers.js deleted file mode 100644 index b69e1820..00000000 --- a/claude-code-source/node_modules/@azure/core-client/dist/esm/operationHelpers.js +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { state } from "./state.js"; -/** - * @internal - * Retrieves the value to use for a given operation argument - * @param operationArguments - The arguments passed from the generated client - * @param parameter - The parameter description - * @param fallbackObject - If something isn't found in the arguments bag, look here. - * Generally used to look at the service client properties. - */ -export function getOperationArgumentValueFromParameter(operationArguments, parameter, fallbackObject) { - let parameterPath = parameter.parameterPath; - const parameterMapper = parameter.mapper; - let value; - if (typeof parameterPath === "string") { - parameterPath = [parameterPath]; - } - if (Array.isArray(parameterPath)) { - if (parameterPath.length > 0) { - if (parameterMapper.isConstant) { - value = parameterMapper.defaultValue; - } - else { - let propertySearchResult = getPropertyFromParameterPath(operationArguments, parameterPath); - if (!propertySearchResult.propertyFound && fallbackObject) { - propertySearchResult = getPropertyFromParameterPath(fallbackObject, parameterPath); - } - let useDefaultValue = false; - if (!propertySearchResult.propertyFound) { - useDefaultValue = - parameterMapper.required || - (parameterPath[0] === "options" && parameterPath.length === 2); - } - value = useDefaultValue ? parameterMapper.defaultValue : propertySearchResult.propertyValue; - } - } - } - else { - if (parameterMapper.required) { - value = {}; - } - for (const propertyName in parameterPath) { - const propertyMapper = parameterMapper.type.modelProperties[propertyName]; - const propertyPath = parameterPath[propertyName]; - const propertyValue = getOperationArgumentValueFromParameter(operationArguments, { - parameterPath: propertyPath, - mapper: propertyMapper, - }, fallbackObject); - if (propertyValue !== undefined) { - if (!value) { - value = {}; - } - value[propertyName] = propertyValue; - } - } - } - return value; -} -function getPropertyFromParameterPath(parent, parameterPath) { - const result = { propertyFound: false }; - let i = 0; - for (; i < parameterPath.length; ++i) { - const parameterPathPart = parameterPath[i]; - // Make sure to check inherited properties too, so don't use hasOwnProperty(). - if (parent && parameterPathPart in parent) { - parent = parent[parameterPathPart]; - } - else { - break; - } - } - if (i === parameterPath.length) { - result.propertyValue = parent; - result.propertyFound = true; - } - return result; -} -const originalRequestSymbol = Symbol.for("@azure/core-client original request"); -function hasOriginalRequest(request) { - return originalRequestSymbol in request; -} -export function getOperationRequestInfo(request) { - if (hasOriginalRequest(request)) { - return getOperationRequestInfo(request[originalRequestSymbol]); - } - let info = state.operationRequestMap.get(request); - if (!info) { - info = {}; - state.operationRequestMap.set(request, info); - } - return info; -} -//# sourceMappingURL=operationHelpers.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/pipeline.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/pipeline.js deleted file mode 100644 index dba25033..00000000 --- a/claude-code-source/node_modules/@azure/core-client/dist/esm/pipeline.js +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { deserializationPolicy } from "./deserializationPolicy.js"; -import { bearerTokenAuthenticationPolicy, createPipelineFromOptions, } from "@azure/core-rest-pipeline"; -import { serializationPolicy } from "./serializationPolicy.js"; -/** - * Creates a new Pipeline for use with a Service Client. - * Adds in deserializationPolicy by default. - * Also adds in bearerTokenAuthenticationPolicy if passed a TokenCredential. - * @param options - Options to customize the created pipeline. - */ -export function createClientPipeline(options = {}) { - const pipeline = createPipelineFromOptions(options !== null && options !== void 0 ? options : {}); - if (options.credentialOptions) { - pipeline.addPolicy(bearerTokenAuthenticationPolicy({ - credential: options.credentialOptions.credential, - scopes: options.credentialOptions.credentialScopes, - })); - } - pipeline.addPolicy(serializationPolicy(options.serializationOptions), { phase: "Serialize" }); - pipeline.addPolicy(deserializationPolicy(options.deserializationOptions), { - phase: "Deserialize", - }); - return pipeline; -} -//# sourceMappingURL=pipeline.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/serializationPolicy.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/serializationPolicy.js deleted file mode 100644 index cb8e6ac7..00000000 --- a/claude-code-source/node_modules/@azure/core-client/dist/esm/serializationPolicy.js +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { XML_ATTRKEY, XML_CHARKEY } from "./interfaces.js"; -import { getOperationArgumentValueFromParameter, getOperationRequestInfo, } from "./operationHelpers.js"; -import { MapperTypeNames } from "./serializer.js"; -import { getPathStringFromParameter } from "./interfaceHelpers.js"; -/** - * The programmatic identifier of the serializationPolicy. - */ -export const serializationPolicyName = "serializationPolicy"; -/** - * This policy handles assembling the request body and headers using - * an OperationSpec and OperationArguments on the request. - */ -export function serializationPolicy(options = {}) { - const stringifyXML = options.stringifyXML; - return { - name: serializationPolicyName, - async sendRequest(request, next) { - const operationInfo = getOperationRequestInfo(request); - const operationSpec = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationSpec; - const operationArguments = operationInfo === null || operationInfo === void 0 ? void 0 : operationInfo.operationArguments; - if (operationSpec && operationArguments) { - serializeHeaders(request, operationArguments, operationSpec); - serializeRequestBody(request, operationArguments, operationSpec, stringifyXML); - } - return next(request); - }, - }; -} -/** - * @internal - */ -export function serializeHeaders(request, operationArguments, operationSpec) { - var _a, _b; - if (operationSpec.headerParameters) { - for (const headerParameter of operationSpec.headerParameters) { - let headerValue = getOperationArgumentValueFromParameter(operationArguments, headerParameter); - if ((headerValue !== null && headerValue !== undefined) || headerParameter.mapper.required) { - headerValue = operationSpec.serializer.serialize(headerParameter.mapper, headerValue, getPathStringFromParameter(headerParameter)); - const headerCollectionPrefix = headerParameter.mapper - .headerCollectionPrefix; - if (headerCollectionPrefix) { - for (const key of Object.keys(headerValue)) { - request.headers.set(headerCollectionPrefix + key, headerValue[key]); - } - } - else { - request.headers.set(headerParameter.mapper.serializedName || getPathStringFromParameter(headerParameter), headerValue); - } - } - } - } - const customHeaders = (_b = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.requestOptions) === null || _b === void 0 ? void 0 : _b.customHeaders; - if (customHeaders) { - for (const customHeaderName of Object.keys(customHeaders)) { - request.headers.set(customHeaderName, customHeaders[customHeaderName]); - } - } -} -/** - * @internal - */ -export function serializeRequestBody(request, operationArguments, operationSpec, stringifyXML = function () { - throw new Error("XML serialization unsupported!"); -}) { - var _a, _b, _c, _d, _e; - const serializerOptions = (_a = operationArguments.options) === null || _a === void 0 ? void 0 : _a.serializerOptions; - const updatedOptions = { - xml: { - rootName: (_b = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.rootName) !== null && _b !== void 0 ? _b : "", - includeRoot: (_c = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.includeRoot) !== null && _c !== void 0 ? _c : false, - xmlCharKey: (_d = serializerOptions === null || serializerOptions === void 0 ? void 0 : serializerOptions.xml.xmlCharKey) !== null && _d !== void 0 ? _d : XML_CHARKEY, - }, - }; - const xmlCharKey = updatedOptions.xml.xmlCharKey; - if (operationSpec.requestBody && operationSpec.requestBody.mapper) { - request.body = getOperationArgumentValueFromParameter(operationArguments, operationSpec.requestBody); - const bodyMapper = operationSpec.requestBody.mapper; - const { required, serializedName, xmlName, xmlElementName, xmlNamespace, xmlNamespacePrefix, nullable, } = bodyMapper; - const typeName = bodyMapper.type.name; - try { - if ((request.body !== undefined && request.body !== null) || - (nullable && request.body === null) || - required) { - const requestBodyParameterPathString = getPathStringFromParameter(operationSpec.requestBody); - request.body = operationSpec.serializer.serialize(bodyMapper, request.body, requestBodyParameterPathString, updatedOptions); - const isStream = typeName === MapperTypeNames.Stream; - if (operationSpec.isXML) { - const xmlnsKey = xmlNamespacePrefix ? `xmlns:${xmlNamespacePrefix}` : "xmlns"; - const value = getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, request.body, updatedOptions); - if (typeName === MapperTypeNames.Sequence) { - request.body = stringifyXML(prepareXMLRootList(value, xmlElementName || xmlName || serializedName, xmlnsKey, xmlNamespace), { rootName: xmlName || serializedName, xmlCharKey }); - } - else if (!isStream) { - request.body = stringifyXML(value, { - rootName: xmlName || serializedName, - xmlCharKey, - }); - } - } - else if (typeName === MapperTypeNames.String && - (((_e = operationSpec.contentType) === null || _e === void 0 ? void 0 : _e.match("text/plain")) || operationSpec.mediaType === "text")) { - // the String serializer has validated that request body is a string - // so just send the string. - return; - } - else if (!isStream) { - request.body = JSON.stringify(request.body); - } - } - } - catch (error) { - throw new Error(`Error "${error.message}" occurred in serializing the payload - ${JSON.stringify(serializedName, undefined, " ")}.`); - } - } - else if (operationSpec.formDataParameters && operationSpec.formDataParameters.length > 0) { - request.formData = {}; - for (const formDataParameter of operationSpec.formDataParameters) { - const formDataParameterValue = getOperationArgumentValueFromParameter(operationArguments, formDataParameter); - if (formDataParameterValue !== undefined && formDataParameterValue !== null) { - const formDataParameterPropertyName = formDataParameter.mapper.serializedName || getPathStringFromParameter(formDataParameter); - request.formData[formDataParameterPropertyName] = operationSpec.serializer.serialize(formDataParameter.mapper, formDataParameterValue, getPathStringFromParameter(formDataParameter), updatedOptions); - } - } - } -} -/** - * Adds an xml namespace to the xml serialized object if needed, otherwise it just returns the value itself - */ -function getXmlValueWithNamespace(xmlNamespace, xmlnsKey, typeName, serializedValue, options) { - // Composite and Sequence schemas already got their root namespace set during serialization - // We just need to add xmlns to the other schema types - if (xmlNamespace && !["Composite", "Sequence", "Dictionary"].includes(typeName)) { - const result = {}; - result[options.xml.xmlCharKey] = serializedValue; - result[XML_ATTRKEY] = { [xmlnsKey]: xmlNamespace }; - return result; - } - return serializedValue; -} -function prepareXMLRootList(obj, elementName, xmlNamespaceKey, xmlNamespace) { - if (!Array.isArray(obj)) { - obj = [obj]; - } - if (!xmlNamespaceKey || !xmlNamespace) { - return { [elementName]: obj }; - } - const result = { [elementName]: obj }; - result[XML_ATTRKEY] = { [xmlNamespaceKey]: xmlNamespace }; - return result; -} -//# sourceMappingURL=serializationPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/serializer.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/serializer.js deleted file mode 100644 index 76add4cf..00000000 --- a/claude-code-source/node_modules/@azure/core-client/dist/esm/serializer.js +++ /dev/null @@ -1,922 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import * as base64 from "./base64.js"; -import { XML_ATTRKEY, XML_CHARKEY } from "./interfaces.js"; -import { isDuration, isValidUuid } from "./utils.js"; -class SerializerImpl { - constructor(modelMappers = {}, isXML = false) { - this.modelMappers = modelMappers; - this.isXML = isXML; - } - /** - * @deprecated Removing the constraints validation on client side. - */ - validateConstraints(mapper, value, objectName) { - const failValidation = (constraintName, constraintValue) => { - throw new Error(`"${objectName}" with value "${value}" should satisfy the constraint "${constraintName}": ${constraintValue}.`); - }; - if (mapper.constraints && value !== undefined && value !== null) { - const { ExclusiveMaximum, ExclusiveMinimum, InclusiveMaximum, InclusiveMinimum, MaxItems, MaxLength, MinItems, MinLength, MultipleOf, Pattern, UniqueItems, } = mapper.constraints; - if (ExclusiveMaximum !== undefined && value >= ExclusiveMaximum) { - failValidation("ExclusiveMaximum", ExclusiveMaximum); - } - if (ExclusiveMinimum !== undefined && value <= ExclusiveMinimum) { - failValidation("ExclusiveMinimum", ExclusiveMinimum); - } - if (InclusiveMaximum !== undefined && value > InclusiveMaximum) { - failValidation("InclusiveMaximum", InclusiveMaximum); - } - if (InclusiveMinimum !== undefined && value < InclusiveMinimum) { - failValidation("InclusiveMinimum", InclusiveMinimum); - } - if (MaxItems !== undefined && value.length > MaxItems) { - failValidation("MaxItems", MaxItems); - } - if (MaxLength !== undefined && value.length > MaxLength) { - failValidation("MaxLength", MaxLength); - } - if (MinItems !== undefined && value.length < MinItems) { - failValidation("MinItems", MinItems); - } - if (MinLength !== undefined && value.length < MinLength) { - failValidation("MinLength", MinLength); - } - if (MultipleOf !== undefined && value % MultipleOf !== 0) { - failValidation("MultipleOf", MultipleOf); - } - if (Pattern) { - const pattern = typeof Pattern === "string" ? new RegExp(Pattern) : Pattern; - if (typeof value !== "string" || value.match(pattern) === null) { - failValidation("Pattern", Pattern); - } - } - if (UniqueItems && - value.some((item, i, ar) => ar.indexOf(item) !== i)) { - failValidation("UniqueItems", UniqueItems); - } - } - } - /** - * Serialize the given object based on its metadata defined in the mapper - * - * @param mapper - The mapper which defines the metadata of the serializable object - * - * @param object - A valid Javascript object to be serialized - * - * @param objectName - Name of the serialized object - * - * @param options - additional options to serialization - * - * @returns A valid serialized Javascript object - */ - serialize(mapper, object, objectName, options = { xml: {} }) { - var _a, _b, _c; - const updatedOptions = { - xml: { - rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "", - includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false, - xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY, - }, - }; - let payload = {}; - const mapperType = mapper.type.name; - if (!objectName) { - objectName = mapper.serializedName; - } - if (mapperType.match(/^Sequence$/i) !== null) { - payload = []; - } - if (mapper.isConstant) { - object = mapper.defaultValue; - } - // This table of allowed values should help explain - // the mapper.required and mapper.nullable properties. - // X means "neither undefined or null are allowed". - // || required - // || true | false - // nullable || ========================== - // true || null | undefined/null - // false || X | undefined - // undefined || X | undefined/null - const { required, nullable } = mapper; - if (required && nullable && object === undefined) { - throw new Error(`${objectName} cannot be undefined.`); - } - if (required && !nullable && (object === undefined || object === null)) { - throw new Error(`${objectName} cannot be null or undefined.`); - } - if (!required && nullable === false && object === null) { - throw new Error(`${objectName} cannot be null.`); - } - if (object === undefined || object === null) { - payload = object; - } - else { - if (mapperType.match(/^any$/i) !== null) { - payload = object; - } - else if (mapperType.match(/^(Number|String|Boolean|Object|Stream|Uuid)$/i) !== null) { - payload = serializeBasicTypes(mapperType, objectName, object); - } - else if (mapperType.match(/^Enum$/i) !== null) { - const enumMapper = mapper; - payload = serializeEnumType(objectName, enumMapper.type.allowedValues, object); - } - else if (mapperType.match(/^(Date|DateTime|TimeSpan|DateTimeRfc1123|UnixTime)$/i) !== null) { - payload = serializeDateTypes(mapperType, object, objectName); - } - else if (mapperType.match(/^ByteArray$/i) !== null) { - payload = serializeByteArrayType(objectName, object); - } - else if (mapperType.match(/^Base64Url$/i) !== null) { - payload = serializeBase64UrlType(objectName, object); - } - else if (mapperType.match(/^Sequence$/i) !== null) { - payload = serializeSequenceType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); - } - else if (mapperType.match(/^Dictionary$/i) !== null) { - payload = serializeDictionaryType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); - } - else if (mapperType.match(/^Composite$/i) !== null) { - payload = serializeCompositeType(this, mapper, object, objectName, Boolean(this.isXML), updatedOptions); - } - } - return payload; - } - /** - * Deserialize the given object based on its metadata defined in the mapper - * - * @param mapper - The mapper which defines the metadata of the serializable object - * - * @param responseBody - A valid Javascript entity to be deserialized - * - * @param objectName - Name of the deserialized object - * - * @param options - Controls behavior of XML parser and builder. - * - * @returns A valid deserialized Javascript object - */ - deserialize(mapper, responseBody, objectName, options = { xml: {} }) { - var _a, _b, _c, _d; - const updatedOptions = { - xml: { - rootName: (_a = options.xml.rootName) !== null && _a !== void 0 ? _a : "", - includeRoot: (_b = options.xml.includeRoot) !== null && _b !== void 0 ? _b : false, - xmlCharKey: (_c = options.xml.xmlCharKey) !== null && _c !== void 0 ? _c : XML_CHARKEY, - }, - ignoreUnknownProperties: (_d = options.ignoreUnknownProperties) !== null && _d !== void 0 ? _d : false, - }; - if (responseBody === undefined || responseBody === null) { - if (this.isXML && mapper.type.name === "Sequence" && !mapper.xmlIsWrapped) { - // Edge case for empty XML non-wrapped lists. xml2js can't distinguish - // between the list being empty versus being missing, - // so let's do the more user-friendly thing and return an empty list. - responseBody = []; - } - // specifically check for undefined as default value can be a falsey value `0, "", false, null` - if (mapper.defaultValue !== undefined) { - responseBody = mapper.defaultValue; - } - return responseBody; - } - let payload; - const mapperType = mapper.type.name; - if (!objectName) { - objectName = mapper.serializedName; - } - if (mapperType.match(/^Composite$/i) !== null) { - payload = deserializeCompositeType(this, mapper, responseBody, objectName, updatedOptions); - } - else { - if (this.isXML) { - const xmlCharKey = updatedOptions.xml.xmlCharKey; - /** - * If the mapper specifies this as a non-composite type value but the responseBody contains - * both header ("$" i.e., XML_ATTRKEY) and body ("#" i.e., XML_CHARKEY) properties, - * then just reduce the responseBody value to the body ("#" i.e., XML_CHARKEY) property. - */ - if (responseBody[XML_ATTRKEY] !== undefined && responseBody[xmlCharKey] !== undefined) { - responseBody = responseBody[xmlCharKey]; - } - } - if (mapperType.match(/^Number$/i) !== null) { - payload = parseFloat(responseBody); - if (isNaN(payload)) { - payload = responseBody; - } - } - else if (mapperType.match(/^Boolean$/i) !== null) { - if (responseBody === "true") { - payload = true; - } - else if (responseBody === "false") { - payload = false; - } - else { - payload = responseBody; - } - } - else if (mapperType.match(/^(String|Enum|Object|Stream|Uuid|TimeSpan|any)$/i) !== null) { - payload = responseBody; - } - else if (mapperType.match(/^(Date|DateTime|DateTimeRfc1123)$/i) !== null) { - payload = new Date(responseBody); - } - else if (mapperType.match(/^UnixTime$/i) !== null) { - payload = unixTimeToDate(responseBody); - } - else if (mapperType.match(/^ByteArray$/i) !== null) { - payload = base64.decodeString(responseBody); - } - else if (mapperType.match(/^Base64Url$/i) !== null) { - payload = base64UrlToByteArray(responseBody); - } - else if (mapperType.match(/^Sequence$/i) !== null) { - payload = deserializeSequenceType(this, mapper, responseBody, objectName, updatedOptions); - } - else if (mapperType.match(/^Dictionary$/i) !== null) { - payload = deserializeDictionaryType(this, mapper, responseBody, objectName, updatedOptions); - } - } - if (mapper.isConstant) { - payload = mapper.defaultValue; - } - return payload; - } -} -/** - * Method that creates and returns a Serializer. - * @param modelMappers - Known models to map - * @param isXML - If XML should be supported - */ -export function createSerializer(modelMappers = {}, isXML = false) { - return new SerializerImpl(modelMappers, isXML); -} -function trimEnd(str, ch) { - let len = str.length; - while (len - 1 >= 0 && str[len - 1] === ch) { - --len; - } - return str.substr(0, len); -} -function bufferToBase64Url(buffer) { - if (!buffer) { - return undefined; - } - if (!(buffer instanceof Uint8Array)) { - throw new Error(`Please provide an input of type Uint8Array for converting to Base64Url.`); - } - // Uint8Array to Base64. - const str = base64.encodeByteArray(buffer); - // Base64 to Base64Url. - return trimEnd(str, "=").replace(/\+/g, "-").replace(/\//g, "_"); -} -function base64UrlToByteArray(str) { - if (!str) { - return undefined; - } - if (str && typeof str.valueOf() !== "string") { - throw new Error("Please provide an input of type string for converting to Uint8Array"); - } - // Base64Url to Base64. - str = str.replace(/-/g, "+").replace(/_/g, "/"); - // Base64 to Uint8Array. - return base64.decodeString(str); -} -function splitSerializeName(prop) { - const classes = []; - let partialclass = ""; - if (prop) { - const subwords = prop.split("."); - for (const item of subwords) { - if (item.charAt(item.length - 1) === "\\") { - partialclass += item.substr(0, item.length - 1) + "."; - } - else { - partialclass += item; - classes.push(partialclass); - partialclass = ""; - } - } - } - return classes; -} -function dateToUnixTime(d) { - if (!d) { - return undefined; - } - if (typeof d.valueOf() === "string") { - d = new Date(d); - } - return Math.floor(d.getTime() / 1000); -} -function unixTimeToDate(n) { - if (!n) { - return undefined; - } - return new Date(n * 1000); -} -function serializeBasicTypes(typeName, objectName, value) { - if (value !== null && value !== undefined) { - if (typeName.match(/^Number$/i) !== null) { - if (typeof value !== "number") { - throw new Error(`${objectName} with value ${value} must be of type number.`); - } - } - else if (typeName.match(/^String$/i) !== null) { - if (typeof value.valueOf() !== "string") { - throw new Error(`${objectName} with value "${value}" must be of type string.`); - } - } - else if (typeName.match(/^Uuid$/i) !== null) { - if (!(typeof value.valueOf() === "string" && isValidUuid(value))) { - throw new Error(`${objectName} with value "${value}" must be of type string and a valid uuid.`); - } - } - else if (typeName.match(/^Boolean$/i) !== null) { - if (typeof value !== "boolean") { - throw new Error(`${objectName} with value ${value} must be of type boolean.`); - } - } - else if (typeName.match(/^Stream$/i) !== null) { - const objectType = typeof value; - if (objectType !== "string" && - typeof value.pipe !== "function" && // NodeJS.ReadableStream - typeof value.tee !== "function" && // browser ReadableStream - !(value instanceof ArrayBuffer) && - !ArrayBuffer.isView(value) && - // File objects count as a type of Blob, so we want to use instanceof explicitly - !((typeof Blob === "function" || typeof Blob === "object") && value instanceof Blob) && - objectType !== "function") { - throw new Error(`${objectName} must be a string, Blob, ArrayBuffer, ArrayBufferView, ReadableStream, or () => ReadableStream.`); - } - } - } - return value; -} -function serializeEnumType(objectName, allowedValues, value) { - if (!allowedValues) { - throw new Error(`Please provide a set of allowedValues to validate ${objectName} as an Enum Type.`); - } - const isPresent = allowedValues.some((item) => { - if (typeof item.valueOf() === "string") { - return item.toLowerCase() === value.toLowerCase(); - } - return item === value; - }); - if (!isPresent) { - throw new Error(`${value} is not a valid value for ${objectName}. The valid values are: ${JSON.stringify(allowedValues)}.`); - } - return value; -} -function serializeByteArrayType(objectName, value) { - if (value !== undefined && value !== null) { - if (!(value instanceof Uint8Array)) { - throw new Error(`${objectName} must be of type Uint8Array.`); - } - value = base64.encodeByteArray(value); - } - return value; -} -function serializeBase64UrlType(objectName, value) { - if (value !== undefined && value !== null) { - if (!(value instanceof Uint8Array)) { - throw new Error(`${objectName} must be of type Uint8Array.`); - } - value = bufferToBase64Url(value); - } - return value; -} -function serializeDateTypes(typeName, value, objectName) { - if (value !== undefined && value !== null) { - if (typeName.match(/^Date$/i) !== null) { - if (!(value instanceof Date || - (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { - throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); - } - value = - value instanceof Date - ? value.toISOString().substring(0, 10) - : new Date(value).toISOString().substring(0, 10); - } - else if (typeName.match(/^DateTime$/i) !== null) { - if (!(value instanceof Date || - (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { - throw new Error(`${objectName} must be an instanceof Date or a string in ISO8601 format.`); - } - value = value instanceof Date ? value.toISOString() : new Date(value).toISOString(); - } - else if (typeName.match(/^DateTimeRfc1123$/i) !== null) { - if (!(value instanceof Date || - (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { - throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123 format.`); - } - value = value instanceof Date ? value.toUTCString() : new Date(value).toUTCString(); - } - else if (typeName.match(/^UnixTime$/i) !== null) { - if (!(value instanceof Date || - (typeof value.valueOf() === "string" && !isNaN(Date.parse(value))))) { - throw new Error(`${objectName} must be an instanceof Date or a string in RFC-1123/ISO8601 format ` + - `for it to be serialized in UnixTime/Epoch format.`); - } - value = dateToUnixTime(value); - } - else if (typeName.match(/^TimeSpan$/i) !== null) { - if (!isDuration(value)) { - throw new Error(`${objectName} must be a string in ISO 8601 format. Instead was "${value}".`); - } - } - } - return value; -} -function serializeSequenceType(serializer, mapper, object, objectName, isXml, options) { - var _a; - if (!Array.isArray(object)) { - throw new Error(`${objectName} must be of type Array.`); - } - let elementType = mapper.type.element; - if (!elementType || typeof elementType !== "object") { - throw new Error(`element" metadata for an Array must be defined in the ` + - `mapper and it must of type "object" in ${objectName}.`); - } - // Quirk: Composite mappers referenced by `element` might - // not have *all* properties declared (like uberParent), - // so let's try to look up the full definition by name. - if (elementType.type.name === "Composite" && elementType.type.className) { - elementType = (_a = serializer.modelMappers[elementType.type.className]) !== null && _a !== void 0 ? _a : elementType; - } - const tempArray = []; - for (let i = 0; i < object.length; i++) { - const serializedValue = serializer.serialize(elementType, object[i], objectName, options); - if (isXml && elementType.xmlNamespace) { - const xmlnsKey = elementType.xmlNamespacePrefix - ? `xmlns:${elementType.xmlNamespacePrefix}` - : "xmlns"; - if (elementType.type.name === "Composite") { - tempArray[i] = Object.assign({}, serializedValue); - tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; - } - else { - tempArray[i] = {}; - tempArray[i][options.xml.xmlCharKey] = serializedValue; - tempArray[i][XML_ATTRKEY] = { [xmlnsKey]: elementType.xmlNamespace }; - } - } - else { - tempArray[i] = serializedValue; - } - } - return tempArray; -} -function serializeDictionaryType(serializer, mapper, object, objectName, isXml, options) { - if (typeof object !== "object") { - throw new Error(`${objectName} must be of type object.`); - } - const valueType = mapper.type.value; - if (!valueType || typeof valueType !== "object") { - throw new Error(`"value" metadata for a Dictionary must be defined in the ` + - `mapper and it must of type "object" in ${objectName}.`); - } - const tempDictionary = {}; - for (const key of Object.keys(object)) { - const serializedValue = serializer.serialize(valueType, object[key], objectName, options); - // If the element needs an XML namespace we need to add it within the $ property - tempDictionary[key] = getXmlObjectValue(valueType, serializedValue, isXml, options); - } - // Add the namespace to the root element if needed - if (isXml && mapper.xmlNamespace) { - const xmlnsKey = mapper.xmlNamespacePrefix ? `xmlns:${mapper.xmlNamespacePrefix}` : "xmlns"; - const result = tempDictionary; - result[XML_ATTRKEY] = { [xmlnsKey]: mapper.xmlNamespace }; - return result; - } - return tempDictionary; -} -/** - * Resolves the additionalProperties property from a referenced mapper - * @param serializer - the serializer containing the entire set of mappers - * @param mapper - the composite mapper to resolve - * @param objectName - name of the object being serialized - */ -function resolveAdditionalProperties(serializer, mapper, objectName) { - const additionalProperties = mapper.type.additionalProperties; - if (!additionalProperties && mapper.type.className) { - const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); - return modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.additionalProperties; - } - return additionalProperties; -} -/** - * Finds the mapper referenced by className - * @param serializer - the serializer containing the entire set of mappers - * @param mapper - the composite mapper to resolve - * @param objectName - name of the object being serialized - */ -function resolveReferencedMapper(serializer, mapper, objectName) { - const className = mapper.type.className; - if (!className) { - throw new Error(`Class name for model "${objectName}" is not provided in the mapper "${JSON.stringify(mapper, undefined, 2)}".`); - } - return serializer.modelMappers[className]; -} -/** - * Resolves a composite mapper's modelProperties. - * @param serializer - the serializer containing the entire set of mappers - * @param mapper - the composite mapper to resolve - */ -function resolveModelProperties(serializer, mapper, objectName) { - let modelProps = mapper.type.modelProperties; - if (!modelProps) { - const modelMapper = resolveReferencedMapper(serializer, mapper, objectName); - if (!modelMapper) { - throw new Error(`mapper() cannot be null or undefined for model "${mapper.type.className}".`); - } - modelProps = modelMapper === null || modelMapper === void 0 ? void 0 : modelMapper.type.modelProperties; - if (!modelProps) { - throw new Error(`modelProperties cannot be null or undefined in the ` + - `mapper "${JSON.stringify(modelMapper)}" of type "${mapper.type.className}" for object "${objectName}".`); - } - } - return modelProps; -} -function serializeCompositeType(serializer, mapper, object, objectName, isXml, options) { - if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { - mapper = getPolymorphicMapper(serializer, mapper, object, "clientName"); - } - if (object !== undefined && object !== null) { - const payload = {}; - const modelProps = resolveModelProperties(serializer, mapper, objectName); - for (const key of Object.keys(modelProps)) { - const propertyMapper = modelProps[key]; - if (propertyMapper.readOnly) { - continue; - } - let propName; - let parentObject = payload; - if (serializer.isXML) { - if (propertyMapper.xmlIsWrapped) { - propName = propertyMapper.xmlName; - } - else { - propName = propertyMapper.xmlElementName || propertyMapper.xmlName; - } - } - else { - const paths = splitSerializeName(propertyMapper.serializedName); - propName = paths.pop(); - for (const pathName of paths) { - const childObject = parentObject[pathName]; - if ((childObject === undefined || childObject === null) && - ((object[key] !== undefined && object[key] !== null) || - propertyMapper.defaultValue !== undefined)) { - parentObject[pathName] = {}; - } - parentObject = parentObject[pathName]; - } - } - if (parentObject !== undefined && parentObject !== null) { - if (isXml && mapper.xmlNamespace) { - const xmlnsKey = mapper.xmlNamespacePrefix - ? `xmlns:${mapper.xmlNamespacePrefix}` - : "xmlns"; - parentObject[XML_ATTRKEY] = Object.assign(Object.assign({}, parentObject[XML_ATTRKEY]), { [xmlnsKey]: mapper.xmlNamespace }); - } - const propertyObjectName = propertyMapper.serializedName !== "" - ? objectName + "." + propertyMapper.serializedName - : objectName; - let toSerialize = object[key]; - const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); - if (polymorphicDiscriminator && - polymorphicDiscriminator.clientName === key && - (toSerialize === undefined || toSerialize === null)) { - toSerialize = mapper.serializedName; - } - const serializedValue = serializer.serialize(propertyMapper, toSerialize, propertyObjectName, options); - if (serializedValue !== undefined && propName !== undefined && propName !== null) { - const value = getXmlObjectValue(propertyMapper, serializedValue, isXml, options); - if (isXml && propertyMapper.xmlIsAttribute) { - // XML_ATTRKEY, i.e., $ is the key attributes are kept under in xml2js. - // This keeps things simple while preventing name collision - // with names in user documents. - parentObject[XML_ATTRKEY] = parentObject[XML_ATTRKEY] || {}; - parentObject[XML_ATTRKEY][propName] = serializedValue; - } - else if (isXml && propertyMapper.xmlIsWrapped) { - parentObject[propName] = { [propertyMapper.xmlElementName]: value }; - } - else { - parentObject[propName] = value; - } - } - } - } - const additionalPropertiesMapper = resolveAdditionalProperties(serializer, mapper, objectName); - if (additionalPropertiesMapper) { - const propNames = Object.keys(modelProps); - for (const clientPropName in object) { - const isAdditionalProperty = propNames.every((pn) => pn !== clientPropName); - if (isAdditionalProperty) { - payload[clientPropName] = serializer.serialize(additionalPropertiesMapper, object[clientPropName], objectName + '["' + clientPropName + '"]', options); - } - } - } - return payload; - } - return object; -} -function getXmlObjectValue(propertyMapper, serializedValue, isXml, options) { - if (!isXml || !propertyMapper.xmlNamespace) { - return serializedValue; - } - const xmlnsKey = propertyMapper.xmlNamespacePrefix - ? `xmlns:${propertyMapper.xmlNamespacePrefix}` - : "xmlns"; - const xmlNamespace = { [xmlnsKey]: propertyMapper.xmlNamespace }; - if (["Composite"].includes(propertyMapper.type.name)) { - if (serializedValue[XML_ATTRKEY]) { - return serializedValue; - } - else { - const result = Object.assign({}, serializedValue); - result[XML_ATTRKEY] = xmlNamespace; - return result; - } - } - const result = {}; - result[options.xml.xmlCharKey] = serializedValue; - result[XML_ATTRKEY] = xmlNamespace; - return result; -} -function isSpecialXmlProperty(propertyName, options) { - return [XML_ATTRKEY, options.xml.xmlCharKey].includes(propertyName); -} -function deserializeCompositeType(serializer, mapper, responseBody, objectName, options) { - var _a, _b; - const xmlCharKey = (_a = options.xml.xmlCharKey) !== null && _a !== void 0 ? _a : XML_CHARKEY; - if (getPolymorphicDiscriminatorRecursively(serializer, mapper)) { - mapper = getPolymorphicMapper(serializer, mapper, responseBody, "serializedName"); - } - const modelProps = resolveModelProperties(serializer, mapper, objectName); - let instance = {}; - const handledPropertyNames = []; - for (const key of Object.keys(modelProps)) { - const propertyMapper = modelProps[key]; - const paths = splitSerializeName(modelProps[key].serializedName); - handledPropertyNames.push(paths[0]); - const { serializedName, xmlName, xmlElementName } = propertyMapper; - let propertyObjectName = objectName; - if (serializedName !== "" && serializedName !== undefined) { - propertyObjectName = objectName + "." + serializedName; - } - const headerCollectionPrefix = propertyMapper.headerCollectionPrefix; - if (headerCollectionPrefix) { - const dictionary = {}; - for (const headerKey of Object.keys(responseBody)) { - if (headerKey.startsWith(headerCollectionPrefix)) { - dictionary[headerKey.substring(headerCollectionPrefix.length)] = serializer.deserialize(propertyMapper.type.value, responseBody[headerKey], propertyObjectName, options); - } - handledPropertyNames.push(headerKey); - } - instance[key] = dictionary; - } - else if (serializer.isXML) { - if (propertyMapper.xmlIsAttribute && responseBody[XML_ATTRKEY]) { - instance[key] = serializer.deserialize(propertyMapper, responseBody[XML_ATTRKEY][xmlName], propertyObjectName, options); - } - else if (propertyMapper.xmlIsMsText) { - if (responseBody[xmlCharKey] !== undefined) { - instance[key] = responseBody[xmlCharKey]; - } - else if (typeof responseBody === "string") { - // The special case where xml parser parses "content" into JSON of - // `{ name: "content"}` instead of `{ name: { "_": "content" }}` - instance[key] = responseBody; - } - } - else { - const propertyName = xmlElementName || xmlName || serializedName; - if (propertyMapper.xmlIsWrapped) { - /* a list of wrapped by - For the xml example below - - ... - ... - - the responseBody has - { - Cors: { - CorsRule: [{...}, {...}] - } - } - xmlName is "Cors" and xmlElementName is"CorsRule". - */ - const wrapped = responseBody[xmlName]; - const elementList = (_b = wrapped === null || wrapped === void 0 ? void 0 : wrapped[xmlElementName]) !== null && _b !== void 0 ? _b : []; - instance[key] = serializer.deserialize(propertyMapper, elementList, propertyObjectName, options); - handledPropertyNames.push(xmlName); - } - else { - const property = responseBody[propertyName]; - instance[key] = serializer.deserialize(propertyMapper, property, propertyObjectName, options); - handledPropertyNames.push(propertyName); - } - } - } - else { - // deserialize the property if it is present in the provided responseBody instance - let propertyInstance; - let res = responseBody; - // traversing the object step by step. - let steps = 0; - for (const item of paths) { - if (!res) - break; - steps++; - res = res[item]; - } - // only accept null when reaching the last position of object otherwise it would be undefined - if (res === null && steps < paths.length) { - res = undefined; - } - propertyInstance = res; - const polymorphicDiscriminator = mapper.type.polymorphicDiscriminator; - // checking that the model property name (key)(ex: "fishtype") and the - // clientName of the polymorphicDiscriminator {metadata} (ex: "fishtype") - // instead of the serializedName of the polymorphicDiscriminator (ex: "fish.type") - // is a better approach. The generator is not consistent with escaping '\.' in the - // serializedName of the property (ex: "fish\.type") that is marked as polymorphic discriminator - // and the serializedName of the metadata polymorphicDiscriminator (ex: "fish.type"). However, - // the clientName transformation of the polymorphicDiscriminator (ex: "fishtype") and - // the transformation of model property name (ex: "fishtype") is done consistently. - // Hence, it is a safer bet to rely on the clientName of the polymorphicDiscriminator. - if (polymorphicDiscriminator && - key === polymorphicDiscriminator.clientName && - (propertyInstance === undefined || propertyInstance === null)) { - propertyInstance = mapper.serializedName; - } - let serializedValue; - // paging - if (Array.isArray(responseBody[key]) && modelProps[key].serializedName === "") { - propertyInstance = responseBody[key]; - const arrayInstance = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); - // Copy over any properties that have already been added into the instance, where they do - // not exist on the newly de-serialized array - for (const [k, v] of Object.entries(instance)) { - if (!Object.prototype.hasOwnProperty.call(arrayInstance, k)) { - arrayInstance[k] = v; - } - } - instance = arrayInstance; - } - else if (propertyInstance !== undefined || propertyMapper.defaultValue !== undefined) { - serializedValue = serializer.deserialize(propertyMapper, propertyInstance, propertyObjectName, options); - instance[key] = serializedValue; - } - } - } - const additionalPropertiesMapper = mapper.type.additionalProperties; - if (additionalPropertiesMapper) { - const isAdditionalProperty = (responsePropName) => { - for (const clientPropName in modelProps) { - const paths = splitSerializeName(modelProps[clientPropName].serializedName); - if (paths[0] === responsePropName) { - return false; - } - } - return true; - }; - for (const responsePropName in responseBody) { - if (isAdditionalProperty(responsePropName)) { - instance[responsePropName] = serializer.deserialize(additionalPropertiesMapper, responseBody[responsePropName], objectName + '["' + responsePropName + '"]', options); - } - } - } - else if (responseBody && !options.ignoreUnknownProperties) { - for (const key of Object.keys(responseBody)) { - if (instance[key] === undefined && - !handledPropertyNames.includes(key) && - !isSpecialXmlProperty(key, options)) { - instance[key] = responseBody[key]; - } - } - } - return instance; -} -function deserializeDictionaryType(serializer, mapper, responseBody, objectName, options) { - /* jshint validthis: true */ - const value = mapper.type.value; - if (!value || typeof value !== "object") { - throw new Error(`"value" metadata for a Dictionary must be defined in the ` + - `mapper and it must of type "object" in ${objectName}`); - } - if (responseBody) { - const tempDictionary = {}; - for (const key of Object.keys(responseBody)) { - tempDictionary[key] = serializer.deserialize(value, responseBody[key], objectName, options); - } - return tempDictionary; - } - return responseBody; -} -function deserializeSequenceType(serializer, mapper, responseBody, objectName, options) { - var _a; - let element = mapper.type.element; - if (!element || typeof element !== "object") { - throw new Error(`element" metadata for an Array must be defined in the ` + - `mapper and it must of type "object" in ${objectName}`); - } - if (responseBody) { - if (!Array.isArray(responseBody)) { - // xml2js will interpret a single element array as just the element, so force it to be an array - responseBody = [responseBody]; - } - // Quirk: Composite mappers referenced by `element` might - // not have *all* properties declared (like uberParent), - // so let's try to look up the full definition by name. - if (element.type.name === "Composite" && element.type.className) { - element = (_a = serializer.modelMappers[element.type.className]) !== null && _a !== void 0 ? _a : element; - } - const tempArray = []; - for (let i = 0; i < responseBody.length; i++) { - tempArray[i] = serializer.deserialize(element, responseBody[i], `${objectName}[${i}]`, options); - } - return tempArray; - } - return responseBody; -} -function getIndexDiscriminator(discriminators, discriminatorValue, typeName) { - const typeNamesToCheck = [typeName]; - while (typeNamesToCheck.length) { - const currentName = typeNamesToCheck.shift(); - const indexDiscriminator = discriminatorValue === currentName - ? discriminatorValue - : currentName + "." + discriminatorValue; - if (Object.prototype.hasOwnProperty.call(discriminators, indexDiscriminator)) { - return discriminators[indexDiscriminator]; - } - else { - for (const [name, mapper] of Object.entries(discriminators)) { - if (name.startsWith(currentName + ".") && - mapper.type.uberParent === currentName && - mapper.type.className) { - typeNamesToCheck.push(mapper.type.className); - } - } - } - } - return undefined; -} -function getPolymorphicMapper(serializer, mapper, object, polymorphicPropertyName) { - var _a; - const polymorphicDiscriminator = getPolymorphicDiscriminatorRecursively(serializer, mapper); - if (polymorphicDiscriminator) { - let discriminatorName = polymorphicDiscriminator[polymorphicPropertyName]; - if (discriminatorName) { - // The serializedName might have \\, which we just want to ignore - if (polymorphicPropertyName === "serializedName") { - discriminatorName = discriminatorName.replace(/\\/gi, ""); - } - const discriminatorValue = object[discriminatorName]; - const typeName = (_a = mapper.type.uberParent) !== null && _a !== void 0 ? _a : mapper.type.className; - if (typeof discriminatorValue === "string" && typeName) { - const polymorphicMapper = getIndexDiscriminator(serializer.modelMappers.discriminators, discriminatorValue, typeName); - if (polymorphicMapper) { - mapper = polymorphicMapper; - } - } - } - } - return mapper; -} -function getPolymorphicDiscriminatorRecursively(serializer, mapper) { - return (mapper.type.polymorphicDiscriminator || - getPolymorphicDiscriminatorSafely(serializer, mapper.type.uberParent) || - getPolymorphicDiscriminatorSafely(serializer, mapper.type.className)); -} -function getPolymorphicDiscriminatorSafely(serializer, typeName) { - return (typeName && - serializer.modelMappers[typeName] && - serializer.modelMappers[typeName].type.polymorphicDiscriminator); -} -/** - * Known types of Mappers - */ -export const MapperTypeNames = { - Base64Url: "Base64Url", - Boolean: "Boolean", - ByteArray: "ByteArray", - Composite: "Composite", - Date: "Date", - DateTime: "DateTime", - DateTimeRfc1123: "DateTimeRfc1123", - Dictionary: "Dictionary", - Enum: "Enum", - Number: "Number", - Object: "Object", - Sequence: "Sequence", - String: "String", - Stream: "Stream", - TimeSpan: "TimeSpan", - UnixTime: "UnixTime", -}; -//# sourceMappingURL=serializer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/serviceClient.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/serviceClient.js deleted file mode 100644 index 5a8efb51..00000000 --- a/claude-code-source/node_modules/@azure/core-client/dist/esm/serviceClient.js +++ /dev/null @@ -1,148 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createPipelineRequest } from "@azure/core-rest-pipeline"; -import { createClientPipeline } from "./pipeline.js"; -import { flattenResponse } from "./utils.js"; -import { getCachedDefaultHttpClient } from "./httpClientCache.js"; -import { getOperationRequestInfo } from "./operationHelpers.js"; -import { getRequestUrl } from "./urlHelpers.js"; -import { getStreamingResponseStatusCodes } from "./interfaceHelpers.js"; -import { logger } from "./log.js"; -/** - * Initializes a new instance of the ServiceClient. - */ -export class ServiceClient { - /** - * The ServiceClient constructor - * @param options - The service client options that govern the behavior of the client. - */ - constructor(options = {}) { - var _a, _b; - this._requestContentType = options.requestContentType; - this._endpoint = (_a = options.endpoint) !== null && _a !== void 0 ? _a : options.baseUri; - if (options.baseUri) { - logger.warning("The baseUri option for SDK Clients has been deprecated, please use endpoint instead."); - } - this._allowInsecureConnection = options.allowInsecureConnection; - this._httpClient = options.httpClient || getCachedDefaultHttpClient(); - this.pipeline = options.pipeline || createDefaultPipeline(options); - if ((_b = options.additionalPolicies) === null || _b === void 0 ? void 0 : _b.length) { - for (const { policy, position } of options.additionalPolicies) { - // Sign happens after Retry and is commonly needed to occur - // before policies that intercept post-retry. - const afterPhase = position === "perRetry" ? "Sign" : undefined; - this.pipeline.addPolicy(policy, { - afterPhase, - }); - } - } - } - /** - * Send the provided httpRequest. - */ - async sendRequest(request) { - return this.pipeline.sendRequest(this._httpClient, request); - } - /** - * Send an HTTP request that is populated using the provided OperationSpec. - * @typeParam T - The typed result of the request, based on the OperationSpec. - * @param operationArguments - The arguments that the HTTP request's templated values will be populated from. - * @param operationSpec - The OperationSpec to use to populate the httpRequest. - */ - async sendOperationRequest(operationArguments, operationSpec) { - const endpoint = operationSpec.baseUrl || this._endpoint; - if (!endpoint) { - throw new Error("If operationSpec.baseUrl is not specified, then the ServiceClient must have a endpoint string property that contains the base URL to use."); - } - // Templatized URLs sometimes reference properties on the ServiceClient child class, - // so we have to pass `this` below in order to search these properties if they're - // not part of OperationArguments - const url = getRequestUrl(endpoint, operationSpec, operationArguments, this); - const request = createPipelineRequest({ - url, - }); - request.method = operationSpec.httpMethod; - const operationInfo = getOperationRequestInfo(request); - operationInfo.operationSpec = operationSpec; - operationInfo.operationArguments = operationArguments; - const contentType = operationSpec.contentType || this._requestContentType; - if (contentType && operationSpec.requestBody) { - request.headers.set("Content-Type", contentType); - } - const options = operationArguments.options; - if (options) { - const requestOptions = options.requestOptions; - if (requestOptions) { - if (requestOptions.timeout) { - request.timeout = requestOptions.timeout; - } - if (requestOptions.onUploadProgress) { - request.onUploadProgress = requestOptions.onUploadProgress; - } - if (requestOptions.onDownloadProgress) { - request.onDownloadProgress = requestOptions.onDownloadProgress; - } - if (requestOptions.shouldDeserialize !== undefined) { - operationInfo.shouldDeserialize = requestOptions.shouldDeserialize; - } - if (requestOptions.allowInsecureConnection) { - request.allowInsecureConnection = true; - } - } - if (options.abortSignal) { - request.abortSignal = options.abortSignal; - } - if (options.tracingOptions) { - request.tracingOptions = options.tracingOptions; - } - } - if (this._allowInsecureConnection) { - request.allowInsecureConnection = true; - } - if (request.streamResponseStatusCodes === undefined) { - request.streamResponseStatusCodes = getStreamingResponseStatusCodes(operationSpec); - } - try { - const rawResponse = await this.sendRequest(request); - const flatResponse = flattenResponse(rawResponse, operationSpec.responses[rawResponse.status]); - if (options === null || options === void 0 ? void 0 : options.onResponse) { - options.onResponse(rawResponse, flatResponse); - } - return flatResponse; - } - catch (error) { - if (typeof error === "object" && (error === null || error === void 0 ? void 0 : error.response)) { - const rawResponse = error.response; - const flatResponse = flattenResponse(rawResponse, operationSpec.responses[error.statusCode] || operationSpec.responses["default"]); - error.details = flatResponse; - if (options === null || options === void 0 ? void 0 : options.onResponse) { - options.onResponse(rawResponse, flatResponse, error); - } - } - throw error; - } - } -} -function createDefaultPipeline(options) { - const credentialScopes = getCredentialScopes(options); - const credentialOptions = options.credential && credentialScopes - ? { credentialScopes, credential: options.credential } - : undefined; - return createClientPipeline(Object.assign(Object.assign({}, options), { credentialOptions })); -} -function getCredentialScopes(options) { - if (options.credentialScopes) { - return options.credentialScopes; - } - if (options.endpoint) { - return `${options.endpoint}/.default`; - } - if (options.baseUri) { - return `${options.baseUri}/.default`; - } - if (options.credential && !options.credentialScopes) { - throw new Error(`When using credentials, the ServiceClientOptions must contain either a endpoint or a credentialScopes. Unable to create a bearerTokenAuthenticationPolicy`); - } - return undefined; -} -//# sourceMappingURL=serviceClient.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/state.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/state.js deleted file mode 100644 index e42b6638..00000000 --- a/claude-code-source/node_modules/@azure/core-client/dist/esm/state.js +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -// @ts-expect-error The recommended approach to sharing module state between ESM and CJS. -// See https://github.com/isaacs/tshy/blob/main/README.md#module-local-state for additional information. -import { state as cjsState } from "../commonjs/state.js"; -/** - * Defines the shared state between CJS and ESM by re-exporting the CJS state. - */ -export const state = cjsState; -//# sourceMappingURL=state.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/urlHelpers.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/urlHelpers.js deleted file mode 100644 index 2dddee39..00000000 --- a/claude-code-source/node_modules/@azure/core-client/dist/esm/urlHelpers.js +++ /dev/null @@ -1,235 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { getOperationArgumentValueFromParameter } from "./operationHelpers.js"; -import { getPathStringFromParameter } from "./interfaceHelpers.js"; -const CollectionFormatToDelimiterMap = { - CSV: ",", - SSV: " ", - Multi: "Multi", - TSV: "\t", - Pipes: "|", -}; -export function getRequestUrl(baseUri, operationSpec, operationArguments, fallbackObject) { - const urlReplacements = calculateUrlReplacements(operationSpec, operationArguments, fallbackObject); - let isAbsolutePath = false; - let requestUrl = replaceAll(baseUri, urlReplacements); - if (operationSpec.path) { - let path = replaceAll(operationSpec.path, urlReplacements); - // QUIRK: sometimes we get a path component like /{nextLink} - // which may be a fully formed URL with a leading /. In that case, we should - // remove the leading / - if (operationSpec.path === "/{nextLink}" && path.startsWith("/")) { - path = path.substring(1); - } - // QUIRK: sometimes we get a path component like {nextLink} - // which may be a fully formed URL. In that case, we should - // ignore the baseUri. - if (isAbsoluteUrl(path)) { - requestUrl = path; - isAbsolutePath = true; - } - else { - requestUrl = appendPath(requestUrl, path); - } - } - const { queryParams, sequenceParams } = calculateQueryParameters(operationSpec, operationArguments, fallbackObject); - /** - * Notice that this call sets the `noOverwrite` parameter to true if the `requestUrl` - * is an absolute path. This ensures that existing query parameter values in `requestUrl` - * do not get overwritten. On the other hand when `requestUrl` is not absolute path, it - * is still being built so there is nothing to overwrite. - */ - requestUrl = appendQueryParams(requestUrl, queryParams, sequenceParams, isAbsolutePath); - return requestUrl; -} -function replaceAll(input, replacements) { - let result = input; - for (const [searchValue, replaceValue] of replacements) { - result = result.split(searchValue).join(replaceValue); - } - return result; -} -function calculateUrlReplacements(operationSpec, operationArguments, fallbackObject) { - var _a; - const result = new Map(); - if ((_a = operationSpec.urlParameters) === null || _a === void 0 ? void 0 : _a.length) { - for (const urlParameter of operationSpec.urlParameters) { - let urlParameterValue = getOperationArgumentValueFromParameter(operationArguments, urlParameter, fallbackObject); - const parameterPathString = getPathStringFromParameter(urlParameter); - urlParameterValue = operationSpec.serializer.serialize(urlParameter.mapper, urlParameterValue, parameterPathString); - if (!urlParameter.skipEncoding) { - urlParameterValue = encodeURIComponent(urlParameterValue); - } - result.set(`{${urlParameter.mapper.serializedName || parameterPathString}}`, urlParameterValue); - } - } - return result; -} -function isAbsoluteUrl(url) { - return url.includes("://"); -} -function appendPath(url, pathToAppend) { - if (!pathToAppend) { - return url; - } - const parsedUrl = new URL(url); - let newPath = parsedUrl.pathname; - if (!newPath.endsWith("/")) { - newPath = `${newPath}/`; - } - if (pathToAppend.startsWith("/")) { - pathToAppend = pathToAppend.substring(1); - } - const searchStart = pathToAppend.indexOf("?"); - if (searchStart !== -1) { - const path = pathToAppend.substring(0, searchStart); - const search = pathToAppend.substring(searchStart + 1); - newPath = newPath + path; - if (search) { - parsedUrl.search = parsedUrl.search ? `${parsedUrl.search}&${search}` : search; - } - } - else { - newPath = newPath + pathToAppend; - } - parsedUrl.pathname = newPath; - return parsedUrl.toString(); -} -function calculateQueryParameters(operationSpec, operationArguments, fallbackObject) { - var _a; - const result = new Map(); - const sequenceParams = new Set(); - if ((_a = operationSpec.queryParameters) === null || _a === void 0 ? void 0 : _a.length) { - for (const queryParameter of operationSpec.queryParameters) { - if (queryParameter.mapper.type.name === "Sequence" && queryParameter.mapper.serializedName) { - sequenceParams.add(queryParameter.mapper.serializedName); - } - let queryParameterValue = getOperationArgumentValueFromParameter(operationArguments, queryParameter, fallbackObject); - if ((queryParameterValue !== undefined && queryParameterValue !== null) || - queryParameter.mapper.required) { - queryParameterValue = operationSpec.serializer.serialize(queryParameter.mapper, queryParameterValue, getPathStringFromParameter(queryParameter)); - const delimiter = queryParameter.collectionFormat - ? CollectionFormatToDelimiterMap[queryParameter.collectionFormat] - : ""; - if (Array.isArray(queryParameterValue)) { - // replace null and undefined - queryParameterValue = queryParameterValue.map((item) => { - if (item === null || item === undefined) { - return ""; - } - return item; - }); - } - if (queryParameter.collectionFormat === "Multi" && queryParameterValue.length === 0) { - continue; - } - else if (Array.isArray(queryParameterValue) && - (queryParameter.collectionFormat === "SSV" || queryParameter.collectionFormat === "TSV")) { - queryParameterValue = queryParameterValue.join(delimiter); - } - if (!queryParameter.skipEncoding) { - if (Array.isArray(queryParameterValue)) { - queryParameterValue = queryParameterValue.map((item) => { - return encodeURIComponent(item); - }); - } - else { - queryParameterValue = encodeURIComponent(queryParameterValue); - } - } - // Join pipes and CSV *after* encoding, or the server will be upset. - if (Array.isArray(queryParameterValue) && - (queryParameter.collectionFormat === "CSV" || queryParameter.collectionFormat === "Pipes")) { - queryParameterValue = queryParameterValue.join(delimiter); - } - result.set(queryParameter.mapper.serializedName || getPathStringFromParameter(queryParameter), queryParameterValue); - } - } - } - return { - queryParams: result, - sequenceParams, - }; -} -function simpleParseQueryParams(queryString) { - const result = new Map(); - if (!queryString || queryString[0] !== "?") { - return result; - } - // remove the leading ? - queryString = queryString.slice(1); - const pairs = queryString.split("&"); - for (const pair of pairs) { - const [name, value] = pair.split("=", 2); - const existingValue = result.get(name); - if (existingValue) { - if (Array.isArray(existingValue)) { - existingValue.push(value); - } - else { - result.set(name, [existingValue, value]); - } - } - else { - result.set(name, value); - } - } - return result; -} -/** @internal */ -export function appendQueryParams(url, queryParams, sequenceParams, noOverwrite = false) { - if (queryParams.size === 0) { - return url; - } - const parsedUrl = new URL(url); - // QUIRK: parsedUrl.searchParams will have their name/value pairs decoded, which - // can change their meaning to the server, such as in the case of a SAS signature. - // To avoid accidentally un-encoding a query param, we parse the key/values ourselves - const combinedParams = simpleParseQueryParams(parsedUrl.search); - for (const [name, value] of queryParams) { - const existingValue = combinedParams.get(name); - if (Array.isArray(existingValue)) { - if (Array.isArray(value)) { - existingValue.push(...value); - const valueSet = new Set(existingValue); - combinedParams.set(name, Array.from(valueSet)); - } - else { - existingValue.push(value); - } - } - else if (existingValue) { - if (Array.isArray(value)) { - value.unshift(existingValue); - } - else if (sequenceParams.has(name)) { - combinedParams.set(name, [existingValue, value]); - } - if (!noOverwrite) { - combinedParams.set(name, value); - } - } - else { - combinedParams.set(name, value); - } - } - const searchPieces = []; - for (const [name, value] of combinedParams) { - if (typeof value === "string") { - searchPieces.push(`${name}=${value}`); - } - else if (Array.isArray(value)) { - // QUIRK: If we get an array of values, include multiple key/value pairs - for (const subValue of value) { - searchPieces.push(`${name}=${subValue}`); - } - } - else { - searchPieces.push(`${name}=${value}`); - } - } - // QUIRK: we have to set search manually as searchParams will encode comma when it shouldn't. - parsedUrl.search = searchPieces.length ? `?${searchPieces.join("&")}` : ""; - return parsedUrl.toString(); -} -//# sourceMappingURL=urlHelpers.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-client/dist/esm/utils.js b/claude-code-source/node_modules/@azure/core-client/dist/esm/utils.js deleted file mode 100644 index ca2bf052..00000000 --- a/claude-code-source/node_modules/@azure/core-client/dist/esm/utils.js +++ /dev/null @@ -1,115 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * A type guard for a primitive response body. - * @param value - Value to test - * - * @internal - */ -export function isPrimitiveBody(value, mapperTypeName) { - return (mapperTypeName !== "Composite" && - mapperTypeName !== "Dictionary" && - (typeof value === "string" || - typeof value === "number" || - typeof value === "boolean" || - (mapperTypeName === null || mapperTypeName === void 0 ? void 0 : mapperTypeName.match(/^(Date|DateTime|DateTimeRfc1123|UnixTime|ByteArray|Base64Url)$/i)) !== - null || - value === undefined || - value === null)); -} -const validateISODuration = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; -/** - * Returns true if the given string is in ISO 8601 format. - * @param value - The value to be validated for ISO 8601 duration format. - * @internal - */ -export function isDuration(value) { - return validateISODuration.test(value); -} -const validUuidRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/i; -/** - * Returns true if the provided uuid is valid. - * - * @param uuid - The uuid that needs to be validated. - * - * @internal - */ -export function isValidUuid(uuid) { - return validUuidRegex.test(uuid); -} -/** - * Maps the response as follows: - * - wraps the response body if needed (typically if its type is primitive). - * - returns null if the combination of the headers and the body is empty. - * - otherwise, returns the combination of the headers and the body. - * - * @param responseObject - a representation of the parsed response - * @returns the response that will be returned to the user which can be null and/or wrapped - * - * @internal - */ -function handleNullableResponseAndWrappableBody(responseObject) { - const combinedHeadersAndBody = Object.assign(Object.assign({}, responseObject.headers), responseObject.body); - if (responseObject.hasNullableType && - Object.getOwnPropertyNames(combinedHeadersAndBody).length === 0) { - return responseObject.shouldWrapBody ? { body: null } : null; - } - else { - return responseObject.shouldWrapBody - ? Object.assign(Object.assign({}, responseObject.headers), { body: responseObject.body }) : combinedHeadersAndBody; - } -} -/** - * Take a `FullOperationResponse` and turn it into a flat - * response object to hand back to the consumer. - * @param fullResponse - The processed response from the operation request - * @param responseSpec - The response map from the OperationSpec - * - * @internal - */ -export function flattenResponse(fullResponse, responseSpec) { - var _a, _b; - const parsedHeaders = fullResponse.parsedHeaders; - // head methods never have a body, but we return a boolean set to body property - // to indicate presence/absence of the resource - if (fullResponse.request.method === "HEAD") { - return Object.assign(Object.assign({}, parsedHeaders), { body: fullResponse.parsedBody }); - } - const bodyMapper = responseSpec && responseSpec.bodyMapper; - const isNullable = Boolean(bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.nullable); - const expectedBodyTypeName = bodyMapper === null || bodyMapper === void 0 ? void 0 : bodyMapper.type.name; - /** If the body is asked for, we look at the expected body type to handle it */ - if (expectedBodyTypeName === "Stream") { - return Object.assign(Object.assign({}, parsedHeaders), { blobBody: fullResponse.blobBody, readableStreamBody: fullResponse.readableStreamBody }); - } - const modelProperties = (expectedBodyTypeName === "Composite" && - bodyMapper.type.modelProperties) || - {}; - const isPageableResponse = Object.keys(modelProperties).some((k) => modelProperties[k].serializedName === ""); - if (expectedBodyTypeName === "Sequence" || isPageableResponse) { - const arrayResponse = (_a = fullResponse.parsedBody) !== null && _a !== void 0 ? _a : []; - for (const key of Object.keys(modelProperties)) { - if (modelProperties[key].serializedName) { - arrayResponse[key] = (_b = fullResponse.parsedBody) === null || _b === void 0 ? void 0 : _b[key]; - } - } - if (parsedHeaders) { - for (const key of Object.keys(parsedHeaders)) { - arrayResponse[key] = parsedHeaders[key]; - } - } - return isNullable && - !fullResponse.parsedBody && - !parsedHeaders && - Object.getOwnPropertyNames(modelProperties).length === 0 - ? null - : arrayResponse; - } - return handleNullableResponseAndWrappableBody({ - body: fullResponse.parsedBody, - headers: parsedHeaders, - hasNullableType: isNullable, - shouldWrapBody: isPrimitiveBody(fullResponse.parsedBody, expectedBodyTypeName), - }); -} -//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/constants.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/constants.js deleted file mode 100644 index d63b2b98..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/constants.js +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -export const SDK_VERSION = "1.21.0"; -export const DEFAULT_RETRY_POLICY_COUNT = 3; -//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/createPipelineFromOptions.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/createPipelineFromOptions.js deleted file mode 100644 index 8cc8514c..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/createPipelineFromOptions.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { logPolicy } from "./policies/logPolicy.js"; -import { createEmptyPipeline } from "./pipeline.js"; -import { redirectPolicy } from "./policies/redirectPolicy.js"; -import { userAgentPolicy } from "./policies/userAgentPolicy.js"; -import { multipartPolicy, multipartPolicyName } from "./policies/multipartPolicy.js"; -import { decompressResponsePolicy } from "./policies/decompressResponsePolicy.js"; -import { defaultRetryPolicy } from "./policies/defaultRetryPolicy.js"; -import { formDataPolicy } from "./policies/formDataPolicy.js"; -import { isNodeLike } from "@azure/core-util"; -import { proxyPolicy } from "./policies/proxyPolicy.js"; -import { setClientRequestIdPolicy } from "./policies/setClientRequestIdPolicy.js"; -import { agentPolicy } from "./policies/agentPolicy.js"; -import { tlsPolicy } from "./policies/tlsPolicy.js"; -import { tracingPolicy } from "./policies/tracingPolicy.js"; -import { wrapAbortSignalLikePolicy } from "./policies/wrapAbortSignalLikePolicy.js"; -/** - * Create a new pipeline with a default set of customizable policies. - * @param options - Options to configure a custom pipeline. - */ -export function createPipelineFromOptions(options) { - var _a; - const pipeline = createEmptyPipeline(); - if (isNodeLike) { - if (options.agent) { - pipeline.addPolicy(agentPolicy(options.agent)); - } - if (options.tlsOptions) { - pipeline.addPolicy(tlsPolicy(options.tlsOptions)); - } - pipeline.addPolicy(proxyPolicy(options.proxyOptions)); - pipeline.addPolicy(decompressResponsePolicy()); - } - pipeline.addPolicy(wrapAbortSignalLikePolicy()); - pipeline.addPolicy(formDataPolicy(), { beforePolicies: [multipartPolicyName] }); - pipeline.addPolicy(userAgentPolicy(options.userAgentOptions)); - pipeline.addPolicy(setClientRequestIdPolicy((_a = options.telemetryOptions) === null || _a === void 0 ? void 0 : _a.clientRequestIdHeaderName)); - // The multipart policy is added after policies with no phase, so that - // policies can be added between it and formDataPolicy to modify - // properties (e.g., making the boundary constant in recorded tests). - pipeline.addPolicy(multipartPolicy(), { afterPhase: "Deserialize" }); - pipeline.addPolicy(defaultRetryPolicy(options.retryOptions), { phase: "Retry" }); - pipeline.addPolicy(tracingPolicy(Object.assign(Object.assign({}, options.userAgentOptions), options.loggingOptions)), { - afterPhase: "Retry", - }); - if (isNodeLike) { - // Both XHR and Fetch expect to handle redirects automatically, - // so only include this policy when we're in Node. - pipeline.addPolicy(redirectPolicy(options.redirectOptions), { afterPhase: "Retry" }); - } - pipeline.addPolicy(logPolicy(options.loggingOptions), { afterPhase: "Sign" }); - return pipeline; -} -//# sourceMappingURL=createPipelineFromOptions.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/defaultHttpClient.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/defaultHttpClient.js deleted file mode 100644 index b031abf8..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/defaultHttpClient.js +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createDefaultHttpClient as tspCreateDefaultHttpClient } from "@typespec/ts-http-runtime"; -import { wrapAbortSignalLike } from "./util/wrapAbortSignal.js"; -/** - * Create the correct HttpClient for the current environment. - */ -export function createDefaultHttpClient() { - const client = tspCreateDefaultHttpClient(); - return { - async sendRequest(request) { - // we wrap any AbortSignalLike here since the TypeSpec runtime expects a native AbortSignal. - // 99% of the time, this should be a no-op since a native AbortSignal is passed in. - const { abortSignal, cleanup } = request.abortSignal - ? wrapAbortSignalLike(request.abortSignal) - : {}; - try { - // eslint-disable-next-line no-param-reassign - request.abortSignal = abortSignal; - return await client.sendRequest(request); - } - finally { - cleanup === null || cleanup === void 0 ? void 0 : cleanup(); - } - }, - }; -} -//# sourceMappingURL=defaultHttpClient.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/httpHeaders.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/httpHeaders.js deleted file mode 100644 index 8c0677c3..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/httpHeaders.js +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createHttpHeaders as tspCreateHttpHeaders } from "@typespec/ts-http-runtime"; -/** - * Creates an object that satisfies the `HttpHeaders` interface. - * @param rawHeaders - A simple object representing initial headers - */ -export function createHttpHeaders(rawHeaders) { - return tspCreateHttpHeaders(rawHeaders); -} -//# sourceMappingURL=httpHeaders.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/index.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/index.js deleted file mode 100644 index 6b5609db..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/index.js +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -export { createEmptyPipeline, } from "./pipeline.js"; -export { createPipelineFromOptions, } from "./createPipelineFromOptions.js"; -export { createDefaultHttpClient } from "./defaultHttpClient.js"; -export { createHttpHeaders } from "./httpHeaders.js"; -export { createPipelineRequest } from "./pipelineRequest.js"; -export { RestError, isRestError, } from "./restError.js"; -export { decompressResponsePolicy, decompressResponsePolicyName, } from "./policies/decompressResponsePolicy.js"; -export { exponentialRetryPolicy, exponentialRetryPolicyName, } from "./policies/exponentialRetryPolicy.js"; -export { setClientRequestIdPolicy, setClientRequestIdPolicyName, } from "./policies/setClientRequestIdPolicy.js"; -export { logPolicy, logPolicyName } from "./policies/logPolicy.js"; -export { multipartPolicy, multipartPolicyName } from "./policies/multipartPolicy.js"; -export { proxyPolicy, proxyPolicyName, getDefaultProxySettings } from "./policies/proxyPolicy.js"; -export { redirectPolicy, redirectPolicyName, } from "./policies/redirectPolicy.js"; -export { systemErrorRetryPolicy, systemErrorRetryPolicyName, } from "./policies/systemErrorRetryPolicy.js"; -export { throttlingRetryPolicy, throttlingRetryPolicyName, } from "./policies/throttlingRetryPolicy.js"; -export { retryPolicy, } from "./policies/retryPolicy.js"; -export { tracingPolicy, tracingPolicyName, } from "./policies/tracingPolicy.js"; -export { defaultRetryPolicy, } from "./policies/defaultRetryPolicy.js"; -export { userAgentPolicy, userAgentPolicyName, } from "./policies/userAgentPolicy.js"; -export { tlsPolicy, tlsPolicyName } from "./policies/tlsPolicy.js"; -export { formDataPolicy, formDataPolicyName } from "./policies/formDataPolicy.js"; -export { bearerTokenAuthenticationPolicy, bearerTokenAuthenticationPolicyName, } from "./policies/bearerTokenAuthenticationPolicy.js"; -export { ndJsonPolicy, ndJsonPolicyName } from "./policies/ndJsonPolicy.js"; -export { auxiliaryAuthenticationHeaderPolicy, auxiliaryAuthenticationHeaderPolicyName, } from "./policies/auxiliaryAuthenticationHeaderPolicy.js"; -export { agentPolicy, agentPolicyName } from "./policies/agentPolicy.js"; -export { createFile, createFileFromStream, } from "./util/file.js"; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/log.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/log.js deleted file mode 100644 index 6e3a66a4..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/log.js +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createClientLogger } from "@azure/logger"; -export const logger = createClientLogger("core-rest-pipeline"); -//# sourceMappingURL=log.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/pipeline.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/pipeline.js deleted file mode 100644 index 566258a9..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/pipeline.js +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createEmptyPipeline as tspCreateEmptyPipeline } from "@typespec/ts-http-runtime"; -/** - * Creates a totally empty pipeline. - * Useful for testing or creating a custom one. - */ -export function createEmptyPipeline() { - return tspCreateEmptyPipeline(); -} -//# sourceMappingURL=pipeline.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/pipelineRequest.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/pipelineRequest.js deleted file mode 100644 index 463dac5e..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/pipelineRequest.js +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createPipelineRequest as tspCreatePipelineRequest, } from "@typespec/ts-http-runtime"; -/** - * Creates a new pipeline request with the given options. - * This method is to allow for the easy setting of default values and not required. - * @param options - The options to create the request with. - */ -export function createPipelineRequest(options) { - // Cast required due to difference between ts-http-runtime requiring AbortSignal while core-rest-pipeline allows - // the more generic AbortSignalLike. The wrapAbortSignalLike pipeline policy will take care of ensuring that any AbortSignalLike in the request - // is converted into a true AbortSignal. - return tspCreatePipelineRequest(options); -} -//# sourceMappingURL=pipelineRequest.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/agentPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/agentPolicy.js deleted file mode 100644 index b4f11e8a..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/agentPolicy.js +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { agentPolicyName as tspAgentPolicyName, agentPolicy as tspAgentPolicy, } from "@typespec/ts-http-runtime/internal/policies"; -/** - * Name of the Agent Policy - */ -export const agentPolicyName = tspAgentPolicyName; -/** - * Gets a pipeline policy that sets http.agent - */ -export function agentPolicy(agent) { - return tspAgentPolicy(agent); -} -//# sourceMappingURL=agentPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/bearerTokenAuthenticationPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/bearerTokenAuthenticationPolicy.js deleted file mode 100644 index 6ace777a..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/bearerTokenAuthenticationPolicy.js +++ /dev/null @@ -1,238 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createTokenCycler } from "../util/tokenCycler.js"; -import { logger as coreLogger } from "../log.js"; -import { isRestError } from "../restError.js"; -/** - * The programmatic identifier of the bearerTokenAuthenticationPolicy. - */ -export const bearerTokenAuthenticationPolicyName = "bearerTokenAuthenticationPolicy"; -/** - * Try to send the given request. - * - * When a response is received, returns a tuple of the response received and, if the response was received - * inside a thrown RestError, the RestError that was thrown. - * - * Otherwise, if an error was thrown while sending the request that did not provide an underlying response, it - * will be rethrown. - */ -async function trySendRequest(request, next) { - try { - return [await next(request), undefined]; - } - catch (e) { - if (isRestError(e) && e.response) { - return [e.response, e]; - } - else { - throw e; - } - } -} -/** - * Default authorize request handler - */ -async function defaultAuthorizeRequest(options) { - const { scopes, getAccessToken, request } = options; - // Enable CAE true by default - const getTokenOptions = { - abortSignal: request.abortSignal, - tracingOptions: request.tracingOptions, - enableCae: true, - }; - const accessToken = await getAccessToken(scopes, getTokenOptions); - if (accessToken) { - options.request.headers.set("Authorization", `Bearer ${accessToken.token}`); - } -} -/** - * We will retrieve the challenge only if the response status code was 401, - * and if the response contained the header "WWW-Authenticate" with a non-empty value. - */ -function isChallengeResponse(response) { - return response.status === 401 && response.headers.has("WWW-Authenticate"); -} -/** - * Re-authorize the request for CAE challenge. - * The response containing the challenge is `options.response`. - * If this method returns true, the underlying request will be sent once again. - */ -async function authorizeRequestOnCaeChallenge(onChallengeOptions, caeClaims) { - var _a; - const { scopes } = onChallengeOptions; - const accessToken = await onChallengeOptions.getAccessToken(scopes, { - enableCae: true, - claims: caeClaims, - }); - if (!accessToken) { - return false; - } - onChallengeOptions.request.headers.set("Authorization", `${(_a = accessToken.tokenType) !== null && _a !== void 0 ? _a : "Bearer"} ${accessToken.token}`); - return true; -} -/** - * A policy that can request a token from a TokenCredential implementation and - * then apply it to the Authorization header of a request as a Bearer token. - */ -export function bearerTokenAuthenticationPolicy(options) { - var _a, _b, _c; - const { credential, scopes, challengeCallbacks } = options; - const logger = options.logger || coreLogger; - const callbacks = { - authorizeRequest: (_b = (_a = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequest) === null || _a === void 0 ? void 0 : _a.bind(challengeCallbacks)) !== null && _b !== void 0 ? _b : defaultAuthorizeRequest, - authorizeRequestOnChallenge: (_c = challengeCallbacks === null || challengeCallbacks === void 0 ? void 0 : challengeCallbacks.authorizeRequestOnChallenge) === null || _c === void 0 ? void 0 : _c.bind(challengeCallbacks), - }; - // This function encapsulates the entire process of reliably retrieving the token - // The options are left out of the public API until there's demand to configure this. - // Remember to extend `BearerTokenAuthenticationPolicyOptions` with `TokenCyclerOptions` - // in order to pass through the `options` object. - const getAccessToken = credential - ? createTokenCycler(credential /* , options */) - : () => Promise.resolve(null); - return { - name: bearerTokenAuthenticationPolicyName, - /** - * If there's no challenge parameter: - * - It will try to retrieve the token using the cache, or the credential's getToken. - * - Then it will try the next policy with or without the retrieved token. - * - * It uses the challenge parameters to: - * - Skip a first attempt to get the token from the credential if there's no cached token, - * since it expects the token to be retrievable only after the challenge. - * - Prepare the outgoing request if the `prepareRequest` method has been provided. - * - Send an initial request to receive the challenge if it fails. - * - Process a challenge if the response contains it. - * - Retrieve a token with the challenge information, then re-send the request. - */ - async sendRequest(request, next) { - if (!request.url.toLowerCase().startsWith("https://")) { - throw new Error("Bearer token authentication is not permitted for non-TLS protected (non-https) URLs."); - } - await callbacks.authorizeRequest({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - request, - getAccessToken, - logger, - }); - let response; - let error; - let shouldSendRequest; - [response, error] = await trySendRequest(request, next); - if (isChallengeResponse(response)) { - let claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate")); - // Handle CAE by default when receive CAE claim - if (claims) { - let parsedClaim; - // Return the response immediately if claims is not a valid base64 encoded string - try { - parsedClaim = atob(claims); - } - catch (e) { - logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`); - return response; - } - shouldSendRequest = await authorizeRequestOnCaeChallenge({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - response, - request, - getAccessToken, - logger, - }, parsedClaim); - // Send updated request and handle response for RestError - if (shouldSendRequest) { - [response, error] = await trySendRequest(request, next); - } - } - else if (callbacks.authorizeRequestOnChallenge) { - // Handle custom challenges when client provides custom callback - shouldSendRequest = await callbacks.authorizeRequestOnChallenge({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - request, - response, - getAccessToken, - logger, - }); - // Send updated request and handle response for RestError - if (shouldSendRequest) { - [response, error] = await trySendRequest(request, next); - } - // If we get another CAE Claim, we will handle it by default and return whatever value we receive for this - if (isChallengeResponse(response)) { - claims = getCaeChallengeClaims(response.headers.get("WWW-Authenticate")); - if (claims) { - let parsedClaim; - try { - parsedClaim = atob(claims); - } - catch (e) { - logger.warning(`The WWW-Authenticate header contains "claims" that cannot be parsed. Unable to perform the Continuous Access Evaluation authentication flow. Unparsable claims: ${claims}`); - return response; - } - shouldSendRequest = await authorizeRequestOnCaeChallenge({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - response, - request, - getAccessToken, - logger, - }, parsedClaim); - // Send updated request and handle response for RestError - if (shouldSendRequest) { - [response, error] = await trySendRequest(request, next); - } - } - } - } - } - if (error) { - throw error; - } - else { - return response; - } - }, - }; -} -/** - * Converts: `Bearer a="b", c="d", Pop e="f", g="h"`. - * Into: `[ { scheme: 'Bearer', params: { a: 'b', c: 'd' } }, { scheme: 'Pop', params: { e: 'f', g: 'h' } } ]`. - * - * @internal - */ -export function parseChallenges(challenges) { - // Challenge regex seperates the string to individual challenges with different schemes in the format `Scheme a="b", c=d` - // The challenge regex captures parameteres with either quotes values or unquoted values - const challengeRegex = /(\w+)\s+((?:\w+=(?:"[^"]*"|[^,]*),?\s*)+)/g; - // Parameter regex captures the claims group removed from the scheme in the format `a="b"` and `c="d"` - // CAE challenge always have quoted parameters. For more reference, https://learn.microsoft.com/entra/identity-platform/claims-challenge - const paramRegex = /(\w+)="([^"]*)"/g; - const parsedChallenges = []; - let match; - // Iterate over each challenge match - while ((match = challengeRegex.exec(challenges)) !== null) { - const scheme = match[1]; - const paramsString = match[2]; - const params = {}; - let paramMatch; - // Iterate over each parameter match - while ((paramMatch = paramRegex.exec(paramsString)) !== null) { - params[paramMatch[1]] = paramMatch[2]; - } - parsedChallenges.push({ scheme, params }); - } - return parsedChallenges; -} -/** - * Parse a pipeline response and look for a CAE challenge with "Bearer" scheme - * Return the value in the header without parsing the challenge - * @internal - */ -function getCaeChallengeClaims(challenges) { - var _a; - if (!challenges) { - return; - } - // Find all challenges present in the header - const parsedChallenges = parseChallenges(challenges); - return (_a = parsedChallenges.find((x) => x.scheme === "Bearer" && x.params.claims && x.params.error === "insufficient_claims")) === null || _a === void 0 ? void 0 : _a.params.claims; -} -//# sourceMappingURL=bearerTokenAuthenticationPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/decompressResponsePolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/decompressResponsePolicy.js deleted file mode 100644 index 3cb1afb6..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/decompressResponsePolicy.js +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { decompressResponsePolicyName as tspDecompressResponsePolicyName, decompressResponsePolicy as tspDecompressResponsePolicy, } from "@typespec/ts-http-runtime/internal/policies"; -/** - * The programmatic identifier of the decompressResponsePolicy. - */ -export const decompressResponsePolicyName = tspDecompressResponsePolicyName; -/** - * A policy to enable response decompression according to Accept-Encoding header - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding - */ -export function decompressResponsePolicy() { - return tspDecompressResponsePolicy(); -} -//# sourceMappingURL=decompressResponsePolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/defaultRetryPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/defaultRetryPolicy.js deleted file mode 100644 index f3d8f35d..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/defaultRetryPolicy.js +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { defaultRetryPolicyName as tspDefaultRetryPolicyName, defaultRetryPolicy as tspDefaultRetryPolicy, } from "@typespec/ts-http-runtime/internal/policies"; -/** - * Name of the {@link defaultRetryPolicy} - */ -export const defaultRetryPolicyName = tspDefaultRetryPolicyName; -/** - * A policy that retries according to three strategies: - * - When the server sends a 429 response with a Retry-After header. - * - When there are errors in the underlying transport layer (e.g. DNS lookup failures). - * - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay. - */ -export function defaultRetryPolicy(options = {}) { - return tspDefaultRetryPolicy(options); -} -//# sourceMappingURL=defaultRetryPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/formDataPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/formDataPolicy.js deleted file mode 100644 index 3d978c94..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/formDataPolicy.js +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { formDataPolicyName as tspFormDataPolicyName, formDataPolicy as tspFormDataPolicy, } from "@typespec/ts-http-runtime/internal/policies"; -/** - * The programmatic identifier of the formDataPolicy. - */ -export const formDataPolicyName = tspFormDataPolicyName; -/** - * A policy that encodes FormData on the request into the body. - */ -export function formDataPolicy() { - return tspFormDataPolicy(); -} -//# sourceMappingURL=formDataPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/logPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/logPolicy.js deleted file mode 100644 index ee71a286..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/logPolicy.js +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { logger as coreLogger } from "../log.js"; -import { logPolicyName as tspLogPolicyName, logPolicy as tspLogPolicy, } from "@typespec/ts-http-runtime/internal/policies"; -/** - * The programmatic identifier of the logPolicy. - */ -export const logPolicyName = tspLogPolicyName; -/** - * A policy that logs all requests and responses. - * @param options - Options to configure logPolicy. - */ -export function logPolicy(options = {}) { - return tspLogPolicy(Object.assign({ logger: coreLogger.info }, options)); -} -//# sourceMappingURL=logPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/multipartPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/multipartPolicy.js deleted file mode 100644 index e0617750..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/multipartPolicy.js +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { multipartPolicyName as tspMultipartPolicyName, multipartPolicy as tspMultipartPolicy, } from "@typespec/ts-http-runtime/internal/policies"; -import { getRawContent, hasRawContent } from "../util/file.js"; -/** - * Name of multipart policy - */ -export const multipartPolicyName = tspMultipartPolicyName; -/** - * Pipeline policy for multipart requests - */ -export function multipartPolicy() { - const tspPolicy = tspMultipartPolicy(); - return { - name: multipartPolicyName, - sendRequest: async (request, next) => { - if (request.multipartBody) { - for (const part of request.multipartBody.parts) { - if (hasRawContent(part.body)) { - part.body = getRawContent(part.body); - } - } - } - return tspPolicy.sendRequest(request, next); - }, - }; -} -//# sourceMappingURL=multipartPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/proxyPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/proxyPolicy.js deleted file mode 100644 index 092b1ef3..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/proxyPolicy.js +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { proxyPolicy as tspProxyPolicy, proxyPolicyName as tspProxyPolicyName, getDefaultProxySettings as tspGetDefaultProxySettings, } from "@typespec/ts-http-runtime/internal/policies"; -/** - * The programmatic identifier of the proxyPolicy. - */ -export const proxyPolicyName = tspProxyPolicyName; -/** - * This method converts a proxy url into `ProxySettings` for use with ProxyPolicy. - * If no argument is given, it attempts to parse a proxy URL from the environment - * variables `HTTPS_PROXY` or `HTTP_PROXY`. - * @param proxyUrl - The url of the proxy to use. May contain authentication information. - * @deprecated - Internally this method is no longer necessary when setting proxy information. - */ -export function getDefaultProxySettings(proxyUrl) { - return tspGetDefaultProxySettings(proxyUrl); -} -/** - * A policy that allows one to apply proxy settings to all requests. - * If not passed static settings, they will be retrieved from the HTTPS_PROXY - * or HTTP_PROXY environment variables. - * @param proxySettings - ProxySettings to use on each request. - * @param options - additional settings, for example, custom NO_PROXY patterns - */ -export function proxyPolicy(proxySettings, options) { - return tspProxyPolicy(proxySettings, options); -} -//# sourceMappingURL=proxyPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/redirectPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/redirectPolicy.js deleted file mode 100644 index 503c33e3..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/redirectPolicy.js +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { redirectPolicyName as tspRedirectPolicyName, redirectPolicy as tspRedirectPolicy, } from "@typespec/ts-http-runtime/internal/policies"; -/** - * The programmatic identifier of the redirectPolicy. - */ -export const redirectPolicyName = tspRedirectPolicyName; -/** - * A policy to follow Location headers from the server in order - * to support server-side redirection. - * In the browser, this policy is not used. - * @param options - Options to control policy behavior. - */ -export function redirectPolicy(options = {}) { - return tspRedirectPolicy(options); -} -//# sourceMappingURL=redirectPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/retryPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/retryPolicy.js deleted file mode 100644 index 748f1a2b..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/retryPolicy.js +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createClientLogger } from "@azure/logger"; -import { DEFAULT_RETRY_POLICY_COUNT } from "../constants.js"; -import { retryPolicy as tspRetryPolicy, } from "@typespec/ts-http-runtime/internal/policies"; -const retryPolicyLogger = createClientLogger("core-rest-pipeline retryPolicy"); -/** - * retryPolicy is a generic policy to enable retrying requests when certain conditions are met - */ -export function retryPolicy(strategies, options = { maxRetries: DEFAULT_RETRY_POLICY_COUNT }) { - // Cast is required since the TSP runtime retry strategy type is slightly different - // very deep down (using real AbortSignal vs. AbortSignalLike in RestError). - // In practice the difference doesn't actually matter. - return tspRetryPolicy(strategies, Object.assign({ logger: retryPolicyLogger }, options)); -} -//# sourceMappingURL=retryPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/setClientRequestIdPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/setClientRequestIdPolicy.js deleted file mode 100644 index 4bbf2822..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/setClientRequestIdPolicy.js +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * The programmatic identifier of the setClientRequestIdPolicy. - */ -export const setClientRequestIdPolicyName = "setClientRequestIdPolicy"; -/** - * Each PipelineRequest gets a unique id upon creation. - * This policy passes that unique id along via an HTTP header to enable better - * telemetry and tracing. - * @param requestIdHeaderName - The name of the header to pass the request ID to. - */ -export function setClientRequestIdPolicy(requestIdHeaderName = "x-ms-client-request-id") { - return { - name: setClientRequestIdPolicyName, - async sendRequest(request, next) { - if (!request.headers.has(requestIdHeaderName)) { - request.headers.set(requestIdHeaderName, request.requestId); - } - return next(request); - }, - }; -} -//# sourceMappingURL=setClientRequestIdPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/tlsPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/tlsPolicy.js deleted file mode 100644 index d8a21dda..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/tlsPolicy.js +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { tlsPolicy as tspTlsPolicy, tlsPolicyName as tspTlsPolicyName, } from "@typespec/ts-http-runtime/internal/policies"; -/** - * Name of the TLS Policy - */ -export const tlsPolicyName = tspTlsPolicyName; -/** - * Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication. - */ -export function tlsPolicy(tlsSettings) { - return tspTlsPolicy(tlsSettings); -} -//# sourceMappingURL=tlsPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/tracingPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/tracingPolicy.js deleted file mode 100644 index a54c6332..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/tracingPolicy.js +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createTracingClient, } from "@azure/core-tracing"; -import { SDK_VERSION } from "../constants.js"; -import { getUserAgentValue } from "../util/userAgent.js"; -import { logger } from "../log.js"; -import { getErrorMessage, isError } from "@azure/core-util"; -import { isRestError } from "../restError.js"; -import { Sanitizer } from "@typespec/ts-http-runtime/internal/util"; -/** - * The programmatic identifier of the tracingPolicy. - */ -export const tracingPolicyName = "tracingPolicy"; -/** - * A simple policy to create OpenTelemetry Spans for each request made by the pipeline - * that has SpanOptions with a parent. - * Requests made without a parent Span will not be recorded. - * @param options - Options to configure the telemetry logged by the tracing policy. - */ -export function tracingPolicy(options = {}) { - const userAgentPromise = getUserAgentValue(options.userAgentPrefix); - const sanitizer = new Sanitizer({ - additionalAllowedQueryParameters: options.additionalAllowedQueryParameters, - }); - const tracingClient = tryCreateTracingClient(); - return { - name: tracingPolicyName, - async sendRequest(request, next) { - var _a; - if (!tracingClient) { - return next(request); - } - const userAgent = await userAgentPromise; - const spanAttributes = { - "http.url": sanitizer.sanitizeUrl(request.url), - "http.method": request.method, - "http.user_agent": userAgent, - requestId: request.requestId, - }; - if (userAgent) { - spanAttributes["http.user_agent"] = userAgent; - } - const { span, tracingContext } = (_a = tryCreateSpan(tracingClient, request, spanAttributes)) !== null && _a !== void 0 ? _a : {}; - if (!span || !tracingContext) { - return next(request); - } - try { - const response = await tracingClient.withContext(tracingContext, next, request); - tryProcessResponse(span, response); - return response; - } - catch (err) { - tryProcessError(span, err); - throw err; - } - }, - }; -} -function tryCreateTracingClient() { - try { - return createTracingClient({ - namespace: "", - packageName: "@azure/core-rest-pipeline", - packageVersion: SDK_VERSION, - }); - } - catch (e) { - logger.warning(`Error when creating the TracingClient: ${getErrorMessage(e)}`); - return undefined; - } -} -function tryCreateSpan(tracingClient, request, spanAttributes) { - try { - // As per spec, we do not need to differentiate between HTTP and HTTPS in span name. - const { span, updatedOptions } = tracingClient.startSpan(`HTTP ${request.method}`, { tracingOptions: request.tracingOptions }, { - spanKind: "client", - spanAttributes, - }); - // If the span is not recording, don't do any more work. - if (!span.isRecording()) { - span.end(); - return undefined; - } - // set headers - const headers = tracingClient.createRequestHeaders(updatedOptions.tracingOptions.tracingContext); - for (const [key, value] of Object.entries(headers)) { - request.headers.set(key, value); - } - return { span, tracingContext: updatedOptions.tracingOptions.tracingContext }; - } - catch (e) { - logger.warning(`Skipping creating a tracing span due to an error: ${getErrorMessage(e)}`); - return undefined; - } -} -function tryProcessError(span, error) { - try { - span.setStatus({ - status: "error", - error: isError(error) ? error : undefined, - }); - if (isRestError(error) && error.statusCode) { - span.setAttribute("http.status_code", error.statusCode); - } - span.end(); - } - catch (e) { - logger.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`); - } -} -function tryProcessResponse(span, response) { - try { - span.setAttribute("http.status_code", response.status); - const serviceRequestId = response.headers.get("x-ms-request-id"); - if (serviceRequestId) { - span.setAttribute("serviceRequestId", serviceRequestId); - } - // Per semantic conventions, only set the status to error if the status code is 4xx or 5xx. - // Otherwise, the status MUST remain unset. - // https://opentelemetry.io/docs/specs/semconv/http/http-spans/#status - if (response.status >= 400) { - span.setStatus({ - status: "error", - }); - } - span.end(); - } - catch (e) { - logger.warning(`Skipping tracing span processing due to an error: ${getErrorMessage(e)}`); - } -} -//# sourceMappingURL=tracingPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/userAgentPolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/userAgentPolicy.js deleted file mode 100644 index 57d47077..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/userAgentPolicy.js +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { getUserAgentHeaderName, getUserAgentValue } from "../util/userAgent.js"; -const UserAgentHeaderName = getUserAgentHeaderName(); -/** - * The programmatic identifier of the userAgentPolicy. - */ -export const userAgentPolicyName = "userAgentPolicy"; -/** - * A policy that sets the User-Agent header (or equivalent) to reflect - * the library version. - * @param options - Options to customize the user agent value. - */ -export function userAgentPolicy(options = {}) { - const userAgentValue = getUserAgentValue(options.userAgentPrefix); - return { - name: userAgentPolicyName, - async sendRequest(request, next) { - if (!request.headers.has(UserAgentHeaderName)) { - request.headers.set(UserAgentHeaderName, await userAgentValue); - } - return next(request); - }, - }; -} -//# sourceMappingURL=userAgentPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/wrapAbortSignalLikePolicy.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/wrapAbortSignalLikePolicy.js deleted file mode 100644 index 4487214e..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/policies/wrapAbortSignalLikePolicy.js +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { wrapAbortSignalLike } from "../util/wrapAbortSignal.js"; -export const wrapAbortSignalLikePolicyName = "wrapAbortSignalLikePolicy"; -/** - * Policy that ensure that any AbortSignalLike is wrapped in a native AbortSignal for processing by the pipeline. - * Since the ts-http-runtime expects a native AbortSignal, this policy is used to ensure that any AbortSignalLike is wrapped in a native AbortSignal. - * - * @returns - created policy - */ -export function wrapAbortSignalLikePolicy() { - return { - name: wrapAbortSignalLikePolicyName, - sendRequest: async (request, next) => { - if (!request.abortSignal) { - return next(request); - } - const { abortSignal, cleanup } = wrapAbortSignalLike(request.abortSignal); - // eslint-disable-next-line no-param-reassign - request.abortSignal = abortSignal; - try { - return await next(request); - } - finally { - cleanup === null || cleanup === void 0 ? void 0 : cleanup(); - } - }, - }; -} -//# sourceMappingURL=wrapAbortSignalLikePolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/restError.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/restError.js deleted file mode 100644 index b2e2161f..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/restError.js +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { RestError as TspRestError, isRestError as tspIsRestError, } from "@typespec/ts-http-runtime"; -/** - * A custom error type for failed pipeline requests. - */ -// eslint-disable-next-line @typescript-eslint/no-redeclare -export const RestError = TspRestError; -/** - * Typeguard for RestError - * @param e - Something caught by a catch clause. - */ -export function isRestError(e) { - return tspIsRestError(e); -} -//# sourceMappingURL=restError.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/file.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/file.js deleted file mode 100644 index e8951bfa..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/file.js +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { isNodeLike } from "@azure/core-util"; -function isNodeReadableStream(x) { - return Boolean(x && typeof x["pipe"] === "function"); -} -const unimplementedMethods = { - arrayBuffer: () => { - throw new Error("Not implemented"); - }, - bytes: () => { - throw new Error("Not implemented"); - }, - slice: () => { - throw new Error("Not implemented"); - }, - text: () => { - throw new Error("Not implemented"); - }, -}; -/** - * Private symbol used as key on objects created using createFile containing the - * original source of the file object. - * - * This is used in Node to access the original Node stream without using Blob#stream, which - * returns a web stream. This is done to avoid a couple of bugs to do with Blob#stream and - * Readable#to/fromWeb in Node versions we support: - * - https://github.com/nodejs/node/issues/42694 (fixed in Node 18.14) - * - https://github.com/nodejs/node/issues/48916 (fixed in Node 20.6) - * - * Once these versions are no longer supported, we may be able to stop doing this. - * - * @internal - */ -const rawContent = Symbol("rawContent"); -/** - * Type guard to check if a given object is a blob-like object with a raw content property. - */ -export function hasRawContent(x) { - return typeof x[rawContent] === "function"; -} -/** - * Extract the raw content from a given blob-like object. If the input was created using createFile - * or createFileFromStream, the exact content passed into createFile/createFileFromStream will be used. - * For true instances of Blob and File, returns the actual blob. - * - * @internal - */ -export function getRawContent(blob) { - if (hasRawContent(blob)) { - return blob[rawContent](); - } - else { - return blob; - } -} -/** - * Create an object that implements the File interface. This object is intended to be - * passed into RequestBodyType.formData, and is not guaranteed to work as expected in - * other situations. - * - * Use this function to: - * - Create a File object for use in RequestBodyType.formData in environments where the - * global File object is unavailable. - * - Create a File-like object from a readable stream without reading the stream into memory. - * - * @param stream - the content of the file as a callback returning a stream. When a File object made using createFile is - * passed in a request's form data map, the stream will not be read into memory - * and instead will be streamed when the request is made. In the event of a retry, the - * stream needs to be read again, so this callback SHOULD return a fresh stream if possible. - * @param name - the name of the file. - * @param options - optional metadata about the file, e.g. file name, file size, MIME type. - */ -export function createFileFromStream(stream, name, options = {}) { - var _a, _b, _c, _d; - return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : new Date().getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: (_d = options.size) !== null && _d !== void 0 ? _d : -1, name, stream: () => { - const s = stream(); - if (isNodeReadableStream(s)) { - throw new Error("Not supported: a Node stream was provided as input to createFileFromStream."); - } - return s; - }, [rawContent]: stream }); -} -/** - * Create an object that implements the File interface. This object is intended to be - * passed into RequestBodyType.formData, and is not guaranteed to work as expected in - * other situations. - * - * Use this function create a File object for use in RequestBodyType.formData in environments where the global File object is unavailable. - * - * @param content - the content of the file as a Uint8Array in memory. - * @param name - the name of the file. - * @param options - optional metadata about the file, e.g. file name, file size, MIME type. - */ -export function createFile(content, name, options = {}) { - var _a, _b, _c; - if (isNodeLike) { - return Object.assign(Object.assign({}, unimplementedMethods), { type: (_a = options.type) !== null && _a !== void 0 ? _a : "", lastModified: (_b = options.lastModified) !== null && _b !== void 0 ? _b : new Date().getTime(), webkitRelativePath: (_c = options.webkitRelativePath) !== null && _c !== void 0 ? _c : "", size: content.byteLength, name, arrayBuffer: async () => content.buffer, stream: () => new Blob([content]).stream(), [rawContent]: () => content }); - } - else { - return new File([content], name, options); - } -} -//# sourceMappingURL=file.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/tokenCycler.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/tokenCycler.js deleted file mode 100644 index 0d522dba..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/tokenCycler.js +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { delay } from "@azure/core-util"; -// Default options for the cycler if none are provided -export const DEFAULT_CYCLER_OPTIONS = { - forcedRefreshWindowInMs: 1000, // Force waiting for a refresh 1s before the token expires - retryIntervalInMs: 3000, // Allow refresh attempts every 3s - refreshWindowInMs: 1000 * 60 * 2, // Start refreshing 2m before expiry -}; -/** - * Converts an an unreliable access token getter (which may resolve with null) - * into an AccessTokenGetter by retrying the unreliable getter in a regular - * interval. - * - * @param getAccessToken - A function that produces a promise of an access token that may fail by returning null. - * @param retryIntervalInMs - The time (in milliseconds) to wait between retry attempts. - * @param refreshTimeout - The timestamp after which the refresh attempt will fail, throwing an exception. - * @returns - A promise that, if it resolves, will resolve with an access token. - */ -async function beginRefresh(getAccessToken, retryIntervalInMs, refreshTimeout) { - // This wrapper handles exceptions gracefully as long as we haven't exceeded - // the timeout. - async function tryGetAccessToken() { - if (Date.now() < refreshTimeout) { - try { - return await getAccessToken(); - } - catch (_a) { - return null; - } - } - else { - const finalToken = await getAccessToken(); - // Timeout is up, so throw if it's still null - if (finalToken === null) { - throw new Error("Failed to refresh access token."); - } - return finalToken; - } - } - let token = await tryGetAccessToken(); - while (token === null) { - await delay(retryIntervalInMs); - token = await tryGetAccessToken(); - } - return token; -} -/** - * Creates a token cycler from a credential, scopes, and optional settings. - * - * A token cycler represents a way to reliably retrieve a valid access token - * from a TokenCredential. It will handle initializing the token, refreshing it - * when it nears expiration, and synchronizes refresh attempts to avoid - * concurrency hazards. - * - * @param credential - the underlying TokenCredential that provides the access - * token - * @param tokenCyclerOptions - optionally override default settings for the cycler - * - * @returns - a function that reliably produces a valid access token - */ -export function createTokenCycler(credential, tokenCyclerOptions) { - let refreshWorker = null; - let token = null; - let tenantId; - const options = Object.assign(Object.assign({}, DEFAULT_CYCLER_OPTIONS), tokenCyclerOptions); - /** - * This little holder defines several predicates that we use to construct - * the rules of refreshing the token. - */ - const cycler = { - /** - * Produces true if a refresh job is currently in progress. - */ - get isRefreshing() { - return refreshWorker !== null; - }, - /** - * Produces true if the cycler SHOULD refresh (we are within the refresh - * window and not already refreshing) - */ - get shouldRefresh() { - var _a; - if (cycler.isRefreshing) { - return false; - } - if ((token === null || token === void 0 ? void 0 : token.refreshAfterTimestamp) && token.refreshAfterTimestamp < Date.now()) { - return true; - } - return ((_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : 0) - options.refreshWindowInMs < Date.now(); - }, - /** - * Produces true if the cycler MUST refresh (null or nearly-expired - * token). - */ - get mustRefresh() { - return (token === null || token.expiresOnTimestamp - options.forcedRefreshWindowInMs < Date.now()); - }, - }; - /** - * Starts a refresh job or returns the existing job if one is already - * running. - */ - function refresh(scopes, getTokenOptions) { - var _a; - if (!cycler.isRefreshing) { - // We bind `scopes` here to avoid passing it around a lot - const tryGetAccessToken = () => credential.getToken(scopes, getTokenOptions); - // Take advantage of promise chaining to insert an assignment to `token` - // before the refresh can be considered done. - refreshWorker = beginRefresh(tryGetAccessToken, options.retryIntervalInMs, - // If we don't have a token, then we should timeout immediately - (_a = token === null || token === void 0 ? void 0 : token.expiresOnTimestamp) !== null && _a !== void 0 ? _a : Date.now()) - .then((_token) => { - refreshWorker = null; - token = _token; - tenantId = getTokenOptions.tenantId; - return token; - }) - .catch((reason) => { - // We also should reset the refresher if we enter a failed state. All - // existing awaiters will throw, but subsequent requests will start a - // new retry chain. - refreshWorker = null; - token = null; - tenantId = undefined; - throw reason; - }); - } - return refreshWorker; - } - return async (scopes, tokenOptions) => { - // - // Simple rules: - // - If we MUST refresh, then return the refresh task, blocking - // the pipeline until a token is available. - // - If we SHOULD refresh, then run refresh but don't return it - // (we can still use the cached token). - // - Return the token, since it's fine if we didn't return in - // step 1. - // - const hasClaimChallenge = Boolean(tokenOptions.claims); - const tenantIdChanged = tenantId !== tokenOptions.tenantId; - if (hasClaimChallenge) { - // If we've received a claim, we know the existing token isn't valid - // We want to clear it so that that refresh worker won't use the old expiration time as a timeout - token = null; - } - // If the tenantId passed in token options is different to the one we have - // Or if we are in claim challenge and the token was rejected and a new access token need to be issued, we need to - // refresh the token with the new tenantId or token. - const mustRefresh = tenantIdChanged || hasClaimChallenge || cycler.mustRefresh; - if (mustRefresh) { - return refresh(scopes, tokenOptions); - } - if (cycler.shouldRefresh) { - refresh(scopes, tokenOptions); - } - return token; - }; -} -//# sourceMappingURL=tokenCycler.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgent.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgent.js deleted file mode 100644 index ed9dc78e..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgent.js +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { getHeaderName, setPlatformSpecificData } from "./userAgentPlatform.js"; -import { SDK_VERSION } from "../constants.js"; -function getUserAgentString(telemetryInfo) { - const parts = []; - for (const [key, value] of telemetryInfo) { - const token = value ? `${key}/${value}` : key; - parts.push(token); - } - return parts.join(" "); -} -/** - * @internal - */ -export function getUserAgentHeaderName() { - return getHeaderName(); -} -/** - * @internal - */ -export async function getUserAgentValue(prefix) { - const runtimeInfo = new Map(); - runtimeInfo.set("core-rest-pipeline", SDK_VERSION); - await setPlatformSpecificData(runtimeInfo); - const defaultAgent = getUserAgentString(runtimeInfo); - const userAgentValue = prefix ? `${prefix} ${defaultAgent}` : defaultAgent; - return userAgentValue; -} -//# sourceMappingURL=userAgent.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgentPlatform.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgentPlatform.js deleted file mode 100644 index f5a2c680..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/userAgentPlatform.js +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import * as os from "node:os"; -import * as process from "node:process"; -/** - * @internal - */ -export function getHeaderName() { - return "User-Agent"; -} -/** - * @internal - */ -export async function setPlatformSpecificData(map) { - if (process && process.versions) { - const versions = process.versions; - if (versions.bun) { - map.set("Bun", versions.bun); - } - else if (versions.deno) { - map.set("Deno", versions.deno); - } - else if (versions.node) { - map.set("Node", versions.node); - } - } - map.set("OS", `(${os.arch()}-${os.type()}-${os.release()})`); -} -//# sourceMappingURL=userAgentPlatform.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/wrapAbortSignal.js b/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/wrapAbortSignal.js deleted file mode 100644 index dbd1fbd5..00000000 --- a/claude-code-source/node_modules/@azure/core-rest-pipeline/dist/esm/util/wrapAbortSignal.js +++ /dev/null @@ -1,31 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * Creates a native AbortSignal which reflects the state of the provided AbortSignalLike. - * If the AbortSignalLike is already a native AbortSignal, it is returned as is. - * @param abortSignalLike - The AbortSignalLike to wrap. - * @returns - An object containing the native AbortSignal and an optional cleanup function. The cleanup function should be called when the AbortSignal is no longer needed. - */ -export function wrapAbortSignalLike(abortSignalLike) { - if (abortSignalLike instanceof AbortSignal) { - return { abortSignal: abortSignalLike }; - } - if (abortSignalLike.aborted) { - return { abortSignal: AbortSignal.abort(abortSignalLike.reason) }; - } - const controller = new AbortController(); - let needsCleanup = true; - function cleanup() { - if (needsCleanup) { - abortSignalLike.removeEventListener("abort", listener); - needsCleanup = false; - } - } - function listener() { - controller.abort(abortSignalLike.reason); - cleanup(); - } - abortSignalLike.addEventListener("abort", listener); - return { abortSignal: controller.signal, cleanup }; -} -//# sourceMappingURL=wrapAbortSignal.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-tracing/dist/commonjs/state.js b/claude-code-source/node_modules/@azure/core-tracing/dist/commonjs/state.js deleted file mode 100644 index 3e781757..00000000 --- a/claude-code-source/node_modules/@azure/core-tracing/dist/commonjs/state.js +++ /dev/null @@ -1,14 +0,0 @@ -"use strict"; -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.state = void 0; -/** - * @internal - * - * Holds the singleton instrumenter, to be shared across CJS and ESM imports. - */ -exports.state = { - instrumenterImplementation: undefined, -}; -//# sourceMappingURL=state-cjs.cjs.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-tracing/dist/esm/index.js b/claude-code-source/node_modules/@azure/core-tracing/dist/esm/index.js deleted file mode 100644 index c2376651..00000000 --- a/claude-code-source/node_modules/@azure/core-tracing/dist/esm/index.js +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -export { useInstrumenter } from "./instrumenter.js"; -export { createTracingClient } from "./tracingClient.js"; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-tracing/dist/esm/instrumenter.js b/claude-code-source/node_modules/@azure/core-tracing/dist/esm/instrumenter.js deleted file mode 100644 index a394aa99..00000000 --- a/claude-code-source/node_modules/@azure/core-tracing/dist/esm/instrumenter.js +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createTracingContext } from "./tracingContext.js"; -import { state } from "./state.js"; -export function createDefaultTracingSpan() { - return { - end: () => { - // noop - }, - isRecording: () => false, - recordException: () => { - // noop - }, - setAttribute: () => { - // noop - }, - setStatus: () => { - // noop - }, - addEvent: () => { - // noop - }, - }; -} -export function createDefaultInstrumenter() { - return { - createRequestHeaders: () => { - return {}; - }, - parseTraceparentHeader: () => { - return undefined; - }, - startSpan: (_name, spanOptions) => { - return { - span: createDefaultTracingSpan(), - tracingContext: createTracingContext({ parentContext: spanOptions.tracingContext }), - }; - }, - withContext(_context, callback, ...callbackArgs) { - return callback(...callbackArgs); - }, - }; -} -/** - * Extends the Azure SDK with support for a given instrumenter implementation. - * - * @param instrumenter - The instrumenter implementation to use. - */ -export function useInstrumenter(instrumenter) { - state.instrumenterImplementation = instrumenter; -} -/** - * Gets the currently set instrumenter, a No-Op instrumenter by default. - * - * @returns The currently set instrumenter - */ -export function getInstrumenter() { - if (!state.instrumenterImplementation) { - state.instrumenterImplementation = createDefaultInstrumenter(); - } - return state.instrumenterImplementation; -} -//# sourceMappingURL=instrumenter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-tracing/dist/esm/state.js b/claude-code-source/node_modules/@azure/core-tracing/dist/esm/state.js deleted file mode 100644 index e42b6638..00000000 --- a/claude-code-source/node_modules/@azure/core-tracing/dist/esm/state.js +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -// @ts-expect-error The recommended approach to sharing module state between ESM and CJS. -// See https://github.com/isaacs/tshy/blob/main/README.md#module-local-state for additional information. -import { state as cjsState } from "../commonjs/state.js"; -/** - * Defines the shared state between CJS and ESM by re-exporting the CJS state. - */ -export const state = cjsState; -//# sourceMappingURL=state.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-tracing/dist/esm/tracingClient.js b/claude-code-source/node_modules/@azure/core-tracing/dist/esm/tracingClient.js deleted file mode 100644 index 3e79edd1..00000000 --- a/claude-code-source/node_modules/@azure/core-tracing/dist/esm/tracingClient.js +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { getInstrumenter } from "./instrumenter.js"; -import { knownContextKeys } from "./tracingContext.js"; -/** - * Creates a new tracing client. - * - * @param options - Options used to configure the tracing client. - * @returns - An instance of {@link TracingClient}. - */ -export function createTracingClient(options) { - const { namespace, packageName, packageVersion } = options; - function startSpan(name, operationOptions, spanOptions) { - var _a; - const startSpanResult = getInstrumenter().startSpan(name, Object.assign(Object.assign({}, spanOptions), { packageName: packageName, packageVersion: packageVersion, tracingContext: (_a = operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions) === null || _a === void 0 ? void 0 : _a.tracingContext })); - let tracingContext = startSpanResult.tracingContext; - const span = startSpanResult.span; - if (!tracingContext.getValue(knownContextKeys.namespace)) { - tracingContext = tracingContext.setValue(knownContextKeys.namespace, namespace); - } - span.setAttribute("az.namespace", tracingContext.getValue(knownContextKeys.namespace)); - const updatedOptions = Object.assign({}, operationOptions, { - tracingOptions: Object.assign(Object.assign({}, operationOptions === null || operationOptions === void 0 ? void 0 : operationOptions.tracingOptions), { tracingContext }), - }); - return { - span, - updatedOptions, - }; - } - async function withSpan(name, operationOptions, callback, spanOptions) { - const { span, updatedOptions } = startSpan(name, operationOptions, spanOptions); - try { - const result = await withContext(updatedOptions.tracingOptions.tracingContext, () => Promise.resolve(callback(updatedOptions, span))); - span.setStatus({ status: "success" }); - return result; - } - catch (err) { - span.setStatus({ status: "error", error: err }); - throw err; - } - finally { - span.end(); - } - } - function withContext(context, callback, ...callbackArgs) { - return getInstrumenter().withContext(context, callback, ...callbackArgs); - } - /** - * Parses a traceparent header value into a span identifier. - * - * @param traceparentHeader - The traceparent header to parse. - * @returns An implementation-specific identifier for the span. - */ - function parseTraceparentHeader(traceparentHeader) { - return getInstrumenter().parseTraceparentHeader(traceparentHeader); - } - /** - * Creates a set of request headers to propagate tracing information to a backend. - * - * @param tracingContext - The context containing the span to serialize. - * @returns The set of headers to add to a request. - */ - function createRequestHeaders(tracingContext) { - return getInstrumenter().createRequestHeaders(tracingContext); - } - return { - startSpan, - withSpan, - withContext, - parseTraceparentHeader, - createRequestHeaders, - }; -} -//# sourceMappingURL=tracingClient.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-tracing/dist/esm/tracingContext.js b/claude-code-source/node_modules/@azure/core-tracing/dist/esm/tracingContext.js deleted file mode 100644 index 46a0bb8e..00000000 --- a/claude-code-source/node_modules/@azure/core-tracing/dist/esm/tracingContext.js +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** @internal */ -export const knownContextKeys = { - span: Symbol.for("@azure/core-tracing span"), - namespace: Symbol.for("@azure/core-tracing namespace"), -}; -/** - * Creates a new {@link TracingContext} with the given options. - * @param options - A set of known keys that may be set on the context. - * @returns A new {@link TracingContext} with the given options. - * - * @internal - */ -export function createTracingContext(options = {}) { - let context = new TracingContextImpl(options.parentContext); - if (options.span) { - context = context.setValue(knownContextKeys.span, options.span); - } - if (options.namespace) { - context = context.setValue(knownContextKeys.namespace, options.namespace); - } - return context; -} -/** @internal */ -export class TracingContextImpl { - constructor(initialContext) { - this._contextMap = - initialContext instanceof TracingContextImpl - ? new Map(initialContext._contextMap) - : new Map(); - } - setValue(key, value) { - const newContext = new TracingContextImpl(this); - newContext._contextMap.set(key, value); - return newContext; - } - getValue(key) { - return this._contextMap.get(key); - } - deleteValue(key) { - const newContext = new TracingContextImpl(this); - newContext._contextMap.delete(key); - return newContext; - } -} -//# sourceMappingURL=tracingContext.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-util/dist/esm/createAbortablePromise.js b/claude-code-source/node_modules/@azure/core-util/dist/esm/createAbortablePromise.js deleted file mode 100644 index b58c71c3..00000000 --- a/claude-code-source/node_modules/@azure/core-util/dist/esm/createAbortablePromise.js +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { AbortError } from "@azure/abort-controller"; -/** - * Creates an abortable promise. - * @param buildPromise - A function that takes the resolve and reject functions as parameters. - * @param options - The options for the abortable promise. - * @returns A promise that can be aborted. - */ -export function createAbortablePromise(buildPromise, options) { - const { cleanupBeforeAbort, abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; - return new Promise((resolve, reject) => { - function rejectOnAbort() { - reject(new AbortError(abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : "The operation was aborted.")); - } - function removeListeners() { - abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.removeEventListener("abort", onAbort); - } - function onAbort() { - cleanupBeforeAbort === null || cleanupBeforeAbort === void 0 ? void 0 : cleanupBeforeAbort(); - removeListeners(); - rejectOnAbort(); - } - if (abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.aborted) { - return rejectOnAbort(); - } - try { - buildPromise((x) => { - removeListeners(); - resolve(x); - }, (x) => { - removeListeners(); - reject(x); - }); - } - catch (err) { - reject(err); - } - abortSignal === null || abortSignal === void 0 ? void 0 : abortSignal.addEventListener("abort", onAbort); - }); -} -//# sourceMappingURL=createAbortablePromise.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-util/dist/esm/delay.js b/claude-code-source/node_modules/@azure/core-util/dist/esm/delay.js deleted file mode 100644 index 4e83133a..00000000 --- a/claude-code-source/node_modules/@azure/core-util/dist/esm/delay.js +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createAbortablePromise } from "./createAbortablePromise.js"; -import { getRandomIntegerInclusive } from "@typespec/ts-http-runtime/internal/util"; -const StandardAbortMessage = "The delay was aborted."; -/** - * A wrapper for setTimeout that resolves a promise after timeInMs milliseconds. - * @param timeInMs - The number of milliseconds to be delayed. - * @param options - The options for delay - currently abort options - * @returns Promise that is resolved after timeInMs - */ -export function delay(timeInMs, options) { - let token; - const { abortSignal, abortErrorMsg } = options !== null && options !== void 0 ? options : {}; - return createAbortablePromise((resolve) => { - token = setTimeout(resolve, timeInMs); - }, { - cleanupBeforeAbort: () => clearTimeout(token), - abortSignal, - abortErrorMsg: abortErrorMsg !== null && abortErrorMsg !== void 0 ? abortErrorMsg : StandardAbortMessage, - }); -} -/** - * Calculates the delay interval for retry attempts using exponential delay with jitter. - * @param retryAttempt - The current retry attempt number. - * @param config - The exponential retry configuration. - * @returns An object containing the calculated retry delay. - */ -export function calculateRetryDelay(retryAttempt, config) { - // Exponentially increase the delay each time - const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); - // Don't let the delay exceed the maximum - const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); - // Allow the final value to have some "jitter" (within 50% of the delay size) so - // that retries across multiple clients don't occur simultaneously. - const retryAfterInMs = clampedDelay / 2 + getRandomIntegerInclusive(0, clampedDelay / 2); - return { retryAfterInMs }; -} -//# sourceMappingURL=delay.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-util/dist/esm/error.js b/claude-code-source/node_modules/@azure/core-util/dist/esm/error.js deleted file mode 100644 index b28f2866..00000000 --- a/claude-code-source/node_modules/@azure/core-util/dist/esm/error.js +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { isError } from "@typespec/ts-http-runtime/internal/util"; -/** - * Given what is thought to be an error object, return the message if possible. - * If the message is missing, returns a stringified version of the input. - * @param e - Something thrown from a try block - * @returns The error message or a string of the input - */ -export function getErrorMessage(e) { - if (isError(e)) { - return e.message; - } - else { - let stringified; - try { - if (typeof e === "object" && e) { - stringified = JSON.stringify(e); - } - else { - stringified = String(e); - } - } - catch (err) { - stringified = "[unable to stringify input]"; - } - return `Unknown error ${stringified}`; - } -} -//# sourceMappingURL=error.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/core-util/dist/esm/index.js b/claude-code-source/node_modules/@azure/core-util/dist/esm/index.js deleted file mode 100644 index 4ce68b72..00000000 --- a/claude-code-source/node_modules/@azure/core-util/dist/esm/index.js +++ /dev/null @@ -1,131 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import * as tspRuntime from "@typespec/ts-http-runtime/internal/util"; -export { cancelablePromiseRace, } from "./aborterUtils.js"; -export { createAbortablePromise, } from "./createAbortablePromise.js"; -export { delay } from "./delay.js"; -export { getErrorMessage } from "./error.js"; -export { isDefined, isObjectWithProperties, objectHasProperty } from "./typeGuards.js"; -/** - * Calculates the delay interval for retry attempts using exponential delay with jitter. - * - * @param retryAttempt - The current retry attempt number. - * - * @param config - The exponential retry configuration. - * - * @returns An object containing the calculated retry delay. - */ -export function calculateRetryDelay(retryAttempt, config) { - return tspRuntime.calculateRetryDelay(retryAttempt, config); -} -/** - * Generates a SHA-256 hash. - * - * @param content - The data to be included in the hash. - * - * @param encoding - The textual encoding to use for the returned hash. - */ -export function computeSha256Hash(content, encoding) { - return tspRuntime.computeSha256Hash(content, encoding); -} -/** - * Generates a SHA-256 HMAC signature. - * - * @param key - The HMAC key represented as a base64 string, used to generate the cryptographic HMAC hash. - * - * @param stringToSign - The data to be signed. - * - * @param encoding - The textual encoding to use for the returned HMAC digest. - */ -export function computeSha256Hmac(key, stringToSign, encoding) { - return tspRuntime.computeSha256Hmac(key, stringToSign, encoding); -} -/** - * Returns a random integer value between a lower and upper bound, inclusive of both bounds. Note that this uses Math.random and isn't secure. If you need to use this for any kind of security purpose, find a better source of random. - * - * @param min - The smallest integer value allowed. - * - * @param max - The largest integer value allowed. - */ -export function getRandomIntegerInclusive(min, max) { - return tspRuntime.getRandomIntegerInclusive(min, max); -} -/** - * Typeguard for an error object shape (has name and message) - * - * @param e - Something caught by a catch clause. - */ -export function isError(e) { - return tspRuntime.isError(e); -} -/** - * Helper to determine when an input is a generic JS object. - * - * @returns true when input is an object type that is not null, Array, RegExp, or Date. - */ -export function isObject(input) { - return tspRuntime.isObject(input); -} -/** - * Generated Universally Unique Identifier - * - * @returns RFC4122 v4 UUID. - */ -export function randomUUID() { - return tspRuntime.randomUUID(); -} -/** - * A constant that indicates whether the environment the code is running is a Web Browser. - */ -export const isBrowser = tspRuntime.isBrowser; -/** - * A constant that indicates whether the environment the code is running is Bun.sh. - */ -export const isBun = tspRuntime.isBun; -/** - * A constant that indicates whether the environment the code is running is Deno. - */ -export const isDeno = tspRuntime.isDeno; -/** - * A constant that indicates whether the environment the code is running is a Node.js compatible environment. - * - * @deprecated - * - * Use `isNodeLike` instead. - */ -export const isNode = tspRuntime.isNodeLike; -/** - * A constant that indicates whether the environment the code is running is a Node.js compatible environment. - */ -export const isNodeLike = tspRuntime.isNodeLike; -/** - * A constant that indicates whether the environment the code is running is Node.JS. - */ -export const isNodeRuntime = tspRuntime.isNodeRuntime; -/** - * A constant that indicates whether the environment the code is running is in React-Native. - */ -export const isReactNative = tspRuntime.isReactNative; -/** - * A constant that indicates whether the environment the code is running is a Web Worker. - */ -export const isWebWorker = tspRuntime.isWebWorker; -/** - * The helper that transforms bytes with specific character encoding into string - * @param bytes - the uint8array bytes - * @param format - the format we use to encode the byte - * @returns a string of the encoded string - */ -export function uint8ArrayToString(bytes, format) { - return tspRuntime.uint8ArrayToString(bytes, format); -} -/** - * The helper that transforms string to specific character encoded bytes array. - * @param value - the string to be converted - * @param format - the format we use to decode the value - * @returns a uint8array - */ -export function stringToUint8Array(value, format) { - return tspRuntime.stringToUint8Array(value, format); -} -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/client/identityClient.js b/claude-code-source/node_modules/@azure/identity/dist/esm/client/identityClient.js deleted file mode 100644 index ba7eca57..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/client/identityClient.js +++ /dev/null @@ -1,248 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { ServiceClient } from "@azure/core-client"; -import { isNode } from "@azure/core-util"; -import { createHttpHeaders, createPipelineRequest } from "@azure/core-rest-pipeline"; -import { AuthenticationError, AuthenticationErrorName } from "../errors.js"; -import { getIdentityTokenEndpointSuffix } from "../util/identityTokenEndpoint.js"; -import { DefaultAuthorityHost, SDK_VERSION } from "../constants.js"; -import { tracingClient } from "../util/tracing.js"; -import { logger } from "../util/logging.js"; -import { parseExpirationTimestamp, parseRefreshTimestamp, } from "../credentials/managedIdentityCredential/utils.js"; -const noCorrelationId = "noCorrelationId"; -/** - * @internal - */ -export function getIdentityClientAuthorityHost(options) { - // The authorityHost can come from options or from the AZURE_AUTHORITY_HOST environment variable. - let authorityHost = options === null || options === void 0 ? void 0 : options.authorityHost; - // The AZURE_AUTHORITY_HOST environment variable can only be provided in Node.js. - if (isNode) { - authorityHost = authorityHost !== null && authorityHost !== void 0 ? authorityHost : process.env.AZURE_AUTHORITY_HOST; - } - // If the authorityHost is not provided, we use the default one from the public cloud: https://login.microsoftonline.com - return authorityHost !== null && authorityHost !== void 0 ? authorityHost : DefaultAuthorityHost; -} -/** - * The network module used by the Identity credentials. - * - * It allows for credentials to abort any pending request independently of the MSAL flow, - * by calling to the `abortRequests()` method. - * - */ -export class IdentityClient extends ServiceClient { - constructor(options) { - var _a, _b; - const packageDetails = `azsdk-js-identity/${SDK_VERSION}`; - const userAgentPrefix = ((_a = options === null || options === void 0 ? void 0 : options.userAgentOptions) === null || _a === void 0 ? void 0 : _a.userAgentPrefix) - ? `${options.userAgentOptions.userAgentPrefix} ${packageDetails}` - : `${packageDetails}`; - const baseUri = getIdentityClientAuthorityHost(options); - if (!baseUri.startsWith("https:")) { - throw new Error("The authorityHost address must use the 'https' protocol."); - } - super(Object.assign(Object.assign({ requestContentType: "application/json; charset=utf-8", retryOptions: { - maxRetries: 3, - } }, options), { userAgentOptions: { - userAgentPrefix, - }, baseUri })); - this.allowInsecureConnection = false; - this.authorityHost = baseUri; - this.abortControllers = new Map(); - this.allowLoggingAccountIdentifiers = (_b = options === null || options === void 0 ? void 0 : options.loggingOptions) === null || _b === void 0 ? void 0 : _b.allowLoggingAccountIdentifiers; - // used for WorkloadIdentity - this.tokenCredentialOptions = Object.assign({}, options); - // used for ManagedIdentity - if (options === null || options === void 0 ? void 0 : options.allowInsecureConnection) { - this.allowInsecureConnection = options.allowInsecureConnection; - } - } - async sendTokenRequest(request) { - logger.info(`IdentityClient: sending token request to [${request.url}]`); - const response = await this.sendRequest(request); - if (response.bodyAsText && (response.status === 200 || response.status === 201)) { - const parsedBody = JSON.parse(response.bodyAsText); - if (!parsedBody.access_token) { - return null; - } - this.logIdentifiers(response); - const token = { - accessToken: { - token: parsedBody.access_token, - expiresOnTimestamp: parseExpirationTimestamp(parsedBody), - refreshAfterTimestamp: parseRefreshTimestamp(parsedBody), - tokenType: "Bearer", - }, - refreshToken: parsedBody.refresh_token, - }; - logger.info(`IdentityClient: [${request.url}] token acquired, expires on ${token.accessToken.expiresOnTimestamp}`); - return token; - } - else { - const error = new AuthenticationError(response.status, response.bodyAsText); - logger.warning(`IdentityClient: authentication error. HTTP status: ${response.status}, ${error.errorResponse.errorDescription}`); - throw error; - } - } - async refreshAccessToken(tenantId, clientId, scopes, refreshToken, clientSecret, options = {}) { - if (refreshToken === undefined) { - return null; - } - logger.info(`IdentityClient: refreshing access token with client ID: ${clientId}, scopes: ${scopes} started`); - const refreshParams = { - grant_type: "refresh_token", - client_id: clientId, - refresh_token: refreshToken, - scope: scopes, - }; - if (clientSecret !== undefined) { - refreshParams.client_secret = clientSecret; - } - const query = new URLSearchParams(refreshParams); - return tracingClient.withSpan("IdentityClient.refreshAccessToken", options, async (updatedOptions) => { - try { - const urlSuffix = getIdentityTokenEndpointSuffix(tenantId); - const request = createPipelineRequest({ - url: `${this.authorityHost}/${tenantId}/${urlSuffix}`, - method: "POST", - body: query.toString(), - abortSignal: options.abortSignal, - headers: createHttpHeaders({ - Accept: "application/json", - "Content-Type": "application/x-www-form-urlencoded", - }), - tracingOptions: updatedOptions.tracingOptions, - }); - const response = await this.sendTokenRequest(request); - logger.info(`IdentityClient: refreshed token for client ID: ${clientId}`); - return response; - } - catch (err) { - if (err.name === AuthenticationErrorName && - err.errorResponse.error === "interaction_required") { - // It's likely that the refresh token has expired, so - // return null so that the credential implementation will - // initiate the authentication flow again. - logger.info(`IdentityClient: interaction required for client ID: ${clientId}`); - return null; - } - else { - logger.warning(`IdentityClient: failed refreshing token for client ID: ${clientId}: ${err}`); - throw err; - } - } - }); - } - // Here is a custom layer that allows us to abort requests that go through MSAL, - // since MSAL doesn't allow us to pass options all the way through. - generateAbortSignal(correlationId) { - const controller = new AbortController(); - const controllers = this.abortControllers.get(correlationId) || []; - controllers.push(controller); - this.abortControllers.set(correlationId, controllers); - const existingOnAbort = controller.signal.onabort; - controller.signal.onabort = (...params) => { - this.abortControllers.set(correlationId, undefined); - if (existingOnAbort) { - existingOnAbort.apply(controller.signal, params); - } - }; - return controller.signal; - } - abortRequests(correlationId) { - const key = correlationId || noCorrelationId; - const controllers = [ - ...(this.abortControllers.get(key) || []), - // MSAL passes no correlation ID to the get requests... - ...(this.abortControllers.get(noCorrelationId) || []), - ]; - if (!controllers.length) { - return; - } - for (const controller of controllers) { - controller.abort(); - } - this.abortControllers.set(key, undefined); - } - getCorrelationId(options) { - var _a; - const parameter = (_a = options === null || options === void 0 ? void 0 : options.body) === null || _a === void 0 ? void 0 : _a.split("&").map((part) => part.split("=")).find(([key]) => key === "client-request-id"); - return parameter && parameter.length ? parameter[1] || noCorrelationId : noCorrelationId; - } - // The MSAL network module methods follow - async sendGetRequestAsync(url, options) { - const request = createPipelineRequest({ - url, - method: "GET", - body: options === null || options === void 0 ? void 0 : options.body, - allowInsecureConnection: this.allowInsecureConnection, - headers: createHttpHeaders(options === null || options === void 0 ? void 0 : options.headers), - abortSignal: this.generateAbortSignal(noCorrelationId), - }); - const response = await this.sendRequest(request); - this.logIdentifiers(response); - return { - body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined, - headers: response.headers.toJSON(), - status: response.status, - }; - } - async sendPostRequestAsync(url, options) { - const request = createPipelineRequest({ - url, - method: "POST", - body: options === null || options === void 0 ? void 0 : options.body, - headers: createHttpHeaders(options === null || options === void 0 ? void 0 : options.headers), - allowInsecureConnection: this.allowInsecureConnection, - // MSAL doesn't send the correlation ID on the get requests. - abortSignal: this.generateAbortSignal(this.getCorrelationId(options)), - }); - const response = await this.sendRequest(request); - this.logIdentifiers(response); - return { - body: response.bodyAsText ? JSON.parse(response.bodyAsText) : undefined, - headers: response.headers.toJSON(), - status: response.status, - }; - } - /** - * - * @internal - */ - getTokenCredentialOptions() { - return this.tokenCredentialOptions; - } - /** - * If allowLoggingAccountIdentifiers was set on the constructor options - * we try to log the account identifiers by parsing the received access token. - * - * The account identifiers we try to log are: - * - `appid`: The application or Client Identifier. - * - `upn`: User Principal Name. - * - It might not be available in some authentication scenarios. - * - If it's not available, we put a placeholder: "No User Principal Name available". - * - `tid`: Tenant Identifier. - * - `oid`: Object Identifier of the authenticated user. - */ - logIdentifiers(response) { - if (!this.allowLoggingAccountIdentifiers || !response.bodyAsText) { - return; - } - const unavailableUpn = "No User Principal Name available"; - try { - const parsed = response.parsedBody || JSON.parse(response.bodyAsText); - const accessToken = parsed.access_token; - if (!accessToken) { - // Without an access token allowLoggingAccountIdentifiers isn't useful. - return; - } - const base64Metadata = accessToken.split(".")[1]; - const { appid, upn, tid, oid } = JSON.parse(Buffer.from(base64Metadata, "base64").toString("utf8")); - logger.info(`[Authenticated account] Client ID: ${appid}. Tenant ID: ${tid}. User Principal Name: ${upn || unavailableUpn}. Object ID (user): ${oid}`); - } - catch (e) { - logger.warning("allowLoggingAccountIdentifiers was set, but we couldn't log the account information. Error:", e.message); - } - } -} -//# sourceMappingURL=identityClient.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/constants.js b/claude-code-source/node_modules/@azure/identity/dist/esm/constants.js deleted file mode 100644 index 5f60f124..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/constants.js +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * Current version of the `@azure/identity` package. - */ -export const SDK_VERSION = `4.10.1`; -/** - * The default client ID for authentication - * @internal - */ -// TODO: temporary - this is the Azure CLI clientID - we'll replace it when -// Developer Sign On application is available -// https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/Constants.cs#L9 -export const DeveloperSignOnClientId = "04b07795-8ddb-461a-bbee-02f9e1bf7b46"; -/** - * The default tenant for authentication - * @internal - */ -export const DefaultTenantId = "common"; -/** - * A list of known Azure authority hosts - */ -export var AzureAuthorityHosts; -(function (AzureAuthorityHosts) { - /** - * China-based Azure Authority Host - */ - AzureAuthorityHosts["AzureChina"] = "https://login.chinacloudapi.cn"; - /** - * Germany-based Azure Authority Host - * - * @deprecated Microsoft Cloud Germany was closed on October 29th, 2021. - * - * */ - AzureAuthorityHosts["AzureGermany"] = "https://login.microsoftonline.de"; - /** - * US Government Azure Authority Host - */ - AzureAuthorityHosts["AzureGovernment"] = "https://login.microsoftonline.us"; - /** - * Public Cloud Azure Authority Host - */ - AzureAuthorityHosts["AzurePublicCloud"] = "https://login.microsoftonline.com"; -})(AzureAuthorityHosts || (AzureAuthorityHosts = {})); -/** - * @internal - * The default authority host. - */ -export const DefaultAuthorityHost = AzureAuthorityHosts.AzurePublicCloud; -/** - * @internal - * The default environment host for Azure Public Cloud - */ -export const DefaultAuthority = "login.microsoftonline.com"; -/** - * @internal - * Allow acquiring tokens for any tenant for multi-tentant auth. - */ -export const ALL_TENANTS = ["*"]; -/** - * @internal - */ -export const CACHE_CAE_SUFFIX = "cae"; -/** - * @internal - */ -export const CACHE_NON_CAE_SUFFIX = "nocae"; -/** - * @internal - * - * The default name for the cache persistence plugin. - * Matches the constant defined in the cache persistence package. - */ -export const DEFAULT_TOKEN_CACHE_NAME = "msal.cache"; -//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/authorizationCodeCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/authorizationCodeCredential.js deleted file mode 100644 index e0ffb9b8..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/authorizationCodeCredential.js +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils.js"; -import { checkTenantId } from "../util/tenantIdUtils.js"; -import { credentialLogger } from "../util/logging.js"; -import { ensureScopes } from "../util/scopeUtils.js"; -import { tracingClient } from "../util/tracing.js"; -import { createMsalClient } from "../msal/nodeFlows/msalClient.js"; -const logger = credentialLogger("AuthorizationCodeCredential"); -/** - * Enables authentication to Microsoft Entra ID using an authorization code - * that was obtained through the authorization code flow, described in more detail - * in the Microsoft Entra ID documentation: - * - * https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow - */ -export class AuthorizationCodeCredential { - /** - * @hidden - * @internal - */ - constructor(tenantId, clientId, clientSecretOrAuthorizationCode, authorizationCodeOrRedirectUri, redirectUriOrOptions, options) { - checkTenantId(logger, tenantId); - this.clientSecret = clientSecretOrAuthorizationCode; - if (typeof redirectUriOrOptions === "string") { - // the clientId+clientSecret constructor - this.authorizationCode = authorizationCodeOrRedirectUri; - this.redirectUri = redirectUriOrOptions; - // in this case, options are good as they come - } - else { - // clientId only - this.authorizationCode = clientSecretOrAuthorizationCode; - this.redirectUri = authorizationCodeOrRedirectUri; - this.clientSecret = undefined; - options = redirectUriOrOptions; - } - // TODO: Validate tenant if provided - this.tenantId = tenantId; - this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); - this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { logger, tokenCredentialOptions: options !== null && options !== void 0 ? options : {} })); - } - /** - * Authenticates with Microsoft Entra ID and returns an access token if successful. - * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. - * - * @param scopes - The list of scopes for which the token will have access. - * @param options - The options used to configure any requests this - * TokenCredential implementation might make. - */ - async getToken(scopes, options = {}) { - return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => { - const tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds); - newOptions.tenantId = tenantId; - const arrayScopes = ensureScopes(scopes); - return this.msalClient.getTokenByAuthorizationCode(arrayScopes, this.redirectUri, this.authorizationCode, this.clientSecret, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: this.disableAutomaticAuthentication })); - }); - } -} -//# sourceMappingURL=authorizationCodeCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azureCliCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azureCliCredential.js deleted file mode 100644 index 15cd22fc..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azureCliCredential.js +++ /dev/null @@ -1,191 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { checkTenantId, processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils.js"; -import { credentialLogger, formatError, formatSuccess } from "../util/logging.js"; -import { ensureValidScopeForDevTimeCreds, getScopeResource } from "../util/scopeUtils.js"; -import { CredentialUnavailableError } from "../errors.js"; -import child_process from "child_process"; -import { tracingClient } from "../util/tracing.js"; -import { checkSubscription } from "../util/subscriptionUtils.js"; -const logger = credentialLogger("AzureCliCredential"); -/** - * Mockable reference to the CLI credential cliCredentialFunctions - * @internal - */ -export const cliCredentialInternals = { - /** - * @internal - */ - getSafeWorkingDir() { - if (process.platform === "win32") { - let systemRoot = process.env.SystemRoot || process.env["SYSTEMROOT"]; - if (!systemRoot) { - logger.getToken.warning("The SystemRoot environment variable is not set. This may cause issues when using the Azure CLI credential."); - systemRoot = "C:\\Windows"; - } - return systemRoot; - } - else { - return "/bin"; - } - }, - /** - * Gets the access token from Azure CLI - * @param resource - The resource to use when getting the token - * @internal - */ - async getAzureCliAccessToken(resource, tenantId, subscription, timeout) { - let tenantSection = []; - let subscriptionSection = []; - if (tenantId) { - tenantSection = ["--tenant", tenantId]; - } - if (subscription) { - // Add quotes around the subscription to handle subscriptions with spaces - subscriptionSection = ["--subscription", `"${subscription}"`]; - } - return new Promise((resolve, reject) => { - try { - child_process.execFile("az", [ - "account", - "get-access-token", - "--output", - "json", - "--resource", - resource, - ...tenantSection, - ...subscriptionSection, - ], { cwd: cliCredentialInternals.getSafeWorkingDir(), shell: true, timeout }, (error, stdout, stderr) => { - resolve({ stdout: stdout, stderr: stderr, error }); - }); - } - catch (err) { - reject(err); - } - }); - }, -}; -/** - * This credential will use the currently logged-in user login information - * via the Azure CLI ('az') commandline tool. - * To do so, it will read the user access token and expire time - * with Azure CLI command "az account get-access-token". - */ -export class AzureCliCredential { - /** - * Creates an instance of the {@link AzureCliCredential}. - * - * To use this credential, ensure that you have already logged - * in via the 'az' tool using the command "az login" from the commandline. - * - * @param options - Options, to optionally allow multi-tenant requests. - */ - constructor(options) { - if (options === null || options === void 0 ? void 0 : options.tenantId) { - checkTenantId(logger, options === null || options === void 0 ? void 0 : options.tenantId); - this.tenantId = options === null || options === void 0 ? void 0 : options.tenantId; - } - if (options === null || options === void 0 ? void 0 : options.subscription) { - checkSubscription(logger, options === null || options === void 0 ? void 0 : options.subscription); - this.subscription = options === null || options === void 0 ? void 0 : options.subscription; - } - this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); - this.timeout = options === null || options === void 0 ? void 0 : options.processTimeoutInMs; - } - /** - * Authenticates with Microsoft Entra ID and returns an access token if successful. - * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. - * - * @param scopes - The list of scopes for which the token will have access. - * @param options - The options used to configure any requests this - * TokenCredential implementation might make. - */ - async getToken(scopes, options = {}) { - const tenantId = processMultiTenantRequest(this.tenantId, options, this.additionallyAllowedTenantIds); - if (tenantId) { - checkTenantId(logger, tenantId); - } - if (this.subscription) { - checkSubscription(logger, this.subscription); - } - const scope = typeof scopes === "string" ? scopes : scopes[0]; - logger.getToken.info(`Using the scope ${scope}`); - return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => { - var _a, _b, _c, _d; - try { - ensureValidScopeForDevTimeCreds(scope, logger); - const resource = getScopeResource(scope); - const obj = await cliCredentialInternals.getAzureCliAccessToken(resource, tenantId, this.subscription, this.timeout); - const specificScope = (_a = obj.stderr) === null || _a === void 0 ? void 0 : _a.match("(.*)az login --scope(.*)"); - const isLoginError = ((_b = obj.stderr) === null || _b === void 0 ? void 0 : _b.match("(.*)az login(.*)")) && !specificScope; - const isNotInstallError = ((_c = obj.stderr) === null || _c === void 0 ? void 0 : _c.match("az:(.*)not found")) || ((_d = obj.stderr) === null || _d === void 0 ? void 0 : _d.startsWith("'az' is not recognized")); - if (isNotInstallError) { - const error = new CredentialUnavailableError("Azure CLI could not be found. Please visit https://aka.ms/azure-cli for installation instructions and then, once installed, authenticate to your Azure account using 'az login'."); - logger.getToken.info(formatError(scopes, error)); - throw error; - } - if (isLoginError) { - const error = new CredentialUnavailableError("Please run 'az login' from a command prompt to authenticate before using this credential."); - logger.getToken.info(formatError(scopes, error)); - throw error; - } - try { - const responseData = obj.stdout; - const response = this.parseRawResponse(responseData); - logger.getToken.info(formatSuccess(scopes)); - return response; - } - catch (e) { - if (obj.stderr) { - throw new CredentialUnavailableError(obj.stderr); - } - throw e; - } - } - catch (err) { - const error = err.name === "CredentialUnavailableError" - ? err - : new CredentialUnavailableError(err.message || "Unknown error while trying to retrieve the access token"); - logger.getToken.info(formatError(scopes, error)); - throw error; - } - }); - } - /** - * Parses the raw JSON response from the Azure CLI into a usable AccessToken object - * - * @param rawResponse - The raw JSON response from the Azure CLI - * @returns An access token with the expiry time parsed from the raw response - * - * The expiryTime of the credential's access token, in milliseconds, is calculated as follows: - * - * When available, expires_on (introduced in Azure CLI v2.54.0) will be preferred. Otherwise falls back to expiresOn. - */ - parseRawResponse(rawResponse) { - const response = JSON.parse(rawResponse); - const token = response.accessToken; - // if available, expires_on will be a number representing seconds since epoch. - // ensure it's a number or NaN - let expiresOnTimestamp = Number.parseInt(response.expires_on, 10) * 1000; - if (!isNaN(expiresOnTimestamp)) { - logger.getToken.info("expires_on is available and is valid, using it"); - return { - token, - expiresOnTimestamp, - tokenType: "Bearer", - }; - } - // fallback to the older expiresOn - an RFC3339 date string - expiresOnTimestamp = new Date(response.expiresOn).getTime(); - // ensure expiresOn is well-formatted - if (isNaN(expiresOnTimestamp)) { - throw new CredentialUnavailableError(`Unexpected response from Azure CLI when getting token. Expected "expiresOn" to be a RFC3339 date string. Got: "${response.expiresOn}"`); - } - return { - token, - expiresOnTimestamp, - tokenType: "Bearer", - }; - } -} -//# sourceMappingURL=azureCliCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azureDeveloperCliCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azureDeveloperCliCredential.js deleted file mode 100644 index 423ac8ca..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azureDeveloperCliCredential.js +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { credentialLogger, formatError, formatSuccess } from "../util/logging.js"; -import { CredentialUnavailableError } from "../errors.js"; -import child_process from "child_process"; -import { checkTenantId, processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils.js"; -import { tracingClient } from "../util/tracing.js"; -import { ensureValidScopeForDevTimeCreds } from "../util/scopeUtils.js"; -const logger = credentialLogger("AzureDeveloperCliCredential"); -/** - * Mockable reference to the Developer CLI credential cliCredentialFunctions - * @internal - */ -export const developerCliCredentialInternals = { - /** - * @internal - */ - getSafeWorkingDir() { - if (process.platform === "win32") { - let systemRoot = process.env.SystemRoot || process.env["SYSTEMROOT"]; - if (!systemRoot) { - logger.getToken.warning("The SystemRoot environment variable is not set. This may cause issues when using the Azure Developer CLI credential."); - systemRoot = "C:\\Windows"; - } - return systemRoot; - } - else { - return "/bin"; - } - }, - /** - * Gets the access token from Azure Developer CLI - * @param scopes - The scopes to use when getting the token - * @internal - */ - async getAzdAccessToken(scopes, tenantId, timeout) { - let tenantSection = []; - if (tenantId) { - tenantSection = ["--tenant-id", tenantId]; - } - return new Promise((resolve, reject) => { - try { - child_process.execFile("azd", [ - "auth", - "token", - "--output", - "json", - ...scopes.reduce((previous, current) => previous.concat("--scope", current), []), - ...tenantSection, - ], { - cwd: developerCliCredentialInternals.getSafeWorkingDir(), - timeout, - }, (error, stdout, stderr) => { - resolve({ stdout, stderr, error }); - }); - } - catch (err) { - reject(err); - } - }); - }, -}; -/** - * Azure Developer CLI is a command-line interface tool that allows developers to create, manage, and deploy - * resources in Azure. It's built on top of the Azure CLI and provides additional functionality specific - * to Azure developers. It allows users to authenticate as a user and/or a service principal against - * Microsoft Entra ID. The - * AzureDeveloperCliCredential authenticates in a development environment and acquires a token on behalf of - * the logged-in user or service principal in the Azure Developer CLI. It acts as the Azure Developer CLI logged in user or - * service principal and executes an Azure CLI command underneath to authenticate the application against - * Microsoft Entra ID. - * - *

Configure AzureDeveloperCliCredential

- * - * To use this credential, the developer needs to authenticate locally in Azure Developer CLI using one of the - * commands below: - * - *
    - *
  1. Run "azd auth login" in Azure Developer CLI to authenticate interactively as a user.
  2. - *
  3. Run "azd auth login --client-id clientID --client-secret clientSecret - * --tenant-id tenantID" to authenticate as a service principal.
  4. - *
- * - * You may need to repeat this process after a certain time period, depending on the refresh token validity in your - * organization. Generally, the refresh token validity period is a few weeks to a few months. - * AzureDeveloperCliCredential will prompt you to sign in again. - */ -export class AzureDeveloperCliCredential { - /** - * Creates an instance of the {@link AzureDeveloperCliCredential}. - * - * To use this credential, ensure that you have already logged - * in via the 'azd' tool using the command "azd auth login" from the commandline. - * - * @param options - Options, to optionally allow multi-tenant requests. - */ - constructor(options) { - if (options === null || options === void 0 ? void 0 : options.tenantId) { - checkTenantId(logger, options === null || options === void 0 ? void 0 : options.tenantId); - this.tenantId = options === null || options === void 0 ? void 0 : options.tenantId; - } - this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); - this.timeout = options === null || options === void 0 ? void 0 : options.processTimeoutInMs; - } - /** - * Authenticates with Microsoft Entra ID and returns an access token if successful. - * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. - * - * @param scopes - The list of scopes for which the token will have access. - * @param options - The options used to configure any requests this - * TokenCredential implementation might make. - */ - async getToken(scopes, options = {}) { - const tenantId = processMultiTenantRequest(this.tenantId, options, this.additionallyAllowedTenantIds); - if (tenantId) { - checkTenantId(logger, tenantId); - } - let scopeList; - if (typeof scopes === "string") { - scopeList = [scopes]; - } - else { - scopeList = scopes; - } - logger.getToken.info(`Using the scopes ${scopes}`); - return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => { - var _a, _b, _c, _d; - try { - scopeList.forEach((scope) => { - ensureValidScopeForDevTimeCreds(scope, logger); - }); - const obj = await developerCliCredentialInternals.getAzdAccessToken(scopeList, tenantId, this.timeout); - const isNotLoggedInError = ((_a = obj.stderr) === null || _a === void 0 ? void 0 : _a.match("not logged in, run `azd login` to login")) || - ((_b = obj.stderr) === null || _b === void 0 ? void 0 : _b.match("not logged in, run `azd auth login` to login")); - const isNotInstallError = ((_c = obj.stderr) === null || _c === void 0 ? void 0 : _c.match("azd:(.*)not found")) || - ((_d = obj.stderr) === null || _d === void 0 ? void 0 : _d.startsWith("'azd' is not recognized")); - if (isNotInstallError || (obj.error && obj.error.code === "ENOENT")) { - const error = new CredentialUnavailableError("Azure Developer CLI couldn't be found. To mitigate this issue, see the troubleshooting guidelines at https://aka.ms/azsdk/js/identity/azdevclicredential/troubleshoot."); - logger.getToken.info(formatError(scopes, error)); - throw error; - } - if (isNotLoggedInError) { - const error = new CredentialUnavailableError("Please run 'azd auth login' from a command prompt to authenticate before using this credential. For more information, see the troubleshooting guidelines at https://aka.ms/azsdk/js/identity/azdevclicredential/troubleshoot."); - logger.getToken.info(formatError(scopes, error)); - throw error; - } - try { - const resp = JSON.parse(obj.stdout); - logger.getToken.info(formatSuccess(scopes)); - return { - token: resp.token, - expiresOnTimestamp: new Date(resp.expiresOn).getTime(), - tokenType: "Bearer", - }; - } - catch (e) { - if (obj.stderr) { - throw new CredentialUnavailableError(obj.stderr); - } - throw e; - } - } - catch (err) { - const error = err.name === "CredentialUnavailableError" - ? err - : new CredentialUnavailableError(err.message || "Unknown error while trying to retrieve the access token"); - logger.getToken.info(formatError(scopes, error)); - throw error; - } - }); - } -} -//# sourceMappingURL=azureDeveloperCliCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azurePipelinesCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azurePipelinesCredential.js deleted file mode 100644 index e44cdddd..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azurePipelinesCredential.js +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { AuthenticationError, CredentialUnavailableError } from "../errors.js"; -import { createHttpHeaders, createPipelineRequest } from "@azure/core-rest-pipeline"; -import { ClientAssertionCredential } from "./clientAssertionCredential.js"; -import { IdentityClient } from "../client/identityClient.js"; -import { checkTenantId } from "../util/tenantIdUtils.js"; -import { credentialLogger } from "../util/logging.js"; -const credentialName = "AzurePipelinesCredential"; -const logger = credentialLogger(credentialName); -const OIDC_API_VERSION = "7.1"; -/** - * This credential is designed to be used in Azure Pipelines with service connections - * as a setup for workload identity federation. - */ -export class AzurePipelinesCredential { - /** - * AzurePipelinesCredential supports Federated Identity on Azure Pipelines through Service Connections. - * @param tenantId - tenantId associated with the service connection - * @param clientId - clientId associated with the service connection - * @param serviceConnectionId - Unique ID for the service connection, as found in the querystring's resourceId key - * @param systemAccessToken - The pipeline's System.AccessToken value. - * @param options - The identity client options to use for authentication. - */ - constructor(tenantId, clientId, serviceConnectionId, systemAccessToken, options = {}) { - var _a, _b; - if (!clientId) { - throw new CredentialUnavailableError(`${credentialName}: is unavailable. clientId is a required parameter.`); - } - if (!tenantId) { - throw new CredentialUnavailableError(`${credentialName}: is unavailable. tenantId is a required parameter.`); - } - if (!serviceConnectionId) { - throw new CredentialUnavailableError(`${credentialName}: is unavailable. serviceConnectionId is a required parameter.`); - } - if (!systemAccessToken) { - throw new CredentialUnavailableError(`${credentialName}: is unavailable. systemAccessToken is a required parameter.`); - } - // Allow these headers to be logged for troubleshooting by AzurePipelines. - options.loggingOptions = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.loggingOptions), { additionalAllowedHeaderNames: [ - ...((_b = (_a = options.loggingOptions) === null || _a === void 0 ? void 0 : _a.additionalAllowedHeaderNames) !== null && _b !== void 0 ? _b : []), - "x-vss-e2eid", - "x-msedge-ref", - ] }); - this.identityClient = new IdentityClient(options); - checkTenantId(logger, tenantId); - logger.info(`Invoking AzurePipelinesCredential with tenant ID: ${tenantId}, client ID: ${clientId}, and service connection ID: ${serviceConnectionId}`); - if (!process.env.SYSTEM_OIDCREQUESTURI) { - throw new CredentialUnavailableError(`${credentialName}: is unavailable. Ensure that you're running this task in an Azure Pipeline, so that following missing system variable(s) can be defined- "SYSTEM_OIDCREQUESTURI"`); - } - const oidcRequestUrl = `${process.env.SYSTEM_OIDCREQUESTURI}?api-version=${OIDC_API_VERSION}&serviceConnectionId=${serviceConnectionId}`; - logger.info(`Invoking ClientAssertionCredential with tenant ID: ${tenantId}, client ID: ${clientId} and service connection ID: ${serviceConnectionId}`); - this.clientAssertionCredential = new ClientAssertionCredential(tenantId, clientId, this.requestOidcToken.bind(this, oidcRequestUrl, systemAccessToken), options); - } - /** - * Authenticates with Microsoft Entra ID and returns an access token if successful. - * If authentication fails, a {@link CredentialUnavailableError} or {@link AuthenticationError} will be thrown with the details of the failure. - * - * @param scopes - The list of scopes for which the token will have access. - * @param options - The options used to configure any requests this - * TokenCredential implementation might make. - */ - async getToken(scopes, options) { - if (!this.clientAssertionCredential) { - const errorMessage = `${credentialName}: is unavailable. To use Federation Identity in Azure Pipelines, the following parameters are required - - tenantId, - clientId, - serviceConnectionId, - systemAccessToken, - "SYSTEM_OIDCREQUESTURI". - See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`; - logger.error(errorMessage); - throw new CredentialUnavailableError(errorMessage); - } - logger.info("Invoking getToken() of Client Assertion Credential"); - return this.clientAssertionCredential.getToken(scopes, options); - } - /** - * - * @param oidcRequestUrl - oidc request url - * @param systemAccessToken - system access token - * @returns OIDC token from Azure Pipelines - */ - async requestOidcToken(oidcRequestUrl, systemAccessToken) { - logger.info("Requesting OIDC token from Azure Pipelines..."); - logger.info(oidcRequestUrl); - const request = createPipelineRequest({ - url: oidcRequestUrl, - method: "POST", - headers: createHttpHeaders({ - "Content-Type": "application/json", - Authorization: `Bearer ${systemAccessToken}`, - // Prevents the service from responding with a redirect HTTP status code (useful for automation). - "X-TFS-FedAuthRedirect": "Suppress", - }), - }); - const response = await this.identityClient.sendRequest(request); - return handleOidcResponse(response); - } -} -export function handleOidcResponse(response) { - // OIDC token is present in `bodyAsText` field - const text = response.bodyAsText; - if (!text) { - logger.error(`${credentialName}: Authentication Failed. Received null token from OIDC request. Response status- ${response.status}. Complete response - ${JSON.stringify(response)}`); - throw new AuthenticationError(response.status, { - error: `${credentialName}: Authentication Failed. Received null token from OIDC request.`, - error_description: `${JSON.stringify(response)}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`, - }); - } - try { - const result = JSON.parse(text); - if (result === null || result === void 0 ? void 0 : result.oidcToken) { - return result.oidcToken; - } - else { - const errorMessage = `${credentialName}: Authentication Failed. oidcToken field not detected in the response.`; - let errorDescription = ``; - if (response.status !== 200) { - errorDescription = `Response body = ${text}. Response Headers ["x-vss-e2eid"] = ${response.headers.get("x-vss-e2eid")} and ["x-msedge-ref"] = ${response.headers.get("x-msedge-ref")}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`; - } - logger.error(errorMessage); - logger.error(errorDescription); - throw new AuthenticationError(response.status, { - error: errorMessage, - error_description: errorDescription, - }); - } - } - catch (e) { - const errorDetails = `${credentialName}: Authentication Failed. oidcToken field not detected in the response.`; - logger.error(`Response from service = ${text}, Response Headers ["x-vss-e2eid"] = ${response.headers.get("x-vss-e2eid")} - and ["x-msedge-ref"] = ${response.headers.get("x-msedge-ref")}, error message = ${e.message}`); - logger.error(errorDetails); - throw new AuthenticationError(response.status, { - error: errorDetails, - error_description: `Response = ${text}. Response headers ["x-vss-e2eid"] = ${response.headers.get("x-vss-e2eid")} and ["x-msedge-ref"] = ${response.headers.get("x-msedge-ref")}. See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/azurepipelinescredential/troubleshoot`, - }); - } -} -//# sourceMappingURL=azurePipelinesCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azurePowerShellCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azurePowerShellCredential.js deleted file mode 100644 index cdf54277..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/azurePowerShellCredential.js +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { checkTenantId, processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils.js"; -import { credentialLogger, formatError, formatSuccess } from "../util/logging.js"; -import { ensureValidScopeForDevTimeCreds, getScopeResource } from "../util/scopeUtils.js"; -import { CredentialUnavailableError } from "../errors.js"; -import { processUtils } from "../util/processUtils.js"; -import { tracingClient } from "../util/tracing.js"; -const logger = credentialLogger("AzurePowerShellCredential"); -const isWindows = process.platform === "win32"; -/** - * Returns a platform-appropriate command name by appending ".exe" on Windows. - * - * @internal - */ -export function formatCommand(commandName) { - if (isWindows) { - return `${commandName}.exe`; - } - else { - return commandName; - } -} -/** - * Receives a list of commands to run, executes them, then returns the outputs. - * If anything fails, an error is thrown. - * @internal - */ -async function runCommands(commands, timeout) { - const results = []; - for (const command of commands) { - const [file, ...parameters] = command; - const result = (await processUtils.execFile(file, parameters, { - encoding: "utf8", - timeout, - })); - results.push(result); - } - return results; -} -/** - * Known PowerShell errors - * @internal - */ -export const powerShellErrors = { - login: "Run Connect-AzAccount to login", - installed: "The specified module 'Az.Accounts' with version '2.2.0' was not loaded because no valid module file was found in any module directory", -}; -/** - * Messages to use when throwing in this credential. - * @internal - */ -export const powerShellPublicErrorMessages = { - login: "Please run 'Connect-AzAccount' from PowerShell to authenticate before using this credential.", - installed: `The 'Az.Account' module >= 2.2.0 is not installed. Install the Azure Az PowerShell module with: "Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force".`, - troubleshoot: `To troubleshoot, visit https://aka.ms/azsdk/js/identity/powershellcredential/troubleshoot.`, -}; -// PowerShell Azure User not logged in error check. -const isLoginError = (err) => err.message.match(`(.*)${powerShellErrors.login}(.*)`); -// Az Module not Installed in Azure PowerShell check. -const isNotInstalledError = (err) => err.message.match(powerShellErrors.installed); -/** - * The PowerShell commands to be tried, in order. - * - * @internal - */ -export const commandStack = [formatCommand("pwsh")]; -if (isWindows) { - commandStack.push(formatCommand("powershell")); -} -/** - * This credential will use the currently logged-in user information from the - * Azure PowerShell module. To do so, it will read the user access token and - * expire time with Azure PowerShell command `Get-AzAccessToken -ResourceUrl {ResourceScope}` - */ -export class AzurePowerShellCredential { - /** - * Creates an instance of the {@link AzurePowerShellCredential}. - * - * To use this credential: - * - Install the Azure Az PowerShell module with: - * `Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force`. - * - You have already logged in to Azure PowerShell using the command - * `Connect-AzAccount` from the command line. - * - * @param options - Options, to optionally allow multi-tenant requests. - */ - constructor(options) { - if (options === null || options === void 0 ? void 0 : options.tenantId) { - checkTenantId(logger, options === null || options === void 0 ? void 0 : options.tenantId); - this.tenantId = options === null || options === void 0 ? void 0 : options.tenantId; - } - this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); - this.timeout = options === null || options === void 0 ? void 0 : options.processTimeoutInMs; - } - /** - * Gets the access token from Azure PowerShell - * @param resource - The resource to use when getting the token - */ - async getAzurePowerShellAccessToken(resource, tenantId, timeout) { - // Clone the stack to avoid mutating it while iterating - for (const powerShellCommand of [...commandStack]) { - try { - await runCommands([[powerShellCommand, "/?"]], timeout); - } - catch (e) { - // Remove this credential from the original stack so that we don't try it again. - commandStack.shift(); - continue; - } - const results = await runCommands([ - [ - powerShellCommand, - "-NoProfile", - "-NonInteractive", - "-Command", - ` - $tenantId = "${tenantId !== null && tenantId !== void 0 ? tenantId : ""}" - $m = Import-Module Az.Accounts -MinimumVersion 2.2.0 -PassThru - $useSecureString = $m.Version -ge [version]'2.17.0' - - $params = @{ - ResourceUrl = "${resource}" - } - - if ($tenantId.Length -gt 0) { - $params["TenantId"] = $tenantId - } - - if ($useSecureString) { - $params["AsSecureString"] = $true - } - - $token = Get-AzAccessToken @params - - $result = New-Object -TypeName PSObject - $result | Add-Member -MemberType NoteProperty -Name ExpiresOn -Value $token.ExpiresOn - if ($useSecureString) { - $result | Add-Member -MemberType NoteProperty -Name Token -Value (ConvertFrom-SecureString -AsPlainText $token.Token) - } else { - $result | Add-Member -MemberType NoteProperty -Name Token -Value $token.Token - } - - Write-Output (ConvertTo-Json $result) - `, - ], - ]); - const result = results[0]; - return parseJsonToken(result); - } - throw new Error(`Unable to execute PowerShell. Ensure that it is installed in your system`); - } - /** - * Authenticates with Microsoft Entra ID and returns an access token if successful. - * If the authentication cannot be performed through PowerShell, a {@link CredentialUnavailableError} will be thrown. - * - * @param scopes - The list of scopes for which the token will have access. - * @param options - The options used to configure any requests this TokenCredential implementation might make. - */ - async getToken(scopes, options = {}) { - return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async () => { - const tenantId = processMultiTenantRequest(this.tenantId, options, this.additionallyAllowedTenantIds); - const scope = typeof scopes === "string" ? scopes : scopes[0]; - if (tenantId) { - checkTenantId(logger, tenantId); - } - try { - ensureValidScopeForDevTimeCreds(scope, logger); - logger.getToken.info(`Using the scope ${scope}`); - const resource = getScopeResource(scope); - const response = await this.getAzurePowerShellAccessToken(resource, tenantId, this.timeout); - logger.getToken.info(formatSuccess(scopes)); - return { - token: response.Token, - expiresOnTimestamp: new Date(response.ExpiresOn).getTime(), - tokenType: "Bearer", - }; - } - catch (err) { - if (isNotInstalledError(err)) { - const error = new CredentialUnavailableError(powerShellPublicErrorMessages.installed); - logger.getToken.info(formatError(scope, error)); - throw error; - } - else if (isLoginError(err)) { - const error = new CredentialUnavailableError(powerShellPublicErrorMessages.login); - logger.getToken.info(formatError(scope, error)); - throw error; - } - const error = new CredentialUnavailableError(`${err}. ${powerShellPublicErrorMessages.troubleshoot}`); - logger.getToken.info(formatError(scope, error)); - throw error; - } - }); - } -} -/** - * - * @internal - */ -export async function parseJsonToken(result) { - const jsonRegex = /{[^{}]*}/g; - const matches = result.match(jsonRegex); - let resultWithoutToken = result; - if (matches) { - try { - for (const item of matches) { - try { - const jsonContent = JSON.parse(item); - if (jsonContent === null || jsonContent === void 0 ? void 0 : jsonContent.Token) { - resultWithoutToken = resultWithoutToken.replace(item, ""); - if (resultWithoutToken) { - logger.getToken.warning(resultWithoutToken); - } - return jsonContent; - } - } - catch (e) { - continue; - } - } - } - catch (e) { - throw new Error(`Unable to parse the output of PowerShell. Received output: ${result}`); - } - } - throw new Error(`No access token found in the output. Received output: ${result}`); -} -//# sourceMappingURL=azurePowerShellCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/chainedTokenCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/chainedTokenCredential.js deleted file mode 100644 index 030bb403..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/chainedTokenCredential.js +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { AggregateAuthenticationError, CredentialUnavailableError } from "../errors.js"; -import { credentialLogger, formatError, formatSuccess } from "../util/logging.js"; -import { tracingClient } from "../util/tracing.js"; -/** - * @internal - */ -export const logger = credentialLogger("ChainedTokenCredential"); -/** - * Enables multiple `TokenCredential` implementations to be tried in order until - * one of the getToken methods returns an access token. For more information, see - * [ChainedTokenCredential overview](https://aka.ms/azsdk/js/identity/credential-chains#use-chainedtokencredential-for-granularity). - */ -export class ChainedTokenCredential { - /** - * Creates an instance of ChainedTokenCredential using the given credentials. - * - * @param sources - `TokenCredential` implementations to be tried in order. - * - * Example usage: - * ```ts snippet:chained_token_credential_example - * import { ClientSecretCredential, ChainedTokenCredential } from "@azure/identity"; - * - * const tenantId = ""; - * const clientId = ""; - * const clientSecret = ""; - * const anotherClientId = ""; - * const anotherSecret = ""; - * - * const firstCredential = new ClientSecretCredential(tenantId, clientId, clientSecret); - * const secondCredential = new ClientSecretCredential(tenantId, anotherClientId, anotherSecret); - * - * const credentialChain = new ChainedTokenCredential(firstCredential, secondCredential); - * ``` - */ - constructor(...sources) { - this._sources = []; - this._sources = sources; - } - /** - * Returns the first access token returned by one of the chained - * `TokenCredential` implementations. Throws an {@link AggregateAuthenticationError} - * when one or more credentials throws an {@link AuthenticationError} and - * no credentials have returned an access token. - * - * This method is called automatically by Azure SDK client libraries. You may call this method - * directly, but you must also handle token caching and token refreshing. - * - * @param scopes - The list of scopes for which the token will have access. - * @param options - The options used to configure any requests this - * `TokenCredential` implementation might make. - */ - async getToken(scopes, options = {}) { - const { token } = await this.getTokenInternal(scopes, options); - return token; - } - async getTokenInternal(scopes, options = {}) { - let token = null; - let successfulCredential; - const errors = []; - return tracingClient.withSpan("ChainedTokenCredential.getToken", options, async (updatedOptions) => { - for (let i = 0; i < this._sources.length && token === null; i++) { - try { - token = await this._sources[i].getToken(scopes, updatedOptions); - successfulCredential = this._sources[i]; - } - catch (err) { - if (err.name === "CredentialUnavailableError" || - err.name === "AuthenticationRequiredError") { - errors.push(err); - } - else { - logger.getToken.info(formatError(scopes, err)); - throw err; - } - } - } - if (!token && errors.length > 0) { - const err = new AggregateAuthenticationError(errors, "ChainedTokenCredential authentication failed."); - logger.getToken.info(formatError(scopes, err)); - throw err; - } - logger.getToken.info(`Result for ${successfulCredential.constructor.name}: ${formatSuccess(scopes)}`); - if (token === null) { - throw new CredentialUnavailableError("Failed to retrieve a valid token"); - } - return { token, successfulCredential }; - }); - } -} -//# sourceMappingURL=chainedTokenCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientAssertionCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientAssertionCredential.js deleted file mode 100644 index a5071d47..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientAssertionCredential.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createMsalClient } from "../msal/nodeFlows/msalClient.js"; -import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils.js"; -import { CredentialUnavailableError } from "../errors.js"; -import { credentialLogger } from "../util/logging.js"; -import { tracingClient } from "../util/tracing.js"; -const logger = credentialLogger("ClientAssertionCredential"); -/** - * Authenticates a service principal with a JWT assertion. - */ -export class ClientAssertionCredential { - /** - * Creates an instance of the ClientAssertionCredential with the details - * needed to authenticate against Microsoft Entra ID with a client - * assertion provided by the developer through the `getAssertion` function parameter. - * - * @param tenantId - The Microsoft Entra tenant (directory) ID. - * @param clientId - The client (application) ID of an App Registration in the tenant. - * @param getAssertion - A function that retrieves the assertion for the credential to use. - * @param options - Options for configuring the client which makes the authentication request. - */ - constructor(tenantId, clientId, getAssertion, options = {}) { - if (!tenantId) { - throw new CredentialUnavailableError("ClientAssertionCredential: tenantId is a required parameter."); - } - if (!clientId) { - throw new CredentialUnavailableError("ClientAssertionCredential: clientId is a required parameter."); - } - if (!getAssertion) { - throw new CredentialUnavailableError("ClientAssertionCredential: clientAssertion is a required parameter."); - } - this.tenantId = tenantId; - this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); - this.options = options; - this.getAssertion = getAssertion; - this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { logger, tokenCredentialOptions: this.options })); - } - /** - * Authenticates with Microsoft Entra ID and returns an access token if successful. - * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. - * - * @param scopes - The list of scopes for which the token will have access. - * @param options - The options used to configure any requests this - * TokenCredential implementation might make. - */ - async getToken(scopes, options = {}) { - return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => { - newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger); - const arrayScopes = Array.isArray(scopes) ? scopes : [scopes]; - return this.msalClient.getTokenByClientAssertion(arrayScopes, this.getAssertion, newOptions); - }); - } -} -//# sourceMappingURL=clientAssertionCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientCertificateCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientCertificateCredential.js deleted file mode 100644 index be43e121..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientCertificateCredential.js +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createMsalClient } from "../msal/nodeFlows/msalClient.js"; -import { createHash, createPrivateKey } from "node:crypto"; -import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils.js"; -import { credentialLogger } from "../util/logging.js"; -import { readFile } from "node:fs/promises"; -import { tracingClient } from "../util/tracing.js"; -const credentialName = "ClientCertificateCredential"; -const logger = credentialLogger(credentialName); -/** - * Enables authentication to Microsoft Entra ID using a PEM-encoded - * certificate that is assigned to an App Registration. More information - * on how to configure certificate authentication can be found here: - * - * https://learn.microsoft.com/azure/active-directory/develop/active-directory-certificate-credentials#register-your-certificate-with-azure-ad - * - */ -export class ClientCertificateCredential { - constructor(tenantId, clientId, certificatePathOrConfiguration, options = {}) { - if (!tenantId || !clientId) { - throw new Error(`${credentialName}: tenantId and clientId are required parameters.`); - } - this.tenantId = tenantId; - this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); - this.sendCertificateChain = options.sendCertificateChain; - this.certificateConfiguration = Object.assign({}, (typeof certificatePathOrConfiguration === "string" - ? { - certificatePath: certificatePathOrConfiguration, - } - : certificatePathOrConfiguration)); - const certificate = this.certificateConfiguration - .certificate; - const certificatePath = this.certificateConfiguration - .certificatePath; - if (!this.certificateConfiguration || !(certificate || certificatePath)) { - throw new Error(`${credentialName}: Provide either a PEM certificate in string form, or the path to that certificate in the filesystem. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`); - } - if (certificate && certificatePath) { - throw new Error(`${credentialName}: To avoid unexpected behaviors, providing both the contents of a PEM certificate and the path to a PEM certificate is forbidden. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`); - } - this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { logger, tokenCredentialOptions: options })); - } - /** - * Authenticates with Microsoft Entra ID and returns an access token if successful. - * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. - * - * @param scopes - The list of scopes for which the token will have access. - * @param options - The options used to configure any requests this - * TokenCredential implementation might make. - */ - async getToken(scopes, options = {}) { - return tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => { - newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger); - const arrayScopes = Array.isArray(scopes) ? scopes : [scopes]; - const certificate = await this.buildClientCertificate(); - return this.msalClient.getTokenByClientCertificate(arrayScopes, certificate, newOptions); - }); - } - async buildClientCertificate() { - var _a; - const parts = await parseCertificate(this.certificateConfiguration, (_a = this.sendCertificateChain) !== null && _a !== void 0 ? _a : false); - let privateKey; - if (this.certificateConfiguration.certificatePassword !== undefined) { - privateKey = createPrivateKey({ - key: parts.certificateContents, - passphrase: this.certificateConfiguration.certificatePassword, - format: "pem", - }) - .export({ - format: "pem", - type: "pkcs8", - }) - .toString(); - } - else { - privateKey = parts.certificateContents; - } - return { - thumbprint: parts.thumbprint, - thumbprintSha256: parts.thumbprintSha256, - privateKey, - x5c: parts.x5c, - }; - } -} -/** - * Parses a certificate into its relevant parts - * - * @param certificateConfiguration - The certificate contents or path to the certificate - * @param sendCertificateChain - true if the entire certificate chain should be sent for SNI, false otherwise - * @returns The parsed certificate parts and the certificate contents - */ -export async function parseCertificate(certificateConfiguration, sendCertificateChain) { - const certificate = certificateConfiguration.certificate; - const certificatePath = certificateConfiguration - .certificatePath; - const certificateContents = certificate || (await readFile(certificatePath, "utf8")); - const x5c = sendCertificateChain ? certificateContents : undefined; - const certificatePattern = /(-+BEGIN CERTIFICATE-+)(\n\r?|\r\n?)([A-Za-z0-9+/\n\r]+=*)(\n\r?|\r\n?)(-+END CERTIFICATE-+)/g; - const publicKeys = []; - // Match all possible certificates, in the order they are in the file. These will form the chain that is used for x5c - let match; - do { - match = certificatePattern.exec(certificateContents); - if (match) { - publicKeys.push(match[3]); - } - } while (match); - if (publicKeys.length === 0) { - throw new Error("The file at the specified path does not contain a PEM-encoded certificate."); - } - const thumbprint = createHash("sha1") - .update(Buffer.from(publicKeys[0], "base64")) - .digest("hex") - .toUpperCase(); - const thumbprintSha256 = createHash("sha256") - .update(Buffer.from(publicKeys[0], "base64")) - .digest("hex") - .toUpperCase(); - return { - certificateContents, - thumbprintSha256, - thumbprint, - x5c, - }; -} -//# sourceMappingURL=clientCertificateCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientSecretCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientSecretCredential.js deleted file mode 100644 index c6a68a18..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/clientSecretCredential.js +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createMsalClient } from "../msal/nodeFlows/msalClient.js"; -import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils.js"; -import { CredentialUnavailableError } from "../errors.js"; -import { credentialLogger } from "../util/logging.js"; -import { ensureScopes } from "../util/scopeUtils.js"; -import { tracingClient } from "../util/tracing.js"; -const logger = credentialLogger("ClientSecretCredential"); -/** - * Enables authentication to Microsoft Entra ID using a client secret - * that was generated for an App Registration. More information on how - * to configure a client secret can be found here: - * - * https://learn.microsoft.com/entra/identity-platform/quickstart-configure-app-access-web-apis#add-credentials-to-your-web-application - * - */ -export class ClientSecretCredential { - /** - * Creates an instance of the ClientSecretCredential with the details - * needed to authenticate against Microsoft Entra ID with a client - * secret. - * - * @param tenantId - The Microsoft Entra tenant (directory) ID. - * @param clientId - The client (application) ID of an App Registration in the tenant. - * @param clientSecret - A client secret that was generated for the App Registration. - * @param options - Options for configuring the client which makes the authentication request. - */ - constructor(tenantId, clientId, clientSecret, options = {}) { - if (!tenantId) { - throw new CredentialUnavailableError("ClientSecretCredential: tenantId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot."); - } - if (!clientId) { - throw new CredentialUnavailableError("ClientSecretCredential: clientId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot."); - } - if (!clientSecret) { - throw new CredentialUnavailableError("ClientSecretCredential: clientSecret is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot."); - } - this.clientSecret = clientSecret; - this.tenantId = tenantId; - this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); - this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { logger, tokenCredentialOptions: options })); - } - /** - * Authenticates with Microsoft Entra ID and returns an access token if successful. - * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. - * - * @param scopes - The list of scopes for which the token will have access. - * @param options - The options used to configure any requests this - * TokenCredential implementation might make. - */ - async getToken(scopes, options = {}) { - return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => { - newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger); - const arrayScopes = ensureScopes(scopes); - return this.msalClient.getTokenByClientSecret(arrayScopes, this.clientSecret, newOptions); - }); - } -} -//# sourceMappingURL=clientSecretCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/defaultAzureCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/defaultAzureCredential.js deleted file mode 100644 index b8df5544..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/defaultAzureCredential.js +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { ManagedIdentityCredential } from "./managedIdentityCredential/index.js"; -import { AzureCliCredential } from "./azureCliCredential.js"; -import { AzureDeveloperCliCredential } from "./azureDeveloperCliCredential.js"; -import { AzurePowerShellCredential } from "./azurePowerShellCredential.js"; -import { ChainedTokenCredential } from "./chainedTokenCredential.js"; -import { EnvironmentCredential } from "./environmentCredential.js"; -import { WorkloadIdentityCredential } from "./workloadIdentityCredential.js"; -import { credentialLogger } from "../util/logging.js"; -const logger = credentialLogger("DefaultAzureCredential"); -/** - * Creates a {@link ManagedIdentityCredential} from the provided options. - * @param options - Options to configure the credential. - * - * @internal - */ -export function createDefaultManagedIdentityCredential(options = {}) { - var _a, _b, _c, _d; - (_a = options.retryOptions) !== null && _a !== void 0 ? _a : (options.retryOptions = { - maxRetries: 5, - retryDelayInMs: 800, - }); - const managedIdentityClientId = (_b = options === null || options === void 0 ? void 0 : options.managedIdentityClientId) !== null && _b !== void 0 ? _b : process.env.AZURE_CLIENT_ID; - const workloadIdentityClientId = (_c = options === null || options === void 0 ? void 0 : options.workloadIdentityClientId) !== null && _c !== void 0 ? _c : managedIdentityClientId; - const managedResourceId = options === null || options === void 0 ? void 0 : options.managedIdentityResourceId; - const workloadFile = process.env.AZURE_FEDERATED_TOKEN_FILE; - const tenantId = (_d = options === null || options === void 0 ? void 0 : options.tenantId) !== null && _d !== void 0 ? _d : process.env.AZURE_TENANT_ID; - if (managedResourceId) { - const managedIdentityResourceIdOptions = Object.assign(Object.assign({}, options), { resourceId: managedResourceId }); - return new ManagedIdentityCredential(managedIdentityResourceIdOptions); - } - if (workloadFile && workloadIdentityClientId) { - const workloadIdentityCredentialOptions = Object.assign(Object.assign({}, options), { tenantId: tenantId }); - return new ManagedIdentityCredential(workloadIdentityClientId, workloadIdentityCredentialOptions); - } - if (managedIdentityClientId) { - const managedIdentityClientOptions = Object.assign(Object.assign({}, options), { clientId: managedIdentityClientId }); - return new ManagedIdentityCredential(managedIdentityClientOptions); - } - // We may be able to return a UnavailableCredential here, but that may be a breaking change - return new ManagedIdentityCredential(options); -} -/** - * Creates a {@link WorkloadIdentityCredential} from the provided options. - * @param options - Options to configure the credential. - * - * @internal - */ -function createDefaultWorkloadIdentityCredential(options) { - var _a, _b, _c; - const managedIdentityClientId = (_a = options === null || options === void 0 ? void 0 : options.managedIdentityClientId) !== null && _a !== void 0 ? _a : process.env.AZURE_CLIENT_ID; - const workloadIdentityClientId = (_b = options === null || options === void 0 ? void 0 : options.workloadIdentityClientId) !== null && _b !== void 0 ? _b : managedIdentityClientId; - const workloadFile = process.env.AZURE_FEDERATED_TOKEN_FILE; - const tenantId = (_c = options === null || options === void 0 ? void 0 : options.tenantId) !== null && _c !== void 0 ? _c : process.env.AZURE_TENANT_ID; - if (workloadFile && workloadIdentityClientId) { - const workloadIdentityCredentialOptions = Object.assign(Object.assign({}, options), { tenantId, clientId: workloadIdentityClientId, tokenFilePath: workloadFile }); - return new WorkloadIdentityCredential(workloadIdentityCredentialOptions); - } - if (tenantId) { - const workloadIdentityClientTenantOptions = Object.assign(Object.assign({}, options), { tenantId }); - return new WorkloadIdentityCredential(workloadIdentityClientTenantOptions); - } - // We may be able to return a UnavailableCredential here, but that may be a breaking change - return new WorkloadIdentityCredential(options); -} -/** - * Creates a {@link AzureDeveloperCliCredential} from the provided options. - * @param options - Options to configure the credential. - * - * @internal - */ -function createDefaultAzureDeveloperCliCredential(options = {}) { - const processTimeoutInMs = options.processTimeoutInMs; - return new AzureDeveloperCliCredential(Object.assign({ processTimeoutInMs }, options)); -} -/** - * Creates a {@link AzureCliCredential} from the provided options. - * @param options - Options to configure the credential. - * - * @internal - */ -function createDefaultAzureCliCredential(options = {}) { - const processTimeoutInMs = options.processTimeoutInMs; - return new AzureCliCredential(Object.assign({ processTimeoutInMs }, options)); -} -/** - * Creates a {@link AzurePowerShellCredential} from the provided options. - * @param options - Options to configure the credential. - * - * @internal - */ -function createDefaultAzurePowershellCredential(options = {}) { - const processTimeoutInMs = options.processTimeoutInMs; - return new AzurePowerShellCredential(Object.assign({ processTimeoutInMs }, options)); -} -/** - * Creates an {@link EnvironmentCredential} from the provided options. - * @param options - Options to configure the credential. - * - * @internal - */ -export function createEnvironmentCredential(options = {}) { - return new EnvironmentCredential(options); -} -/** - * A no-op credential that logs the reason it was skipped if getToken is called. - * @internal - */ -export class UnavailableDefaultCredential { - constructor(credentialName, message) { - this.credentialName = credentialName; - this.credentialUnavailableErrorMessage = message; - } - getToken() { - logger.getToken.info(`Skipping ${this.credentialName}, reason: ${this.credentialUnavailableErrorMessage}`); - return Promise.resolve(null); - } -} -/** - * Provides a default {@link ChainedTokenCredential} configuration that works for most - * applications that use Azure SDK client libraries. For more information, see - * [DefaultAzureCredential overview](https://aka.ms/azsdk/js/identity/credential-chains#use-defaultazurecredential-for-flexibility). - * - * The following credential types will be tried, in order: - * - * - {@link EnvironmentCredential} - * - {@link WorkloadIdentityCredential} - * - {@link ManagedIdentityCredential} - * - {@link AzureCliCredential} - * - {@link AzurePowerShellCredential} - * - {@link AzureDeveloperCliCredential} - * - * Consult the documentation of these credential types for more information - * on how they attempt authentication. - */ -export class DefaultAzureCredential extends ChainedTokenCredential { - constructor(options) { - // If AZURE_TOKEN_CREDENTIALS is not set, use the default credential chain. - const azureTokenCredentials = process.env.AZURE_TOKEN_CREDENTIALS - ? process.env.AZURE_TOKEN_CREDENTIALS.trim().toLowerCase() - : undefined; - const devCredentialFunctions = [ - createDefaultAzureCliCredential, - createDefaultAzurePowershellCredential, - createDefaultAzureDeveloperCliCredential, - ]; - const prodCredentialFunctions = [ - createEnvironmentCredential, - createDefaultWorkloadIdentityCredential, - createDefaultManagedIdentityCredential, - ]; - let credentialFunctions = []; - // If AZURE_TOKEN_CREDENTIALS is set, use it to determine which credentials to use. - // The value of AZURE_TOKEN_CREDENTIALS should be either "dev" or "prod". - if (azureTokenCredentials) { - switch (azureTokenCredentials) { - case "dev": - // If AZURE_TOKEN_CREDENTIALS is set to "dev", use the developer tool-based credential chain. - credentialFunctions = devCredentialFunctions; - break; - case "prod": - // If AZURE_TOKEN_CREDENTIALS is set to "prod", use the production credential chain. - credentialFunctions = prodCredentialFunctions; - break; - default: { - // If AZURE_TOKEN_CREDENTIALS is set to an unsupported value, throw an error. - // We will throw an error here to prevent the creation of the DefaultAzureCredential. - const errorMessage = `Invalid value for AZURE_TOKEN_CREDENTIALS = ${process.env.AZURE_TOKEN_CREDENTIALS}. Valid values are 'prod' or 'dev'.`; - logger.warning(errorMessage); - throw new Error(errorMessage); - } - } - } - else { - // If AZURE_TOKEN_CREDENTIALS is not set, use the default credential chain. - credentialFunctions = [...prodCredentialFunctions, ...devCredentialFunctions]; - } - // Errors from individual credentials should not be thrown in the DefaultAzureCredential constructor, instead throwing on getToken() which is handled by ChainedTokenCredential. - // When adding new credentials to the default chain, consider: - // 1. Making the constructor parameters required and explicit - // 2. Validating any required parameters in the factory function - // 3. Returning a UnavailableDefaultCredential from the factory function if a credential is unavailable for any reason - const credentials = credentialFunctions.map((createCredentialFn) => { - try { - return createCredentialFn(options); - } - catch (err) { - logger.warning(`Skipped ${createCredentialFn.name} because of an error creating the credential: ${err}`); - return new UnavailableDefaultCredential(createCredentialFn.name, err.message); - } - }); - super(...credentials); - } -} -//# sourceMappingURL=defaultAzureCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/deviceCodeCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/deviceCodeCredential.js deleted file mode 100644 index e8e95f90..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/deviceCodeCredential.js +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, resolveTenantId, } from "../util/tenantIdUtils.js"; -import { credentialLogger } from "../util/logging.js"; -import { ensureScopes } from "../util/scopeUtils.js"; -import { tracingClient } from "../util/tracing.js"; -import { createMsalClient } from "../msal/nodeFlows/msalClient.js"; -import { DeveloperSignOnClientId } from "../constants.js"; -const logger = credentialLogger("DeviceCodeCredential"); -/** - * Method that logs the user code from the DeviceCodeCredential. - * @param deviceCodeInfo - The device code. - */ -export function defaultDeviceCodePromptCallback(deviceCodeInfo) { - console.log(deviceCodeInfo.message); -} -/** - * Enables authentication to Microsoft Entra ID using a device code - * that the user can enter into https://microsoft.com/devicelogin. - */ -export class DeviceCodeCredential { - /** - * Creates an instance of DeviceCodeCredential with the details needed - * to initiate the device code authorization flow with Microsoft Entra ID. - * - * A message will be logged, giving users a code that they can use to authenticate once they go to https://microsoft.com/devicelogin - * - * Developers can configure how this message is shown by passing a custom `userPromptCallback`: - * - * ```ts snippet:device_code_credential_example - * import { DeviceCodeCredential } from "@azure/identity"; - * - * const credential = new DeviceCodeCredential({ - * tenantId: process.env.AZURE_TENANT_ID, - * clientId: process.env.AZURE_CLIENT_ID, - * userPromptCallback: (info) => { - * console.log("CUSTOMIZED PROMPT CALLBACK", info.message); - * }, - * }); - * ``` - * - * @param options - Options for configuring the client which makes the authentication requests. - */ - constructor(options) { - var _a, _b; - this.tenantId = options === null || options === void 0 ? void 0 : options.tenantId; - this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); - const clientId = (_a = options === null || options === void 0 ? void 0 : options.clientId) !== null && _a !== void 0 ? _a : DeveloperSignOnClientId; - const tenantId = resolveTenantId(logger, options === null || options === void 0 ? void 0 : options.tenantId, clientId); - this.userPromptCallback = (_b = options === null || options === void 0 ? void 0 : options.userPromptCallback) !== null && _b !== void 0 ? _b : defaultDeviceCodePromptCallback; - this.msalClient = createMsalClient(clientId, tenantId, Object.assign(Object.assign({}, options), { logger, tokenCredentialOptions: options || {} })); - this.disableAutomaticAuthentication = options === null || options === void 0 ? void 0 : options.disableAutomaticAuthentication; - } - /** - * Authenticates with Microsoft Entra ID and returns an access token if successful. - * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. - * - * If the user provided the option `disableAutomaticAuthentication`, - * once the token can't be retrieved silently, - * this method won't attempt to request user interaction to retrieve the token. - * - * @param scopes - The list of scopes for which the token will have access. - * @param options - The options used to configure any requests this - * TokenCredential implementation might make. - */ - async getToken(scopes, options = {}) { - return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => { - newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger); - const arrayScopes = ensureScopes(scopes); - return this.msalClient.getTokenByDeviceCode(arrayScopes, this.userPromptCallback, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: this.disableAutomaticAuthentication })); - }); - } - /** - * Authenticates with Microsoft Entra ID and returns an access token if successful. - * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. - * - * If the token can't be retrieved silently, this method will always generate a challenge for the user. - * - * @param scopes - The list of scopes for which the token will have access. - * @param options - The options used to configure any requests this - * TokenCredential implementation might make. - */ - async authenticate(scopes, options = {}) { - return tracingClient.withSpan(`${this.constructor.name}.authenticate`, options, async (newOptions) => { - const arrayScopes = Array.isArray(scopes) ? scopes : [scopes]; - await this.msalClient.getTokenByDeviceCode(arrayScopes, this.userPromptCallback, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: false })); - return this.msalClient.getActiveAccount(); - }); - } -} -//# sourceMappingURL=deviceCodeCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/environmentCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/environmentCredential.js deleted file mode 100644 index 365c07f3..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/environmentCredential.js +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { AuthenticationError, CredentialUnavailableError } from "../errors.js"; -import { credentialLogger, formatError, formatSuccess, processEnvVars } from "../util/logging.js"; -import { ClientCertificateCredential } from "./clientCertificateCredential.js"; -import { ClientSecretCredential } from "./clientSecretCredential.js"; -import { UsernamePasswordCredential } from "./usernamePasswordCredential.js"; -import { checkTenantId } from "../util/tenantIdUtils.js"; -import { tracingClient } from "../util/tracing.js"; -/** - * Contains the list of all supported environment variable names so that an - * appropriate error message can be generated when no credentials can be - * configured. - * - * @internal - */ -export const AllSupportedEnvironmentVariables = [ - "AZURE_TENANT_ID", - "AZURE_CLIENT_ID", - "AZURE_CLIENT_SECRET", - "AZURE_CLIENT_CERTIFICATE_PATH", - "AZURE_CLIENT_CERTIFICATE_PASSWORD", - "AZURE_USERNAME", - "AZURE_PASSWORD", - "AZURE_ADDITIONALLY_ALLOWED_TENANTS", - "AZURE_CLIENT_SEND_CERTIFICATE_CHAIN", -]; -function getAdditionallyAllowedTenants() { - var _a; - const additionallyAllowedValues = (_a = process.env.AZURE_ADDITIONALLY_ALLOWED_TENANTS) !== null && _a !== void 0 ? _a : ""; - return additionallyAllowedValues.split(";"); -} -const credentialName = "EnvironmentCredential"; -const logger = credentialLogger(credentialName); -export function getSendCertificateChain() { - var _a; - const sendCertificateChain = ((_a = process.env.AZURE_CLIENT_SEND_CERTIFICATE_CHAIN) !== null && _a !== void 0 ? _a : "").toLowerCase(); - const result = sendCertificateChain === "true" || sendCertificateChain === "1"; - logger.verbose(`AZURE_CLIENT_SEND_CERTIFICATE_CHAIN: ${process.env.AZURE_CLIENT_SEND_CERTIFICATE_CHAIN}; sendCertificateChain: ${result}`); - return result; -} -/** - * Enables authentication to Microsoft Entra ID using a client secret or certificate. - */ -export class EnvironmentCredential { - /** - * Creates an instance of the EnvironmentCredential class and decides what credential to use depending on the available environment variables. - * - * Required environment variables: - * - `AZURE_TENANT_ID`: The Microsoft Entra tenant (directory) ID. - * - `AZURE_CLIENT_ID`: The client (application) ID of an App Registration in the tenant. - * - * If setting the AZURE_TENANT_ID, then you can also set the additionally allowed tenants - * - `AZURE_ADDITIONALLY_ALLOWED_TENANTS`: For multi-tenant applications, specifies additional tenants for which the credential may acquire tokens with a single semicolon delimited string. Use * to allow all tenants. - * - * Environment variables used for client credential authentication: - * - `AZURE_CLIENT_SECRET`: A client secret that was generated for the App Registration. - * - `AZURE_CLIENT_CERTIFICATE_PATH`: The path to a PEM certificate to use during the authentication, instead of the client secret. - * - `AZURE_CLIENT_CERTIFICATE_PASSWORD`: (optional) password for the certificate file. - * - `AZURE_CLIENT_SEND_CERTIFICATE_CHAIN`: (optional) indicates that the certificate chain should be set in x5c header to support subject name / issuer based authentication. - * - * Username and password authentication is deprecated, since it doesn't support multifactor authentication (MFA). See https://aka.ms/azsdk/identity/mfa for more details. Users can still provide environment variables for this authentication method: - * - `AZURE_USERNAME`: Username to authenticate with. - * - `AZURE_PASSWORD`: Password to authenticate with. - * - * If the environment variables required to perform the authentication are missing, a {@link CredentialUnavailableError} will be thrown. - * If the authentication fails, or if there's an unknown error, an {@link AuthenticationError} will be thrown. - * - * @param options - Options for configuring the client which makes the authentication request. - */ - constructor(options) { - // Keep track of any missing environment variables for error details - this._credential = undefined; - const assigned = processEnvVars(AllSupportedEnvironmentVariables).assigned.join(", "); - logger.info(`Found the following environment variables: ${assigned}`); - const tenantId = process.env.AZURE_TENANT_ID, clientId = process.env.AZURE_CLIENT_ID, clientSecret = process.env.AZURE_CLIENT_SECRET; - const additionallyAllowedTenantIds = getAdditionallyAllowedTenants(); - const sendCertificateChain = getSendCertificateChain(); - const newOptions = Object.assign(Object.assign({}, options), { additionallyAllowedTenantIds, sendCertificateChain }); - if (tenantId) { - checkTenantId(logger, tenantId); - } - if (tenantId && clientId && clientSecret) { - logger.info(`Invoking ClientSecretCredential with tenant ID: ${tenantId}, clientId: ${clientId} and clientSecret: [REDACTED]`); - this._credential = new ClientSecretCredential(tenantId, clientId, clientSecret, newOptions); - return; - } - const certificatePath = process.env.AZURE_CLIENT_CERTIFICATE_PATH; - const certificatePassword = process.env.AZURE_CLIENT_CERTIFICATE_PASSWORD; - if (tenantId && clientId && certificatePath) { - logger.info(`Invoking ClientCertificateCredential with tenant ID: ${tenantId}, clientId: ${clientId} and certificatePath: ${certificatePath}`); - this._credential = new ClientCertificateCredential(tenantId, clientId, { certificatePath, certificatePassword }, newOptions); - return; - } - const username = process.env.AZURE_USERNAME; - const password = process.env.AZURE_PASSWORD; - if (tenantId && clientId && username && password) { - logger.info(`Invoking UsernamePasswordCredential with tenant ID: ${tenantId}, clientId: ${clientId} and username: ${username}`); - logger.warning("Environment is configured to use username and password authentication. This authentication method is deprecated, as it doesn't support multifactor authentication (MFA). Use a more secure credential. For more details, see https://aka.ms/azsdk/identity/mfa."); - this._credential = new UsernamePasswordCredential(tenantId, clientId, username, password, newOptions); - } - } - /** - * Authenticates with Microsoft Entra ID and returns an access token if successful. - * - * @param scopes - The list of scopes for which the token will have access. - * @param options - Optional parameters. See {@link GetTokenOptions}. - */ - async getToken(scopes, options = {}) { - return tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => { - if (this._credential) { - try { - const result = await this._credential.getToken(scopes, newOptions); - logger.getToken.info(formatSuccess(scopes)); - return result; - } - catch (err) { - const authenticationError = new AuthenticationError(400, { - error: `${credentialName} authentication failed. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`, - error_description: err.message.toString().split("More details:").join(""), - }); - logger.getToken.info(formatError(scopes, authenticationError)); - throw authenticationError; - } - } - throw new CredentialUnavailableError(`${credentialName} is unavailable. No underlying credential could be used. To troubleshoot, visit https://aka.ms/azsdk/js/identity/environmentcredential/troubleshoot.`); - }); - } -} -//# sourceMappingURL=environmentCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/interactiveBrowserCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/interactiveBrowserCredential.js deleted file mode 100644 index 0ec597f6..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/interactiveBrowserCredential.js +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, resolveTenantId, } from "../util/tenantIdUtils.js"; -import { credentialLogger } from "../util/logging.js"; -import { ensureScopes } from "../util/scopeUtils.js"; -import { tracingClient } from "../util/tracing.js"; -import { createMsalClient } from "../msal/nodeFlows/msalClient.js"; -import { DeveloperSignOnClientId } from "../constants.js"; -const logger = credentialLogger("InteractiveBrowserCredential"); -/** - * Enables authentication to Microsoft Entra ID inside of the web browser - * using the interactive login flow. - */ -export class InteractiveBrowserCredential { - /** - * Creates an instance of InteractiveBrowserCredential with the details needed. - * - * This credential uses the [Authorization Code Flow](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow). - * On Node.js, it will open a browser window while it listens for a redirect response from the authentication service. - * On browsers, it authenticates via popups. The `loginStyle` optional parameter can be set to `redirect` to authenticate by redirecting the user to an Azure secure login page, which then will redirect the user back to the web application where the authentication started. - * - * For Node.js, if a `clientId` is provided, the Microsoft Entra application will need to be configured to have a "Mobile and desktop applications" redirect endpoint. - * Follow our guide on [setting up Redirect URIs for Desktop apps that calls to web APIs](https://learn.microsoft.com/entra/identity-platform/scenario-desktop-app-registration#redirect-uris). - * - * @param options - Options for configuring the client which makes the authentication requests. - */ - constructor(options) { - var _a, _b, _c, _d, _e; - this.tenantId = resolveTenantId(logger, options.tenantId, options.clientId); - this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); - const msalClientOptions = Object.assign(Object.assign({}, options), { tokenCredentialOptions: options, logger }); - const ibcNodeOptions = options; - this.browserCustomizationOptions = ibcNodeOptions.browserCustomizationOptions; - this.loginHint = ibcNodeOptions.loginHint; - if ((_a = ibcNodeOptions === null || ibcNodeOptions === void 0 ? void 0 : ibcNodeOptions.brokerOptions) === null || _a === void 0 ? void 0 : _a.enabled) { - if (!((_b = ibcNodeOptions === null || ibcNodeOptions === void 0 ? void 0 : ibcNodeOptions.brokerOptions) === null || _b === void 0 ? void 0 : _b.parentWindowHandle)) { - throw new Error("In order to do WAM authentication, `parentWindowHandle` under `brokerOptions` is a required parameter"); - } - else { - msalClientOptions.brokerOptions = { - enabled: true, - parentWindowHandle: ibcNodeOptions.brokerOptions.parentWindowHandle, - legacyEnableMsaPassthrough: (_c = ibcNodeOptions.brokerOptions) === null || _c === void 0 ? void 0 : _c.legacyEnableMsaPassthrough, - useDefaultBrokerAccount: (_d = ibcNodeOptions.brokerOptions) === null || _d === void 0 ? void 0 : _d.useDefaultBrokerAccount, - }; - } - } - this.msalClient = createMsalClient((_e = options.clientId) !== null && _e !== void 0 ? _e : DeveloperSignOnClientId, this.tenantId, msalClientOptions); - this.disableAutomaticAuthentication = options === null || options === void 0 ? void 0 : options.disableAutomaticAuthentication; - } - /** - * Authenticates with Microsoft Entra ID and returns an access token if successful. - * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. - * - * If the user provided the option `disableAutomaticAuthentication`, - * once the token can't be retrieved silently, - * this method won't attempt to request user interaction to retrieve the token. - * - * @param scopes - The list of scopes for which the token will have access. - * @param options - The options used to configure any requests this - * TokenCredential implementation might make. - */ - async getToken(scopes, options = {}) { - return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => { - newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger); - const arrayScopes = ensureScopes(scopes); - return this.msalClient.getTokenByInteractiveRequest(arrayScopes, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: this.disableAutomaticAuthentication, browserCustomizationOptions: this.browserCustomizationOptions, loginHint: this.loginHint })); - }); - } - /** - * Authenticates with Microsoft Entra ID and returns an access token if successful. - * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. - * - * If the token can't be retrieved silently, this method will always generate a challenge for the user. - * - * On Node.js, this credential has [Proof Key for Code Exchange (PKCE)](https://datatracker.ietf.org/doc/html/rfc7636) enabled by default. - * PKCE is a security feature that mitigates authentication code interception attacks. - * - * @param scopes - The list of scopes for which the token will have access. - * @param options - The options used to configure any requests this - * TokenCredential implementation might make. - */ - async authenticate(scopes, options = {}) { - return tracingClient.withSpan(`${this.constructor.name}.authenticate`, options, async (newOptions) => { - const arrayScopes = ensureScopes(scopes); - await this.msalClient.getTokenByInteractiveRequest(arrayScopes, Object.assign(Object.assign({}, newOptions), { disableAutomaticAuthentication: false, browserCustomizationOptions: this.browserCustomizationOptions, loginHint: this.loginHint })); - return this.msalClient.getActiveAccount(); - }); - } -} -//# sourceMappingURL=interactiveBrowserCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/imdsMsi.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/imdsMsi.js deleted file mode 100644 index 6f38f0a4..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/imdsMsi.js +++ /dev/null @@ -1,99 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createHttpHeaders, createPipelineRequest } from "@azure/core-rest-pipeline"; -import { isError } from "@azure/core-util"; -import { credentialLogger } from "../../util/logging.js"; -import { mapScopesToResource } from "./utils.js"; -import { tracingClient } from "../../util/tracing.js"; -const msiName = "ManagedIdentityCredential - IMDS"; -const logger = credentialLogger(msiName); -const imdsHost = "http://169.254.169.254"; -const imdsEndpointPath = "/metadata/identity/oauth2/token"; -/** - * Generates an invalid request options to get a response quickly from IMDS endpoint. - * The response indicates the availability of IMSD service; otherwise the request would time out. - */ -function prepareInvalidRequestOptions(scopes) { - var _a; - const resource = mapScopesToResource(scopes); - if (!resource) { - throw new Error(`${msiName}: Multiple scopes are not supported.`); - } - // Pod Identity will try to process this request even if the Metadata header is missing. - // We can exclude the request query to ensure no IMDS endpoint tries to process the ping request. - const url = new URL(imdsEndpointPath, (_a = process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) !== null && _a !== void 0 ? _a : imdsHost); - const rawHeaders = { - Accept: "application/json", - // intentionally leave out the Metadata header to invoke an error from IMDS endpoint. - }; - return { - // intentionally not including any query - url: `${url}`, - method: "GET", - headers: createHttpHeaders(rawHeaders), - }; -} -/** - * Defines how to determine whether the Azure IMDS MSI is available. - * - * Actually getting the token once we determine IMDS is available is handled by MSAL. - */ -export const imdsMsi = { - name: "imdsMsi", - async isAvailable(options) { - const { scopes, identityClient, getTokenOptions } = options; - const resource = mapScopesToResource(scopes); - if (!resource) { - logger.info(`${msiName}: Unavailable. Multiple scopes are not supported.`); - return false; - } - // if the PodIdentityEndpoint environment variable was set no need to probe the endpoint, it can be assumed to exist - if (process.env.AZURE_POD_IDENTITY_AUTHORITY_HOST) { - return true; - } - if (!identityClient) { - throw new Error("Missing IdentityClient"); - } - const requestOptions = prepareInvalidRequestOptions(resource); - return tracingClient.withSpan("ManagedIdentityCredential-pingImdsEndpoint", getTokenOptions !== null && getTokenOptions !== void 0 ? getTokenOptions : {}, async (updatedOptions) => { - var _a, _b; - requestOptions.tracingOptions = updatedOptions.tracingOptions; - // Create a request with a timeout since we expect that - // not having a "Metadata" header should cause an error to be - // returned quickly from the endpoint, proving its availability. - const request = createPipelineRequest(requestOptions); - // Default to 1000 if the default of 0 is used. - // Negative values can still be used to disable the timeout. - request.timeout = ((_a = updatedOptions.requestOptions) === null || _a === void 0 ? void 0 : _a.timeout) || 1000; - // This MSI uses the imdsEndpoint to get the token, which only uses http:// - request.allowInsecureConnection = true; - let response; - try { - logger.info(`${msiName}: Pinging the Azure IMDS endpoint`); - response = await identityClient.sendRequest(request); - } - catch (err) { - // If the request failed, or Node.js was unable to establish a connection, - // or the host was down, we'll assume the IMDS endpoint isn't available. - if (isError(err)) { - logger.verbose(`${msiName}: Caught error ${err.name}: ${err.message}`); - } - // This is a special case for Docker Desktop which responds with a 403 with a message that contains "A socket operation was attempted to an unreachable network" or "A socket operation was attempted to an unreachable host" - // rather than just timing out, as expected. - logger.info(`${msiName}: The Azure IMDS endpoint is unavailable`); - return false; - } - if (response.status === 403) { - if ((_b = response.bodyAsText) === null || _b === void 0 ? void 0 : _b.includes("unreachable")) { - logger.info(`${msiName}: The Azure IMDS endpoint is unavailable`); - logger.info(`${msiName}: ${response.bodyAsText}`); - return false; - } - } - // If we received any response, the endpoint is available - logger.info(`${msiName}: The Azure IMDS endpoint is available`); - return true; - }); - }, -}; -//# sourceMappingURL=imdsMsi.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/imdsRetryPolicy.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/imdsRetryPolicy.js deleted file mode 100644 index af248aae..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/imdsRetryPolicy.js +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { retryPolicy } from "@azure/core-rest-pipeline"; -import { calculateRetryDelay } from "@azure/core-util"; -// Matches the default retry configuration in expontentialRetryStrategy.ts -const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64; -/** - * An additional policy that retries on 404 errors. The default retry policy does not retry on - * 404s, but the IMDS endpoint can return 404s when the token is not yet available. This policy - * will retry on 404s with an exponential backoff. - * - * @param msiRetryConfig - The retry configuration for the MSI credential. - * @returns - The policy that will retry on 404s. - */ -export function imdsRetryPolicy(msiRetryConfig) { - return retryPolicy([ - { - name: "imdsRetryPolicy", - retry: ({ retryCount, response }) => { - if ((response === null || response === void 0 ? void 0 : response.status) !== 404) { - return { skipStrategy: true }; - } - return calculateRetryDelay(retryCount, { - retryDelayInMs: msiRetryConfig.startDelayInMs, - maxRetryDelayInMs: DEFAULT_CLIENT_MAX_RETRY_INTERVAL, - }); - }, - }, - ], { - maxRetries: msiRetryConfig.maxRetries, - }); -} -//# sourceMappingURL=imdsRetryPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/index.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/index.js deleted file mode 100644 index fa64e374..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/index.js +++ /dev/null @@ -1,239 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { getLogLevel } from "@azure/logger"; -import { ManagedIdentityApplication } from "@azure/msal-node"; -import { IdentityClient } from "../../client/identityClient.js"; -import { AuthenticationRequiredError, CredentialUnavailableError } from "../../errors.js"; -import { getMSALLogLevel, defaultLoggerCallback } from "../../msal/utils.js"; -import { imdsRetryPolicy } from "./imdsRetryPolicy.js"; -import { formatSuccess, formatError, credentialLogger } from "../../util/logging.js"; -import { tracingClient } from "../../util/tracing.js"; -import { imdsMsi } from "./imdsMsi.js"; -import { tokenExchangeMsi } from "./tokenExchangeMsi.js"; -import { mapScopesToResource, serviceFabricErrorMessage } from "./utils.js"; -const logger = credentialLogger("ManagedIdentityCredential"); -/** - * Attempts authentication using a managed identity available at the deployment environment. - * This authentication type works in Azure VMs, App Service instances, Azure Functions applications, - * Azure Kubernetes Services, Azure Service Fabric instances and inside of the Azure Cloud Shell. - * - * More information about configuring managed identities can be found here: - * https://learn.microsoft.com/azure/active-directory/managed-identities-azure-resources/overview - */ -export class ManagedIdentityCredential { - /** - * @internal - * @hidden - */ - constructor(clientIdOrOptions, options) { - var _a, _b; - this.msiRetryConfig = { - maxRetries: 5, - startDelayInMs: 800, - intervalIncrement: 2, - }; - let _options; - if (typeof clientIdOrOptions === "string") { - this.clientId = clientIdOrOptions; - _options = options !== null && options !== void 0 ? options : {}; - } - else { - this.clientId = clientIdOrOptions === null || clientIdOrOptions === void 0 ? void 0 : clientIdOrOptions.clientId; - _options = clientIdOrOptions !== null && clientIdOrOptions !== void 0 ? clientIdOrOptions : {}; - } - this.resourceId = _options === null || _options === void 0 ? void 0 : _options.resourceId; - this.objectId = _options === null || _options === void 0 ? void 0 : _options.objectId; - // For JavaScript users. - const providedIds = [ - { key: "clientId", value: this.clientId }, - { key: "resourceId", value: this.resourceId }, - { key: "objectId", value: this.objectId }, - ].filter((id) => id.value); - if (providedIds.length > 1) { - throw new Error(`ManagedIdentityCredential: only one of 'clientId', 'resourceId', or 'objectId' can be provided. Received values: ${JSON.stringify({ clientId: this.clientId, resourceId: this.resourceId, objectId: this.objectId })}`); - } - // ManagedIdentity uses http for local requests - _options.allowInsecureConnection = true; - if (((_a = _options.retryOptions) === null || _a === void 0 ? void 0 : _a.maxRetries) !== undefined) { - this.msiRetryConfig.maxRetries = _options.retryOptions.maxRetries; - } - this.identityClient = new IdentityClient(Object.assign(Object.assign({}, _options), { additionalPolicies: [{ policy: imdsRetryPolicy(this.msiRetryConfig), position: "perCall" }] })); - this.managedIdentityApp = new ManagedIdentityApplication({ - managedIdentityIdParams: { - userAssignedClientId: this.clientId, - userAssignedResourceId: this.resourceId, - userAssignedObjectId: this.objectId, - }, - system: { - disableInternalRetries: true, - networkClient: this.identityClient, - loggerOptions: { - logLevel: getMSALLogLevel(getLogLevel()), - piiLoggingEnabled: (_b = _options.loggingOptions) === null || _b === void 0 ? void 0 : _b.enableUnsafeSupportLogging, - loggerCallback: defaultLoggerCallback(logger), - }, - }, - }); - this.isAvailableIdentityClient = new IdentityClient(Object.assign(Object.assign({}, _options), { retryOptions: { - maxRetries: 0, - } })); - const managedIdentitySource = this.managedIdentityApp.getManagedIdentitySource(); - // CloudShell MSI will ignore any user-assigned identity passed as parameters. To avoid confusion, we prevent this from happening as early as possible. - if (managedIdentitySource === "CloudShell") { - if (this.clientId || this.resourceId || this.objectId) { - logger.warning(`CloudShell MSI detected with user-provided IDs - throwing. Received values: ${JSON.stringify({ - clientId: this.clientId, - resourceId: this.resourceId, - objectId: this.objectId, - })}.`); - throw new CredentialUnavailableError("ManagedIdentityCredential: Specifying a user-assigned managed identity is not supported for CloudShell at runtime. When using Managed Identity in CloudShell, omit the clientId, resourceId, and objectId parameters."); - } - } - // ServiceFabric does not support specifying user-assigned managed identity by client ID or resource ID. The managed identity selected is based on the resource configuration. - if (managedIdentitySource === "ServiceFabric") { - if (this.clientId || this.resourceId || this.objectId) { - logger.warning(`Service Fabric detected with user-provided IDs - throwing. Received values: ${JSON.stringify({ - clientId: this.clientId, - resourceId: this.resourceId, - objectId: this.objectId, - })}.`); - throw new CredentialUnavailableError(`ManagedIdentityCredential: ${serviceFabricErrorMessage}`); - } - } - logger.info(`Using ${managedIdentitySource} managed identity.`); - // Check if either clientId, resourceId or objectId was provided and log the value used - if (providedIds.length === 1) { - const { key, value } = providedIds[0]; - logger.info(`${managedIdentitySource} with ${key}: ${value}`); - } - } - /** - * Authenticates with Microsoft Entra ID and returns an access token if successful. - * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. - * If an unexpected error occurs, an {@link AuthenticationError} will be thrown with the details of the failure. - * - * @param scopes - The list of scopes for which the token will have access. - * @param options - The options used to configure any requests this - * TokenCredential implementation might make. - */ - async getToken(scopes, options = {}) { - logger.getToken.info("Using the MSAL provider for Managed Identity."); - const resource = mapScopesToResource(scopes); - if (!resource) { - throw new CredentialUnavailableError(`ManagedIdentityCredential: Multiple scopes are not supported. Scopes: ${JSON.stringify(scopes)}`); - } - return tracingClient.withSpan("ManagedIdentityCredential.getToken", options, async () => { - var _a; - try { - const isTokenExchangeMsi = await tokenExchangeMsi.isAvailable(this.clientId); - // Most scenarios are handled by MSAL except for two: - // AKS pod identity - MSAL does not implement the token exchange flow. - // IMDS Endpoint probing - MSAL does not do any probing before trying to get a token. - // As a DefaultAzureCredential optimization we probe the IMDS endpoint with a short timeout and no retries before actually trying to get a token - // We will continue to implement these features in the Identity library. - const identitySource = this.managedIdentityApp.getManagedIdentitySource(); - const isImdsMsi = identitySource === "DefaultToImds" || identitySource === "Imds"; // Neither actually checks that IMDS endpoint is available, just that it's the source the MSAL _would_ try to use. - logger.getToken.info(`MSAL Identity source: ${identitySource}`); - if (isTokenExchangeMsi) { - // In the AKS scenario we will use the existing tokenExchangeMsi indefinitely. - logger.getToken.info("Using the token exchange managed identity."); - const result = await tokenExchangeMsi.getToken({ - scopes, - clientId: this.clientId, - identityClient: this.identityClient, - retryConfig: this.msiRetryConfig, - resourceId: this.resourceId, - }); - if (result === null) { - throw new CredentialUnavailableError("Attempted to use the token exchange managed identity, but received a null response."); - } - return result; - } - else if (isImdsMsi) { - // In the IMDS scenario we will probe the IMDS endpoint to ensure it's available before trying to get a token. - // If the IMDS endpoint is not available and this is the source that MSAL will use, we will fail-fast with an error that tells DAC to move to the next credential. - logger.getToken.info("Using the IMDS endpoint to probe for availability."); - const isAvailable = await imdsMsi.isAvailable({ - scopes, - clientId: this.clientId, - getTokenOptions: options, - identityClient: this.isAvailableIdentityClient, - resourceId: this.resourceId, - }); - if (!isAvailable) { - throw new CredentialUnavailableError(`Attempted to use the IMDS endpoint, but it is not available.`); - } - } - // If we got this far, it means: - // - This is not a tokenExchangeMsi, - // - We already probed for IMDS endpoint availability and failed-fast if it's unreachable. - // We can proceed normally by calling MSAL for a token. - logger.getToken.info("Calling into MSAL for managed identity token."); - const token = await this.managedIdentityApp.acquireToken({ - resource, - }); - this.ensureValidMsalToken(scopes, token, options); - logger.getToken.info(formatSuccess(scopes)); - return { - expiresOnTimestamp: token.expiresOn.getTime(), - token: token.accessToken, - refreshAfterTimestamp: (_a = token.refreshOn) === null || _a === void 0 ? void 0 : _a.getTime(), - tokenType: "Bearer", - }; - } - catch (err) { - logger.getToken.error(formatError(scopes, err)); - // AuthenticationRequiredError described as Error to enforce authentication after trying to retrieve a token silently. - // TODO: why would this _ever_ happen considering we're not trying the silent request in this flow? - if (err.name === "AuthenticationRequiredError") { - throw err; - } - if (isNetworkError(err)) { - throw new CredentialUnavailableError(`ManagedIdentityCredential: Network unreachable. Message: ${err.message}`, { cause: err }); - } - throw new CredentialUnavailableError(`ManagedIdentityCredential: Authentication failed. Message ${err.message}`, { cause: err }); - } - }); - } - /** - * Ensures the validity of the MSAL token - */ - ensureValidMsalToken(scopes, msalToken, getTokenOptions) { - const createError = (message) => { - logger.getToken.info(message); - return new AuthenticationRequiredError({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - getTokenOptions, - message, - }); - }; - if (!msalToken) { - throw createError("No response."); - } - if (!msalToken.expiresOn) { - throw createError(`Response had no "expiresOn" property.`); - } - if (!msalToken.accessToken) { - throw createError(`Response had no "accessToken" property.`); - } - } -} -function isNetworkError(err) { - // MSAL error - if (err.errorCode === "network_error") { - return true; - } - // Probe errors - if (err.code === "ENETUNREACH" || err.code === "EHOSTUNREACH") { - return true; - } - // This is a special case for Docker Desktop which responds with a 403 with a message that contains "A socket operation was attempted to an unreachable network" or "A socket operation was attempted to an unreachable host" - // rather than just timing out, as expected. - if (err.statusCode === 403 || err.code === 403) { - if (err.message.includes("unreachable")) { - return true; - } - } - return false; -} -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/tokenExchangeMsi.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/tokenExchangeMsi.js deleted file mode 100644 index ba748f1a..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/tokenExchangeMsi.js +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { WorkloadIdentityCredential } from "../workloadIdentityCredential.js"; -import { credentialLogger } from "../../util/logging.js"; -const msiName = "ManagedIdentityCredential - Token Exchange"; -const logger = credentialLogger(msiName); -/** - * Defines how to determine whether the token exchange MSI is available, and also how to retrieve a token from the token exchange MSI. - * - * Token exchange MSI (used by AKS) is the only MSI implementation handled entirely by Azure Identity. - * The rest have been migrated to MSAL. - */ -export const tokenExchangeMsi = { - name: "tokenExchangeMsi", - async isAvailable(clientId) { - const env = process.env; - const result = Boolean((clientId || env.AZURE_CLIENT_ID) && - env.AZURE_TENANT_ID && - process.env.AZURE_FEDERATED_TOKEN_FILE); - if (!result) { - logger.info(`${msiName}: Unavailable. The environment variables needed are: AZURE_CLIENT_ID (or the client ID sent through the parameters), AZURE_TENANT_ID and AZURE_FEDERATED_TOKEN_FILE`); - } - return result; - }, - async getToken(configuration, getTokenOptions = {}) { - const { scopes, clientId } = configuration; - const identityClientTokenCredentialOptions = {}; - const workloadIdentityCredential = new WorkloadIdentityCredential(Object.assign(Object.assign({ clientId, tenantId: process.env.AZURE_TENANT_ID, tokenFilePath: process.env.AZURE_FEDERATED_TOKEN_FILE }, identityClientTokenCredentialOptions), { disableInstanceDiscovery: true })); - return workloadIdentityCredential.getToken(scopes, getTokenOptions); - }, -}; -//# sourceMappingURL=tokenExchangeMsi.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/utils.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/utils.js deleted file mode 100644 index 6bf58871..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/managedIdentityCredential/utils.js +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -const DefaultScopeSuffix = "/.default"; -/** - * Error message for Service Fabric Managed Identity environment. - */ -export const serviceFabricErrorMessage = "Specifying a `clientId` or `resourceId` is not supported by the Service Fabric managed identity environment. The managed identity configuration is determined by the Service Fabric cluster resource configuration. See https://aka.ms/servicefabricmi for more information"; -/** - * Most MSIs send requests to the IMDS endpoint, or a similar endpoint. - * These are GET requests that require sending a `resource` parameter on the query. - * This resource can be derived from the scopes received through the getToken call, as long as only one scope is received. - * Multiple scopes assume that the resulting token will have access to multiple resources, which won't be the case. - * - * For that reason, when we encounter multiple scopes, we return undefined. - * It's up to the individual MSI implementations to throw the errors (which helps us provide less generic errors). - */ -export function mapScopesToResource(scopes) { - let scope = ""; - if (Array.isArray(scopes)) { - if (scopes.length !== 1) { - return; - } - scope = scopes[0]; - } - else if (typeof scopes === "string") { - scope = scopes; - } - if (!scope.endsWith(DefaultScopeSuffix)) { - return scope; - } - return scope.substr(0, scope.lastIndexOf(DefaultScopeSuffix)); -} -/** - * Given a token response, return the expiration timestamp as the number of milliseconds from the Unix epoch. - * @param body - A parsed response body from the authentication endpoint. - */ -export function parseExpirationTimestamp(body) { - if (typeof body.expires_on === "number") { - return body.expires_on * 1000; - } - if (typeof body.expires_on === "string") { - const asNumber = +body.expires_on; - if (!isNaN(asNumber)) { - return asNumber * 1000; - } - const asDate = Date.parse(body.expires_on); - if (!isNaN(asDate)) { - return asDate; - } - } - if (typeof body.expires_in === "number") { - return Date.now() + body.expires_in * 1000; - } - throw new Error(`Failed to parse token expiration from body. expires_in="${body.expires_in}", expires_on="${body.expires_on}"`); -} -/** - * Given a token response, return the expiration timestamp as the number of milliseconds from the Unix epoch. - * @param body - A parsed response body from the authentication endpoint. - */ -export function parseRefreshTimestamp(body) { - if (body.refresh_on) { - if (typeof body.refresh_on === "number") { - return body.refresh_on * 1000; - } - if (typeof body.refresh_on === "string") { - const asNumber = +body.refresh_on; - if (!isNaN(asNumber)) { - return asNumber * 1000; - } - const asDate = Date.parse(body.refresh_on); - if (!isNaN(asDate)) { - return asDate; - } - } - throw new Error(`Failed to parse refresh_on from body. refresh_on="${body.refresh_on}"`); - } - else { - return undefined; - } -} -//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/onBehalfOfCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/onBehalfOfCredential.js deleted file mode 100644 index 4c3188b8..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/onBehalfOfCredential.js +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createMsalClient } from "../msal/nodeFlows/msalClient.js"; -import { credentialLogger, formatError } from "../util/logging.js"; -import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils.js"; -import { CredentialUnavailableError } from "../errors.js"; -import { createHash } from "node:crypto"; -import { ensureScopes } from "../util/scopeUtils.js"; -import { readFile } from "node:fs/promises"; -import { tracingClient } from "../util/tracing.js"; -const credentialName = "OnBehalfOfCredential"; -const logger = credentialLogger(credentialName); -/** - * Enables authentication to Microsoft Entra ID using the [On Behalf Of flow](https://learn.microsoft.com/entra/identity-platform/v2-oauth2-on-behalf-of-flow). - */ -export class OnBehalfOfCredential { - constructor(options) { - const { clientSecret } = options; - const { certificatePath, sendCertificateChain } = options; - const { getAssertion } = options; - const { tenantId, clientId, userAssertionToken, additionallyAllowedTenants: additionallyAllowedTenantIds, } = options; - if (!tenantId) { - throw new CredentialUnavailableError(`${credentialName}: tenantId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`); - } - if (!clientId) { - throw new CredentialUnavailableError(`${credentialName}: clientId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`); - } - if (!clientSecret && !certificatePath && !getAssertion) { - throw new CredentialUnavailableError(`${credentialName}: You must provide one of clientSecret, certificatePath, or a getAssertion callback but none were provided. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`); - } - if (!userAssertionToken) { - throw new CredentialUnavailableError(`${credentialName}: userAssertionToken is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/serviceprincipalauthentication/troubleshoot.`); - } - this.certificatePath = certificatePath; - this.clientSecret = clientSecret; - this.userAssertionToken = userAssertionToken; - this.sendCertificateChain = sendCertificateChain; - this.clientAssertion = getAssertion; - this.tenantId = tenantId; - this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(additionallyAllowedTenantIds); - this.msalClient = createMsalClient(clientId, this.tenantId, Object.assign(Object.assign({}, options), { logger, tokenCredentialOptions: options })); - } - /** - * Authenticates with Microsoft Entra ID and returns an access token if successful. - * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. - * - * @param scopes - The list of scopes for which the token will have access. - * @param options - The options used to configure the underlying network requests. - */ - async getToken(scopes, options = {}) { - return tracingClient.withSpan(`${credentialName}.getToken`, options, async (newOptions) => { - newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger); - const arrayScopes = ensureScopes(scopes); - if (this.certificatePath) { - const clientCertificate = await this.buildClientCertificate(this.certificatePath); - return this.msalClient.getTokenOnBehalfOf(arrayScopes, this.userAssertionToken, clientCertificate, newOptions); - } - else if (this.clientSecret) { - return this.msalClient.getTokenOnBehalfOf(arrayScopes, this.userAssertionToken, this.clientSecret, options); - } - else if (this.clientAssertion) { - return this.msalClient.getTokenOnBehalfOf(arrayScopes, this.userAssertionToken, this.clientAssertion, options); - } - else { - // this is an invalid scenario and is a bug, as the constructor should have thrown an error if neither clientSecret nor certificatePath nor clientAssertion were provided - throw new Error("Expected either clientSecret or certificatePath or clientAssertion to be defined."); - } - }); - } - async buildClientCertificate(certificatePath) { - try { - const parts = await this.parseCertificate({ certificatePath }, this.sendCertificateChain); - return { - thumbprint: parts.thumbprint, - thumbprintSha256: parts.thumbprintSha256, - privateKey: parts.certificateContents, - x5c: parts.x5c, - }; - } - catch (error) { - logger.info(formatError("", error)); - throw error; - } - } - async parseCertificate(configuration, sendCertificateChain) { - const certificatePath = configuration.certificatePath; - const certificateContents = await readFile(certificatePath, "utf8"); - const x5c = sendCertificateChain ? certificateContents : undefined; - const certificatePattern = /(-+BEGIN CERTIFICATE-+)(\n\r?|\r\n?)([A-Za-z0-9+/\n\r]+=*)(\n\r?|\r\n?)(-+END CERTIFICATE-+)/g; - const publicKeys = []; - // Match all possible certificates, in the order they are in the file. These will form the chain that is used for x5c - let match; - do { - match = certificatePattern.exec(certificateContents); - if (match) { - publicKeys.push(match[3]); - } - } while (match); - if (publicKeys.length === 0) { - throw new Error("The file at the specified path does not contain a PEM-encoded certificate."); - } - const thumbprint = createHash("sha1") - .update(Buffer.from(publicKeys[0], "base64")) - .digest("hex") - .toUpperCase(); - const thumbprintSha256 = createHash("sha256") - .update(Buffer.from(publicKeys[0], "base64")) - .digest("hex") - .toUpperCase(); - return { - certificateContents, - thumbprintSha256, - thumbprint, - x5c, - }; - } -} -//# sourceMappingURL=onBehalfOfCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/usernamePasswordCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/usernamePasswordCredential.js deleted file mode 100644 index 93ee5455..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/usernamePasswordCredential.js +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createMsalClient } from "../msal/nodeFlows/msalClient.js"; -import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils.js"; -import { CredentialUnavailableError } from "../errors.js"; -import { credentialLogger } from "../util/logging.js"; -import { ensureScopes } from "../util/scopeUtils.js"; -import { tracingClient } from "../util/tracing.js"; -const logger = credentialLogger("UsernamePasswordCredential"); -/** - * Enables authentication to Microsoft Entra ID with a user's - * username and password. This credential requires a high degree of - * trust so you should only use it when other, more secure credential - * types can't be used. - * @deprecated UsernamePasswordCredential is deprecated. Use a more secure credential. See https://aka.ms/azsdk/identity/mfa for details. - */ -export class UsernamePasswordCredential { - /** - * Creates an instance of the UsernamePasswordCredential with the details - * needed to authenticate against Microsoft Entra ID with a username - * and password. - * - * @param tenantId - The Microsoft Entra tenant (directory). - * @param clientId - The client (application) ID of an App Registration in the tenant. - * @param username - The user account's e-mail address (user name). - * @param password - The user account's account password - * @param options - Options for configuring the client which makes the authentication request. - */ - constructor(tenantId, clientId, username, password, options = {}) { - if (!tenantId) { - throw new CredentialUnavailableError("UsernamePasswordCredential: tenantId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot."); - } - if (!clientId) { - throw new CredentialUnavailableError("UsernamePasswordCredential: clientId is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot."); - } - if (!username) { - throw new CredentialUnavailableError("UsernamePasswordCredential: username is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot."); - } - if (!password) { - throw new CredentialUnavailableError("UsernamePasswordCredential: password is a required parameter. To troubleshoot, visit https://aka.ms/azsdk/js/identity/usernamepasswordcredential/troubleshoot."); - } - this.tenantId = tenantId; - this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); - this.username = username; - this.password = password; - this.msalClient = createMsalClient(clientId, this.tenantId, Object.assign(Object.assign({}, options), { tokenCredentialOptions: options !== null && options !== void 0 ? options : {} })); - } - /** - * Authenticates with Microsoft Entra ID and returns an access token if successful. - * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. - * - * If the user provided the option `disableAutomaticAuthentication`, - * once the token can't be retrieved silently, - * this method won't attempt to request user interaction to retrieve the token. - * - * @param scopes - The list of scopes for which the token will have access. - * @param options - The options used to configure any requests this - * TokenCredential implementation might make. - */ - async getToken(scopes, options = {}) { - return tracingClient.withSpan(`${this.constructor.name}.getToken`, options, async (newOptions) => { - newOptions.tenantId = processMultiTenantRequest(this.tenantId, newOptions, this.additionallyAllowedTenantIds, logger); - const arrayScopes = ensureScopes(scopes); - return this.msalClient.getTokenByUsernamePassword(arrayScopes, this.username, this.password, newOptions); - }); - } -} -//# sourceMappingURL=usernamePasswordCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/visualStudioCodeCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/visualStudioCodeCredential.js deleted file mode 100644 index afa39e59..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/visualStudioCodeCredential.js +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { credentialLogger, formatError, formatSuccess } from "../util/logging.js"; -import { processMultiTenantRequest, resolveAdditionallyAllowedTenantIds, } from "../util/tenantIdUtils.js"; -import { AzureAuthorityHosts } from "../constants.js"; -import { CredentialUnavailableError } from "../errors.js"; -import { IdentityClient } from "../client/identityClient.js"; -import { checkTenantId } from "../util/tenantIdUtils.js"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; -const CommonTenantId = "common"; -const AzureAccountClientId = "aebc6443-996d-45c2-90f0-388ff96faa56"; // VSC: 'aebc6443-996d-45c2-90f0-388ff96faa56' -const logger = credentialLogger("VisualStudioCodeCredential"); -let findCredentials = undefined; -export const vsCodeCredentialControl = { - setVsCodeCredentialFinder(finder) { - findCredentials = finder; - }, -}; -// Map of unsupported Tenant IDs and the errors we will be throwing. -const unsupportedTenantIds = { - adfs: "The VisualStudioCodeCredential does not support authentication with ADFS tenants.", -}; -function checkUnsupportedTenant(tenantId) { - // If the Tenant ID isn't supported, we throw. - const unsupportedTenantError = unsupportedTenantIds[tenantId]; - if (unsupportedTenantError) { - throw new CredentialUnavailableError(unsupportedTenantError); - } -} -const mapVSCodeAuthorityHosts = { - AzureCloud: AzureAuthorityHosts.AzurePublicCloud, - AzureChina: AzureAuthorityHosts.AzureChina, - AzureGermanCloud: AzureAuthorityHosts.AzureGermany, - AzureUSGovernment: AzureAuthorityHosts.AzureGovernment, -}; -/** - * Attempts to load a specific property from the VSCode configurations of the current OS. - * If it fails at any point, returns undefined. - */ -export function getPropertyFromVSCode(property) { - const settingsPath = ["User", "settings.json"]; - // Eventually we can add more folders for more versions of VSCode. - const vsCodeFolder = "Code"; - const homedir = os.homedir(); - function loadProperty(...pathSegments) { - const fullPath = path.join(...pathSegments, vsCodeFolder, ...settingsPath); - const settings = JSON.parse(fs.readFileSync(fullPath, { encoding: "utf8" })); - return settings[property]; - } - try { - let appData; - switch (process.platform) { - case "win32": - appData = process.env.APPDATA; - return appData ? loadProperty(appData) : undefined; - case "darwin": - return loadProperty(homedir, "Library", "Application Support"); - case "linux": - return loadProperty(homedir, ".config"); - default: - return; - } - } - catch (e) { - logger.info(`Failed to load the Visual Studio Code configuration file. Error: ${e.message}`); - return; - } -} -/** - * Connects to Azure using the credential provided by the VSCode extension 'Azure Account'. - * Once the user has logged in via the extension, this credential can share the same refresh token - * that is cached by the extension. - * - * It's a [known issue](https://github.com/Azure/azure-sdk-for-js/issues/20500) that this credential doesn't - * work with [Azure Account extension](https://marketplace.visualstudio.com/items?itemName=ms-vscode.azure-account) - * versions newer than **0.9.11**. A long-term fix to this problem is in progress. In the meantime, consider - * authenticating with {@link AzureCliCredential}. - * - * @deprecated This credential is deprecated because the VS Code Azure Account extension on which this credential - * relies has been deprecated. Users should use other dev-time credentials, such as {@link AzureCliCredential}, - * {@link AzureDeveloperCliCredential}, or {@link AzurePowerShellCredential} for their - * local development needs. See Azure Account extension deprecation notice [here](https://github.com/microsoft/vscode-azure-account/issues/964). - * - */ -export class VisualStudioCodeCredential { - /** - * Creates an instance of VisualStudioCodeCredential to use for automatically authenticating via VSCode. - * - * **Note**: `VisualStudioCodeCredential` is provided by a plugin package: - * `@azure/identity-vscode`. If this package is not installed and registered - * using the plugin API (`useIdentityPlugin`), then authentication using - * `VisualStudioCodeCredential` will not be available. - * - * @param options - Options for configuring the client which makes the authentication request. - */ - constructor(options) { - // We want to make sure we use the one assigned by the user on the VSCode settings. - // Or just `AzureCloud` by default. - this.cloudName = (getPropertyFromVSCode("azure.cloud") || "AzureCloud"); - // Picking an authority host based on the cloud name. - const authorityHost = mapVSCodeAuthorityHosts[this.cloudName]; - this.identityClient = new IdentityClient(Object.assign({ authorityHost }, options)); - if (options && options.tenantId) { - checkTenantId(logger, options.tenantId); - this.tenantId = options.tenantId; - } - else { - this.tenantId = CommonTenantId; - } - this.additionallyAllowedTenantIds = resolveAdditionallyAllowedTenantIds(options === null || options === void 0 ? void 0 : options.additionallyAllowedTenants); - checkUnsupportedTenant(this.tenantId); - } - /** - * Runs preparations for any further getToken request. - */ - async prepare() { - // Attempts to load the tenant from the VSCode configuration file. - const settingsTenant = getPropertyFromVSCode("azure.tenant"); - if (settingsTenant) { - this.tenantId = settingsTenant; - } - checkUnsupportedTenant(this.tenantId); - } - /** - * Runs preparations for any further getToken, but only once. - */ - prepareOnce() { - if (!this.preparePromise) { - this.preparePromise = this.prepare(); - } - return this.preparePromise; - } - /** - * Returns the token found by searching VSCode's authentication cache or - * returns null if no token could be found. - * - * @param scopes - The list of scopes for which the token will have access. - * @param options - The options used to configure any requests this - * `TokenCredential` implementation might make. - */ - async getToken(scopes, options) { - var _a, _b; - await this.prepareOnce(); - const tenantId = processMultiTenantRequest(this.tenantId, options, this.additionallyAllowedTenantIds, logger) || this.tenantId; - if (findCredentials === undefined) { - throw new CredentialUnavailableError([ - "No implementation of `VisualStudioCodeCredential` is available.", - "You must install the identity-vscode plugin package (`npm install --save-dev @azure/identity-vscode`)", - "and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling", - "`useIdentityPlugin(vsCodePlugin)` before creating a `VisualStudioCodeCredential`.", - "To troubleshoot, visit https://aka.ms/azsdk/js/identity/vscodecredential/troubleshoot.", - ].join(" ")); - } - let scopeString = typeof scopes === "string" ? scopes : scopes.join(" "); - // Check to make sure the scope we get back is a valid scope - if (!scopeString.match(/^[0-9a-zA-Z-.:/]+$/)) { - const error = new Error("Invalid scope was specified by the user or calling client"); - logger.getToken.info(formatError(scopes, error)); - throw error; - } - if (scopeString.indexOf("offline_access") < 0) { - scopeString += " offline_access"; - } - // findCredentials returns an array similar to: - // [ - // { - // account: "", - // password: "", - // }, - // /* ... */ - // ] - const credentials = await findCredentials(); - // If we can't find the credential based on the name, we'll pick the first one available. - const { password: refreshToken } = (_b = (_a = credentials.find(({ account }) => account === this.cloudName)) !== null && _a !== void 0 ? _a : credentials[0]) !== null && _b !== void 0 ? _b : {}; - if (refreshToken) { - const tokenResponse = await this.identityClient.refreshAccessToken(tenantId, AzureAccountClientId, scopeString, refreshToken, undefined); - if (tokenResponse) { - logger.getToken.info(formatSuccess(scopes)); - return tokenResponse.accessToken; - } - else { - const error = new CredentialUnavailableError("Could not retrieve the token associated with Visual Studio Code. Have you connected using the 'Azure Account' extension recently? To troubleshoot, visit https://aka.ms/azsdk/js/identity/vscodecredential/troubleshoot."); - logger.getToken.info(formatError(scopes, error)); - throw error; - } - } - else { - const error = new CredentialUnavailableError("Could not retrieve the token associated with Visual Studio Code. Did you connect using the 'Azure Account' extension? To troubleshoot, visit https://aka.ms/azsdk/js/identity/vscodecredential/troubleshoot."); - logger.getToken.info(formatError(scopes, error)); - throw error; - } - } -} -//# sourceMappingURL=visualStudioCodeCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/workloadIdentityCredential.js b/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/workloadIdentityCredential.js deleted file mode 100644 index e80d8b0b..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/credentials/workloadIdentityCredential.js +++ /dev/null @@ -1,114 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { credentialLogger, processEnvVars } from "../util/logging.js"; -import { ClientAssertionCredential } from "./clientAssertionCredential.js"; -import { CredentialUnavailableError } from "../errors.js"; -import { checkTenantId } from "../util/tenantIdUtils.js"; -import { readFile } from "node:fs/promises"; -const credentialName = "WorkloadIdentityCredential"; -/** - * Contains the list of all supported environment variable names so that an - * appropriate error message can be generated when no credentials can be - * configured. - * - * @internal - */ -export const SupportedWorkloadEnvironmentVariables = [ - "AZURE_TENANT_ID", - "AZURE_CLIENT_ID", - "AZURE_FEDERATED_TOKEN_FILE", -]; -const logger = credentialLogger(credentialName); -/** - * Workload Identity authentication is a feature in Azure that allows applications running on virtual machines (VMs) - * to access other Azure resources without the need for a service principal or managed identity. With Workload Identity - * authentication, applications authenticate themselves using their own identity, rather than using a shared service - * principal or managed identity. Under the hood, Workload Identity authentication uses the concept of Service Account - * Credentials (SACs), which are automatically created by Azure and stored securely in the VM. By using Workload - * Identity authentication, you can avoid the need to manage and rotate service principals or managed identities for - * each application on each VM. Additionally, because SACs are created automatically and managed by Azure, you don't - * need to worry about storing and securing sensitive credentials themselves. - * The WorkloadIdentityCredential supports Microsoft Entra Workload ID authentication on Azure Kubernetes and acquires - * a token using the SACs available in the Azure Kubernetes environment. - * Refer to Microsoft Entra - * Workload ID for more information. - */ -export class WorkloadIdentityCredential { - /** - * WorkloadIdentityCredential supports Microsoft Entra Workload ID on Kubernetes. - * - * @param options - The identity client options to use for authentication. - */ - constructor(options) { - this.azureFederatedTokenFileContent = undefined; - this.cacheDate = undefined; - // Logging environment variables for error details - const assignedEnv = processEnvVars(SupportedWorkloadEnvironmentVariables).assigned.join(", "); - logger.info(`Found the following environment variables: ${assignedEnv}`); - const workloadIdentityCredentialOptions = options !== null && options !== void 0 ? options : {}; - const tenantId = workloadIdentityCredentialOptions.tenantId || process.env.AZURE_TENANT_ID; - const clientId = workloadIdentityCredentialOptions.clientId || process.env.AZURE_CLIENT_ID; - this.federatedTokenFilePath = - workloadIdentityCredentialOptions.tokenFilePath || process.env.AZURE_FEDERATED_TOKEN_FILE; - if (tenantId) { - checkTenantId(logger, tenantId); - } - if (!clientId) { - throw new CredentialUnavailableError(`${credentialName}: is unavailable. clientId is a required parameter. In DefaultAzureCredential and ManagedIdentityCredential, this can be provided as an environment variable - "AZURE_CLIENT_ID". - See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`); - } - if (!tenantId) { - throw new CredentialUnavailableError(`${credentialName}: is unavailable. tenantId is a required parameter. In DefaultAzureCredential and ManagedIdentityCredential, this can be provided as an environment variable - "AZURE_TENANT_ID". - See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`); - } - if (!this.federatedTokenFilePath) { - throw new CredentialUnavailableError(`${credentialName}: is unavailable. federatedTokenFilePath is a required parameter. In DefaultAzureCredential and ManagedIdentityCredential, this can be provided as an environment variable - "AZURE_FEDERATED_TOKEN_FILE". - See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`); - } - logger.info(`Invoking ClientAssertionCredential with tenant ID: ${tenantId}, clientId: ${workloadIdentityCredentialOptions.clientId} and federated token path: [REDACTED]`); - this.client = new ClientAssertionCredential(tenantId, clientId, this.readFileContents.bind(this), options); - } - /** - * Authenticates with Microsoft Entra ID and returns an access token if successful. - * If authentication fails, a {@link CredentialUnavailableError} will be thrown with the details of the failure. - * - * @param scopes - The list of scopes for which the token will have access. - * @param options - The options used to configure any requests this - * TokenCredential implementation might make. - */ - async getToken(scopes, options) { - if (!this.client) { - const errorMessage = `${credentialName}: is unavailable. tenantId, clientId, and federatedTokenFilePath are required parameters. - In DefaultAzureCredential and ManagedIdentityCredential, these can be provided as environment variables - - "AZURE_TENANT_ID", - "AZURE_CLIENT_ID", - "AZURE_FEDERATED_TOKEN_FILE". See the troubleshooting guide for more information: https://aka.ms/azsdk/js/identity/workloadidentitycredential/troubleshoot`; - logger.info(errorMessage); - throw new CredentialUnavailableError(errorMessage); - } - logger.info("Invoking getToken() of Client Assertion Credential"); - return this.client.getToken(scopes, options); - } - async readFileContents() { - // Cached assertions expire after 5 minutes - if (this.cacheDate !== undefined && Date.now() - this.cacheDate >= 1000 * 60 * 5) { - this.azureFederatedTokenFileContent = undefined; - } - if (!this.federatedTokenFilePath) { - throw new CredentialUnavailableError(`${credentialName}: is unavailable. Invalid file path provided ${this.federatedTokenFilePath}.`); - } - if (!this.azureFederatedTokenFileContent) { - const file = await readFile(this.federatedTokenFilePath, "utf8"); - const value = file.trim(); - if (!value) { - throw new CredentialUnavailableError(`${credentialName}: is unavailable. No content on the file ${this.federatedTokenFilePath}.`); - } - else { - this.azureFederatedTokenFileContent = value; - this.cacheDate = Date.now(); - } - } - return this.azureFederatedTokenFileContent; - } -} -//# sourceMappingURL=workloadIdentityCredential.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/errors.js b/claude-code-source/node_modules/@azure/identity/dist/esm/errors.js deleted file mode 100644 index d015c473..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/errors.js +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -function isErrorResponse(errorResponse) { - return (errorResponse && - typeof errorResponse.error === "string" && - typeof errorResponse.error_description === "string"); -} -/** - * The Error.name value of an CredentialUnavailable - */ -export const CredentialUnavailableErrorName = "CredentialUnavailableError"; -/** - * This signifies that the credential that was tried in a chained credential - * was not available to be used as the credential. Rather than treating this as - * an error that should halt the chain, it's caught and the chain continues - */ -export class CredentialUnavailableError extends Error { - constructor(message, options) { - // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property - super(message, options); - this.name = CredentialUnavailableErrorName; - } -} -/** - * The Error.name value of an AuthenticationError - */ -export const AuthenticationErrorName = "AuthenticationError"; -/** - * Provides details about a failure to authenticate with Azure Active - * Directory. The `errorResponse` field contains more details about - * the specific failure. - */ -export class AuthenticationError extends Error { - constructor(statusCode, errorBody, options) { - let errorResponse = { - error: "unknown", - errorDescription: "An unknown error occurred and no additional details are available.", - }; - if (isErrorResponse(errorBody)) { - errorResponse = convertOAuthErrorResponseToErrorResponse(errorBody); - } - else if (typeof errorBody === "string") { - try { - // Most error responses will contain JSON-formatted error details - // in the response body - const oauthErrorResponse = JSON.parse(errorBody); - errorResponse = convertOAuthErrorResponseToErrorResponse(oauthErrorResponse); - } - catch (e) { - if (statusCode === 400) { - errorResponse = { - error: "invalid_request", - errorDescription: `The service indicated that the request was invalid.\n\n${errorBody}`, - }; - } - else { - errorResponse = { - error: "unknown_error", - errorDescription: `An unknown error has occurred. Response body:\n\n${errorBody}`, - }; - } - } - } - else { - errorResponse = { - error: "unknown_error", - errorDescription: "An unknown error occurred and no additional details are available.", - }; - } - super(`${errorResponse.error} Status code: ${statusCode}\nMore details:\n${errorResponse.errorDescription},`, - // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property - options); - this.statusCode = statusCode; - this.errorResponse = errorResponse; - // Ensure that this type reports the correct name - this.name = AuthenticationErrorName; - } -} -/** - * The Error.name value of an AggregateAuthenticationError - */ -export const AggregateAuthenticationErrorName = "AggregateAuthenticationError"; -/** - * Provides an `errors` array containing {@link AuthenticationError} instance - * for authentication failures from credentials in a {@link ChainedTokenCredential}. - */ -export class AggregateAuthenticationError extends Error { - constructor(errors, errorMessage) { - const errorDetail = errors.join("\n"); - super(`${errorMessage}\n${errorDetail}`); - this.errors = errors; - // Ensure that this type reports the correct name - this.name = AggregateAuthenticationErrorName; - } -} -function convertOAuthErrorResponseToErrorResponse(errorBody) { - return { - error: errorBody.error, - errorDescription: errorBody.error_description, - correlationId: errorBody.correlation_id, - errorCodes: errorBody.error_codes, - timestamp: errorBody.timestamp, - traceId: errorBody.trace_id, - }; -} -/** - * Error used to enforce authentication after trying to retrieve a token silently. - */ -export class AuthenticationRequiredError extends Error { - constructor( - /** - * Optional parameters. A message can be specified. The {@link GetTokenOptions} of the request can also be specified to more easily associate the error with the received parameters. - */ - options) { - super(options.message, - // @ts-expect-error - TypeScript does not recognize this until we use ES2022 as the target; however, all our major runtimes do support the `cause` property - options.cause ? { cause: options.cause } : undefined); - this.scopes = options.scopes; - this.getTokenOptions = options.getTokenOptions; - this.name = "AuthenticationRequiredError"; - } -} -//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/index.js b/claude-code-source/node_modules/@azure/identity/dist/esm/index.js deleted file mode 100644 index c376aadb..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/index.js +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -export * from "./plugins/consumer.js"; -import { DefaultAzureCredential } from "./credentials/defaultAzureCredential.js"; -export { AuthenticationError, AggregateAuthenticationError, AuthenticationErrorName, AggregateAuthenticationErrorName, CredentialUnavailableError, CredentialUnavailableErrorName, AuthenticationRequiredError, } from "./errors.js"; -export { serializeAuthenticationRecord, deserializeAuthenticationRecord } from "./msal/utils.js"; -export { ChainedTokenCredential } from "./credentials/chainedTokenCredential.js"; -export { ClientSecretCredential } from "./credentials/clientSecretCredential.js"; -export { DefaultAzureCredential } from "./credentials/defaultAzureCredential.js"; -export { EnvironmentCredential } from "./credentials/environmentCredential.js"; -export { ClientCertificateCredential } from "./credentials/clientCertificateCredential.js"; -export { ClientAssertionCredential } from "./credentials/clientAssertionCredential.js"; -export { AzureCliCredential } from "./credentials/azureCliCredential.js"; -export { AzureDeveloperCliCredential } from "./credentials/azureDeveloperCliCredential.js"; -export { InteractiveBrowserCredential } from "./credentials/interactiveBrowserCredential.js"; -export { ManagedIdentityCredential } from "./credentials/managedIdentityCredential/index.js"; -export { DeviceCodeCredential } from "./credentials/deviceCodeCredential.js"; -export { AzurePipelinesCredential as AzurePipelinesCredential } from "./credentials/azurePipelinesCredential.js"; -export { AuthorizationCodeCredential } from "./credentials/authorizationCodeCredential.js"; -export { AzurePowerShellCredential } from "./credentials/azurePowerShellCredential.js"; -export { UsernamePasswordCredential } from "./credentials/usernamePasswordCredential.js"; -export { VisualStudioCodeCredential } from "./credentials/visualStudioCodeCredential.js"; -export { OnBehalfOfCredential } from "./credentials/onBehalfOfCredential.js"; -export { WorkloadIdentityCredential } from "./credentials/workloadIdentityCredential.js"; -export { logger } from "./util/logging.js"; -export { AzureAuthorityHosts } from "./constants.js"; -/** - * Returns a new instance of the {@link DefaultAzureCredential}. - */ -export function getDefaultAzureCredential() { - return new DefaultAzureCredential(); -} -export { getBearerTokenProvider } from "./tokenProvider.js"; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/msal/msal.js b/claude-code-source/node_modules/@azure/identity/dist/esm/msal/msal.js deleted file mode 100644 index 269bbc0b..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/msal/msal.js +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import * as msalCommon from "@azure/msal-node"; -export { msalCommon }; -//# sourceMappingURL=msal.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/msal/nodeFlows/msalClient.js b/claude-code-source/node_modules/@azure/identity/dist/esm/msal/nodeFlows/msalClient.js deleted file mode 100644 index 8a66c937..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/msal/nodeFlows/msalClient.js +++ /dev/null @@ -1,469 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import * as msal from "@azure/msal-node"; -import { credentialLogger, formatSuccess } from "../../util/logging.js"; -import { msalPlugins } from "./msalPlugins.js"; -import { defaultLoggerCallback, ensureValidMsalToken, getAuthority, getAuthorityHost, getKnownAuthorities, getMSALLogLevel, handleMsalError, msalToPublic, publicToMsal, } from "../utils.js"; -import { AuthenticationRequiredError } from "../../errors.js"; -import { IdentityClient } from "../../client/identityClient.js"; -import { calculateRegionalAuthority } from "../../regionalAuthority.js"; -import { getLogLevel } from "@azure/logger"; -import { resolveTenantId } from "../../util/tenantIdUtils.js"; -/** - * The default logger used if no logger was passed in by the credential. - */ -const msalLogger = credentialLogger("MsalClient"); -/** - * Generates the configuration for MSAL (Microsoft Authentication Library). - * - * @param clientId - The client ID of the application. - * @param tenantId - The tenant ID of the Azure Active Directory. - * @param msalClientOptions - Optional. Additional options for creating the MSAL client. - * @returns The MSAL configuration object. - */ -export function generateMsalConfiguration(clientId, tenantId, msalClientOptions = {}) { - var _a, _b, _c; - const resolvedTenant = resolveTenantId((_a = msalClientOptions.logger) !== null && _a !== void 0 ? _a : msalLogger, tenantId, clientId); - // TODO: move and reuse getIdentityClientAuthorityHost - const authority = getAuthority(resolvedTenant, getAuthorityHost(msalClientOptions)); - const httpClient = new IdentityClient(Object.assign(Object.assign({}, msalClientOptions.tokenCredentialOptions), { authorityHost: authority, loggingOptions: msalClientOptions.loggingOptions })); - const msalConfig = { - auth: { - clientId, - authority, - knownAuthorities: getKnownAuthorities(resolvedTenant, authority, msalClientOptions.disableInstanceDiscovery), - }, - system: { - networkClient: httpClient, - loggerOptions: { - loggerCallback: defaultLoggerCallback((_b = msalClientOptions.logger) !== null && _b !== void 0 ? _b : msalLogger), - logLevel: getMSALLogLevel(getLogLevel()), - piiLoggingEnabled: (_c = msalClientOptions.loggingOptions) === null || _c === void 0 ? void 0 : _c.enableUnsafeSupportLogging, - }, - }, - }; - return msalConfig; -} -/** - * Creates an instance of the MSAL (Microsoft Authentication Library) client. - * - * @param clientId - The client ID of the application. - * @param tenantId - The tenant ID of the Azure Active Directory. - * @param createMsalClientOptions - Optional. Additional options for creating the MSAL client. - * @returns An instance of the MSAL client. - * - * @public - */ -export function createMsalClient(clientId, tenantId, createMsalClientOptions = {}) { - var _a; - const state = { - msalConfig: generateMsalConfiguration(clientId, tenantId, createMsalClientOptions), - cachedAccount: createMsalClientOptions.authenticationRecord - ? publicToMsal(createMsalClientOptions.authenticationRecord) - : null, - pluginConfiguration: msalPlugins.generatePluginConfiguration(createMsalClientOptions), - logger: (_a = createMsalClientOptions.logger) !== null && _a !== void 0 ? _a : msalLogger, - }; - const publicApps = new Map(); - async function getPublicApp(options = {}) { - const appKey = options.enableCae ? "CAE" : "default"; - let publicClientApp = publicApps.get(appKey); - if (publicClientApp) { - state.logger.getToken.info("Existing PublicClientApplication found in cache, returning it."); - return publicClientApp; - } - // Initialize a new app and cache it - state.logger.getToken.info(`Creating new PublicClientApplication with CAE ${options.enableCae ? "enabled" : "disabled"}.`); - const cachePlugin = options.enableCae - ? state.pluginConfiguration.cache.cachePluginCae - : state.pluginConfiguration.cache.cachePlugin; - state.msalConfig.auth.clientCapabilities = options.enableCae ? ["cp1"] : undefined; - publicClientApp = new msal.PublicClientApplication(Object.assign(Object.assign({}, state.msalConfig), { broker: { nativeBrokerPlugin: state.pluginConfiguration.broker.nativeBrokerPlugin }, cache: { cachePlugin: await cachePlugin } })); - publicApps.set(appKey, publicClientApp); - return publicClientApp; - } - const confidentialApps = new Map(); - async function getConfidentialApp(options = {}) { - const appKey = options.enableCae ? "CAE" : "default"; - let confidentialClientApp = confidentialApps.get(appKey); - if (confidentialClientApp) { - state.logger.getToken.info("Existing ConfidentialClientApplication found in cache, returning it."); - return confidentialClientApp; - } - // Initialize a new app and cache it - state.logger.getToken.info(`Creating new ConfidentialClientApplication with CAE ${options.enableCae ? "enabled" : "disabled"}.`); - const cachePlugin = options.enableCae - ? state.pluginConfiguration.cache.cachePluginCae - : state.pluginConfiguration.cache.cachePlugin; - state.msalConfig.auth.clientCapabilities = options.enableCae ? ["cp1"] : undefined; - confidentialClientApp = new msal.ConfidentialClientApplication(Object.assign(Object.assign({}, state.msalConfig), { broker: { nativeBrokerPlugin: state.pluginConfiguration.broker.nativeBrokerPlugin }, cache: { cachePlugin: await cachePlugin } })); - confidentialApps.set(appKey, confidentialClientApp); - return confidentialClientApp; - } - async function getTokenSilent(app, scopes, options = {}) { - if (state.cachedAccount === null) { - state.logger.getToken.info("No cached account found in local state."); - throw new AuthenticationRequiredError({ scopes }); - } - // Keep track and reuse the claims we received across challenges - if (options.claims) { - state.cachedClaims = options.claims; - } - const silentRequest = { - account: state.cachedAccount, - scopes, - claims: state.cachedClaims, - }; - if (state.pluginConfiguration.broker.isEnabled) { - silentRequest.tokenQueryParameters || (silentRequest.tokenQueryParameters = {}); - if (state.pluginConfiguration.broker.enableMsaPassthrough) { - silentRequest.tokenQueryParameters["msal_request_type"] = "consumer_passthrough"; - } - } - if (options.proofOfPossessionOptions) { - silentRequest.shrNonce = options.proofOfPossessionOptions.nonce; - silentRequest.authenticationScheme = "pop"; - silentRequest.resourceRequestMethod = options.proofOfPossessionOptions.resourceRequestMethod; - silentRequest.resourceRequestUri = options.proofOfPossessionOptions.resourceRequestUrl; - } - state.logger.getToken.info("Attempting to acquire token silently"); - try { - return await app.acquireTokenSilent(silentRequest); - } - catch (err) { - throw handleMsalError(scopes, err, options); - } - } - /** - * Builds an authority URL for the given request. The authority may be different than the one used when creating the MSAL client - * if the user is creating cross-tenant requests - */ - function calculateRequestAuthority(options) { - if (options === null || options === void 0 ? void 0 : options.tenantId) { - return getAuthority(options.tenantId, getAuthorityHost(createMsalClientOptions)); - } - return state.msalConfig.auth.authority; - } - /** - * Performs silent authentication using MSAL to acquire an access token. - * If silent authentication fails, falls back to interactive authentication. - * - * @param msalApp - The MSAL application instance. - * @param scopes - The scopes for which to acquire the access token. - * @param options - The options for acquiring the access token. - * @param onAuthenticationRequired - A callback function to handle interactive authentication when silent authentication fails. - * @returns A promise that resolves to an AccessToken object containing the access token and its expiration timestamp. - */ - async function withSilentAuthentication(msalApp, scopes, options, onAuthenticationRequired) { - var _a, _b; - let response = null; - try { - response = await getTokenSilent(msalApp, scopes, options); - } - catch (e) { - if (e.name !== "AuthenticationRequiredError") { - throw e; - } - if (options.disableAutomaticAuthentication) { - throw new AuthenticationRequiredError({ - scopes, - getTokenOptions: options, - message: "Automatic authentication has been disabled. You may call the authentication() method.", - }); - } - } - // Silent authentication failed - if (response === null) { - try { - response = await onAuthenticationRequired(); - } - catch (err) { - throw handleMsalError(scopes, err, options); - } - } - // At this point we should have a token, process it - ensureValidMsalToken(scopes, response, options); - state.cachedAccount = (_a = response === null || response === void 0 ? void 0 : response.account) !== null && _a !== void 0 ? _a : null; - state.logger.getToken.info(formatSuccess(scopes)); - return { - token: response.accessToken, - expiresOnTimestamp: response.expiresOn.getTime(), - refreshAfterTimestamp: (_b = response.refreshOn) === null || _b === void 0 ? void 0 : _b.getTime(), - tokenType: response.tokenType, - }; - } - async function getTokenByClientSecret(scopes, clientSecret, options = {}) { - var _a; - state.logger.getToken.info(`Attempting to acquire token using client secret`); - state.msalConfig.auth.clientSecret = clientSecret; - const msalApp = await getConfidentialApp(options); - try { - const response = await msalApp.acquireTokenByClientCredential({ - scopes, - authority: calculateRequestAuthority(options), - azureRegion: calculateRegionalAuthority(), - claims: options === null || options === void 0 ? void 0 : options.claims, - }); - ensureValidMsalToken(scopes, response, options); - state.logger.getToken.info(formatSuccess(scopes)); - return { - token: response.accessToken, - expiresOnTimestamp: response.expiresOn.getTime(), - refreshAfterTimestamp: (_a = response.refreshOn) === null || _a === void 0 ? void 0 : _a.getTime(), - tokenType: response.tokenType, - }; - } - catch (err) { - throw handleMsalError(scopes, err, options); - } - } - async function getTokenByClientAssertion(scopes, clientAssertion, options = {}) { - var _a; - state.logger.getToken.info(`Attempting to acquire token using client assertion`); - state.msalConfig.auth.clientAssertion = clientAssertion; - const msalApp = await getConfidentialApp(options); - try { - const response = await msalApp.acquireTokenByClientCredential({ - scopes, - authority: calculateRequestAuthority(options), - azureRegion: calculateRegionalAuthority(), - claims: options === null || options === void 0 ? void 0 : options.claims, - clientAssertion, - }); - ensureValidMsalToken(scopes, response, options); - state.logger.getToken.info(formatSuccess(scopes)); - return { - token: response.accessToken, - expiresOnTimestamp: response.expiresOn.getTime(), - refreshAfterTimestamp: (_a = response.refreshOn) === null || _a === void 0 ? void 0 : _a.getTime(), - tokenType: response.tokenType, - }; - } - catch (err) { - throw handleMsalError(scopes, err, options); - } - } - async function getTokenByClientCertificate(scopes, certificate, options = {}) { - var _a; - state.logger.getToken.info(`Attempting to acquire token using client certificate`); - state.msalConfig.auth.clientCertificate = certificate; - const msalApp = await getConfidentialApp(options); - try { - const response = await msalApp.acquireTokenByClientCredential({ - scopes, - authority: calculateRequestAuthority(options), - azureRegion: calculateRegionalAuthority(), - claims: options === null || options === void 0 ? void 0 : options.claims, - }); - ensureValidMsalToken(scopes, response, options); - state.logger.getToken.info(formatSuccess(scopes)); - return { - token: response.accessToken, - expiresOnTimestamp: response.expiresOn.getTime(), - refreshAfterTimestamp: (_a = response.refreshOn) === null || _a === void 0 ? void 0 : _a.getTime(), - tokenType: response.tokenType, - }; - } - catch (err) { - throw handleMsalError(scopes, err, options); - } - } - async function getTokenByDeviceCode(scopes, deviceCodeCallback, options = {}) { - state.logger.getToken.info(`Attempting to acquire token using device code`); - const msalApp = await getPublicApp(options); - return withSilentAuthentication(msalApp, scopes, options, () => { - var _a, _b; - const requestOptions = { - scopes, - cancel: (_b = (_a = options === null || options === void 0 ? void 0 : options.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) !== null && _b !== void 0 ? _b : false, - deviceCodeCallback, - authority: calculateRequestAuthority(options), - claims: options === null || options === void 0 ? void 0 : options.claims, - }; - const deviceCodeRequest = msalApp.acquireTokenByDeviceCode(requestOptions); - if (options.abortSignal) { - options.abortSignal.addEventListener("abort", () => { - requestOptions.cancel = true; - }); - } - return deviceCodeRequest; - }); - } - async function getTokenByUsernamePassword(scopes, username, password, options = {}) { - state.logger.getToken.info(`Attempting to acquire token using username and password`); - const msalApp = await getPublicApp(options); - return withSilentAuthentication(msalApp, scopes, options, () => { - const requestOptions = { - scopes, - username, - password, - authority: calculateRequestAuthority(options), - claims: options === null || options === void 0 ? void 0 : options.claims, - }; - return msalApp.acquireTokenByUsernamePassword(requestOptions); - }); - } - function getActiveAccount() { - if (!state.cachedAccount) { - return undefined; - } - return msalToPublic(clientId, state.cachedAccount); - } - async function getTokenByAuthorizationCode(scopes, redirectUri, authorizationCode, clientSecret, options = {}) { - state.logger.getToken.info(`Attempting to acquire token using authorization code`); - let msalApp; - if (clientSecret) { - // If a client secret is provided, we need to use a confidential client application - // See https://learn.microsoft.com/entra/identity-platform/v2-oauth2-auth-code-flow#request-an-access-token-with-a-client_secret - state.msalConfig.auth.clientSecret = clientSecret; - msalApp = await getConfidentialApp(options); - } - else { - msalApp = await getPublicApp(options); - } - return withSilentAuthentication(msalApp, scopes, options, () => { - return msalApp.acquireTokenByCode({ - scopes, - redirectUri, - code: authorizationCode, - authority: calculateRequestAuthority(options), - claims: options === null || options === void 0 ? void 0 : options.claims, - }); - }); - } - async function getTokenOnBehalfOf(scopes, userAssertionToken, clientCredentials, options = {}) { - var _a; - msalLogger.getToken.info(`Attempting to acquire token on behalf of another user`); - if (typeof clientCredentials === "string") { - // Client secret - msalLogger.getToken.info(`Using client secret for on behalf of flow`); - state.msalConfig.auth.clientSecret = clientCredentials; - } - else if (typeof clientCredentials === "function") { - // Client Assertion - msalLogger.getToken.info(`Using client assertion callback for on behalf of flow`); - state.msalConfig.auth.clientAssertion = clientCredentials; - } - else { - // Client certificate - msalLogger.getToken.info(`Using client certificate for on behalf of flow`); - state.msalConfig.auth.clientCertificate = clientCredentials; - } - const msalApp = await getConfidentialApp(options); - try { - const response = await msalApp.acquireTokenOnBehalfOf({ - scopes, - authority: calculateRequestAuthority(options), - claims: options.claims, - oboAssertion: userAssertionToken, - }); - ensureValidMsalToken(scopes, response, options); - msalLogger.getToken.info(formatSuccess(scopes)); - return { - token: response.accessToken, - expiresOnTimestamp: response.expiresOn.getTime(), - refreshAfterTimestamp: (_a = response.refreshOn) === null || _a === void 0 ? void 0 : _a.getTime(), - tokenType: response.tokenType, - }; - } - catch (err) { - throw handleMsalError(scopes, err, options); - } - } - async function getTokenByInteractiveRequest(scopes, options = {}) { - msalLogger.getToken.info(`Attempting to acquire token interactively`); - const app = await getPublicApp(options); - /** - * A helper function that supports brokered authentication through the MSAL's public application. - * - * When options.useDefaultBrokerAccount is true, the method will attempt to authenticate using the default broker account. - * If the default broker account is not available, the method will fall back to interactive authentication. - */ - async function getBrokeredToken(useDefaultBrokerAccount) { - var _a; - msalLogger.verbose("Authentication will resume through the broker"); - const interactiveRequest = createBaseInteractiveRequest(); - if (state.pluginConfiguration.broker.parentWindowHandle) { - interactiveRequest.windowHandle = Buffer.from(state.pluginConfiguration.broker.parentWindowHandle); - } - else { - // this is a bug, as the pluginConfiguration handler should validate this case. - msalLogger.warning("Parent window handle is not specified for the broker. This may cause unexpected behavior. Please provide the parentWindowHandle."); - } - if (state.pluginConfiguration.broker.enableMsaPassthrough) { - ((_a = interactiveRequest.tokenQueryParameters) !== null && _a !== void 0 ? _a : (interactiveRequest.tokenQueryParameters = {}))["msal_request_type"] = - "consumer_passthrough"; - } - if (useDefaultBrokerAccount) { - interactiveRequest.prompt = "none"; - msalLogger.verbose("Attempting broker authentication using the default broker account"); - } - else { - msalLogger.verbose("Attempting broker authentication without the default broker account"); - } - if (options.proofOfPossessionOptions) { - interactiveRequest.shrNonce = options.proofOfPossessionOptions.nonce; - interactiveRequest.authenticationScheme = "pop"; - interactiveRequest.resourceRequestMethod = - options.proofOfPossessionOptions.resourceRequestMethod; - interactiveRequest.resourceRequestUri = options.proofOfPossessionOptions.resourceRequestUrl; - } - try { - return await app.acquireTokenInteractive(interactiveRequest); - } - catch (e) { - msalLogger.verbose(`Failed to authenticate through the broker: ${e.message}`); - // If we tried to use the default broker account and failed, fall back to interactive authentication - if (useDefaultBrokerAccount) { - return getBrokeredToken(/* useDefaultBrokerAccount: */ false); - } - else { - throw e; - } - } - } - function createBaseInteractiveRequest() { - var _a, _b; - return { - openBrowser: async (url) => { - const open = await import("open"); - await open.default(url, { wait: true, newInstance: true }); - }, - scopes, - authority: calculateRequestAuthority(options), - claims: options === null || options === void 0 ? void 0 : options.claims, - loginHint: options === null || options === void 0 ? void 0 : options.loginHint, - errorTemplate: (_a = options === null || options === void 0 ? void 0 : options.browserCustomizationOptions) === null || _a === void 0 ? void 0 : _a.errorMessage, - successTemplate: (_b = options === null || options === void 0 ? void 0 : options.browserCustomizationOptions) === null || _b === void 0 ? void 0 : _b.successMessage, - prompt: (options === null || options === void 0 ? void 0 : options.loginHint) ? "login" : "select_account", - }; - } - return withSilentAuthentication(app, scopes, options, async () => { - var _a; - const interactiveRequest = createBaseInteractiveRequest(); - if (state.pluginConfiguration.broker.isEnabled) { - return getBrokeredToken((_a = state.pluginConfiguration.broker.useDefaultBrokerAccount) !== null && _a !== void 0 ? _a : false); - } - if (options.proofOfPossessionOptions) { - interactiveRequest.shrNonce = options.proofOfPossessionOptions.nonce; - interactiveRequest.authenticationScheme = "pop"; - interactiveRequest.resourceRequestMethod = - options.proofOfPossessionOptions.resourceRequestMethod; - interactiveRequest.resourceRequestUri = options.proofOfPossessionOptions.resourceRequestUrl; - } - return app.acquireTokenInteractive(interactiveRequest); - }); - } - return { - getActiveAccount, - getTokenByClientSecret, - getTokenByClientAssertion, - getTokenByClientCertificate, - getTokenByDeviceCode, - getTokenByUsernamePassword, - getTokenByAuthorizationCode, - getTokenOnBehalfOf, - getTokenByInteractiveRequest, - }; -} -//# sourceMappingURL=msalClient.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/msal/nodeFlows/msalPlugins.js b/claude-code-source/node_modules/@azure/identity/dist/esm/msal/nodeFlows/msalPlugins.js deleted file mode 100644 index bcd2057c..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/msal/nodeFlows/msalPlugins.js +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { CACHE_CAE_SUFFIX, CACHE_NON_CAE_SUFFIX, DEFAULT_TOKEN_CACHE_NAME, } from "../../constants.js"; -/** - * The current persistence provider, undefined by default. - * @internal - */ -export let persistenceProvider = undefined; -/** - * An object that allows setting the persistence provider. - * @internal - */ -export const msalNodeFlowCacheControl = { - setPersistence(pluginProvider) { - persistenceProvider = pluginProvider; - }, -}; -/** - * The current native broker provider, undefined by default. - * @internal - */ -export let nativeBrokerInfo = undefined; -export function hasNativeBroker() { - return nativeBrokerInfo !== undefined; -} -/** - * An object that allows setting the native broker provider. - * @internal - */ -export const msalNodeFlowNativeBrokerControl = { - setNativeBroker(broker) { - nativeBrokerInfo = { - broker, - }; - }, -}; -/** - * Configures plugins, validating that required plugins are available and enabled. - * - * Does not create the plugins themselves, but rather returns the configuration that will be used to create them. - * - * @param options - options for creating the MSAL client - * @returns plugin configuration - */ -function generatePluginConfiguration(options) { - var _a, _b, _c, _d, _e, _f, _g; - const config = { - cache: {}, - broker: { - isEnabled: (_b = (_a = options.brokerOptions) === null || _a === void 0 ? void 0 : _a.enabled) !== null && _b !== void 0 ? _b : false, - enableMsaPassthrough: (_d = (_c = options.brokerOptions) === null || _c === void 0 ? void 0 : _c.legacyEnableMsaPassthrough) !== null && _d !== void 0 ? _d : false, - parentWindowHandle: (_e = options.brokerOptions) === null || _e === void 0 ? void 0 : _e.parentWindowHandle, - }, - }; - if ((_f = options.tokenCachePersistenceOptions) === null || _f === void 0 ? void 0 : _f.enabled) { - if (persistenceProvider === undefined) { - throw new Error([ - "Persistent token caching was requested, but no persistence provider was configured.", - "You must install the identity-cache-persistence plugin package (`npm install --save @azure/identity-cache-persistence`)", - "and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling", - "`useIdentityPlugin(cachePersistencePlugin)` before using `tokenCachePersistenceOptions`.", - ].join(" ")); - } - const cacheBaseName = options.tokenCachePersistenceOptions.name || DEFAULT_TOKEN_CACHE_NAME; - config.cache.cachePlugin = persistenceProvider(Object.assign({ name: `${cacheBaseName}.${CACHE_NON_CAE_SUFFIX}` }, options.tokenCachePersistenceOptions)); - config.cache.cachePluginCae = persistenceProvider(Object.assign({ name: `${cacheBaseName}.${CACHE_CAE_SUFFIX}` }, options.tokenCachePersistenceOptions)); - } - if ((_g = options.brokerOptions) === null || _g === void 0 ? void 0 : _g.enabled) { - if (nativeBrokerInfo === undefined) { - throw new Error([ - "Broker for WAM was requested to be enabled, but no native broker was configured.", - "You must install the identity-broker plugin package (`npm install --save @azure/identity-broker`)", - "and enable it by importing `useIdentityPlugin` from `@azure/identity` and calling", - "`useIdentityPlugin(createNativeBrokerPlugin())` before using `enableBroker`.", - ].join(" ")); - } - config.broker.nativeBrokerPlugin = nativeBrokerInfo.broker; - } - return config; -} -/** - * Wraps generatePluginConfiguration as a writeable property for test stubbing purposes. - */ -export const msalPlugins = { - generatePluginConfiguration, -}; -//# sourceMappingURL=msalPlugins.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/msal/utils.js b/claude-code-source/node_modules/@azure/identity/dist/esm/msal/utils.js deleted file mode 100644 index b221d132..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/msal/utils.js +++ /dev/null @@ -1,238 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { AuthenticationRequiredError, CredentialUnavailableError } from "../errors.js"; -import { credentialLogger, formatError } from "../util/logging.js"; -import { DefaultAuthority, DefaultAuthorityHost, DefaultTenantId } from "../constants.js"; -import { randomUUID as coreRandomUUID, isNode, isNodeLike } from "@azure/core-util"; -import { AbortError } from "@azure/abort-controller"; -import { msalCommon } from "./msal.js"; -/** - * @internal - */ -const logger = credentialLogger("IdentityUtils"); -/** - * Latest AuthenticationRecord version - * @internal - */ -const LatestAuthenticationRecordVersion = "1.0"; -/** - * Ensures the validity of the MSAL token - * @internal - */ -export function ensureValidMsalToken(scopes, msalToken, getTokenOptions) { - const error = (message) => { - logger.getToken.info(message); - return new AuthenticationRequiredError({ - scopes: Array.isArray(scopes) ? scopes : [scopes], - getTokenOptions, - message, - }); - }; - if (!msalToken) { - throw error("No response"); - } - if (!msalToken.expiresOn) { - throw error(`Response had no "expiresOn" property.`); - } - if (!msalToken.accessToken) { - throw error(`Response had no "accessToken" property.`); - } -} -/** - * Returns the authority host from either the options bag or the AZURE_AUTHORITY_HOST environment variable. - * - * Defaults to {@link DefaultAuthorityHost}. - * @internal - */ -export function getAuthorityHost(options) { - let authorityHost = options === null || options === void 0 ? void 0 : options.authorityHost; - if (!authorityHost && isNodeLike) { - authorityHost = process.env.AZURE_AUTHORITY_HOST; - } - return authorityHost !== null && authorityHost !== void 0 ? authorityHost : DefaultAuthorityHost; -} -/** - * Generates a valid authority by combining a host with a tenantId. - * @internal - */ -export function getAuthority(tenantId, host) { - if (!host) { - host = DefaultAuthorityHost; - } - if (new RegExp(`${tenantId}/?$`).test(host)) { - return host; - } - if (host.endsWith("/")) { - return host + tenantId; - } - else { - return `${host}/${tenantId}`; - } -} -/** - * Generates the known authorities. - * If the Tenant Id is `adfs`, the authority can't be validated since the format won't match the expected one. - * For that reason, we have to force MSAL to disable validating the authority - * by sending it within the known authorities in the MSAL configuration. - * @internal - */ -export function getKnownAuthorities(tenantId, authorityHost, disableInstanceDiscovery) { - if ((tenantId === "adfs" && authorityHost) || disableInstanceDiscovery) { - return [authorityHost]; - } - return []; -} -/** - * Generates a logger that can be passed to the MSAL clients. - * @param credLogger - The logger of the credential. - * @internal - */ -export const defaultLoggerCallback = (credLogger, platform = isNode ? "Node" : "Browser") => (level, message, containsPii) => { - if (containsPii) { - return; - } - switch (level) { - case msalCommon.LogLevel.Error: - credLogger.info(`MSAL ${platform} V2 error: ${message}`); - return; - case msalCommon.LogLevel.Info: - credLogger.info(`MSAL ${platform} V2 info message: ${message}`); - return; - case msalCommon.LogLevel.Verbose: - credLogger.info(`MSAL ${platform} V2 verbose message: ${message}`); - return; - case msalCommon.LogLevel.Warning: - credLogger.info(`MSAL ${platform} V2 warning: ${message}`); - return; - } -}; -/** - * @internal - */ -export function getMSALLogLevel(logLevel) { - switch (logLevel) { - case "error": - return msalCommon.LogLevel.Error; - case "info": - return msalCommon.LogLevel.Info; - case "verbose": - return msalCommon.LogLevel.Verbose; - case "warning": - return msalCommon.LogLevel.Warning; - default: - // default msal logging level should be Info - return msalCommon.LogLevel.Info; - } -} -/** - * Wraps core-util's randomUUID in order to allow for mocking in tests. - * This prepares the library for the upcoming core-util update to ESM. - * - * @internal - * @returns A string containing a random UUID - */ -export function randomUUID() { - return coreRandomUUID(); -} -/** - * Handles MSAL errors. - */ -export function handleMsalError(scopes, error, getTokenOptions) { - if (error.name === "AuthError" || - error.name === "ClientAuthError" || - error.name === "BrowserAuthError") { - const msalError = error; - switch (msalError.errorCode) { - case "endpoints_resolution_error": - logger.info(formatError(scopes, error.message)); - return new CredentialUnavailableError(error.message); - case "device_code_polling_cancelled": - return new AbortError("The authentication has been aborted by the caller."); - case "consent_required": - case "interaction_required": - case "login_required": - logger.info(formatError(scopes, `Authentication returned errorCode ${msalError.errorCode}`)); - break; - default: - logger.info(formatError(scopes, `Failed to acquire token: ${error.message}`)); - break; - } - } - if (error.name === "ClientConfigurationError" || - error.name === "BrowserConfigurationAuthError" || - error.name === "AbortError" || - error.name === "AuthenticationError") { - return error; - } - if (error.name === "NativeAuthError") { - logger.info(formatError(scopes, `Error from the native broker: ${error.message} with status code: ${error.statusCode}`)); - return error; - } - return new AuthenticationRequiredError({ scopes, getTokenOptions, message: error.message }); -} -// transformations -export function publicToMsal(account) { - return { - localAccountId: account.homeAccountId, - environment: account.authority, - username: account.username, - homeAccountId: account.homeAccountId, - tenantId: account.tenantId, - }; -} -export function msalToPublic(clientId, account) { - var _a; - const record = { - authority: (_a = account.environment) !== null && _a !== void 0 ? _a : DefaultAuthority, - homeAccountId: account.homeAccountId, - tenantId: account.tenantId || DefaultTenantId, - username: account.username, - clientId, - version: LatestAuthenticationRecordVersion, - }; - return record; -} -/** - * Serializes an `AuthenticationRecord` into a string. - * - * The output of a serialized authentication record will contain the following properties: - * - * - "authority" - * - "homeAccountId" - * - "clientId" - * - "tenantId" - * - "username" - * - "version" - * - * To later convert this string to a serialized `AuthenticationRecord`, please use the exported function `deserializeAuthenticationRecord()`. - */ -export function serializeAuthenticationRecord(record) { - return JSON.stringify(record); -} -/** - * Deserializes a previously serialized authentication record from a string into an object. - * - * The input string must contain the following properties: - * - * - "authority" - * - "homeAccountId" - * - "clientId" - * - "tenantId" - * - "username" - * - "version" - * - * If the version we receive is unsupported, an error will be thrown. - * - * At the moment, the only available version is: "1.0", which is always set when the authentication record is serialized. - * - * @param serializedRecord - Authentication record previously serialized into string. - * @returns AuthenticationRecord. - */ -export function deserializeAuthenticationRecord(serializedRecord) { - const parsed = JSON.parse(serializedRecord); - if (parsed.version && parsed.version !== LatestAuthenticationRecordVersion) { - throw Error("Unsupported AuthenticationRecord version"); - } - return parsed; -} -//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/plugins/consumer.js b/claude-code-source/node_modules/@azure/identity/dist/esm/plugins/consumer.js deleted file mode 100644 index 95c1b1a2..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/plugins/consumer.js +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { msalNodeFlowCacheControl, msalNodeFlowNativeBrokerControl, } from "../msal/nodeFlows/msalPlugins.js"; -import { vsCodeCredentialControl } from "../credentials/visualStudioCodeCredential.js"; -/** - * The context passed to an Identity plugin. This contains objects that - * plugins can use to set backend implementations. - * @internal - */ -const pluginContext = { - cachePluginControl: msalNodeFlowCacheControl, - nativeBrokerPluginControl: msalNodeFlowNativeBrokerControl, - vsCodeCredentialControl: vsCodeCredentialControl, -}; -/** - * Extend Azure Identity with additional functionality. Pass a plugin from - * a plugin package, such as: - * - * - `@azure/identity-cache-persistence`: provides persistent token caching - * - `@azure/identity-vscode`: provides the dependencies of - * `VisualStudioCodeCredential` and enables it - * - * Example: - * - * ```ts snippet:consumer_example - * import { useIdentityPlugin, DeviceCodeCredential } from "@azure/identity"; - * - * useIdentityPlugin(cachePersistencePlugin); - * // The plugin has the capability to extend `DeviceCodeCredential` and to - * // add middleware to the underlying credentials, such as persistence. - * const credential = new DeviceCodeCredential({ - * tokenCachePersistenceOptions: { - * enabled: true, - * }, - * }); - * ``` - * - * @param plugin - the plugin to register - */ -export function useIdentityPlugin(plugin) { - plugin(pluginContext); -} -//# sourceMappingURL=consumer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/regionalAuthority.js b/claude-code-source/node_modules/@azure/identity/dist/esm/regionalAuthority.js deleted file mode 100644 index 16f73f11..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/regionalAuthority.js +++ /dev/null @@ -1,140 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * Helps specify a regional authority, or "AutoDiscoverRegion" to auto-detect the region. - */ -export var RegionalAuthority; -(function (RegionalAuthority) { - /** Instructs MSAL to attempt to discover the region */ - RegionalAuthority["AutoDiscoverRegion"] = "AutoDiscoverRegion"; - /** Uses the {@link RegionalAuthority} for the Azure 'westus' region. */ - RegionalAuthority["USWest"] = "westus"; - /** Uses the {@link RegionalAuthority} for the Azure 'westus2' region. */ - RegionalAuthority["USWest2"] = "westus2"; - /** Uses the {@link RegionalAuthority} for the Azure 'centralus' region. */ - RegionalAuthority["USCentral"] = "centralus"; - /** Uses the {@link RegionalAuthority} for the Azure 'eastus' region. */ - RegionalAuthority["USEast"] = "eastus"; - /** Uses the {@link RegionalAuthority} for the Azure 'eastus2' region. */ - RegionalAuthority["USEast2"] = "eastus2"; - /** Uses the {@link RegionalAuthority} for the Azure 'northcentralus' region. */ - RegionalAuthority["USNorthCentral"] = "northcentralus"; - /** Uses the {@link RegionalAuthority} for the Azure 'southcentralus' region. */ - RegionalAuthority["USSouthCentral"] = "southcentralus"; - /** Uses the {@link RegionalAuthority} for the Azure 'westcentralus' region. */ - RegionalAuthority["USWestCentral"] = "westcentralus"; - /** Uses the {@link RegionalAuthority} for the Azure 'canadacentral' region. */ - RegionalAuthority["CanadaCentral"] = "canadacentral"; - /** Uses the {@link RegionalAuthority} for the Azure 'canadaeast' region. */ - RegionalAuthority["CanadaEast"] = "canadaeast"; - /** Uses the {@link RegionalAuthority} for the Azure 'brazilsouth' region. */ - RegionalAuthority["BrazilSouth"] = "brazilsouth"; - /** Uses the {@link RegionalAuthority} for the Azure 'northeurope' region. */ - RegionalAuthority["EuropeNorth"] = "northeurope"; - /** Uses the {@link RegionalAuthority} for the Azure 'westeurope' region. */ - RegionalAuthority["EuropeWest"] = "westeurope"; - /** Uses the {@link RegionalAuthority} for the Azure 'uksouth' region. */ - RegionalAuthority["UKSouth"] = "uksouth"; - /** Uses the {@link RegionalAuthority} for the Azure 'ukwest' region. */ - RegionalAuthority["UKWest"] = "ukwest"; - /** Uses the {@link RegionalAuthority} for the Azure 'francecentral' region. */ - RegionalAuthority["FranceCentral"] = "francecentral"; - /** Uses the {@link RegionalAuthority} for the Azure 'francesouth' region. */ - RegionalAuthority["FranceSouth"] = "francesouth"; - /** Uses the {@link RegionalAuthority} for the Azure 'switzerlandnorth' region. */ - RegionalAuthority["SwitzerlandNorth"] = "switzerlandnorth"; - /** Uses the {@link RegionalAuthority} for the Azure 'switzerlandwest' region. */ - RegionalAuthority["SwitzerlandWest"] = "switzerlandwest"; - /** Uses the {@link RegionalAuthority} for the Azure 'germanynorth' region. */ - RegionalAuthority["GermanyNorth"] = "germanynorth"; - /** Uses the {@link RegionalAuthority} for the Azure 'germanywestcentral' region. */ - RegionalAuthority["GermanyWestCentral"] = "germanywestcentral"; - /** Uses the {@link RegionalAuthority} for the Azure 'norwaywest' region. */ - RegionalAuthority["NorwayWest"] = "norwaywest"; - /** Uses the {@link RegionalAuthority} for the Azure 'norwayeast' region. */ - RegionalAuthority["NorwayEast"] = "norwayeast"; - /** Uses the {@link RegionalAuthority} for the Azure 'eastasia' region. */ - RegionalAuthority["AsiaEast"] = "eastasia"; - /** Uses the {@link RegionalAuthority} for the Azure 'southeastasia' region. */ - RegionalAuthority["AsiaSouthEast"] = "southeastasia"; - /** Uses the {@link RegionalAuthority} for the Azure 'japaneast' region. */ - RegionalAuthority["JapanEast"] = "japaneast"; - /** Uses the {@link RegionalAuthority} for the Azure 'japanwest' region. */ - RegionalAuthority["JapanWest"] = "japanwest"; - /** Uses the {@link RegionalAuthority} for the Azure 'australiaeast' region. */ - RegionalAuthority["AustraliaEast"] = "australiaeast"; - /** Uses the {@link RegionalAuthority} for the Azure 'australiasoutheast' region. */ - RegionalAuthority["AustraliaSouthEast"] = "australiasoutheast"; - /** Uses the {@link RegionalAuthority} for the Azure 'australiacentral' region. */ - RegionalAuthority["AustraliaCentral"] = "australiacentral"; - /** Uses the {@link RegionalAuthority} for the Azure 'australiacentral2' region. */ - RegionalAuthority["AustraliaCentral2"] = "australiacentral2"; - /** Uses the {@link RegionalAuthority} for the Azure 'centralindia' region. */ - RegionalAuthority["IndiaCentral"] = "centralindia"; - /** Uses the {@link RegionalAuthority} for the Azure 'southindia' region. */ - RegionalAuthority["IndiaSouth"] = "southindia"; - /** Uses the {@link RegionalAuthority} for the Azure 'westindia' region. */ - RegionalAuthority["IndiaWest"] = "westindia"; - /** Uses the {@link RegionalAuthority} for the Azure 'koreasouth' region. */ - RegionalAuthority["KoreaSouth"] = "koreasouth"; - /** Uses the {@link RegionalAuthority} for the Azure 'koreacentral' region. */ - RegionalAuthority["KoreaCentral"] = "koreacentral"; - /** Uses the {@link RegionalAuthority} for the Azure 'uaecentral' region. */ - RegionalAuthority["UAECentral"] = "uaecentral"; - /** Uses the {@link RegionalAuthority} for the Azure 'uaenorth' region. */ - RegionalAuthority["UAENorth"] = "uaenorth"; - /** Uses the {@link RegionalAuthority} for the Azure 'southafricanorth' region. */ - RegionalAuthority["SouthAfricaNorth"] = "southafricanorth"; - /** Uses the {@link RegionalAuthority} for the Azure 'southafricawest' region. */ - RegionalAuthority["SouthAfricaWest"] = "southafricawest"; - /** Uses the {@link RegionalAuthority} for the Azure 'chinanorth' region. */ - RegionalAuthority["ChinaNorth"] = "chinanorth"; - /** Uses the {@link RegionalAuthority} for the Azure 'chinaeast' region. */ - RegionalAuthority["ChinaEast"] = "chinaeast"; - /** Uses the {@link RegionalAuthority} for the Azure 'chinanorth2' region. */ - RegionalAuthority["ChinaNorth2"] = "chinanorth2"; - /** Uses the {@link RegionalAuthority} for the Azure 'chinaeast2' region. */ - RegionalAuthority["ChinaEast2"] = "chinaeast2"; - /** Uses the {@link RegionalAuthority} for the Azure 'germanycentral' region. */ - RegionalAuthority["GermanyCentral"] = "germanycentral"; - /** Uses the {@link RegionalAuthority} for the Azure 'germanynortheast' region. */ - RegionalAuthority["GermanyNorthEast"] = "germanynortheast"; - /** Uses the {@link RegionalAuthority} for the Azure 'usgovvirginia' region. */ - RegionalAuthority["GovernmentUSVirginia"] = "usgovvirginia"; - /** Uses the {@link RegionalAuthority} for the Azure 'usgoviowa' region. */ - RegionalAuthority["GovernmentUSIowa"] = "usgoviowa"; - /** Uses the {@link RegionalAuthority} for the Azure 'usgovarizona' region. */ - RegionalAuthority["GovernmentUSArizona"] = "usgovarizona"; - /** Uses the {@link RegionalAuthority} for the Azure 'usgovtexas' region. */ - RegionalAuthority["GovernmentUSTexas"] = "usgovtexas"; - /** Uses the {@link RegionalAuthority} for the Azure 'usdodeast' region. */ - RegionalAuthority["GovernmentUSDodEast"] = "usdodeast"; - /** Uses the {@link RegionalAuthority} for the Azure 'usdodcentral' region. */ - RegionalAuthority["GovernmentUSDodCentral"] = "usdodcentral"; -})(RegionalAuthority || (RegionalAuthority = {})); -/** - * Calculates the correct regional authority based on the supplied value - * and the AZURE_REGIONAL_AUTHORITY_NAME environment variable. - * - * Values will be returned verbatim, except for {@link RegionalAuthority.AutoDiscoverRegion} - * which is mapped to a value MSAL can understand. - * - * @internal - */ -export function calculateRegionalAuthority(regionalAuthority) { - // Note: as of today only 3 credentials support regional authority, and the parameter - // is not exposed via the public API. Regional Authority is _only_ supported - // via the AZURE_REGIONAL_AUTHORITY_NAME env var and _only_ for: ClientSecretCredential, ClientCertificateCredential, and ClientAssertionCredential. - var _a, _b; - // Accepting the regionalAuthority parameter will allow us to support it in the future. - let azureRegion = regionalAuthority; - if (azureRegion === undefined && - ((_b = (_a = globalThis.process) === null || _a === void 0 ? void 0 : _a.env) === null || _b === void 0 ? void 0 : _b.AZURE_REGIONAL_AUTHORITY_NAME) !== undefined) { - azureRegion = process.env.AZURE_REGIONAL_AUTHORITY_NAME; - } - if (azureRegion === RegionalAuthority.AutoDiscoverRegion) { - return "AUTO_DISCOVER"; - } - return azureRegion; -} -//# sourceMappingURL=regionalAuthority.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/tokenProvider.js b/claude-code-source/node_modules/@azure/identity/dist/esm/tokenProvider.js deleted file mode 100644 index 26187e70..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/tokenProvider.js +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { bearerTokenAuthenticationPolicy, createEmptyPipeline, createPipelineRequest, } from "@azure/core-rest-pipeline"; -/** - * Returns a callback that provides a bearer token. - * For example, the bearer token can be used to authenticate a request as follows: - * ```ts snippet:token_provider_example - * import { DefaultAzureCredential, getBearerTokenProvider } from "@azure/identity"; - * import { createPipelineRequest } from "@azure/core-rest-pipeline"; - * - * const credential = new DefaultAzureCredential(); - * const scope = "https://cognitiveservices.azure.com/.default"; - * const getAccessToken = getBearerTokenProvider(credential, scope); - * const token = await getAccessToken(); - * - * // usage - * const request = createPipelineRequest({ url: "https://example.com" }); - * request.headers.set("Authorization", `Bearer ${token}`); - * ``` - * - * @param credential - The credential used to authenticate the request. - * @param scopes - The scopes required for the bearer token. - * @param options - Options to configure the token provider. - * @returns a callback that provides a bearer token. - */ -export function getBearerTokenProvider(credential, scopes, options) { - const { abortSignal, tracingOptions } = options || {}; - const pipeline = createEmptyPipeline(); - pipeline.addPolicy(bearerTokenAuthenticationPolicy({ credential, scopes })); - async function getRefreshedToken() { - var _a; - // Create a pipeline with just the bearer token policy - // and run a dummy request through it to get the token - const res = await pipeline.sendRequest({ - sendRequest: (request) => Promise.resolve({ - request, - status: 200, - headers: request.headers, - }), - }, createPipelineRequest({ - url: "https://example.com", - abortSignal, - tracingOptions, - })); - const accessToken = (_a = res.headers.get("authorization")) === null || _a === void 0 ? void 0 : _a.split(" ")[1]; - if (!accessToken) { - throw new Error("Failed to get access token"); - } - return accessToken; - } - return getRefreshedToken; -} -//# sourceMappingURL=tokenProvider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/util/identityTokenEndpoint.js b/claude-code-source/node_modules/@azure/identity/dist/esm/util/identityTokenEndpoint.js deleted file mode 100644 index 157ac18f..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/util/identityTokenEndpoint.js +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -export function getIdentityTokenEndpointSuffix(tenantId) { - if (tenantId === "adfs") { - return "oauth2/token"; - } - else { - return "oauth2/v2.0/token"; - } -} -//# sourceMappingURL=identityTokenEndpoint.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/util/logging.js b/claude-code-source/node_modules/@azure/identity/dist/esm/util/logging.js deleted file mode 100644 index c79c4dcf..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/util/logging.js +++ /dev/null @@ -1,94 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createClientLogger } from "@azure/logger"; -/** - * The AzureLogger used for all clients within the identity package - */ -export const logger = createClientLogger("identity"); -/** - * Separates a list of environment variable names into a plain object with two arrays: an array of missing environment variables and another array with assigned environment variables. - * @param supportedEnvVars - List of environment variable names - */ -export function processEnvVars(supportedEnvVars) { - return supportedEnvVars.reduce((acc, envVariable) => { - if (process.env[envVariable]) { - acc.assigned.push(envVariable); - } - else { - acc.missing.push(envVariable); - } - return acc; - }, { missing: [], assigned: [] }); -} -/** - * Based on a given list of environment variable names, - * logs the environment variables currently assigned during the usage of a credential that goes by the given name. - * @param credentialName - Name of the credential in use - * @param supportedEnvVars - List of environment variables supported by that credential - */ -export function logEnvVars(credentialName, supportedEnvVars) { - const { assigned } = processEnvVars(supportedEnvVars); - logger.info(`${credentialName} => Found the following environment variables: ${assigned.join(", ")}`); -} -/** - * Formatting the success event on the credentials - */ -export function formatSuccess(scope) { - return `SUCCESS. Scopes: ${Array.isArray(scope) ? scope.join(", ") : scope}.`; -} -/** - * Formatting the success event on the credentials - */ -export function formatError(scope, error) { - let message = "ERROR."; - if (scope === null || scope === void 0 ? void 0 : scope.length) { - message += ` Scopes: ${Array.isArray(scope) ? scope.join(", ") : scope}.`; - } - return `${message} Error message: ${typeof error === "string" ? error : error.message}.`; -} -/** - * Generates a CredentialLoggerInstance. - * - * It logs with the format: - * - * `[title] => [message]` - * - */ -export function credentialLoggerInstance(title, parent, log = logger) { - const fullTitle = parent ? `${parent.fullTitle} ${title}` : title; - function info(message) { - log.info(`${fullTitle} =>`, message); - } - function warning(message) { - log.warning(`${fullTitle} =>`, message); - } - function verbose(message) { - log.verbose(`${fullTitle} =>`, message); - } - function error(message) { - log.error(`${fullTitle} =>`, message); - } - return { - title, - fullTitle, - info, - warning, - verbose, - error, - }; -} -/** - * Generates a CredentialLogger, which is a logger declared at the credential's constructor, and used at any point in the credential. - * It has all the properties of a CredentialLoggerInstance, plus other logger instances, one per method. - * - * It logs with the format: - * - * `[title] => [message]` - * `[title] => getToken() => [message]` - * - */ -export function credentialLogger(title, log = logger) { - const credLogger = credentialLoggerInstance(title, undefined, log); - return Object.assign(Object.assign({}, credLogger), { parent: log, getToken: credentialLoggerInstance("=> getToken()", credLogger, log) }); -} -//# sourceMappingURL=logging.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/util/processMultiTenantRequest.js b/claude-code-source/node_modules/@azure/identity/dist/esm/util/processMultiTenantRequest.js deleted file mode 100644 index 7faf281d..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/util/processMultiTenantRequest.js +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { CredentialUnavailableError } from "../errors.js"; -function createConfigurationErrorMessage(tenantId) { - return `The current credential is not configured to acquire tokens for tenant ${tenantId}. To enable acquiring tokens for this tenant add it to the AdditionallyAllowedTenants on the credential options, or add "*" to AdditionallyAllowedTenants to allow acquiring tokens for any tenant.`; -} -/** - * Of getToken contains a tenantId, this functions allows picking this tenantId as the appropriate for authentication, - * unless multitenant authentication has been disabled through the AZURE_IDENTITY_DISABLE_MULTITENANTAUTH (on Node.js), - * or unless the original tenant Id is `adfs`. - * @internal - */ -export function processMultiTenantRequest(tenantId, getTokenOptions, additionallyAllowedTenantIds = [], logger) { - var _a; - let resolvedTenantId; - if (process.env.AZURE_IDENTITY_DISABLE_MULTITENANTAUTH) { - resolvedTenantId = tenantId; - } - else if (tenantId === "adfs") { - resolvedTenantId = tenantId; - } - else { - resolvedTenantId = (_a = getTokenOptions === null || getTokenOptions === void 0 ? void 0 : getTokenOptions.tenantId) !== null && _a !== void 0 ? _a : tenantId; - } - if (tenantId && - resolvedTenantId !== tenantId && - !additionallyAllowedTenantIds.includes("*") && - !additionallyAllowedTenantIds.some((t) => t.localeCompare(resolvedTenantId) === 0)) { - const message = createConfigurationErrorMessage(resolvedTenantId); - logger === null || logger === void 0 ? void 0 : logger.info(message); - throw new CredentialUnavailableError(message); - } - return resolvedTenantId; -} -//# sourceMappingURL=processMultiTenantRequest.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/util/processUtils.js b/claude-code-source/node_modules/@azure/identity/dist/esm/util/processUtils.js deleted file mode 100644 index 70beda48..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/util/processUtils.js +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import * as childProcess from "child_process"; -/** - * Easy to mock childProcess utils. - * @internal - */ -export const processUtils = { - /** - * Promisifying childProcess.execFile - * @internal - */ - execFile(file, params, options) { - return new Promise((resolve, reject) => { - childProcess.execFile(file, params, options, (error, stdout, stderr) => { - if (Buffer.isBuffer(stdout)) { - stdout = stdout.toString("utf8"); - } - if (Buffer.isBuffer(stderr)) { - stderr = stderr.toString("utf8"); - } - if (stderr || error) { - reject(stderr ? new Error(stderr) : error); - } - else { - resolve(stdout); - } - }); - }); - }, -}; -//# sourceMappingURL=processUtils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/util/scopeUtils.js b/claude-code-source/node_modules/@azure/identity/dist/esm/util/scopeUtils.js deleted file mode 100644 index 2e0ace33..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/util/scopeUtils.js +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { formatError } from "./logging.js"; -/** - * Ensures the scopes value is an array. - * @internal - */ -export function ensureScopes(scopes) { - return Array.isArray(scopes) ? scopes : [scopes]; -} -/** - * Throws if the received scope is not valid. - * @internal - */ -export function ensureValidScopeForDevTimeCreds(scope, logger) { - if (!scope.match(/^[0-9a-zA-Z-_.:/]+$/)) { - const error = new Error("Invalid scope was specified by the user or calling client"); - logger.getToken.info(formatError(scope, error)); - throw error; - } -} -/** - * Returns the resource out of a scope. - * @internal - */ -export function getScopeResource(scope) { - return scope.replace(/\/.default$/, ""); -} -//# sourceMappingURL=scopeUtils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/util/subscriptionUtils.js b/claude-code-source/node_modules/@azure/identity/dist/esm/util/subscriptionUtils.js deleted file mode 100644 index 9aa6afef..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/util/subscriptionUtils.js +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { formatError } from "./logging.js"; -/** - * @internal - */ -export function checkSubscription(logger, subscription) { - if (!subscription.match(/^[0-9a-zA-Z-._ ]+$/)) { - const error = new Error("Invalid subscription provided. You can locate your subscription by following the instructions listed here: https://learn.microsoft.com/azure/azure-portal/get-subscription-tenant-id."); - logger.info(formatError("", error)); - throw error; - } -} -//# sourceMappingURL=subscriptionUtils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/util/tenantIdUtils.js b/claude-code-source/node_modules/@azure/identity/dist/esm/util/tenantIdUtils.js deleted file mode 100644 index 2cbf4d5a..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/util/tenantIdUtils.js +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { ALL_TENANTS, DeveloperSignOnClientId } from "../constants.js"; -import { formatError } from "./logging.js"; -export { processMultiTenantRequest } from "./processMultiTenantRequest.js"; -/** - * @internal - */ -export function checkTenantId(logger, tenantId) { - if (!tenantId.match(/^[0-9a-zA-Z-.]+$/)) { - const error = new Error("Invalid tenant id provided. You can locate your tenant id by following the instructions listed here: https://learn.microsoft.com/partner-center/find-ids-and-domain-names."); - logger.info(formatError("", error)); - throw error; - } -} -/** - * @internal - */ -export function resolveTenantId(logger, tenantId, clientId) { - if (tenantId) { - checkTenantId(logger, tenantId); - return tenantId; - } - if (!clientId) { - clientId = DeveloperSignOnClientId; - } - if (clientId !== DeveloperSignOnClientId) { - return "common"; - } - return "organizations"; -} -/** - * @internal - */ -export function resolveAdditionallyAllowedTenantIds(additionallyAllowedTenants) { - if (!additionallyAllowedTenants || additionallyAllowedTenants.length === 0) { - return []; - } - if (additionallyAllowedTenants.includes("*")) { - return ALL_TENANTS; - } - return additionallyAllowedTenants; -} -//# sourceMappingURL=tenantIdUtils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/identity/dist/esm/util/tracing.js b/claude-code-source/node_modules/@azure/identity/dist/esm/util/tracing.js deleted file mode 100644 index e4a0411c..00000000 --- a/claude-code-source/node_modules/@azure/identity/dist/esm/util/tracing.js +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { SDK_VERSION } from "../constants.js"; -import { createTracingClient } from "@azure/core-tracing"; -/** - * Creates a span using the global tracer. - * @internal - */ -export const tracingClient = createTracingClient({ - namespace: "Microsoft.AAD", - packageName: "@azure/identity", - packageVersion: SDK_VERSION, -}); -//# sourceMappingURL=tracing.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/logger/dist/esm/index.js b/claude-code-source/node_modules/@azure/logger/dist/esm/index.js deleted file mode 100644 index 2cad4bd9..00000000 --- a/claude-code-source/node_modules/@azure/logger/dist/esm/index.js +++ /dev/null @@ -1,40 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createLoggerContext } from "@typespec/ts-http-runtime/internal/logger"; -const context = createLoggerContext({ - logLevelEnvVarName: "AZURE_LOG_LEVEL", - namespace: "azure", -}); -/** - * The AzureLogger provides a mechanism for overriding where logs are output to. - * By default, logs are sent to stderr. - * Override the `log` method to redirect logs to another location. - */ -export const AzureLogger = context.logger; -/** - * Immediately enables logging at the specified log level. If no level is specified, logging is disabled. - * @param level - The log level to enable for logging. - * Options from most verbose to least verbose are: - * - verbose - * - info - * - warning - * - error - */ -export function setLogLevel(level) { - context.setLogLevel(level); -} -/** - * Retrieves the currently specified log level. - */ -export function getLogLevel() { - return context.getLogLevel(); -} -/** - * Creates a logger for use by the Azure SDKs that inherits from `AzureLogger`. - * @param namespace - The name of the SDK package. - * @hidden - */ -export function createClientLogger(namespace) { - return context.createClientLogger(namespace); -} -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/account/AccountInfo.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/account/AccountInfo.mjs deleted file mode 100644 index 1ff56926..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/account/AccountInfo.mjs +++ /dev/null @@ -1,85 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Returns true if tenantId matches the utid portion of homeAccountId - * @param tenantId - * @param homeAccountId - * @returns - */ -function tenantIdMatchesHomeTenant(tenantId, homeAccountId) { - return (!!tenantId && - !!homeAccountId && - tenantId === homeAccountId.split(".")[1]); -} -/** - * Build tenant profile - * @param homeAccountId - Home account identifier for this account object - * @param localAccountId - Local account identifer for this account object - * @param tenantId - Full tenant or organizational id that this account belongs to - * @param idTokenClaims - Claims from the ID token - * @returns - */ -function buildTenantProfile(homeAccountId, localAccountId, tenantId, idTokenClaims) { - if (idTokenClaims) { - const { oid, sub, tid, name, tfp, acr, preferred_username, upn, login_hint, } = idTokenClaims; - /** - * Since there is no way to determine if the authority is AAD or B2C, we exhaust all the possible claims that can serve as tenant ID with the following precedence: - * tid - TenantID claim that identifies the tenant that issued the token in AAD. Expected in all AAD ID tokens, not present in B2C ID Tokens. - * tfp - Trust Framework Policy claim that identifies the policy that was used to authenticate the user. Functions as tenant for B2C scenarios. - * acr - Authentication Context Class Reference claim used only with older B2C policies. Fallback in case tfp is not present, but likely won't be present anyway. - */ - const tenantId = tid || tfp || acr || ""; - return { - tenantId: tenantId, - localAccountId: oid || sub || "", - name: name, - username: preferred_username || upn || "", - loginHint: login_hint, - isHomeTenant: tenantIdMatchesHomeTenant(tenantId, homeAccountId), - }; - } - else { - return { - tenantId, - localAccountId, - username: "", - isHomeTenant: tenantIdMatchesHomeTenant(tenantId, homeAccountId), - }; - } -} -/** - * Replaces account info that varies by tenant profile sourced from the ID token claims passed in with the tenant-specific account info - * @param baseAccountInfo - * @param idTokenClaims - * @returns - */ -function updateAccountTenantProfileData(baseAccountInfo, tenantProfile, idTokenClaims, idTokenSecret) { - let updatedAccountInfo = baseAccountInfo; - // Tenant Profile overrides passed in account info - if (tenantProfile) { - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const { isHomeTenant, ...tenantProfileOverride } = tenantProfile; - updatedAccountInfo = { ...baseAccountInfo, ...tenantProfileOverride }; - } - // ID token claims override passed in account info and tenant profile - if (idTokenClaims) { - // Ignore isHomeTenant, loginHint, and sid which are part of tenant profile but not base account info - // eslint-disable-next-line @typescript-eslint/no-unused-vars - const { isHomeTenant, ...claimsSourcedTenantProfile } = buildTenantProfile(baseAccountInfo.homeAccountId, baseAccountInfo.localAccountId, baseAccountInfo.tenantId, idTokenClaims); - updatedAccountInfo = { - ...updatedAccountInfo, - ...claimsSourcedTenantProfile, - idTokenClaims: idTokenClaims, - idToken: idTokenSecret, - }; - return updatedAccountInfo; - } - return updatedAccountInfo; -} - -export { buildTenantProfile, tenantIdMatchesHomeTenant, updateAccountTenantProfileData }; -//# sourceMappingURL=AccountInfo.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/account/AuthToken.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/account/AuthToken.mjs deleted file mode 100644 index 3b04a3c9..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/account/AuthToken.mjs +++ /dev/null @@ -1,86 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { createClientAuthError } from '../error/ClientAuthError.mjs'; -import { tokenParsingError, nullOrEmptyToken, maxAgeTranspired } from '../error/ClientAuthErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Extract token by decoding the rawToken - * - * @param encodedToken - */ -function extractTokenClaims(encodedToken, base64Decode) { - const jswPayload = getJWSPayload(encodedToken); - // token will be decoded to get the username - try { - // base64Decode() should throw an error if there is an issue - const base64Decoded = base64Decode(jswPayload); - return JSON.parse(base64Decoded); - } - catch (err) { - throw createClientAuthError(tokenParsingError); - } -} -/** - * Check if the signin_state claim contains "kmsi" - * @param idTokenClaims - * @returns - */ -function isKmsi(idTokenClaims) { - if (!idTokenClaims.signin_state) { - return false; - } - /** - * Signin_state claim known values: - * dvc_mngd - device is managed - * dvc_dmjd - device is domain joined - * kmsi - user opted to "keep me signed in" - * inknownntwk - Request made inside a known network. Don't use this, use CAE instead. - */ - const kmsiClaims = ["kmsi", "dvc_dmjd"]; // There are some cases where kmsi may not be returned but persistent storage is still OK - allow dvc_dmjd as well - const kmsi = idTokenClaims.signin_state.some((value) => kmsiClaims.includes(value.trim().toLowerCase())); - return kmsi; -} -/** - * decode a JWT - * - * @param authToken - */ -function getJWSPayload(authToken) { - if (!authToken) { - throw createClientAuthError(nullOrEmptyToken); - } - const tokenPartsRegex = /^([^\.\s]*)\.([^\.\s]+)\.([^\.\s]*)$/; - const matches = tokenPartsRegex.exec(authToken); - if (!matches || matches.length < 4) { - throw createClientAuthError(tokenParsingError); - } - /** - * const crackedToken = { - * header: matches[1], - * JWSPayload: matches[2], - * JWSSig: matches[3], - * }; - */ - return matches[2]; -} -/** - * Determine if the token's max_age has transpired - */ -function checkMaxAge(authTime, maxAge) { - /* - * per https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest - * To force an immediate re-authentication: If an app requires that a user re-authenticate prior to access, - * provide a value of 0 for the max_age parameter and the AS will force a fresh login. - */ - const fiveMinuteSkew = 300000; // five minutes in milliseconds - if (maxAge === 0 || Date.now() - fiveMinuteSkew > authTime + maxAge) { - throw createClientAuthError(maxAgeTranspired); - } -} - -export { checkMaxAge, extractTokenClaims, getJWSPayload, isKmsi }; -//# sourceMappingURL=AuthToken.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/account/CcsCredential.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/account/CcsCredential.mjs deleted file mode 100644 index 3310d948..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/account/CcsCredential.mjs +++ /dev/null @@ -1,13 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const CcsCredentialType = { - HOME_ACCOUNT_ID: "home_account_id", - UPN: "UPN", -}; - -export { CcsCredentialType }; -//# sourceMappingURL=CcsCredential.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/account/ClientInfo.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/account/ClientInfo.mjs deleted file mode 100644 index 1219e36a..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/account/ClientInfo.mjs +++ /dev/null @@ -1,46 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { createClientAuthError } from '../error/ClientAuthError.mjs'; -import { Separators, Constants } from '../utils/Constants.mjs'; -import { clientInfoEmptyError, clientInfoDecodingError } from '../error/ClientAuthErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Function to build a client info object from server clientInfo string - * @param rawClientInfo - * @param crypto - */ -function buildClientInfo(rawClientInfo, base64Decode) { - if (!rawClientInfo) { - throw createClientAuthError(clientInfoEmptyError); - } - try { - const decodedClientInfo = base64Decode(rawClientInfo); - return JSON.parse(decodedClientInfo); - } - catch (e) { - throw createClientAuthError(clientInfoDecodingError); - } -} -/** - * Function to build a client info object from cached homeAccountId string - * @param homeAccountId - */ -function buildClientInfoFromHomeAccountId(homeAccountId) { - if (!homeAccountId) { - throw createClientAuthError(clientInfoDecodingError); - } - const clientInfoParts = homeAccountId.split(Separators.CLIENT_INFO_SEPARATOR, 2); - return { - uid: clientInfoParts[0], - utid: clientInfoParts.length < 2 - ? Constants.EMPTY_STRING - : clientInfoParts[1], - }; -} - -export { buildClientInfo, buildClientInfoFromHomeAccountId }; -//# sourceMappingURL=ClientInfo.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/account/TokenClaims.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/account/TokenClaims.mjs deleted file mode 100644 index a4c491b6..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/account/TokenClaims.mjs +++ /dev/null @@ -1,25 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Gets tenantId from available ID token claims to set as credential realm with the following precedence: - * 1. tid - if the token is acquired from an Azure AD tenant tid will be present - * 2. tfp - if the token is acquired from a modern B2C tenant tfp should be present - * 3. acr - if the token is acquired from a legacy B2C tenant acr should be present - * Downcased to match the realm case-insensitive comparison requirements - * @param idTokenClaims - * @returns - */ -function getTenantIdFromIdTokenClaims(idTokenClaims) { - if (idTokenClaims) { - const tenantId = idTokenClaims.tid || idTokenClaims.tfp || idTokenClaims.acr; - return tenantId || null; - } - return null; -} - -export { getTenantIdFromIdTokenClaims }; -//# sourceMappingURL=TokenClaims.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/authority/Authority.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/authority/Authority.mjs deleted file mode 100644 index 6804a032..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/authority/Authority.mjs +++ /dev/null @@ -1,860 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { AuthorityType } from './AuthorityType.mjs'; -import { isOpenIdConfigResponse } from './OpenIdConfigResponse.mjs'; -import { UrlString } from '../url/UrlString.mjs'; -import { createClientAuthError } from '../error/ClientAuthError.mjs'; -import { Constants, AuthorityMetadataSource, RegionDiscoveryOutcomes, AADAuthorityConstants } from '../utils/Constants.mjs'; -import { EndpointMetadata, getCloudDiscoveryMetadataFromHardcodedValues, getCloudDiscoveryMetadataFromNetworkResponse, InstanceDiscoveryMetadataAliases } from './AuthorityMetadata.mjs'; -import { createClientConfigurationError } from '../error/ClientConfigurationError.mjs'; -import { ProtocolMode } from './ProtocolMode.mjs'; -import { AzureCloudInstance } from './AuthorityOptions.mjs'; -import { isCloudInstanceDiscoveryResponse } from './CloudInstanceDiscoveryResponse.mjs'; -import { isCloudInstanceDiscoveryErrorResponse } from './CloudInstanceDiscoveryErrorResponse.mjs'; -import { RegionDiscovery } from './RegionDiscovery.mjs'; -import { AuthError } from '../error/AuthError.mjs'; -import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs'; -import { invokeAsync } from '../utils/FunctionWrappers.mjs'; -import { generateAuthorityMetadataExpiresAt, updateAuthorityEndpointMetadata, isAuthorityMetadataExpired, updateCloudDiscoveryMetadata } from '../cache/utils/CacheHelpers.mjs'; -import { endpointResolutionError, endSessionEndpointNotSupported, openIdConfigError } from '../error/ClientAuthErrorCodes.mjs'; -import { invalidAuthorityMetadata, untrustedAuthority, invalidCloudDiscoveryMetadata } from '../error/ClientConfigurationErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * The authority class validates the authority URIs used by the user, and retrieves the OpenID Configuration Data from the - * endpoint. It will store the pertinent config data in this object for use during token calls. - * @internal - */ -class Authority { - constructor(authority, networkInterface, cacheManager, authorityOptions, logger, correlationId, performanceClient, managedIdentity) { - this.canonicalAuthority = authority; - this._canonicalAuthority.validateAsUri(); - this.networkInterface = networkInterface; - this.cacheManager = cacheManager; - this.authorityOptions = authorityOptions; - this.regionDiscoveryMetadata = { - region_used: undefined, - region_source: undefined, - region_outcome: undefined, - }; - this.logger = logger; - this.performanceClient = performanceClient; - this.correlationId = correlationId; - this.managedIdentity = managedIdentity || false; - this.regionDiscovery = new RegionDiscovery(networkInterface, this.logger, this.performanceClient, this.correlationId); - } - /** - * Get {@link AuthorityType} - * @param authorityUri {@link IUri} - * @private - */ - getAuthorityType(authorityUri) { - // CIAM auth url pattern is being standardized as: .ciamlogin.com - if (authorityUri.HostNameAndPort.endsWith(Constants.CIAM_AUTH_URL)) { - return AuthorityType.Ciam; - } - const pathSegments = authorityUri.PathSegments; - if (pathSegments.length) { - switch (pathSegments[0].toLowerCase()) { - case Constants.ADFS: - return AuthorityType.Adfs; - case Constants.DSTS: - return AuthorityType.Dsts; - } - } - return AuthorityType.Default; - } - // See above for AuthorityType - get authorityType() { - return this.getAuthorityType(this.canonicalAuthorityUrlComponents); - } - /** - * ProtocolMode enum representing the way endpoints are constructed. - */ - get protocolMode() { - return this.authorityOptions.protocolMode; - } - /** - * Returns authorityOptions which can be used to reinstantiate a new authority instance - */ - get options() { - return this.authorityOptions; - } - /** - * A URL that is the authority set by the developer - */ - get canonicalAuthority() { - return this._canonicalAuthority.urlString; - } - /** - * Sets canonical authority. - */ - set canonicalAuthority(url) { - this._canonicalAuthority = new UrlString(url); - this._canonicalAuthority.validateAsUri(); - this._canonicalAuthorityUrlComponents = null; - } - /** - * Get authority components. - */ - get canonicalAuthorityUrlComponents() { - if (!this._canonicalAuthorityUrlComponents) { - this._canonicalAuthorityUrlComponents = - this._canonicalAuthority.getUrlComponents(); - } - return this._canonicalAuthorityUrlComponents; - } - /** - * Get hostname and port i.e. login.microsoftonline.com - */ - get hostnameAndPort() { - return this.canonicalAuthorityUrlComponents.HostNameAndPort.toLowerCase(); - } - /** - * Get tenant for authority. - */ - get tenant() { - return this.canonicalAuthorityUrlComponents.PathSegments[0]; - } - /** - * OAuth /authorize endpoint for requests - */ - get authorizationEndpoint() { - if (this.discoveryComplete()) { - return this.replacePath(this.metadata.authorization_endpoint); - } - else { - throw createClientAuthError(endpointResolutionError); - } - } - /** - * OAuth /token endpoint for requests - */ - get tokenEndpoint() { - if (this.discoveryComplete()) { - return this.replacePath(this.metadata.token_endpoint); - } - else { - throw createClientAuthError(endpointResolutionError); - } - } - get deviceCodeEndpoint() { - if (this.discoveryComplete()) { - return this.replacePath(this.metadata.token_endpoint.replace("/token", "/devicecode")); - } - else { - throw createClientAuthError(endpointResolutionError); - } - } - /** - * OAuth logout endpoint for requests - */ - get endSessionEndpoint() { - if (this.discoveryComplete()) { - // ROPC policies may not have end_session_endpoint set - if (!this.metadata.end_session_endpoint) { - throw createClientAuthError(endSessionEndpointNotSupported); - } - return this.replacePath(this.metadata.end_session_endpoint); - } - else { - throw createClientAuthError(endpointResolutionError); - } - } - /** - * OAuth issuer for requests - */ - get selfSignedJwtAudience() { - if (this.discoveryComplete()) { - return this.replacePath(this.metadata.issuer); - } - else { - throw createClientAuthError(endpointResolutionError); - } - } - /** - * Jwks_uri for token signing keys - */ - get jwksUri() { - if (this.discoveryComplete()) { - return this.replacePath(this.metadata.jwks_uri); - } - else { - throw createClientAuthError(endpointResolutionError); - } - } - /** - * Returns a flag indicating that tenant name can be replaced in authority {@link IUri} - * @param authorityUri {@link IUri} - * @private - */ - canReplaceTenant(authorityUri) { - return (authorityUri.PathSegments.length === 1 && - !Authority.reservedTenantDomains.has(authorityUri.PathSegments[0]) && - this.getAuthorityType(authorityUri) === AuthorityType.Default && - this.protocolMode !== ProtocolMode.OIDC); - } - /** - * Replaces tenant in url path with current tenant. Defaults to common. - * @param urlString - */ - replaceTenant(urlString) { - return urlString.replace(/{tenant}|{tenantid}/g, this.tenant); - } - /** - * Replaces path such as tenant or policy with the current tenant or policy. - * @param urlString - */ - replacePath(urlString) { - let endpoint = urlString; - const cachedAuthorityUrl = new UrlString(this.metadata.canonical_authority); - const cachedAuthorityUrlComponents = cachedAuthorityUrl.getUrlComponents(); - const cachedAuthorityParts = cachedAuthorityUrlComponents.PathSegments; - const currentAuthorityParts = this.canonicalAuthorityUrlComponents.PathSegments; - currentAuthorityParts.forEach((currentPart, index) => { - let cachedPart = cachedAuthorityParts[index]; - if (index === 0 && - this.canReplaceTenant(cachedAuthorityUrlComponents)) { - const tenantId = new UrlString(this.metadata.authorization_endpoint).getUrlComponents().PathSegments[0]; - /** - * Check if AAD canonical authority contains tenant domain name, for example "testdomain.onmicrosoft.com", - * by comparing its first path segment to the corresponding authorization endpoint path segment, which is - * always resolved with tenant id by OIDC. - */ - if (cachedPart !== tenantId) { - this.logger.verbose(`Replacing tenant domain name ${cachedPart} with id ${tenantId}`); - cachedPart = tenantId; - } - } - if (currentPart !== cachedPart) { - endpoint = endpoint.replace(`/${cachedPart}/`, `/${currentPart}/`); - } - }); - return this.replaceTenant(endpoint); - } - /** - * The default open id configuration endpoint for any canonical authority. - */ - get defaultOpenIdConfigurationEndpoint() { - const canonicalAuthorityHost = this.hostnameAndPort; - if (this.canonicalAuthority.endsWith("v2.0/") || - this.authorityType === AuthorityType.Adfs || - (this.protocolMode === ProtocolMode.OIDC && - !this.isAliasOfKnownMicrosoftAuthority(canonicalAuthorityHost))) { - return `${this.canonicalAuthority}.well-known/openid-configuration`; - } - return `${this.canonicalAuthority}v2.0/.well-known/openid-configuration`; - } - /** - * Boolean that returns whether or not tenant discovery has been completed. - */ - discoveryComplete() { - return !!this.metadata; - } - /** - * Perform endpoint discovery to discover aliases, preferred_cache, preferred_network - * and the /authorize, /token and logout endpoints. - */ - async resolveEndpointsAsync() { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityResolveEndpointsAsync, this.correlationId); - const metadataEntity = this.getCurrentMetadataEntity(); - const cloudDiscoverySource = await invokeAsync(this.updateCloudDiscoveryMetadata.bind(this), PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata, this.logger, this.performanceClient, this.correlationId)(metadataEntity); - this.canonicalAuthority = this.canonicalAuthority.replace(this.hostnameAndPort, metadataEntity.preferred_network); - const endpointSource = await invokeAsync(this.updateEndpointMetadata.bind(this), PerformanceEvents.AuthorityUpdateEndpointMetadata, this.logger, this.performanceClient, this.correlationId)(metadataEntity); - this.updateCachedMetadata(metadataEntity, cloudDiscoverySource, { - source: endpointSource, - }); - this.performanceClient?.addFields({ - cloudDiscoverySource: cloudDiscoverySource, - authorityEndpointSource: endpointSource, - }, this.correlationId); - } - /** - * Returns metadata entity from cache if it exists, otherwiser returns a new metadata entity built - * from the configured canonical authority - * @returns - */ - getCurrentMetadataEntity() { - let metadataEntity = this.cacheManager.getAuthorityMetadataByAlias(this.hostnameAndPort); - if (!metadataEntity) { - metadataEntity = { - aliases: [], - preferred_cache: this.hostnameAndPort, - preferred_network: this.hostnameAndPort, - canonical_authority: this.canonicalAuthority, - authorization_endpoint: "", - token_endpoint: "", - end_session_endpoint: "", - issuer: "", - aliasesFromNetwork: false, - endpointsFromNetwork: false, - expiresAt: generateAuthorityMetadataExpiresAt(), - jwks_uri: "", - }; - } - return metadataEntity; - } - /** - * Updates cached metadata based on metadata source and sets the instance's metadata - * property to the same value - * @param metadataEntity - * @param cloudDiscoverySource - * @param endpointMetadataResult - */ - updateCachedMetadata(metadataEntity, cloudDiscoverySource, endpointMetadataResult) { - if (cloudDiscoverySource !== AuthorityMetadataSource.CACHE && - endpointMetadataResult?.source !== AuthorityMetadataSource.CACHE) { - // Reset the expiration time unless both values came from a successful cache lookup - metadataEntity.expiresAt = - generateAuthorityMetadataExpiresAt(); - metadataEntity.canonical_authority = this.canonicalAuthority; - } - const cacheKey = this.cacheManager.generateAuthorityMetadataCacheKey(metadataEntity.preferred_cache); - this.cacheManager.setAuthorityMetadata(cacheKey, metadataEntity); - this.metadata = metadataEntity; - } - /** - * Update AuthorityMetadataEntity with new endpoints and return where the information came from - * @param metadataEntity - */ - async updateEndpointMetadata(metadataEntity) { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityUpdateEndpointMetadata, this.correlationId); - const localMetadata = this.updateEndpointMetadataFromLocalSources(metadataEntity); - // Further update may be required for hardcoded metadata if regional metadata is preferred - if (localMetadata) { - if (localMetadata.source === - AuthorityMetadataSource.HARDCODED_VALUES) { - // If the user prefers to use an azure region replace the global endpoints with regional information. - if (this.authorityOptions.azureRegionConfiguration?.azureRegion) { - if (localMetadata.metadata) { - const hardcodedMetadata = await invokeAsync(this.updateMetadataWithRegionalInformation.bind(this), PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.logger, this.performanceClient, this.correlationId)(localMetadata.metadata); - updateAuthorityEndpointMetadata(metadataEntity, hardcodedMetadata, false); - metadataEntity.canonical_authority = - this.canonicalAuthority; - } - } - } - return localMetadata.source; - } - // Get metadata from network if local sources aren't available - let metadata = await invokeAsync(this.getEndpointMetadataFromNetwork.bind(this), PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork, this.logger, this.performanceClient, this.correlationId)(); - if (metadata) { - // If the user prefers to use an azure region replace the global endpoints with regional information. - if (this.authorityOptions.azureRegionConfiguration?.azureRegion) { - metadata = await invokeAsync(this.updateMetadataWithRegionalInformation.bind(this), PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.logger, this.performanceClient, this.correlationId)(metadata); - } - updateAuthorityEndpointMetadata(metadataEntity, metadata, true); - return AuthorityMetadataSource.NETWORK; - } - else { - // Metadata could not be obtained from the config, cache, network or hardcoded values - throw createClientAuthError(openIdConfigError, this.defaultOpenIdConfigurationEndpoint); - } - } - /** - * Updates endpoint metadata from local sources and returns where the information was retrieved from and the metadata config - * response if the source is hardcoded metadata - * @param metadataEntity - * @returns - */ - updateEndpointMetadataFromLocalSources(metadataEntity) { - this.logger.verbose("Attempting to get endpoint metadata from authority configuration"); - const configMetadata = this.getEndpointMetadataFromConfig(); - if (configMetadata) { - this.logger.verbose("Found endpoint metadata in authority configuration"); - updateAuthorityEndpointMetadata(metadataEntity, configMetadata, false); - return { - source: AuthorityMetadataSource.CONFIG, - }; - } - this.logger.verbose("Did not find endpoint metadata in the config... Attempting to get endpoint metadata from the hardcoded values."); - // skipAuthorityMetadataCache is used to bypass hardcoded authority metadata and force a network metadata cache lookup and network metadata request if no cached response is available. - if (this.authorityOptions.skipAuthorityMetadataCache) { - this.logger.verbose("Skipping hardcoded metadata cache since skipAuthorityMetadataCache is set to true. Attempting to get endpoint metadata from the network metadata cache."); - } - else { - const hardcodedMetadata = this.getEndpointMetadataFromHardcodedValues(); - if (hardcodedMetadata) { - updateAuthorityEndpointMetadata(metadataEntity, hardcodedMetadata, false); - return { - source: AuthorityMetadataSource.HARDCODED_VALUES, - metadata: hardcodedMetadata, - }; - } - else { - this.logger.verbose("Did not find endpoint metadata in hardcoded values... Attempting to get endpoint metadata from the network metadata cache."); - } - } - // Check cached metadata entity expiration status - const metadataEntityExpired = isAuthorityMetadataExpired(metadataEntity); - if (this.isAuthoritySameType(metadataEntity) && - metadataEntity.endpointsFromNetwork && - !metadataEntityExpired) { - // No need to update - this.logger.verbose("Found endpoint metadata in the cache."); - return { source: AuthorityMetadataSource.CACHE }; - } - else if (metadataEntityExpired) { - this.logger.verbose("The metadata entity is expired."); - } - return null; - } - /** - * Compares the number of url components after the domain to determine if the cached - * authority metadata can be used for the requested authority. Protects against same domain different - * authority such as login.microsoftonline.com/tenant and login.microsoftonline.com/tfp/tenant/policy - * @param metadataEntity - */ - isAuthoritySameType(metadataEntity) { - const cachedAuthorityUrl = new UrlString(metadataEntity.canonical_authority); - const cachedParts = cachedAuthorityUrl.getUrlComponents().PathSegments; - return (cachedParts.length === - this.canonicalAuthorityUrlComponents.PathSegments.length); - } - /** - * Parse authorityMetadata config option - */ - getEndpointMetadataFromConfig() { - if (this.authorityOptions.authorityMetadata) { - try { - return JSON.parse(this.authorityOptions.authorityMetadata); - } - catch (e) { - throw createClientConfigurationError(invalidAuthorityMetadata); - } - } - return null; - } - /** - * Gets OAuth endpoints from the given OpenID configuration endpoint. - * - * @param hasHardcodedMetadata boolean - */ - async getEndpointMetadataFromNetwork() { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork, this.correlationId); - const options = {}; - /* - * TODO: Add a timeout if the authority exists in our library's - * hardcoded list of metadata - */ - const openIdConfigurationEndpoint = this.defaultOpenIdConfigurationEndpoint; - this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: attempting to retrieve OAuth endpoints from ${openIdConfigurationEndpoint}`); - try { - const response = await this.networkInterface.sendGetRequestAsync(openIdConfigurationEndpoint, options); - const isValidResponse = isOpenIdConfigResponse(response.body); - if (isValidResponse) { - return response.body; - } - else { - this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: could not parse response as OpenID configuration`); - return null; - } - } - catch (e) { - this.logger.verbose(`Authority.getEndpointMetadataFromNetwork: ${e}`); - return null; - } - } - /** - * Get OAuth endpoints for common authorities. - */ - getEndpointMetadataFromHardcodedValues() { - if (this.hostnameAndPort in EndpointMetadata) { - return EndpointMetadata[this.hostnameAndPort]; - } - return null; - } - /** - * Update the retrieved metadata with regional information. - * User selected Azure region will be used if configured. - */ - async updateMetadataWithRegionalInformation(metadata) { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, this.correlationId); - const userConfiguredAzureRegion = this.authorityOptions.azureRegionConfiguration?.azureRegion; - if (userConfiguredAzureRegion) { - if (userConfiguredAzureRegion !== - Constants.AZURE_REGION_AUTO_DISCOVER_FLAG) { - this.regionDiscoveryMetadata.region_outcome = - RegionDiscoveryOutcomes.CONFIGURED_NO_AUTO_DETECTION; - this.regionDiscoveryMetadata.region_used = - userConfiguredAzureRegion; - return Authority.replaceWithRegionalInformation(metadata, userConfiguredAzureRegion); - } - const autodetectedRegionName = await invokeAsync(this.regionDiscovery.detectRegion.bind(this.regionDiscovery), PerformanceEvents.RegionDiscoveryDetectRegion, this.logger, this.performanceClient, this.correlationId)(this.authorityOptions.azureRegionConfiguration - ?.environmentRegion, this.regionDiscoveryMetadata); - if (autodetectedRegionName) { - this.regionDiscoveryMetadata.region_outcome = - RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_SUCCESSFUL; - this.regionDiscoveryMetadata.region_used = - autodetectedRegionName; - return Authority.replaceWithRegionalInformation(metadata, autodetectedRegionName); - } - this.regionDiscoveryMetadata.region_outcome = - RegionDiscoveryOutcomes.AUTO_DETECTION_REQUESTED_FAILED; - } - return metadata; - } - /** - * Updates the AuthorityMetadataEntity with new aliases, preferred_network and preferred_cache - * and returns where the information was retrieved from - * @param metadataEntity - * @returns AuthorityMetadataSource - */ - async updateCloudDiscoveryMetadata(metadataEntity) { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata, this.correlationId); - const localMetadataSource = this.updateCloudDiscoveryMetadataFromLocalSources(metadataEntity); - if (localMetadataSource) { - return localMetadataSource; - } - // Fallback to network as metadata source - const metadata = await invokeAsync(this.getCloudDiscoveryMetadataFromNetwork.bind(this), PerformanceEvents.AuthorityGetCloudDiscoveryMetadataFromNetwork, this.logger, this.performanceClient, this.correlationId)(); - if (metadata) { - updateCloudDiscoveryMetadata(metadataEntity, metadata, true); - return AuthorityMetadataSource.NETWORK; - } - // Metadata could not be obtained from the config, cache, network or hardcoded values - throw createClientConfigurationError(untrustedAuthority); - } - updateCloudDiscoveryMetadataFromLocalSources(metadataEntity) { - this.logger.verbose("Attempting to get cloud discovery metadata from authority configuration"); - this.logger.verbosePii(`Known Authorities: ${this.authorityOptions.knownAuthorities || - Constants.NOT_APPLICABLE}`); - this.logger.verbosePii(`Authority Metadata: ${this.authorityOptions.authorityMetadata || - Constants.NOT_APPLICABLE}`); - this.logger.verbosePii(`Canonical Authority: ${metadataEntity.canonical_authority || Constants.NOT_APPLICABLE}`); - const metadata = this.getCloudDiscoveryMetadataFromConfig(); - if (metadata) { - this.logger.verbose("Found cloud discovery metadata in authority configuration"); - updateCloudDiscoveryMetadata(metadataEntity, metadata, false); - return AuthorityMetadataSource.CONFIG; - } - // If the cached metadata came from config but that config was not passed to this instance, we must go to hardcoded values - this.logger.verbose("Did not find cloud discovery metadata in the config... Attempting to get cloud discovery metadata from the hardcoded values."); - if (this.options.skipAuthorityMetadataCache) { - this.logger.verbose("Skipping hardcoded cloud discovery metadata cache since skipAuthorityMetadataCache is set to true. Attempting to get cloud discovery metadata from the network metadata cache."); - } - else { - const hardcodedMetadata = getCloudDiscoveryMetadataFromHardcodedValues(this.hostnameAndPort); - if (hardcodedMetadata) { - this.logger.verbose("Found cloud discovery metadata from hardcoded values."); - updateCloudDiscoveryMetadata(metadataEntity, hardcodedMetadata, false); - return AuthorityMetadataSource.HARDCODED_VALUES; - } - this.logger.verbose("Did not find cloud discovery metadata in hardcoded values... Attempting to get cloud discovery metadata from the network metadata cache."); - } - const metadataEntityExpired = isAuthorityMetadataExpired(metadataEntity); - if (this.isAuthoritySameType(metadataEntity) && - metadataEntity.aliasesFromNetwork && - !metadataEntityExpired) { - this.logger.verbose("Found cloud discovery metadata in the cache."); - // No need to update - return AuthorityMetadataSource.CACHE; - } - else if (metadataEntityExpired) { - this.logger.verbose("The metadata entity is expired."); - } - return null; - } - /** - * Parse cloudDiscoveryMetadata config or check knownAuthorities - */ - getCloudDiscoveryMetadataFromConfig() { - // CIAM does not support cloud discovery metadata - if (this.authorityType === AuthorityType.Ciam) { - this.logger.verbose("CIAM authorities do not support cloud discovery metadata, generate the aliases from authority host."); - return Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort); - } - // Check if network response was provided in config - if (this.authorityOptions.cloudDiscoveryMetadata) { - this.logger.verbose("The cloud discovery metadata has been provided as a network response, in the config."); - try { - this.logger.verbose("Attempting to parse the cloud discovery metadata."); - const parsedResponse = JSON.parse(this.authorityOptions.cloudDiscoveryMetadata); - const metadata = getCloudDiscoveryMetadataFromNetworkResponse(parsedResponse.metadata, this.hostnameAndPort); - this.logger.verbose("Parsed the cloud discovery metadata."); - if (metadata) { - this.logger.verbose("There is returnable metadata attached to the parsed cloud discovery metadata."); - return metadata; - } - else { - this.logger.verbose("There is no metadata attached to the parsed cloud discovery metadata."); - } - } - catch (e) { - this.logger.verbose("Unable to parse the cloud discovery metadata. Throwing Invalid Cloud Discovery Metadata Error."); - throw createClientConfigurationError(invalidCloudDiscoveryMetadata); - } - } - // If cloudDiscoveryMetadata is empty or does not contain the host, check knownAuthorities - if (this.isInKnownAuthorities()) { - this.logger.verbose("The host is included in knownAuthorities. Creating new cloud discovery metadata from the host."); - return Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort); - } - return null; - } - /** - * Called to get metadata from network if CloudDiscoveryMetadata was not populated by config - * - * @param hasHardcodedMetadata boolean - */ - async getCloudDiscoveryMetadataFromNetwork() { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityGetCloudDiscoveryMetadataFromNetwork, this.correlationId); - const instanceDiscoveryEndpoint = `${Constants.AAD_INSTANCE_DISCOVERY_ENDPT}${this.canonicalAuthority}oauth2/v2.0/authorize`; - const options = {}; - /* - * TODO: Add a timeout if the authority exists in our library's - * hardcoded list of metadata - */ - let match = null; - try { - const response = await this.networkInterface.sendGetRequestAsync(instanceDiscoveryEndpoint, options); - let typedResponseBody; - let metadata; - if (isCloudInstanceDiscoveryResponse(response.body)) { - typedResponseBody = - response.body; - metadata = typedResponseBody.metadata; - this.logger.verbosePii(`tenant_discovery_endpoint is: ${typedResponseBody.tenant_discovery_endpoint}`); - } - else if (isCloudInstanceDiscoveryErrorResponse(response.body)) { - this.logger.warning(`A CloudInstanceDiscoveryErrorResponse was returned. The cloud instance discovery network request's status code is: ${response.status}`); - typedResponseBody = - response.body; - if (typedResponseBody.error === Constants.INVALID_INSTANCE) { - this.logger.error("The CloudInstanceDiscoveryErrorResponse error is invalid_instance."); - return null; - } - this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error is ${typedResponseBody.error}`); - this.logger.warning(`The CloudInstanceDiscoveryErrorResponse error description is ${typedResponseBody.error_description}`); - this.logger.warning("Setting the value of the CloudInstanceDiscoveryMetadata (returned from the network) to []"); - metadata = []; - } - else { - this.logger.error("AAD did not return a CloudInstanceDiscoveryResponse or CloudInstanceDiscoveryErrorResponse"); - return null; - } - this.logger.verbose("Attempting to find a match between the developer's authority and the CloudInstanceDiscoveryMetadata returned from the network request."); - match = getCloudDiscoveryMetadataFromNetworkResponse(metadata, this.hostnameAndPort); - } - catch (error) { - if (error instanceof AuthError) { - this.logger.error(`There was a network error while attempting to get the cloud discovery instance metadata.\nError: ${error.errorCode}\nError Description: ${error.errorMessage}`); - } - else { - const typedError = error; - this.logger.error(`A non-MSALJS error was thrown while attempting to get the cloud instance discovery metadata.\nError: ${typedError.name}\nError Description: ${typedError.message}`); - } - return null; - } - // Custom Domain scenario, host is trusted because Instance Discovery call succeeded - if (!match) { - this.logger.warning("The developer's authority was not found within the CloudInstanceDiscoveryMetadata returned from the network request."); - this.logger.verbose("Creating custom Authority for custom domain scenario."); - match = Authority.createCloudDiscoveryMetadataFromHost(this.hostnameAndPort); - } - return match; - } - /** - * Helper function to determine if this host is included in the knownAuthorities config option - */ - isInKnownAuthorities() { - const matches = this.authorityOptions.knownAuthorities.filter((authority) => { - return (authority && - UrlString.getDomainFromUrl(authority).toLowerCase() === - this.hostnameAndPort); - }); - return matches.length > 0; - } - /** - * helper function to populate the authority based on azureCloudOptions - * @param authorityString - * @param azureCloudOptions - */ - static generateAuthority(authorityString, azureCloudOptions) { - let authorityAzureCloudInstance; - if (azureCloudOptions && - azureCloudOptions.azureCloudInstance !== AzureCloudInstance.None) { - const tenant = azureCloudOptions.tenant - ? azureCloudOptions.tenant - : Constants.DEFAULT_COMMON_TENANT; - authorityAzureCloudInstance = `${azureCloudOptions.azureCloudInstance}/${tenant}/`; - } - return authorityAzureCloudInstance - ? authorityAzureCloudInstance - : authorityString; - } - /** - * Creates cloud discovery metadata object from a given host - * @param host - */ - static createCloudDiscoveryMetadataFromHost(host) { - return { - preferred_network: host, - preferred_cache: host, - aliases: [host], - }; - } - /** - * helper function to generate environment from authority object - */ - getPreferredCache() { - if (this.managedIdentity) { - return Constants.DEFAULT_AUTHORITY_HOST; - } - else if (this.discoveryComplete()) { - return this.metadata.preferred_cache; - } - else { - throw createClientAuthError(endpointResolutionError); - } - } - /** - * Returns whether or not the provided host is an alias of this authority instance - * @param host - */ - isAlias(host) { - return this.metadata.aliases.indexOf(host) > -1; - } - /** - * Returns whether or not the provided host is an alias of a known Microsoft authority for purposes of endpoint discovery - * @param host - */ - isAliasOfKnownMicrosoftAuthority(host) { - return InstanceDiscoveryMetadataAliases.has(host); - } - /** - * Checks whether the provided host is that of a public cloud authority - * - * @param authority string - * @returns bool - */ - static isPublicCloudAuthority(host) { - return Constants.KNOWN_PUBLIC_CLOUDS.indexOf(host) >= 0; - } - /** - * Rebuild the authority string with the region - * - * @param host string - * @param region string - */ - static buildRegionalAuthorityString(host, region, queryString) { - // Create and validate a Url string object with the initial authority string - const authorityUrlInstance = new UrlString(host); - authorityUrlInstance.validateAsUri(); - const authorityUrlParts = authorityUrlInstance.getUrlComponents(); - let hostNameAndPort = `${region}.${authorityUrlParts.HostNameAndPort}`; - if (this.isPublicCloudAuthority(authorityUrlParts.HostNameAndPort)) { - hostNameAndPort = `${region}.${Constants.REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX}`; - } - // Include the query string portion of the url - const url = UrlString.constructAuthorityUriFromObject({ - ...authorityUrlInstance.getUrlComponents(), - HostNameAndPort: hostNameAndPort, - }).urlString; - // Add the query string if a query string was provided - if (queryString) - return `${url}?${queryString}`; - return url; - } - /** - * Replace the endpoints in the metadata object with their regional equivalents. - * - * @param metadata OpenIdConfigResponse - * @param azureRegion string - */ - static replaceWithRegionalInformation(metadata, azureRegion) { - const regionalMetadata = { ...metadata }; - regionalMetadata.authorization_endpoint = - Authority.buildRegionalAuthorityString(regionalMetadata.authorization_endpoint, azureRegion); - regionalMetadata.token_endpoint = - Authority.buildRegionalAuthorityString(regionalMetadata.token_endpoint, azureRegion); - if (regionalMetadata.end_session_endpoint) { - regionalMetadata.end_session_endpoint = - Authority.buildRegionalAuthorityString(regionalMetadata.end_session_endpoint, azureRegion); - } - return regionalMetadata; - } - /** - * Transform CIAM_AUTHORIY as per the below rules: - * If no path segments found and it is a CIAM authority (hostname ends with .ciamlogin.com), then transform it - * - * NOTE: The transformation path should go away once STS supports CIAM with the format: `tenantIdorDomain.ciamlogin.com` - * `ciamlogin.com` can also change in the future and we should accommodate the same - * - * @param authority - */ - static transformCIAMAuthority(authority) { - let ciamAuthority = authority; - const authorityUrl = new UrlString(authority); - const authorityUrlComponents = authorityUrl.getUrlComponents(); - // check if transformation is needed - if (authorityUrlComponents.PathSegments.length === 0 && - authorityUrlComponents.HostNameAndPort.endsWith(Constants.CIAM_AUTH_URL)) { - const tenantIdOrDomain = authorityUrlComponents.HostNameAndPort.split(".")[0]; - ciamAuthority = `${ciamAuthority}${tenantIdOrDomain}${Constants.AAD_TENANT_DOMAIN_SUFFIX}`; - } - return ciamAuthority; - } -} -// Reserved tenant domain names that will not be replaced with tenant id -Authority.reservedTenantDomains = new Set([ - "{tenant}", - "{tenantid}", - AADAuthorityConstants.COMMON, - AADAuthorityConstants.CONSUMERS, - AADAuthorityConstants.ORGANIZATIONS, -]); -/** - * Extract tenantId from authority - */ -function getTenantFromAuthorityString(authority) { - const authorityUrl = new UrlString(authority); - const authorityUrlComponents = authorityUrl.getUrlComponents(); - /** - * For credential matching purposes, tenantId is the last path segment of the authority URL: - * AAD Authority - domain/tenantId -> Credentials are cached with realm = tenantId - * B2C Authority - domain/{tenantId}?/.../policy -> Credentials are cached with realm = policy - * tenantId is downcased because B2C policies can have mixed case but tfp claim is downcased - * - * Note that we may not have any path segments in certain OIDC scenarios. - */ - const tenantId = authorityUrlComponents.PathSegments.slice(-1)[0]?.toLowerCase(); - switch (tenantId) { - case AADAuthorityConstants.COMMON: - case AADAuthorityConstants.ORGANIZATIONS: - case AADAuthorityConstants.CONSUMERS: - return undefined; - default: - return tenantId; - } -} -function formatAuthorityUri(authorityUri) { - return authorityUri.endsWith(Constants.FORWARD_SLASH) - ? authorityUri - : `${authorityUri}${Constants.FORWARD_SLASH}`; -} -function buildStaticAuthorityOptions(authOptions) { - const rawCloudDiscoveryMetadata = authOptions.cloudDiscoveryMetadata; - let cloudDiscoveryMetadata = undefined; - if (rawCloudDiscoveryMetadata) { - try { - cloudDiscoveryMetadata = JSON.parse(rawCloudDiscoveryMetadata); - } - catch (e) { - throw createClientConfigurationError(invalidCloudDiscoveryMetadata); - } - } - return { - canonicalAuthority: authOptions.authority - ? formatAuthorityUri(authOptions.authority) - : undefined, - knownAuthorities: authOptions.knownAuthorities, - cloudDiscoveryMetadata: cloudDiscoveryMetadata, - }; -} - -export { Authority, buildStaticAuthorityOptions, formatAuthorityUri, getTenantFromAuthorityString }; -//# sourceMappingURL=Authority.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityFactory.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityFactory.mjs deleted file mode 100644 index 53341f26..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityFactory.mjs +++ /dev/null @@ -1,39 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { Authority, formatAuthorityUri } from './Authority.mjs'; -import { createClientAuthError } from '../error/ClientAuthError.mjs'; -import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs'; -import { invokeAsync } from '../utils/FunctionWrappers.mjs'; -import { endpointResolutionError } from '../error/ClientAuthErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Create an authority object of the correct type based on the url - * Performs basic authority validation - checks to see if the authority is of a valid type (i.e. aad, b2c, adfs) - * - * Also performs endpoint discovery. - * - * @param authorityUri - * @param networkClient - * @param protocolMode - * @internal - */ -async function createDiscoveredInstance(authorityUri, networkClient, cacheManager, authorityOptions, logger, correlationId, performanceClient) { - performanceClient?.addQueueMeasurement(PerformanceEvents.AuthorityFactoryCreateDiscoveredInstance, correlationId); - const authorityUriFinal = Authority.transformCIAMAuthority(formatAuthorityUri(authorityUri)); - // Initialize authority and perform discovery endpoint check. - const acquireTokenAuthority = new Authority(authorityUriFinal, networkClient, cacheManager, authorityOptions, logger, correlationId, performanceClient); - try { - await invokeAsync(acquireTokenAuthority.resolveEndpointsAsync.bind(acquireTokenAuthority), PerformanceEvents.AuthorityResolveEndpointsAsync, logger, performanceClient, correlationId)(); - return acquireTokenAuthority; - } - catch (e) { - throw createClientAuthError(endpointResolutionError); - } -} - -export { createDiscoveredInstance }; -//# sourceMappingURL=AuthorityFactory.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityMetadata.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityMetadata.mjs deleted file mode 100644 index 61beae40..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityMetadata.mjs +++ /dev/null @@ -1,144 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { UrlString } from '../url/UrlString.mjs'; -import { AuthorityMetadataSource } from '../utils/Constants.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const rawMetdataJSON = { - endpointMetadata: { - "login.microsoftonline.com": { - token_endpoint: "https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/token", - jwks_uri: "https://login.microsoftonline.com/{tenantid}/discovery/v2.0/keys", - issuer: "https://login.microsoftonline.com/{tenantid}/v2.0", - authorization_endpoint: "https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/authorize", - end_session_endpoint: "https://login.microsoftonline.com/{tenantid}/oauth2/v2.0/logout", - }, - "login.chinacloudapi.cn": { - token_endpoint: "https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/token", - jwks_uri: "https://login.chinacloudapi.cn/{tenantid}/discovery/v2.0/keys", - issuer: "https://login.partner.microsoftonline.cn/{tenantid}/v2.0", - authorization_endpoint: "https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/authorize", - end_session_endpoint: "https://login.chinacloudapi.cn/{tenantid}/oauth2/v2.0/logout", - }, - "login.microsoftonline.us": { - token_endpoint: "https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/token", - jwks_uri: "https://login.microsoftonline.us/{tenantid}/discovery/v2.0/keys", - issuer: "https://login.microsoftonline.us/{tenantid}/v2.0", - authorization_endpoint: "https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/authorize", - end_session_endpoint: "https://login.microsoftonline.us/{tenantid}/oauth2/v2.0/logout", - }, - }, - instanceDiscoveryMetadata: { - metadata: [ - { - preferred_network: "login.microsoftonline.com", - preferred_cache: "login.windows.net", - aliases: [ - "login.microsoftonline.com", - "login.windows.net", - "login.microsoft.com", - "sts.windows.net", - ], - }, - { - preferred_network: "login.partner.microsoftonline.cn", - preferred_cache: "login.partner.microsoftonline.cn", - aliases: [ - "login.partner.microsoftonline.cn", - "login.chinacloudapi.cn", - ], - }, - { - preferred_network: "login.microsoftonline.de", - preferred_cache: "login.microsoftonline.de", - aliases: ["login.microsoftonline.de"], - }, - { - preferred_network: "login.microsoftonline.us", - preferred_cache: "login.microsoftonline.us", - aliases: [ - "login.microsoftonline.us", - "login.usgovcloudapi.net", - ], - }, - { - preferred_network: "login-us.microsoftonline.com", - preferred_cache: "login-us.microsoftonline.com", - aliases: ["login-us.microsoftonline.com"], - }, - ], - }, -}; -const EndpointMetadata = rawMetdataJSON.endpointMetadata; -const InstanceDiscoveryMetadata = rawMetdataJSON.instanceDiscoveryMetadata; -const InstanceDiscoveryMetadataAliases = new Set(); -InstanceDiscoveryMetadata.metadata.forEach((metadataEntry) => { - metadataEntry.aliases.forEach((alias) => { - InstanceDiscoveryMetadataAliases.add(alias); - }); -}); -/** - * Attempts to get an aliases array from the static authority metadata sources based on the canonical authority host - * @param staticAuthorityOptions - * @param logger - * @returns - */ -function getAliasesFromStaticSources(staticAuthorityOptions, logger) { - let staticAliases; - const canonicalAuthority = staticAuthorityOptions.canonicalAuthority; - if (canonicalAuthority) { - const authorityHost = new UrlString(canonicalAuthority).getUrlComponents().HostNameAndPort; - staticAliases = - getAliasesFromMetadata(authorityHost, staticAuthorityOptions.cloudDiscoveryMetadata?.metadata, AuthorityMetadataSource.CONFIG, logger) || - getAliasesFromMetadata(authorityHost, InstanceDiscoveryMetadata.metadata, AuthorityMetadataSource.HARDCODED_VALUES, logger) || - staticAuthorityOptions.knownAuthorities; - } - return staticAliases || []; -} -/** - * Returns aliases for from the raw cloud discovery metadata passed in - * @param authorityHost - * @param rawCloudDiscoveryMetadata - * @returns - */ -function getAliasesFromMetadata(authorityHost, cloudDiscoveryMetadata, source, logger) { - logger?.trace(`getAliasesFromMetadata called with source: ${source}`); - if (authorityHost && cloudDiscoveryMetadata) { - const metadata = getCloudDiscoveryMetadataFromNetworkResponse(cloudDiscoveryMetadata, authorityHost); - if (metadata) { - logger?.trace(`getAliasesFromMetadata: found cloud discovery metadata in ${source}, returning aliases`); - return metadata.aliases; - } - else { - logger?.trace(`getAliasesFromMetadata: did not find cloud discovery metadata in ${source}`); - } - } - return null; -} -/** - * Get cloud discovery metadata for common authorities - */ -function getCloudDiscoveryMetadataFromHardcodedValues(authorityHost) { - const metadata = getCloudDiscoveryMetadataFromNetworkResponse(InstanceDiscoveryMetadata.metadata, authorityHost); - return metadata; -} -/** - * Searches instance discovery network response for the entry that contains the host in the aliases list - * @param response - * @param authority - */ -function getCloudDiscoveryMetadataFromNetworkResponse(response, authorityHost) { - for (let i = 0; i < response.length; i++) { - const metadata = response[i]; - if (metadata.aliases.includes(authorityHost)) { - return metadata; - } - } - return null; -} - -export { EndpointMetadata, InstanceDiscoveryMetadata, InstanceDiscoveryMetadataAliases, getAliasesFromMetadata, getAliasesFromStaticSources, getCloudDiscoveryMetadataFromHardcodedValues, getCloudDiscoveryMetadataFromNetworkResponse, rawMetdataJSON }; -//# sourceMappingURL=AuthorityMetadata.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityOptions.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityOptions.mjs deleted file mode 100644 index f78d2198..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityOptions.mjs +++ /dev/null @@ -1,23 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const AzureCloudInstance = { - // AzureCloudInstance is not specified. - None: "none", - // Microsoft Azure public cloud - AzurePublic: "https://login.microsoftonline.com", - // Microsoft PPE - AzurePpe: "https://login.windows-ppe.net", - // Microsoft Chinese national/regional cloud - AzureChina: "https://login.chinacloudapi.cn", - // Microsoft German national/regional cloud ("Black Forest") - AzureGermany: "https://login.microsoftonline.de", - // US Government cloud - AzureUsGovernment: "https://login.microsoftonline.us", -}; - -export { AzureCloudInstance }; -//# sourceMappingURL=AuthorityOptions.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityType.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityType.mjs deleted file mode 100644 index a29e4839..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/authority/AuthorityType.mjs +++ /dev/null @@ -1,18 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Authority types supported by MSAL. - */ -const AuthorityType = { - Default: 0, - Adfs: 1, - Dsts: 2, - Ciam: 3, -}; - -export { AuthorityType }; -//# sourceMappingURL=AuthorityType.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryErrorResponse.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryErrorResponse.mjs deleted file mode 100644 index 71709801..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryErrorResponse.mjs +++ /dev/null @@ -1,13 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -function isCloudInstanceDiscoveryErrorResponse(response) { - return (response.hasOwnProperty("error") && - response.hasOwnProperty("error_description")); -} - -export { isCloudInstanceDiscoveryErrorResponse }; -//# sourceMappingURL=CloudInstanceDiscoveryErrorResponse.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryResponse.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryResponse.mjs deleted file mode 100644 index 6608cb34..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/authority/CloudInstanceDiscoveryResponse.mjs +++ /dev/null @@ -1,13 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -function isCloudInstanceDiscoveryResponse(response) { - return (response.hasOwnProperty("tenant_discovery_endpoint") && - response.hasOwnProperty("metadata")); -} - -export { isCloudInstanceDiscoveryResponse }; -//# sourceMappingURL=CloudInstanceDiscoveryResponse.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/authority/OpenIdConfigResponse.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/authority/OpenIdConfigResponse.mjs deleted file mode 100644 index 99b0ef61..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/authority/OpenIdConfigResponse.mjs +++ /dev/null @@ -1,15 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -function isOpenIdConfigResponse(response) { - return (response.hasOwnProperty("authorization_endpoint") && - response.hasOwnProperty("token_endpoint") && - response.hasOwnProperty("issuer") && - response.hasOwnProperty("jwks_uri")); -} - -export { isOpenIdConfigResponse }; -//# sourceMappingURL=OpenIdConfigResponse.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/authority/ProtocolMode.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/authority/ProtocolMode.mjs deleted file mode 100644 index cd2d7d2b..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/authority/ProtocolMode.mjs +++ /dev/null @@ -1,27 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Protocol modes supported by MSAL. - */ -const ProtocolMode = { - /** - * Auth Code + PKCE with Entra ID (formerly AAD) specific optimizations and features - */ - AAD: "AAD", - /** - * Auth Code + PKCE without Entra ID specific optimizations and features. For use only with non-Microsoft owned authorities. - * Support is limited for this mode. - */ - OIDC: "OIDC", - /** - * Encrypted Authorize Response (EAR) with Entra ID specific optimizations and features - */ - EAR: "EAR", -}; - -export { ProtocolMode }; -//# sourceMappingURL=ProtocolMode.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/authority/RegionDiscovery.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/authority/RegionDiscovery.mjs deleted file mode 100644 index c144b170..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/authority/RegionDiscovery.mjs +++ /dev/null @@ -1,112 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { Constants, HttpStatus, RegionDiscoverySources } from '../utils/Constants.mjs'; -import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs'; -import { invokeAsync } from '../utils/FunctionWrappers.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -class RegionDiscovery { - constructor(networkInterface, logger, performanceClient, correlationId) { - this.networkInterface = networkInterface; - this.logger = logger; - this.performanceClient = performanceClient; - this.correlationId = correlationId; - } - /** - * Detect the region from the application's environment. - * - * @returns Promise - */ - async detectRegion(environmentRegion, regionDiscoveryMetadata) { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.RegionDiscoveryDetectRegion, this.correlationId); - // Initialize auto detected region with the region from the envrionment - let autodetectedRegionName = environmentRegion; - // Check if a region was detected from the environment, if not, attempt to get the region from IMDS - if (!autodetectedRegionName) { - const options = RegionDiscovery.IMDS_OPTIONS; - try { - const localIMDSVersionResponse = await invokeAsync(this.getRegionFromIMDS.bind(this), PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, this.logger, this.performanceClient, this.correlationId)(Constants.IMDS_VERSION, options); - if (localIMDSVersionResponse.status === HttpStatus.SUCCESS) { - autodetectedRegionName = localIMDSVersionResponse.body; - regionDiscoveryMetadata.region_source = - RegionDiscoverySources.IMDS; - } - // If the response using the local IMDS version failed, try to fetch the current version of IMDS and retry. - if (localIMDSVersionResponse.status === HttpStatus.BAD_REQUEST) { - const currentIMDSVersion = await invokeAsync(this.getCurrentVersion.bind(this), PerformanceEvents.RegionDiscoveryGetCurrentVersion, this.logger, this.performanceClient, this.correlationId)(options); - if (!currentIMDSVersion) { - regionDiscoveryMetadata.region_source = - RegionDiscoverySources.FAILED_AUTO_DETECTION; - return null; - } - const currentIMDSVersionResponse = await invokeAsync(this.getRegionFromIMDS.bind(this), PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, this.logger, this.performanceClient, this.correlationId)(currentIMDSVersion, options); - if (currentIMDSVersionResponse.status === HttpStatus.SUCCESS) { - autodetectedRegionName = - currentIMDSVersionResponse.body; - regionDiscoveryMetadata.region_source = - RegionDiscoverySources.IMDS; - } - } - } - catch (e) { - regionDiscoveryMetadata.region_source = - RegionDiscoverySources.FAILED_AUTO_DETECTION; - return null; - } - } - else { - regionDiscoveryMetadata.region_source = - RegionDiscoverySources.ENVIRONMENT_VARIABLE; - } - // If no region was auto detected from the environment or from the IMDS endpoint, mark the attempt as a FAILED_AUTO_DETECTION - if (!autodetectedRegionName) { - regionDiscoveryMetadata.region_source = - RegionDiscoverySources.FAILED_AUTO_DETECTION; - } - return autodetectedRegionName || null; - } - /** - * Make the call to the IMDS endpoint - * - * @param imdsEndpointUrl - * @returns Promise> - */ - async getRegionFromIMDS(version, options) { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, this.correlationId); - return this.networkInterface.sendGetRequestAsync(`${Constants.IMDS_ENDPOINT}?api-version=${version}&format=text`, options, Constants.IMDS_TIMEOUT); - } - /** - * Get the most recent version of the IMDS endpoint available - * - * @returns Promise - */ - async getCurrentVersion(options) { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.RegionDiscoveryGetCurrentVersion, this.correlationId); - try { - const response = await this.networkInterface.sendGetRequestAsync(`${Constants.IMDS_ENDPOINT}?format=json`, options); - // When IMDS endpoint is called without the api version query param, bad request response comes back with latest version. - if (response.status === HttpStatus.BAD_REQUEST && - response.body && - response.body["newest-versions"] && - response.body["newest-versions"].length > 0) { - return response.body["newest-versions"][0]; - } - return null; - } - catch (e) { - return null; - } - } -} -// Options for the IMDS endpoint request -RegionDiscovery.IMDS_OPTIONS = { - headers: { - Metadata: "true", - }, -}; - -export { RegionDiscovery }; -//# sourceMappingURL=RegionDiscovery.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/cache/CacheManager.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/cache/CacheManager.mjs deleted file mode 100644 index 7d4a67d4..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/cache/CacheManager.mjs +++ /dev/null @@ -1,1124 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { CredentialType, AuthenticationScheme, THE_FAMILY_ID, APP_METADATA, AUTHORITY_METADATA_CONSTANTS } from '../utils/Constants.mjs'; -import { ScopeSet } from '../request/ScopeSet.mjs'; -import { AccountEntity } from './entities/AccountEntity.mjs'; -import { createClientAuthError } from '../error/ClientAuthError.mjs'; -import { updateAccountTenantProfileData } from '../account/AccountInfo.mjs'; -import { extractTokenClaims } from '../account/AuthToken.mjs'; -import { name, version } from '../packageMetadata.mjs'; -import { getAliasesFromStaticSources } from '../authority/AuthorityMetadata.mjs'; -import { createCacheError } from '../error/CacheError.mjs'; -import { AuthError } from '../error/AuthError.mjs'; -import { invalidCacheRecord, multipleMatchingAppMetadata, methodNotImplemented } from '../error/ClientAuthErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Interface class which implement cache storage functions used by MSAL to perform validity checks, and store tokens. - * @internal - */ -class CacheManager { - constructor(clientId, cryptoImpl, logger, performanceClient, staticAuthorityOptions) { - this.clientId = clientId; - this.cryptoImpl = cryptoImpl; - this.commonLogger = logger.clone(name, version); - this.staticAuthorityOptions = staticAuthorityOptions; - this.performanceClient = performanceClient; - } - /** - * Returns all the accounts in the cache that match the optional filter. If no filter is provided, all accounts are returned. - * @param accountFilter - (Optional) filter to narrow down the accounts returned - * @returns Array of AccountInfo objects in cache - */ - getAllAccounts(accountFilter, correlationId) { - return this.buildTenantProfiles(this.getAccountsFilteredBy(accountFilter, correlationId), correlationId, accountFilter); - } - /** - * Gets first tenanted AccountInfo object found based on provided filters - */ - getAccountInfoFilteredBy(accountFilter, correlationId) { - if (Object.keys(accountFilter).length === 0 || - Object.values(accountFilter).every((value) => !value)) { - this.commonLogger.warning("getAccountInfoFilteredBy: Account filter is empty or invalid, returning null"); - return null; - } - const allAccounts = this.getAllAccounts(accountFilter, correlationId); - if (allAccounts.length > 1) { - // If one or more accounts are found, prioritize accounts that have an ID token - const sortedAccounts = allAccounts.sort((account) => { - return account.idTokenClaims ? -1 : 1; - }); - return sortedAccounts[0]; - } - else if (allAccounts.length === 1) { - // If only one account is found, return it regardless of whether a matching ID token was found - return allAccounts[0]; - } - else { - return null; - } - } - /** - * Returns a single matching - * @param accountFilter - * @returns - */ - getBaseAccountInfo(accountFilter, correlationId) { - const accountEntities = this.getAccountsFilteredBy(accountFilter, correlationId); - if (accountEntities.length > 0) { - return AccountEntity.getAccountInfo(accountEntities[0]); - } - else { - return null; - } - } - /** - * Matches filtered account entities with cached ID tokens that match the tenant profile-specific account filters - * and builds the account info objects from the matching ID token's claims - * @param cachedAccounts - * @param accountFilter - * @returns Array of AccountInfo objects that match account and tenant profile filters - */ - buildTenantProfiles(cachedAccounts, correlationId, accountFilter) { - return cachedAccounts.flatMap((accountEntity) => { - return this.getTenantProfilesFromAccountEntity(accountEntity, correlationId, accountFilter?.tenantId, accountFilter); - }); - } - getTenantedAccountInfoByFilter(accountInfo, tokenKeys, tenantProfile, correlationId, tenantProfileFilter) { - let tenantedAccountInfo = null; - let idTokenClaims; - if (tenantProfileFilter) { - if (!this.tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter)) { - return null; - } - } - const idToken = this.getIdToken(accountInfo, correlationId, tokenKeys, tenantProfile.tenantId); - if (idToken) { - idTokenClaims = extractTokenClaims(idToken.secret, this.cryptoImpl.base64Decode); - if (!this.idTokenClaimsMatchTenantProfileFilter(idTokenClaims, tenantProfileFilter)) { - // ID token sourced claims don't match so this tenant profile is not a match - return null; - } - } - // Expand tenant profile into account info based on matching tenant profile and if available matching ID token claims - tenantedAccountInfo = updateAccountTenantProfileData(accountInfo, tenantProfile, idTokenClaims, idToken?.secret); - return tenantedAccountInfo; - } - getTenantProfilesFromAccountEntity(accountEntity, correlationId, targetTenantId, tenantProfileFilter) { - const accountInfo = AccountEntity.getAccountInfo(accountEntity); - let searchTenantProfiles = accountInfo.tenantProfiles || new Map(); - const tokenKeys = this.getTokenKeys(); - // If a tenant ID was provided, only return the tenant profile for that tenant ID if it exists - if (targetTenantId) { - const tenantProfile = searchTenantProfiles.get(targetTenantId); - if (tenantProfile) { - // Reduce search field to just this tenant profile - searchTenantProfiles = new Map([ - [targetTenantId, tenantProfile], - ]); - } - else { - // No tenant profile for search tenant ID, return empty array - return []; - } - } - const matchingTenantProfiles = []; - searchTenantProfiles.forEach((tenantProfile) => { - const tenantedAccountInfo = this.getTenantedAccountInfoByFilter(accountInfo, tokenKeys, tenantProfile, correlationId, tenantProfileFilter); - if (tenantedAccountInfo) { - matchingTenantProfiles.push(tenantedAccountInfo); - } - }); - return matchingTenantProfiles; - } - tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter) { - if (!!tenantProfileFilter.localAccountId && - !this.matchLocalAccountIdFromTenantProfile(tenantProfile, tenantProfileFilter.localAccountId)) { - return false; - } - if (!!tenantProfileFilter.name && - !(tenantProfile.name === tenantProfileFilter.name)) { - return false; - } - if (tenantProfileFilter.isHomeTenant !== undefined && - !(tenantProfile.isHomeTenant === tenantProfileFilter.isHomeTenant)) { - return false; - } - return true; - } - idTokenClaimsMatchTenantProfileFilter(idTokenClaims, tenantProfileFilter) { - // Tenant Profile filtering - if (tenantProfileFilter) { - if (!!tenantProfileFilter.localAccountId && - !this.matchLocalAccountIdFromTokenClaims(idTokenClaims, tenantProfileFilter.localAccountId)) { - return false; - } - if (!!tenantProfileFilter.loginHint && - !this.matchLoginHintFromTokenClaims(idTokenClaims, tenantProfileFilter.loginHint)) { - return false; - } - if (!!tenantProfileFilter.username && - !this.matchUsername(idTokenClaims.preferred_username, tenantProfileFilter.username)) { - return false; - } - if (!!tenantProfileFilter.name && - !this.matchName(idTokenClaims, tenantProfileFilter.name)) { - return false; - } - if (!!tenantProfileFilter.sid && - !this.matchSid(idTokenClaims, tenantProfileFilter.sid)) { - return false; - } - } - return true; - } - /** - * saves a cache record - * @param cacheRecord {CacheRecord} - * @param correlationId {?string} correlation id - * @param kmsi - Keep Me Signed In - * @param storeInCache {?StoreInCache} - */ - async saveCacheRecord(cacheRecord, correlationId, kmsi, storeInCache) { - if (!cacheRecord) { - throw createClientAuthError(invalidCacheRecord); - } - try { - if (!!cacheRecord.account) { - await this.setAccount(cacheRecord.account, correlationId, kmsi); - } - if (!!cacheRecord.idToken && storeInCache?.idToken !== false) { - await this.setIdTokenCredential(cacheRecord.idToken, correlationId, kmsi); - } - if (!!cacheRecord.accessToken && - storeInCache?.accessToken !== false) { - await this.saveAccessToken(cacheRecord.accessToken, correlationId, kmsi); - } - if (!!cacheRecord.refreshToken && - storeInCache?.refreshToken !== false) { - await this.setRefreshTokenCredential(cacheRecord.refreshToken, correlationId, kmsi); - } - if (!!cacheRecord.appMetadata) { - this.setAppMetadata(cacheRecord.appMetadata, correlationId); - } - } - catch (e) { - this.commonLogger?.error(`CacheManager.saveCacheRecord: failed`); - if (e instanceof AuthError) { - throw e; - } - else { - throw createCacheError(e); - } - } - } - /** - * saves access token credential - * @param credential - */ - async saveAccessToken(credential, correlationId, kmsi) { - const accessTokenFilter = { - clientId: credential.clientId, - credentialType: credential.credentialType, - environment: credential.environment, - homeAccountId: credential.homeAccountId, - realm: credential.realm, - tokenType: credential.tokenType, - requestedClaimsHash: credential.requestedClaimsHash, - }; - const tokenKeys = this.getTokenKeys(); - const currentScopes = ScopeSet.fromString(credential.target); - tokenKeys.accessToken.forEach((key) => { - if (!this.accessTokenKeyMatchesFilter(key, accessTokenFilter, false)) { - return; - } - const tokenEntity = this.getAccessTokenCredential(key, correlationId); - if (tokenEntity && - this.credentialMatchesFilter(tokenEntity, accessTokenFilter)) { - const tokenScopeSet = ScopeSet.fromString(tokenEntity.target); - if (tokenScopeSet.intersectingScopeSets(currentScopes)) { - this.removeAccessToken(key, correlationId); - } - } - }); - await this.setAccessTokenCredential(credential, correlationId, kmsi); - } - /** - * Retrieve account entities matching all provided tenant-agnostic filters; if no filter is set, get all account entities in the cache - * Not checking for casing as keys are all generated in lower case, remember to convert to lower case if object properties are compared - * @param accountFilter - An object containing Account properties to filter by - */ - getAccountsFilteredBy(accountFilter, correlationId) { - const allAccountKeys = this.getAccountKeys(); - const matchingAccounts = []; - allAccountKeys.forEach((cacheKey) => { - const entity = this.getAccount(cacheKey, correlationId); - // Match base account fields - if (!entity) { - return; - } - if (!!accountFilter.homeAccountId && - !this.matchHomeAccountId(entity, accountFilter.homeAccountId)) { - return; - } - if (!!accountFilter.username && - !this.matchUsername(entity.username, accountFilter.username)) { - return; - } - if (!!accountFilter.environment && - !this.matchEnvironment(entity, accountFilter.environment)) { - return; - } - if (!!accountFilter.realm && - !this.matchRealm(entity, accountFilter.realm)) { - return; - } - if (!!accountFilter.nativeAccountId && - !this.matchNativeAccountId(entity, accountFilter.nativeAccountId)) { - return; - } - if (!!accountFilter.authorityType && - !this.matchAuthorityType(entity, accountFilter.authorityType)) { - return; - } - // If at least one tenant profile matches the tenant profile filter, add the account to the list of matching accounts - const tenantProfileFilter = { - localAccountId: accountFilter?.localAccountId, - name: accountFilter?.name, - }; - const matchingTenantProfiles = entity.tenantProfiles?.filter((tenantProfile) => { - return this.tenantProfileMatchesFilter(tenantProfile, tenantProfileFilter); - }); - if (matchingTenantProfiles && matchingTenantProfiles.length === 0) { - // No tenant profile for this account matches filter, don't add to list of matching accounts - return; - } - matchingAccounts.push(entity); - }); - return matchingAccounts; - } - /** - * Returns whether or not the given credential entity matches the filter - * @param entity - * @param filter - * @returns - */ - credentialMatchesFilter(entity, filter) { - if (!!filter.clientId && !this.matchClientId(entity, filter.clientId)) { - return false; - } - if (!!filter.userAssertionHash && - !this.matchUserAssertionHash(entity, filter.userAssertionHash)) { - return false; - } - /* - * homeAccountId can be undefined, and we want to filter out cached items that have a homeAccountId of "" - * because we don't want a client_credential request to return a cached token that has a homeAccountId - */ - if (typeof filter.homeAccountId === "string" && - !this.matchHomeAccountId(entity, filter.homeAccountId)) { - return false; - } - if (!!filter.environment && - !this.matchEnvironment(entity, filter.environment)) { - return false; - } - if (!!filter.realm && !this.matchRealm(entity, filter.realm)) { - return false; - } - if (!!filter.credentialType && - !this.matchCredentialType(entity, filter.credentialType)) { - return false; - } - if (!!filter.familyId && !this.matchFamilyId(entity, filter.familyId)) { - return false; - } - /* - * idTokens do not have "target", target specific refreshTokens do exist for some types of authentication - * Resource specific refresh tokens case will be added when the support is deemed necessary - */ - if (!!filter.target && !this.matchTarget(entity, filter.target)) { - return false; - } - // If request OR cached entity has requested Claims Hash, check if they match - if (filter.requestedClaimsHash || entity.requestedClaimsHash) { - // Don't match if either is undefined or they are different - if (entity.requestedClaimsHash !== filter.requestedClaimsHash) { - return false; - } - } - // Access Token with Auth Scheme specific matching - if (entity.credentialType === - CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME) { - if (!!filter.tokenType && - !this.matchTokenType(entity, filter.tokenType)) { - return false; - } - // KeyId (sshKid) in request must match cached SSH certificate keyId because SSH cert is bound to a specific key - if (filter.tokenType === AuthenticationScheme.SSH) { - if (filter.keyId && !this.matchKeyId(entity, filter.keyId)) { - return false; - } - } - } - return true; - } - /** - * retrieve appMetadata matching all provided filters; if no filter is set, get all appMetadata - * @param filter - */ - getAppMetadataFilteredBy(filter) { - const allCacheKeys = this.getKeys(); - const matchingAppMetadata = {}; - allCacheKeys.forEach((cacheKey) => { - // don't parse any non-appMetadata type cache entities - if (!this.isAppMetadata(cacheKey)) { - return; - } - // Attempt retrieval - const entity = this.getAppMetadata(cacheKey); - if (!entity) { - return; - } - if (!!filter.environment && - !this.matchEnvironment(entity, filter.environment)) { - return; - } - if (!!filter.clientId && - !this.matchClientId(entity, filter.clientId)) { - return; - } - matchingAppMetadata[cacheKey] = entity; - }); - return matchingAppMetadata; - } - /** - * retrieve authorityMetadata that contains a matching alias - * @param filter - */ - getAuthorityMetadataByAlias(host) { - const allCacheKeys = this.getAuthorityMetadataKeys(); - let matchedEntity = null; - allCacheKeys.forEach((cacheKey) => { - // don't parse any non-authorityMetadata type cache entities - if (!this.isAuthorityMetadata(cacheKey) || - cacheKey.indexOf(this.clientId) === -1) { - return; - } - // Attempt retrieval - const entity = this.getAuthorityMetadata(cacheKey); - if (!entity) { - return; - } - if (entity.aliases.indexOf(host) === -1) { - return; - } - matchedEntity = entity; - }); - return matchedEntity; - } - /** - * Removes all accounts and related tokens from cache. - */ - removeAllAccounts(correlationId) { - const accounts = this.getAllAccounts({}, correlationId); - accounts.forEach((account) => { - this.removeAccount(account, correlationId); - }); - } - /** - * Removes the account and related tokens for a given account key - * @param account - */ - removeAccount(account, correlationId) { - this.removeAccountContext(account, correlationId); - const accountKeys = this.getAccountKeys(); - const keyFilter = (key) => { - return (key.includes(account.homeAccountId) && - key.includes(account.environment)); - }; - accountKeys.filter(keyFilter).forEach((key) => { - this.removeItem(key, correlationId); - this.performanceClient.incrementFields({ accountsRemoved: 1 }, correlationId); - }); - } - /** - * Removes credentials associated with the provided account - * @param account - */ - removeAccountContext(account, correlationId) { - const allTokenKeys = this.getTokenKeys(); - const keyFilter = (key) => { - return (key.includes(account.homeAccountId) && - key.includes(account.environment)); - }; - allTokenKeys.idToken.filter(keyFilter).forEach((key) => { - this.removeIdToken(key, correlationId); - }); - allTokenKeys.accessToken.filter(keyFilter).forEach((key) => { - this.removeAccessToken(key, correlationId); - }); - allTokenKeys.refreshToken.filter(keyFilter).forEach((key) => { - this.removeRefreshToken(key, correlationId); - }); - } - /** - * Removes accessToken from the cache - * @param key - * @param correlationId - */ - removeAccessToken(key, correlationId) { - const credential = this.getAccessTokenCredential(key, correlationId); - this.removeItem(key, correlationId); - this.performanceClient.incrementFields({ accessTokensRemoved: 1 }, correlationId); - if (!credential || - credential.credentialType.toLowerCase() !== - CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME.toLowerCase() || - credential.tokenType !== AuthenticationScheme.POP) { - // If the credential is not a PoP token, we can return - return; - } - // Remove Token Binding Key from key store for PoP Tokens Credentials - const kid = credential.keyId; - if (kid) { - void this.cryptoImpl.removeTokenBindingKey(kid).catch(() => { - this.commonLogger.error(`Failed to remove token binding key ${kid}`, correlationId); - this.performanceClient?.incrementFields({ removeTokenBindingKeyFailure: 1 }, correlationId); - }); - } - } - /** - * Removes all app metadata objects from cache. - */ - removeAppMetadata(correlationId) { - const allCacheKeys = this.getKeys(); - allCacheKeys.forEach((cacheKey) => { - if (this.isAppMetadata(cacheKey)) { - this.removeItem(cacheKey, correlationId); - } - }); - return true; - } - /** - * Retrieve IdTokenEntity from cache - * @param account {AccountInfo} - * @param tokenKeys {?TokenKeys} - * @param targetRealm {?string} - * @param performanceClient {?IPerformanceClient} - * @param correlationId {?string} - */ - getIdToken(account, correlationId, tokenKeys, targetRealm, performanceClient) { - this.commonLogger.trace("CacheManager - getIdToken called"); - const idTokenFilter = { - homeAccountId: account.homeAccountId, - environment: account.environment, - credentialType: CredentialType.ID_TOKEN, - clientId: this.clientId, - realm: targetRealm, - }; - const idTokenMap = this.getIdTokensByFilter(idTokenFilter, correlationId, tokenKeys); - const numIdTokens = idTokenMap.size; - if (numIdTokens < 1) { - this.commonLogger.info("CacheManager:getIdToken - No token found"); - return null; - } - else if (numIdTokens > 1) { - let tokensToBeRemoved = idTokenMap; - // Multiple tenant profiles and no tenant specified, pick home account - if (!targetRealm) { - const homeIdTokenMap = new Map(); - idTokenMap.forEach((idToken, key) => { - if (idToken.realm === account.tenantId) { - homeIdTokenMap.set(key, idToken); - } - }); - const numHomeIdTokens = homeIdTokenMap.size; - if (numHomeIdTokens < 1) { - this.commonLogger.info("CacheManager:getIdToken - Multiple ID tokens found for account but none match account entity tenant id, returning first result"); - return idTokenMap.values().next().value; - } - else if (numHomeIdTokens === 1) { - this.commonLogger.info("CacheManager:getIdToken - Multiple ID tokens found for account, defaulting to home tenant profile"); - return homeIdTokenMap.values().next().value; - } - else { - // Multiple ID tokens for home tenant profile, remove all and return null - tokensToBeRemoved = homeIdTokenMap; - } - } - // Multiple tokens for a single tenant profile, remove all and return null - this.commonLogger.info("CacheManager:getIdToken - Multiple matching ID tokens found, clearing them"); - tokensToBeRemoved.forEach((idToken, key) => { - this.removeIdToken(key, correlationId); - }); - if (performanceClient && correlationId) { - performanceClient.addFields({ multiMatchedID: idTokenMap.size }, correlationId); - } - return null; - } - this.commonLogger.info("CacheManager:getIdToken - Returning ID token"); - return idTokenMap.values().next().value; - } - /** - * Gets all idTokens matching the given filter - * @param filter - * @returns - */ - getIdTokensByFilter(filter, correlationId, tokenKeys) { - const idTokenKeys = (tokenKeys && tokenKeys.idToken) || this.getTokenKeys().idToken; - const idTokens = new Map(); - idTokenKeys.forEach((key) => { - if (!this.idTokenKeyMatchesFilter(key, { - clientId: this.clientId, - ...filter, - })) { - return; - } - const idToken = this.getIdTokenCredential(key, correlationId); - if (idToken && this.credentialMatchesFilter(idToken, filter)) { - idTokens.set(key, idToken); - } - }); - return idTokens; - } - /** - * Validate the cache key against filter before retrieving and parsing cache value - * @param key - * @param filter - * @returns - */ - idTokenKeyMatchesFilter(inputKey, filter) { - const key = inputKey.toLowerCase(); - if (filter.clientId && - key.indexOf(filter.clientId.toLowerCase()) === -1) { - return false; - } - if (filter.homeAccountId && - key.indexOf(filter.homeAccountId.toLowerCase()) === -1) { - return false; - } - return true; - } - /** - * Removes idToken from the cache - * @param key - */ - removeIdToken(key, correlationId) { - this.removeItem(key, correlationId); - } - /** - * Removes refresh token from the cache - * @param key - */ - removeRefreshToken(key, correlationId) { - this.removeItem(key, correlationId); - } - /** - * Retrieve AccessTokenEntity from cache - * @param account {AccountInfo} - * @param request {BaseAuthRequest} - * @param correlationId {?string} - * @param tokenKeys {?TokenKeys} - * @param performanceClient {?IPerformanceClient} - */ - getAccessToken(account, request, tokenKeys, targetRealm) { - const correlationId = request.correlationId; - this.commonLogger.trace("CacheManager - getAccessToken called", correlationId); - const scopes = ScopeSet.createSearchScopes(request.scopes); - const authScheme = request.authenticationScheme || AuthenticationScheme.BEARER; - /* - * Distinguish between Bearer and PoP/SSH token cache types - * Cast to lowercase to handle "bearer" from ADFS - */ - const credentialType = authScheme && - authScheme.toLowerCase() !== - AuthenticationScheme.BEARER.toLowerCase() - ? CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME - : CredentialType.ACCESS_TOKEN; - const accessTokenFilter = { - homeAccountId: account.homeAccountId, - environment: account.environment, - credentialType: credentialType, - clientId: this.clientId, - realm: targetRealm || account.tenantId, - target: scopes, - tokenType: authScheme, - keyId: request.sshKid, - requestedClaimsHash: request.requestedClaimsHash, - }; - const accessTokenKeys = (tokenKeys && tokenKeys.accessToken) || - this.getTokenKeys().accessToken; - const accessTokens = []; - accessTokenKeys.forEach((key) => { - // Validate key - if (this.accessTokenKeyMatchesFilter(key, accessTokenFilter, true)) { - const accessToken = this.getAccessTokenCredential(key, correlationId); - // Validate value - if (accessToken && - this.credentialMatchesFilter(accessToken, accessTokenFilter)) { - accessTokens.push(accessToken); - } - } - }); - const numAccessTokens = accessTokens.length; - if (numAccessTokens < 1) { - this.commonLogger.info("CacheManager:getAccessToken - No token found", correlationId); - return null; - } - else if (numAccessTokens > 1) { - this.commonLogger.info("CacheManager:getAccessToken - Multiple access tokens found, clearing them", correlationId); - accessTokens.forEach((accessToken) => { - this.removeAccessToken(this.generateCredentialKey(accessToken), correlationId); - }); - this.performanceClient.addFields({ multiMatchedAT: accessTokens.length }, correlationId); - return null; - } - this.commonLogger.info("CacheManager:getAccessToken - Returning access token", correlationId); - return accessTokens[0]; - } - /** - * Validate the cache key against filter before retrieving and parsing cache value - * @param key - * @param filter - * @param keyMustContainAllScopes - * @returns - */ - accessTokenKeyMatchesFilter(inputKey, filter, keyMustContainAllScopes) { - const key = inputKey.toLowerCase(); - if (filter.clientId && - key.indexOf(filter.clientId.toLowerCase()) === -1) { - return false; - } - if (filter.homeAccountId && - key.indexOf(filter.homeAccountId.toLowerCase()) === -1) { - return false; - } - if (filter.realm && key.indexOf(filter.realm.toLowerCase()) === -1) { - return false; - } - if (filter.requestedClaimsHash && - key.indexOf(filter.requestedClaimsHash.toLowerCase()) === -1) { - return false; - } - if (filter.target) { - const scopes = filter.target.asArray(); - for (let i = 0; i < scopes.length; i++) { - if (keyMustContainAllScopes && - !key.includes(scopes[i].toLowerCase())) { - // When performing a cache lookup a missing scope would be a cache miss - return false; - } - else if (!keyMustContainAllScopes && - key.includes(scopes[i].toLowerCase())) { - // When performing a cache write, any token with a subset of requested scopes should be replaced - return true; - } - } - } - return true; - } - /** - * Gets all access tokens matching the filter - * @param filter - * @returns - */ - getAccessTokensByFilter(filter, correlationId) { - const tokenKeys = this.getTokenKeys(); - const accessTokens = []; - tokenKeys.accessToken.forEach((key) => { - if (!this.accessTokenKeyMatchesFilter(key, filter, true)) { - return; - } - const accessToken = this.getAccessTokenCredential(key, correlationId); - if (accessToken && - this.credentialMatchesFilter(accessToken, filter)) { - accessTokens.push(accessToken); - } - }); - return accessTokens; - } - /** - * Helper to retrieve the appropriate refresh token from cache - * @param account {AccountInfo} - * @param familyRT {boolean} - * @param correlationId {?string} - * @param tokenKeys {?TokenKeys} - * @param performanceClient {?IPerformanceClient} - */ - getRefreshToken(account, familyRT, correlationId, tokenKeys, performanceClient) { - this.commonLogger.trace("CacheManager - getRefreshToken called"); - const id = familyRT ? THE_FAMILY_ID : undefined; - const refreshTokenFilter = { - homeAccountId: account.homeAccountId, - environment: account.environment, - credentialType: CredentialType.REFRESH_TOKEN, - clientId: this.clientId, - familyId: id, - }; - const refreshTokenKeys = (tokenKeys && tokenKeys.refreshToken) || - this.getTokenKeys().refreshToken; - const refreshTokens = []; - refreshTokenKeys.forEach((key) => { - // Validate key - if (this.refreshTokenKeyMatchesFilter(key, refreshTokenFilter)) { - const refreshToken = this.getRefreshTokenCredential(key, correlationId); - // Validate value - if (refreshToken && - this.credentialMatchesFilter(refreshToken, refreshTokenFilter)) { - refreshTokens.push(refreshToken); - } - } - }); - const numRefreshTokens = refreshTokens.length; - if (numRefreshTokens < 1) { - this.commonLogger.info("CacheManager:getRefreshToken - No refresh token found."); - return null; - } - // address the else case after remove functions address environment aliases - if (numRefreshTokens > 1 && performanceClient && correlationId) { - performanceClient.addFields({ multiMatchedRT: numRefreshTokens }, correlationId); - } - this.commonLogger.info("CacheManager:getRefreshToken - returning refresh token"); - return refreshTokens[0]; - } - /** - * Validate the cache key against filter before retrieving and parsing cache value - * @param key - * @param filter - */ - refreshTokenKeyMatchesFilter(inputKey, filter) { - const key = inputKey.toLowerCase(); - if (filter.familyId && - key.indexOf(filter.familyId.toLowerCase()) === -1) { - return false; - } - // If familyId is used, clientId is not in the key - if (!filter.familyId && - filter.clientId && - key.indexOf(filter.clientId.toLowerCase()) === -1) { - return false; - } - if (filter.homeAccountId && - key.indexOf(filter.homeAccountId.toLowerCase()) === -1) { - return false; - } - return true; - } - /** - * Retrieve AppMetadataEntity from cache - */ - readAppMetadataFromCache(environment) { - const appMetadataFilter = { - environment, - clientId: this.clientId, - }; - const appMetadata = this.getAppMetadataFilteredBy(appMetadataFilter); - const appMetadataEntries = Object.keys(appMetadata).map((key) => appMetadata[key]); - const numAppMetadata = appMetadataEntries.length; - if (numAppMetadata < 1) { - return null; - } - else if (numAppMetadata > 1) { - throw createClientAuthError(multipleMatchingAppMetadata); - } - return appMetadataEntries[0]; - } - /** - * Return the family_id value associated with FOCI - * @param environment - * @param clientId - */ - isAppMetadataFOCI(environment) { - const appMetadata = this.readAppMetadataFromCache(environment); - return !!(appMetadata && appMetadata.familyId === THE_FAMILY_ID); - } - /** - * helper to match account ids - * @param value - * @param homeAccountId - */ - matchHomeAccountId(entity, homeAccountId) { - return !!(typeof entity.homeAccountId === "string" && - homeAccountId === entity.homeAccountId); - } - /** - * helper to match account ids - * @param entity - * @param localAccountId - * @returns - */ - matchLocalAccountIdFromTokenClaims(tokenClaims, localAccountId) { - const idTokenLocalAccountId = tokenClaims.oid || tokenClaims.sub; - return localAccountId === idTokenLocalAccountId; - } - matchLocalAccountIdFromTenantProfile(tenantProfile, localAccountId) { - return tenantProfile.localAccountId === localAccountId; - } - /** - * helper to match names - * @param entity - * @param name - * @returns true if the downcased name properties are present and match in the filter and the entity - */ - matchName(claims, name) { - return !!(name.toLowerCase() === claims.name?.toLowerCase()); - } - /** - * helper to match usernames - * @param entity - * @param username - * @returns - */ - matchUsername(cachedUsername, filterUsername) { - return !!(cachedUsername && - typeof cachedUsername === "string" && - filterUsername?.toLowerCase() === cachedUsername.toLowerCase()); - } - /** - * helper to match assertion - * @param value - * @param oboAssertion - */ - matchUserAssertionHash(entity, userAssertionHash) { - return !!(entity.userAssertionHash && - userAssertionHash === entity.userAssertionHash); - } - /** - * helper to match environment - * @param value - * @param environment - */ - matchEnvironment(entity, environment) { - // Check static authority options first for cases where authority metadata has not been resolved and cached yet - if (this.staticAuthorityOptions) { - const staticAliases = getAliasesFromStaticSources(this.staticAuthorityOptions, this.commonLogger); - if (staticAliases.includes(environment) && - staticAliases.includes(entity.environment)) { - return true; - } - } - // Query metadata cache if no static authority configuration has aliases that match enviroment - const cloudMetadata = this.getAuthorityMetadataByAlias(environment); - if (cloudMetadata && - cloudMetadata.aliases.indexOf(entity.environment) > -1) { - return true; - } - return false; - } - /** - * helper to match credential type - * @param entity - * @param credentialType - */ - matchCredentialType(entity, credentialType) { - return (entity.credentialType && - credentialType.toLowerCase() === entity.credentialType.toLowerCase()); - } - /** - * helper to match client ids - * @param entity - * @param clientId - */ - matchClientId(entity, clientId) { - return !!(entity.clientId && clientId === entity.clientId); - } - /** - * helper to match family ids - * @param entity - * @param familyId - */ - matchFamilyId(entity, familyId) { - return !!(entity.familyId && familyId === entity.familyId); - } - /** - * helper to match realm - * @param entity - * @param realm - */ - matchRealm(entity, realm) { - return !!(entity.realm?.toLowerCase() === realm.toLowerCase()); - } - /** - * helper to match nativeAccountId - * @param entity - * @param nativeAccountId - * @returns boolean indicating the match result - */ - matchNativeAccountId(entity, nativeAccountId) { - return !!(entity.nativeAccountId && nativeAccountId === entity.nativeAccountId); - } - /** - * helper to match loginHint which can be either: - * 1. login_hint ID token claim - * 2. username in cached account object - * 3. upn in ID token claims - * @param entity - * @param loginHint - * @returns - */ - matchLoginHintFromTokenClaims(tokenClaims, loginHint) { - if (tokenClaims.login_hint === loginHint) { - return true; - } - if (tokenClaims.preferred_username === loginHint) { - return true; - } - if (tokenClaims.upn === loginHint) { - return true; - } - return false; - } - /** - * Helper to match sid - * @param entity - * @param sid - * @returns true if the sid claim is present and matches the filter - */ - matchSid(idTokenClaims, sid) { - return idTokenClaims.sid === sid; - } - matchAuthorityType(entity, authorityType) { - return !!(entity.authorityType && - authorityType.toLowerCase() === entity.authorityType.toLowerCase()); - } - /** - * Returns true if the target scopes are a subset of the current entity's scopes, false otherwise. - * @param entity - * @param target - */ - matchTarget(entity, target) { - const isNotAccessTokenCredential = entity.credentialType !== CredentialType.ACCESS_TOKEN && - entity.credentialType !== - CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME; - if (isNotAccessTokenCredential || !entity.target) { - return false; - } - const entityScopeSet = ScopeSet.fromString(entity.target); - return entityScopeSet.containsScopeSet(target); - } - /** - * Returns true if the credential's tokenType or Authentication Scheme matches the one in the request, false otherwise - * @param entity - * @param tokenType - */ - matchTokenType(entity, tokenType) { - return !!(entity.tokenType && entity.tokenType === tokenType); - } - /** - * Returns true if the credential's keyId matches the one in the request, false otherwise - * @param entity - * @param keyId - */ - matchKeyId(entity, keyId) { - return !!(entity.keyId && entity.keyId === keyId); - } - /** - * returns if a given cache entity is of the type appmetadata - * @param key - */ - isAppMetadata(key) { - return key.indexOf(APP_METADATA) !== -1; - } - /** - * returns if a given cache entity is of the type authoritymetadata - * @param key - */ - isAuthorityMetadata(key) { - return key.indexOf(AUTHORITY_METADATA_CONSTANTS.CACHE_KEY) !== -1; - } - /** - * returns cache key used for cloud instance metadata - */ - generateAuthorityMetadataCacheKey(authority) { - return `${AUTHORITY_METADATA_CONSTANTS.CACHE_KEY}-${this.clientId}-${authority}`; - } - /** - * Helper to convert serialized data to object - * @param obj - * @param json - */ - static toObject(obj, json) { - for (const propertyName in json) { - obj[propertyName] = json[propertyName]; - } - return obj; - } -} -/** @internal */ -class DefaultStorageClass extends CacheManager { - async setAccount() { - throw createClientAuthError(methodNotImplemented); - } - getAccount() { - throw createClientAuthError(methodNotImplemented); - } - async setIdTokenCredential() { - throw createClientAuthError(methodNotImplemented); - } - getIdTokenCredential() { - throw createClientAuthError(methodNotImplemented); - } - async setAccessTokenCredential() { - throw createClientAuthError(methodNotImplemented); - } - getAccessTokenCredential() { - throw createClientAuthError(methodNotImplemented); - } - async setRefreshTokenCredential() { - throw createClientAuthError(methodNotImplemented); - } - getRefreshTokenCredential() { - throw createClientAuthError(methodNotImplemented); - } - setAppMetadata() { - throw createClientAuthError(methodNotImplemented); - } - getAppMetadata() { - throw createClientAuthError(methodNotImplemented); - } - setServerTelemetry() { - throw createClientAuthError(methodNotImplemented); - } - getServerTelemetry() { - throw createClientAuthError(methodNotImplemented); - } - setAuthorityMetadata() { - throw createClientAuthError(methodNotImplemented); - } - getAuthorityMetadata() { - throw createClientAuthError(methodNotImplemented); - } - getAuthorityMetadataKeys() { - throw createClientAuthError(methodNotImplemented); - } - setThrottlingCache() { - throw createClientAuthError(methodNotImplemented); - } - getThrottlingCache() { - throw createClientAuthError(methodNotImplemented); - } - removeItem() { - throw createClientAuthError(methodNotImplemented); - } - getKeys() { - throw createClientAuthError(methodNotImplemented); - } - getAccountKeys() { - throw createClientAuthError(methodNotImplemented); - } - getTokenKeys() { - throw createClientAuthError(methodNotImplemented); - } - generateCredentialKey() { - throw createClientAuthError(methodNotImplemented); - } - generateAccountKey() { - throw createClientAuthError(methodNotImplemented); - } -} - -export { CacheManager, DefaultStorageClass }; -//# sourceMappingURL=CacheManager.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/cache/entities/AccountEntity.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/cache/entities/AccountEntity.mjs deleted file mode 100644 index eb0ea4f6..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/cache/entities/AccountEntity.mjs +++ /dev/null @@ -1,232 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { CacheAccountType } from '../../utils/Constants.mjs'; -import { buildClientInfo } from '../../account/ClientInfo.mjs'; -import { buildTenantProfile } from '../../account/AccountInfo.mjs'; -import { createClientAuthError } from '../../error/ClientAuthError.mjs'; -import { AuthorityType } from '../../authority/AuthorityType.mjs'; -import { getTenantIdFromIdTokenClaims } from '../../account/TokenClaims.mjs'; -import { ProtocolMode } from '../../authority/ProtocolMode.mjs'; -import { invalidCacheEnvironment } from '../../error/ClientAuthErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Type that defines required and optional parameters for an Account field (based on universal cache schema implemented by all MSALs). - * - * Key : Value Schema - * - * Key: -- - * - * Value Schema: - * { - * homeAccountId: home account identifier for the auth scheme, - * environment: entity that issued the token, represented as a full host - * realm: Full tenant or organizational identifier that the account belongs to - * localAccountId: Original tenant-specific accountID, usually used for legacy cases - * username: primary username that represents the user, usually corresponds to preferred_username in the v2 endpt - * authorityType: Accounts authority type as a string - * name: Full name for the account, including given name and family name, - * lastModificationTime: last time this entity was modified in the cache - * lastModificationApp: - * nativeAccountId: Account identifier on the native device - * tenantProfiles: Array of tenant profile objects for each tenant that the account has authenticated with in the browser - * } - * @internal - */ -class AccountEntity { - /** - * Returns the AccountInfo interface for this account. - */ - static getAccountInfo(accountEntity) { - return { - homeAccountId: accountEntity.homeAccountId, - environment: accountEntity.environment, - tenantId: accountEntity.realm, - username: accountEntity.username, - localAccountId: accountEntity.localAccountId, - loginHint: accountEntity.loginHint, - name: accountEntity.name, - nativeAccountId: accountEntity.nativeAccountId, - authorityType: accountEntity.authorityType, - // Deserialize tenant profiles array into a Map - tenantProfiles: new Map((accountEntity.tenantProfiles || []).map((tenantProfile) => { - return [tenantProfile.tenantId, tenantProfile]; - })), - dataBoundary: accountEntity.dataBoundary, - }; - } - /** - * Returns true if the account entity is in single tenant format (outdated), false otherwise - */ - isSingleTenant() { - return !this.tenantProfiles; - } - /** - * Build Account cache from IdToken, clientInfo and authority/policy. Associated with AAD. - * @param accountDetails - */ - static createAccount(accountDetails, authority, base64Decode) { - const account = new AccountEntity(); - if (authority.authorityType === AuthorityType.Adfs) { - account.authorityType = CacheAccountType.ADFS_ACCOUNT_TYPE; - } - else if (authority.protocolMode === ProtocolMode.OIDC) { - account.authorityType = CacheAccountType.GENERIC_ACCOUNT_TYPE; - } - else { - account.authorityType = CacheAccountType.MSSTS_ACCOUNT_TYPE; - } - let clientInfo; - if (accountDetails.clientInfo && base64Decode) { - clientInfo = buildClientInfo(accountDetails.clientInfo, base64Decode); - if (clientInfo.xms_tdbr) { - account.dataBoundary = - clientInfo.xms_tdbr === "EU" ? "EU" : "None"; - } - } - account.clientInfo = accountDetails.clientInfo; - account.homeAccountId = accountDetails.homeAccountId; - account.nativeAccountId = accountDetails.nativeAccountId; - const env = accountDetails.environment || - (authority && authority.getPreferredCache()); - if (!env) { - throw createClientAuthError(invalidCacheEnvironment); - } - account.environment = env; - // non AAD scenarios can have empty realm - account.realm = - clientInfo?.utid || - getTenantIdFromIdTokenClaims(accountDetails.idTokenClaims) || - ""; - // How do you account for MSA CID here? - account.localAccountId = - clientInfo?.uid || - accountDetails.idTokenClaims?.oid || - accountDetails.idTokenClaims?.sub || - ""; - /* - * In B2C scenarios the emails claim is used instead of preferred_username and it is an array. - * In most cases it will contain a single email. This field should not be relied upon if a custom - * policy is configured to return more than 1 email. - */ - const preferredUsername = accountDetails.idTokenClaims?.preferred_username || - accountDetails.idTokenClaims?.upn; - const email = accountDetails.idTokenClaims?.emails - ? accountDetails.idTokenClaims.emails[0] - : null; - account.username = preferredUsername || email || ""; - account.loginHint = accountDetails.idTokenClaims?.login_hint; - account.name = accountDetails.idTokenClaims?.name || ""; - account.cloudGraphHostName = accountDetails.cloudGraphHostName; - account.msGraphHost = accountDetails.msGraphHost; - if (accountDetails.tenantProfiles) { - account.tenantProfiles = accountDetails.tenantProfiles; - } - else { - const tenantProfile = buildTenantProfile(accountDetails.homeAccountId, account.localAccountId, account.realm, accountDetails.idTokenClaims); - account.tenantProfiles = [tenantProfile]; - } - return account; - } - /** - * Creates an AccountEntity object from AccountInfo - * @param accountInfo - * @param cloudGraphHostName - * @param msGraphHost - * @returns - */ - static createFromAccountInfo(accountInfo, cloudGraphHostName, msGraphHost) { - const account = new AccountEntity(); - account.authorityType = - accountInfo.authorityType || CacheAccountType.GENERIC_ACCOUNT_TYPE; - account.homeAccountId = accountInfo.homeAccountId; - account.localAccountId = accountInfo.localAccountId; - account.nativeAccountId = accountInfo.nativeAccountId; - account.realm = accountInfo.tenantId; - account.environment = accountInfo.environment; - account.username = accountInfo.username; - account.name = accountInfo.name; - account.loginHint = accountInfo.loginHint; - account.cloudGraphHostName = cloudGraphHostName; - account.msGraphHost = msGraphHost; - // Serialize tenant profiles map into an array - account.tenantProfiles = Array.from(accountInfo.tenantProfiles?.values() || []); - account.dataBoundary = accountInfo.dataBoundary; - return account; - } - /** - * Generate HomeAccountId from server response - * @param serverClientInfo - * @param authType - */ - static generateHomeAccountId(serverClientInfo, authType, logger, cryptoObj, idTokenClaims) { - // since ADFS/DSTS do not have tid and does not set client_info - if (!(authType === AuthorityType.Adfs || - authType === AuthorityType.Dsts)) { - // for cases where there is clientInfo - if (serverClientInfo) { - try { - const clientInfo = buildClientInfo(serverClientInfo, cryptoObj.base64Decode); - if (clientInfo.uid && clientInfo.utid) { - return `${clientInfo.uid}.${clientInfo.utid}`; - } - } - catch (e) { } - } - logger.warning("No client info in response"); - } - // default to "sub" claim - return idTokenClaims?.sub || ""; - } - /** - * Validates an entity: checks for all expected params - * @param entity - */ - static isAccountEntity(entity) { - if (!entity) { - return false; - } - return (entity.hasOwnProperty("homeAccountId") && - entity.hasOwnProperty("environment") && - entity.hasOwnProperty("realm") && - entity.hasOwnProperty("localAccountId") && - entity.hasOwnProperty("username") && - entity.hasOwnProperty("authorityType")); - } - /** - * Helper function to determine whether 2 accountInfo objects represent the same account - * @param accountA - * @param accountB - * @param compareClaims - If set to true idTokenClaims will also be compared to determine account equality - */ - static accountInfoIsEqual(accountA, accountB, compareClaims) { - if (!accountA || !accountB) { - return false; - } - let claimsMatch = true; // default to true so as to not fail comparison below if compareClaims: false - if (compareClaims) { - const accountAClaims = (accountA.idTokenClaims || - {}); - const accountBClaims = (accountB.idTokenClaims || - {}); - // issued at timestamp and nonce are expected to change each time a new id token is acquired - claimsMatch = - accountAClaims.iat === accountBClaims.iat && - accountAClaims.nonce === accountBClaims.nonce; - } - return (accountA.homeAccountId === accountB.homeAccountId && - accountA.localAccountId === accountB.localAccountId && - accountA.username === accountB.username && - accountA.tenantId === accountB.tenantId && - accountA.loginHint === accountB.loginHint && - accountA.environment === accountB.environment && - accountA.nativeAccountId === accountB.nativeAccountId && - claimsMatch); - } -} - -export { AccountEntity }; -//# sourceMappingURL=AccountEntity.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/cache/persistence/TokenCacheContext.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/cache/persistence/TokenCacheContext.mjs deleted file mode 100644 index 688d8ea1..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/cache/persistence/TokenCacheContext.mjs +++ /dev/null @@ -1,30 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * This class instance helps track the memory changes facilitating - * decisions to read from and write to the persistent cache - */ class TokenCacheContext { - constructor(tokenCache, hasChanged) { - this.cache = tokenCache; - this.hasChanged = hasChanged; - } - /** - * boolean which indicates the changes in cache - */ - get cacheHasChanged() { - return this.hasChanged; - } - /** - * function to retrieve the token cache - */ - get tokenCache() { - return this.cache; - } -} - -export { TokenCacheContext }; -//# sourceMappingURL=TokenCacheContext.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/cache/utils/CacheHelpers.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/cache/utils/CacheHelpers.mjs deleted file mode 100644 index 77996654..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/cache/utils/CacheHelpers.mjs +++ /dev/null @@ -1,270 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { extractTokenClaims } from '../../account/AuthToken.mjs'; -import { createClientAuthError } from '../../error/ClientAuthError.mjs'; -import { CredentialType, AuthenticationScheme, SERVER_TELEM_CONSTANTS, ThrottlingConstants, APP_METADATA, Separators, AUTHORITY_METADATA_CONSTANTS } from '../../utils/Constants.mjs'; -import { nowSeconds } from '../../utils/TimeUtils.mjs'; -import { tokenClaimsCnfRequiredForSignedJwt } from '../../error/ClientAuthErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Create IdTokenEntity - * @param homeAccountId - * @param authenticationResult - * @param clientId - * @param authority - */ -function createIdTokenEntity(homeAccountId, environment, idToken, clientId, tenantId) { - const idTokenEntity = { - credentialType: CredentialType.ID_TOKEN, - homeAccountId: homeAccountId, - environment: environment, - clientId: clientId, - secret: idToken, - realm: tenantId, - lastUpdatedAt: Date.now().toString(), // Set the last updated time to now - }; - return idTokenEntity; -} -/** - * Create AccessTokenEntity - * @param homeAccountId - * @param environment - * @param accessToken - * @param clientId - * @param tenantId - * @param scopes - * @param expiresOn - * @param extExpiresOn - */ -function createAccessTokenEntity(homeAccountId, environment, accessToken, clientId, tenantId, scopes, expiresOn, extExpiresOn, base64Decode, refreshOn, tokenType, userAssertionHash, keyId, requestedClaims, requestedClaimsHash) { - const atEntity = { - homeAccountId: homeAccountId, - credentialType: CredentialType.ACCESS_TOKEN, - secret: accessToken, - cachedAt: nowSeconds().toString(), - expiresOn: expiresOn.toString(), - extendedExpiresOn: extExpiresOn.toString(), - environment: environment, - clientId: clientId, - realm: tenantId, - target: scopes, - tokenType: tokenType || AuthenticationScheme.BEARER, - lastUpdatedAt: Date.now().toString(), // Set the last updated time to now - }; - if (userAssertionHash) { - atEntity.userAssertionHash = userAssertionHash; - } - if (refreshOn) { - atEntity.refreshOn = refreshOn.toString(); - } - if (requestedClaims) { - atEntity.requestedClaims = requestedClaims; - atEntity.requestedClaimsHash = requestedClaimsHash; - } - /* - * Create Access Token With Auth Scheme instead of regular access token - * Cast to lower to handle "bearer" from ADFS - */ - if (atEntity.tokenType?.toLowerCase() !== - AuthenticationScheme.BEARER.toLowerCase()) { - atEntity.credentialType = CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME; - switch (atEntity.tokenType) { - case AuthenticationScheme.POP: - // Make sure keyId is present and add it to credential - const tokenClaims = extractTokenClaims(accessToken, base64Decode); - if (!tokenClaims?.cnf?.kid) { - throw createClientAuthError(tokenClaimsCnfRequiredForSignedJwt); - } - atEntity.keyId = tokenClaims.cnf.kid; - break; - case AuthenticationScheme.SSH: - atEntity.keyId = keyId; - } - } - return atEntity; -} -/** - * Create RefreshTokenEntity - * @param homeAccountId - * @param authenticationResult - * @param clientId - * @param authority - */ -function createRefreshTokenEntity(homeAccountId, environment, refreshToken, clientId, familyId, userAssertionHash, expiresOn) { - const rtEntity = { - credentialType: CredentialType.REFRESH_TOKEN, - homeAccountId: homeAccountId, - environment: environment, - clientId: clientId, - secret: refreshToken, - lastUpdatedAt: Date.now().toString(), - }; - if (userAssertionHash) { - rtEntity.userAssertionHash = userAssertionHash; - } - if (familyId) { - rtEntity.familyId = familyId; - } - if (expiresOn) { - rtEntity.expiresOn = expiresOn.toString(); - } - return rtEntity; -} -function isCredentialEntity(entity) { - return (entity.hasOwnProperty("homeAccountId") && - entity.hasOwnProperty("environment") && - entity.hasOwnProperty("credentialType") && - entity.hasOwnProperty("clientId") && - entity.hasOwnProperty("secret")); -} -/** - * Validates an entity: checks for all expected params - * @param entity - */ -function isAccessTokenEntity(entity) { - if (!entity) { - return false; - } - return (isCredentialEntity(entity) && - entity.hasOwnProperty("realm") && - entity.hasOwnProperty("target") && - (entity["credentialType"] === CredentialType.ACCESS_TOKEN || - entity["credentialType"] === - CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME)); -} -/** - * Validates an entity: checks for all expected params - * @param entity - */ -function isIdTokenEntity(entity) { - if (!entity) { - return false; - } - return (isCredentialEntity(entity) && - entity.hasOwnProperty("realm") && - entity["credentialType"] === CredentialType.ID_TOKEN); -} -/** - * Validates an entity: checks for all expected params - * @param entity - */ -function isRefreshTokenEntity(entity) { - if (!entity) { - return false; - } - return (isCredentialEntity(entity) && - entity["credentialType"] === CredentialType.REFRESH_TOKEN); -} -/** - * validates if a given cache entry is "Telemetry", parses - * @param key - * @param entity - */ -function isServerTelemetryEntity(key, entity) { - const validateKey = key.indexOf(SERVER_TELEM_CONSTANTS.CACHE_KEY) === 0; - let validateEntity = true; - if (entity) { - validateEntity = - entity.hasOwnProperty("failedRequests") && - entity.hasOwnProperty("errors") && - entity.hasOwnProperty("cacheHits"); - } - return validateKey && validateEntity; -} -/** - * validates if a given cache entry is "Throttling", parses - * @param key - * @param entity - */ -function isThrottlingEntity(key, entity) { - let validateKey = false; - if (key) { - validateKey = key.indexOf(ThrottlingConstants.THROTTLING_PREFIX) === 0; - } - let validateEntity = true; - if (entity) { - validateEntity = entity.hasOwnProperty("throttleTime"); - } - return validateKey && validateEntity; -} -/** - * Generate AppMetadata Cache Key as per the schema: appmetadata-- - */ -function generateAppMetadataKey({ environment, clientId, }) { - const appMetaDataKeyArray = [ - APP_METADATA, - environment, - clientId, - ]; - return appMetaDataKeyArray - .join(Separators.CACHE_KEY_SEPARATOR) - .toLowerCase(); -} -/* - * Validates an entity: checks for all expected params - * @param entity - */ -function isAppMetadataEntity(key, entity) { - if (!entity) { - return false; - } - return (key.indexOf(APP_METADATA) === 0 && - entity.hasOwnProperty("clientId") && - entity.hasOwnProperty("environment")); -} -/** - * Validates an entity: checks for all expected params - * @param entity - */ -function isAuthorityMetadataEntity(key, entity) { - if (!entity) { - return false; - } - return (key.indexOf(AUTHORITY_METADATA_CONSTANTS.CACHE_KEY) === 0 && - entity.hasOwnProperty("aliases") && - entity.hasOwnProperty("preferred_cache") && - entity.hasOwnProperty("preferred_network") && - entity.hasOwnProperty("canonical_authority") && - entity.hasOwnProperty("authorization_endpoint") && - entity.hasOwnProperty("token_endpoint") && - entity.hasOwnProperty("issuer") && - entity.hasOwnProperty("aliasesFromNetwork") && - entity.hasOwnProperty("endpointsFromNetwork") && - entity.hasOwnProperty("expiresAt") && - entity.hasOwnProperty("jwks_uri")); -} -/** - * Reset the exiresAt value - */ -function generateAuthorityMetadataExpiresAt() { - return (nowSeconds() + - AUTHORITY_METADATA_CONSTANTS.REFRESH_TIME_SECONDS); -} -function updateAuthorityEndpointMetadata(authorityMetadata, updatedValues, fromNetwork) { - authorityMetadata.authorization_endpoint = - updatedValues.authorization_endpoint; - authorityMetadata.token_endpoint = updatedValues.token_endpoint; - authorityMetadata.end_session_endpoint = updatedValues.end_session_endpoint; - authorityMetadata.issuer = updatedValues.issuer; - authorityMetadata.endpointsFromNetwork = fromNetwork; - authorityMetadata.jwks_uri = updatedValues.jwks_uri; -} -function updateCloudDiscoveryMetadata(authorityMetadata, updatedValues, fromNetwork) { - authorityMetadata.aliases = updatedValues.aliases; - authorityMetadata.preferred_cache = updatedValues.preferred_cache; - authorityMetadata.preferred_network = updatedValues.preferred_network; - authorityMetadata.aliasesFromNetwork = fromNetwork; -} -/** - * Returns whether or not the data needs to be refreshed - */ -function isAuthorityMetadataExpired(metadata) { - return metadata.expiresAt <= nowSeconds(); -} - -export { createAccessTokenEntity, createIdTokenEntity, createRefreshTokenEntity, generateAppMetadataKey, generateAuthorityMetadataExpiresAt, isAccessTokenEntity, isAppMetadataEntity, isAuthorityMetadataEntity, isAuthorityMetadataExpired, isCredentialEntity, isIdTokenEntity, isRefreshTokenEntity, isServerTelemetryEntity, isThrottlingEntity, updateAuthorityEndpointMetadata, updateCloudDiscoveryMetadata }; -//# sourceMappingURL=CacheHelpers.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/client/AuthorizationCodeClient.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/client/AuthorizationCodeClient.mjs deleted file mode 100644 index d41eadc8..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/client/AuthorizationCodeClient.mjs +++ /dev/null @@ -1,259 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { BaseClient } from './BaseClient.mjs'; -import { addClientId, addRedirectUri, addScopes, addAuthorizationCode, addLibraryInfo, addApplicationTelemetry, addThrottling, addServerTelemetry, addCodeVerifier, addClientSecret, addClientAssertion, addClientAssertionType, addGrantType, addClientInfo, addPopToken, addSshJwk, addClaims, addCcsUpn, addCcsOid, addBrokerParameters, addExtraQueryParameters, instrumentBrokerParams, addPostLogoutRedirectUri, addCorrelationId, addIdTokenHint, addState, addLogoutHint, addInstanceAware } from '../request/RequestParameterBuilder.mjs'; -import { mapToQueryString } from '../utils/UrlUtils.mjs'; -import { Separators, AuthenticationScheme, HeaderNames, GrantType } from '../utils/Constants.mjs'; -import { RETURN_SPA_CODE, CLIENT_ID } from '../constants/AADServerParamKeys.mjs'; -import { isOidcProtocolMode } from '../config/ClientConfiguration.mjs'; -import { ResponseHandler } from '../response/ResponseHandler.mjs'; -import { StringUtils } from '../utils/StringUtils.mjs'; -import { createClientAuthError } from '../error/ClientAuthError.mjs'; -import { UrlString } from '../url/UrlString.mjs'; -import { PopTokenGenerator } from '../crypto/PopTokenGenerator.mjs'; -import { nowSeconds } from '../utils/TimeUtils.mjs'; -import { buildClientInfo, buildClientInfoFromHomeAccountId } from '../account/ClientInfo.mjs'; -import { CcsCredentialType } from '../account/CcsCredential.mjs'; -import { createClientConfigurationError } from '../error/ClientConfigurationError.mjs'; -import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs'; -import { invokeAsync } from '../utils/FunctionWrappers.mjs'; -import { getClientAssertion } from '../utils/ClientAssertionUtils.mjs'; -import { getRequestThumbprint } from '../network/RequestThumbprint.mjs'; -import { requestCannotBeMade } from '../error/ClientAuthErrorCodes.mjs'; -import { logoutRequestEmpty, redirectUriEmpty, missingSshJwk } from '../error/ClientConfigurationErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Oauth2.0 Authorization Code client - * @internal - */ -class AuthorizationCodeClient extends BaseClient { - constructor(configuration, performanceClient) { - super(configuration, performanceClient); - // Flag to indicate if client is for hybrid spa auth code redemption - this.includeRedirectUri = true; - this.oidcDefaultScopes = - this.config.authOptions.authority.options.OIDCOptions?.defaultScopes; - } - /** - * API to acquire a token in exchange of 'authorization_code` acquired by the user in the first leg of the - * authorization_code_grant - * @param request - */ - async acquireToken(request, authCodePayload) { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthClientAcquireToken, request.correlationId); - if (!request.code) { - throw createClientAuthError(requestCannotBeMade); - } - const reqTimestamp = nowSeconds(); - const response = await invokeAsync(this.executeTokenRequest.bind(this), PerformanceEvents.AuthClientExecuteTokenRequest, this.logger, this.performanceClient, request.correlationId)(this.authority, request); - // Retrieve requestId from response headers - const requestId = response.headers?.[HeaderNames.X_MS_REQUEST_ID]; - const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin, this.performanceClient); - // Validate response. This function throws a server error if an error is returned by the server. - responseHandler.validateTokenResponse(response.body); - return invokeAsync(responseHandler.handleServerTokenResponse.bind(responseHandler), PerformanceEvents.HandleServerTokenResponse, this.logger, this.performanceClient, request.correlationId)(response.body, this.authority, reqTimestamp, request, authCodePayload, undefined, undefined, undefined, requestId); - } - /** - * Used to log out the current user, and redirect the user to the postLogoutRedirectUri. - * Default behaviour is to redirect the user to `window.location.href`. - * @param authorityUri - */ - getLogoutUri(logoutRequest) { - // Throw error if logoutRequest is null/undefined - if (!logoutRequest) { - throw createClientConfigurationError(logoutRequestEmpty); - } - const queryString = this.createLogoutUrlQueryString(logoutRequest); - // Construct logout URI - return UrlString.appendQueryString(this.authority.endSessionEndpoint, queryString); - } - /** - * Executes POST request to token endpoint - * @param authority - * @param request - */ - async executeTokenRequest(authority, request) { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthClientExecuteTokenRequest, request.correlationId); - const queryParametersString = this.createTokenQueryParameters(request); - const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString); - const requestBody = await invokeAsync(this.createTokenRequestBody.bind(this), PerformanceEvents.AuthClientCreateTokenRequestBody, this.logger, this.performanceClient, request.correlationId)(request); - let ccsCredential = undefined; - if (request.clientInfo) { - try { - const clientInfo = buildClientInfo(request.clientInfo, this.cryptoUtils.base64Decode); - ccsCredential = { - credential: `${clientInfo.uid}${Separators.CLIENT_INFO_SEPARATOR}${clientInfo.utid}`, - type: CcsCredentialType.HOME_ACCOUNT_ID, - }; - } - catch (e) { - this.logger.verbose("Could not parse client info for CCS Header: " + e); - } - } - const headers = this.createTokenRequestHeaders(ccsCredential || request.ccsCredential); - const thumbprint = getRequestThumbprint(this.config.authOptions.clientId, request); - return invokeAsync(this.executePostToTokenEndpoint.bind(this), PerformanceEvents.AuthorizationCodeClientExecutePostToTokenEndpoint, this.logger, this.performanceClient, request.correlationId)(endpoint, requestBody, headers, thumbprint, request.correlationId, PerformanceEvents.AuthorizationCodeClientExecutePostToTokenEndpoint); - } - /** - * Generates a map for all the params to be sent to the service - * @param request - */ - async createTokenRequestBody(request) { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.AuthClientCreateTokenRequestBody, request.correlationId); - const parameters = new Map(); - addClientId(parameters, request.embeddedClientId || - request.tokenBodyParameters?.[CLIENT_ID] || - this.config.authOptions.clientId); - /* - * For hybrid spa flow, there will be a code but no verifier - * In this scenario, don't include redirect uri as auth code will not be bound to redirect URI - */ - if (!this.includeRedirectUri) { - // Just validate - if (!request.redirectUri) { - throw createClientConfigurationError(redirectUriEmpty); - } - } - else { - // Validate and include redirect uri - addRedirectUri(parameters, request.redirectUri); - } - // Add scope array, parameter builder will add default scopes and dedupe - addScopes(parameters, request.scopes, true, this.oidcDefaultScopes); - // add code: user set, not validated - addAuthorizationCode(parameters, request.code); - // Add library metadata - addLibraryInfo(parameters, this.config.libraryInfo); - addApplicationTelemetry(parameters, this.config.telemetry.application); - addThrottling(parameters); - if (this.serverTelemetryManager && !isOidcProtocolMode(this.config)) { - addServerTelemetry(parameters, this.serverTelemetryManager); - } - // add code_verifier if passed - if (request.codeVerifier) { - addCodeVerifier(parameters, request.codeVerifier); - } - if (this.config.clientCredentials.clientSecret) { - addClientSecret(parameters, this.config.clientCredentials.clientSecret); - } - if (this.config.clientCredentials.clientAssertion) { - const clientAssertion = this.config.clientCredentials.clientAssertion; - addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri)); - addClientAssertionType(parameters, clientAssertion.assertionType); - } - addGrantType(parameters, GrantType.AUTHORIZATION_CODE_GRANT); - addClientInfo(parameters); - if (request.authenticationScheme === AuthenticationScheme.POP) { - const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.performanceClient); - let reqCnfData; - if (!request.popKid) { - const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PerformanceEvents.PopTokenGenerateCnf, this.logger, this.performanceClient, request.correlationId)(request, this.logger); - reqCnfData = generatedReqCnfData.reqCnfString; - } - else { - reqCnfData = this.cryptoUtils.encodeKid(request.popKid); - } - // SPA PoP requires full Base64Url encoded req_cnf string (unhashed) - addPopToken(parameters, reqCnfData); - } - else if (request.authenticationScheme === AuthenticationScheme.SSH) { - if (request.sshJwk) { - addSshJwk(parameters, request.sshJwk); - } - else { - throw createClientConfigurationError(missingSshJwk); - } - } - if (!StringUtils.isEmptyObj(request.claims) || - (this.config.authOptions.clientCapabilities && - this.config.authOptions.clientCapabilities.length > 0)) { - addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities); - } - let ccsCred = undefined; - if (request.clientInfo) { - try { - const clientInfo = buildClientInfo(request.clientInfo, this.cryptoUtils.base64Decode); - ccsCred = { - credential: `${clientInfo.uid}${Separators.CLIENT_INFO_SEPARATOR}${clientInfo.utid}`, - type: CcsCredentialType.HOME_ACCOUNT_ID, - }; - } - catch (e) { - this.logger.verbose("Could not parse client info for CCS Header: " + e); - } - } - else { - ccsCred = request.ccsCredential; - } - // Adds these as parameters in the request instead of headers to prevent CORS preflight request - if (this.config.systemOptions.preventCorsPreflight && ccsCred) { - switch (ccsCred.type) { - case CcsCredentialType.HOME_ACCOUNT_ID: - try { - const clientInfo = buildClientInfoFromHomeAccountId(ccsCred.credential); - addCcsOid(parameters, clientInfo); - } - catch (e) { - this.logger.verbose("Could not parse home account ID for CCS Header: " + - e); - } - break; - case CcsCredentialType.UPN: - addCcsUpn(parameters, ccsCred.credential); - break; - } - } - if (request.embeddedClientId) { - addBrokerParameters(parameters, this.config.authOptions.clientId, this.config.authOptions.redirectUri); - } - if (request.tokenBodyParameters) { - addExtraQueryParameters(parameters, request.tokenBodyParameters); - } - // Add hybrid spa parameters if not already provided - if (request.enableSpaAuthorizationCode && - (!request.tokenBodyParameters || - !request.tokenBodyParameters[RETURN_SPA_CODE])) { - addExtraQueryParameters(parameters, { - [RETURN_SPA_CODE]: "1", - }); - } - instrumentBrokerParams(parameters, request.correlationId, this.performanceClient); - return mapToQueryString(parameters); - } - /** - * This API validates the `EndSessionRequest` and creates a URL - * @param request - */ - createLogoutUrlQueryString(request) { - const parameters = new Map(); - if (request.postLogoutRedirectUri) { - addPostLogoutRedirectUri(parameters, request.postLogoutRedirectUri); - } - if (request.correlationId) { - addCorrelationId(parameters, request.correlationId); - } - if (request.idTokenHint) { - addIdTokenHint(parameters, request.idTokenHint); - } - if (request.state) { - addState(parameters, request.state); - } - if (request.logoutHint) { - addLogoutHint(parameters, request.logoutHint); - } - if (request.extraQueryParameters) { - addExtraQueryParameters(parameters, request.extraQueryParameters); - } - if (this.config.authOptions.instanceAware) { - addInstanceAware(parameters); - } - return mapToQueryString(parameters, this.config.authOptions.encodeExtraQueryParams, request.extraQueryParameters); - } -} - -export { AuthorizationCodeClient }; -//# sourceMappingURL=AuthorizationCodeClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/client/BaseClient.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/client/BaseClient.mjs deleted file mode 100644 index 21e5535a..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/client/BaseClient.mjs +++ /dev/null @@ -1,167 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { buildClientConfiguration } from '../config/ClientConfiguration.mjs'; -import { Logger } from '../logger/Logger.mjs'; -import { Constants, HeaderNames } from '../utils/Constants.mjs'; -import { name, version } from '../packageMetadata.mjs'; -import { CcsCredentialType } from '../account/CcsCredential.mjs'; -import { buildClientInfoFromHomeAccountId } from '../account/ClientInfo.mjs'; -import { addBrokerParameters, addExtraQueryParameters, addCorrelationId, instrumentBrokerParams } from '../request/RequestParameterBuilder.mjs'; -import { mapToQueryString } from '../utils/UrlUtils.mjs'; -import { createDiscoveredInstance } from '../authority/AuthorityFactory.mjs'; -import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs'; -import { ThrottlingUtils } from '../network/ThrottlingUtils.mjs'; -import { AuthError } from '../error/AuthError.mjs'; -import { createClientAuthError } from '../error/ClientAuthError.mjs'; -import { NetworkError } from '../error/NetworkError.mjs'; -import { invokeAsync } from '../utils/FunctionWrappers.mjs'; -import { networkError } from '../error/ClientAuthErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Base application class which will construct requests to send to and handle responses from the Microsoft STS using the authorization code flow. - * @internal - */ -class BaseClient { - constructor(configuration, performanceClient) { - // Set the configuration - this.config = buildClientConfiguration(configuration); - // Initialize the logger - this.logger = new Logger(this.config.loggerOptions, name, version); - // Initialize crypto - this.cryptoUtils = this.config.cryptoInterface; - // Initialize storage interface - this.cacheManager = this.config.storageInterface; - // Set the network interface - this.networkClient = this.config.networkInterface; - // Set TelemetryManager - this.serverTelemetryManager = this.config.serverTelemetryManager; - // set Authority - this.authority = this.config.authOptions.authority; - // set performance telemetry client - this.performanceClient = performanceClient; - } - /** - * Creates default headers for requests to token endpoint - */ - createTokenRequestHeaders(ccsCred) { - const headers = {}; - headers[HeaderNames.CONTENT_TYPE] = Constants.URL_FORM_CONTENT_TYPE; - if (!this.config.systemOptions.preventCorsPreflight && ccsCred) { - switch (ccsCred.type) { - case CcsCredentialType.HOME_ACCOUNT_ID: - try { - const clientInfo = buildClientInfoFromHomeAccountId(ccsCred.credential); - headers[HeaderNames.CCS_HEADER] = `Oid:${clientInfo.uid}@${clientInfo.utid}`; - } - catch (e) { - this.logger.verbose("Could not parse home account ID for CCS Header: " + - e); - } - break; - case CcsCredentialType.UPN: - headers[HeaderNames.CCS_HEADER] = `UPN: ${ccsCred.credential}`; - break; - } - } - return headers; - } - /** - * Http post to token endpoint - * @param tokenEndpoint - * @param queryString - * @param headers - * @param thumbprint - */ - async executePostToTokenEndpoint(tokenEndpoint, queryString, headers, thumbprint, correlationId, queuedEvent) { - if (queuedEvent) { - this.performanceClient?.addQueueMeasurement(queuedEvent, correlationId); - } - const response = await this.sendPostRequest(thumbprint, tokenEndpoint, { body: queryString, headers: headers }, correlationId); - if (this.config.serverTelemetryManager && - response.status < 500 && - response.status !== 429) { - // Telemetry data successfully logged by server, clear Telemetry cache - this.config.serverTelemetryManager.clearTelemetryCache(); - } - return response; - } - /** - * Wraps sendPostRequestAsync with necessary preflight and postflight logic - * @param thumbprint - Request thumbprint for throttling - * @param tokenEndpoint - Endpoint to make the POST to - * @param options - Body and Headers to include on the POST request - * @param correlationId - CorrelationId for telemetry - */ - async sendPostRequest(thumbprint, tokenEndpoint, options, correlationId) { - ThrottlingUtils.preProcess(this.cacheManager, thumbprint, correlationId); - let response; - try { - response = await invokeAsync((this.networkClient.sendPostRequestAsync.bind(this.networkClient)), PerformanceEvents.NetworkClientSendPostRequestAsync, this.logger, this.performanceClient, correlationId)(tokenEndpoint, options); - const responseHeaders = response.headers || {}; - this.performanceClient?.addFields({ - refreshTokenSize: response.body.refresh_token?.length || 0, - httpVerToken: responseHeaders[HeaderNames.X_MS_HTTP_VERSION] || "", - requestId: responseHeaders[HeaderNames.X_MS_REQUEST_ID] || "", - }, correlationId); - } - catch (e) { - if (e instanceof NetworkError) { - const responseHeaders = e.responseHeaders; - if (responseHeaders) { - this.performanceClient?.addFields({ - httpVerToken: responseHeaders[HeaderNames.X_MS_HTTP_VERSION] || "", - requestId: responseHeaders[HeaderNames.X_MS_REQUEST_ID] || - "", - contentTypeHeader: responseHeaders[HeaderNames.CONTENT_TYPE] || - undefined, - contentLengthHeader: responseHeaders[HeaderNames.CONTENT_LENGTH] || - undefined, - httpStatus: e.httpStatus, - }, correlationId); - } - throw e.error; - } - if (e instanceof AuthError) { - throw e; - } - else { - throw createClientAuthError(networkError); - } - } - ThrottlingUtils.postProcess(this.cacheManager, thumbprint, response, correlationId); - return response; - } - /** - * Updates the authority object of the client. Endpoint discovery must be completed. - * @param updatedAuthority - */ - async updateAuthority(cloudInstanceHostname, correlationId) { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.UpdateTokenEndpointAuthority, correlationId); - const cloudInstanceAuthorityUri = `https://${cloudInstanceHostname}/${this.authority.tenant}/`; - const cloudInstanceAuthority = await createDiscoveredInstance(cloudInstanceAuthorityUri, this.networkClient, this.cacheManager, this.authority.options, this.logger, correlationId, this.performanceClient); - this.authority = cloudInstanceAuthority; - } - /** - * Creates query string for the /token request - * @param request - */ - createTokenQueryParameters(request) { - const parameters = new Map(); - if (request.embeddedClientId) { - addBrokerParameters(parameters, this.config.authOptions.clientId, this.config.authOptions.redirectUri); - } - if (request.tokenQueryParameters) { - addExtraQueryParameters(parameters, request.tokenQueryParameters); - } - addCorrelationId(parameters, request.correlationId); - instrumentBrokerParams(parameters, request.correlationId, this.performanceClient); - return mapToQueryString(parameters); - } -} - -export { BaseClient }; -//# sourceMappingURL=BaseClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/client/RefreshTokenClient.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/client/RefreshTokenClient.mjs deleted file mode 100644 index 78b3fd82..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/client/RefreshTokenClient.mjs +++ /dev/null @@ -1,236 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { isOidcProtocolMode } from '../config/ClientConfiguration.mjs'; -import { BaseClient } from './BaseClient.mjs'; -import { addClientId, addRedirectUri, addScopes, addGrantType, addClientInfo, addLibraryInfo, addApplicationTelemetry, addThrottling, addServerTelemetry, addRefreshToken, addClientSecret, addClientAssertion, addClientAssertionType, addPopToken, addSshJwk, addClaims, addCcsUpn, addCcsOid, addBrokerParameters, addExtraQueryParameters, instrumentBrokerParams } from '../request/RequestParameterBuilder.mjs'; -import { mapToQueryString } from '../utils/UrlUtils.mjs'; -import { AuthenticationScheme, HeaderNames, Errors, GrantType } from '../utils/Constants.mjs'; -import { CLIENT_ID } from '../constants/AADServerParamKeys.mjs'; -import { ResponseHandler } from '../response/ResponseHandler.mjs'; -import { PopTokenGenerator } from '../crypto/PopTokenGenerator.mjs'; -import { StringUtils } from '../utils/StringUtils.mjs'; -import { createClientConfigurationError } from '../error/ClientConfigurationError.mjs'; -import { createClientAuthError } from '../error/ClientAuthError.mjs'; -import { ServerError } from '../error/ServerError.mjs'; -import { nowSeconds, isTokenExpired } from '../utils/TimeUtils.mjs'; -import { UrlString } from '../url/UrlString.mjs'; -import { CcsCredentialType } from '../account/CcsCredential.mjs'; -import { buildClientInfoFromHomeAccountId } from '../account/ClientInfo.mjs'; -import { createInteractionRequiredAuthError, InteractionRequiredAuthError } from '../error/InteractionRequiredAuthError.mjs'; -import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs'; -import { invokeAsync, invoke } from '../utils/FunctionWrappers.mjs'; -import { getClientAssertion } from '../utils/ClientAssertionUtils.mjs'; -import { getRequestThumbprint } from '../network/RequestThumbprint.mjs'; -import { badToken, noTokensFound, refreshTokenExpired } from '../error/InteractionRequiredAuthErrorCodes.mjs'; -import { tokenRequestEmpty, missingSshJwk } from '../error/ClientConfigurationErrorCodes.mjs'; -import { noAccountInSilentRequest } from '../error/ClientAuthErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const DEFAULT_REFRESH_TOKEN_EXPIRATION_OFFSET_SECONDS = 300; // 5 Minutes -/** - * OAuth2.0 refresh token client - * @internal - */ -class RefreshTokenClient extends BaseClient { - constructor(configuration, performanceClient) { - super(configuration, performanceClient); - } - async acquireToken(request) { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientAcquireToken, request.correlationId); - const reqTimestamp = nowSeconds(); - const response = await invokeAsync(this.executeTokenRequest.bind(this), PerformanceEvents.RefreshTokenClientExecuteTokenRequest, this.logger, this.performanceClient, request.correlationId)(request, this.authority); - // Retrieve requestId from response headers - const requestId = response.headers?.[HeaderNames.X_MS_REQUEST_ID]; - const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin); - responseHandler.validateTokenResponse(response.body); - return invokeAsync(responseHandler.handleServerTokenResponse.bind(responseHandler), PerformanceEvents.HandleServerTokenResponse, this.logger, this.performanceClient, request.correlationId)(response.body, this.authority, reqTimestamp, request, undefined, undefined, true, request.forceCache, requestId); - } - /** - * Gets cached refresh token and attaches to request, then calls acquireToken API - * @param request - */ - async acquireTokenByRefreshToken(request) { - // Cannot renew token if no request object is given. - if (!request) { - throw createClientConfigurationError(tokenRequestEmpty); - } - this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientAcquireTokenByRefreshToken, request.correlationId); - // We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases - if (!request.account) { - throw createClientAuthError(noAccountInSilentRequest); - } - // try checking if FOCI is enabled for the given application - const isFOCI = this.cacheManager.isAppMetadataFOCI(request.account.environment); - // if the app is part of the family, retrive a Family refresh token if present and make a refreshTokenRequest - if (isFOCI) { - try { - return await invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, true); - } - catch (e) { - const noFamilyRTInCache = e instanceof InteractionRequiredAuthError && - e.errorCode === - noTokensFound; - const clientMismatchErrorWithFamilyRT = e instanceof ServerError && - e.errorCode === Errors.INVALID_GRANT_ERROR && - e.subError === Errors.CLIENT_MISMATCH_ERROR; - // if family Refresh Token (FRT) cache acquisition fails or if client_mismatch error is seen with FRT, reattempt with application Refresh Token (ART) - if (noFamilyRTInCache || clientMismatchErrorWithFamilyRT) { - return invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, false); - // throw in all other cases - } - else { - throw e; - } - } - } - // fall back to application refresh token acquisition - return invokeAsync(this.acquireTokenWithCachedRefreshToken.bind(this), PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, this.logger, this.performanceClient, request.correlationId)(request, false); - } - /** - * makes a network call to acquire tokens by exchanging RefreshToken available in userCache; throws if refresh token is not cached - * @param request - */ - async acquireTokenWithCachedRefreshToken(request, foci) { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, request.correlationId); - // fetches family RT or application RT based on FOCI value - const refreshToken = invoke(this.cacheManager.getRefreshToken.bind(this.cacheManager), PerformanceEvents.CacheManagerGetRefreshToken, this.logger, this.performanceClient, request.correlationId)(request.account, foci, request.correlationId, undefined, this.performanceClient); - if (!refreshToken) { - throw createInteractionRequiredAuthError(noTokensFound); - } - if (refreshToken.expiresOn && - isTokenExpired(refreshToken.expiresOn, request.refreshTokenExpirationOffsetSeconds || - DEFAULT_REFRESH_TOKEN_EXPIRATION_OFFSET_SECONDS)) { - this.performanceClient?.addFields({ rtExpiresOnMs: Number(refreshToken.expiresOn) }, request.correlationId); - throw createInteractionRequiredAuthError(refreshTokenExpired); - } - // attach cached RT size to the current measurement - const refreshTokenRequest = { - ...request, - refreshToken: refreshToken.secret, - authenticationScheme: request.authenticationScheme || AuthenticationScheme.BEARER, - ccsCredential: { - credential: request.account.homeAccountId, - type: CcsCredentialType.HOME_ACCOUNT_ID, - }, - }; - try { - return await invokeAsync(this.acquireToken.bind(this), PerformanceEvents.RefreshTokenClientAcquireToken, this.logger, this.performanceClient, request.correlationId)(refreshTokenRequest); - } - catch (e) { - if (e instanceof InteractionRequiredAuthError) { - this.performanceClient?.addFields({ rtExpiresOnMs: Number(refreshToken.expiresOn) }, request.correlationId); - if (e.subError === badToken) { - // Remove bad refresh token from cache - this.logger.verbose("acquireTokenWithRefreshToken: bad refresh token, removing from cache"); - const badRefreshTokenKey = this.cacheManager.generateCredentialKey(refreshToken); - this.cacheManager.removeRefreshToken(badRefreshTokenKey, request.correlationId); - } - } - throw e; - } - } - /** - * Constructs the network message and makes a NW call to the underlying secure token service - * @param request - * @param authority - */ - async executeTokenRequest(request, authority) { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientExecuteTokenRequest, request.correlationId); - const queryParametersString = this.createTokenQueryParameters(request); - const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString); - const requestBody = await invokeAsync(this.createTokenRequestBody.bind(this), PerformanceEvents.RefreshTokenClientCreateTokenRequestBody, this.logger, this.performanceClient, request.correlationId)(request); - const headers = this.createTokenRequestHeaders(request.ccsCredential); - const thumbprint = getRequestThumbprint(this.config.authOptions.clientId, request); - return invokeAsync(this.executePostToTokenEndpoint.bind(this), PerformanceEvents.RefreshTokenClientExecutePostToTokenEndpoint, this.logger, this.performanceClient, request.correlationId)(endpoint, requestBody, headers, thumbprint, request.correlationId, PerformanceEvents.RefreshTokenClientExecutePostToTokenEndpoint); - } - /** - * Helper function to create the token request body - * @param request - */ - async createTokenRequestBody(request) { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.RefreshTokenClientCreateTokenRequestBody, request.correlationId); - const parameters = new Map(); - addClientId(parameters, request.embeddedClientId || - request.tokenBodyParameters?.[CLIENT_ID] || - this.config.authOptions.clientId); - if (request.redirectUri) { - addRedirectUri(parameters, request.redirectUri); - } - addScopes(parameters, request.scopes, true, this.config.authOptions.authority.options.OIDCOptions?.defaultScopes); - addGrantType(parameters, GrantType.REFRESH_TOKEN_GRANT); - addClientInfo(parameters); - addLibraryInfo(parameters, this.config.libraryInfo); - addApplicationTelemetry(parameters, this.config.telemetry.application); - addThrottling(parameters); - if (this.serverTelemetryManager && !isOidcProtocolMode(this.config)) { - addServerTelemetry(parameters, this.serverTelemetryManager); - } - addRefreshToken(parameters, request.refreshToken); - if (this.config.clientCredentials.clientSecret) { - addClientSecret(parameters, this.config.clientCredentials.clientSecret); - } - if (this.config.clientCredentials.clientAssertion) { - const clientAssertion = this.config.clientCredentials.clientAssertion; - addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri)); - addClientAssertionType(parameters, clientAssertion.assertionType); - } - if (request.authenticationScheme === AuthenticationScheme.POP) { - const popTokenGenerator = new PopTokenGenerator(this.cryptoUtils, this.performanceClient); - let reqCnfData; - if (!request.popKid) { - const generatedReqCnfData = await invokeAsync(popTokenGenerator.generateCnf.bind(popTokenGenerator), PerformanceEvents.PopTokenGenerateCnf, this.logger, this.performanceClient, request.correlationId)(request, this.logger); - reqCnfData = generatedReqCnfData.reqCnfString; - } - else { - reqCnfData = this.cryptoUtils.encodeKid(request.popKid); - } - // SPA PoP requires full Base64Url encoded req_cnf string (unhashed) - addPopToken(parameters, reqCnfData); - } - else if (request.authenticationScheme === AuthenticationScheme.SSH) { - if (request.sshJwk) { - addSshJwk(parameters, request.sshJwk); - } - else { - throw createClientConfigurationError(missingSshJwk); - } - } - if (!StringUtils.isEmptyObj(request.claims) || - (this.config.authOptions.clientCapabilities && - this.config.authOptions.clientCapabilities.length > 0)) { - addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities); - } - if (this.config.systemOptions.preventCorsPreflight && - request.ccsCredential) { - switch (request.ccsCredential.type) { - case CcsCredentialType.HOME_ACCOUNT_ID: - try { - const clientInfo = buildClientInfoFromHomeAccountId(request.ccsCredential.credential); - addCcsOid(parameters, clientInfo); - } - catch (e) { - this.logger.verbose("Could not parse home account ID for CCS Header: " + - e); - } - break; - case CcsCredentialType.UPN: - addCcsUpn(parameters, request.ccsCredential.credential); - break; - } - } - if (request.embeddedClientId) { - addBrokerParameters(parameters, this.config.authOptions.clientId, this.config.authOptions.redirectUri); - } - if (request.tokenBodyParameters) { - addExtraQueryParameters(parameters, request.tokenBodyParameters); - } - instrumentBrokerParams(parameters, request.correlationId, this.performanceClient); - return mapToQueryString(parameters); - } -} - -export { RefreshTokenClient }; -//# sourceMappingURL=RefreshTokenClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/client/SilentFlowClient.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/client/SilentFlowClient.mjs deleted file mode 100644 index 0ea3444c..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/client/SilentFlowClient.mjs +++ /dev/null @@ -1,112 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { BaseClient } from './BaseClient.mjs'; -import { wasClockTurnedBack, isTokenExpired } from '../utils/TimeUtils.mjs'; -import { createClientAuthError } from '../error/ClientAuthError.mjs'; -import { ResponseHandler } from '../response/ResponseHandler.mjs'; -import { CacheOutcome } from '../utils/Constants.mjs'; -import { StringUtils } from '../utils/StringUtils.mjs'; -import { extractTokenClaims, checkMaxAge } from '../account/AuthToken.mjs'; -import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs'; -import { invokeAsync } from '../utils/FunctionWrappers.mjs'; -import { getTenantFromAuthorityString } from '../authority/Authority.mjs'; -import { tokenRefreshRequired, noAccountInSilentRequest, authTimeNotFound } from '../error/ClientAuthErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** @internal */ -class SilentFlowClient extends BaseClient { - constructor(configuration, performanceClient) { - super(configuration, performanceClient); - } - /** - * Retrieves token from cache or throws an error if it must be refreshed. - * @param request - */ - async acquireCachedToken(request) { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.SilentFlowClientAcquireCachedToken, request.correlationId); - let lastCacheOutcome = CacheOutcome.NOT_APPLICABLE; - if (request.forceRefresh || - (!this.config.cacheOptions.claimsBasedCachingEnabled && - !StringUtils.isEmptyObj(request.claims))) { - // Must refresh due to present force_refresh flag. - this.setCacheOutcome(CacheOutcome.FORCE_REFRESH_OR_CLAIMS, request.correlationId); - throw createClientAuthError(tokenRefreshRequired); - } - // We currently do not support silent flow for account === null use cases; This will be revisited for confidential flow usecases - if (!request.account) { - throw createClientAuthError(noAccountInSilentRequest); - } - const requestTenantId = request.account.tenantId || - getTenantFromAuthorityString(request.authority); - const tokenKeys = this.cacheManager.getTokenKeys(); - const cachedAccessToken = this.cacheManager.getAccessToken(request.account, request, tokenKeys, requestTenantId); - if (!cachedAccessToken) { - // must refresh due to non-existent access_token - this.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN, request.correlationId); - throw createClientAuthError(tokenRefreshRequired); - } - else if (wasClockTurnedBack(cachedAccessToken.cachedAt) || - isTokenExpired(cachedAccessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) { - // must refresh due to the expires_in value - this.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED, request.correlationId); - throw createClientAuthError(tokenRefreshRequired); - } - else if (cachedAccessToken.refreshOn && - isTokenExpired(cachedAccessToken.refreshOn, 0)) { - // must refresh (in the background) due to the refresh_in value - lastCacheOutcome = CacheOutcome.PROACTIVELY_REFRESHED; - // don't throw ClientAuthError.createRefreshRequiredError(), return cached token instead - } - const environment = request.authority || this.authority.getPreferredCache(); - const cacheRecord = { - account: this.cacheManager.getAccount(this.cacheManager.generateAccountKey(request.account), request.correlationId), - accessToken: cachedAccessToken, - idToken: this.cacheManager.getIdToken(request.account, request.correlationId, tokenKeys, requestTenantId, this.performanceClient), - refreshToken: null, - appMetadata: this.cacheManager.readAppMetadataFromCache(environment), - }; - this.setCacheOutcome(lastCacheOutcome, request.correlationId); - if (this.config.serverTelemetryManager) { - this.config.serverTelemetryManager.incrementCacheHits(); - } - return [ - await invokeAsync(this.generateResultFromCacheRecord.bind(this), PerformanceEvents.SilentFlowClientGenerateResultFromCacheRecord, this.logger, this.performanceClient, request.correlationId)(cacheRecord, request), - lastCacheOutcome, - ]; - } - setCacheOutcome(cacheOutcome, correlationId) { - this.serverTelemetryManager?.setCacheOutcome(cacheOutcome); - this.performanceClient?.addFields({ - cacheOutcome: cacheOutcome, - }, correlationId); - if (cacheOutcome !== CacheOutcome.NOT_APPLICABLE) { - this.logger.info(`Token refresh is required due to cache outcome: ${cacheOutcome}`); - } - } - /** - * Helper function to build response object from the CacheRecord - * @param cacheRecord - */ - async generateResultFromCacheRecord(cacheRecord, request) { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.SilentFlowClientGenerateResultFromCacheRecord, request.correlationId); - let idTokenClaims; - if (cacheRecord.idToken) { - idTokenClaims = extractTokenClaims(cacheRecord.idToken.secret, this.config.cryptoInterface.base64Decode); - } - // token max_age check - if (request.maxAge || request.maxAge === 0) { - const authTime = idTokenClaims?.auth_time; - if (!authTime) { - throw createClientAuthError(authTimeNotFound); - } - checkMaxAge(authTime, request.maxAge); - } - return ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, cacheRecord, true, request, idTokenClaims); - } -} - -export { SilentFlowClient }; -//# sourceMappingURL=SilentFlowClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/config/ClientConfiguration.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/config/ClientConfiguration.mjs deleted file mode 100644 index 8a91ccd7..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/config/ClientConfiguration.mjs +++ /dev/null @@ -1,113 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { DEFAULT_CRYPTO_IMPLEMENTATION } from '../crypto/ICrypto.mjs'; -import { LogLevel, Logger } from '../logger/Logger.mjs'; -import { DEFAULT_TOKEN_RENEWAL_OFFSET_SEC, Constants } from '../utils/Constants.mjs'; -import { version } from '../packageMetadata.mjs'; -import { AzureCloudInstance } from '../authority/AuthorityOptions.mjs'; -import { DefaultStorageClass } from '../cache/CacheManager.mjs'; -import { ProtocolMode } from '../authority/ProtocolMode.mjs'; -import { createClientAuthError } from '../error/ClientAuthError.mjs'; -import { StubPerformanceClient } from '../telemetry/performance/StubPerformanceClient.mjs'; -import { methodNotImplemented } from '../error/ClientAuthErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const DEFAULT_SYSTEM_OPTIONS = { - tokenRenewalOffsetSeconds: DEFAULT_TOKEN_RENEWAL_OFFSET_SEC, - preventCorsPreflight: false, -}; -const DEFAULT_LOGGER_IMPLEMENTATION = { - loggerCallback: () => { - // allow users to not set loggerCallback - }, - piiLoggingEnabled: false, - logLevel: LogLevel.Info, - correlationId: Constants.EMPTY_STRING, -}; -const DEFAULT_CACHE_OPTIONS = { - claimsBasedCachingEnabled: false, -}; -const DEFAULT_NETWORK_IMPLEMENTATION = { - async sendGetRequestAsync() { - throw createClientAuthError(methodNotImplemented); - }, - async sendPostRequestAsync() { - throw createClientAuthError(methodNotImplemented); - }, -}; -const DEFAULT_LIBRARY_INFO = { - sku: Constants.SKU, - version: version, - cpu: Constants.EMPTY_STRING, - os: Constants.EMPTY_STRING, -}; -const DEFAULT_CLIENT_CREDENTIALS = { - clientSecret: Constants.EMPTY_STRING, - clientAssertion: undefined, -}; -const DEFAULT_AZURE_CLOUD_OPTIONS = { - azureCloudInstance: AzureCloudInstance.None, - tenant: `${Constants.DEFAULT_COMMON_TENANT}`, -}; -const DEFAULT_TELEMETRY_OPTIONS = { - application: { - appName: "", - appVersion: "", - }, -}; -/** - * Function that sets the default options when not explicitly configured from app developer - * - * @param Configuration - * - * @returns Configuration - */ -function buildClientConfiguration({ authOptions: userAuthOptions, systemOptions: userSystemOptions, loggerOptions: userLoggerOption, cacheOptions: userCacheOptions, storageInterface: storageImplementation, networkInterface: networkImplementation, cryptoInterface: cryptoImplementation, clientCredentials: clientCredentials, libraryInfo: libraryInfo, telemetry: telemetry, serverTelemetryManager: serverTelemetryManager, persistencePlugin: persistencePlugin, serializableCache: serializableCache, }) { - const loggerOptions = { - ...DEFAULT_LOGGER_IMPLEMENTATION, - ...userLoggerOption, - }; - return { - authOptions: buildAuthOptions(userAuthOptions), - systemOptions: { ...DEFAULT_SYSTEM_OPTIONS, ...userSystemOptions }, - loggerOptions: loggerOptions, - cacheOptions: { ...DEFAULT_CACHE_OPTIONS, ...userCacheOptions }, - storageInterface: storageImplementation || - new DefaultStorageClass(userAuthOptions.clientId, DEFAULT_CRYPTO_IMPLEMENTATION, new Logger(loggerOptions), new StubPerformanceClient()), - networkInterface: networkImplementation || DEFAULT_NETWORK_IMPLEMENTATION, - cryptoInterface: cryptoImplementation || DEFAULT_CRYPTO_IMPLEMENTATION, - clientCredentials: clientCredentials || DEFAULT_CLIENT_CREDENTIALS, - libraryInfo: { ...DEFAULT_LIBRARY_INFO, ...libraryInfo }, - telemetry: { ...DEFAULT_TELEMETRY_OPTIONS, ...telemetry }, - serverTelemetryManager: serverTelemetryManager || null, - persistencePlugin: persistencePlugin || null, - serializableCache: serializableCache || null, - }; -} -/** - * Construct authoptions from the client and platform passed values - * @param authOptions - */ -function buildAuthOptions(authOptions) { - return { - clientCapabilities: [], - azureCloudOptions: DEFAULT_AZURE_CLOUD_OPTIONS, - skipAuthorityMetadataCache: false, - instanceAware: false, - encodeExtraQueryParams: false, - ...authOptions, - }; -} -/** - * Returns true if config has protocolMode set to ProtocolMode.OIDC, false otherwise - * @param ClientConfiguration - */ -function isOidcProtocolMode(config) { - return (config.authOptions.authority.options.protocolMode === ProtocolMode.OIDC); -} - -export { DEFAULT_SYSTEM_OPTIONS, buildClientConfiguration, isOidcProtocolMode }; -//# sourceMappingURL=ClientConfiguration.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/constants/AADServerParamKeys.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/constants/AADServerParamKeys.mjs deleted file mode 100644 index d084642f..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/constants/AADServerParamKeys.mjs +++ /dev/null @@ -1,67 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const CLIENT_ID = "client_id"; -const REDIRECT_URI = "redirect_uri"; -const RESPONSE_TYPE = "response_type"; -const RESPONSE_MODE = "response_mode"; -const GRANT_TYPE = "grant_type"; -const CLAIMS = "claims"; -const SCOPE = "scope"; -const ERROR = "error"; -const ERROR_DESCRIPTION = "error_description"; -const ACCESS_TOKEN = "access_token"; -const ID_TOKEN = "id_token"; -const REFRESH_TOKEN = "refresh_token"; -const EXPIRES_IN = "expires_in"; -const REFRESH_TOKEN_EXPIRES_IN = "refresh_token_expires_in"; -const STATE = "state"; -const NONCE = "nonce"; -const PROMPT = "prompt"; -const SESSION_STATE = "session_state"; -const CLIENT_INFO = "client_info"; -const CODE = "code"; -const CODE_CHALLENGE = "code_challenge"; -const CODE_CHALLENGE_METHOD = "code_challenge_method"; -const CODE_VERIFIER = "code_verifier"; -const CLIENT_REQUEST_ID = "client-request-id"; -const X_CLIENT_SKU = "x-client-SKU"; -const X_CLIENT_VER = "x-client-VER"; -const X_CLIENT_OS = "x-client-OS"; -const X_CLIENT_CPU = "x-client-CPU"; -const X_CLIENT_CURR_TELEM = "x-client-current-telemetry"; -const X_CLIENT_LAST_TELEM = "x-client-last-telemetry"; -const X_MS_LIB_CAPABILITY = "x-ms-lib-capability"; -const X_APP_NAME = "x-app-name"; -const X_APP_VER = "x-app-ver"; -const POST_LOGOUT_URI = "post_logout_redirect_uri"; -const ID_TOKEN_HINT = "id_token_hint"; -const DEVICE_CODE = "device_code"; -const CLIENT_SECRET = "client_secret"; -const CLIENT_ASSERTION = "client_assertion"; -const CLIENT_ASSERTION_TYPE = "client_assertion_type"; -const TOKEN_TYPE = "token_type"; -const REQ_CNF = "req_cnf"; -const OBO_ASSERTION = "assertion"; -const REQUESTED_TOKEN_USE = "requested_token_use"; -const ON_BEHALF_OF = "on_behalf_of"; -const FOCI = "foci"; -const CCS_HEADER = "X-AnchorMailbox"; -const RETURN_SPA_CODE = "return_spa_code"; -const NATIVE_BROKER = "nativebroker"; -const LOGOUT_HINT = "logout_hint"; -const SID = "sid"; -const LOGIN_HINT = "login_hint"; -const DOMAIN_HINT = "domain_hint"; -const X_CLIENT_EXTRA_SKU = "x-client-xtra-sku"; -const BROKER_CLIENT_ID = "brk_client_id"; -const BROKER_REDIRECT_URI = "brk_redirect_uri"; -const INSTANCE_AWARE = "instance_aware"; -const EAR_JWK = "ear_jwk"; -const EAR_JWE_CRYPTO = "ear_jwe_crypto"; - -export { ACCESS_TOKEN, BROKER_CLIENT_ID, BROKER_REDIRECT_URI, CCS_HEADER, CLAIMS, CLIENT_ASSERTION, CLIENT_ASSERTION_TYPE, CLIENT_ID, CLIENT_INFO, CLIENT_REQUEST_ID, CLIENT_SECRET, CODE, CODE_CHALLENGE, CODE_CHALLENGE_METHOD, CODE_VERIFIER, DEVICE_CODE, DOMAIN_HINT, EAR_JWE_CRYPTO, EAR_JWK, ERROR, ERROR_DESCRIPTION, EXPIRES_IN, FOCI, GRANT_TYPE, ID_TOKEN, ID_TOKEN_HINT, INSTANCE_AWARE, LOGIN_HINT, LOGOUT_HINT, NATIVE_BROKER, NONCE, OBO_ASSERTION, ON_BEHALF_OF, POST_LOGOUT_URI, PROMPT, REDIRECT_URI, REFRESH_TOKEN, REFRESH_TOKEN_EXPIRES_IN, REQUESTED_TOKEN_USE, REQ_CNF, RESPONSE_MODE, RESPONSE_TYPE, RETURN_SPA_CODE, SCOPE, SESSION_STATE, SID, STATE, TOKEN_TYPE, X_APP_NAME, X_APP_VER, X_CLIENT_CPU, X_CLIENT_CURR_TELEM, X_CLIENT_EXTRA_SKU, X_CLIENT_LAST_TELEM, X_CLIENT_OS, X_CLIENT_SKU, X_CLIENT_VER, X_MS_LIB_CAPABILITY }; -//# sourceMappingURL=AADServerParamKeys.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/crypto/ICrypto.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/crypto/ICrypto.mjs deleted file mode 100644 index 562c4c41..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/crypto/ICrypto.mjs +++ /dev/null @@ -1,44 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { createClientAuthError } from '../error/ClientAuthError.mjs'; -import { methodNotImplemented } from '../error/ClientAuthErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const DEFAULT_CRYPTO_IMPLEMENTATION = { - createNewGuid: () => { - throw createClientAuthError(methodNotImplemented); - }, - base64Decode: () => { - throw createClientAuthError(methodNotImplemented); - }, - base64Encode: () => { - throw createClientAuthError(methodNotImplemented); - }, - base64UrlEncode: () => { - throw createClientAuthError(methodNotImplemented); - }, - encodeKid: () => { - throw createClientAuthError(methodNotImplemented); - }, - async getPublicKeyThumbprint() { - throw createClientAuthError(methodNotImplemented); - }, - async removeTokenBindingKey() { - throw createClientAuthError(methodNotImplemented); - }, - async clearKeystore() { - throw createClientAuthError(methodNotImplemented); - }, - async signJwt() { - throw createClientAuthError(methodNotImplemented); - }, - async hashString() { - throw createClientAuthError(methodNotImplemented); - }, -}; - -export { DEFAULT_CRYPTO_IMPLEMENTATION }; -//# sourceMappingURL=ICrypto.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/crypto/PopTokenGenerator.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/crypto/PopTokenGenerator.mjs deleted file mode 100644 index 2def7f2b..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/crypto/PopTokenGenerator.mjs +++ /dev/null @@ -1,89 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { nowSeconds } from '../utils/TimeUtils.mjs'; -import { UrlString } from '../url/UrlString.mjs'; -import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs'; -import { invokeAsync } from '../utils/FunctionWrappers.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const KeyLocation = { - SW: "sw"}; -/** @internal */ -class PopTokenGenerator { - constructor(cryptoUtils, performanceClient) { - this.cryptoUtils = cryptoUtils; - this.performanceClient = performanceClient; - } - /** - * Generates the req_cnf validated at the RP in the POP protocol for SHR parameters - * and returns an object containing the keyid, the full req_cnf string and the req_cnf string hash - * @param request - * @returns - */ - async generateCnf(request, logger) { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.PopTokenGenerateCnf, request.correlationId); - const reqCnf = await invokeAsync(this.generateKid.bind(this), PerformanceEvents.PopTokenGenerateCnf, logger, this.performanceClient, request.correlationId)(request); - const reqCnfString = this.cryptoUtils.base64UrlEncode(JSON.stringify(reqCnf)); - return { - kid: reqCnf.kid, - reqCnfString, - }; - } - /** - * Generates key_id for a SHR token request - * @param request - * @returns - */ - async generateKid(request) { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.PopTokenGenerateKid, request.correlationId); - const kidThumbprint = await this.cryptoUtils.getPublicKeyThumbprint(request); - return { - kid: kidThumbprint, - xms_ksl: KeyLocation.SW, - }; - } - /** - * Signs the POP access_token with the local generated key-pair - * @param accessToken - * @param request - * @returns - */ - async signPopToken(accessToken, keyId, request) { - return this.signPayload(accessToken, keyId, request); - } - /** - * Utility function to generate the signed JWT for an access_token - * @param payload - * @param kid - * @param request - * @param claims - * @returns - */ - async signPayload(payload, keyId, request, claims) { - // Deconstruct request to extract SHR parameters - const { resourceRequestMethod, resourceRequestUri, shrClaims, shrNonce, shrOptions, } = request; - const resourceUrlString = resourceRequestUri - ? new UrlString(resourceRequestUri) - : undefined; - const resourceUrlComponents = resourceUrlString?.getUrlComponents(); - return this.cryptoUtils.signJwt({ - at: payload, - ts: nowSeconds(), - m: resourceRequestMethod?.toUpperCase(), - u: resourceUrlComponents?.HostNameAndPort, - nonce: shrNonce || this.cryptoUtils.createNewGuid(), - p: resourceUrlComponents?.AbsolutePath, - q: resourceUrlComponents?.QueryString - ? [[], resourceUrlComponents.QueryString] - : undefined, - client_claims: shrClaims || undefined, - ...claims, - }, keyId, shrOptions, request.correlationId); - } -} - -export { PopTokenGenerator }; -//# sourceMappingURL=PopTokenGenerator.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/AuthError.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/AuthError.mjs deleted file mode 100644 index f92abafc..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/error/AuthError.mjs +++ /dev/null @@ -1,56 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { Constants } from '../utils/Constants.mjs'; -import { postRequestFailed, unexpectedError } from './AuthErrorCodes.mjs'; -import * as AuthErrorCodes from './AuthErrorCodes.mjs'; -export { AuthErrorCodes }; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const AuthErrorMessages = { - [unexpectedError]: "Unexpected error in authentication.", - [postRequestFailed]: "Post request failed from the network, could be a 4xx/5xx or a network unavailability. Please check the exact error code for details.", -}; -/** - * AuthErrorMessage class containing string constants used by error codes and messages. - * @deprecated Use AuthErrorCodes instead - */ -const AuthErrorMessage = { - unexpectedError: { - code: unexpectedError, - desc: AuthErrorMessages[unexpectedError], - }, - postRequestFailed: { - code: postRequestFailed, - desc: AuthErrorMessages[postRequestFailed], - }, -}; -/** - * General error class thrown by the MSAL.js library. - */ -class AuthError extends Error { - constructor(errorCode, errorMessage, suberror) { - const errorString = errorMessage - ? `${errorCode}: ${errorMessage}` - : errorCode; - super(errorString); - Object.setPrototypeOf(this, AuthError.prototype); - this.errorCode = errorCode || Constants.EMPTY_STRING; - this.errorMessage = errorMessage || Constants.EMPTY_STRING; - this.subError = suberror || Constants.EMPTY_STRING; - this.name = "AuthError"; - } - setCorrelationId(correlationId) { - this.correlationId = correlationId; - } -} -function createAuthError(code, additionalMessage) { - return new AuthError(code, additionalMessage - ? `${AuthErrorMessages[code]} ${additionalMessage}` - : AuthErrorMessages[code]); -} - -export { AuthError, AuthErrorMessage, AuthErrorMessages, createAuthError }; -//# sourceMappingURL=AuthError.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/AuthErrorCodes.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/AuthErrorCodes.mjs deleted file mode 100644 index 4da8c460..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/error/AuthErrorCodes.mjs +++ /dev/null @@ -1,14 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * AuthErrorMessage class containing string constants used by error codes and messages. - */ -const unexpectedError = "unexpected_error"; -const postRequestFailed = "post_request_failed"; - -export { postRequestFailed, unexpectedError }; -//# sourceMappingURL=AuthErrorCodes.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/CacheError.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/CacheError.mjs deleted file mode 100644 index 95bd233e..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/error/CacheError.mjs +++ /dev/null @@ -1,52 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { AuthError } from './AuthError.mjs'; -import { cacheErrorUnknown, cacheQuotaExceeded } from './CacheErrorCodes.mjs'; -import * as CacheErrorCodes from './CacheErrorCodes.mjs'; -export { CacheErrorCodes }; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const CacheErrorMessages = { - [cacheQuotaExceeded]: "Exceeded cache storage capacity.", - [cacheErrorUnknown]: "Unexpected error occurred when using cache storage.", -}; -/** - * Error thrown when there is an error with the cache - */ -class CacheError extends AuthError { - constructor(errorCode, errorMessage) { - const message = errorMessage || - (CacheErrorMessages[errorCode] - ? CacheErrorMessages[errorCode] - : CacheErrorMessages[cacheErrorUnknown]); - super(`${errorCode}: ${message}`); - Object.setPrototypeOf(this, CacheError.prototype); - this.name = "CacheError"; - this.errorCode = errorCode; - this.errorMessage = message; - } -} -/** - * Helper function to wrap browser errors in a CacheError object - * @param e - * @returns - */ -function createCacheError(e) { - if (!(e instanceof Error)) { - return new CacheError(cacheErrorUnknown); - } - if (e.name === "QuotaExceededError" || - e.name === "NS_ERROR_DOM_QUOTA_REACHED" || - e.message.includes("exceeded the quota")) { - return new CacheError(cacheQuotaExceeded); - } - else { - return new CacheError(e.name, e.message); - } -} - -export { CacheError, CacheErrorMessages, createCacheError }; -//# sourceMappingURL=CacheError.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/CacheErrorCodes.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/CacheErrorCodes.mjs deleted file mode 100644 index f8aa9244..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/error/CacheErrorCodes.mjs +++ /dev/null @@ -1,11 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const cacheQuotaExceeded = "cache_quota_exceeded"; -const cacheErrorUnknown = "cache_error_unknown"; - -export { cacheErrorUnknown, cacheQuotaExceeded }; -//# sourceMappingURL=CacheErrorCodes.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientAuthError.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientAuthError.mjs deleted file mode 100644 index 2a7dc322..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientAuthError.mjs +++ /dev/null @@ -1,259 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { AuthError } from './AuthError.mjs'; -import { nestedAppAuthBridgeDisabled, missingTenantIdError, userCanceled, noNetworkConnectivity, keyIdMissing, endSessionEndpointNotSupported, bindingKeyNotRemoved, authorizationCodeMissingFromServerResponse, tokenClaimsCnfRequiredForSignedJwt, userTimeoutReached, tokenRefreshRequired, invalidClientCredential, invalidAssertion, unexpectedCredentialType, noCryptoObject, noAccountFound, invalidCacheEnvironment, invalidCacheRecord, noAccountInSilentRequest, deviceCodeUnknownError, deviceCodeExpired, deviceCodePollingCancelled, emptyInputScopeSet, cannotAppendScopeSet, cannotRemoveEmptyScope, requestCannotBeMade, multipleMatchingAppMetadata, multipleMatchingAccounts, multipleMatchingTokens, maxAgeTranspired, authTimeNotFound, nonceMismatch, stateNotFound, stateMismatch, invalidState, hashNotDeserialized, openIdConfigError, networkError, endpointResolutionError, nullOrEmptyToken, tokenParsingError, clientInfoEmptyError, clientInfoDecodingError, methodNotImplemented } from './ClientAuthErrorCodes.mjs'; -import * as ClientAuthErrorCodes from './ClientAuthErrorCodes.mjs'; -export { ClientAuthErrorCodes }; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * ClientAuthErrorMessage class containing string constants used by error codes and messages. - */ -const ClientAuthErrorMessages = { - [clientInfoDecodingError]: "The client info could not be parsed/decoded correctly", - [clientInfoEmptyError]: "The client info was empty", - [tokenParsingError]: "Token cannot be parsed", - [nullOrEmptyToken]: "The token is null or empty", - [endpointResolutionError]: "Endpoints cannot be resolved", - [networkError]: "Network request failed", - [openIdConfigError]: "Could not retrieve endpoints. Check your authority and verify the .well-known/openid-configuration endpoint returns the required endpoints.", - [hashNotDeserialized]: "The hash parameters could not be deserialized", - [invalidState]: "State was not the expected format", - [stateMismatch]: "State mismatch error", - [stateNotFound]: "State not found", - [nonceMismatch]: "Nonce mismatch error", - [authTimeNotFound]: "Max Age was requested and the ID token is missing the auth_time variable." + - " auth_time is an optional claim and is not enabled by default - it must be enabled." + - " See https://aka.ms/msaljs/optional-claims for more information.", - [maxAgeTranspired]: "Max Age is set to 0, or too much time has elapsed since the last end-user authentication.", - [multipleMatchingTokens]: "The cache contains multiple tokens satisfying the requirements. " + - "Call AcquireToken again providing more requirements such as authority or account.", - [multipleMatchingAccounts]: "The cache contains multiple accounts satisfying the given parameters. Please pass more info to obtain the correct account", - [multipleMatchingAppMetadata]: "The cache contains multiple appMetadata satisfying the given parameters. Please pass more info to obtain the correct appMetadata", - [requestCannotBeMade]: "Token request cannot be made without authorization code or refresh token.", - [cannotRemoveEmptyScope]: "Cannot remove null or empty scope from ScopeSet", - [cannotAppendScopeSet]: "Cannot append ScopeSet", - [emptyInputScopeSet]: "Empty input ScopeSet cannot be processed", - [deviceCodePollingCancelled]: "Caller has cancelled token endpoint polling during device code flow by setting DeviceCodeRequest.cancel = true.", - [deviceCodeExpired]: "Device code is expired.", - [deviceCodeUnknownError]: "Device code stopped polling for unknown reasons.", - [noAccountInSilentRequest]: "Please pass an account object, silent flow is not supported without account information", - [invalidCacheRecord]: "Cache record object was null or undefined.", - [invalidCacheEnvironment]: "Invalid environment when attempting to create cache entry", - [noAccountFound]: "No account found in cache for given key.", - [noCryptoObject]: "No crypto object detected.", - [unexpectedCredentialType]: "Unexpected credential type.", - [invalidAssertion]: "Client assertion must meet requirements described in https://tools.ietf.org/html/rfc7515", - [invalidClientCredential]: "Client credential (secret, certificate, or assertion) must not be empty when creating a confidential client. An application should at most have one credential", - [tokenRefreshRequired]: "Cannot return token from cache because it must be refreshed. This may be due to one of the following reasons: forceRefresh parameter is set to true, claims have been requested, there is no cached access token or it is expired.", - [userTimeoutReached]: "User defined timeout for device code polling reached", - [tokenClaimsCnfRequiredForSignedJwt]: "Cannot generate a POP jwt if the token_claims are not populated", - [authorizationCodeMissingFromServerResponse]: "Server response does not contain an authorization code to proceed", - [bindingKeyNotRemoved]: "Could not remove the credential's binding key from storage.", - [endSessionEndpointNotSupported]: "The provided authority does not support logout", - [keyIdMissing]: "A keyId value is missing from the requested bound token's cache record and is required to match the token to it's stored binding key.", - [noNetworkConnectivity]: "No network connectivity. Check your internet connection.", - [userCanceled]: "User cancelled the flow.", - [missingTenantIdError]: "A tenant id - not common, organizations, or consumers - must be specified when using the client_credentials flow.", - [methodNotImplemented]: "This method has not been implemented", - [nestedAppAuthBridgeDisabled]: "The nested app auth bridge is disabled", -}; -/** - * String constants used by error codes and messages. - * @deprecated Use ClientAuthErrorCodes instead - */ -const ClientAuthErrorMessage = { - clientInfoDecodingError: { - code: clientInfoDecodingError, - desc: ClientAuthErrorMessages[clientInfoDecodingError], - }, - clientInfoEmptyError: { - code: clientInfoEmptyError, - desc: ClientAuthErrorMessages[clientInfoEmptyError], - }, - tokenParsingError: { - code: tokenParsingError, - desc: ClientAuthErrorMessages[tokenParsingError], - }, - nullOrEmptyToken: { - code: nullOrEmptyToken, - desc: ClientAuthErrorMessages[nullOrEmptyToken], - }, - endpointResolutionError: { - code: endpointResolutionError, - desc: ClientAuthErrorMessages[endpointResolutionError], - }, - networkError: { - code: networkError, - desc: ClientAuthErrorMessages[networkError], - }, - unableToGetOpenidConfigError: { - code: openIdConfigError, - desc: ClientAuthErrorMessages[openIdConfigError], - }, - hashNotDeserialized: { - code: hashNotDeserialized, - desc: ClientAuthErrorMessages[hashNotDeserialized], - }, - invalidStateError: { - code: invalidState, - desc: ClientAuthErrorMessages[invalidState], - }, - stateMismatchError: { - code: stateMismatch, - desc: ClientAuthErrorMessages[stateMismatch], - }, - stateNotFoundError: { - code: stateNotFound, - desc: ClientAuthErrorMessages[stateNotFound], - }, - nonceMismatchError: { - code: nonceMismatch, - desc: ClientAuthErrorMessages[nonceMismatch], - }, - authTimeNotFoundError: { - code: authTimeNotFound, - desc: ClientAuthErrorMessages[authTimeNotFound], - }, - maxAgeTranspired: { - code: maxAgeTranspired, - desc: ClientAuthErrorMessages[maxAgeTranspired], - }, - multipleMatchingTokens: { - code: multipleMatchingTokens, - desc: ClientAuthErrorMessages[multipleMatchingTokens], - }, - multipleMatchingAccounts: { - code: multipleMatchingAccounts, - desc: ClientAuthErrorMessages[multipleMatchingAccounts], - }, - multipleMatchingAppMetadata: { - code: multipleMatchingAppMetadata, - desc: ClientAuthErrorMessages[multipleMatchingAppMetadata], - }, - tokenRequestCannotBeMade: { - code: requestCannotBeMade, - desc: ClientAuthErrorMessages[requestCannotBeMade], - }, - removeEmptyScopeError: { - code: cannotRemoveEmptyScope, - desc: ClientAuthErrorMessages[cannotRemoveEmptyScope], - }, - appendScopeSetError: { - code: cannotAppendScopeSet, - desc: ClientAuthErrorMessages[cannotAppendScopeSet], - }, - emptyInputScopeSetError: { - code: emptyInputScopeSet, - desc: ClientAuthErrorMessages[emptyInputScopeSet], - }, - DeviceCodePollingCancelled: { - code: deviceCodePollingCancelled, - desc: ClientAuthErrorMessages[deviceCodePollingCancelled], - }, - DeviceCodeExpired: { - code: deviceCodeExpired, - desc: ClientAuthErrorMessages[deviceCodeExpired], - }, - DeviceCodeUnknownError: { - code: deviceCodeUnknownError, - desc: ClientAuthErrorMessages[deviceCodeUnknownError], - }, - NoAccountInSilentRequest: { - code: noAccountInSilentRequest, - desc: ClientAuthErrorMessages[noAccountInSilentRequest], - }, - invalidCacheRecord: { - code: invalidCacheRecord, - desc: ClientAuthErrorMessages[invalidCacheRecord], - }, - invalidCacheEnvironment: { - code: invalidCacheEnvironment, - desc: ClientAuthErrorMessages[invalidCacheEnvironment], - }, - noAccountFound: { - code: noAccountFound, - desc: ClientAuthErrorMessages[noAccountFound], - }, - noCryptoObj: { - code: noCryptoObject, - desc: ClientAuthErrorMessages[noCryptoObject], - }, - unexpectedCredentialType: { - code: unexpectedCredentialType, - desc: ClientAuthErrorMessages[unexpectedCredentialType], - }, - invalidAssertion: { - code: invalidAssertion, - desc: ClientAuthErrorMessages[invalidAssertion], - }, - invalidClientCredential: { - code: invalidClientCredential, - desc: ClientAuthErrorMessages[invalidClientCredential], - }, - tokenRefreshRequired: { - code: tokenRefreshRequired, - desc: ClientAuthErrorMessages[tokenRefreshRequired], - }, - userTimeoutReached: { - code: userTimeoutReached, - desc: ClientAuthErrorMessages[userTimeoutReached], - }, - tokenClaimsRequired: { - code: tokenClaimsCnfRequiredForSignedJwt, - desc: ClientAuthErrorMessages[tokenClaimsCnfRequiredForSignedJwt], - }, - noAuthorizationCodeFromServer: { - code: authorizationCodeMissingFromServerResponse, - desc: ClientAuthErrorMessages[authorizationCodeMissingFromServerResponse], - }, - bindingKeyNotRemovedError: { - code: bindingKeyNotRemoved, - desc: ClientAuthErrorMessages[bindingKeyNotRemoved], - }, - logoutNotSupported: { - code: endSessionEndpointNotSupported, - desc: ClientAuthErrorMessages[endSessionEndpointNotSupported], - }, - keyIdMissing: { - code: keyIdMissing, - desc: ClientAuthErrorMessages[keyIdMissing], - }, - noNetworkConnectivity: { - code: noNetworkConnectivity, - desc: ClientAuthErrorMessages[noNetworkConnectivity], - }, - userCanceledError: { - code: userCanceled, - desc: ClientAuthErrorMessages[userCanceled], - }, - missingTenantIdError: { - code: missingTenantIdError, - desc: ClientAuthErrorMessages[missingTenantIdError], - }, - nestedAppAuthBridgeDisabled: { - code: nestedAppAuthBridgeDisabled, - desc: ClientAuthErrorMessages[nestedAppAuthBridgeDisabled], - }, -}; -/** - * Error thrown when there is an error in the client code running on the browser. - */ -class ClientAuthError extends AuthError { - constructor(errorCode, additionalMessage) { - super(errorCode, additionalMessage - ? `${ClientAuthErrorMessages[errorCode]}: ${additionalMessage}` - : ClientAuthErrorMessages[errorCode]); - this.name = "ClientAuthError"; - Object.setPrototypeOf(this, ClientAuthError.prototype); - } -} -function createClientAuthError(errorCode, additionalMessage) { - return new ClientAuthError(errorCode, additionalMessage); -} - -export { ClientAuthError, ClientAuthErrorMessage, ClientAuthErrorMessages, createClientAuthError }; -//# sourceMappingURL=ClientAuthError.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientAuthErrorCodes.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientAuthErrorCodes.mjs deleted file mode 100644 index 745c8d20..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientAuthErrorCodes.mjs +++ /dev/null @@ -1,53 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const clientInfoDecodingError = "client_info_decoding_error"; -const clientInfoEmptyError = "client_info_empty_error"; -const tokenParsingError = "token_parsing_error"; -const nullOrEmptyToken = "null_or_empty_token"; -const endpointResolutionError = "endpoints_resolution_error"; -const networkError = "network_error"; -const openIdConfigError = "openid_config_error"; -const hashNotDeserialized = "hash_not_deserialized"; -const invalidState = "invalid_state"; -const stateMismatch = "state_mismatch"; -const stateNotFound = "state_not_found"; -const nonceMismatch = "nonce_mismatch"; -const authTimeNotFound = "auth_time_not_found"; -const maxAgeTranspired = "max_age_transpired"; -const multipleMatchingTokens = "multiple_matching_tokens"; -const multipleMatchingAccounts = "multiple_matching_accounts"; -const multipleMatchingAppMetadata = "multiple_matching_appMetadata"; -const requestCannotBeMade = "request_cannot_be_made"; -const cannotRemoveEmptyScope = "cannot_remove_empty_scope"; -const cannotAppendScopeSet = "cannot_append_scopeset"; -const emptyInputScopeSet = "empty_input_scopeset"; -const deviceCodePollingCancelled = "device_code_polling_cancelled"; -const deviceCodeExpired = "device_code_expired"; -const deviceCodeUnknownError = "device_code_unknown_error"; -const noAccountInSilentRequest = "no_account_in_silent_request"; -const invalidCacheRecord = "invalid_cache_record"; -const invalidCacheEnvironment = "invalid_cache_environment"; -const noAccountFound = "no_account_found"; -const noCryptoObject = "no_crypto_object"; -const unexpectedCredentialType = "unexpected_credential_type"; -const invalidAssertion = "invalid_assertion"; -const invalidClientCredential = "invalid_client_credential"; -const tokenRefreshRequired = "token_refresh_required"; -const userTimeoutReached = "user_timeout_reached"; -const tokenClaimsCnfRequiredForSignedJwt = "token_claims_cnf_required_for_signedjwt"; -const authorizationCodeMissingFromServerResponse = "authorization_code_missing_from_server_response"; -const bindingKeyNotRemoved = "binding_key_not_removed"; -const endSessionEndpointNotSupported = "end_session_endpoint_not_supported"; -const keyIdMissing = "key_id_missing"; -const noNetworkConnectivity = "no_network_connectivity"; -const userCanceled = "user_canceled"; -const missingTenantIdError = "missing_tenant_id_error"; -const methodNotImplemented = "method_not_implemented"; -const nestedAppAuthBridgeDisabled = "nested_app_auth_bridge_disabled"; - -export { authTimeNotFound, authorizationCodeMissingFromServerResponse, bindingKeyNotRemoved, cannotAppendScopeSet, cannotRemoveEmptyScope, clientInfoDecodingError, clientInfoEmptyError, deviceCodeExpired, deviceCodePollingCancelled, deviceCodeUnknownError, emptyInputScopeSet, endSessionEndpointNotSupported, endpointResolutionError, hashNotDeserialized, invalidAssertion, invalidCacheEnvironment, invalidCacheRecord, invalidClientCredential, invalidState, keyIdMissing, maxAgeTranspired, methodNotImplemented, missingTenantIdError, multipleMatchingAccounts, multipleMatchingAppMetadata, multipleMatchingTokens, nestedAppAuthBridgeDisabled, networkError, noAccountFound, noAccountInSilentRequest, noCryptoObject, noNetworkConnectivity, nonceMismatch, nullOrEmptyToken, openIdConfigError, requestCannotBeMade, stateMismatch, stateNotFound, tokenClaimsCnfRequiredForSignedJwt, tokenParsingError, tokenRefreshRequired, unexpectedCredentialType, userCanceled, userTimeoutReached }; -//# sourceMappingURL=ClientAuthErrorCodes.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientConfigurationError.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientConfigurationError.mjs deleted file mode 100644 index 960d4d8c..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientConfigurationError.mjs +++ /dev/null @@ -1,150 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { AuthError } from './AuthError.mjs'; -import { invalidRequestMethodForEAR, invalidAuthorizePostBodyParameters, authorityMismatch, cannotAllowPlatformBroker, cannotSetOIDCOptions, invalidAuthenticationHeader, missingNonceAuthenticationHeader, missingSshKid, missingSshJwk, untrustedAuthority, invalidAuthorityMetadata, invalidCloudDiscoveryMetadata, pkceParamsMissing, invalidCodeChallengeMethod, logoutRequestEmpty, tokenRequestEmpty, invalidClaims, emptyInputScopesError, urlEmptyError, urlParseError, authorityUriInsecure, claimsRequestParsingError, redirectUriEmpty } from './ClientConfigurationErrorCodes.mjs'; -import * as ClientConfigurationErrorCodes from './ClientConfigurationErrorCodes.mjs'; -export { ClientConfigurationErrorCodes }; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const ClientConfigurationErrorMessages = { - [redirectUriEmpty]: "A redirect URI is required for all calls, and none has been set.", - [claimsRequestParsingError]: "Could not parse the given claims request object.", - [authorityUriInsecure]: "Authority URIs must use https. Please see here for valid authority configuration options: https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-js-initializing-client-applications#configuration-options", - [urlParseError]: "URL could not be parsed into appropriate segments.", - [urlEmptyError]: "URL was empty or null.", - [emptyInputScopesError]: "Scopes cannot be passed as null, undefined or empty array because they are required to obtain an access token.", - [invalidClaims]: "Given claims parameter must be a stringified JSON object.", - [tokenRequestEmpty]: "Token request was empty and not found in cache.", - [logoutRequestEmpty]: "The logout request was null or undefined.", - [invalidCodeChallengeMethod]: 'code_challenge_method passed is invalid. Valid values are "plain" and "S256".', - [pkceParamsMissing]: "Both params: code_challenge and code_challenge_method are to be passed if to be sent in the request", - [invalidCloudDiscoveryMetadata]: "Invalid cloudDiscoveryMetadata provided. Must be a stringified JSON object containing tenant_discovery_endpoint and metadata fields", - [invalidAuthorityMetadata]: "Invalid authorityMetadata provided. Must by a stringified JSON object containing authorization_endpoint, token_endpoint, issuer fields.", - [untrustedAuthority]: "The provided authority is not a trusted authority. Please include this authority in the knownAuthorities config parameter.", - [missingSshJwk]: "Missing sshJwk in SSH certificate request. A stringified JSON Web Key is required when using the SSH authentication scheme.", - [missingSshKid]: "Missing sshKid in SSH certificate request. A string that uniquely identifies the public SSH key is required when using the SSH authentication scheme.", - [missingNonceAuthenticationHeader]: "Unable to find an authentication header containing server nonce. Either the Authentication-Info or WWW-Authenticate headers must be present in order to obtain a server nonce.", - [invalidAuthenticationHeader]: "Invalid authentication header provided", - [cannotSetOIDCOptions]: "Cannot set OIDCOptions parameter. Please change the protocol mode to OIDC or use a non-Microsoft authority.", - [cannotAllowPlatformBroker]: "Cannot set allowPlatformBroker parameter to true when not in AAD protocol mode.", - [authorityMismatch]: "Authority mismatch error. Authority provided in login request or PublicClientApplication config does not match the environment of the provided account. Please use a matching account or make an interactive request to login to this authority.", - [invalidAuthorizePostBodyParameters]: "Invalid authorize post body parameters provided. If you are using authorizePostBodyParameters, the request method must be POST. Please check the request method and parameters.", - [invalidRequestMethodForEAR]: "Invalid request method for EAR protocol mode. The request method cannot be GET when using EAR protocol mode. Please change the request method to POST.", -}; -/** - * ClientConfigurationErrorMessage class containing string constants used by error codes and messages. - * @deprecated Use ClientConfigurationErrorCodes instead - */ -const ClientConfigurationErrorMessage = { - redirectUriNotSet: { - code: redirectUriEmpty, - desc: ClientConfigurationErrorMessages[redirectUriEmpty], - }, - claimsRequestParsingError: { - code: claimsRequestParsingError, - desc: ClientConfigurationErrorMessages[claimsRequestParsingError], - }, - authorityUriInsecure: { - code: authorityUriInsecure, - desc: ClientConfigurationErrorMessages[authorityUriInsecure], - }, - urlParseError: { - code: urlParseError, - desc: ClientConfigurationErrorMessages[urlParseError], - }, - urlEmptyError: { - code: urlEmptyError, - desc: ClientConfigurationErrorMessages[urlEmptyError], - }, - emptyScopesError: { - code: emptyInputScopesError, - desc: ClientConfigurationErrorMessages[emptyInputScopesError], - }, - invalidClaimsRequest: { - code: invalidClaims, - desc: ClientConfigurationErrorMessages[invalidClaims], - }, - tokenRequestEmptyError: { - code: tokenRequestEmpty, - desc: ClientConfigurationErrorMessages[tokenRequestEmpty], - }, - logoutRequestEmptyError: { - code: logoutRequestEmpty, - desc: ClientConfigurationErrorMessages[logoutRequestEmpty], - }, - invalidCodeChallengeMethod: { - code: invalidCodeChallengeMethod, - desc: ClientConfigurationErrorMessages[invalidCodeChallengeMethod], - }, - invalidCodeChallengeParams: { - code: pkceParamsMissing, - desc: ClientConfigurationErrorMessages[pkceParamsMissing], - }, - invalidCloudDiscoveryMetadata: { - code: invalidCloudDiscoveryMetadata, - desc: ClientConfigurationErrorMessages[invalidCloudDiscoveryMetadata], - }, - invalidAuthorityMetadata: { - code: invalidAuthorityMetadata, - desc: ClientConfigurationErrorMessages[invalidAuthorityMetadata], - }, - untrustedAuthority: { - code: untrustedAuthority, - desc: ClientConfigurationErrorMessages[untrustedAuthority], - }, - missingSshJwk: { - code: missingSshJwk, - desc: ClientConfigurationErrorMessages[missingSshJwk], - }, - missingSshKid: { - code: missingSshKid, - desc: ClientConfigurationErrorMessages[missingSshKid], - }, - missingNonceAuthenticationHeader: { - code: missingNonceAuthenticationHeader, - desc: ClientConfigurationErrorMessages[missingNonceAuthenticationHeader], - }, - invalidAuthenticationHeader: { - code: invalidAuthenticationHeader, - desc: ClientConfigurationErrorMessages[invalidAuthenticationHeader], - }, - cannotSetOIDCOptions: { - code: cannotSetOIDCOptions, - desc: ClientConfigurationErrorMessages[cannotSetOIDCOptions], - }, - cannotAllowPlatformBroker: { - code: cannotAllowPlatformBroker, - desc: ClientConfigurationErrorMessages[cannotAllowPlatformBroker], - }, - authorityMismatch: { - code: authorityMismatch, - desc: ClientConfigurationErrorMessages[authorityMismatch], - }, - invalidAuthorizePostBodyParameters: { - code: invalidAuthorizePostBodyParameters, - desc: ClientConfigurationErrorMessages[invalidAuthorizePostBodyParameters], - }, - invalidRequestMethodForEAR: { - code: invalidRequestMethodForEAR, - desc: ClientConfigurationErrorMessages[invalidRequestMethodForEAR], - }, -}; -/** - * Error thrown when there is an error in configuration of the MSAL.js library. - */ -class ClientConfigurationError extends AuthError { - constructor(errorCode) { - super(errorCode, ClientConfigurationErrorMessages[errorCode]); - this.name = "ClientConfigurationError"; - Object.setPrototypeOf(this, ClientConfigurationError.prototype); - } -} -function createClientConfigurationError(errorCode) { - return new ClientConfigurationError(errorCode); -} - -export { ClientConfigurationError, ClientConfigurationErrorMessage, ClientConfigurationErrorMessages, createClientConfigurationError }; -//# sourceMappingURL=ClientConfigurationError.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientConfigurationErrorCodes.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientConfigurationErrorCodes.mjs deleted file mode 100644 index 8368520b..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/error/ClientConfigurationErrorCodes.mjs +++ /dev/null @@ -1,32 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const redirectUriEmpty = "redirect_uri_empty"; -const claimsRequestParsingError = "claims_request_parsing_error"; -const authorityUriInsecure = "authority_uri_insecure"; -const urlParseError = "url_parse_error"; -const urlEmptyError = "empty_url_error"; -const emptyInputScopesError = "empty_input_scopes_error"; -const invalidClaims = "invalid_claims"; -const tokenRequestEmpty = "token_request_empty"; -const logoutRequestEmpty = "logout_request_empty"; -const invalidCodeChallengeMethod = "invalid_code_challenge_method"; -const pkceParamsMissing = "pkce_params_missing"; -const invalidCloudDiscoveryMetadata = "invalid_cloud_discovery_metadata"; -const invalidAuthorityMetadata = "invalid_authority_metadata"; -const untrustedAuthority = "untrusted_authority"; -const missingSshJwk = "missing_ssh_jwk"; -const missingSshKid = "missing_ssh_kid"; -const missingNonceAuthenticationHeader = "missing_nonce_authentication_header"; -const invalidAuthenticationHeader = "invalid_authentication_header"; -const cannotSetOIDCOptions = "cannot_set_OIDCOptions"; -const cannotAllowPlatformBroker = "cannot_allow_platform_broker"; -const authorityMismatch = "authority_mismatch"; -const invalidRequestMethodForEAR = "invalid_request_method_for_EAR"; -const invalidAuthorizePostBodyParameters = "invalid_authorize_post_body_parameters"; - -export { authorityMismatch, authorityUriInsecure, cannotAllowPlatformBroker, cannotSetOIDCOptions, claimsRequestParsingError, emptyInputScopesError, invalidAuthenticationHeader, invalidAuthorityMetadata, invalidAuthorizePostBodyParameters, invalidClaims, invalidCloudDiscoveryMetadata, invalidCodeChallengeMethod, invalidRequestMethodForEAR, logoutRequestEmpty, missingNonceAuthenticationHeader, missingSshJwk, missingSshKid, pkceParamsMissing, redirectUriEmpty, tokenRequestEmpty, untrustedAuthority, urlEmptyError, urlParseError }; -//# sourceMappingURL=ClientConfigurationErrorCodes.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthError.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthError.mjs deleted file mode 100644 index 1b3d60a7..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthError.mjs +++ /dev/null @@ -1,98 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { Constants } from '../utils/Constants.mjs'; -import { AuthError } from './AuthError.mjs'; -import { badToken, nativeAccountUnavailable, noTokensFound, uxNotAllowed, refreshTokenExpired, interactionRequired, consentRequired, loginRequired } from './InteractionRequiredAuthErrorCodes.mjs'; -import * as InteractionRequiredAuthErrorCodes from './InteractionRequiredAuthErrorCodes.mjs'; -export { InteractionRequiredAuthErrorCodes }; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * InteractionRequiredServerErrorMessage contains string constants used by error codes and messages returned by the server indicating interaction is required - */ -const InteractionRequiredServerErrorMessage = [ - interactionRequired, - consentRequired, - loginRequired, - badToken, - uxNotAllowed, -]; -const InteractionRequiredAuthSubErrorMessage = [ - "message_only", - "additional_action", - "basic_action", - "user_password_expired", - "consent_required", - "bad_token", -]; -const InteractionRequiredAuthErrorMessages = { - [noTokensFound]: "No refresh token found in the cache. Please sign-in.", - [nativeAccountUnavailable]: "The requested account is not available in the native broker. It may have been deleted or logged out. Please sign-in again using an interactive API.", - [refreshTokenExpired]: "Refresh token has expired.", - [badToken]: "Identity provider returned bad_token due to an expired or invalid refresh token. Please invoke an interactive API to resolve.", - [uxNotAllowed]: "`canShowUI` flag in Edge was set to false. User interaction required on web page. Please invoke an interactive API to resolve.", -}; -/** - * Interaction required errors defined by the SDK - * @deprecated Use InteractionRequiredAuthErrorCodes instead - */ -const InteractionRequiredAuthErrorMessage = { - noTokensFoundError: { - code: noTokensFound, - desc: InteractionRequiredAuthErrorMessages[noTokensFound], - }, - native_account_unavailable: { - code: nativeAccountUnavailable, - desc: InteractionRequiredAuthErrorMessages[nativeAccountUnavailable], - }, - bad_token: { - code: badToken, - desc: InteractionRequiredAuthErrorMessages[badToken], - }, -}; -/** - * Error thrown when user interaction is required. - */ -class InteractionRequiredAuthError extends AuthError { - constructor(errorCode, errorMessage, subError, timestamp, traceId, correlationId, claims, errorNo) { - super(errorCode, errorMessage, subError); - Object.setPrototypeOf(this, InteractionRequiredAuthError.prototype); - this.timestamp = timestamp || Constants.EMPTY_STRING; - this.traceId = traceId || Constants.EMPTY_STRING; - this.correlationId = correlationId || Constants.EMPTY_STRING; - this.claims = claims || Constants.EMPTY_STRING; - this.name = "InteractionRequiredAuthError"; - this.errorNo = errorNo; - } -} -/** - * Helper function used to determine if an error thrown by the server requires interaction to resolve - * @param errorCode - * @param errorString - * @param subError - */ -function isInteractionRequiredError(errorCode, errorString, subError) { - const isInteractionRequiredErrorCode = !!errorCode && - InteractionRequiredServerErrorMessage.indexOf(errorCode) > -1; - const isInteractionRequiredSubError = !!subError && - InteractionRequiredAuthSubErrorMessage.indexOf(subError) > -1; - const isInteractionRequiredErrorDesc = !!errorString && - InteractionRequiredServerErrorMessage.some((irErrorCode) => { - return errorString.indexOf(irErrorCode) > -1; - }); - return (isInteractionRequiredErrorCode || - isInteractionRequiredErrorDesc || - isInteractionRequiredSubError); -} -/** - * Creates an InteractionRequiredAuthError - */ -function createInteractionRequiredAuthError(errorCode) { - return new InteractionRequiredAuthError(errorCode, InteractionRequiredAuthErrorMessages[errorCode]); -} - -export { InteractionRequiredAuthError, InteractionRequiredAuthErrorMessage, InteractionRequiredAuthSubErrorMessage, InteractionRequiredServerErrorMessage, createInteractionRequiredAuthError, isInteractionRequiredError }; -//# sourceMappingURL=InteractionRequiredAuthError.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthErrorCodes.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthErrorCodes.mjs deleted file mode 100644 index c15b837f..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/error/InteractionRequiredAuthErrorCodes.mjs +++ /dev/null @@ -1,19 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -// Codes defined by MSAL -const noTokensFound = "no_tokens_found"; -const nativeAccountUnavailable = "native_account_unavailable"; -const refreshTokenExpired = "refresh_token_expired"; -const uxNotAllowed = "ux_not_allowed"; -// Codes potentially returned by server -const interactionRequired = "interaction_required"; -const consentRequired = "consent_required"; -const loginRequired = "login_required"; -const badToken = "bad_token"; - -export { badToken, consentRequired, interactionRequired, loginRequired, nativeAccountUnavailable, noTokensFound, refreshTokenExpired, uxNotAllowed }; -//# sourceMappingURL=InteractionRequiredAuthErrorCodes.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/NetworkError.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/NetworkError.mjs deleted file mode 100644 index e5109ae3..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/error/NetworkError.mjs +++ /dev/null @@ -1,35 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { AuthError } from './AuthError.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Represents network related errors - */ -class NetworkError extends AuthError { - constructor(error, httpStatus, responseHeaders) { - super(error.errorCode, error.errorMessage, error.subError); - Object.setPrototypeOf(this, NetworkError.prototype); - this.name = "NetworkError"; - this.error = error; - this.httpStatus = httpStatus; - this.responseHeaders = responseHeaders; - } -} -/** - * Creates NetworkError object for a failed network request - * @param error - Error to be thrown back to the caller - * @param httpStatus - Status code of the network request - * @param responseHeaders - Response headers of the network request, when available - * @returns NetworkError object - */ -function createNetworkError(error, httpStatus, responseHeaders, additionalError) { - error.errorMessage = `${error.errorMessage}, additionalErrorInfo: error.name:${additionalError?.name}, error.message:${additionalError?.message}`; - return new NetworkError(error, httpStatus, responseHeaders); -} - -export { NetworkError, createNetworkError }; -//# sourceMappingURL=NetworkError.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/error/ServerError.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/error/ServerError.mjs deleted file mode 100644 index 24b83f94..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/error/ServerError.mjs +++ /dev/null @@ -1,23 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { AuthError } from './AuthError.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Error thrown when there is an error with the server code, for example, unavailability. - */ -class ServerError extends AuthError { - constructor(errorCode, errorMessage, subError, errorNo, status) { - super(errorCode, errorMessage, subError); - this.name = "ServerError"; - this.errorNo = errorNo; - this.status = status; - Object.setPrototypeOf(this, ServerError.prototype); - } -} - -export { ServerError }; -//# sourceMappingURL=ServerError.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/index-node.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/index-node.mjs deleted file mode 100644 index 48883931..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/index-node.mjs +++ /dev/null @@ -1,70 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -export { AuthorizationCodeClient } from './client/AuthorizationCodeClient.mjs'; -export { RefreshTokenClient } from './client/RefreshTokenClient.mjs'; -export { SilentFlowClient } from './client/SilentFlowClient.mjs'; -export { BaseClient } from './client/BaseClient.mjs'; -export { DEFAULT_SYSTEM_OPTIONS } from './config/ClientConfiguration.mjs'; -export { buildTenantProfile, tenantIdMatchesHomeTenant, updateAccountTenantProfileData } from './account/AccountInfo.mjs'; -export { getTenantIdFromIdTokenClaims } from './account/TokenClaims.mjs'; -export { CcsCredentialType } from './account/CcsCredential.mjs'; -export { buildClientInfo, buildClientInfoFromHomeAccountId } from './account/ClientInfo.mjs'; -export { Authority, buildStaticAuthorityOptions, formatAuthorityUri } from './authority/Authority.mjs'; -export { AzureCloudInstance } from './authority/AuthorityOptions.mjs'; -export { AuthorityType } from './authority/AuthorityType.mjs'; -export { ProtocolMode } from './authority/ProtocolMode.mjs'; -export { CacheManager, DefaultStorageClass } from './cache/CacheManager.mjs'; -export { AccountEntity } from './cache/entities/AccountEntity.mjs'; -export { StubbedNetworkModule } from './network/INetworkModule.mjs'; -export { ThrottlingUtils } from './network/ThrottlingUtils.mjs'; -export { getRequestThumbprint } from './network/RequestThumbprint.mjs'; -export { UrlString } from './url/UrlString.mjs'; -export { DEFAULT_CRYPTO_IMPLEMENTATION } from './crypto/ICrypto.mjs'; -import * as Authorize from './protocol/Authorize.mjs'; -export { Authorize as AuthorizeProtocol }; -import * as RequestParameterBuilder from './request/RequestParameterBuilder.mjs'; -export { RequestParameterBuilder }; -export { ResponseHandler, buildAccountToCache } from './response/ResponseHandler.mjs'; -export { ScopeSet } from './request/ScopeSet.mjs'; -export { AuthenticationHeaderParser } from './request/AuthenticationHeaderParser.mjs'; -export { LogLevel, Logger } from './logger/Logger.mjs'; -export { InteractionRequiredAuthError, InteractionRequiredAuthErrorMessage, createInteractionRequiredAuthError } from './error/InteractionRequiredAuthError.mjs'; -import * as InteractionRequiredAuthErrorCodes from './error/InteractionRequiredAuthErrorCodes.mjs'; -export { InteractionRequiredAuthErrorCodes }; -export { AuthError, AuthErrorMessage, createAuthError } from './error/AuthError.mjs'; -import * as AuthErrorCodes from './error/AuthErrorCodes.mjs'; -export { AuthErrorCodes }; -export { ServerError } from './error/ServerError.mjs'; -export { NetworkError, createNetworkError } from './error/NetworkError.mjs'; -export { CacheError, createCacheError } from './error/CacheError.mjs'; -import * as CacheErrorCodes from './error/CacheErrorCodes.mjs'; -export { CacheErrorCodes }; -export { ClientAuthError, ClientAuthErrorMessage, createClientAuthError } from './error/ClientAuthError.mjs'; -import * as ClientAuthErrorCodes from './error/ClientAuthErrorCodes.mjs'; -export { ClientAuthErrorCodes }; -export { ClientConfigurationError, ClientConfigurationErrorMessage, createClientConfigurationError } from './error/ClientConfigurationError.mjs'; -import * as ClientConfigurationErrorCodes from './error/ClientConfigurationErrorCodes.mjs'; -export { ClientConfigurationErrorCodes }; -export { AADAuthorityConstants, AuthenticationScheme, CacheAccountType, CacheOutcome, CacheType, ClaimsRequestKeys, CodeChallengeMethodValues, Constants, CredentialType, DEFAULT_TOKEN_RENEWAL_OFFSET_SEC, EncodingTypes, Errors, GrantType, HeaderNames, HttpMethod, HttpStatus, JsonWebTokenTypes, OAuthResponseType, OIDC_DEFAULT_SCOPES, ONE_DAY_IN_MS, PasswordGrantConstants, PersistentCacheKeys, PromptValue, ResponseMode, ServerResponseType, THE_FAMILY_ID, ThrottlingConstants } from './utils/Constants.mjs'; -export { StringUtils } from './utils/StringUtils.mjs'; -export { ProtocolUtils } from './utils/ProtocolUtils.mjs'; -export { ServerTelemetryManager } from './telemetry/server/ServerTelemetryManager.mjs'; -export { version } from './packageMetadata.mjs'; -export { invoke, invokeAsync } from './utils/FunctionWrappers.mjs'; -import * as AuthToken from './account/AuthToken.mjs'; -export { AuthToken }; -import * as AuthorityFactory from './authority/AuthorityFactory.mjs'; -export { AuthorityFactory }; -import * as CacheHelpers from './cache/utils/CacheHelpers.mjs'; -export { CacheHelpers }; -import * as TimeUtils from './utils/TimeUtils.mjs'; -export { TimeUtils }; -import * as UrlUtils from './utils/UrlUtils.mjs'; -export { UrlUtils }; -import * as AADServerParamKeys from './constants/AADServerParamKeys.mjs'; -export { AADServerParamKeys }; -export { TokenCacheContext } from './cache/persistence/TokenCacheContext.mjs'; -import * as ClientAssertionUtils from './utils/ClientAssertionUtils.mjs'; -export { ClientAssertionUtils }; -export { getClientAssertion } from './utils/ClientAssertionUtils.mjs'; -//# sourceMappingURL=index-node.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/index.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/index.mjs deleted file mode 100644 index df10aa3e..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/index.mjs +++ /dev/null @@ -1,75 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -export { AuthorizationCodeClient } from './client/AuthorizationCodeClient.mjs'; -export { RefreshTokenClient } from './client/RefreshTokenClient.mjs'; -export { SilentFlowClient } from './client/SilentFlowClient.mjs'; -export { BaseClient } from './client/BaseClient.mjs'; -export { DEFAULT_SYSTEM_OPTIONS } from './config/ClientConfiguration.mjs'; -export { buildTenantProfile, tenantIdMatchesHomeTenant, updateAccountTenantProfileData } from './account/AccountInfo.mjs'; -export { getTenantIdFromIdTokenClaims } from './account/TokenClaims.mjs'; -export { CcsCredentialType } from './account/CcsCredential.mjs'; -export { buildClientInfo, buildClientInfoFromHomeAccountId } from './account/ClientInfo.mjs'; -export { Authority, buildStaticAuthorityOptions, formatAuthorityUri } from './authority/Authority.mjs'; -export { AzureCloudInstance } from './authority/AuthorityOptions.mjs'; -export { AuthorityType } from './authority/AuthorityType.mjs'; -export { ProtocolMode } from './authority/ProtocolMode.mjs'; -export { CacheManager, DefaultStorageClass } from './cache/CacheManager.mjs'; -export { AccountEntity } from './cache/entities/AccountEntity.mjs'; -export { StubbedNetworkModule } from './network/INetworkModule.mjs'; -export { ThrottlingUtils } from './network/ThrottlingUtils.mjs'; -export { getRequestThumbprint } from './network/RequestThumbprint.mjs'; -export { UrlString } from './url/UrlString.mjs'; -export { DEFAULT_CRYPTO_IMPLEMENTATION } from './crypto/ICrypto.mjs'; -import * as Authorize from './protocol/Authorize.mjs'; -export { Authorize as AuthorizeProtocol }; -import * as RequestParameterBuilder from './request/RequestParameterBuilder.mjs'; -export { RequestParameterBuilder }; -export { ResponseHandler, buildAccountToCache } from './response/ResponseHandler.mjs'; -export { ScopeSet } from './request/ScopeSet.mjs'; -export { AuthenticationHeaderParser } from './request/AuthenticationHeaderParser.mjs'; -export { LogLevel, Logger } from './logger/Logger.mjs'; -export { InteractionRequiredAuthError, InteractionRequiredAuthErrorMessage, createInteractionRequiredAuthError } from './error/InteractionRequiredAuthError.mjs'; -import * as InteractionRequiredAuthErrorCodes from './error/InteractionRequiredAuthErrorCodes.mjs'; -export { InteractionRequiredAuthErrorCodes }; -export { AuthError, AuthErrorMessage, createAuthError } from './error/AuthError.mjs'; -import * as AuthErrorCodes from './error/AuthErrorCodes.mjs'; -export { AuthErrorCodes }; -export { ServerError } from './error/ServerError.mjs'; -export { NetworkError, createNetworkError } from './error/NetworkError.mjs'; -export { CacheError, createCacheError } from './error/CacheError.mjs'; -import * as CacheErrorCodes from './error/CacheErrorCodes.mjs'; -export { CacheErrorCodes }; -export { ClientAuthError, ClientAuthErrorMessage, createClientAuthError } from './error/ClientAuthError.mjs'; -import * as ClientAuthErrorCodes from './error/ClientAuthErrorCodes.mjs'; -export { ClientAuthErrorCodes }; -export { ClientConfigurationError, ClientConfigurationErrorMessage, createClientConfigurationError } from './error/ClientConfigurationError.mjs'; -import * as ClientConfigurationErrorCodes from './error/ClientConfigurationErrorCodes.mjs'; -export { ClientConfigurationErrorCodes }; -export { AADAuthorityConstants, AuthenticationScheme, CacheAccountType, CacheOutcome, CacheType, ClaimsRequestKeys, CodeChallengeMethodValues, Constants, CredentialType, DEFAULT_TOKEN_RENEWAL_OFFSET_SEC, EncodingTypes, Errors, GrantType, HeaderNames, HttpMethod, HttpStatus, JsonWebTokenTypes, OAuthResponseType, OIDC_DEFAULT_SCOPES, ONE_DAY_IN_MS, PasswordGrantConstants, PersistentCacheKeys, PromptValue, ResponseMode, ServerResponseType, THE_FAMILY_ID, ThrottlingConstants } from './utils/Constants.mjs'; -export { StringUtils } from './utils/StringUtils.mjs'; -export { ProtocolUtils } from './utils/ProtocolUtils.mjs'; -export { ServerTelemetryManager } from './telemetry/server/ServerTelemetryManager.mjs'; -export { version } from './packageMetadata.mjs'; -export { invoke, invokeAsync } from './utils/FunctionWrappers.mjs'; -import * as AuthToken from './account/AuthToken.mjs'; -export { AuthToken }; -import * as AuthorityFactory from './authority/AuthorityFactory.mjs'; -export { AuthorityFactory }; -import * as CacheHelpers from './cache/utils/CacheHelpers.mjs'; -export { CacheHelpers }; -import * as TimeUtils from './utils/TimeUtils.mjs'; -export { TimeUtils }; -import * as UrlUtils from './utils/UrlUtils.mjs'; -export { UrlUtils }; -import * as AADServerParamKeys from './constants/AADServerParamKeys.mjs'; -export { AADServerParamKeys }; -export { JoseHeader } from './crypto/JoseHeader.mjs'; -export { IntFields, PerformanceEventStatus, PerformanceEvents } from './telemetry/performance/PerformanceEvent.mjs'; -export { PerformanceClient } from './telemetry/performance/PerformanceClient.mjs'; -export { StubPerformanceClient } from './telemetry/performance/StubPerformanceClient.mjs'; -export { PopTokenGenerator } from './crypto/PopTokenGenerator.mjs'; -export { TokenCacheContext } from './cache/persistence/TokenCacheContext.mjs'; -import * as ClientAssertionUtils from './utils/ClientAssertionUtils.mjs'; -export { ClientAssertionUtils }; -export { getClientAssertion } from './utils/ClientAssertionUtils.mjs'; -//# sourceMappingURL=index.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/logger/Logger.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/logger/Logger.mjs deleted file mode 100644 index 8af83586..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/logger/Logger.mjs +++ /dev/null @@ -1,195 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { Constants } from '../utils/Constants.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Log message level. - */ -var LogLevel; -(function (LogLevel) { - LogLevel[LogLevel["Error"] = 0] = "Error"; - LogLevel[LogLevel["Warning"] = 1] = "Warning"; - LogLevel[LogLevel["Info"] = 2] = "Info"; - LogLevel[LogLevel["Verbose"] = 3] = "Verbose"; - LogLevel[LogLevel["Trace"] = 4] = "Trace"; -})(LogLevel || (LogLevel = {})); -/** - * Class which facilitates logging of messages to a specific place. - */ -class Logger { - constructor(loggerOptions, packageName, packageVersion) { - // Current log level, defaults to info. - this.level = LogLevel.Info; - const defaultLoggerCallback = () => { - return; - }; - const setLoggerOptions = loggerOptions || Logger.createDefaultLoggerOptions(); - this.localCallback = - setLoggerOptions.loggerCallback || defaultLoggerCallback; - this.piiLoggingEnabled = setLoggerOptions.piiLoggingEnabled || false; - this.level = - typeof setLoggerOptions.logLevel === "number" - ? setLoggerOptions.logLevel - : LogLevel.Info; - this.correlationId = - setLoggerOptions.correlationId || Constants.EMPTY_STRING; - this.packageName = packageName || Constants.EMPTY_STRING; - this.packageVersion = packageVersion || Constants.EMPTY_STRING; - } - static createDefaultLoggerOptions() { - return { - loggerCallback: () => { - // allow users to not set loggerCallback - }, - piiLoggingEnabled: false, - logLevel: LogLevel.Info, - }; - } - /** - * Create new Logger with existing configurations. - */ - clone(packageName, packageVersion, correlationId) { - return new Logger({ - loggerCallback: this.localCallback, - piiLoggingEnabled: this.piiLoggingEnabled, - logLevel: this.level, - correlationId: correlationId || this.correlationId, - }, packageName, packageVersion); - } - /** - * Log message with required options. - */ - logMessage(logMessage, options) { - if (options.logLevel > this.level || - (!this.piiLoggingEnabled && options.containsPii)) { - return; - } - const timestamp = new Date().toUTCString(); - // Add correlationId to logs if set, correlationId provided on log messages take precedence - const logHeader = `[${timestamp}] : [${options.correlationId || this.correlationId || ""}]`; - const log = `${logHeader} : ${this.packageName}@${this.packageVersion} : ${LogLevel[options.logLevel]} - ${logMessage}`; - // debug(`msal:${LogLevel[options.logLevel]}${options.containsPii ? "-Pii": Constants.EMPTY_STRING}${options.context ? `:${options.context}` : Constants.EMPTY_STRING}`)(logMessage); - this.executeCallback(options.logLevel, log, options.containsPii || false); - } - /** - * Execute callback with message. - */ - executeCallback(level, message, containsPii) { - if (this.localCallback) { - this.localCallback(level, message, containsPii); - } - } - /** - * Logs error messages. - */ - error(message, correlationId) { - this.logMessage(message, { - logLevel: LogLevel.Error, - containsPii: false, - correlationId: correlationId || Constants.EMPTY_STRING, - }); - } - /** - * Logs error messages with PII. - */ - errorPii(message, correlationId) { - this.logMessage(message, { - logLevel: LogLevel.Error, - containsPii: true, - correlationId: correlationId || Constants.EMPTY_STRING, - }); - } - /** - * Logs warning messages. - */ - warning(message, correlationId) { - this.logMessage(message, { - logLevel: LogLevel.Warning, - containsPii: false, - correlationId: correlationId || Constants.EMPTY_STRING, - }); - } - /** - * Logs warning messages with PII. - */ - warningPii(message, correlationId) { - this.logMessage(message, { - logLevel: LogLevel.Warning, - containsPii: true, - correlationId: correlationId || Constants.EMPTY_STRING, - }); - } - /** - * Logs info messages. - */ - info(message, correlationId) { - this.logMessage(message, { - logLevel: LogLevel.Info, - containsPii: false, - correlationId: correlationId || Constants.EMPTY_STRING, - }); - } - /** - * Logs info messages with PII. - */ - infoPii(message, correlationId) { - this.logMessage(message, { - logLevel: LogLevel.Info, - containsPii: true, - correlationId: correlationId || Constants.EMPTY_STRING, - }); - } - /** - * Logs verbose messages. - */ - verbose(message, correlationId) { - this.logMessage(message, { - logLevel: LogLevel.Verbose, - containsPii: false, - correlationId: correlationId || Constants.EMPTY_STRING, - }); - } - /** - * Logs verbose messages with PII. - */ - verbosePii(message, correlationId) { - this.logMessage(message, { - logLevel: LogLevel.Verbose, - containsPii: true, - correlationId: correlationId || Constants.EMPTY_STRING, - }); - } - /** - * Logs trace messages. - */ - trace(message, correlationId) { - this.logMessage(message, { - logLevel: LogLevel.Trace, - containsPii: false, - correlationId: correlationId || Constants.EMPTY_STRING, - }); - } - /** - * Logs trace messages with PII. - */ - tracePii(message, correlationId) { - this.logMessage(message, { - logLevel: LogLevel.Trace, - containsPii: true, - correlationId: correlationId || Constants.EMPTY_STRING, - }); - } - /** - * Returns whether PII Logging is enabled or not. - */ - isPiiLoggingEnabled() { - return this.piiLoggingEnabled || false; - } -} - -export { LogLevel, Logger }; -//# sourceMappingURL=Logger.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/network/RequestThumbprint.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/network/RequestThumbprint.mjs deleted file mode 100644 index 08ed9e64..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/network/RequestThumbprint.mjs +++ /dev/null @@ -1,24 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -function getRequestThumbprint(clientId, request, homeAccountId) { - return { - clientId: clientId, - authority: request.authority, - scopes: request.scopes, - homeAccountIdentifier: homeAccountId, - claims: request.claims, - authenticationScheme: request.authenticationScheme, - resourceRequestMethod: request.resourceRequestMethod, - resourceRequestUri: request.resourceRequestUri, - shrClaims: request.shrClaims, - sshKid: request.sshKid, - embeddedClientId: request.embeddedClientId || request.tokenBodyParameters?.clientId, - }; -} - -export { getRequestThumbprint }; -//# sourceMappingURL=RequestThumbprint.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/network/ThrottlingUtils.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/network/ThrottlingUtils.mjs deleted file mode 100644 index 24a2b62e..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/network/ThrottlingUtils.mjs +++ /dev/null @@ -1,93 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { ThrottlingConstants, Constants, HeaderNames } from '../utils/Constants.mjs'; -import { ServerError } from '../error/ServerError.mjs'; -import { getRequestThumbprint } from './RequestThumbprint.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** @internal */ -class ThrottlingUtils { - /** - * Prepares a RequestThumbprint to be stored as a key. - * @param thumbprint - */ - static generateThrottlingStorageKey(thumbprint) { - return `${ThrottlingConstants.THROTTLING_PREFIX}.${JSON.stringify(thumbprint)}`; - } - /** - * Performs necessary throttling checks before a network request. - * @param cacheManager - * @param thumbprint - */ - static preProcess(cacheManager, thumbprint, correlationId) { - const key = ThrottlingUtils.generateThrottlingStorageKey(thumbprint); - const value = cacheManager.getThrottlingCache(key); - if (value) { - if (value.throttleTime < Date.now()) { - cacheManager.removeItem(key, correlationId); - return; - } - throw new ServerError(value.errorCodes?.join(" ") || Constants.EMPTY_STRING, value.errorMessage, value.subError); - } - } - /** - * Performs necessary throttling checks after a network request. - * @param cacheManager - * @param thumbprint - * @param response - */ - static postProcess(cacheManager, thumbprint, response, correlationId) { - if (ThrottlingUtils.checkResponseStatus(response) || - ThrottlingUtils.checkResponseForRetryAfter(response)) { - const thumbprintValue = { - throttleTime: ThrottlingUtils.calculateThrottleTime(parseInt(response.headers[HeaderNames.RETRY_AFTER])), - error: response.body.error, - errorCodes: response.body.error_codes, - errorMessage: response.body.error_description, - subError: response.body.suberror, - }; - cacheManager.setThrottlingCache(ThrottlingUtils.generateThrottlingStorageKey(thumbprint), thumbprintValue, correlationId); - } - } - /** - * Checks a NetworkResponse object's status codes against 429 or 5xx - * @param response - */ - static checkResponseStatus(response) { - return (response.status === 429 || - (response.status >= 500 && response.status < 600)); - } - /** - * Checks a NetworkResponse object's RetryAfter header - * @param response - */ - static checkResponseForRetryAfter(response) { - if (response.headers) { - return (response.headers.hasOwnProperty(HeaderNames.RETRY_AFTER) && - (response.status < 200 || response.status >= 300)); - } - return false; - } - /** - * Calculates the Unix-time value for a throttle to expire given throttleTime in seconds. - * @param throttleTime - */ - static calculateThrottleTime(throttleTime) { - const time = throttleTime <= 0 ? 0 : throttleTime; - const currentSeconds = Date.now() / 1000; - return Math.floor(Math.min(currentSeconds + - (time || ThrottlingConstants.DEFAULT_THROTTLE_TIME_SECONDS), currentSeconds + - ThrottlingConstants.DEFAULT_MAX_THROTTLE_TIME_SECONDS) * 1000); - } - static removeThrottle(cacheManager, clientId, request, homeAccountIdentifier) { - const thumbprint = getRequestThumbprint(clientId, request, homeAccountIdentifier); - const key = this.generateThrottlingStorageKey(thumbprint); - cacheManager.removeItem(key, request.correlationId); - } -} - -export { ThrottlingUtils }; -//# sourceMappingURL=ThrottlingUtils.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/packageMetadata.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/packageMetadata.mjs deleted file mode 100644 index 66c2d945..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/packageMetadata.mjs +++ /dev/null @@ -1,8 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* eslint-disable header/header */ -const name = "@azure/msal-common"; -const version = "15.13.1"; - -export { name, version }; -//# sourceMappingURL=packageMetadata.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/protocol/Authorize.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/protocol/Authorize.mjs deleted file mode 100644 index 4b872c4e..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/protocol/Authorize.mjs +++ /dev/null @@ -1,237 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { addClientId, addScopes, addRedirectUri, addCorrelationId, addResponseMode, addClientInfo, addPrompt, addDomainHint, addSid, addLoginHint, addCcsOid, addCcsUpn, addNonce, addState, addClaims, addBrokerParameters, addInstanceAware } from '../request/RequestParameterBuilder.mjs'; -import { INSTANCE_AWARE, CLIENT_ID } from '../constants/AADServerParamKeys.mjs'; -import { PromptValue } from '../utils/Constants.mjs'; -import { buildClientInfoFromHomeAccountId } from '../account/ClientInfo.mjs'; -import { mapToQueryString } from '../utils/UrlUtils.mjs'; -import { UrlString } from '../url/UrlString.mjs'; -import { createClientAuthError } from '../error/ClientAuthError.mjs'; -import { isInteractionRequiredError, InteractionRequiredAuthError } from '../error/InteractionRequiredAuthError.mjs'; -import { ServerError } from '../error/ServerError.mjs'; -import { authorizationCodeMissingFromServerResponse, stateNotFound, invalidState, stateMismatch } from '../error/ClientAuthErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Returns map of parameters that are applicable to all calls to /authorize whether using PKCE or EAR - * @param config - * @param request - * @param logger - * @param performanceClient - * @returns - */ -function getStandardAuthorizeRequestParameters(authOptions, request, logger, performanceClient) { - // generate the correlationId if not set by the user and add - const correlationId = request.correlationId; - const parameters = new Map(); - addClientId(parameters, request.embeddedClientId || - request.extraQueryParameters?.[CLIENT_ID] || - authOptions.clientId); - const requestScopes = [ - ...(request.scopes || []), - ...(request.extraScopesToConsent || []), - ]; - addScopes(parameters, requestScopes, true, authOptions.authority.options.OIDCOptions?.defaultScopes); - addRedirectUri(parameters, request.redirectUri); - addCorrelationId(parameters, correlationId); - // add response_mode. If not passed in it defaults to query. - addResponseMode(parameters, request.responseMode); - // add client_info=1 - addClientInfo(parameters); - if (request.prompt) { - addPrompt(parameters, request.prompt); - performanceClient?.addFields({ prompt: request.prompt }, correlationId); - } - if (request.domainHint) { - addDomainHint(parameters, request.domainHint); - performanceClient?.addFields({ domainHintFromRequest: true }, correlationId); - } - // Add sid or loginHint with preference for login_hint claim (in request) -> sid -> loginHint (upn/email) -> username of AccountInfo object - if (request.prompt !== PromptValue.SELECT_ACCOUNT) { - // AAD will throw if prompt=select_account is passed with an account hint - if (request.sid && request.prompt === PromptValue.NONE) { - // SessionID is only used in silent calls - logger.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from request"); - addSid(parameters, request.sid); - performanceClient?.addFields({ sidFromRequest: true }, correlationId); - } - else if (request.account) { - const accountSid = extractAccountSid(request.account); - let accountLoginHintClaim = extractLoginHint(request.account); - if (accountLoginHintClaim && request.domainHint) { - logger.warning(`AuthorizationCodeClient.createAuthCodeUrlQueryString: "domainHint" param is set, skipping opaque "login_hint" claim. Please consider not passing domainHint`); - accountLoginHintClaim = null; - } - // If login_hint claim is present, use it over sid/username - if (accountLoginHintClaim) { - logger.verbose("createAuthCodeUrlQueryString: login_hint claim present on account"); - addLoginHint(parameters, accountLoginHintClaim); - performanceClient?.addFields({ loginHintFromClaim: true }, correlationId); - try { - const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId); - addCcsOid(parameters, clientInfo); - } - catch (e) { - logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header"); - } - } - else if (accountSid && request.prompt === PromptValue.NONE) { - /* - * If account and loginHint are provided, we will check account first for sid before adding loginHint - * SessionId is only used in silent calls - */ - logger.verbose("createAuthCodeUrlQueryString: Prompt is none, adding sid from account"); - addSid(parameters, accountSid); - performanceClient?.addFields({ sidFromClaim: true }, correlationId); - try { - const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId); - addCcsOid(parameters, clientInfo); - } - catch (e) { - logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header"); - } - } - else if (request.loginHint) { - logger.verbose("createAuthCodeUrlQueryString: Adding login_hint from request"); - addLoginHint(parameters, request.loginHint); - addCcsUpn(parameters, request.loginHint); - performanceClient?.addFields({ loginHintFromRequest: true }, correlationId); - } - else if (request.account.username) { - // Fallback to account username if provided - logger.verbose("createAuthCodeUrlQueryString: Adding login_hint from account"); - addLoginHint(parameters, request.account.username); - performanceClient?.addFields({ loginHintFromUpn: true }, correlationId); - try { - const clientInfo = buildClientInfoFromHomeAccountId(request.account.homeAccountId); - addCcsOid(parameters, clientInfo); - } - catch (e) { - logger.verbose("createAuthCodeUrlQueryString: Could not parse home account ID for CCS Header"); - } - } - } - else if (request.loginHint) { - logger.verbose("createAuthCodeUrlQueryString: No account, adding login_hint from request"); - addLoginHint(parameters, request.loginHint); - addCcsUpn(parameters, request.loginHint); - performanceClient?.addFields({ loginHintFromRequest: true }, correlationId); - } - } - else { - logger.verbose("createAuthCodeUrlQueryString: Prompt is select_account, ignoring account hints"); - } - if (request.nonce) { - addNonce(parameters, request.nonce); - } - if (request.state) { - addState(parameters, request.state); - } - if (request.claims || - (authOptions.clientCapabilities && - authOptions.clientCapabilities.length > 0)) { - addClaims(parameters, request.claims, authOptions.clientCapabilities); - } - if (request.embeddedClientId) { - addBrokerParameters(parameters, authOptions.clientId, authOptions.redirectUri); - } - // If extraQueryParameters includes instance_aware its value will be added when extraQueryParameters are added - if (authOptions.instanceAware && - (!request.extraQueryParameters || - !Object.keys(request.extraQueryParameters).includes(INSTANCE_AWARE))) { - addInstanceAware(parameters); - } - return parameters; -} -/** - * Returns authorize endpoint with given request parameters in the query string - * @param authority - * @param requestParameters - * @returns - */ -function getAuthorizeUrl(authority, requestParameters, encodeParams, extraQueryParameters) { - const queryString = mapToQueryString(requestParameters, encodeParams, extraQueryParameters); - return UrlString.appendQueryString(authority.authorizationEndpoint, queryString); -} -/** - * Handles the hash fragment response from public client code request. Returns a code response used by - * the client to exchange for a token in acquireToken. - * @param serverParams - * @param cachedState - */ -function getAuthorizationCodePayload(serverParams, cachedState) { - // Get code response - validateAuthorizationResponse(serverParams, cachedState); - // throw when there is no auth code in the response - if (!serverParams.code) { - throw createClientAuthError(authorizationCodeMissingFromServerResponse); - } - return serverParams; -} -/** - * Function which validates server authorization code response. - * @param serverResponseHash - * @param requestState - */ -function validateAuthorizationResponse(serverResponse, requestState) { - if (!serverResponse.state || !requestState) { - throw serverResponse.state - ? createClientAuthError(stateNotFound, "Cached State") - : createClientAuthError(stateNotFound, "Server State"); - } - let decodedServerResponseState; - let decodedRequestState; - try { - decodedServerResponseState = decodeURIComponent(serverResponse.state); - } - catch (e) { - throw createClientAuthError(invalidState, serverResponse.state); - } - try { - decodedRequestState = decodeURIComponent(requestState); - } - catch (e) { - throw createClientAuthError(invalidState, serverResponse.state); - } - if (decodedServerResponseState !== decodedRequestState) { - throw createClientAuthError(stateMismatch); - } - // Check for error - if (serverResponse.error || - serverResponse.error_description || - serverResponse.suberror) { - const serverErrorNo = parseServerErrorNo(serverResponse); - if (isInteractionRequiredError(serverResponse.error, serverResponse.error_description, serverResponse.suberror)) { - throw new InteractionRequiredAuthError(serverResponse.error || "", serverResponse.error_description, serverResponse.suberror, serverResponse.timestamp || "", serverResponse.trace_id || "", serverResponse.correlation_id || "", serverResponse.claims || "", serverErrorNo); - } - throw new ServerError(serverResponse.error || "", serverResponse.error_description, serverResponse.suberror, serverErrorNo); - } -} -/** - * Get server error No from the error_uri - * @param serverResponse - * @returns - */ -function parseServerErrorNo(serverResponse) { - const errorCodePrefix = "code="; - const errorCodePrefixIndex = serverResponse.error_uri?.lastIndexOf(errorCodePrefix); - return errorCodePrefixIndex && errorCodePrefixIndex >= 0 - ? serverResponse.error_uri?.substring(errorCodePrefixIndex + errorCodePrefix.length) - : undefined; -} -/** - * Helper to get sid from account. Returns null if idTokenClaims are not present or sid is not present. - * @param account - */ -function extractAccountSid(account) { - return account.idTokenClaims?.sid || null; -} -function extractLoginHint(account) { - return account.loginHint || account.idTokenClaims?.login_hint || null; -} - -export { getAuthorizationCodePayload, getAuthorizeUrl, getStandardAuthorizeRequestParameters, validateAuthorizationResponse }; -//# sourceMappingURL=Authorize.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/request/RequestParameterBuilder.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/request/RequestParameterBuilder.mjs deleted file mode 100644 index 15485722..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/request/RequestParameterBuilder.mjs +++ /dev/null @@ -1,423 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { OIDC_DEFAULT_SCOPES, ResponseMode, HeaderNames, CLIENT_INFO, ClaimsRequestKeys, PasswordGrantConstants, AuthenticationScheme, ThrottlingConstants } from '../utils/Constants.mjs'; -import { CLIENT_ID, BROKER_CLIENT_ID, REDIRECT_URI, RESPONSE_TYPE, RESPONSE_MODE, NATIVE_BROKER, SCOPE, POST_LOGOUT_URI, ID_TOKEN_HINT, DOMAIN_HINT, LOGIN_HINT, SID, CLAIMS, CLIENT_REQUEST_ID, X_CLIENT_SKU, X_CLIENT_VER, X_CLIENT_OS, X_CLIENT_CPU, X_APP_NAME, X_APP_VER, PROMPT, STATE, NONCE, CODE_CHALLENGE, CODE_CHALLENGE_METHOD, CODE, DEVICE_CODE, REFRESH_TOKEN, CODE_VERIFIER, CLIENT_SECRET, CLIENT_ASSERTION, CLIENT_ASSERTION_TYPE, OBO_ASSERTION, REQUESTED_TOKEN_USE, GRANT_TYPE, INSTANCE_AWARE, TOKEN_TYPE, REQ_CNF, X_CLIENT_CURR_TELEM, X_CLIENT_LAST_TELEM, X_MS_LIB_CAPABILITY, LOGOUT_HINT, BROKER_REDIRECT_URI, EAR_JWK, EAR_JWE_CRYPTO } from '../constants/AADServerParamKeys.mjs'; -import { ScopeSet } from './ScopeSet.mjs'; -import { createClientConfigurationError } from '../error/ClientConfigurationError.mjs'; -import { invalidClaims, pkceParamsMissing } from '../error/ClientConfigurationErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -function instrumentBrokerParams(parameters, correlationId, performanceClient) { - if (!correlationId) { - return; - } - const clientId = parameters.get(CLIENT_ID); - if (clientId && parameters.has(BROKER_CLIENT_ID)) { - performanceClient?.addFields({ - embeddedClientId: clientId, - embeddedRedirectUri: parameters.get(REDIRECT_URI), - }, correlationId); - } -} -/** - * Add the given response_type - * @param parameters - * @param responseType - */ -function addResponseType(parameters, responseType) { - parameters.set(RESPONSE_TYPE, responseType); -} -/** - * add response_mode. defaults to query. - * @param responseMode - */ -function addResponseMode(parameters, responseMode) { - parameters.set(RESPONSE_MODE, responseMode ? responseMode : ResponseMode.QUERY); -} -/** - * Add flag to indicate STS should attempt to use WAM if available - */ -function addNativeBroker(parameters) { - parameters.set(NATIVE_BROKER, "1"); -} -/** - * add scopes. set addOidcScopes to false to prevent default scopes in non-user scenarios - * @param scopeSet - * @param addOidcScopes - */ -function addScopes(parameters, scopes, addOidcScopes = true, defaultScopes = OIDC_DEFAULT_SCOPES) { - // Always add openid to the scopes when adding OIDC scopes - if (addOidcScopes && - !defaultScopes.includes("openid") && - !scopes.includes("openid")) { - defaultScopes.push("openid"); - } - const requestScopes = addOidcScopes - ? [...(scopes || []), ...defaultScopes] - : scopes || []; - const scopeSet = new ScopeSet(requestScopes); - parameters.set(SCOPE, scopeSet.printScopes()); -} -/** - * add clientId - * @param clientId - */ -function addClientId(parameters, clientId) { - parameters.set(CLIENT_ID, clientId); -} -/** - * add redirect_uri - * @param redirectUri - */ -function addRedirectUri(parameters, redirectUri) { - parameters.set(REDIRECT_URI, redirectUri); -} -/** - * add post logout redirectUri - * @param redirectUri - */ -function addPostLogoutRedirectUri(parameters, redirectUri) { - parameters.set(POST_LOGOUT_URI, redirectUri); -} -/** - * add id_token_hint to logout request - * @param idTokenHint - */ -function addIdTokenHint(parameters, idTokenHint) { - parameters.set(ID_TOKEN_HINT, idTokenHint); -} -/** - * add domain_hint - * @param domainHint - */ -function addDomainHint(parameters, domainHint) { - parameters.set(DOMAIN_HINT, domainHint); -} -/** - * add login_hint - * @param loginHint - */ -function addLoginHint(parameters, loginHint) { - parameters.set(LOGIN_HINT, loginHint); -} -/** - * Adds the CCS (Cache Credential Service) query parameter for login_hint - * @param loginHint - */ -function addCcsUpn(parameters, loginHint) { - parameters.set(HeaderNames.CCS_HEADER, `UPN:${loginHint}`); -} -/** - * Adds the CCS (Cache Credential Service) query parameter for account object - * @param loginHint - */ -function addCcsOid(parameters, clientInfo) { - parameters.set(HeaderNames.CCS_HEADER, `Oid:${clientInfo.uid}@${clientInfo.utid}`); -} -/** - * add sid - * @param sid - */ -function addSid(parameters, sid) { - parameters.set(SID, sid); -} -/** - * add claims - * @param claims - */ -function addClaims(parameters, claims, clientCapabilities) { - const mergedClaims = addClientCapabilitiesToClaims(claims, clientCapabilities); - try { - JSON.parse(mergedClaims); - } - catch (e) { - throw createClientConfigurationError(invalidClaims); - } - parameters.set(CLAIMS, mergedClaims); -} -/** - * add correlationId - * @param correlationId - */ -function addCorrelationId(parameters, correlationId) { - parameters.set(CLIENT_REQUEST_ID, correlationId); -} -/** - * add library info query params - * @param libraryInfo - */ -function addLibraryInfo(parameters, libraryInfo) { - // Telemetry Info - parameters.set(X_CLIENT_SKU, libraryInfo.sku); - parameters.set(X_CLIENT_VER, libraryInfo.version); - if (libraryInfo.os) { - parameters.set(X_CLIENT_OS, libraryInfo.os); - } - if (libraryInfo.cpu) { - parameters.set(X_CLIENT_CPU, libraryInfo.cpu); - } -} -/** - * Add client telemetry parameters - * @param appTelemetry - */ -function addApplicationTelemetry(parameters, appTelemetry) { - if (appTelemetry?.appName) { - parameters.set(X_APP_NAME, appTelemetry.appName); - } - if (appTelemetry?.appVersion) { - parameters.set(X_APP_VER, appTelemetry.appVersion); - } -} -/** - * add prompt - * @param prompt - */ -function addPrompt(parameters, prompt) { - parameters.set(PROMPT, prompt); -} -/** - * add state - * @param state - */ -function addState(parameters, state) { - if (state) { - parameters.set(STATE, state); - } -} -/** - * add nonce - * @param nonce - */ -function addNonce(parameters, nonce) { - parameters.set(NONCE, nonce); -} -/** - * add code_challenge and code_challenge_method - * - throw if either of them are not passed - * @param codeChallenge - * @param codeChallengeMethod - */ -function addCodeChallengeParams(parameters, codeChallenge, codeChallengeMethod) { - if (codeChallenge && codeChallengeMethod) { - parameters.set(CODE_CHALLENGE, codeChallenge); - parameters.set(CODE_CHALLENGE_METHOD, codeChallengeMethod); - } - else { - throw createClientConfigurationError(pkceParamsMissing); - } -} -/** - * add the `authorization_code` passed by the user to exchange for a token - * @param code - */ -function addAuthorizationCode(parameters, code) { - parameters.set(CODE, code); -} -/** - * add the `authorization_code` passed by the user to exchange for a token - * @param code - */ -function addDeviceCode(parameters, code) { - parameters.set(DEVICE_CODE, code); -} -/** - * add the `refreshToken` passed by the user - * @param refreshToken - */ -function addRefreshToken(parameters, refreshToken) { - parameters.set(REFRESH_TOKEN, refreshToken); -} -/** - * add the `code_verifier` passed by the user to exchange for a token - * @param codeVerifier - */ -function addCodeVerifier(parameters, codeVerifier) { - parameters.set(CODE_VERIFIER, codeVerifier); -} -/** - * add client_secret - * @param clientSecret - */ -function addClientSecret(parameters, clientSecret) { - parameters.set(CLIENT_SECRET, clientSecret); -} -/** - * add clientAssertion for confidential client flows - * @param clientAssertion - */ -function addClientAssertion(parameters, clientAssertion) { - if (clientAssertion) { - parameters.set(CLIENT_ASSERTION, clientAssertion); - } -} -/** - * add clientAssertionType for confidential client flows - * @param clientAssertionType - */ -function addClientAssertionType(parameters, clientAssertionType) { - if (clientAssertionType) { - parameters.set(CLIENT_ASSERTION_TYPE, clientAssertionType); - } -} -/** - * add OBO assertion for confidential client flows - * @param clientAssertion - */ -function addOboAssertion(parameters, oboAssertion) { - parameters.set(OBO_ASSERTION, oboAssertion); -} -/** - * add grant type - * @param grantType - */ -function addRequestTokenUse(parameters, tokenUse) { - parameters.set(REQUESTED_TOKEN_USE, tokenUse); -} -/** - * add grant type - * @param grantType - */ -function addGrantType(parameters, grantType) { - parameters.set(GRANT_TYPE, grantType); -} -/** - * add client info - * - */ -function addClientInfo(parameters) { - parameters.set(CLIENT_INFO, "1"); -} -function addInstanceAware(parameters) { - if (!parameters.has(INSTANCE_AWARE)) { - parameters.set(INSTANCE_AWARE, "true"); - } -} -/** - * add extraQueryParams - * @param eQParams - */ -function addExtraQueryParameters(parameters, eQParams) { - Object.entries(eQParams).forEach(([key, value]) => { - if (!parameters.has(key) && value) { - parameters.set(key, value); - } - }); -} -function addClientCapabilitiesToClaims(claims, clientCapabilities) { - let mergedClaims; - // Parse provided claims into JSON object or initialize empty object - if (!claims) { - mergedClaims = {}; - } - else { - try { - mergedClaims = JSON.parse(claims); - } - catch (e) { - throw createClientConfigurationError(invalidClaims); - } - } - if (clientCapabilities && clientCapabilities.length > 0) { - if (!mergedClaims.hasOwnProperty(ClaimsRequestKeys.ACCESS_TOKEN)) { - // Add access_token key to claims object - mergedClaims[ClaimsRequestKeys.ACCESS_TOKEN] = {}; - } - // Add xms_cc claim with provided clientCapabilities to access_token key - mergedClaims[ClaimsRequestKeys.ACCESS_TOKEN][ClaimsRequestKeys.XMS_CC] = - { - values: clientCapabilities, - }; - } - return JSON.stringify(mergedClaims); -} -/** - * adds `username` for Password Grant flow - * @param username - */ -function addUsername(parameters, username) { - parameters.set(PasswordGrantConstants.username, username); -} -/** - * adds `password` for Password Grant flow - * @param password - */ -function addPassword(parameters, password) { - parameters.set(PasswordGrantConstants.password, password); -} -/** - * add pop_jwk to query params - * @param cnfString - */ -function addPopToken(parameters, cnfString) { - if (cnfString) { - parameters.set(TOKEN_TYPE, AuthenticationScheme.POP); - parameters.set(REQ_CNF, cnfString); - } -} -/** - * add SSH JWK and key ID to query params - */ -function addSshJwk(parameters, sshJwkString) { - if (sshJwkString) { - parameters.set(TOKEN_TYPE, AuthenticationScheme.SSH); - parameters.set(REQ_CNF, sshJwkString); - } -} -/** - * add server telemetry fields - * @param serverTelemetryManager - */ -function addServerTelemetry(parameters, serverTelemetryManager) { - parameters.set(X_CLIENT_CURR_TELEM, serverTelemetryManager.generateCurrentRequestHeaderValue()); - parameters.set(X_CLIENT_LAST_TELEM, serverTelemetryManager.generateLastRequestHeaderValue()); -} -/** - * Adds parameter that indicates to the server that throttling is supported - */ -function addThrottling(parameters) { - parameters.set(X_MS_LIB_CAPABILITY, ThrottlingConstants.X_MS_LIB_CAPABILITY_VALUE); -} -/** - * Adds logout_hint parameter for "silent" logout which prevent server account picker - */ -function addLogoutHint(parameters, logoutHint) { - parameters.set(LOGOUT_HINT, logoutHint); -} -function addBrokerParameters(parameters, brokerClientId, brokerRedirectUri) { - if (!parameters.has(BROKER_CLIENT_ID)) { - parameters.set(BROKER_CLIENT_ID, brokerClientId); - } - if (!parameters.has(BROKER_REDIRECT_URI)) { - parameters.set(BROKER_REDIRECT_URI, brokerRedirectUri); - } -} -/** - * Add EAR (Encrypted Authorize Response) request parameters - * @param parameters - * @param jwk - */ -function addEARParameters(parameters, jwk) { - parameters.set(EAR_JWK, encodeURIComponent(jwk)); - // ear_jwe_crypto will always have value: {"alg":"dir","enc":"A256GCM"} so we can hardcode this - const jweCryptoB64Encoded = "eyJhbGciOiJkaXIiLCJlbmMiOiJBMjU2R0NNIn0"; - parameters.set(EAR_JWE_CRYPTO, jweCryptoB64Encoded); -} -/** - * Adds authorize body parameters to the request parameters - * @param parameters - * @param bodyParameters - */ -function addPostBodyParameters(parameters, bodyParameters) { - Object.entries(bodyParameters).forEach(([key, value]) => { - if (value) { - parameters.set(key, value); - } - }); -} - -export { addApplicationTelemetry, addAuthorizationCode, addBrokerParameters, addCcsOid, addCcsUpn, addClaims, addClientAssertion, addClientAssertionType, addClientCapabilitiesToClaims, addClientId, addClientInfo, addClientSecret, addCodeChallengeParams, addCodeVerifier, addCorrelationId, addDeviceCode, addDomainHint, addEARParameters, addExtraQueryParameters, addGrantType, addIdTokenHint, addInstanceAware, addLibraryInfo, addLoginHint, addLogoutHint, addNativeBroker, addNonce, addOboAssertion, addPassword, addPopToken, addPostBodyParameters, addPostLogoutRedirectUri, addPrompt, addRedirectUri, addRefreshToken, addRequestTokenUse, addResponseMode, addResponseType, addScopes, addServerTelemetry, addSid, addSshJwk, addState, addThrottling, addUsername, instrumentBrokerParams }; -//# sourceMappingURL=RequestParameterBuilder.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/request/ScopeSet.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/request/ScopeSet.mjs deleted file mode 100644 index b60814d8..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/request/ScopeSet.mjs +++ /dev/null @@ -1,204 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { createClientConfigurationError } from '../error/ClientConfigurationError.mjs'; -import { StringUtils } from '../utils/StringUtils.mjs'; -import { createClientAuthError } from '../error/ClientAuthError.mjs'; -import { Constants, OIDC_DEFAULT_SCOPES, OIDC_SCOPES } from '../utils/Constants.mjs'; -import { emptyInputScopesError } from '../error/ClientConfigurationErrorCodes.mjs'; -import { cannotAppendScopeSet, cannotRemoveEmptyScope, emptyInputScopeSet } from '../error/ClientAuthErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * The ScopeSet class creates a set of scopes. Scopes are case-insensitive, unique values, so the Set object in JS makes - * the most sense to implement for this class. All scopes are trimmed and converted to lower case strings in intersection and union functions - * to ensure uniqueness of strings. - */ -class ScopeSet { - constructor(inputScopes) { - // Filter empty string and null/undefined array items - const scopeArr = inputScopes - ? StringUtils.trimArrayEntries([...inputScopes]) - : []; - const filteredInput = scopeArr - ? StringUtils.removeEmptyStringsFromArray(scopeArr) - : []; - // Check if scopes array has at least one member - if (!filteredInput || !filteredInput.length) { - throw createClientConfigurationError(emptyInputScopesError); - } - this.scopes = new Set(); // Iterator in constructor not supported by IE11 - filteredInput.forEach((scope) => this.scopes.add(scope)); - } - /** - * Factory method to create ScopeSet from space-delimited string - * @param inputScopeString - * @param appClientId - * @param scopesRequired - */ - static fromString(inputScopeString) { - const scopeString = inputScopeString || Constants.EMPTY_STRING; - const inputScopes = scopeString.split(" "); - return new ScopeSet(inputScopes); - } - /** - * Creates the set of scopes to search for in cache lookups - * @param inputScopeString - * @returns - */ - static createSearchScopes(inputScopeString) { - // Handle empty scopes by using default OIDC scopes for cache lookup - const scopesToUse = inputScopeString && inputScopeString.length > 0 - ? inputScopeString - : [...OIDC_DEFAULT_SCOPES]; - const scopeSet = new ScopeSet(scopesToUse); - if (!scopeSet.containsOnlyOIDCScopes()) { - scopeSet.removeOIDCScopes(); - } - else { - scopeSet.removeScope(Constants.OFFLINE_ACCESS_SCOPE); - } - return scopeSet; - } - /** - * Check if a given scope is present in this set of scopes. - * @param scope - */ - containsScope(scope) { - const lowerCaseScopes = this.printScopesLowerCase().split(" "); - const lowerCaseScopesSet = new ScopeSet(lowerCaseScopes); - // compare lowercase scopes - return scope - ? lowerCaseScopesSet.scopes.has(scope.toLowerCase()) - : false; - } - /** - * Check if a set of scopes is present in this set of scopes. - * @param scopeSet - */ - containsScopeSet(scopeSet) { - if (!scopeSet || scopeSet.scopes.size <= 0) { - return false; - } - return (this.scopes.size >= scopeSet.scopes.size && - scopeSet.asArray().every((scope) => this.containsScope(scope))); - } - /** - * Check if set of scopes contains only the defaults - */ - containsOnlyOIDCScopes() { - let defaultScopeCount = 0; - OIDC_SCOPES.forEach((defaultScope) => { - if (this.containsScope(defaultScope)) { - defaultScopeCount += 1; - } - }); - return this.scopes.size === defaultScopeCount; - } - /** - * Appends single scope if passed - * @param newScope - */ - appendScope(newScope) { - if (newScope) { - this.scopes.add(newScope.trim()); - } - } - /** - * Appends multiple scopes if passed - * @param newScopes - */ - appendScopes(newScopes) { - try { - newScopes.forEach((newScope) => this.appendScope(newScope)); - } - catch (e) { - throw createClientAuthError(cannotAppendScopeSet); - } - } - /** - * Removes element from set of scopes. - * @param scope - */ - removeScope(scope) { - if (!scope) { - throw createClientAuthError(cannotRemoveEmptyScope); - } - this.scopes.delete(scope.trim()); - } - /** - * Removes default scopes from set of scopes - * Primarily used to prevent cache misses if the default scopes are not returned from the server - */ - removeOIDCScopes() { - OIDC_SCOPES.forEach((defaultScope) => { - this.scopes.delete(defaultScope); - }); - } - /** - * Combines an array of scopes with the current set of scopes. - * @param otherScopes - */ - unionScopeSets(otherScopes) { - if (!otherScopes) { - throw createClientAuthError(emptyInputScopeSet); - } - const unionScopes = new Set(); // Iterator in constructor not supported in IE11 - otherScopes.scopes.forEach((scope) => unionScopes.add(scope.toLowerCase())); - this.scopes.forEach((scope) => unionScopes.add(scope.toLowerCase())); - return unionScopes; - } - /** - * Check if scopes intersect between this set and another. - * @param otherScopes - */ - intersectingScopeSets(otherScopes) { - if (!otherScopes) { - throw createClientAuthError(emptyInputScopeSet); - } - // Do not allow OIDC scopes to be the only intersecting scopes - if (!otherScopes.containsOnlyOIDCScopes()) { - otherScopes.removeOIDCScopes(); - } - const unionScopes = this.unionScopeSets(otherScopes); - const sizeOtherScopes = otherScopes.getScopeCount(); - const sizeThisScopes = this.getScopeCount(); - const sizeUnionScopes = unionScopes.size; - return sizeUnionScopes < sizeThisScopes + sizeOtherScopes; - } - /** - * Returns size of set of scopes. - */ - getScopeCount() { - return this.scopes.size; - } - /** - * Returns the scopes as an array of string values - */ - asArray() { - const array = []; - this.scopes.forEach((val) => array.push(val)); - return array; - } - /** - * Prints scopes into a space-delimited string - */ - printScopes() { - if (this.scopes) { - const scopeArr = this.asArray(); - return scopeArr.join(" "); - } - return Constants.EMPTY_STRING; - } - /** - * Prints scopes into a space-delimited lower-case string (used for caching) - */ - printScopesLowerCase() { - return this.printScopes().toLowerCase(); - } -} - -export { ScopeSet }; -//# sourceMappingURL=ScopeSet.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/response/ResponseHandler.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/response/ResponseHandler.mjs deleted file mode 100644 index 4b9f0ffc..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/response/ResponseHandler.mjs +++ /dev/null @@ -1,350 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { createClientAuthError } from '../error/ClientAuthError.mjs'; -import { ServerError } from '../error/ServerError.mjs'; -import { ScopeSet } from '../request/ScopeSet.mjs'; -import { AccountEntity } from '../cache/entities/AccountEntity.mjs'; -import { isInteractionRequiredError, InteractionRequiredAuthError } from '../error/InteractionRequiredAuthError.mjs'; -import { ProtocolUtils } from '../utils/ProtocolUtils.mjs'; -import { Constants, HttpStatus, AuthenticationScheme, THE_FAMILY_ID } from '../utils/Constants.mjs'; -import { PopTokenGenerator } from '../crypto/PopTokenGenerator.mjs'; -import { TokenCacheContext } from '../cache/persistence/TokenCacheContext.mjs'; -import { PerformanceEvents } from '../telemetry/performance/PerformanceEvent.mjs'; -import { extractTokenClaims, checkMaxAge, isKmsi } from '../account/AuthToken.mjs'; -import { getTenantIdFromIdTokenClaims } from '../account/TokenClaims.mjs'; -import { updateAccountTenantProfileData, buildTenantProfile } from '../account/AccountInfo.mjs'; -import { createIdTokenEntity, createAccessTokenEntity, createRefreshTokenEntity } from '../cache/utils/CacheHelpers.mjs'; -import { toDateFromSeconds } from '../utils/TimeUtils.mjs'; -import { nonceMismatch, authTimeNotFound, invalidCacheEnvironment, keyIdMissing } from '../error/ClientAuthErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Class that handles response parsing. - * @internal - */ -class ResponseHandler { - constructor(clientId, cacheStorage, cryptoObj, logger, serializableCache, persistencePlugin, performanceClient) { - this.clientId = clientId; - this.cacheStorage = cacheStorage; - this.cryptoObj = cryptoObj; - this.logger = logger; - this.serializableCache = serializableCache; - this.persistencePlugin = persistencePlugin; - this.performanceClient = performanceClient; - } - /** - * Function which validates server authorization token response. - * @param serverResponse - * @param refreshAccessToken - */ - validateTokenResponse(serverResponse, refreshAccessToken) { - // Check for error - if (serverResponse.error || - serverResponse.error_description || - serverResponse.suberror) { - const errString = `Error(s): ${serverResponse.error_codes || Constants.NOT_AVAILABLE} - Timestamp: ${serverResponse.timestamp || Constants.NOT_AVAILABLE} - Description: ${serverResponse.error_description || Constants.NOT_AVAILABLE} - Correlation ID: ${serverResponse.correlation_id || Constants.NOT_AVAILABLE} - Trace ID: ${serverResponse.trace_id || Constants.NOT_AVAILABLE}`; - const serverErrorNo = serverResponse.error_codes?.length - ? serverResponse.error_codes[0] - : undefined; - const serverError = new ServerError(serverResponse.error, errString, serverResponse.suberror, serverErrorNo, serverResponse.status); - // check if 500 error - if (refreshAccessToken && - serverResponse.status && - serverResponse.status >= HttpStatus.SERVER_ERROR_RANGE_START && - serverResponse.status <= HttpStatus.SERVER_ERROR_RANGE_END) { - this.logger.warning(`executeTokenRequest:validateTokenResponse - AAD is currently unavailable and the access token is unable to be refreshed.\n${serverError}`); - // don't throw an exception, but alert the user via a log that the token was unable to be refreshed - return; - // check if 400 error - } - else if (refreshAccessToken && - serverResponse.status && - serverResponse.status >= HttpStatus.CLIENT_ERROR_RANGE_START && - serverResponse.status <= HttpStatus.CLIENT_ERROR_RANGE_END) { - this.logger.warning(`executeTokenRequest:validateTokenResponse - AAD is currently available but is unable to refresh the access token.\n${serverError}`); - // don't throw an exception, but alert the user via a log that the token was unable to be refreshed - return; - } - if (isInteractionRequiredError(serverResponse.error, serverResponse.error_description, serverResponse.suberror)) { - throw new InteractionRequiredAuthError(serverResponse.error, serverResponse.error_description, serverResponse.suberror, serverResponse.timestamp || Constants.EMPTY_STRING, serverResponse.trace_id || Constants.EMPTY_STRING, serverResponse.correlation_id || Constants.EMPTY_STRING, serverResponse.claims || Constants.EMPTY_STRING, serverErrorNo); - } - throw serverError; - } - } - /** - * Returns a constructed token response based on given string. Also manages the cache updates and cleanups. - * @param serverTokenResponse - * @param authority - */ - async handleServerTokenResponse(serverTokenResponse, authority, reqTimestamp, request, authCodePayload, userAssertionHash, handlingRefreshTokenResponse, forceCacheRefreshTokenResponse, serverRequestId) { - this.performanceClient?.addQueueMeasurement(PerformanceEvents.HandleServerTokenResponse, serverTokenResponse.correlation_id); - // create an idToken object (not entity) - let idTokenClaims; - if (serverTokenResponse.id_token) { - idTokenClaims = extractTokenClaims(serverTokenResponse.id_token || Constants.EMPTY_STRING, this.cryptoObj.base64Decode); - // token nonce check (TODO: Add a warning if no nonce is given?) - if (authCodePayload && authCodePayload.nonce) { - if (idTokenClaims.nonce !== authCodePayload.nonce) { - throw createClientAuthError(nonceMismatch); - } - } - // token max_age check - if (request.maxAge || request.maxAge === 0) { - const authTime = idTokenClaims.auth_time; - if (!authTime) { - throw createClientAuthError(authTimeNotFound); - } - checkMaxAge(authTime, request.maxAge); - } - } - // generate homeAccountId - this.homeAccountIdentifier = AccountEntity.generateHomeAccountId(serverTokenResponse.client_info || Constants.EMPTY_STRING, authority.authorityType, this.logger, this.cryptoObj, idTokenClaims); - // save the response tokens - let requestStateObj; - if (!!authCodePayload && !!authCodePayload.state) { - requestStateObj = ProtocolUtils.parseRequestState(this.cryptoObj, authCodePayload.state); - } - // Add keyId from request to serverTokenResponse if defined - serverTokenResponse.key_id = - serverTokenResponse.key_id || request.sshKid || undefined; - const cacheRecord = this.generateCacheRecord(serverTokenResponse, authority, reqTimestamp, request, idTokenClaims, userAssertionHash, authCodePayload); - let cacheContext; - try { - if (this.persistencePlugin && this.serializableCache) { - this.logger.verbose("Persistence enabled, calling beforeCacheAccess"); - cacheContext = new TokenCacheContext(this.serializableCache, true); - await this.persistencePlugin.beforeCacheAccess(cacheContext); - } - /* - * When saving a refreshed tokens to the cache, it is expected that the account that was used is present in the cache. - * If not present, we should return null, as it's the case that another application called removeAccount in between - * the calls to getAllAccounts and acquireTokenSilent. We should not overwrite that removal, unless explicitly flagged by - * the developer, as in the case of refresh token flow used in ADAL Node to MSAL Node migration. - */ - if (handlingRefreshTokenResponse && - !forceCacheRefreshTokenResponse && - cacheRecord.account) { - const key = this.cacheStorage.generateAccountKey(AccountEntity.getAccountInfo(cacheRecord.account)); - const account = this.cacheStorage.getAccount(key, request.correlationId); - if (!account) { - this.logger.warning("Account used to refresh tokens not in persistence, refreshed tokens will not be stored in the cache"); - return await ResponseHandler.generateAuthenticationResult(this.cryptoObj, authority, cacheRecord, false, request, idTokenClaims, requestStateObj, undefined, serverRequestId); - } - } - await this.cacheStorage.saveCacheRecord(cacheRecord, request.correlationId, isKmsi(idTokenClaims || {}), request.storeInCache); - } - finally { - if (this.persistencePlugin && - this.serializableCache && - cacheContext) { - this.logger.verbose("Persistence enabled, calling afterCacheAccess"); - await this.persistencePlugin.afterCacheAccess(cacheContext); - } - } - return ResponseHandler.generateAuthenticationResult(this.cryptoObj, authority, cacheRecord, false, request, idTokenClaims, requestStateObj, serverTokenResponse, serverRequestId); - } - /** - * Generates CacheRecord - * @param serverTokenResponse - * @param idTokenObj - * @param authority - */ - generateCacheRecord(serverTokenResponse, authority, reqTimestamp, request, idTokenClaims, userAssertionHash, authCodePayload) { - const env = authority.getPreferredCache(); - if (!env) { - throw createClientAuthError(invalidCacheEnvironment); - } - const claimsTenantId = getTenantIdFromIdTokenClaims(idTokenClaims); - // IdToken: non AAD scenarios can have empty realm - let cachedIdToken; - let cachedAccount; - if (serverTokenResponse.id_token && !!idTokenClaims) { - cachedIdToken = createIdTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.id_token, this.clientId, claimsTenantId || ""); - cachedAccount = buildAccountToCache(this.cacheStorage, authority, this.homeAccountIdentifier, this.cryptoObj.base64Decode, request.correlationId, idTokenClaims, serverTokenResponse.client_info, env, claimsTenantId, authCodePayload, undefined, // nativeAccountId - this.logger); - } - // AccessToken - let cachedAccessToken = null; - if (serverTokenResponse.access_token) { - // If scopes not returned in server response, use request scopes - const responseScopes = serverTokenResponse.scope - ? ScopeSet.fromString(serverTokenResponse.scope) - : new ScopeSet(request.scopes || []); - /* - * Use timestamp calculated before request - * Server may return timestamps as strings, parse to numbers if so. - */ - const expiresIn = (typeof serverTokenResponse.expires_in === "string" - ? parseInt(serverTokenResponse.expires_in, 10) - : serverTokenResponse.expires_in) || 0; - const extExpiresIn = (typeof serverTokenResponse.ext_expires_in === "string" - ? parseInt(serverTokenResponse.ext_expires_in, 10) - : serverTokenResponse.ext_expires_in) || 0; - const refreshIn = (typeof serverTokenResponse.refresh_in === "string" - ? parseInt(serverTokenResponse.refresh_in, 10) - : serverTokenResponse.refresh_in) || undefined; - const tokenExpirationSeconds = reqTimestamp + expiresIn; - const extendedTokenExpirationSeconds = tokenExpirationSeconds + extExpiresIn; - const refreshOnSeconds = refreshIn && refreshIn > 0 - ? reqTimestamp + refreshIn - : undefined; - // non AAD scenarios can have empty realm - cachedAccessToken = createAccessTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.access_token, this.clientId, claimsTenantId || authority.tenant || "", responseScopes.printScopes(), tokenExpirationSeconds, extendedTokenExpirationSeconds, this.cryptoObj.base64Decode, refreshOnSeconds, serverTokenResponse.token_type, userAssertionHash, serverTokenResponse.key_id, request.claims, request.requestedClaimsHash); - } - // refreshToken - let cachedRefreshToken = null; - if (serverTokenResponse.refresh_token) { - let rtExpiresOn; - if (serverTokenResponse.refresh_token_expires_in) { - const rtExpiresIn = typeof serverTokenResponse.refresh_token_expires_in === - "string" - ? parseInt(serverTokenResponse.refresh_token_expires_in, 10) - : serverTokenResponse.refresh_token_expires_in; - rtExpiresOn = reqTimestamp + rtExpiresIn; - } - cachedRefreshToken = createRefreshTokenEntity(this.homeAccountIdentifier, env, serverTokenResponse.refresh_token, this.clientId, serverTokenResponse.foci, userAssertionHash, rtExpiresOn); - } - // appMetadata - let cachedAppMetadata = null; - if (serverTokenResponse.foci) { - cachedAppMetadata = { - clientId: this.clientId, - environment: env, - familyId: serverTokenResponse.foci, - }; - } - return { - account: cachedAccount, - idToken: cachedIdToken, - accessToken: cachedAccessToken, - refreshToken: cachedRefreshToken, - appMetadata: cachedAppMetadata, - }; - } - /** - * Creates an @AuthenticationResult from @CacheRecord , @IdToken , and a boolean that states whether or not the result is from cache. - * - * Optionally takes a state string that is set as-is in the response. - * - * @param cacheRecord - * @param idTokenObj - * @param fromTokenCache - * @param stateString - */ - static async generateAuthenticationResult(cryptoObj, authority, cacheRecord, fromTokenCache, request, idTokenClaims, requestState, serverTokenResponse, requestId) { - let accessToken = Constants.EMPTY_STRING; - let responseScopes = []; - let expiresOn = null; - let extExpiresOn; - let refreshOn; - let familyId = Constants.EMPTY_STRING; - if (cacheRecord.accessToken) { - /* - * if the request object has `popKid` property, `signPopToken` will be set to false and - * the token will be returned unsigned - */ - if (cacheRecord.accessToken.tokenType === - AuthenticationScheme.POP && - !request.popKid) { - const popTokenGenerator = new PopTokenGenerator(cryptoObj); - const { secret, keyId } = cacheRecord.accessToken; - if (!keyId) { - throw createClientAuthError(keyIdMissing); - } - accessToken = await popTokenGenerator.signPopToken(secret, keyId, request); - } - else { - accessToken = cacheRecord.accessToken.secret; - } - responseScopes = ScopeSet.fromString(cacheRecord.accessToken.target).asArray(); - // Access token expiresOn cached in seconds, converting to Date for AuthenticationResult - expiresOn = toDateFromSeconds(cacheRecord.accessToken.expiresOn); - extExpiresOn = toDateFromSeconds(cacheRecord.accessToken.extendedExpiresOn); - if (cacheRecord.accessToken.refreshOn) { - refreshOn = toDateFromSeconds(cacheRecord.accessToken.refreshOn); - } - } - if (cacheRecord.appMetadata) { - familyId = - cacheRecord.appMetadata.familyId === THE_FAMILY_ID - ? THE_FAMILY_ID - : ""; - } - const uid = idTokenClaims?.oid || idTokenClaims?.sub || ""; - const tid = idTokenClaims?.tid || ""; - // for hybrid + native bridge enablement, send back the native account Id - if (serverTokenResponse?.spa_accountid && !!cacheRecord.account) { - cacheRecord.account.nativeAccountId = - serverTokenResponse?.spa_accountid; - } - const accountInfo = cacheRecord.account - ? updateAccountTenantProfileData(AccountEntity.getAccountInfo(cacheRecord.account), undefined, // tenantProfile optional - idTokenClaims, cacheRecord.idToken?.secret) - : null; - return { - authority: authority.canonicalAuthority, - uniqueId: uid, - tenantId: tid, - scopes: responseScopes, - account: accountInfo, - idToken: cacheRecord?.idToken?.secret || "", - idTokenClaims: idTokenClaims || {}, - accessToken: accessToken, - fromCache: fromTokenCache, - expiresOn: expiresOn, - extExpiresOn: extExpiresOn, - refreshOn: refreshOn, - correlationId: request.correlationId, - requestId: requestId || Constants.EMPTY_STRING, - familyId: familyId, - tokenType: cacheRecord.accessToken?.tokenType || Constants.EMPTY_STRING, - state: requestState - ? requestState.userRequestState - : Constants.EMPTY_STRING, - cloudGraphHostName: cacheRecord.account?.cloudGraphHostName || - Constants.EMPTY_STRING, - msGraphHost: cacheRecord.account?.msGraphHost || Constants.EMPTY_STRING, - code: serverTokenResponse?.spa_code, - fromNativeBroker: false, - }; - } -} -function buildAccountToCache(cacheStorage, authority, homeAccountId, base64Decode, correlationId, idTokenClaims, clientInfo, environment, claimsTenantId, authCodePayload, nativeAccountId, logger) { - logger?.verbose("setCachedAccount called"); - // Check if base account is already cached - const accountKeys = cacheStorage.getAccountKeys(); - const baseAccountKey = accountKeys.find((accountKey) => { - return accountKey.startsWith(homeAccountId); - }); - let cachedAccount = null; - if (baseAccountKey) { - cachedAccount = cacheStorage.getAccount(baseAccountKey, correlationId); - } - const baseAccount = cachedAccount || - AccountEntity.createAccount({ - homeAccountId, - idTokenClaims, - clientInfo, - environment, - cloudGraphHostName: authCodePayload?.cloud_graph_host_name, - msGraphHost: authCodePayload?.msgraph_host, - nativeAccountId: nativeAccountId, - }, authority, base64Decode); - const tenantProfiles = baseAccount.tenantProfiles || []; - const tenantId = claimsTenantId || baseAccount.realm; - if (tenantId && - !tenantProfiles.find((tenantProfile) => { - return tenantProfile.tenantId === tenantId; - })) { - const newTenantProfile = buildTenantProfile(homeAccountId, baseAccount.localAccountId, tenantId, idTokenClaims); - tenantProfiles.push(newTenantProfile); - } - baseAccount.tenantProfiles = tenantProfiles; - return baseAccount; -} - -export { ResponseHandler, buildAccountToCache }; -//# sourceMappingURL=ResponseHandler.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceEvent.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceEvent.mjs deleted file mode 100644 index 8acf86b6..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/telemetry/performance/PerformanceEvent.mjs +++ /dev/null @@ -1,526 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Enumeration of operations that are instrumented by have their performance measured by the PerformanceClient. - * - * @export - * @enum {number} - */ -const PerformanceEvents = { - /** - * acquireTokenByCode API (msal-browser and msal-node). - * Used to acquire tokens by trading an authorization code against the token endpoint. - */ - AcquireTokenByCode: "acquireTokenByCode", - /** - * acquireTokenByRefreshToken API (msal-browser and msal-node). - * Used to renew an access token using a refresh token against the token endpoint. - */ - AcquireTokenByRefreshToken: "acquireTokenByRefreshToken", - /** - * acquireTokenSilent API (msal-browser and msal-node). - * Used to silently acquire a new access token (from the cache or the network). - */ - AcquireTokenSilent: "acquireTokenSilent", - /** - * acquireTokenSilentAsync (msal-browser). - * Internal API for acquireTokenSilent. - */ - AcquireTokenSilentAsync: "acquireTokenSilentAsync", - /** - * acquireTokenPopup (msal-browser). - * Used to acquire a new access token interactively through pop ups - */ - AcquireTokenPopup: "acquireTokenPopup", - /** - * acquireTokenPreRedirect (msal-browser). - * First part of the redirect flow. - * Used to acquire a new access token interactively through redirects. - */ - AcquireTokenPreRedirect: "acquireTokenPreRedirect", - /** - * acquireTokenRedirect (msal-browser). - * Second part of the redirect flow. - * Used to acquire a new access token interactively through redirects. - */ - AcquireTokenRedirect: "acquireTokenRedirect", - /** - * getPublicKeyThumbprint API in CryptoOpts class (msal-browser). - * Used to generate a public/private keypair and generate a public key thumbprint for pop requests. - */ - CryptoOptsGetPublicKeyThumbprint: "cryptoOptsGetPublicKeyThumbprint", - /** - * signJwt API in CryptoOpts class (msal-browser). - * Used to signed a pop token. - */ - CryptoOptsSignJwt: "cryptoOptsSignJwt", - /** - * acquireToken API in the SilentCacheClient class (msal-browser). - * Used to read access tokens from the cache. - */ - SilentCacheClientAcquireToken: "silentCacheClientAcquireToken", - /** - * acquireToken API in the SilentIframeClient class (msal-browser). - * Used to acquire a new set of tokens from the authorize endpoint in a hidden iframe. - */ - SilentIframeClientAcquireToken: "silentIframeClientAcquireToken", - AwaitConcurrentIframe: "awaitConcurrentIframe", - /** - * acquireToken API in SilentRereshClient (msal-browser). - * Used to acquire a new set of tokens from the token endpoint using a refresh token. - */ - SilentRefreshClientAcquireToken: "silentRefreshClientAcquireToken", - /** - * ssoSilent API (msal-browser). - * Used to silently acquire an authorization code and set of tokens using a hidden iframe. - */ - SsoSilent: "ssoSilent", - /** - * getDiscoveredAuthority API in StandardInteractionClient class (msal-browser). - * Used to load authority metadata for a request. - */ - StandardInteractionClientGetDiscoveredAuthority: "standardInteractionClientGetDiscoveredAuthority", - /** - * acquireToken APIs in msal-browser. - * Used to make an /authorize endpoint call with native brokering enabled. - */ - FetchAccountIdWithNativeBroker: "fetchAccountIdWithNativeBroker", - /** - * acquireToken API in NativeInteractionClient class (msal-browser). - * Used to acquire a token from Native component when native brokering is enabled. - */ - NativeInteractionClientAcquireToken: "nativeInteractionClientAcquireToken", - /** - * Time spent creating default headers for requests to token endpoint - */ - BaseClientCreateTokenRequestHeaders: "baseClientCreateTokenRequestHeaders", - /** - * Time spent sending/waiting for the response of a request to the token endpoint - */ - NetworkClientSendPostRequestAsync: "networkClientSendPostRequestAsync", - RefreshTokenClientExecutePostToTokenEndpoint: "refreshTokenClientExecutePostToTokenEndpoint", - AuthorizationCodeClientExecutePostToTokenEndpoint: "authorizationCodeClientExecutePostToTokenEndpoint", - /** - * Used to measure the time taken for completing embedded-broker handshake (PW-Broker). - */ - BrokerHandhshake: "brokerHandshake", - /** - * acquireTokenByRefreshToken API in BrokerClientApplication (PW-Broker) . - */ - AcquireTokenByRefreshTokenInBroker: "acquireTokenByRefreshTokenInBroker", - /** - * Time taken for token acquisition by broker - */ - AcquireTokenByBroker: "acquireTokenByBroker", - /** - * Time spent on the network for refresh token acquisition - */ - RefreshTokenClientExecuteTokenRequest: "refreshTokenClientExecuteTokenRequest", - /** - * Time taken for acquiring refresh token , records RT size - */ - RefreshTokenClientAcquireToken: "refreshTokenClientAcquireToken", - /** - * Time taken for acquiring cached refresh token - */ - RefreshTokenClientAcquireTokenWithCachedRefreshToken: "refreshTokenClientAcquireTokenWithCachedRefreshToken", - /** - * acquireTokenByRefreshToken API in RefreshTokenClient (msal-common). - */ - RefreshTokenClientAcquireTokenByRefreshToken: "refreshTokenClientAcquireTokenByRefreshToken", - /** - * Helper function to create token request body in RefreshTokenClient (msal-common). - */ - RefreshTokenClientCreateTokenRequestBody: "refreshTokenClientCreateTokenRequestBody", - /** - * acquireTokenFromCache (msal-browser). - * Internal API for acquiring token from cache - */ - AcquireTokenFromCache: "acquireTokenFromCache", - SilentFlowClientAcquireCachedToken: "silentFlowClientAcquireCachedToken", - SilentFlowClientGenerateResultFromCacheRecord: "silentFlowClientGenerateResultFromCacheRecord", - /** - * acquireTokenBySilentIframe (msal-browser). - * Internal API for acquiring token by silent Iframe - */ - AcquireTokenBySilentIframe: "acquireTokenBySilentIframe", - /** - * Internal API for initializing base request in BaseInteractionClient (msal-browser) - */ - InitializeBaseRequest: "initializeBaseRequest", - /** - * Internal API for initializing silent request in SilentCacheClient (msal-browser) - */ - InitializeSilentRequest: "initializeSilentRequest", - InitializeClientApplication: "initializeClientApplication", - InitializeCache: "initializeCache", - /** - * Helper function in SilentIframeClient class (msal-browser). - */ - SilentIframeClientTokenHelper: "silentIframeClientTokenHelper", - /** - * SilentHandler - */ - SilentHandlerInitiateAuthRequest: "silentHandlerInitiateAuthRequest", - SilentHandlerMonitorIframeForHash: "silentHandlerMonitorIframeForHash", - SilentHandlerLoadFrame: "silentHandlerLoadFrame", - SilentHandlerLoadFrameSync: "silentHandlerLoadFrameSync", - /** - * Helper functions in StandardInteractionClient class (msal-browser) - */ - StandardInteractionClientCreateAuthCodeClient: "standardInteractionClientCreateAuthCodeClient", - StandardInteractionClientGetClientConfiguration: "standardInteractionClientGetClientConfiguration", - StandardInteractionClientInitializeAuthorizationRequest: "standardInteractionClientInitializeAuthorizationRequest", - /** - * getAuthCodeUrl API (msal-browser and msal-node). - */ - GetAuthCodeUrl: "getAuthCodeUrl", - GetStandardParams: "getStandardParams", - /** - * Functions from InteractionHandler (msal-browser) - */ - HandleCodeResponseFromServer: "handleCodeResponseFromServer", - HandleCodeResponse: "handleCodeResponse", - HandleResponseEar: "handleResponseEar", - HandleResponsePlatformBroker: "handleResponsePlatformBroker", - HandleResponseCode: "handleResponseCode", - UpdateTokenEndpointAuthority: "updateTokenEndpointAuthority", - /** - * APIs in Authorization Code Client (msal-common) - */ - AuthClientAcquireToken: "authClientAcquireToken", - AuthClientExecuteTokenRequest: "authClientExecuteTokenRequest", - AuthClientCreateTokenRequestBody: "authClientCreateTokenRequestBody", - /** - * Generate functions in PopTokenGenerator (msal-common) - */ - PopTokenGenerateCnf: "popTokenGenerateCnf", - PopTokenGenerateKid: "popTokenGenerateKid", - /** - * handleServerTokenResponse API in ResponseHandler (msal-common) - */ - HandleServerTokenResponse: "handleServerTokenResponse", - DeserializeResponse: "deserializeResponse", - /** - * Authority functions - */ - AuthorityFactoryCreateDiscoveredInstance: "authorityFactoryCreateDiscoveredInstance", - AuthorityResolveEndpointsAsync: "authorityResolveEndpointsAsync", - AuthorityResolveEndpointsFromLocalSources: "authorityResolveEndpointsFromLocalSources", - AuthorityGetCloudDiscoveryMetadataFromNetwork: "authorityGetCloudDiscoveryMetadataFromNetwork", - AuthorityUpdateCloudDiscoveryMetadata: "authorityUpdateCloudDiscoveryMetadata", - AuthorityGetEndpointMetadataFromNetwork: "authorityGetEndpointMetadataFromNetwork", - AuthorityUpdateEndpointMetadata: "authorityUpdateEndpointMetadata", - AuthorityUpdateMetadataWithRegionalInformation: "authorityUpdateMetadataWithRegionalInformation", - /** - * Region Discovery functions - */ - RegionDiscoveryDetectRegion: "regionDiscoveryDetectRegion", - RegionDiscoveryGetRegionFromIMDS: "regionDiscoveryGetRegionFromIMDS", - RegionDiscoveryGetCurrentVersion: "regionDiscoveryGetCurrentVersion", - AcquireTokenByCodeAsync: "acquireTokenByCodeAsync", - GetEndpointMetadataFromNetwork: "getEndpointMetadataFromNetwork", - GetCloudDiscoveryMetadataFromNetworkMeasurement: "getCloudDiscoveryMetadataFromNetworkMeasurement", - HandleRedirectPromiseMeasurement: "handleRedirectPromise", - HandleNativeRedirectPromiseMeasurement: "handleNativeRedirectPromise", - UpdateCloudDiscoveryMetadataMeasurement: "updateCloudDiscoveryMetadataMeasurement", - UsernamePasswordClientAcquireToken: "usernamePasswordClientAcquireToken", - NativeMessageHandlerHandshake: "nativeMessageHandlerHandshake", - NativeGenerateAuthResult: "nativeGenerateAuthResult", - RemoveHiddenIframe: "removeHiddenIframe", - /** - * Cache operations - */ - ClearTokensAndKeysWithClaims: "clearTokensAndKeysWithClaims", - CacheManagerGetRefreshToken: "cacheManagerGetRefreshToken", - ImportExistingCache: "importExistingCache", - SetUserData: "setUserData", - LocalStorageUpdated: "localStorageUpdated", - /** - * Crypto Operations - */ - GeneratePkceCodes: "generatePkceCodes", - GenerateCodeVerifier: "generateCodeVerifier", - GenerateCodeChallengeFromVerifier: "generateCodeChallengeFromVerifier", - Sha256Digest: "sha256Digest", - GetRandomValues: "getRandomValues", - GenerateHKDF: "generateHKDF", - GenerateBaseKey: "generateBaseKey", - Base64Decode: "base64Decode", - UrlEncodeArr: "urlEncodeArr", - Encrypt: "encrypt", - Decrypt: "decrypt", - GenerateEarKey: "generateEarKey", - DecryptEarResponse: "decryptEarResponse", -}; -const PerformanceEventAbbreviations = new Map([ - [PerformanceEvents.AcquireTokenByCode, "ATByCode"], - [PerformanceEvents.AcquireTokenByRefreshToken, "ATByRT"], - [PerformanceEvents.AcquireTokenSilent, "ATS"], - [PerformanceEvents.AcquireTokenSilentAsync, "ATSAsync"], - [PerformanceEvents.AcquireTokenPopup, "ATPopup"], - [PerformanceEvents.AcquireTokenRedirect, "ATRedirect"], - [ - PerformanceEvents.CryptoOptsGetPublicKeyThumbprint, - "CryptoGetPKThumb", - ], - [PerformanceEvents.CryptoOptsSignJwt, "CryptoSignJwt"], - [PerformanceEvents.SilentCacheClientAcquireToken, "SltCacheClientAT"], - [PerformanceEvents.SilentIframeClientAcquireToken, "SltIframeClientAT"], - [PerformanceEvents.SilentRefreshClientAcquireToken, "SltRClientAT"], - [PerformanceEvents.SsoSilent, "SsoSlt"], - [ - PerformanceEvents.StandardInteractionClientGetDiscoveredAuthority, - "StdIntClientGetDiscAuth", - ], - [ - PerformanceEvents.FetchAccountIdWithNativeBroker, - "FetchAccIdWithNtvBroker", - ], - [ - PerformanceEvents.NativeInteractionClientAcquireToken, - "NtvIntClientAT", - ], - [ - PerformanceEvents.BaseClientCreateTokenRequestHeaders, - "BaseClientCreateTReqHead", - ], - [ - PerformanceEvents.NetworkClientSendPostRequestAsync, - "NetClientSendPost", - ], - [ - PerformanceEvents.RefreshTokenClientExecutePostToTokenEndpoint, - "RTClientExecPost", - ], - [ - PerformanceEvents.AuthorizationCodeClientExecutePostToTokenEndpoint, - "AuthCodeClientExecPost", - ], - [PerformanceEvents.BrokerHandhshake, "BrokerHandshake"], - [ - PerformanceEvents.AcquireTokenByRefreshTokenInBroker, - "ATByRTInBroker", - ], - [PerformanceEvents.AcquireTokenByBroker, "ATByBroker"], - [ - PerformanceEvents.RefreshTokenClientExecuteTokenRequest, - "RTClientExecTReq", - ], - [PerformanceEvents.RefreshTokenClientAcquireToken, "RTClientAT"], - [ - PerformanceEvents.RefreshTokenClientAcquireTokenWithCachedRefreshToken, - "RTClientATWithCachedRT", - ], - [ - PerformanceEvents.RefreshTokenClientAcquireTokenByRefreshToken, - "RTClientATByRT", - ], - [ - PerformanceEvents.RefreshTokenClientCreateTokenRequestBody, - "RTClientCreateTReqBody", - ], - [PerformanceEvents.AcquireTokenFromCache, "ATFromCache"], - [ - PerformanceEvents.SilentFlowClientAcquireCachedToken, - "SltFlowClientATCached", - ], - [ - PerformanceEvents.SilentFlowClientGenerateResultFromCacheRecord, - "SltFlowClientGenResFromCache", - ], - [PerformanceEvents.AcquireTokenBySilentIframe, "ATBySltIframe"], - [PerformanceEvents.InitializeBaseRequest, "InitBaseReq"], - [PerformanceEvents.InitializeSilentRequest, "InitSltReq"], - [ - PerformanceEvents.InitializeClientApplication, - "InitClientApplication", - ], - [PerformanceEvents.InitializeCache, "InitCache"], - [PerformanceEvents.ImportExistingCache, "importCache"], - [PerformanceEvents.SetUserData, "setUserData"], - [PerformanceEvents.LocalStorageUpdated, "localStorageUpdated"], - [PerformanceEvents.SilentIframeClientTokenHelper, "SIClientTHelper"], - [ - PerformanceEvents.SilentHandlerInitiateAuthRequest, - "SHandlerInitAuthReq", - ], - [ - PerformanceEvents.SilentHandlerMonitorIframeForHash, - "SltHandlerMonitorIframeForHash", - ], - [PerformanceEvents.SilentHandlerLoadFrame, "SHandlerLoadFrame"], - [PerformanceEvents.SilentHandlerLoadFrameSync, "SHandlerLoadFrameSync"], - [ - PerformanceEvents.StandardInteractionClientCreateAuthCodeClient, - "StdIntClientCreateAuthCodeClient", - ], - [ - PerformanceEvents.StandardInteractionClientGetClientConfiguration, - "StdIntClientGetClientConf", - ], - [ - PerformanceEvents.StandardInteractionClientInitializeAuthorizationRequest, - "StdIntClientInitAuthReq", - ], - [PerformanceEvents.GetAuthCodeUrl, "GetAuthCodeUrl"], - [ - PerformanceEvents.HandleCodeResponseFromServer, - "HandleCodeResFromServer", - ], - [PerformanceEvents.HandleCodeResponse, "HandleCodeResp"], - [PerformanceEvents.HandleResponseEar, "HandleRespEar"], - [PerformanceEvents.HandleResponseCode, "HandleRespCode"], - [ - PerformanceEvents.HandleResponsePlatformBroker, - "HandleRespPlatBroker", - ], - [PerformanceEvents.UpdateTokenEndpointAuthority, "UpdTEndpointAuth"], - [PerformanceEvents.AuthClientAcquireToken, "AuthClientAT"], - [PerformanceEvents.AuthClientExecuteTokenRequest, "AuthClientExecTReq"], - [ - PerformanceEvents.AuthClientCreateTokenRequestBody, - "AuthClientCreateTReqBody", - ], - [PerformanceEvents.PopTokenGenerateCnf, "PopTGenCnf"], - [PerformanceEvents.PopTokenGenerateKid, "PopTGenKid"], - [PerformanceEvents.HandleServerTokenResponse, "HandleServerTRes"], - [PerformanceEvents.DeserializeResponse, "DeserializeRes"], - [ - PerformanceEvents.AuthorityFactoryCreateDiscoveredInstance, - "AuthFactCreateDiscInst", - ], - [ - PerformanceEvents.AuthorityResolveEndpointsAsync, - "AuthResolveEndpointsAsync", - ], - [ - PerformanceEvents.AuthorityResolveEndpointsFromLocalSources, - "AuthResolveEndpointsFromLocal", - ], - [ - PerformanceEvents.AuthorityGetCloudDiscoveryMetadataFromNetwork, - "AuthGetCDMetaFromNet", - ], - [ - PerformanceEvents.AuthorityUpdateCloudDiscoveryMetadata, - "AuthUpdCDMeta", - ], - [ - PerformanceEvents.AuthorityGetEndpointMetadataFromNetwork, - "AuthUpdCDMetaFromNet", - ], - [ - PerformanceEvents.AuthorityUpdateEndpointMetadata, - "AuthUpdEndpointMeta", - ], - [ - PerformanceEvents.AuthorityUpdateMetadataWithRegionalInformation, - "AuthUpdMetaWithRegInfo", - ], - [PerformanceEvents.RegionDiscoveryDetectRegion, "RegDiscDetectReg"], - [ - PerformanceEvents.RegionDiscoveryGetRegionFromIMDS, - "RegDiscGetRegFromIMDS", - ], - [ - PerformanceEvents.RegionDiscoveryGetCurrentVersion, - "RegDiscGetCurrentVer", - ], - [PerformanceEvents.AcquireTokenByCodeAsync, "ATByCodeAsync"], - [ - PerformanceEvents.GetEndpointMetadataFromNetwork, - "GetEndpointMetaFromNet", - ], - [ - PerformanceEvents.GetCloudDiscoveryMetadataFromNetworkMeasurement, - "GetCDMetaFromNet", - ], - [ - PerformanceEvents.HandleRedirectPromiseMeasurement, - "HandleRedirectPromise", - ], - [ - PerformanceEvents.HandleNativeRedirectPromiseMeasurement, - "HandleNtvRedirectPromise", - ], - [ - PerformanceEvents.UpdateCloudDiscoveryMetadataMeasurement, - "UpdateCDMeta", - ], - [ - PerformanceEvents.UsernamePasswordClientAcquireToken, - "UserPassClientAT", - ], - [ - PerformanceEvents.NativeMessageHandlerHandshake, - "NtvMsgHandlerHandshake", - ], - [PerformanceEvents.NativeGenerateAuthResult, "NtvGenAuthRes"], - [PerformanceEvents.RemoveHiddenIframe, "RemoveHiddenIframe"], - [ - PerformanceEvents.ClearTokensAndKeysWithClaims, - "ClearTAndKeysWithClaims", - ], - [PerformanceEvents.CacheManagerGetRefreshToken, "CacheManagerGetRT"], - [PerformanceEvents.GeneratePkceCodes, "GenPkceCodes"], - [PerformanceEvents.GenerateCodeVerifier, "GenCodeVerifier"], - [ - PerformanceEvents.GenerateCodeChallengeFromVerifier, - "GenCodeChallengeFromVerifier", - ], - [PerformanceEvents.Sha256Digest, "Sha256Digest"], - [PerformanceEvents.GetRandomValues, "GetRandomValues"], - [PerformanceEvents.GenerateHKDF, "genHKDF"], - [PerformanceEvents.GenerateBaseKey, "genBaseKey"], - [PerformanceEvents.Base64Decode, "b64Decode"], - [PerformanceEvents.UrlEncodeArr, "urlEncArr"], - [PerformanceEvents.Encrypt, "encrypt"], - [PerformanceEvents.Decrypt, "decrypt"], - [PerformanceEvents.GenerateEarKey, "genEarKey"], - [PerformanceEvents.DecryptEarResponse, "decryptEarResp"], -]); -/** - * State of the performance event. - * - * @export - * @enum {number} - */ -const PerformanceEventStatus = { - NotStarted: 0, - InProgress: 1, - Completed: 2, -}; -const IntFields = new Set([ - "accessTokenSize", - "durationMs", - "idTokenSize", - "matsSilentStatus", - "matsHttpStatus", - "refreshTokenSize", - "queuedTimeMs", - "startTimeMs", - "status", - "multiMatchedAT", - "multiMatchedID", - "multiMatchedRT", - "unencryptedCacheCount", - "encryptedCacheExpiredCount", - "oldAccountCount", - "oldAccessCount", - "oldIdCount", - "oldRefreshCount", - "currAccountCount", - "currAccessCount", - "currIdCount", - "currRefreshCount", - "expiredCacheRemovedCount", - "upgradedCacheCount", -]); - -export { IntFields, PerformanceEventAbbreviations, PerformanceEventStatus, PerformanceEvents }; -//# sourceMappingURL=PerformanceEvent.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/telemetry/performance/StubPerformanceClient.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/telemetry/performance/StubPerformanceClient.mjs deleted file mode 100644 index 4d6ce0ad..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/telemetry/performance/StubPerformanceClient.mjs +++ /dev/null @@ -1,83 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { PerformanceEventStatus } from './PerformanceEvent.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -class StubPerformanceMeasurement { - startMeasurement() { - return; - } - endMeasurement() { - return; - } - flushMeasurement() { - return null; - } -} -class StubPerformanceClient { - generateId() { - return "callback-id"; - } - startMeasurement(measureName, correlationId) { - return { - end: () => null, - discard: () => { }, - add: () => { }, - increment: () => { }, - event: { - eventId: this.generateId(), - status: PerformanceEventStatus.InProgress, - authority: "", - libraryName: "", - libraryVersion: "", - clientId: "", - name: measureName, - startTimeMs: Date.now(), - correlationId: correlationId || "", - }, - measurement: new StubPerformanceMeasurement(), - }; - } - startPerformanceMeasurement() { - return new StubPerformanceMeasurement(); - } - calculateQueuedTime() { - return 0; - } - addQueueMeasurement() { - return; - } - setPreQueueTime() { - return; - } - endMeasurement() { - return null; - } - discardMeasurements() { - return; - } - removePerformanceCallback() { - return true; - } - addPerformanceCallback() { - return ""; - } - emitEvents() { - return; - } - addFields() { - return; - } - incrementFields() { - return; - } - cacheEventByCorrelationId() { - return; - } -} - -export { StubPerformanceClient, StubPerformanceMeasurement }; -//# sourceMappingURL=StubPerformanceClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/telemetry/server/ServerTelemetryManager.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/telemetry/server/ServerTelemetryManager.mjs deleted file mode 100644 index 8f731d00..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/telemetry/server/ServerTelemetryManager.mjs +++ /dev/null @@ -1,268 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { CacheOutcome, Constants, SERVER_TELEM_CONSTANTS, Separators } from '../../utils/Constants.mjs'; -import { AuthError } from '../../error/AuthError.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const skuGroupSeparator = ","; -const skuValueSeparator = "|"; -function makeExtraSkuString(params) { - const { skus, libraryName, libraryVersion, extensionName, extensionVersion, } = params; - const skuMap = new Map([ - [0, [libraryName, libraryVersion]], - [2, [extensionName, extensionVersion]], - ]); - let skuArr = []; - if (skus?.length) { - skuArr = skus.split(skuGroupSeparator); - // Ignore invalid input sku param - if (skuArr.length < 4) { - return skus; - } - } - else { - skuArr = Array.from({ length: 4 }, () => skuValueSeparator); - } - skuMap.forEach((value, key) => { - if (value.length === 2 && value[0]?.length && value[1]?.length) { - setSku({ - skuArr, - index: key, - skuName: value[0], - skuVersion: value[1], - }); - } - }); - return skuArr.join(skuGroupSeparator); -} -function setSku(params) { - const { skuArr, index, skuName, skuVersion } = params; - if (index >= skuArr.length) { - return; - } - skuArr[index] = [skuName, skuVersion].join(skuValueSeparator); -} -/** @internal */ -class ServerTelemetryManager { - constructor(telemetryRequest, cacheManager) { - this.cacheOutcome = CacheOutcome.NOT_APPLICABLE; - this.cacheManager = cacheManager; - this.apiId = telemetryRequest.apiId; - this.correlationId = telemetryRequest.correlationId; - this.wrapperSKU = telemetryRequest.wrapperSKU || Constants.EMPTY_STRING; - this.wrapperVer = telemetryRequest.wrapperVer || Constants.EMPTY_STRING; - this.telemetryCacheKey = - SERVER_TELEM_CONSTANTS.CACHE_KEY + - Separators.CACHE_KEY_SEPARATOR + - telemetryRequest.clientId; - } - /** - * API to add MSER Telemetry to request - */ - generateCurrentRequestHeaderValue() { - const request = `${this.apiId}${SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR}${this.cacheOutcome}`; - const platformFieldsArr = [this.wrapperSKU, this.wrapperVer]; - const nativeBrokerErrorCode = this.getNativeBrokerErrorCode(); - if (nativeBrokerErrorCode?.length) { - platformFieldsArr.push(`broker_error=${nativeBrokerErrorCode}`); - } - const platformFields = platformFieldsArr.join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR); - const regionDiscoveryFields = this.getRegionDiscoveryFields(); - const requestWithRegionDiscoveryFields = [ - request, - regionDiscoveryFields, - ].join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR); - return [ - SERVER_TELEM_CONSTANTS.SCHEMA_VERSION, - requestWithRegionDiscoveryFields, - platformFields, - ].join(SERVER_TELEM_CONSTANTS.CATEGORY_SEPARATOR); - } - /** - * API to add MSER Telemetry for the last failed request - */ - generateLastRequestHeaderValue() { - const lastRequests = this.getLastRequests(); - const maxErrors = ServerTelemetryManager.maxErrorsToSend(lastRequests); - const failedRequests = lastRequests.failedRequests - .slice(0, 2 * maxErrors) - .join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR); - const errors = lastRequests.errors - .slice(0, maxErrors) - .join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR); - const errorCount = lastRequests.errors.length; - // Indicate whether this header contains all data or partial data - const overflow = maxErrors < errorCount - ? SERVER_TELEM_CONSTANTS.OVERFLOW_TRUE - : SERVER_TELEM_CONSTANTS.OVERFLOW_FALSE; - const platformFields = [errorCount, overflow].join(SERVER_TELEM_CONSTANTS.VALUE_SEPARATOR); - return [ - SERVER_TELEM_CONSTANTS.SCHEMA_VERSION, - lastRequests.cacheHits, - failedRequests, - errors, - platformFields, - ].join(SERVER_TELEM_CONSTANTS.CATEGORY_SEPARATOR); - } - /** - * API to cache token failures for MSER data capture - * @param error - */ - cacheFailedRequest(error) { - const lastRequests = this.getLastRequests(); - if (lastRequests.errors.length >= - SERVER_TELEM_CONSTANTS.MAX_CACHED_ERRORS) { - // Remove a cached error to make room, first in first out - lastRequests.failedRequests.shift(); // apiId - lastRequests.failedRequests.shift(); // correlationId - lastRequests.errors.shift(); - } - lastRequests.failedRequests.push(this.apiId, this.correlationId); - if (error instanceof Error && !!error && error.toString()) { - if (error instanceof AuthError) { - if (error.subError) { - lastRequests.errors.push(error.subError); - } - else if (error.errorCode) { - lastRequests.errors.push(error.errorCode); - } - else { - lastRequests.errors.push(error.toString()); - } - } - else { - lastRequests.errors.push(error.toString()); - } - } - else { - lastRequests.errors.push(SERVER_TELEM_CONSTANTS.UNKNOWN_ERROR); - } - this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId); - return; - } - /** - * Update server telemetry cache entry by incrementing cache hit counter - */ - incrementCacheHits() { - const lastRequests = this.getLastRequests(); - lastRequests.cacheHits += 1; - this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId); - return lastRequests.cacheHits; - } - /** - * Get the server telemetry entity from cache or initialize a new one - */ - getLastRequests() { - const initialValue = { - failedRequests: [], - errors: [], - cacheHits: 0, - }; - const lastRequests = this.cacheManager.getServerTelemetry(this.telemetryCacheKey); - return lastRequests || initialValue; - } - /** - * Remove server telemetry cache entry - */ - clearTelemetryCache() { - const lastRequests = this.getLastRequests(); - const numErrorsFlushed = ServerTelemetryManager.maxErrorsToSend(lastRequests); - const errorCount = lastRequests.errors.length; - if (numErrorsFlushed === errorCount) { - // All errors were sent on last request, clear Telemetry cache - this.cacheManager.removeItem(this.telemetryCacheKey, this.correlationId); - } - else { - // Partial data was flushed to server, construct a new telemetry cache item with errors that were not flushed - const serverTelemEntity = { - failedRequests: lastRequests.failedRequests.slice(numErrorsFlushed * 2), - errors: lastRequests.errors.slice(numErrorsFlushed), - cacheHits: 0, - }; - this.cacheManager.setServerTelemetry(this.telemetryCacheKey, serverTelemEntity, this.correlationId); - } - } - /** - * Returns the maximum number of errors that can be flushed to the server in the next network request - * @param serverTelemetryEntity - */ - static maxErrorsToSend(serverTelemetryEntity) { - let i; - let maxErrors = 0; - let dataSize = 0; - const errorCount = serverTelemetryEntity.errors.length; - for (i = 0; i < errorCount; i++) { - // failedRequests parameter contains pairs of apiId and correlationId, multiply index by 2 to preserve pairs - const apiId = serverTelemetryEntity.failedRequests[2 * i] || - Constants.EMPTY_STRING; - const correlationId = serverTelemetryEntity.failedRequests[2 * i + 1] || - Constants.EMPTY_STRING; - const errorCode = serverTelemetryEntity.errors[i] || Constants.EMPTY_STRING; - // Count number of characters that would be added to header, each character is 1 byte. Add 3 at the end to account for separators - dataSize += - apiId.toString().length + - correlationId.toString().length + - errorCode.length + - 3; - if (dataSize < SERVER_TELEM_CONSTANTS.MAX_LAST_HEADER_BYTES) { - // Adding this entry to the header would still keep header size below the limit - maxErrors += 1; - } - else { - break; - } - } - return maxErrors; - } - /** - * Get the region discovery fields - * - * @returns string - */ - getRegionDiscoveryFields() { - const regionDiscoveryFields = []; - regionDiscoveryFields.push(this.regionUsed || Constants.EMPTY_STRING); - regionDiscoveryFields.push(this.regionSource || Constants.EMPTY_STRING); - regionDiscoveryFields.push(this.regionOutcome || Constants.EMPTY_STRING); - return regionDiscoveryFields.join(","); - } - /** - * Update the region discovery metadata - * - * @param regionDiscoveryMetadata - * @returns void - */ - updateRegionDiscoveryMetadata(regionDiscoveryMetadata) { - this.regionUsed = regionDiscoveryMetadata.region_used; - this.regionSource = regionDiscoveryMetadata.region_source; - this.regionOutcome = regionDiscoveryMetadata.region_outcome; - } - /** - * Set cache outcome - */ - setCacheOutcome(cacheOutcome) { - this.cacheOutcome = cacheOutcome; - } - setNativeBrokerErrorCode(errorCode) { - const lastRequests = this.getLastRequests(); - lastRequests.nativeBrokerErrorCode = errorCode; - this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId); - } - getNativeBrokerErrorCode() { - return this.getLastRequests().nativeBrokerErrorCode; - } - clearNativeBrokerErrorCode() { - const lastRequests = this.getLastRequests(); - delete lastRequests.nativeBrokerErrorCode; - this.cacheManager.setServerTelemetry(this.telemetryCacheKey, lastRequests, this.correlationId); - } - static makeExtraSkuString(params) { - return makeExtraSkuString(params); - } -} - -export { ServerTelemetryManager }; -//# sourceMappingURL=ServerTelemetryManager.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/url/UrlString.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/url/UrlString.mjs deleted file mode 100644 index 902f732e..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/url/UrlString.mjs +++ /dev/null @@ -1,172 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { createClientConfigurationError } from '../error/ClientConfigurationError.mjs'; -import { StringUtils } from '../utils/StringUtils.mjs'; -import { AADAuthorityConstants, Constants } from '../utils/Constants.mjs'; -import { getDeserializedResponse } from '../utils/UrlUtils.mjs'; -import { urlEmptyError, urlParseError, authorityUriInsecure } from '../error/ClientConfigurationErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Url object class which can perform various transformations on url strings. - */ -class UrlString { - get urlString() { - return this._urlString; - } - constructor(url) { - this._urlString = url; - if (!this._urlString) { - // Throws error if url is empty - throw createClientConfigurationError(urlEmptyError); - } - if (!url.includes("#")) { - this._urlString = UrlString.canonicalizeUri(url); - } - } - /** - * Ensure urls are lower case and end with a / character. - * @param url - */ - static canonicalizeUri(url) { - if (url) { - let lowerCaseUrl = url.toLowerCase(); - if (StringUtils.endsWith(lowerCaseUrl, "?")) { - lowerCaseUrl = lowerCaseUrl.slice(0, -1); - } - else if (StringUtils.endsWith(lowerCaseUrl, "?/")) { - lowerCaseUrl = lowerCaseUrl.slice(0, -2); - } - if (!StringUtils.endsWith(lowerCaseUrl, "/")) { - lowerCaseUrl += "/"; - } - return lowerCaseUrl; - } - return url; - } - /** - * Throws if urlString passed is not a valid authority URI string. - */ - validateAsUri() { - // Attempts to parse url for uri components - let components; - try { - components = this.getUrlComponents(); - } - catch (e) { - throw createClientConfigurationError(urlParseError); - } - // Throw error if URI or path segments are not parseable. - if (!components.HostNameAndPort || !components.PathSegments) { - throw createClientConfigurationError(urlParseError); - } - // Throw error if uri is insecure. - if (!components.Protocol || - components.Protocol.toLowerCase() !== "https:") { - throw createClientConfigurationError(authorityUriInsecure); - } - } - /** - * Given a url and a query string return the url with provided query string appended - * @param url - * @param queryString - */ - static appendQueryString(url, queryString) { - if (!queryString) { - return url; - } - return url.indexOf("?") < 0 - ? `${url}?${queryString}` - : `${url}&${queryString}`; - } - /** - * Returns a url with the hash removed - * @param url - */ - static removeHashFromUrl(url) { - return UrlString.canonicalizeUri(url.split("#")[0]); - } - /** - * Given a url like https://a:b/common/d?e=f#g, and a tenantId, returns https://a:b/tenantId/d - * @param href The url - * @param tenantId The tenant id to replace - */ - replaceTenantPath(tenantId) { - const urlObject = this.getUrlComponents(); - const pathArray = urlObject.PathSegments; - if (tenantId && - pathArray.length !== 0 && - (pathArray[0] === AADAuthorityConstants.COMMON || - pathArray[0] === AADAuthorityConstants.ORGANIZATIONS)) { - pathArray[0] = tenantId; - } - return UrlString.constructAuthorityUriFromObject(urlObject); - } - /** - * Parses out the components from a url string. - * @returns An object with the various components. Please cache this value insted of calling this multiple times on the same url. - */ - getUrlComponents() { - // https://gist.github.com/curtisz/11139b2cfcaef4a261e0 - const regEx = RegExp("^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?"); - // If url string does not match regEx, we throw an error - const match = this.urlString.match(regEx); - if (!match) { - throw createClientConfigurationError(urlParseError); - } - // Url component object - const urlComponents = { - Protocol: match[1], - HostNameAndPort: match[4], - AbsolutePath: match[5], - QueryString: match[7], - }; - let pathSegments = urlComponents.AbsolutePath.split("/"); - pathSegments = pathSegments.filter((val) => val && val.length > 0); // remove empty elements - urlComponents.PathSegments = pathSegments; - if (urlComponents.QueryString && - urlComponents.QueryString.endsWith("/")) { - urlComponents.QueryString = urlComponents.QueryString.substring(0, urlComponents.QueryString.length - 1); - } - return urlComponents; - } - static getDomainFromUrl(url) { - const regEx = RegExp("^([^:/?#]+://)?([^/?#]*)"); - const match = url.match(regEx); - if (!match) { - throw createClientConfigurationError(urlParseError); - } - return match[2]; - } - static getAbsoluteUrl(relativeUrl, baseUrl) { - if (relativeUrl[0] === Constants.FORWARD_SLASH) { - const url = new UrlString(baseUrl); - const baseComponents = url.getUrlComponents(); - return (baseComponents.Protocol + - "//" + - baseComponents.HostNameAndPort + - relativeUrl); - } - return relativeUrl; - } - static constructAuthorityUriFromObject(urlObject) { - return new UrlString(urlObject.Protocol + - "//" + - urlObject.HostNameAndPort + - "/" + - urlObject.PathSegments.join("/")); - } - /** - * Check if the hash of the URL string contains known properties - * @deprecated This API will be removed in a future version - */ - static hashContainsKnownProperties(response) { - return !!getDeserializedResponse(response); - } -} - -export { UrlString }; -//# sourceMappingURL=UrlString.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/utils/ClientAssertionUtils.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/utils/ClientAssertionUtils.mjs deleted file mode 100644 index 9e8cce70..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/utils/ClientAssertionUtils.mjs +++ /dev/null @@ -1,21 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -async function getClientAssertion(clientAssertion, clientId, tokenEndpoint) { - if (typeof clientAssertion === "string") { - return clientAssertion; - } - else { - const config = { - clientId: clientId, - tokenEndpoint: tokenEndpoint, - }; - return clientAssertion(config); - } -} - -export { getClientAssertion }; -//# sourceMappingURL=ClientAssertionUtils.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/utils/Constants.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/utils/Constants.mjs deleted file mode 100644 index 5b296da1..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/utils/Constants.mjs +++ /dev/null @@ -1,325 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const Constants = { - LIBRARY_NAME: "MSAL.JS", - SKU: "msal.js.common", - // default authority - DEFAULT_AUTHORITY: "https://login.microsoftonline.com/common/", - DEFAULT_AUTHORITY_HOST: "login.microsoftonline.com", - DEFAULT_COMMON_TENANT: "common", - // ADFS String - ADFS: "adfs", - DSTS: "dstsv2", - // Default AAD Instance Discovery Endpoint - AAD_INSTANCE_DISCOVERY_ENDPT: "https://login.microsoftonline.com/common/discovery/instance?api-version=1.1&authorization_endpoint=", - // CIAM URL - CIAM_AUTH_URL: ".ciamlogin.com", - AAD_TENANT_DOMAIN_SUFFIX: ".onmicrosoft.com", - // Resource delimiter - used for certain cache entries - RESOURCE_DELIM: "|", - // Placeholder for non-existent account ids/objects - NO_ACCOUNT: "NO_ACCOUNT", - // Claims - CLAIMS: "claims", - // Consumer UTID - CONSUMER_UTID: "9188040d-6c67-4c5b-b112-36a304b66dad", - // Default scopes - OPENID_SCOPE: "openid", - PROFILE_SCOPE: "profile", - OFFLINE_ACCESS_SCOPE: "offline_access", - EMAIL_SCOPE: "email", - CODE_GRANT_TYPE: "authorization_code", - RT_GRANT_TYPE: "refresh_token", - S256_CODE_CHALLENGE_METHOD: "S256", - URL_FORM_CONTENT_TYPE: "application/x-www-form-urlencoded;charset=utf-8", - AUTHORIZATION_PENDING: "authorization_pending", - NOT_DEFINED: "not_defined", - EMPTY_STRING: "", - NOT_APPLICABLE: "N/A", - NOT_AVAILABLE: "Not Available", - FORWARD_SLASH: "/", - IMDS_ENDPOINT: "http://169.254.169.254/metadata/instance/compute/location", - IMDS_VERSION: "2020-06-01", - IMDS_TIMEOUT: 2000, - AZURE_REGION_AUTO_DISCOVER_FLAG: "TryAutoDetect", - REGIONAL_AUTH_PUBLIC_CLOUD_SUFFIX: "login.microsoft.com", - KNOWN_PUBLIC_CLOUDS: [ - "login.microsoftonline.com", - "login.windows.net", - "login.microsoft.com", - "sts.windows.net", - ], - SHR_NONCE_VALIDITY: 240, - INVALID_INSTANCE: "invalid_instance", -}; -const HttpStatus = { - SUCCESS: 200, - SUCCESS_RANGE_START: 200, - SUCCESS_RANGE_END: 299, - REDIRECT: 302, - CLIENT_ERROR: 400, - CLIENT_ERROR_RANGE_START: 400, - BAD_REQUEST: 400, - UNAUTHORIZED: 401, - NOT_FOUND: 404, - REQUEST_TIMEOUT: 408, - GONE: 410, - TOO_MANY_REQUESTS: 429, - CLIENT_ERROR_RANGE_END: 499, - SERVER_ERROR: 500, - SERVER_ERROR_RANGE_START: 500, - SERVICE_UNAVAILABLE: 503, - GATEWAY_TIMEOUT: 504, - SERVER_ERROR_RANGE_END: 599, - MULTI_SIDED_ERROR: 600, -}; -const HttpMethod = { - GET: "GET", - POST: "POST", -}; -const OIDC_DEFAULT_SCOPES = [ - Constants.OPENID_SCOPE, - Constants.PROFILE_SCOPE, - Constants.OFFLINE_ACCESS_SCOPE, -]; -const OIDC_SCOPES = [...OIDC_DEFAULT_SCOPES, Constants.EMAIL_SCOPE]; -/** - * Request header names - */ -const HeaderNames = { - CONTENT_TYPE: "Content-Type", - CONTENT_LENGTH: "Content-Length", - RETRY_AFTER: "Retry-After", - CCS_HEADER: "X-AnchorMailbox", - WWWAuthenticate: "WWW-Authenticate", - AuthenticationInfo: "Authentication-Info", - X_MS_REQUEST_ID: "x-ms-request-id", - X_MS_HTTP_VERSION: "x-ms-httpver", -}; -/** - * Persistent cache keys MSAL which stay while user is logged in. - */ -const PersistentCacheKeys = { - ACTIVE_ACCOUNT_FILTERS: "active-account-filters", // new cache entry for active_account for a more robust version for browser -}; -/** - * String constants related to AAD Authority - */ -const AADAuthorityConstants = { - COMMON: "common", - ORGANIZATIONS: "organizations", - CONSUMERS: "consumers", -}; -/** - * Claims request keys - */ -const ClaimsRequestKeys = { - ACCESS_TOKEN: "access_token", - XMS_CC: "xms_cc", -}; -/** - * we considered making this "enum" in the request instead of string, however it looks like the allowed list of - * prompt values kept changing over past couple of years. There are some undocumented prompt values for some - * internal partners too, hence the choice of generic "string" type instead of the "enum" - */ -const PromptValue = { - LOGIN: "login", - SELECT_ACCOUNT: "select_account", - CONSENT: "consent", - NONE: "none", - CREATE: "create", - NO_SESSION: "no_session", -}; -/** - * allowed values for codeVerifier - */ -const CodeChallengeMethodValues = { - PLAIN: "plain", - S256: "S256", -}; -/** - * Allowed values for response_type - */ -const OAuthResponseType = { - CODE: "code", - IDTOKEN_TOKEN: "id_token token", - IDTOKEN_TOKEN_REFRESHTOKEN: "id_token token refresh_token", -}; -/** - * allowed values for server response type - * @deprecated Use ResponseMode instead - */ -const ServerResponseType = { - QUERY: "query", - FRAGMENT: "fragment", -}; -/** - * allowed values for response_mode - */ -const ResponseMode = { - QUERY: "query", - FRAGMENT: "fragment", - FORM_POST: "form_post", -}; -/** - * allowed grant_type - */ -const GrantType = { - IMPLICIT_GRANT: "implicit", - AUTHORIZATION_CODE_GRANT: "authorization_code", - CLIENT_CREDENTIALS_GRANT: "client_credentials", - RESOURCE_OWNER_PASSWORD_GRANT: "password", - REFRESH_TOKEN_GRANT: "refresh_token", - DEVICE_CODE_GRANT: "device_code", - JWT_BEARER: "urn:ietf:params:oauth:grant-type:jwt-bearer", -}; -/** - * Account types in Cache - */ -const CacheAccountType = { - MSSTS_ACCOUNT_TYPE: "MSSTS", - ADFS_ACCOUNT_TYPE: "ADFS", - MSAV1_ACCOUNT_TYPE: "MSA", - GENERIC_ACCOUNT_TYPE: "Generic", // NTLM, Kerberos, FBA, Basic etc -}; -/** - * Separators used in cache - */ -const Separators = { - CACHE_KEY_SEPARATOR: "-", - CLIENT_INFO_SEPARATOR: ".", -}; -/** - * Credential Type stored in the cache - */ -const CredentialType = { - ID_TOKEN: "IdToken", - ACCESS_TOKEN: "AccessToken", - ACCESS_TOKEN_WITH_AUTH_SCHEME: "AccessToken_With_AuthScheme", - REFRESH_TOKEN: "RefreshToken", -}; -/** - * Combine all cache types - */ -const CacheType = { - ADFS: 1001, - MSA: 1002, - MSSTS: 1003, - GENERIC: 1004, - ACCESS_TOKEN: 2001, - REFRESH_TOKEN: 2002, - ID_TOKEN: 2003, - APP_METADATA: 3001, - UNDEFINED: 9999, -}; -/** - * More Cache related constants - */ -const APP_METADATA = "appmetadata"; -const CLIENT_INFO = "client_info"; -const THE_FAMILY_ID = "1"; -const AUTHORITY_METADATA_CONSTANTS = { - CACHE_KEY: "authority-metadata", - REFRESH_TIME_SECONDS: 3600 * 24, // 24 Hours -}; -const AuthorityMetadataSource = { - CONFIG: "config", - CACHE: "cache", - NETWORK: "network", - HARDCODED_VALUES: "hardcoded_values", -}; -const SERVER_TELEM_CONSTANTS = { - SCHEMA_VERSION: 5, - MAX_LAST_HEADER_BYTES: 330, - MAX_CACHED_ERRORS: 50, - CACHE_KEY: "server-telemetry", - CATEGORY_SEPARATOR: "|", - VALUE_SEPARATOR: ",", - OVERFLOW_TRUE: "1", - OVERFLOW_FALSE: "0", - UNKNOWN_ERROR: "unknown_error", -}; -/** - * Type of the authentication request - */ -const AuthenticationScheme = { - BEARER: "Bearer", - POP: "pop", - SSH: "ssh-cert", -}; -/** - * Constants related to throttling - */ -const ThrottlingConstants = { - // Default time to throttle RequestThumbprint in seconds - DEFAULT_THROTTLE_TIME_SECONDS: 60, - // Default maximum time to throttle in seconds, overrides what the server sends back - DEFAULT_MAX_THROTTLE_TIME_SECONDS: 3600, - // Prefix for storing throttling entries - THROTTLING_PREFIX: "throttling", - // Value assigned to the x-ms-lib-capability header to indicate to the server the library supports throttling - X_MS_LIB_CAPABILITY_VALUE: "retry-after, h429", -}; -const Errors = { - INVALID_GRANT_ERROR: "invalid_grant", - CLIENT_MISMATCH_ERROR: "client_mismatch", -}; -/** - * Password grant parameters - */ -const PasswordGrantConstants = { - username: "username", - password: "password", -}; -/** - * Region Discovery Sources - */ -const RegionDiscoverySources = { - FAILED_AUTO_DETECTION: "1", - INTERNAL_CACHE: "2", - ENVIRONMENT_VARIABLE: "3", - IMDS: "4", -}; -/** - * Region Discovery Outcomes - */ -const RegionDiscoveryOutcomes = { - CONFIGURED_NO_AUTO_DETECTION: "2", - AUTO_DETECTION_REQUESTED_SUCCESSFUL: "4", - AUTO_DETECTION_REQUESTED_FAILED: "5", -}; -/** - * Specifies the reason for fetching the access token from the identity provider - */ -const CacheOutcome = { - // When a token is found in the cache or the cache is not supposed to be hit when making the request - NOT_APPLICABLE: "0", - // When the token request goes to the identity provider because force_refresh was set to true. Also occurs if claims were requested - FORCE_REFRESH_OR_CLAIMS: "1", - // When the token request goes to the identity provider because no cached access token exists - NO_CACHED_ACCESS_TOKEN: "2", - // When the token request goes to the identity provider because cached access token expired - CACHED_ACCESS_TOKEN_EXPIRED: "3", - // When the token request goes to the identity provider because refresh_in was used and the existing token needs to be refreshed - PROACTIVELY_REFRESHED: "4", -}; -const JsonWebTokenTypes = { - Jwt: "JWT", - Jwk: "JWK", - Pop: "pop", -}; -const ONE_DAY_IN_MS = 86400000; -// Token renewal offset default in seconds -const DEFAULT_TOKEN_RENEWAL_OFFSET_SEC = 300; -const EncodingTypes = { - BASE64: "base64", - HEX: "hex", - UTF8: "utf-8", -}; - -export { AADAuthorityConstants, APP_METADATA, AUTHORITY_METADATA_CONSTANTS, AuthenticationScheme, AuthorityMetadataSource, CLIENT_INFO, CacheAccountType, CacheOutcome, CacheType, ClaimsRequestKeys, CodeChallengeMethodValues, Constants, CredentialType, DEFAULT_TOKEN_RENEWAL_OFFSET_SEC, EncodingTypes, Errors, GrantType, HeaderNames, HttpMethod, HttpStatus, JsonWebTokenTypes, OAuthResponseType, OIDC_DEFAULT_SCOPES, OIDC_SCOPES, ONE_DAY_IN_MS, PasswordGrantConstants, PersistentCacheKeys, PromptValue, RegionDiscoveryOutcomes, RegionDiscoverySources, ResponseMode, SERVER_TELEM_CONSTANTS, Separators, ServerResponseType, THE_FAMILY_ID, ThrottlingConstants }; -//# sourceMappingURL=Constants.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/utils/FunctionWrappers.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/utils/FunctionWrappers.mjs deleted file mode 100644 index 3b048c8a..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/utils/FunctionWrappers.mjs +++ /dev/null @@ -1,99 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Wraps a function with a performance measurement. - * Usage: invoke(functionToCall, performanceClient, "EventName", "correlationId")(...argsToPassToFunction) - * @param callback - * @param eventName - * @param logger - * @param telemetryClient - * @param correlationId - * @returns - * @internal - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const invoke = (callback, eventName, logger, telemetryClient, correlationId) => { - return (...args) => { - logger.trace(`Executing function ${eventName}`); - const inProgressEvent = telemetryClient?.startMeasurement(eventName, correlationId); - if (correlationId) { - // Track number of times this API is called in a single request - const eventCount = eventName + "CallCount"; - telemetryClient?.incrementFields({ [eventCount]: 1 }, correlationId); - } - try { - const result = callback(...args); - inProgressEvent?.end({ - success: true, - }); - logger.trace(`Returning result from ${eventName}`); - return result; - } - catch (e) { - logger.trace(`Error occurred in ${eventName}`); - try { - logger.trace(JSON.stringify(e)); - } - catch (e) { - logger.trace("Unable to print error message."); - } - inProgressEvent?.end({ - success: false, - }, e); - throw e; - } - }; -}; -/** - * Wraps an async function with a performance measurement. - * Usage: invokeAsync(functionToCall, performanceClient, "EventName", "correlationId")(...argsToPassToFunction) - * @param callback - * @param eventName - * @param logger - * @param telemetryClient - * @param correlationId - * @returns - * @internal - * - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const invokeAsync = (callback, eventName, logger, telemetryClient, correlationId) => { - return (...args) => { - logger.trace(`Executing function ${eventName}`); - const inProgressEvent = telemetryClient?.startMeasurement(eventName, correlationId); - if (correlationId) { - // Track number of times this API is called in a single request - const eventCount = eventName + "CallCount"; - telemetryClient?.incrementFields({ [eventCount]: 1 }, correlationId); - } - telemetryClient?.setPreQueueTime(eventName, correlationId); - return callback(...args) - .then((response) => { - logger.trace(`Returning result from ${eventName}`); - inProgressEvent?.end({ - success: true, - }); - return response; - }) - .catch((e) => { - logger.trace(`Error occurred in ${eventName}`); - try { - logger.trace(JSON.stringify(e)); - } - catch (e) { - logger.trace("Unable to print error message."); - } - inProgressEvent?.end({ - success: false, - }, e); - throw e; - }); - }; -}; - -export { invoke, invokeAsync }; -//# sourceMappingURL=FunctionWrappers.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/utils/ProtocolUtils.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/utils/ProtocolUtils.mjs deleted file mode 100644 index 3da8d459..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/utils/ProtocolUtils.mjs +++ /dev/null @@ -1,78 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { Constants } from './Constants.mjs'; -import { createClientAuthError } from '../error/ClientAuthError.mjs'; -import { noCryptoObject, invalidState } from '../error/ClientAuthErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Class which provides helpers for OAuth 2.0 protocol specific values - */ -class ProtocolUtils { - /** - * Appends user state with random guid, or returns random guid. - * @param userState - * @param randomGuid - */ - static setRequestState(cryptoObj, userState, meta) { - const libraryState = ProtocolUtils.generateLibraryState(cryptoObj, meta); - return userState - ? `${libraryState}${Constants.RESOURCE_DELIM}${userState}` - : libraryState; - } - /** - * Generates the state value used by the common library. - * @param randomGuid - * @param cryptoObj - */ - static generateLibraryState(cryptoObj, meta) { - if (!cryptoObj) { - throw createClientAuthError(noCryptoObject); - } - // Create a state object containing a unique id and the timestamp of the request creation - const stateObj = { - id: cryptoObj.createNewGuid(), - }; - if (meta) { - stateObj.meta = meta; - } - const stateString = JSON.stringify(stateObj); - return cryptoObj.base64Encode(stateString); - } - /** - * Parses the state into the RequestStateObject, which contains the LibraryState info and the state passed by the user. - * @param state - * @param cryptoObj - */ - static parseRequestState(cryptoObj, state) { - if (!cryptoObj) { - throw createClientAuthError(noCryptoObject); - } - if (!state) { - throw createClientAuthError(invalidState); - } - try { - // Split the state between library state and user passed state and decode them separately - const splitState = state.split(Constants.RESOURCE_DELIM); - const libraryState = splitState[0]; - const userState = splitState.length > 1 - ? splitState.slice(1).join(Constants.RESOURCE_DELIM) - : Constants.EMPTY_STRING; - const libraryStateString = cryptoObj.base64Decode(libraryState); - const libraryStateObj = JSON.parse(libraryStateString); - return { - userRequestState: userState || Constants.EMPTY_STRING, - libraryState: libraryStateObj, - }; - } - catch (e) { - throw createClientAuthError(invalidState); - } - } -} - -export { ProtocolUtils }; -//# sourceMappingURL=ProtocolUtils.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/utils/StringUtils.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/utils/StringUtils.mjs deleted file mode 100644 index 2c870989..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/utils/StringUtils.mjs +++ /dev/null @@ -1,100 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * @hidden - */ -class StringUtils { - /** - * Check if stringified object is empty - * @param strObj - */ - static isEmptyObj(strObj) { - if (strObj) { - try { - const obj = JSON.parse(strObj); - return Object.keys(obj).length === 0; - } - catch (e) { } - } - return true; - } - static startsWith(str, search) { - return str.indexOf(search) === 0; - } - static endsWith(str, search) { - return (str.length >= search.length && - str.lastIndexOf(search) === str.length - search.length); - } - /** - * Parses string into an object. - * - * @param query - */ - static queryStringToObject(query) { - const obj = {}; - const params = query.split("&"); - const decode = (s) => decodeURIComponent(s.replace(/\+/g, " ")); - params.forEach((pair) => { - if (pair.trim()) { - const [key, value] = pair.split(/=(.+)/g, 2); // Split on the first occurence of the '=' character - if (key && value) { - obj[decode(key)] = decode(value); - } - } - }); - return obj; - } - /** - * Trims entries in an array. - * - * @param arr - */ - static trimArrayEntries(arr) { - return arr.map((entry) => entry.trim()); - } - /** - * Removes empty strings from array - * @param arr - */ - static removeEmptyStringsFromArray(arr) { - return arr.filter((entry) => { - return !!entry; - }); - } - /** - * Attempts to parse a string into JSON - * @param str - */ - static jsonParseHelper(str) { - try { - return JSON.parse(str); - } - catch (e) { - return null; - } - } - /** - * Tests if a given string matches a given pattern, with support for wildcards and queries. - * @param pattern Wildcard pattern to string match. Supports "*" for wildcards and "?" for queries - * @param input String to match against - */ - static matchPattern(pattern, input) { - /** - * Wildcard support: https://stackoverflow.com/a/3117248/4888559 - * Queries: replaces "?" in string with escaped "\?" for regex test - */ - // eslint-disable-next-line security/detect-non-literal-regexp - const regex = new RegExp(pattern - .replace(/\\/g, "\\\\") - .replace(/\*/g, "[^ ]*") - .replace(/\?/g, "\\?")); - return regex.test(input); - } -} - -export { StringUtils }; -//# sourceMappingURL=StringUtils.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/utils/TimeUtils.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/utils/TimeUtils.mjs deleted file mode 100644 index 38d4e425..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/utils/TimeUtils.mjs +++ /dev/null @@ -1,76 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Utility functions for managing date and time operations. - */ -/** - * return the current time in Unix time (seconds). - */ -function nowSeconds() { - // Date.getTime() returns in milliseconds. - return Math.round(new Date().getTime() / 1000.0); -} -/** - * Converts JS Date object to seconds - * @param date Date - */ -function toSecondsFromDate(date) { - // Convert date to seconds - return date.getTime() / 1000; -} -/** - * Convert seconds to JS Date object. Seconds can be in a number or string format or undefined (will still return a date). - * @param seconds - */ -function toDateFromSeconds(seconds) { - if (seconds) { - return new Date(Number(seconds) * 1000); - } - return new Date(); -} -/** - * check if a token is expired based on given UTC time in seconds. - * @param expiresOn - */ -function isTokenExpired(expiresOn, offset) { - // check for access token expiry - const expirationSec = Number(expiresOn) || 0; - const offsetCurrentTimeSec = nowSeconds() + offset; - // If current time + offset is greater than token expiration time, then token is expired. - return offsetCurrentTimeSec > expirationSec; -} -/** - * Checks if a cache entry is expired based on the last updated time and cache retention days. - * @param lastUpdatedAt - * @param cacheRetentionDays - * @returns - */ -function isCacheExpired(lastUpdatedAt, cacheRetentionDays) { - const cacheExpirationTimestamp = Number(lastUpdatedAt) + cacheRetentionDays * 24 * 60 * 60 * 1000; - return Date.now() > cacheExpirationTimestamp; -} -/** - * If the current time is earlier than the time that a token was cached at, we must discard the token - * i.e. The system clock was turned back after acquiring the cached token - * @param cachedAt - * @param offset - */ -function wasClockTurnedBack(cachedAt) { - const cachedAtSec = Number(cachedAt); - return cachedAtSec > nowSeconds(); -} -/** - * Waits for t number of milliseconds - * @param t number - * @param value T - */ -function delay(t, value) { - return new Promise((resolve) => setTimeout(() => resolve(value), t)); -} - -export { delay, isCacheExpired, isTokenExpired, nowSeconds, toDateFromSeconds, toSecondsFromDate, wasClockTurnedBack }; -//# sourceMappingURL=TimeUtils.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-common/dist/utils/UrlUtils.mjs b/claude-code-source/node_modules/@azure/msal-common/dist/utils/UrlUtils.mjs deleted file mode 100644 index fcfd9569..00000000 --- a/claude-code-source/node_modules/@azure/msal-common/dist/utils/UrlUtils.mjs +++ /dev/null @@ -1,122 +0,0 @@ -/*! @azure/msal-common v15.13.1 2025-10-29 */ -'use strict'; -import { createClientAuthError } from '../error/ClientAuthError.mjs'; -import { StringUtils } from './StringUtils.mjs'; -import { hashNotDeserialized } from '../error/ClientAuthErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Canonicalizes a URL by making it lowercase and ensuring it ends with / - * Inlined version of UrlString.canonicalizeUri to avoid circular dependency - * @param url - URL to canonicalize - * @returns Canonicalized URL - */ -function canonicalizeUrl(url) { - if (!url) { - return url; - } - let lowerCaseUrl = url.toLowerCase(); - if (StringUtils.endsWith(lowerCaseUrl, "?")) { - lowerCaseUrl = lowerCaseUrl.slice(0, -1); - } - else if (StringUtils.endsWith(lowerCaseUrl, "?/")) { - lowerCaseUrl = lowerCaseUrl.slice(0, -2); - } - if (!StringUtils.endsWith(lowerCaseUrl, "/")) { - lowerCaseUrl += "/"; - } - return lowerCaseUrl; -} -/** - * Parses hash string from given string. Returns empty string if no hash symbol is found. - * @param hashString - */ -function stripLeadingHashOrQuery(responseString) { - if (responseString.startsWith("#/")) { - return responseString.substring(2); - } - else if (responseString.startsWith("#") || - responseString.startsWith("?")) { - return responseString.substring(1); - } - return responseString; -} -/** - * Returns URL hash as server auth code response object. - */ -function getDeserializedResponse(responseString) { - // Check if given hash is empty - if (!responseString || responseString.indexOf("=") < 0) { - return null; - } - try { - // Strip the # or ? symbol if present - const normalizedResponse = stripLeadingHashOrQuery(responseString); - // If # symbol was not present, above will return empty string, so give original hash value - const deserializedHash = Object.fromEntries(new URLSearchParams(normalizedResponse)); - // Check for known response properties - if (deserializedHash.code || - deserializedHash.ear_jwe || - deserializedHash.error || - deserializedHash.error_description || - deserializedHash.state) { - return deserializedHash; - } - } - catch (e) { - throw createClientAuthError(hashNotDeserialized); - } - return null; -} -/** - * Utility to create a URL from the params map - */ -function mapToQueryString(parameters, encodeExtraParams = true, extraQueryParameters) { - const queryParameterArray = new Array(); - parameters.forEach((value, key) => { - if (!encodeExtraParams && - extraQueryParameters && - key in extraQueryParameters) { - queryParameterArray.push(`${key}=${value}`); - } - else { - queryParameterArray.push(`${key}=${encodeURIComponent(value)}`); - } - }); - return queryParameterArray.join("&"); -} -/** - * Normalizes URLs for comparison by removing hash, canonicalizing, - * and ensuring consistent URL encoding in query parameters. - * This fixes redirect loops when URLs contain encoded characters like apostrophes (%27). - * @param url - URL to normalize - * @returns Normalized URL string for comparison - */ -function normalizeUrlForComparison(url) { - if (!url) { - return url; - } - // Remove hash first - const urlWithoutHash = url.split("#")[0]; - try { - // Parse the URL to handle encoding consistently - const urlObj = new URL(urlWithoutHash); - /* - * Reconstruct the URL with properly decoded query parameters - * This ensures that %27 and ' are treated as equivalent - */ - const normalizedUrl = urlObj.origin + urlObj.pathname + urlObj.search; - // Apply canonicalization logic inline to avoid circular dependency - return canonicalizeUrl(normalizedUrl); - } - catch (e) { - // Fallback to original logic if URL parsing fails - return canonicalizeUrl(urlWithoutHash); - } -} - -export { getDeserializedResponse, mapToQueryString, normalizeUrlForComparison, stripLeadingHashOrQuery }; -//# sourceMappingURL=UrlUtils.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/cache/CacheHelpers.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/cache/CacheHelpers.mjs deleted file mode 100644 index 932ef0a6..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/cache/CacheHelpers.mjs +++ /dev/null @@ -1,42 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { AuthenticationScheme, CredentialType } from '@azure/msal-common/node'; -import { CACHE } from '../utils/Constants.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -function generateCredentialKey(credential) { - const familyId = (credential.credentialType === CredentialType.REFRESH_TOKEN && - credential.familyId) || - credential.clientId; - const scheme = credential.tokenType && - credential.tokenType.toLowerCase() !== - AuthenticationScheme.BEARER.toLowerCase() - ? credential.tokenType.toLowerCase() - : ""; - const credentialKey = [ - credential.homeAccountId, - credential.environment, - credential.credentialType, - familyId, - credential.realm || "", - credential.target || "", - credential.requestedClaimsHash || "", - scheme, - ]; - return credentialKey.join(CACHE.KEY_SEPARATOR).toLowerCase(); -} -function generateAccountKey(account) { - const homeTenantId = account.homeAccountId.split(".")[1]; - const accountKey = [ - account.homeAccountId, - account.environment, - homeTenantId || account.tenantId || "", - ]; - return accountKey.join(CACHE.KEY_SEPARATOR).toLowerCase(); -} - -export { generateAccountKey, generateCredentialKey }; -//# sourceMappingURL=CacheHelpers.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/cache/NodeStorage.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/cache/NodeStorage.mjs deleted file mode 100644 index c629848f..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/cache/NodeStorage.mjs +++ /dev/null @@ -1,429 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { CacheManager, AccountEntity, CacheHelpers } from '@azure/msal-common/node'; -import { Deserializer } from './serializer/Deserializer.mjs'; -import { Serializer } from './serializer/Serializer.mjs'; -import { StubPerformanceClient } from '@azure/msal-common'; -import { generateCredentialKey, generateAccountKey } from './CacheHelpers.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * This class implements Storage for node, reading cache from user specified storage location or an extension library - * @public - */ -class NodeStorage extends CacheManager { - constructor(logger, clientId, cryptoImpl, staticAuthorityOptions) { - super(clientId, cryptoImpl, logger, new StubPerformanceClient(), staticAuthorityOptions); - this.cache = {}; - this.changeEmitters = []; - this.logger = logger; - } - /** - * Queue up callbacks - * @param func - a callback function for cache change indication - */ - registerChangeEmitter(func) { - this.changeEmitters.push(func); - } - /** - * Invoke the callback when cache changes - */ - emitChange() { - this.changeEmitters.forEach((func) => func.call(null)); - } - /** - * Converts cacheKVStore to InMemoryCache - * @param cache - key value store - */ - cacheToInMemoryCache(cache) { - const inMemoryCache = { - accounts: {}, - idTokens: {}, - accessTokens: {}, - refreshTokens: {}, - appMetadata: {}, - }; - for (const key in cache) { - const value = cache[key]; - if (typeof value !== "object") { - continue; - } - if (value instanceof AccountEntity) { - inMemoryCache.accounts[key] = value; - } - else if (CacheHelpers.isIdTokenEntity(value)) { - inMemoryCache.idTokens[key] = value; - } - else if (CacheHelpers.isAccessTokenEntity(value)) { - inMemoryCache.accessTokens[key] = value; - } - else if (CacheHelpers.isRefreshTokenEntity(value)) { - inMemoryCache.refreshTokens[key] = value; - } - else if (CacheHelpers.isAppMetadataEntity(key, value)) { - inMemoryCache.appMetadata[key] = value; - } - else { - continue; - } - } - return inMemoryCache; - } - /** - * converts inMemoryCache to CacheKVStore - * @param inMemoryCache - kvstore map for inmemory - */ - inMemoryCacheToCache(inMemoryCache) { - // convert in memory cache to a flat Key-Value map - let cache = this.getCache(); - cache = { - ...cache, - ...inMemoryCache.accounts, - ...inMemoryCache.idTokens, - ...inMemoryCache.accessTokens, - ...inMemoryCache.refreshTokens, - ...inMemoryCache.appMetadata, - }; - // convert in memory cache to a flat Key-Value map - return cache; - } - /** - * gets the current in memory cache for the client - */ - getInMemoryCache() { - this.logger.trace("Getting in-memory cache"); - // convert the cache key value store to inMemoryCache - const inMemoryCache = this.cacheToInMemoryCache(this.getCache()); - return inMemoryCache; - } - /** - * sets the current in memory cache for the client - * @param inMemoryCache - key value map in memory - */ - setInMemoryCache(inMemoryCache) { - this.logger.trace("Setting in-memory cache"); - // convert and append the inMemoryCache to cacheKVStore - const cache = this.inMemoryCacheToCache(inMemoryCache); - this.setCache(cache); - this.emitChange(); - } - /** - * get the current cache key-value store - */ - getCache() { - this.logger.trace("Getting cache key-value store"); - return this.cache; - } - /** - * sets the current cache (key value store) - * @param cacheMap - key value map - */ - setCache(cache) { - this.logger.trace("Setting cache key value store"); - this.cache = cache; - // mark change in cache - this.emitChange(); - } - /** - * Gets cache item with given key. - * @param key - lookup key for the cache entry - */ - getItem(key) { - this.logger.tracePii(`Item key: ${key}`); - // read cache - const cache = this.getCache(); - return cache[key]; - } - /** - * Gets cache item with given key-value - * @param key - lookup key for the cache entry - * @param value - value of the cache entry - */ - setItem(key, value) { - this.logger.tracePii(`Item key: ${key}`); - // read cache - const cache = this.getCache(); - cache[key] = value; - // write to cache - this.setCache(cache); - } - generateCredentialKey(credential) { - return generateCredentialKey(credential); - } - generateAccountKey(account) { - return generateAccountKey(account); - } - getAccountKeys() { - const inMemoryCache = this.getInMemoryCache(); - const accountKeys = Object.keys(inMemoryCache.accounts); - return accountKeys; - } - getTokenKeys() { - const inMemoryCache = this.getInMemoryCache(); - const tokenKeys = { - idToken: Object.keys(inMemoryCache.idTokens), - accessToken: Object.keys(inMemoryCache.accessTokens), - refreshToken: Object.keys(inMemoryCache.refreshTokens), - }; - return tokenKeys; - } - /** - * Reads account from cache, builds it into an account entity and returns it. - * @param accountKey - lookup key to fetch cache type AccountEntity - * @returns - */ - getAccount(accountKey) { - const cachedAccount = this.getItem(accountKey); - return cachedAccount - ? Object.assign(new AccountEntity(), this.getItem(accountKey)) - : null; - } - /** - * set account entity - * @param account - cache value to be set of type AccountEntity - */ - async setAccount(account) { - const accountKey = this.generateAccountKey(AccountEntity.getAccountInfo(account)); - this.setItem(accountKey, account); - } - /** - * fetch the idToken credential - * @param idTokenKey - lookup key to fetch cache type IdTokenEntity - */ - getIdTokenCredential(idTokenKey) { - const idToken = this.getItem(idTokenKey); - if (CacheHelpers.isIdTokenEntity(idToken)) { - return idToken; - } - return null; - } - /** - * set idToken credential - * @param idToken - cache value to be set of type IdTokenEntity - */ - async setIdTokenCredential(idToken) { - const idTokenKey = this.generateCredentialKey(idToken); - this.setItem(idTokenKey, idToken); - } - /** - * fetch the accessToken credential - * @param accessTokenKey - lookup key to fetch cache type AccessTokenEntity - */ - getAccessTokenCredential(accessTokenKey) { - const accessToken = this.getItem(accessTokenKey); - if (CacheHelpers.isAccessTokenEntity(accessToken)) { - return accessToken; - } - return null; - } - /** - * set accessToken credential - * @param accessToken - cache value to be set of type AccessTokenEntity - */ - async setAccessTokenCredential(accessToken) { - const accessTokenKey = this.generateCredentialKey(accessToken); - this.setItem(accessTokenKey, accessToken); - } - /** - * fetch the refreshToken credential - * @param refreshTokenKey - lookup key to fetch cache type RefreshTokenEntity - */ - getRefreshTokenCredential(refreshTokenKey) { - const refreshToken = this.getItem(refreshTokenKey); - if (CacheHelpers.isRefreshTokenEntity(refreshToken)) { - return refreshToken; - } - return null; - } - /** - * set refreshToken credential - * @param refreshToken - cache value to be set of type RefreshTokenEntity - */ - async setRefreshTokenCredential(refreshToken) { - const refreshTokenKey = this.generateCredentialKey(refreshToken); - this.setItem(refreshTokenKey, refreshToken); - } - /** - * fetch appMetadata entity from the platform cache - * @param appMetadataKey - lookup key to fetch cache type AppMetadataEntity - */ - getAppMetadata(appMetadataKey) { - const appMetadata = this.getItem(appMetadataKey); - if (CacheHelpers.isAppMetadataEntity(appMetadataKey, appMetadata)) { - return appMetadata; - } - return null; - } - /** - * set appMetadata entity to the platform cache - * @param appMetadata - cache value to be set of type AppMetadataEntity - */ - setAppMetadata(appMetadata) { - const appMetadataKey = CacheHelpers.generateAppMetadataKey(appMetadata); - this.setItem(appMetadataKey, appMetadata); - } - /** - * fetch server telemetry entity from the platform cache - * @param serverTelemetrykey - lookup key to fetch cache type ServerTelemetryEntity - */ - getServerTelemetry(serverTelemetrykey) { - const serverTelemetryEntity = this.getItem(serverTelemetrykey); - if (serverTelemetryEntity && - CacheHelpers.isServerTelemetryEntity(serverTelemetrykey, serverTelemetryEntity)) { - return serverTelemetryEntity; - } - return null; - } - /** - * set server telemetry entity to the platform cache - * @param serverTelemetryKey - lookup key to fetch cache type ServerTelemetryEntity - * @param serverTelemetry - cache value to be set of type ServerTelemetryEntity - */ - setServerTelemetry(serverTelemetryKey, serverTelemetry) { - this.setItem(serverTelemetryKey, serverTelemetry); - } - /** - * fetch authority metadata entity from the platform cache - * @param key - lookup key to fetch cache type AuthorityMetadataEntity - */ - getAuthorityMetadata(key) { - const authorityMetadataEntity = this.getItem(key); - if (authorityMetadataEntity && - CacheHelpers.isAuthorityMetadataEntity(key, authorityMetadataEntity)) { - return authorityMetadataEntity; - } - return null; - } - /** - * Get all authority metadata keys - */ - getAuthorityMetadataKeys() { - return this.getKeys().filter((key) => { - return this.isAuthorityMetadata(key); - }); - } - /** - * set authority metadata entity to the platform cache - * @param key - lookup key to fetch cache type AuthorityMetadataEntity - * @param metadata - cache value to be set of type AuthorityMetadataEntity - */ - setAuthorityMetadata(key, metadata) { - this.setItem(key, metadata); - } - /** - * fetch throttling entity from the platform cache - * @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity - */ - getThrottlingCache(throttlingCacheKey) { - const throttlingCache = this.getItem(throttlingCacheKey); - if (throttlingCache && - CacheHelpers.isThrottlingEntity(throttlingCacheKey, throttlingCache)) { - return throttlingCache; - } - return null; - } - /** - * set throttling entity to the platform cache - * @param throttlingCacheKey - lookup key to fetch cache type ThrottlingEntity - * @param throttlingCache - cache value to be set of type ThrottlingEntity - */ - setThrottlingCache(throttlingCacheKey, throttlingCache) { - this.setItem(throttlingCacheKey, throttlingCache); - } - /** - * Removes the cache item from memory with the given key. - * @param key - lookup key to remove a cache entity - * @param inMemory - key value map of the cache - */ - removeItem(key) { - this.logger.tracePii(`Item key: ${key}`); - // read inMemoryCache - let result = false; - const cache = this.getCache(); - if (!!cache[key]) { - delete cache[key]; - result = true; - } - // write to the cache after removal - if (result) { - this.setCache(cache); - this.emitChange(); - } - return result; - } - /** - * Remove account entity from the platform cache if it's outdated - * @param accountKey - lookup key to fetch cache type AccountEntity - */ - removeOutdatedAccount(accountKey) { - this.removeItem(accountKey); - } - /** - * Checks whether key is in cache. - * @param key - look up key for a cache entity - */ - containsKey(key) { - return this.getKeys().includes(key); - } - /** - * Gets all keys in window. - */ - getKeys() { - this.logger.trace("Retrieving all cache keys"); - // read cache - const cache = this.getCache(); - return [...Object.keys(cache)]; - } - /** - * Clears all cache entries created by MSAL (except tokens). - */ - clear() { - this.logger.trace("Clearing cache entries created by MSAL"); - // read inMemoryCache - const cacheKeys = this.getKeys(); - // delete each element - cacheKeys.forEach((key) => { - this.removeItem(key); - }); - this.emitChange(); - } - /** - * Initialize in memory cache from an exisiting cache vault - * @param cache - blob formatted cache (JSON) - */ - static generateInMemoryCache(cache) { - return Deserializer.deserializeAllCache(Deserializer.deserializeJSONBlob(cache)); - } - /** - * retrieves the final JSON - * @param inMemoryCache - itemised cache read from the JSON - */ - static generateJsonCache(inMemoryCache) { - return Serializer.serializeAllCache(inMemoryCache); - } - /** - * Updates a credential's cache key if the current cache key is outdated - */ - updateCredentialCacheKey(currentCacheKey, credential) { - const updatedCacheKey = this.generateCredentialKey(credential); - if (currentCacheKey !== updatedCacheKey) { - const cacheItem = this.getItem(currentCacheKey); - if (cacheItem) { - this.removeItem(currentCacheKey); - this.setItem(updatedCacheKey, cacheItem); - this.logger.verbose(`Updated an outdated ${credential.credentialType} cache key`); - return updatedCacheKey; - } - else { - this.logger.error(`Attempted to update an outdated ${credential.credentialType} cache key but no item matching the outdated key was found in storage`); - } - } - return currentCacheKey; - } -} - -export { NodeStorage }; -//# sourceMappingURL=NodeStorage.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/cache/TokenCache.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/cache/TokenCache.mjs deleted file mode 100644 index 359dc66d..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/cache/TokenCache.mjs +++ /dev/null @@ -1,300 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { NodeStorage } from './NodeStorage.mjs'; -import { TokenCacheContext } from '@azure/msal-common/node'; -import { Deserializer } from './serializer/Deserializer.mjs'; -import { Serializer } from './serializer/Serializer.mjs'; -import { CryptoProvider } from '../crypto/CryptoProvider.mjs'; -import { GuidGenerator } from '../crypto/GuidGenerator.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const defaultSerializedCache = { - Account: {}, - IdToken: {}, - AccessToken: {}, - RefreshToken: {}, - AppMetadata: {}, -}; -/** - * In-memory token cache manager - * @public - */ -class TokenCache { - constructor(storage, logger, cachePlugin) { - this.cacheHasChanged = false; - this.storage = storage; - this.storage.registerChangeEmitter(this.handleChangeEvent.bind(this)); - if (cachePlugin) { - this.persistence = cachePlugin; - } - this.logger = logger; - } - /** - * Set to true if cache state has changed since last time serialize or writeToPersistence was called - */ - hasChanged() { - return this.cacheHasChanged; - } - /** - * Serializes in memory cache to JSON - */ - serialize() { - this.logger.trace("Serializing in-memory cache"); - let finalState = Serializer.serializeAllCache(this.storage.getInMemoryCache()); - // if cacheSnapshot not null or empty, merge - if (this.cacheSnapshot) { - this.logger.trace("Reading cache snapshot from disk"); - finalState = this.mergeState(JSON.parse(this.cacheSnapshot), finalState); - } - else { - this.logger.trace("No cache snapshot to merge"); - } - this.cacheHasChanged = false; - return JSON.stringify(finalState); - } - /** - * Deserializes JSON to in-memory cache. JSON should be in MSAL cache schema format - * @param cache - blob formatted cache - */ - deserialize(cache) { - this.logger.trace("Deserializing JSON to in-memory cache"); - this.cacheSnapshot = cache; - if (this.cacheSnapshot) { - this.logger.trace("Reading cache snapshot from disk"); - const deserializedCache = Deserializer.deserializeAllCache(this.overlayDefaults(JSON.parse(this.cacheSnapshot))); - this.storage.setInMemoryCache(deserializedCache); - } - else { - this.logger.trace("No cache snapshot to deserialize"); - } - } - /** - * Fetches the cache key-value map - */ - getKVStore() { - return this.storage.getCache(); - } - /** - * Gets cache snapshot in CacheKVStore format - */ - getCacheSnapshot() { - const deserializedPersistentStorage = NodeStorage.generateInMemoryCache(this.cacheSnapshot); - return this.storage.inMemoryCacheToCache(deserializedPersistentStorage); - } - /** - * API that retrieves all accounts currently in cache to the user - */ - async getAllAccounts(correlationId = new CryptoProvider().createNewGuid()) { - this.logger.trace("getAllAccounts called"); - let cacheContext; - try { - if (this.persistence) { - cacheContext = new TokenCacheContext(this, false); - await this.persistence.beforeCacheAccess(cacheContext); - } - return this.storage.getAllAccounts({}, correlationId); - } - finally { - if (this.persistence && cacheContext) { - await this.persistence.afterCacheAccess(cacheContext); - } - } - } - /** - * Returns the signed in account matching homeAccountId. - * (the account object is created at the time of successful login) - * or null when no matching account is found - * @param homeAccountId - unique identifier for an account (uid.utid) - */ - async getAccountByHomeId(homeAccountId) { - const allAccounts = await this.getAllAccounts(); - if (homeAccountId && allAccounts && allAccounts.length) { - return (allAccounts.filter((accountObj) => accountObj.homeAccountId === homeAccountId)[0] || null); - } - else { - return null; - } - } - /** - * Returns the signed in account matching localAccountId. - * (the account object is created at the time of successful login) - * or null when no matching account is found - * @param localAccountId - unique identifier of an account (sub/obj when homeAccountId cannot be populated) - */ - async getAccountByLocalId(localAccountId) { - const allAccounts = await this.getAllAccounts(); - if (localAccountId && allAccounts && allAccounts.length) { - return (allAccounts.filter((accountObj) => accountObj.localAccountId === localAccountId)[0] || null); - } - else { - return null; - } - } - /** - * API to remove a specific account and the relevant data from cache - * @param account - AccountInfo passed by the user - */ - async removeAccount(account, correlationId) { - this.logger.trace("removeAccount called"); - let cacheContext; - try { - if (this.persistence) { - cacheContext = new TokenCacheContext(this, true); - await this.persistence.beforeCacheAccess(cacheContext); - } - this.storage.removeAccount(account, correlationId || new GuidGenerator().generateGuid()); - } - finally { - if (this.persistence && cacheContext) { - await this.persistence.afterCacheAccess(cacheContext); - } - } - } - /** - * Overwrites in-memory cache with persistent cache - */ - async overwriteCache() { - if (!this.persistence) { - this.logger.info("No persistence layer specified, cache cannot be overwritten"); - return; - } - this.logger.info("Overwriting in-memory cache with persistent cache"); - this.storage.clear(); - const cacheContext = new TokenCacheContext(this, false); - await this.persistence.beforeCacheAccess(cacheContext); - const cacheSnapshot = this.getCacheSnapshot(); - this.storage.setCache(cacheSnapshot); - await this.persistence.afterCacheAccess(cacheContext); - } - /** - * Called when the cache has changed state. - */ - handleChangeEvent() { - this.cacheHasChanged = true; - } - /** - * Merge in memory cache with the cache snapshot. - * @param oldState - cache before changes - * @param currentState - current cache state in the library - */ - mergeState(oldState, currentState) { - this.logger.trace("Merging in-memory cache with cache snapshot"); - const stateAfterRemoval = this.mergeRemovals(oldState, currentState); - return this.mergeUpdates(stateAfterRemoval, currentState); - } - /** - * Deep update of oldState based on newState values - * @param oldState - cache before changes - * @param newState - updated cache - */ - mergeUpdates(oldState, newState) { - Object.keys(newState).forEach((newKey) => { - const newValue = newState[newKey]; - // if oldState does not contain value but newValue does, add it - if (!oldState.hasOwnProperty(newKey)) { - if (newValue !== null) { - oldState[newKey] = newValue; - } - } - else { - // both oldState and newState contain the key, do deep update - const newValueNotNull = newValue !== null; - const newValueIsObject = typeof newValue === "object"; - const newValueIsNotArray = !Array.isArray(newValue); - const oldStateNotUndefinedOrNull = typeof oldState[newKey] !== "undefined" && - oldState[newKey] !== null; - if (newValueNotNull && - newValueIsObject && - newValueIsNotArray && - oldStateNotUndefinedOrNull) { - this.mergeUpdates(oldState[newKey], newValue); - } - else { - oldState[newKey] = newValue; - } - } - }); - return oldState; - } - /** - * Removes entities in oldState that the were removed from newState. If there are any unknown values in root of - * oldState that are not recognized, they are left untouched. - * @param oldState - cache before changes - * @param newState - updated cache - */ - mergeRemovals(oldState, newState) { - this.logger.trace("Remove updated entries in cache"); - const accounts = oldState.Account - ? this.mergeRemovalsDict(oldState.Account, newState.Account) - : oldState.Account; - const accessTokens = oldState.AccessToken - ? this.mergeRemovalsDict(oldState.AccessToken, newState.AccessToken) - : oldState.AccessToken; - const refreshTokens = oldState.RefreshToken - ? this.mergeRemovalsDict(oldState.RefreshToken, newState.RefreshToken) - : oldState.RefreshToken; - const idTokens = oldState.IdToken - ? this.mergeRemovalsDict(oldState.IdToken, newState.IdToken) - : oldState.IdToken; - const appMetadata = oldState.AppMetadata - ? this.mergeRemovalsDict(oldState.AppMetadata, newState.AppMetadata) - : oldState.AppMetadata; - return { - ...oldState, - Account: accounts, - AccessToken: accessTokens, - RefreshToken: refreshTokens, - IdToken: idTokens, - AppMetadata: appMetadata, - }; - } - /** - * Helper to merge new cache with the old one - * @param oldState - cache before changes - * @param newState - updated cache - */ - mergeRemovalsDict(oldState, newState) { - const finalState = { ...oldState }; - Object.keys(oldState).forEach((oldKey) => { - if (!newState || !newState.hasOwnProperty(oldKey)) { - delete finalState[oldKey]; - } - }); - return finalState; - } - /** - * Helper to overlay as a part of cache merge - * @param passedInCache - cache read from the blob - */ - overlayDefaults(passedInCache) { - this.logger.trace("Overlaying input cache with the default cache"); - return { - Account: { - ...defaultSerializedCache.Account, - ...passedInCache.Account, - }, - IdToken: { - ...defaultSerializedCache.IdToken, - ...passedInCache.IdToken, - }, - AccessToken: { - ...defaultSerializedCache.AccessToken, - ...passedInCache.AccessToken, - }, - RefreshToken: { - ...defaultSerializedCache.RefreshToken, - ...passedInCache.RefreshToken, - }, - AppMetadata: { - ...defaultSerializedCache.AppMetadata, - ...passedInCache.AppMetadata, - }, - }; - } -} - -export { TokenCache }; -//# sourceMappingURL=TokenCache.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/cache/distributed/DistributedCachePlugin.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/cache/distributed/DistributedCachePlugin.mjs deleted file mode 100644 index c6af24fb..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/cache/distributed/DistributedCachePlugin.mjs +++ /dev/null @@ -1,49 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { AccountEntity } from '@azure/msal-common/node'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Cache plugin that serializes data to the cache and deserializes data from the cache - * @public - */ -class DistributedCachePlugin { - constructor(client, partitionManager) { - this.client = client; - this.partitionManager = partitionManager; - } - /** - * Deserializes the cache before accessing it - * @param cacheContext - TokenCacheContext - */ - async beforeCacheAccess(cacheContext) { - const partitionKey = await this.partitionManager.getKey(); - const cacheData = await this.client.get(partitionKey); - cacheContext.tokenCache.deserialize(cacheData); - } - /** - * Serializes the cache after accessing it - * @param cacheContext - TokenCacheContext - */ - async afterCacheAccess(cacheContext) { - if (cacheContext.cacheHasChanged) { - const kvStore = cacheContext.tokenCache.getKVStore(); - const accountEntities = Object.values(kvStore).filter((value) => AccountEntity.isAccountEntity(value)); - let partitionKey; - if (accountEntities.length > 0) { - const accountEntity = accountEntities[0]; - partitionKey = await this.partitionManager.extractKey(accountEntity); - } - else { - partitionKey = await this.partitionManager.getKey(); - } - await this.client.set(partitionKey, cacheContext.tokenCache.serialize()); - } - } -} - -export { DistributedCachePlugin }; -//# sourceMappingURL=DistributedCachePlugin.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/cache/serializer/Deserializer.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/cache/serializer/Deserializer.mjs deleted file mode 100644 index 4d75a39d..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/cache/serializer/Deserializer.mjs +++ /dev/null @@ -1,179 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { AccountEntity, CacheManager } from '@azure/msal-common/node'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * This class deserializes cache entities read from the file into in-memory object types defined internally - * @internal - */ -class Deserializer { - /** - * Parse the JSON blob in memory and deserialize the content - * @param cachedJson - JSON blob cache - */ - static deserializeJSONBlob(jsonFile) { - const deserializedCache = !jsonFile ? {} : JSON.parse(jsonFile); - return deserializedCache; - } - /** - * Deserializes accounts to AccountEntity objects - * @param accounts - accounts of type SerializedAccountEntity - */ - static deserializeAccounts(accounts) { - const accountObjects = {}; - if (accounts) { - Object.keys(accounts).map(function (key) { - const serializedAcc = accounts[key]; - const mappedAcc = { - homeAccountId: serializedAcc.home_account_id, - environment: serializedAcc.environment, - realm: serializedAcc.realm, - localAccountId: serializedAcc.local_account_id, - username: serializedAcc.username, - authorityType: serializedAcc.authority_type, - name: serializedAcc.name, - clientInfo: serializedAcc.client_info, - lastModificationTime: serializedAcc.last_modification_time, - lastModificationApp: serializedAcc.last_modification_app, - tenantProfiles: serializedAcc.tenantProfiles?.map((serializedTenantProfile) => { - return JSON.parse(serializedTenantProfile); - }), - lastUpdatedAt: Date.now().toString(), - }; - const account = new AccountEntity(); - CacheManager.toObject(account, mappedAcc); - accountObjects[key] = account; - }); - } - return accountObjects; - } - /** - * Deserializes id tokens to IdTokenEntity objects - * @param idTokens - credentials of type SerializedIdTokenEntity - */ - static deserializeIdTokens(idTokens) { - const idObjects = {}; - if (idTokens) { - Object.keys(idTokens).map(function (key) { - const serializedIdT = idTokens[key]; - const idToken = { - homeAccountId: serializedIdT.home_account_id, - environment: serializedIdT.environment, - credentialType: serializedIdT.credential_type, - clientId: serializedIdT.client_id, - secret: serializedIdT.secret, - realm: serializedIdT.realm, - lastUpdatedAt: Date.now().toString(), - }; - idObjects[key] = idToken; - }); - } - return idObjects; - } - /** - * Deserializes access tokens to AccessTokenEntity objects - * @param accessTokens - access tokens of type SerializedAccessTokenEntity - */ - static deserializeAccessTokens(accessTokens) { - const atObjects = {}; - if (accessTokens) { - Object.keys(accessTokens).map(function (key) { - const serializedAT = accessTokens[key]; - const accessToken = { - homeAccountId: serializedAT.home_account_id, - environment: serializedAT.environment, - credentialType: serializedAT.credential_type, - clientId: serializedAT.client_id, - secret: serializedAT.secret, - realm: serializedAT.realm, - target: serializedAT.target, - cachedAt: serializedAT.cached_at, - expiresOn: serializedAT.expires_on, - extendedExpiresOn: serializedAT.extended_expires_on, - refreshOn: serializedAT.refresh_on, - keyId: serializedAT.key_id, - tokenType: serializedAT.token_type, - requestedClaims: serializedAT.requestedClaims, - requestedClaimsHash: serializedAT.requestedClaimsHash, - userAssertionHash: serializedAT.userAssertionHash, - lastUpdatedAt: Date.now().toString(), - }; - atObjects[key] = accessToken; - }); - } - return atObjects; - } - /** - * Deserializes refresh tokens to RefreshTokenEntity objects - * @param refreshTokens - refresh tokens of type SerializedRefreshTokenEntity - */ - static deserializeRefreshTokens(refreshTokens) { - const rtObjects = {}; - if (refreshTokens) { - Object.keys(refreshTokens).map(function (key) { - const serializedRT = refreshTokens[key]; - const refreshToken = { - homeAccountId: serializedRT.home_account_id, - environment: serializedRT.environment, - credentialType: serializedRT.credential_type, - clientId: serializedRT.client_id, - secret: serializedRT.secret, - familyId: serializedRT.family_id, - target: serializedRT.target, - realm: serializedRT.realm, - lastUpdatedAt: Date.now().toString(), - }; - rtObjects[key] = refreshToken; - }); - } - return rtObjects; - } - /** - * Deserializes appMetadata to AppMetaData objects - * @param appMetadata - app metadata of type SerializedAppMetadataEntity - */ - static deserializeAppMetadata(appMetadata) { - const appMetadataObjects = {}; - if (appMetadata) { - Object.keys(appMetadata).map(function (key) { - const serializedAmdt = appMetadata[key]; - appMetadataObjects[key] = { - clientId: serializedAmdt.client_id, - environment: serializedAmdt.environment, - familyId: serializedAmdt.family_id, - }; - }); - } - return appMetadataObjects; - } - /** - * Deserialize an inMemory Cache - * @param jsonCache - JSON blob cache - */ - static deserializeAllCache(jsonCache) { - return { - accounts: jsonCache.Account - ? this.deserializeAccounts(jsonCache.Account) - : {}, - idTokens: jsonCache.IdToken - ? this.deserializeIdTokens(jsonCache.IdToken) - : {}, - accessTokens: jsonCache.AccessToken - ? this.deserializeAccessTokens(jsonCache.AccessToken) - : {}, - refreshTokens: jsonCache.RefreshToken - ? this.deserializeRefreshTokens(jsonCache.RefreshToken) - : {}, - appMetadata: jsonCache.AppMetadata - ? this.deserializeAppMetadata(jsonCache.AppMetadata) - : {}, - }; - } -} - -export { Deserializer }; -//# sourceMappingURL=Deserializer.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/cache/serializer/Serializer.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/cache/serializer/Serializer.mjs deleted file mode 100644 index c548cf6f..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/cache/serializer/Serializer.mjs +++ /dev/null @@ -1,146 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * This class serializes cache entities to be saved into in-memory object types defined internally - * @internal - */ -class Serializer { - /** - * serialize the JSON blob - * @param data - JSON blob cache - */ - static serializeJSONBlob(data) { - return JSON.stringify(data); - } - /** - * Serialize Accounts - * @param accCache - cache of accounts - */ - static serializeAccounts(accCache) { - const accounts = {}; - Object.keys(accCache).map(function (key) { - const accountEntity = accCache[key]; - accounts[key] = { - home_account_id: accountEntity.homeAccountId, - environment: accountEntity.environment, - realm: accountEntity.realm, - local_account_id: accountEntity.localAccountId, - username: accountEntity.username, - authority_type: accountEntity.authorityType, - name: accountEntity.name, - client_info: accountEntity.clientInfo, - last_modification_time: accountEntity.lastModificationTime, - last_modification_app: accountEntity.lastModificationApp, - tenantProfiles: accountEntity.tenantProfiles?.map((tenantProfile) => { - return JSON.stringify(tenantProfile); - }), - }; - }); - return accounts; - } - /** - * Serialize IdTokens - * @param idTCache - cache of ID tokens - */ - static serializeIdTokens(idTCache) { - const idTokens = {}; - Object.keys(idTCache).map(function (key) { - const idTEntity = idTCache[key]; - idTokens[key] = { - home_account_id: idTEntity.homeAccountId, - environment: idTEntity.environment, - credential_type: idTEntity.credentialType, - client_id: idTEntity.clientId, - secret: idTEntity.secret, - realm: idTEntity.realm, - }; - }); - return idTokens; - } - /** - * Serializes AccessTokens - * @param atCache - cache of access tokens - */ - static serializeAccessTokens(atCache) { - const accessTokens = {}; - Object.keys(atCache).map(function (key) { - const atEntity = atCache[key]; - accessTokens[key] = { - home_account_id: atEntity.homeAccountId, - environment: atEntity.environment, - credential_type: atEntity.credentialType, - client_id: atEntity.clientId, - secret: atEntity.secret, - realm: atEntity.realm, - target: atEntity.target, - cached_at: atEntity.cachedAt, - expires_on: atEntity.expiresOn, - extended_expires_on: atEntity.extendedExpiresOn, - refresh_on: atEntity.refreshOn, - key_id: atEntity.keyId, - token_type: atEntity.tokenType, - requestedClaims: atEntity.requestedClaims, - requestedClaimsHash: atEntity.requestedClaimsHash, - userAssertionHash: atEntity.userAssertionHash, - }; - }); - return accessTokens; - } - /** - * Serialize refreshTokens - * @param rtCache - cache of refresh tokens - */ - static serializeRefreshTokens(rtCache) { - const refreshTokens = {}; - Object.keys(rtCache).map(function (key) { - const rtEntity = rtCache[key]; - refreshTokens[key] = { - home_account_id: rtEntity.homeAccountId, - environment: rtEntity.environment, - credential_type: rtEntity.credentialType, - client_id: rtEntity.clientId, - secret: rtEntity.secret, - family_id: rtEntity.familyId, - target: rtEntity.target, - realm: rtEntity.realm, - }; - }); - return refreshTokens; - } - /** - * Serialize amdtCache - * @param amdtCache - cache of app metadata - */ - static serializeAppMetadata(amdtCache) { - const appMetadata = {}; - Object.keys(amdtCache).map(function (key) { - const amdtEntity = amdtCache[key]; - appMetadata[key] = { - client_id: amdtEntity.clientId, - environment: amdtEntity.environment, - family_id: amdtEntity.familyId, - }; - }); - return appMetadata; - } - /** - * Serialize the cache - * @param inMemCache - itemised cache read from the JSON - */ - static serializeAllCache(inMemCache) { - return { - Account: this.serializeAccounts(inMemCache.accounts), - IdToken: this.serializeIdTokens(inMemCache.idTokens), - AccessToken: this.serializeAccessTokens(inMemCache.accessTokens), - RefreshToken: this.serializeRefreshTokens(inMemCache.refreshTokens), - AppMetadata: this.serializeAppMetadata(inMemCache.appMetadata), - }; - } -} - -export { Serializer }; -//# sourceMappingURL=Serializer.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ClientApplication.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ClientApplication.mjs deleted file mode 100644 index eb46b615..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/client/ClientApplication.mjs +++ /dev/null @@ -1,385 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { Logger, buildStaticAuthorityOptions, AuthenticationScheme, AuthorizationCodeClient, AuthError, RefreshTokenClient, SilentFlowClient, ClientAuthError, ClientAuthErrorCodes, OIDC_DEFAULT_SCOPES, CacheOutcome, createClientAuthError, Constants, getClientAssertion, StringUtils, ServerTelemetryManager, Authority, AuthorityFactory, ResponseMode } from '@azure/msal-common/node'; -import { buildAppConfiguration } from '../config/Configuration.mjs'; -import { CryptoProvider } from '../crypto/CryptoProvider.mjs'; -import { NodeStorage } from '../cache/NodeStorage.mjs'; -import { ApiId, Constants as Constants$1 } from '../utils/Constants.mjs'; -import { TokenCache } from '../cache/TokenCache.mjs'; -import { ClientAssertion } from './ClientAssertion.mjs'; -import { name, version } from '../packageMetadata.mjs'; -import { NodeAuthError } from '../error/NodeAuthError.mjs'; -import { UsernamePasswordClient } from './UsernamePasswordClient.mjs'; -import { getAuthCodeRequestUrl } from '../protocol/Authorize.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Base abstract class for all ClientApplications - public and confidential - * @public - */ -class ClientApplication { - /** - * Constructor for the ClientApplication - */ - constructor(configuration) { - this.config = buildAppConfiguration(configuration); - this.cryptoProvider = new CryptoProvider(); - this.logger = new Logger(this.config.system.loggerOptions, name, version); - this.storage = new NodeStorage(this.logger, this.config.auth.clientId, this.cryptoProvider, buildStaticAuthorityOptions(this.config.auth)); - this.tokenCache = new TokenCache(this.storage, this.logger, this.config.cache.cachePlugin); - } - /** - * Creates the URL of the authorization request, letting the user input credentials and consent to the - * application. The URL targets the /authorize endpoint of the authority configured in the - * application object. - * - * Once the user inputs their credentials and consents, the authority will send a response to the redirect URI - * sent in the request and should contain an authorization code, which can then be used to acquire tokens via - * `acquireTokenByCode(AuthorizationCodeRequest)`. - */ - async getAuthCodeUrl(request) { - this.logger.info("getAuthCodeUrl called", request.correlationId); - const validRequest = { - ...request, - ...(await this.initializeBaseRequest(request)), - responseMode: request.responseMode || ResponseMode.QUERY, - authenticationScheme: AuthenticationScheme.BEARER, - state: request.state || "", - nonce: request.nonce || "", - }; - const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request.azureCloudOptions); - return getAuthCodeRequestUrl(this.config, discoveredAuthority, validRequest, this.logger); - } - /** - * Acquires a token by exchanging the Authorization Code received from the first step of OAuth2.0 - * Authorization Code flow. - * - * `getAuthCodeUrl(AuthorizationCodeUrlRequest)` can be used to create the URL for the first step of OAuth2.0 - * Authorization Code flow. Ensure that values for redirectUri and scopes in AuthorizationCodeUrlRequest and - * AuthorizationCodeRequest are the same. - */ - async acquireTokenByCode(request, authCodePayLoad) { - this.logger.info("acquireTokenByCode called"); - if (request.state && authCodePayLoad) { - this.logger.info("acquireTokenByCode - validating state"); - this.validateState(request.state, authCodePayLoad.state || ""); - // eslint-disable-next-line no-param-reassign - authCodePayLoad = { ...authCodePayLoad, state: "" }; - } - const validRequest = { - ...request, - ...(await this.initializeBaseRequest(request)), - authenticationScheme: AuthenticationScheme.BEARER, - }; - const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByCode, validRequest.correlationId); - try { - const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request.azureCloudOptions); - const authClientConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, validRequest.redirectUri, serverTelemetryManager); - const authorizationCodeClient = new AuthorizationCodeClient(authClientConfig); - this.logger.verbose("Auth code client created", validRequest.correlationId); - return await authorizationCodeClient.acquireToken(validRequest, authCodePayLoad); - } - catch (e) { - if (e instanceof AuthError) { - e.setCorrelationId(validRequest.correlationId); - } - serverTelemetryManager.cacheFailedRequest(e); - throw e; - } - } - /** - * Acquires a token by exchanging the refresh token provided for a new set of tokens. - * - * This API is provided only for scenarios where you would like to migrate from ADAL to MSAL. Otherwise, it is - * recommended that you use `acquireTokenSilent()` for silent scenarios. When using `acquireTokenSilent()`, MSAL will - * handle the caching and refreshing of tokens automatically. - */ - async acquireTokenByRefreshToken(request) { - this.logger.info("acquireTokenByRefreshToken called", request.correlationId); - const validRequest = { - ...request, - ...(await this.initializeBaseRequest(request)), - authenticationScheme: AuthenticationScheme.BEARER, - }; - const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByRefreshToken, validRequest.correlationId); - try { - const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request.azureCloudOptions); - const refreshTokenClientConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, validRequest.redirectUri || "", serverTelemetryManager); - const refreshTokenClient = new RefreshTokenClient(refreshTokenClientConfig); - this.logger.verbose("Refresh token client created", validRequest.correlationId); - return await refreshTokenClient.acquireToken(validRequest); - } - catch (e) { - if (e instanceof AuthError) { - e.setCorrelationId(validRequest.correlationId); - } - serverTelemetryManager.cacheFailedRequest(e); - throw e; - } - } - /** - * Acquires a token silently when a user specifies the account the token is requested for. - * - * This API expects the user to provide an account object and looks into the cache to retrieve the token if present. - * There is also an optional "forceRefresh" boolean the user can send to bypass the cache for access_token and id_token. - * In case the refresh_token is expired or not found, an error is thrown - * and the guidance is for the user to call any interactive token acquisition API (eg: `acquireTokenByCode()`). - */ - async acquireTokenSilent(request) { - const validRequest = { - ...request, - ...(await this.initializeBaseRequest(request)), - forceRefresh: request.forceRefresh || false, - }; - const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenSilent, validRequest.correlationId, validRequest.forceRefresh); - try { - const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request.azureCloudOptions); - const clientConfiguration = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, validRequest.redirectUri || "", serverTelemetryManager); - const silentFlowClient = new SilentFlowClient(clientConfiguration); - this.logger.verbose("Silent flow client created", validRequest.correlationId); - try { - // always overwrite the in-memory cache with the persistence cache (if it exists) before a cache lookup - await this.tokenCache.overwriteCache(); - return await this.acquireCachedTokenSilent(validRequest, silentFlowClient, clientConfiguration); - } - catch (error) { - if (error instanceof ClientAuthError && - error.errorCode === - ClientAuthErrorCodes.tokenRefreshRequired) { - const refreshTokenClient = new RefreshTokenClient(clientConfiguration); - return refreshTokenClient.acquireTokenByRefreshToken(validRequest); - } - throw error; - } - } - catch (error) { - if (error instanceof AuthError) { - error.setCorrelationId(validRequest.correlationId); - } - serverTelemetryManager.cacheFailedRequest(error); - throw error; - } - } - async acquireCachedTokenSilent(validRequest, silentFlowClient, clientConfiguration) { - const [authResponse, cacheOutcome] = await silentFlowClient.acquireCachedToken({ - ...validRequest, - scopes: validRequest.scopes?.length - ? validRequest.scopes - : [...OIDC_DEFAULT_SCOPES], - }); - if (cacheOutcome === CacheOutcome.PROACTIVELY_REFRESHED) { - this.logger.info("ClientApplication:acquireCachedTokenSilent - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed."); - // refresh the access token in the background - const refreshTokenClient = new RefreshTokenClient(clientConfiguration); - try { - await refreshTokenClient.acquireTokenByRefreshToken(validRequest); - } - catch { - // do nothing, this is running in the background and no action is to be taken upon success or failure - } - } - // return the cached token - return authResponse; - } - /** - * Acquires tokens with password grant by exchanging client applications username and password for credentials - * - * The latest OAuth 2.0 Security Best Current Practice disallows the password grant entirely. - * More details on this recommendation at https://tools.ietf.org/html/draft-ietf-oauth-security-topics-13#section-3.4 - * Microsoft's documentation and recommendations are at: - * https://docs.microsoft.com/en-us/azure/active-directory/develop/msal-authentication-flows#usernamepassword - * - * @param request - UsenamePasswordRequest - * @deprecated - Use a more secure flow instead - */ - async acquireTokenByUsernamePassword(request) { - this.logger.info("acquireTokenByUsernamePassword called", request.correlationId); - const validRequest = { - ...request, - ...(await this.initializeBaseRequest(request)), - }; - const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByUsernamePassword, validRequest.correlationId); - try { - const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request.azureCloudOptions); - const usernamePasswordClientConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, "", serverTelemetryManager); - const usernamePasswordClient = new UsernamePasswordClient(usernamePasswordClientConfig); - this.logger.verbose("Username password client created", validRequest.correlationId); - return await usernamePasswordClient.acquireToken(validRequest); - } - catch (e) { - if (e instanceof AuthError) { - e.setCorrelationId(validRequest.correlationId); - } - serverTelemetryManager.cacheFailedRequest(e); - throw e; - } - } - /** - * Gets the token cache for the application. - */ - getTokenCache() { - this.logger.info("getTokenCache called"); - return this.tokenCache; - } - /** - * Validates OIDC state by comparing the user cached state with the state received from the server. - * - * This API is provided for scenarios where you would use OAuth2.0 state parameter to mitigate against - * CSRF attacks. - * For more information about state, visit https://datatracker.ietf.org/doc/html/rfc6819#section-3.6. - * @param state - Unique GUID generated by the user that is cached by the user and sent to the server during the first leg of the flow - * @param cachedState - This string is sent back by the server with the authorization code - */ - validateState(state, cachedState) { - if (!state) { - throw NodeAuthError.createStateNotFoundError(); - } - if (state !== cachedState) { - throw createClientAuthError(ClientAuthErrorCodes.stateMismatch); - } - } - /** - * Returns the logger instance - */ - getLogger() { - return this.logger; - } - /** - * Replaces the default logger set in configurations with new Logger with new configurations - * @param logger - Logger instance - */ - setLogger(logger) { - this.logger = logger; - } - /** - * Builds the common configuration to be passed to the common component based on the platform configurarion - * @param authority - user passed authority in configuration - * @param serverTelemetryManager - initializes servertelemetry if passed - */ - async buildOauthClientConfiguration(discoveredAuthority, requestCorrelationId, redirectUri, serverTelemetryManager) { - this.logger.verbose("buildOauthClientConfiguration called", requestCorrelationId); - this.logger.info(`Building oauth client configuration with the following authority: ${discoveredAuthority.tokenEndpoint}.`, requestCorrelationId); - serverTelemetryManager?.updateRegionDiscoveryMetadata(discoveredAuthority.regionDiscoveryMetadata); - const clientConfiguration = { - authOptions: { - clientId: this.config.auth.clientId, - authority: discoveredAuthority, - clientCapabilities: this.config.auth.clientCapabilities, - redirectUri, - }, - loggerOptions: { - logLevel: this.config.system.loggerOptions.logLevel, - loggerCallback: this.config.system.loggerOptions.loggerCallback, - piiLoggingEnabled: this.config.system.loggerOptions.piiLoggingEnabled, - correlationId: requestCorrelationId, - }, - cacheOptions: { - claimsBasedCachingEnabled: this.config.cache.claimsBasedCachingEnabled, - }, - cryptoInterface: this.cryptoProvider, - networkInterface: this.config.system.networkClient, - storageInterface: this.storage, - serverTelemetryManager: serverTelemetryManager, - clientCredentials: { - clientSecret: this.clientSecret, - clientAssertion: await this.getClientAssertion(discoveredAuthority), - }, - libraryInfo: { - sku: Constants$1.MSAL_SKU, - version: version, - cpu: process.arch || Constants.EMPTY_STRING, - os: process.platform || Constants.EMPTY_STRING, - }, - telemetry: this.config.telemetry, - persistencePlugin: this.config.cache.cachePlugin, - serializableCache: this.tokenCache, - }; - return clientConfiguration; - } - async getClientAssertion(authority) { - if (this.developerProvidedClientAssertion) { - this.clientAssertion = ClientAssertion.fromAssertion(await getClientAssertion(this.developerProvidedClientAssertion, this.config.auth.clientId, authority.tokenEndpoint)); - } - return (this.clientAssertion && { - assertion: this.clientAssertion.getJwt(this.cryptoProvider, this.config.auth.clientId, authority.tokenEndpoint), - assertionType: Constants$1.JWT_BEARER_ASSERTION_TYPE, - }); - } - /** - * Generates a request with the default scopes & generates a correlationId. - * @param authRequest - BaseAuthRequest for initialization - */ - async initializeBaseRequest(authRequest) { - this.logger.verbose("initializeRequestScopes called", authRequest.correlationId); - // Default authenticationScheme to Bearer, log that POP isn't supported yet - if (authRequest.authenticationScheme && - authRequest.authenticationScheme === AuthenticationScheme.POP) { - this.logger.verbose("Authentication Scheme 'pop' is not supported yet, setting Authentication Scheme to 'Bearer' for request", authRequest.correlationId); - } - authRequest.authenticationScheme = AuthenticationScheme.BEARER; - // Set requested claims hash if claims-based caching is enabled and claims were requested - if (this.config.cache.claimsBasedCachingEnabled && - authRequest.claims && - // Checks for empty stringified object "{}" which doesn't qualify as requested claims - !StringUtils.isEmptyObj(authRequest.claims)) { - authRequest.requestedClaimsHash = - await this.cryptoProvider.hashString(authRequest.claims); - } - return { - ...authRequest, - scopes: [ - ...((authRequest && authRequest.scopes) || []), - ...OIDC_DEFAULT_SCOPES, - ], - correlationId: (authRequest && authRequest.correlationId) || - this.cryptoProvider.createNewGuid(), - authority: authRequest.authority || this.config.auth.authority, - }; - } - /** - * Initializes the server telemetry payload - * @param apiId - Id for a specific request - * @param correlationId - GUID - * @param forceRefresh - boolean to indicate network call - */ - initializeServerTelemetryManager(apiId, correlationId, forceRefresh) { - const telemetryPayload = { - clientId: this.config.auth.clientId, - correlationId: correlationId, - apiId: apiId, - forceRefresh: forceRefresh || false, - }; - return new ServerTelemetryManager(telemetryPayload, this.storage); - } - /** - * Create authority instance. If authority not passed in request, default to authority set on the application - * object. If no authority set in application object, then default to common authority. - * @param authorityString - authority from user configuration - */ - async createAuthority(authorityString, requestCorrelationId, azureRegionConfiguration, azureCloudOptions) { - this.logger.verbose("createAuthority called", requestCorrelationId); - // build authority string based on auth params - azureCloudInstance is prioritized if provided - const authorityUrl = Authority.generateAuthority(authorityString, azureCloudOptions || this.config.auth.azureCloudOptions); - const authorityOptions = { - protocolMode: this.config.auth.protocolMode, - knownAuthorities: this.config.auth.knownAuthorities, - cloudDiscoveryMetadata: this.config.auth.cloudDiscoveryMetadata, - authorityMetadata: this.config.auth.authorityMetadata, - azureRegionConfiguration, - skipAuthorityMetadataCache: this.config.auth.skipAuthorityMetadataCache, - }; - return AuthorityFactory.createDiscoveredInstance(authorityUrl, this.config.system.networkClient, this.storage, authorityOptions, this.logger, requestCorrelationId); - } - /** - * Clear the cache - */ - clearCache() { - this.storage.clear(); - } -} - -export { ClientApplication }; -//# sourceMappingURL=ClientApplication.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ClientAssertion.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ClientAssertion.mjs deleted file mode 100644 index 758c1148..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/client/ClientAssertion.mjs +++ /dev/null @@ -1,153 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import jwt from 'jsonwebtoken'; -import { createClientAuthError, ClientAuthErrorCodes, TimeUtils, EncodingTypes, Constants } from '@azure/msal-common/node'; -import { EncodingUtils } from '../utils/EncodingUtils.mjs'; -import { JwtConstants } from '../utils/Constants.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Client assertion of type jwt-bearer used in confidential client flows - * @public - */ -class ClientAssertion { - /** - * Initialize the ClientAssertion class from the clientAssertion passed by the user - * @param assertion - refer https://tools.ietf.org/html/rfc7521 - */ - static fromAssertion(assertion) { - const clientAssertion = new ClientAssertion(); - clientAssertion.jwt = assertion; - return clientAssertion; - } - /** - * @deprecated Use fromCertificateWithSha256Thumbprint instead, with a SHA-256 thumprint - * Initialize the ClientAssertion class from the certificate passed by the user - * @param thumbprint - identifier of a certificate - * @param privateKey - secret key - * @param publicCertificate - electronic document provided to prove the ownership of the public key - */ - static fromCertificate(thumbprint, privateKey, publicCertificate) { - const clientAssertion = new ClientAssertion(); - clientAssertion.privateKey = privateKey; - clientAssertion.thumbprint = thumbprint; - clientAssertion.useSha256 = false; - if (publicCertificate) { - clientAssertion.publicCertificate = - this.parseCertificate(publicCertificate); - } - return clientAssertion; - } - /** - * Initialize the ClientAssertion class from the certificate passed by the user - * @param thumbprint - identifier of a certificate - * @param privateKey - secret key - * @param publicCertificate - electronic document provided to prove the ownership of the public key - */ - static fromCertificateWithSha256Thumbprint(thumbprint, privateKey, publicCertificate) { - const clientAssertion = new ClientAssertion(); - clientAssertion.privateKey = privateKey; - clientAssertion.thumbprint = thumbprint; - clientAssertion.useSha256 = true; - if (publicCertificate) { - clientAssertion.publicCertificate = - this.parseCertificate(publicCertificate); - } - return clientAssertion; - } - /** - * Update JWT for certificate based clientAssertion, if passed by the user, uses it as is - * @param cryptoProvider - library's crypto helper - * @param issuer - iss claim - * @param jwtAudience - aud claim - */ - getJwt(cryptoProvider, issuer, jwtAudience) { - // if assertion was created from certificate, check if jwt is expired and create new one. - if (this.privateKey && this.thumbprint) { - if (this.jwt && - !this.isExpired() && - issuer === this.issuer && - jwtAudience === this.jwtAudience) { - return this.jwt; - } - return this.createJwt(cryptoProvider, issuer, jwtAudience); - } - /* - * if assertion was created by caller, then we just append it. It is up to the caller to - * ensure that it contains necessary claims and that it is not expired. - */ - if (this.jwt) { - return this.jwt; - } - throw createClientAuthError(ClientAuthErrorCodes.invalidAssertion); - } - /** - * JWT format and required claims specified: https://tools.ietf.org/html/rfc7523#section-3 - */ - createJwt(cryptoProvider, issuer, jwtAudience) { - this.issuer = issuer; - this.jwtAudience = jwtAudience; - const issuedAt = TimeUtils.nowSeconds(); - this.expirationTime = issuedAt + 600; - const algorithm = this.useSha256 - ? JwtConstants.PSS_256 - : JwtConstants.RSA_256; - const header = { - alg: algorithm, - }; - const thumbprintHeader = this.useSha256 - ? JwtConstants.X5T_256 - : JwtConstants.X5T; - Object.assign(header, { - [thumbprintHeader]: EncodingUtils.base64EncodeUrl(this.thumbprint, EncodingTypes.HEX), - }); - if (this.publicCertificate) { - Object.assign(header, { - [JwtConstants.X5C]: this.publicCertificate, - }); - } - const payload = { - [JwtConstants.AUDIENCE]: this.jwtAudience, - [JwtConstants.EXPIRATION_TIME]: this.expirationTime, - [JwtConstants.ISSUER]: this.issuer, - [JwtConstants.SUBJECT]: this.issuer, - [JwtConstants.NOT_BEFORE]: issuedAt, - [JwtConstants.JWT_ID]: cryptoProvider.createNewGuid(), - }; - this.jwt = jwt.sign(payload, this.privateKey, { header }); - return this.jwt; - } - /** - * Utility API to check expiration - */ - isExpired() { - return this.expirationTime < TimeUtils.nowSeconds(); - } - /** - * Extracts the raw certs from a given certificate string and returns them in an array. - * @param publicCertificate - electronic document provided to prove the ownership of the public key - */ - static parseCertificate(publicCertificate) { - /** - * This is regex to identify the certs in a given certificate string. - * We want to look for the contents between the BEGIN and END certificate strings, without the associated newlines. - * The information in parens "(.+?)" is the capture group to represent the cert we want isolated. - * "." means any string character, "+" means match 1 or more times, and "?" means the shortest match. - * The "g" at the end of the regex means search the string globally, and the "s" enables the "." to match newlines. - */ - const regexToFindCerts = /-----BEGIN CERTIFICATE-----\r*\n(.+?)\r*\n-----END CERTIFICATE-----/gs; - const certs = []; - let matches; - while ((matches = regexToFindCerts.exec(publicCertificate)) !== null) { - // matches[1] represents the first parens capture group in the regex. - certs.push(matches[1].replace(/\r*\n/g, Constants.EMPTY_STRING)); - } - return certs; - } -} - -export { ClientAssertion }; -//# sourceMappingURL=ClientAssertion.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ClientCredentialClient.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ClientCredentialClient.mjs deleted file mode 100644 index 2c0bd208..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/client/ClientCredentialClient.mjs +++ /dev/null @@ -1,202 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { BaseClient, CacheOutcome, TokenCacheContext, ScopeSet, TimeUtils, DEFAULT_TOKEN_RENEWAL_OFFSET_SEC, ResponseHandler, CredentialType, Constants, createClientAuthError, ClientAuthErrorCodes, UrlString, RequestParameterBuilder, GrantType, getClientAssertion, StringUtils, UrlUtils, AuthenticationScheme } from '@azure/msal-common/node'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * OAuth2.0 client credential grant - * @public - */ -class ClientCredentialClient extends BaseClient { - constructor(configuration, appTokenProvider) { - super(configuration); - this.appTokenProvider = appTokenProvider; - } - /** - * Public API to acquire a token with ClientCredential Flow for Confidential clients - * @param request - CommonClientCredentialRequest provided by the developer - */ - async acquireToken(request) { - if (request.skipCache || request.claims) { - return this.executeTokenRequest(request, this.authority); - } - const [cachedAuthenticationResult, lastCacheOutcome] = await this.getCachedAuthenticationResult(request, this.config, this.cryptoUtils, this.authority, this.cacheManager, this.serverTelemetryManager); - if (cachedAuthenticationResult) { - // if the token is not expired but must be refreshed; get a new one in the background - if (lastCacheOutcome === CacheOutcome.PROACTIVELY_REFRESHED) { - this.logger.info("ClientCredentialClient:getCachedAuthenticationResult - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed."); - // refresh the access token in the background - const refreshAccessToken = true; - await this.executeTokenRequest(request, this.authority, refreshAccessToken); - } - // return the cached token - return cachedAuthenticationResult; - } - else { - return this.executeTokenRequest(request, this.authority); - } - } - /** - * looks up cache if the tokens are cached already - */ - async getCachedAuthenticationResult(request, config, cryptoUtils, authority, cacheManager, serverTelemetryManager) { - const clientConfiguration = config; - const managedIdentityConfiguration = config; - let lastCacheOutcome = CacheOutcome.NOT_APPLICABLE; - // read the user-supplied cache into memory, if applicable - let cacheContext; - if (clientConfiguration.serializableCache && - clientConfiguration.persistencePlugin) { - cacheContext = new TokenCacheContext(clientConfiguration.serializableCache, false); - await clientConfiguration.persistencePlugin.beforeCacheAccess(cacheContext); - } - const cachedAccessToken = this.readAccessTokenFromCache(authority, managedIdentityConfiguration.managedIdentityId?.id || - clientConfiguration.authOptions.clientId, new ScopeSet(request.scopes || []), cacheManager, request.correlationId); - if (clientConfiguration.serializableCache && - clientConfiguration.persistencePlugin && - cacheContext) { - await clientConfiguration.persistencePlugin.afterCacheAccess(cacheContext); - } - // must refresh due to non-existent access_token - if (!cachedAccessToken) { - serverTelemetryManager?.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN); - return [null, CacheOutcome.NO_CACHED_ACCESS_TOKEN]; - } - // must refresh due to the expires_in value - if (TimeUtils.isTokenExpired(cachedAccessToken.expiresOn, clientConfiguration.systemOptions?.tokenRenewalOffsetSeconds || - DEFAULT_TOKEN_RENEWAL_OFFSET_SEC)) { - serverTelemetryManager?.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED); - return [null, CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED]; - } - // must refresh (in the background) due to the refresh_in value - if (cachedAccessToken.refreshOn && - TimeUtils.isTokenExpired(cachedAccessToken.refreshOn.toString(), 0)) { - lastCacheOutcome = CacheOutcome.PROACTIVELY_REFRESHED; - serverTelemetryManager?.setCacheOutcome(CacheOutcome.PROACTIVELY_REFRESHED); - } - return [ - await ResponseHandler.generateAuthenticationResult(cryptoUtils, authority, { - account: null, - idToken: null, - accessToken: cachedAccessToken, - refreshToken: null, - appMetadata: null, - }, true, request), - lastCacheOutcome, - ]; - } - /** - * Reads access token from the cache - */ - readAccessTokenFromCache(authority, id, scopeSet, cacheManager, correlationId) { - const accessTokenFilter = { - homeAccountId: Constants.EMPTY_STRING, - environment: authority.canonicalAuthorityUrlComponents.HostNameAndPort, - credentialType: CredentialType.ACCESS_TOKEN, - clientId: id, - realm: authority.tenant, - target: ScopeSet.createSearchScopes(scopeSet.asArray()), - }; - const accessTokens = cacheManager.getAccessTokensByFilter(accessTokenFilter, correlationId); - if (accessTokens.length < 1) { - return null; - } - else if (accessTokens.length > 1) { - throw createClientAuthError(ClientAuthErrorCodes.multipleMatchingTokens); - } - return accessTokens[0]; - } - /** - * Makes a network call to request the token from the service - * @param request - CommonClientCredentialRequest provided by the developer - * @param authority - authority object - */ - async executeTokenRequest(request, authority, refreshAccessToken) { - let serverTokenResponse; - let reqTimestamp; - if (this.appTokenProvider) { - this.logger.info("Using appTokenProvider extensibility."); - const appTokenPropviderParameters = { - correlationId: request.correlationId, - tenantId: this.config.authOptions.authority.tenant, - scopes: request.scopes, - claims: request.claims, - }; - reqTimestamp = TimeUtils.nowSeconds(); - const appTokenProviderResult = await this.appTokenProvider(appTokenPropviderParameters); - serverTokenResponse = { - access_token: appTokenProviderResult.accessToken, - expires_in: appTokenProviderResult.expiresInSeconds, - refresh_in: appTokenProviderResult.refreshInSeconds, - token_type: AuthenticationScheme.BEARER, - }; - } - else { - const queryParametersString = this.createTokenQueryParameters(request); - const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString); - const requestBody = await this.createTokenRequestBody(request); - const headers = this.createTokenRequestHeaders(); - const thumbprint = { - clientId: this.config.authOptions.clientId, - authority: request.authority, - scopes: request.scopes, - claims: request.claims, - authenticationScheme: request.authenticationScheme, - resourceRequestMethod: request.resourceRequestMethod, - resourceRequestUri: request.resourceRequestUri, - shrClaims: request.shrClaims, - sshKid: request.sshKid, - }; - this.logger.info("Sending token request to endpoint: " + authority.tokenEndpoint); - reqTimestamp = TimeUtils.nowSeconds(); - const response = await this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint, request.correlationId); - serverTokenResponse = response.body; - serverTokenResponse.status = response.status; - } - const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin); - responseHandler.validateTokenResponse(serverTokenResponse, refreshAccessToken); - const tokenResponse = await responseHandler.handleServerTokenResponse(serverTokenResponse, this.authority, reqTimestamp, request); - return tokenResponse; - } - /** - * generate the request to the server in the acceptable format - * @param request - CommonClientCredentialRequest provided by the developer - */ - async createTokenRequestBody(request) { - const parameters = new Map(); - RequestParameterBuilder.addClientId(parameters, this.config.authOptions.clientId); - RequestParameterBuilder.addScopes(parameters, request.scopes, false); - RequestParameterBuilder.addGrantType(parameters, GrantType.CLIENT_CREDENTIALS_GRANT); - RequestParameterBuilder.addLibraryInfo(parameters, this.config.libraryInfo); - RequestParameterBuilder.addApplicationTelemetry(parameters, this.config.telemetry.application); - RequestParameterBuilder.addThrottling(parameters); - if (this.serverTelemetryManager) { - RequestParameterBuilder.addServerTelemetry(parameters, this.serverTelemetryManager); - } - const correlationId = request.correlationId || - this.config.cryptoInterface.createNewGuid(); - RequestParameterBuilder.addCorrelationId(parameters, correlationId); - if (this.config.clientCredentials.clientSecret) { - RequestParameterBuilder.addClientSecret(parameters, this.config.clientCredentials.clientSecret); - } - // Use clientAssertion from request, fallback to client assertion in base configuration - const clientAssertion = request.clientAssertion || - this.config.clientCredentials.clientAssertion; - if (clientAssertion) { - RequestParameterBuilder.addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri)); - RequestParameterBuilder.addClientAssertionType(parameters, clientAssertion.assertionType); - } - if (!StringUtils.isEmptyObj(request.claims) || - (this.config.authOptions.clientCapabilities && - this.config.authOptions.clientCapabilities.length > 0)) { - RequestParameterBuilder.addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities); - } - return UrlUtils.mapToQueryString(parameters); - } -} - -export { ClientCredentialClient }; -//# sourceMappingURL=ClientCredentialClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ConfidentialClientApplication.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ConfidentialClientApplication.mjs deleted file mode 100644 index 72c7b350..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/client/ConfidentialClientApplication.mjs +++ /dev/null @@ -1,194 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { ClientApplication } from './ClientApplication.mjs'; -import { ClientAssertion } from './ClientAssertion.mjs'; -import { Constants, MSAL_FORCE_REGION, REGION_ENVIRONMENT_VARIABLE, ApiId } from '../utils/Constants.mjs'; -import { createClientAuthError, ClientAuthErrorCodes, getClientAssertion, OIDC_DEFAULT_SCOPES, UrlString, AADAuthorityConstants, AuthError } from '@azure/msal-common/node'; -import { ClientCredentialClient } from './ClientCredentialClient.mjs'; -import { OnBehalfOfClient } from './OnBehalfOfClient.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -// AADAuthorityConstants -/** - * This class is to be used to acquire tokens for confidential client applications (webApp, webAPI). Confidential client applications - * will configure application secrets, client certificates/assertions as applicable - * @public - */ -class ConfidentialClientApplication extends ClientApplication { - /** - * Constructor for the ConfidentialClientApplication - * - * Required attributes in the Configuration object are: - * - clientID: the application ID of your application. You can obtain one by registering your application with our application registration portal - * - authority: the authority URL for your application. - * - client credential: Must set either client secret, certificate, or assertion for confidential clients. You can obtain a client secret from the application registration portal. - * - * In Azure AD, authority is a URL indicating of the form https://login.microsoftonline.com/\{Enter_the_Tenant_Info_Here\}. - * If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com). - * If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations. - * If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common. - * To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers. - * - * In Azure B2C, authority is of the form https://\{instance\}/tfp/\{tenant\}/\{policyName\}/ - * Full B2C functionality will be available in this library in future versions. - * - * @param Configuration - configuration object for the MSAL ConfidentialClientApplication instance - */ - constructor(configuration) { - super(configuration); - const clientSecretNotEmpty = !!this.config.auth.clientSecret; - const clientAssertionNotEmpty = !!this.config.auth.clientAssertion; - const certificateNotEmpty = (!!this.config.auth.clientCertificate?.thumbprint || - !!this.config.auth.clientCertificate?.thumbprintSha256) && - !!this.config.auth.clientCertificate?.privateKey; - /* - * If app developer configures this callback, they don't need a credential - * i.e. AzureSDK can get token from Managed Identity without a cert / secret - */ - if (this.appTokenProvider) { - return; - } - // Check that at most one credential is set on the application - if ((clientSecretNotEmpty && clientAssertionNotEmpty) || - (clientAssertionNotEmpty && certificateNotEmpty) || - (clientSecretNotEmpty && certificateNotEmpty)) { - throw createClientAuthError(ClientAuthErrorCodes.invalidClientCredential); - } - if (this.config.auth.clientSecret) { - this.clientSecret = this.config.auth.clientSecret; - return; - } - if (this.config.auth.clientAssertion) { - this.developerProvidedClientAssertion = - this.config.auth.clientAssertion; - return; - } - if (!certificateNotEmpty) { - throw createClientAuthError(ClientAuthErrorCodes.invalidClientCredential); - } - else { - this.clientAssertion = !!this.config.auth.clientCertificate - .thumbprintSha256 - ? ClientAssertion.fromCertificateWithSha256Thumbprint(this.config.auth.clientCertificate.thumbprintSha256, this.config.auth.clientCertificate.privateKey, this.config.auth.clientCertificate.x5c) - : ClientAssertion.fromCertificate( - // guaranteed to be a string, due to prior error checking in this function - this.config.auth.clientCertificate.thumbprint, this.config.auth.clientCertificate.privateKey, this.config.auth.clientCertificate.x5c); - } - this.appTokenProvider = undefined; - } - /** - * This extensibility point only works for the client_credential flow, i.e. acquireTokenByClientCredential and - * is meant for Azure SDK to enhance Managed Identity support. - * - * @param IAppTokenProvider - Extensibility interface, which allows the app developer to return a token from a custom source. - */ - SetAppTokenProvider(provider) { - this.appTokenProvider = provider; - } - /** - * Acquires tokens from the authority for the application (not for an end user). - */ - async acquireTokenByClientCredential(request) { - this.logger.info("acquireTokenByClientCredential called", request.correlationId); - // If there is a client assertion present in the request, it overrides the one present in the client configuration - let clientAssertion; - if (request.clientAssertion) { - clientAssertion = { - assertion: await getClientAssertion(request.clientAssertion, this.config.auth.clientId - // tokenEndpoint will be undefined. resourceRequestUri is omitted in ClientCredentialRequest - ), - assertionType: Constants.JWT_BEARER_ASSERTION_TYPE, - }; - } - const baseRequest = await this.initializeBaseRequest(request); - // valid base request should not contain oidc scopes in this grant type - const validBaseRequest = { - ...baseRequest, - scopes: baseRequest.scopes.filter((scope) => !OIDC_DEFAULT_SCOPES.includes(scope)), - }; - const validRequest = { - ...request, - ...validBaseRequest, - clientAssertion, - }; - /* - * valid request should not have "common" or "organizations" in lieu of the tenant_id in the authority in the auth configuration - * example authority: "https://login.microsoftonline.com/TenantId", - */ - const authority = new UrlString(validRequest.authority); - const tenantId = authority.getUrlComponents().PathSegments[0]; - if (Object.values(AADAuthorityConstants).includes(tenantId)) { - throw createClientAuthError(ClientAuthErrorCodes.missingTenantIdError); - } - /* - * if this env variable is set, and the developer provided region isn't defined and isn't "DisableMsalForceRegion", - * MSAL shall opt-in to ESTS-R with the value of this variable - */ - const ENV_MSAL_FORCE_REGION = process.env[MSAL_FORCE_REGION]; - let region; - if (validRequest.azureRegion !== "DisableMsalForceRegion") { - if (!validRequest.azureRegion && ENV_MSAL_FORCE_REGION) { - region = ENV_MSAL_FORCE_REGION; - } - else { - region = validRequest.azureRegion; - } - } - const azureRegionConfiguration = { - azureRegion: region, - environmentRegion: process.env[REGION_ENVIRONMENT_VARIABLE], - }; - const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByClientCredential, validRequest.correlationId, validRequest.skipCache); - try { - const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, azureRegionConfiguration, request.azureCloudOptions); - const clientCredentialConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, "", serverTelemetryManager); - const clientCredentialClient = new ClientCredentialClient(clientCredentialConfig, this.appTokenProvider); - this.logger.verbose("Client credential client created", validRequest.correlationId); - return await clientCredentialClient.acquireToken(validRequest); - } - catch (e) { - if (e instanceof AuthError) { - e.setCorrelationId(validRequest.correlationId); - } - serverTelemetryManager.cacheFailedRequest(e); - throw e; - } - } - /** - * Acquires tokens from the authority for the application. - * - * Used in scenarios where the current app is a middle-tier service which was called with a token - * representing an end user. The current app can use the token (oboAssertion) to request another - * token to access downstream web API, on behalf of that user. - * - * The current middle-tier app has no user interaction to obtain consent. - * See how to gain consent upfront for your middle-tier app from this article. - * https://docs.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-on-behalf-of-flow#gaining-consent-for-the-middle-tier-application - */ - async acquireTokenOnBehalfOf(request) { - this.logger.info("acquireTokenOnBehalfOf called", request.correlationId); - const validRequest = { - ...request, - ...(await this.initializeBaseRequest(request)), - }; - try { - const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request.azureCloudOptions); - const onBehalfOfConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, "", undefined); - const oboClient = new OnBehalfOfClient(onBehalfOfConfig); - this.logger.verbose("On behalf of client created", validRequest.correlationId); - return await oboClient.acquireToken(validRequest); - } - catch (e) { - if (e instanceof AuthError) { - e.setCorrelationId(validRequest.correlationId); - } - throw e; - } - } -} - -export { ConfidentialClientApplication }; -//# sourceMappingURL=ConfidentialClientApplication.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/DeviceCodeClient.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/DeviceCodeClient.mjs deleted file mode 100644 index 5722f8f4..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/client/DeviceCodeClient.mjs +++ /dev/null @@ -1,218 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { BaseClient, TimeUtils, ResponseHandler, UrlString, RequestParameterBuilder, UrlUtils, createClientAuthError, ClientAuthErrorCodes, Constants, createAuthError, AuthErrorCodes, GrantType, StringUtils } from '@azure/msal-common/node'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * OAuth2.0 Device code client - * @public - */ -class DeviceCodeClient extends BaseClient { - constructor(configuration) { - super(configuration); - } - /** - * Gets device code from device code endpoint, calls back to with device code response, and - * polls token endpoint to exchange device code for tokens - * @param request - developer provided CommonDeviceCodeRequest - */ - async acquireToken(request) { - const deviceCodeResponse = await this.getDeviceCode(request); - request.deviceCodeCallback(deviceCodeResponse); - const reqTimestamp = TimeUtils.nowSeconds(); - const response = await this.acquireTokenWithDeviceCode(request, deviceCodeResponse); - const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin); - // Validate response. This function throws a server error if an error is returned by the server. - responseHandler.validateTokenResponse(response); - return responseHandler.handleServerTokenResponse(response, this.authority, reqTimestamp, request); - } - /** - * Creates device code request and executes http GET - * @param request - developer provided CommonDeviceCodeRequest - */ - async getDeviceCode(request) { - const queryParametersString = this.createExtraQueryParameters(request); - const endpoint = UrlString.appendQueryString(this.authority.deviceCodeEndpoint, queryParametersString); - const queryString = this.createQueryString(request); - const headers = this.createTokenRequestHeaders(); - const thumbprint = { - clientId: this.config.authOptions.clientId, - authority: request.authority, - scopes: request.scopes, - claims: request.claims, - authenticationScheme: request.authenticationScheme, - resourceRequestMethod: request.resourceRequestMethod, - resourceRequestUri: request.resourceRequestUri, - shrClaims: request.shrClaims, - sshKid: request.sshKid, - }; - return this.executePostRequestToDeviceCodeEndpoint(endpoint, queryString, headers, thumbprint, request.correlationId); - } - /** - * Creates query string for the device code request - * @param request - developer provided CommonDeviceCodeRequest - */ - createExtraQueryParameters(request) { - const parameters = new Map(); - if (request.extraQueryParameters) { - RequestParameterBuilder.addExtraQueryParameters(parameters, request.extraQueryParameters); - } - return UrlUtils.mapToQueryString(parameters); - } - /** - * Executes POST request to device code endpoint - * @param deviceCodeEndpoint - token endpoint - * @param queryString - string to be used in the body of the request - * @param headers - headers for the request - * @param thumbprint - unique request thumbprint - * @param correlationId - correlation id to be used in the request - */ - async executePostRequestToDeviceCodeEndpoint(deviceCodeEndpoint, queryString, headers, thumbprint, correlationId) { - const { body: { user_code: userCode, device_code: deviceCode, verification_uri: verificationUri, expires_in: expiresIn, interval, message, }, } = await this.sendPostRequest(thumbprint, deviceCodeEndpoint, { - body: queryString, - headers: headers, - }, correlationId); - return { - userCode, - deviceCode, - verificationUri, - expiresIn, - interval, - message, - }; - } - /** - * Create device code endpoint query parameters and returns string - * @param request - developer provided CommonDeviceCodeRequest - */ - createQueryString(request) { - const parameters = new Map(); - RequestParameterBuilder.addScopes(parameters, request.scopes); - RequestParameterBuilder.addClientId(parameters, this.config.authOptions.clientId); - if (request.extraQueryParameters) { - RequestParameterBuilder.addExtraQueryParameters(parameters, request.extraQueryParameters); - } - if (request.claims || - (this.config.authOptions.clientCapabilities && - this.config.authOptions.clientCapabilities.length > 0)) { - RequestParameterBuilder.addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities); - } - return UrlUtils.mapToQueryString(parameters); - } - /** - * Breaks the polling with specific conditions - * @param deviceCodeExpirationTime - expiration time for the device code request - * @param userSpecifiedTimeout - developer provided timeout, to be compared against deviceCodeExpirationTime - * @param userSpecifiedCancelFlag - boolean indicating the developer would like to cancel the request - */ - continuePolling(deviceCodeExpirationTime, userSpecifiedTimeout, userSpecifiedCancelFlag) { - if (userSpecifiedCancelFlag) { - this.logger.error("Token request cancelled by setting DeviceCodeRequest.cancel = true"); - throw createClientAuthError(ClientAuthErrorCodes.deviceCodePollingCancelled); - } - else if (userSpecifiedTimeout && - userSpecifiedTimeout < deviceCodeExpirationTime && - TimeUtils.nowSeconds() > userSpecifiedTimeout) { - this.logger.error(`User defined timeout for device code polling reached. The timeout was set for ${userSpecifiedTimeout}`); - throw createClientAuthError(ClientAuthErrorCodes.userTimeoutReached); - } - else if (TimeUtils.nowSeconds() > deviceCodeExpirationTime) { - if (userSpecifiedTimeout) { - this.logger.verbose(`User specified timeout ignored as the device code has expired before the timeout elapsed. The user specified timeout was set for ${userSpecifiedTimeout}`); - } - this.logger.error(`Device code expired. Expiration time of device code was ${deviceCodeExpirationTime}`); - throw createClientAuthError(ClientAuthErrorCodes.deviceCodeExpired); - } - return true; - } - /** - * Creates token request with device code response and polls token endpoint at interval set by the device code response - * @param request - developer provided CommonDeviceCodeRequest - * @param deviceCodeResponse - DeviceCodeResponse returned by the security token service device code endpoint - */ - async acquireTokenWithDeviceCode(request, deviceCodeResponse) { - const queryParametersString = this.createTokenQueryParameters(request); - const endpoint = UrlString.appendQueryString(this.authority.tokenEndpoint, queryParametersString); - const requestBody = this.createTokenRequestBody(request, deviceCodeResponse); - const headers = this.createTokenRequestHeaders(); - const userSpecifiedTimeout = request.timeout - ? TimeUtils.nowSeconds() + request.timeout - : undefined; - const deviceCodeExpirationTime = TimeUtils.nowSeconds() + deviceCodeResponse.expiresIn; - const pollingIntervalMilli = deviceCodeResponse.interval * 1000; - /* - * Poll token endpoint while (device code is not expired AND operation has not been cancelled by - * setting CancellationToken.cancel = true). POST request is sent at interval set by pollingIntervalMilli - */ - while (this.continuePolling(deviceCodeExpirationTime, userSpecifiedTimeout, request.cancel)) { - const thumbprint = { - clientId: this.config.authOptions.clientId, - authority: request.authority, - scopes: request.scopes, - claims: request.claims, - authenticationScheme: request.authenticationScheme, - resourceRequestMethod: request.resourceRequestMethod, - resourceRequestUri: request.resourceRequestUri, - shrClaims: request.shrClaims, - sshKid: request.sshKid, - }; - const response = await this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint, request.correlationId); - if (response.body && response.body.error) { - // user authorization is pending. Sleep for polling interval and try again - if (response.body.error === Constants.AUTHORIZATION_PENDING) { - this.logger.info("Authorization pending. Continue polling."); - await TimeUtils.delay(pollingIntervalMilli); - } - else { - // for any other error, throw - this.logger.info("Unexpected error in polling from the server"); - throw createAuthError(AuthErrorCodes.postRequestFailed, response.body.error); - } - } - else { - this.logger.verbose("Authorization completed successfully. Polling stopped."); - return response.body; - } - } - /* - * The above code should've thrown by this point, but to satisfy TypeScript, - * and in the rare case the conditionals in continuePolling() may not catch everything... - */ - this.logger.error("Polling stopped for unknown reasons."); - throw createClientAuthError(ClientAuthErrorCodes.deviceCodeUnknownError); - } - /** - * Creates query parameters and converts to string. - * @param request - developer provided CommonDeviceCodeRequest - * @param deviceCodeResponse - DeviceCodeResponse returned by the security token service device code endpoint - */ - createTokenRequestBody(request, deviceCodeResponse) { - const parameters = new Map(); - RequestParameterBuilder.addScopes(parameters, request.scopes); - RequestParameterBuilder.addClientId(parameters, this.config.authOptions.clientId); - RequestParameterBuilder.addGrantType(parameters, GrantType.DEVICE_CODE_GRANT); - RequestParameterBuilder.addDeviceCode(parameters, deviceCodeResponse.deviceCode); - const correlationId = request.correlationId || - this.config.cryptoInterface.createNewGuid(); - RequestParameterBuilder.addCorrelationId(parameters, correlationId); - RequestParameterBuilder.addClientInfo(parameters); - RequestParameterBuilder.addLibraryInfo(parameters, this.config.libraryInfo); - RequestParameterBuilder.addApplicationTelemetry(parameters, this.config.telemetry.application); - RequestParameterBuilder.addThrottling(parameters); - if (this.serverTelemetryManager) { - RequestParameterBuilder.addServerTelemetry(parameters, this.serverTelemetryManager); - } - if (!StringUtils.isEmptyObj(request.claims) || - (this.config.authOptions.clientCapabilities && - this.config.authOptions.clientCapabilities.length > 0)) { - RequestParameterBuilder.addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities); - } - return UrlUtils.mapToQueryString(parameters); - } -} - -export { DeviceCodeClient }; -//# sourceMappingURL=DeviceCodeClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentityApplication.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentityApplication.mjs deleted file mode 100644 index 509701fc..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentityApplication.mjs +++ /dev/null @@ -1,134 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { Logger, DEFAULT_CRYPTO_IMPLEMENTATION, Constants, Authority, ProtocolMode, createClientConfigurationError, ClientConfigurationErrorCodes, EncodingTypes, CacheOutcome } from '@azure/msal-common/node'; -import { buildManagedIdentityConfiguration } from '../config/Configuration.mjs'; -import { name, version } from '../packageMetadata.mjs'; -import { CryptoProvider } from '../crypto/CryptoProvider.mjs'; -import { ClientCredentialClient } from './ClientCredentialClient.mjs'; -import { ManagedIdentityClient } from './ManagedIdentityClient.mjs'; -import { NodeStorage } from '../cache/NodeStorage.mjs'; -import { DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY, ManagedIdentitySourceNames } from '../utils/Constants.mjs'; -import { HashUtils } from '../crypto/HashUtils.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const SOURCES_THAT_SUPPORT_TOKEN_REVOCATION = [ManagedIdentitySourceNames.SERVICE_FABRIC]; -/** - * Class to initialize a managed identity and identify the service - * @public - */ -class ManagedIdentityApplication { - constructor(configuration) { - // undefined config means the managed identity is system-assigned - this.config = buildManagedIdentityConfiguration(configuration || {}); - this.logger = new Logger(this.config.system.loggerOptions, name, version); - const fakeStatusAuthorityOptions = { - canonicalAuthority: Constants.DEFAULT_AUTHORITY, - }; - if (!ManagedIdentityApplication.nodeStorage) { - ManagedIdentityApplication.nodeStorage = new NodeStorage(this.logger, this.config.managedIdentityId.id, DEFAULT_CRYPTO_IMPLEMENTATION, fakeStatusAuthorityOptions); - } - this.networkClient = this.config.system.networkClient; - this.cryptoProvider = new CryptoProvider(); - const fakeAuthorityOptions = { - protocolMode: ProtocolMode.AAD, - knownAuthorities: [DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY], - cloudDiscoveryMetadata: "", - authorityMetadata: "", - }; - this.fakeAuthority = new Authority(DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY, this.networkClient, ManagedIdentityApplication.nodeStorage, fakeAuthorityOptions, this.logger, this.cryptoProvider.createNewGuid(), // correlationID - undefined, true); - this.fakeClientCredentialClient = new ClientCredentialClient({ - authOptions: { - clientId: this.config.managedIdentityId.id, - authority: this.fakeAuthority, - }, - }); - this.managedIdentityClient = new ManagedIdentityClient(this.logger, ManagedIdentityApplication.nodeStorage, this.networkClient, this.cryptoProvider, this.config.disableInternalRetries); - this.hashUtils = new HashUtils(); - } - /** - * Acquire an access token from the cache or the managed identity - * @param managedIdentityRequest - the ManagedIdentityRequestParams object passed in by the developer - * @returns the access token - */ - async acquireToken(managedIdentityRequestParams) { - if (!managedIdentityRequestParams.resource) { - throw createClientConfigurationError(ClientConfigurationErrorCodes.urlEmptyError); - } - const managedIdentityRequest = { - forceRefresh: managedIdentityRequestParams.forceRefresh, - resource: managedIdentityRequestParams.resource.replace("/.default", ""), - scopes: [ - managedIdentityRequestParams.resource.replace("/.default", ""), - ], - authority: this.fakeAuthority.canonicalAuthority, - correlationId: this.cryptoProvider.createNewGuid(), - claims: managedIdentityRequestParams.claims, - clientCapabilities: this.config.clientCapabilities, - }; - if (managedIdentityRequest.forceRefresh) { - return this.acquireTokenFromManagedIdentity(managedIdentityRequest, this.config.managedIdentityId, this.fakeAuthority); - } - const [cachedAuthenticationResult, lastCacheOutcome] = await this.fakeClientCredentialClient.getCachedAuthenticationResult(managedIdentityRequest, this.config, this.cryptoProvider, this.fakeAuthority, ManagedIdentityApplication.nodeStorage); - /* - * Check if claims are present in the managed identity request. - * If so, the cached token will not be used. - */ - if (managedIdentityRequest.claims) { - const sourceName = this.managedIdentityClient.getManagedIdentitySource(); - /* - * Check if there is a cached token and if the Managed Identity source supports token revocation. - * If so, hash the cached access token and add it to the request. - */ - if (cachedAuthenticationResult && - SOURCES_THAT_SUPPORT_TOKEN_REVOCATION.includes(sourceName)) { - const revokedTokenSha256Hash = this.hashUtils - .sha256(cachedAuthenticationResult.accessToken) - .toString(EncodingTypes.HEX); - managedIdentityRequest.revokedTokenSha256Hash = - revokedTokenSha256Hash; - } - return this.acquireTokenFromManagedIdentity(managedIdentityRequest, this.config.managedIdentityId, this.fakeAuthority); - } - if (cachedAuthenticationResult) { - // if the token is not expired but must be refreshed; get a new one in the background - if (lastCacheOutcome === CacheOutcome.PROACTIVELY_REFRESHED) { - this.logger.info("ClientCredentialClient:getCachedAuthenticationResult - Cached access token's refreshOn property has been exceeded'. It's not expired, but must be refreshed."); - // force refresh; will run in the background - const refreshAccessToken = true; - await this.acquireTokenFromManagedIdentity(managedIdentityRequest, this.config.managedIdentityId, this.fakeAuthority, refreshAccessToken); - } - return cachedAuthenticationResult; - } - else { - return this.acquireTokenFromManagedIdentity(managedIdentityRequest, this.config.managedIdentityId, this.fakeAuthority); - } - } - /** - * Acquires a token from a managed identity endpoint. - * - * @param managedIdentityRequest - The request object containing parameters for the managed identity token request. - * @param managedIdentityId - The identifier for the managed identity (e.g., client ID or resource ID). - * @param fakeAuthority - A placeholder authority used for the token request. - * @param refreshAccessToken - Optional flag indicating whether to force a refresh of the access token. - * @returns A promise that resolves to an AuthenticationResult containing the acquired token and related information. - */ - async acquireTokenFromManagedIdentity(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken) { - // make a network call to the managed identity - return this.managedIdentityClient.sendManagedIdentityTokenRequest(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken); - } - /** - * Determine the Managed Identity Source based on available environment variables. This API is consumed by Azure Identity SDK. - * @returns ManagedIdentitySourceNames - The Managed Identity source's name - */ - getManagedIdentitySource() { - return (ManagedIdentityClient.sourceName || - this.managedIdentityClient.getManagedIdentitySource()); - } -} - -export { ManagedIdentityApplication }; -//# sourceMappingURL=ManagedIdentityApplication.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentityClient.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentityClient.mjs deleted file mode 100644 index eecd866d..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentityClient.mjs +++ /dev/null @@ -1,79 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { AppService } from './ManagedIdentitySources/AppService.mjs'; -import { AzureArc } from './ManagedIdentitySources/AzureArc.mjs'; -import { CloudShell } from './ManagedIdentitySources/CloudShell.mjs'; -import { Imds } from './ManagedIdentitySources/Imds.mjs'; -import { ServiceFabric } from './ManagedIdentitySources/ServiceFabric.mjs'; -import { createManagedIdentityError } from '../error/ManagedIdentityError.mjs'; -import { ManagedIdentitySourceNames } from '../utils/Constants.mjs'; -import { MachineLearning } from './ManagedIdentitySources/MachineLearning.mjs'; -import { unableToCreateSource } from '../error/ManagedIdentityErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/* - * Class to initialize a managed identity and identify the service. - * Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/ManagedIdentityClient.cs - */ -class ManagedIdentityClient { - constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) { - this.logger = logger; - this.nodeStorage = nodeStorage; - this.networkClient = networkClient; - this.cryptoProvider = cryptoProvider; - this.disableInternalRetries = disableInternalRetries; - } - async sendManagedIdentityTokenRequest(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken) { - if (!ManagedIdentityClient.identitySource) { - ManagedIdentityClient.identitySource = - this.selectManagedIdentitySource(this.logger, this.nodeStorage, this.networkClient, this.cryptoProvider, this.disableInternalRetries, managedIdentityId); - } - return ManagedIdentityClient.identitySource.acquireTokenWithManagedIdentity(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken); - } - allEnvironmentVariablesAreDefined(environmentVariables) { - return Object.values(environmentVariables).every((environmentVariable) => { - return environmentVariable !== undefined; - }); - } - /** - * Determine the Managed Identity Source based on available environment variables. This API is consumed by ManagedIdentityApplication's getManagedIdentitySource. - * @returns ManagedIdentitySourceNames - The Managed Identity source's name - */ - getManagedIdentitySource() { - ManagedIdentityClient.sourceName = - this.allEnvironmentVariablesAreDefined(ServiceFabric.getEnvironmentVariables()) - ? ManagedIdentitySourceNames.SERVICE_FABRIC - : this.allEnvironmentVariablesAreDefined(AppService.getEnvironmentVariables()) - ? ManagedIdentitySourceNames.APP_SERVICE - : this.allEnvironmentVariablesAreDefined(MachineLearning.getEnvironmentVariables()) - ? ManagedIdentitySourceNames.MACHINE_LEARNING - : this.allEnvironmentVariablesAreDefined(CloudShell.getEnvironmentVariables()) - ? ManagedIdentitySourceNames.CLOUD_SHELL - : this.allEnvironmentVariablesAreDefined(AzureArc.getEnvironmentVariables()) - ? ManagedIdentitySourceNames.AZURE_ARC - : ManagedIdentitySourceNames.DEFAULT_TO_IMDS; - return ManagedIdentityClient.sourceName; - } - /** - * Tries to create a managed identity source for all sources - * @returns the managed identity Source - */ - selectManagedIdentitySource(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) { - const source = ServiceFabric.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) || - AppService.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) || - MachineLearning.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) || - CloudShell.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) || - AzureArc.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) || - Imds.tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries); - if (!source) { - throw createManagedIdentityError(unableToCreateSource); - } - return source; - } -} - -export { ManagedIdentityClient }; -//# sourceMappingURL=ManagedIdentityClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/AppService.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/AppService.mjs deleted file mode 100644 index 0dd165fa..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/AppService.mjs +++ /dev/null @@ -1,109 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { BaseManagedIdentitySource } from './BaseManagedIdentitySource.mjs'; -import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityHeaders, ManagedIdentityQueryParameters, ManagedIdentityIdType, HttpMethod } from '../../utils/Constants.mjs'; -import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -// MSI Constants. Docs for MSI are available here https://docs.microsoft.com/azure/app-service/overview-managed-identity -const APP_SERVICE_MSI_API_VERSION = "2019-08-01"; -/** - * Azure App Service Managed Identity Source implementation. - * - * This class provides managed identity authentication for applications running in Azure App Service. - * It uses the local metadata service endpoint available within App Service environments to obtain - * access tokens without requiring explicit credentials. - * - * Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/AppServiceManagedIdentitySource.cs - */ -class AppService extends BaseManagedIdentitySource { - /** - * Creates a new instance of the AppService managed identity source. - * - * @param logger - Logger instance for diagnostic output - * @param nodeStorage - Node.js storage implementation for caching - * @param networkClient - Network client for making HTTP requests - * @param cryptoProvider - Cryptographic operations provider - * @param disableInternalRetries - Whether to disable internal retry logic - * @param identityEndpoint - The App Service identity endpoint URL - * @param identityHeader - The secret header value required for authentication - */ - constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint, identityHeader) { - super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries); - this.identityEndpoint = identityEndpoint; - this.identityHeader = identityHeader; - } - /** - * Retrieves the required environment variables for App Service managed identity. - * - * App Service managed identity requires two environment variables: - * - IDENTITY_ENDPOINT: The URL of the local metadata service - * - IDENTITY_HEADER: A secret header value for authentication - * - * @returns An array containing [identityEndpoint, identityHeader] values from environment variables. - * Either value may be undefined if the environment variable is not set. - */ - static getEnvironmentVariables() { - const identityEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT]; - const identityHeader = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER]; - return [identityEndpoint, identityHeader]; - } - /** - * Attempts to create an AppService managed identity source if the environment supports it. - * - * This method checks for the presence of required environment variables and validates - * the identity endpoint URL. If the environment is not suitable for App Service managed - * identity (missing environment variables or invalid endpoint), it returns null. - * - * @param logger - Logger instance for diagnostic output - * @param nodeStorage - Node.js storage implementation for caching - * @param networkClient - Network client for making HTTP requests - * @param cryptoProvider - Cryptographic operations provider - * @param disableInternalRetries - Whether to disable internal retry logic - * - * @returns A new AppService instance if the environment is suitable, null otherwise - */ - static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) { - const [identityEndpoint, identityHeader] = AppService.getEnvironmentVariables(); - // if either of the identity endpoint or identity header variables are undefined, this MSI provider is unavailable. - if (!identityEndpoint || !identityHeader) { - logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.APP_SERVICE} managed identity is unavailable because one or both of the '${ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER}' and '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' environment variables are not defined.`); - return null; - } - const validatedIdentityEndpoint = AppService.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT, identityEndpoint, ManagedIdentitySourceNames.APP_SERVICE, logger); - logger.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.APP_SERVICE} managed identity. Endpoint URI: ${validatedIdentityEndpoint}. Creating ${ManagedIdentitySourceNames.APP_SERVICE} managed identity.`); - return new AppService(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint, identityHeader); - } - /** - * Creates a managed identity token request for the App Service environment. - * - * This method constructs an HTTP GET request to the App Service identity endpoint - * with the required headers, query parameters, and managed identity configuration. - * The request includes the secret header for authentication and appropriate API version. - * - * @param resource - The target resource/scope for which to request an access token (e.g., "https://graph.microsoft.com/.default") - * @param managedIdentityId - The managed identity configuration specifying whether to use system-assigned or user-assigned identity - * - * @returns A configured ManagedIdentityRequestParameters object ready for network execution - */ - createRequest(resource, managedIdentityId) { - const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.identityEndpoint); - request.headers[ManagedIdentityHeaders.APP_SERVICE_SECRET_HEADER_NAME] = - this.identityHeader; - request.queryParameters[ManagedIdentityQueryParameters.API_VERSION] = - APP_SERVICE_MSI_API_VERSION; - request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] = - resource; - if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) { - request.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType)] = managedIdentityId.id; - } - // bodyParameters calculated in BaseManagedIdentity.acquireTokenWithManagedIdentity - return request; - } -} - -export { AppService }; -//# sourceMappingURL=AppService.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/AzureArc.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/AzureArc.mjs deleted file mode 100644 index ba1fd627..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/AzureArc.mjs +++ /dev/null @@ -1,248 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { HttpStatus, EncodingTypes, AuthError, createClientAuthError, ClientAuthErrorCodes } from '@azure/msal-common/node'; -import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs'; -import { BaseManagedIdentitySource } from './BaseManagedIdentitySource.mjs'; -import { createManagedIdentityError } from '../../error/ManagedIdentityError.mjs'; -import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityIdType, HttpMethod, ManagedIdentityHeaders, ManagedIdentityQueryParameters, AZURE_ARC_SECRET_FILE_MAX_SIZE_BYTES } from '../../utils/Constants.mjs'; -import { accessSync, constants, statSync, readFileSync } from 'fs'; -import path from 'path'; -import { unableToCreateAzureArc, wwwAuthenticateHeaderMissing, wwwAuthenticateHeaderUnsupportedFormat, platformNotSupported, invalidFileExtension, invalidFilePath, unableToReadSecretFile, invalidSecret } from '../../error/ManagedIdentityErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const ARC_API_VERSION = "2019-11-01"; -const DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT = "http://127.0.0.1:40342/metadata/identity/oauth2/token"; -const HIMDS_EXECUTABLE_HELPER_STRING = "N/A: himds executable exists"; -const SUPPORTED_AZURE_ARC_PLATFORMS = { - win32: `${process.env["ProgramData"]}\\AzureConnectedMachineAgent\\Tokens\\`, - linux: "/var/opt/azcmagent/tokens/", -}; -const AZURE_ARC_FILE_DETECTION = { - win32: `${process.env["ProgramFiles"]}\\AzureConnectedMachineAgent\\himds.exe`, - linux: "/opt/azcmagent/bin/himds", -}; -/** - * Azure Arc managed identity source implementation for acquiring tokens from Azure Arc-enabled servers. - * - * This class provides managed identity authentication for applications running on Azure Arc-enabled servers - * by communicating with the local Hybrid Instance Metadata Service (HIMDS). It supports both environment - * variable-based configuration and automatic detection through the HIMDS executable. - * - * Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/AzureArcManagedIdentitySource.cs - */ -class AzureArc extends BaseManagedIdentitySource { - /** - * Creates a new instance of the AzureArc managed identity source. - * - * @param logger - Logger instance for capturing telemetry and diagnostic information - * @param nodeStorage - Storage implementation for caching tokens and metadata - * @param networkClient - Network client for making HTTP requests to the identity endpoint - * @param cryptoProvider - Cryptographic operations provider for token validation and encryption - * @param disableInternalRetries - Flag to disable automatic retry logic for failed requests - * @param identityEndpoint - The Azure Arc identity endpoint URL for token requests - */ - constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint) { - super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries); - this.identityEndpoint = identityEndpoint; - } - /** - * Retrieves and validates Azure Arc environment variables for managed identity configuration. - * - * This method checks for IDENTITY_ENDPOINT and IMDS_ENDPOINT environment variables. - * If either is missing, it attempts to detect the Azure Arc environment by checking for - * the HIMDS executable at platform-specific paths. On successful detection, it returns - * the default identity endpoint and a helper string indicating file-based detection. - * - * @returns An array containing [identityEndpoint, imdsEndpoint] where both values are - * strings if Azure Arc is available, or undefined if not available. - */ - static getEnvironmentVariables() { - let identityEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT]; - let imdsEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT]; - // if either of the identity or imds endpoints are undefined, check if the himds executable exists - if (!identityEndpoint || !imdsEndpoint) { - // get the expected Windows or Linux file path of the himds executable - const fileDetectionPath = AZURE_ARC_FILE_DETECTION[process.platform]; - try { - /* - * check if the himds executable exists and its permissions allow it to be read - * returns undefined if true, throws an error otherwise - */ - accessSync(fileDetectionPath, constants.F_OK | constants.R_OK); - identityEndpoint = DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT; - imdsEndpoint = HIMDS_EXECUTABLE_HELPER_STRING; - } - catch (err) { - /* - * do nothing - * accessSync returns undefined on success, and throws an error on failure - */ - } - } - return [identityEndpoint, imdsEndpoint]; - } - /** - * Attempts to create an AzureArc managed identity source instance. - * - * Validates the Azure Arc environment by checking environment variables - * and performing file-based detection. It ensures that only system-assigned managed identities - * are supported for Azure Arc scenarios. The method performs comprehensive validation of - * endpoint URLs and logs detailed information about the detection process. - * - * @param logger - Logger instance for capturing creation and validation steps - * @param nodeStorage - Storage implementation for the managed identity source - * @param networkClient - Network client for HTTP communication - * @param cryptoProvider - Cryptographic operations provider - * @param disableInternalRetries - Whether to disable automatic retry mechanisms - * @param managedIdentityId - The managed identity configuration, must be system-assigned - * - * @returns AzureArc instance if the environment supports Azure Arc managed identity, null otherwise - * - * @throws {ManagedIdentityError} When a user-assigned managed identity is specified (not supported for Azure Arc) - */ - static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) { - const [identityEndpoint, imdsEndpoint] = AzureArc.getEnvironmentVariables(); - // if either of the identity or imds endpoints are undefined (even after himds file detection) - if (!identityEndpoint || !imdsEndpoint) { - logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.AZURE_ARC} managed identity is unavailable through environment variables because one or both of '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' and '${ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT}' are not defined. ${ManagedIdentitySourceNames.AZURE_ARC} managed identity is also unavailable through file detection.`); - return null; - } - // check if the imds endpoint is set to the default for file detection - if (imdsEndpoint === HIMDS_EXECUTABLE_HELPER_STRING) { - logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.AZURE_ARC} managed identity is available through file detection. Defaulting to known ${ManagedIdentitySourceNames.AZURE_ARC} endpoint: ${DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT}. Creating ${ManagedIdentitySourceNames.AZURE_ARC} managed identity.`); - } - else { - // otherwise, both the identity and imds endpoints are defined without file detection; validate them - const validatedIdentityEndpoint = AzureArc.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT, identityEndpoint, ManagedIdentitySourceNames.AZURE_ARC, logger); - // remove trailing slash - validatedIdentityEndpoint.endsWith("/") - ? validatedIdentityEndpoint.slice(0, -1) - : validatedIdentityEndpoint; - AzureArc.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT, imdsEndpoint, ManagedIdentitySourceNames.AZURE_ARC, logger); - logger.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.AZURE_ARC} managed identity. Endpoint URI: ${validatedIdentityEndpoint}. Creating ${ManagedIdentitySourceNames.AZURE_ARC} managed identity.`); - } - if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) { - throw createManagedIdentityError(unableToCreateAzureArc); - } - return new AzureArc(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint); - } - /** - * Creates a properly formatted HTTP request for acquiring tokens from the Azure Arc identity endpoint. - * - * This method constructs a GET request to the Azure Arc HIMDS endpoint with the required metadata header - * and query parameters. The endpoint URL is normalized to use 127.0.0.1 instead of localhost for - * consistency. Additional body parameters are calculated by the base class during token acquisition. - * - * @param resource - The target resource/scope for which to request an access token (e.g., "https://graph.microsoft.com/.default") - * - * @returns A configured ManagedIdentityRequestParameters object ready for network execution - */ - createRequest(resource) { - const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.identityEndpoint.replace("localhost", "127.0.0.1")); - request.headers[ManagedIdentityHeaders.METADATA_HEADER_NAME] = "true"; - request.queryParameters[ManagedIdentityQueryParameters.API_VERSION] = - ARC_API_VERSION; - request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] = - resource; - // bodyParameters calculated in BaseManagedIdentity.acquireTokenWithManagedIdentity - return request; - } - /** - * Processes the server response and handles Azure Arc-specific authentication challenges. - * - * This method implements the Azure Arc authentication flow which may require reading a secret file - * for authorization. When the initial request returns HTTP 401 Unauthorized, it extracts the file - * path from the WWW-Authenticate header, validates the file location and size, reads the secret, - * and retries the request with Basic authentication. The method includes comprehensive security - * validations to prevent path traversal and ensure file integrity. - * - * @param originalResponse - The initial HTTP response from the identity endpoint - * @param networkClient - Network client for making the retry request if needed - * @param networkRequest - The original request parameters (modified with auth header for retry) - * @param networkRequestOptions - Additional options for network requests - * - * @returns A promise that resolves to the server token response with access token and metadata - * - * @throws {ManagedIdentityError} When: - * - WWW-Authenticate header is missing or has unsupported format - * - Platform is not supported (not Windows or Linux) - * - Secret file has invalid extension (not .key) - * - Secret file path doesn't match expected platform path - * - Secret file cannot be read or is too large (>4096 bytes) - * @throws {ClientAuthError} When network errors occur during retry request - */ - async getServerTokenResponseAsync(originalResponse, networkClient, networkRequest, networkRequestOptions) { - let retryResponse; - if (originalResponse.status === HttpStatus.UNAUTHORIZED) { - const wwwAuthHeader = originalResponse.headers["www-authenticate"]; - if (!wwwAuthHeader) { - throw createManagedIdentityError(wwwAuthenticateHeaderMissing); - } - if (!wwwAuthHeader.includes("Basic realm=")) { - throw createManagedIdentityError(wwwAuthenticateHeaderUnsupportedFormat); - } - const secretFilePath = wwwAuthHeader.split("Basic realm=")[1]; - // throw an error if the managed identity application is not being run on Windows or Linux - if (!SUPPORTED_AZURE_ARC_PLATFORMS.hasOwnProperty(process.platform)) { - throw createManagedIdentityError(platformNotSupported); - } - // get the expected Windows or Linux file path - const expectedSecretFilePath = SUPPORTED_AZURE_ARC_PLATFORMS[process.platform]; - // throw an error if the file in the file path is not a .key file - const fileName = path.basename(secretFilePath); - if (!fileName.endsWith(".key")) { - throw createManagedIdentityError(invalidFileExtension); - } - /* - * throw an error if the file path from the www-authenticate header does not match the - * expected file path for the platform (Windows or Linux) the managed identity application - * is running on - */ - if (expectedSecretFilePath + fileName !== secretFilePath) { - throw createManagedIdentityError(invalidFilePath); - } - let secretFileSize; - // attempt to get the secret file's size, in bytes - try { - secretFileSize = await statSync(secretFilePath).size; - } - catch (e) { - throw createManagedIdentityError(unableToReadSecretFile); - } - // throw an error if the secret file's size is greater than 4096 bytes - if (secretFileSize > AZURE_ARC_SECRET_FILE_MAX_SIZE_BYTES) { - throw createManagedIdentityError(invalidSecret); - } - // attempt to read the contents of the secret file - let secret; - try { - secret = readFileSync(secretFilePath, EncodingTypes.UTF8); - } - catch (e) { - throw createManagedIdentityError(unableToReadSecretFile); - } - const authHeaderValue = `Basic ${secret}`; - this.logger.info(`[Managed Identity] Adding authorization header to the request.`); - networkRequest.headers[ManagedIdentityHeaders.AUTHORIZATION_HEADER_NAME] = authHeaderValue; - try { - retryResponse = - await networkClient.sendGetRequestAsync(networkRequest.computeUri(), networkRequestOptions); - } - catch (error) { - if (error instanceof AuthError) { - throw error; - } - else { - throw createClientAuthError(ClientAuthErrorCodes.networkError); - } - } - } - return this.getServerTokenResponse(retryResponse || originalResponse); - } -} - -export { ARC_API_VERSION, AZURE_ARC_FILE_DETECTION, AzureArc, DEFAULT_AZURE_ARC_IDENTITY_ENDPOINT, SUPPORTED_AZURE_ARC_PLATFORMS }; -//# sourceMappingURL=AzureArc.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/BaseManagedIdentitySource.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/BaseManagedIdentitySource.mjs deleted file mode 100644 index 8fcd2e96..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/BaseManagedIdentitySource.mjs +++ /dev/null @@ -1,244 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { TimeUtils, Constants, HeaderNames, AuthError, createClientAuthError, ClientAuthErrorCodes, ResponseHandler, UrlString } from '@azure/msal-common/node'; -import { ManagedIdentityQueryParameters, HttpMethod, ManagedIdentityIdType } from '../../utils/Constants.mjs'; -import { createManagedIdentityError } from '../../error/ManagedIdentityError.mjs'; -import { isIso8601 } from '../../utils/TimeUtils.mjs'; -import { HttpClientWithRetries } from '../../network/HttpClientWithRetries.mjs'; -import { invalidManagedIdentityIdType, MsiEnvironmentVariableUrlMalformedErrorCodes } from '../../error/ManagedIdentityErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Managed Identity User Assigned Id Query Parameter Names - */ -const ManagedIdentityUserAssignedIdQueryParameterNames = { - MANAGED_IDENTITY_CLIENT_ID_2017: "clientid", - MANAGED_IDENTITY_CLIENT_ID: "client_id", - MANAGED_IDENTITY_OBJECT_ID: "object_id", - MANAGED_IDENTITY_RESOURCE_ID_IMDS: "msi_res_id", - MANAGED_IDENTITY_RESOURCE_ID_NON_IMDS: "mi_res_id", -}; -/** - * Base class for all Managed Identity sources. Provides common functionality for - * authenticating with Azure Managed Identity endpoints across different Azure services - * including IMDS, App Service, Azure Arc, Service Fabric, Cloud Shell, and Machine Learning. - * - * This abstract class handles token acquisition, response processing, and network communication - * while allowing concrete implementations to define source-specific request creation logic. - */ -class BaseManagedIdentitySource { - /** - * Creates an instance of BaseManagedIdentitySource. - * - * @param logger - Logger instance for diagnostic information - * @param nodeStorage - Storage interface for caching tokens - * @param networkClient - Network client for making HTTP requests - * @param cryptoProvider - Cryptographic provider for token operations - * @param disableInternalRetries - Whether to disable automatic retry logic - */ - constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) { - this.logger = logger; - this.nodeStorage = nodeStorage; - this.networkClient = networkClient; - this.cryptoProvider = cryptoProvider; - this.disableInternalRetries = disableInternalRetries; - } - /** - * Processes the network response and converts it to a standardized server token response. - * This async version allows for source-specific response processing logic while maintaining - * backward compatibility with the synchronous version. - * - * @param response - The network response containing the managed identity token - * @param _networkClient - Network client used for the request (unused in base implementation) - * @param _networkRequest - The original network request parameters (unused in base implementation) - * @param _networkRequestOptions - The network request options (unused in base implementation) - * - * @returns Promise resolving to a standardized server authorization token response - */ - async getServerTokenResponseAsync(response, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _networkClient, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _networkRequest, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - _networkRequestOptions) { - return this.getServerTokenResponse(response); - } - /** - * Converts a managed identity token response to a standardized server authorization token response. - * Handles time format conversion, expiration calculation, and error mapping to ensure - * compatibility with the MSAL response handling pipeline. - * - * @param response - The network response containing the managed identity token - * - * @returns Standardized server authorization token response with normalized fields - */ - getServerTokenResponse(response) { - let refreshIn, expiresIn; - if (response.body.expires_on) { - // if the expires_on field in the response body is a string and in ISO 8601 format, convert it to a Unix timestamp (seconds since epoch) - if (isIso8601(response.body.expires_on)) { - response.body.expires_on = - new Date(response.body.expires_on).getTime() / 1000; - } - expiresIn = response.body.expires_on - TimeUtils.nowSeconds(); - // compute refresh_in as 1/2 of expires_in, but only if expires_in > 2h - if (expiresIn > 2 * 3600) { - refreshIn = expiresIn / 2; - } - } - const serverTokenResponse = { - status: response.status, - // success - access_token: response.body.access_token, - expires_in: expiresIn, - scope: response.body.resource, - token_type: response.body.token_type, - refresh_in: refreshIn, - // error - correlation_id: response.body.correlation_id || response.body.correlationId, - error: typeof response.body.error === "string" - ? response.body.error - : response.body.error?.code, - error_description: response.body.message || - (typeof response.body.error === "string" - ? response.body.error_description - : response.body.error?.message), - error_codes: response.body.error_codes, - timestamp: response.body.timestamp, - trace_id: response.body.trace_id, - }; - return serverTokenResponse; - } - /** - * Acquires an access token using the managed identity endpoint for the specified resource. - * This is the primary method for token acquisition, handling the complete flow from - * request creation through response processing and token caching. - * - * @param managedIdentityRequest - The managed identity request containing resource and optional parameters - * @param managedIdentityId - The managed identity configuration (system or user-assigned) - * @param fakeAuthority - Authority instance used for token caching (managed identity uses a placeholder authority) - * @param refreshAccessToken - Whether this is a token refresh operation - * - * @returns Promise resolving to an authentication result containing the access token and metadata - * - * @throws {AuthError} When network requests fail or token validation fails - * @throws {ClientAuthError} When network errors occur during the request - */ - async acquireTokenWithManagedIdentity(managedIdentityRequest, managedIdentityId, fakeAuthority, refreshAccessToken) { - const networkRequest = this.createRequest(managedIdentityRequest.resource, managedIdentityId); - if (managedIdentityRequest.revokedTokenSha256Hash) { - this.logger.info(`[Managed Identity] The following claims are present in the request: ${managedIdentityRequest.claims}`); - networkRequest.queryParameters[ManagedIdentityQueryParameters.SHA256_TOKEN_TO_REFRESH] = managedIdentityRequest.revokedTokenSha256Hash; - } - if (managedIdentityRequest.clientCapabilities?.length) { - const clientCapabilities = managedIdentityRequest.clientCapabilities.toString(); - this.logger.info(`[Managed Identity] The following client capabilities are present in the request: ${clientCapabilities}`); - networkRequest.queryParameters[ManagedIdentityQueryParameters.XMS_CC] = clientCapabilities; - } - const headers = networkRequest.headers; - headers[HeaderNames.CONTENT_TYPE] = Constants.URL_FORM_CONTENT_TYPE; - const networkRequestOptions = { headers }; - if (Object.keys(networkRequest.bodyParameters).length) { - networkRequestOptions.body = - networkRequest.computeParametersBodyString(); - } - /** - * Initializes the network client helper based on the retry policy configuration. - * If internal retries are disabled, it uses the provided network client directly. - * Otherwise, it wraps the network client with an HTTP client that supports retries. - */ - const networkClientHelper = this.disableInternalRetries - ? this.networkClient - : new HttpClientWithRetries(this.networkClient, networkRequest.retryPolicy, this.logger); - const reqTimestamp = TimeUtils.nowSeconds(); - let response; - try { - // Sources that send POST requests: Cloud Shell - if (networkRequest.httpMethod === HttpMethod.POST) { - response = - await networkClientHelper.sendPostRequestAsync(networkRequest.computeUri(), networkRequestOptions); - // Sources that send GET requests: App Service, Azure Arc, IMDS, Service Fabric - } - else { - response = - await networkClientHelper.sendGetRequestAsync(networkRequest.computeUri(), networkRequestOptions); - } - } - catch (error) { - if (error instanceof AuthError) { - throw error; - } - else { - throw createClientAuthError(ClientAuthErrorCodes.networkError); - } - } - const responseHandler = new ResponseHandler(managedIdentityId.id, this.nodeStorage, this.cryptoProvider, this.logger, null, null); - const serverTokenResponse = await this.getServerTokenResponseAsync(response, networkClientHelper, networkRequest, networkRequestOptions); - responseHandler.validateTokenResponse(serverTokenResponse, refreshAccessToken); - // caches the token - return responseHandler.handleServerTokenResponse(serverTokenResponse, fakeAuthority, reqTimestamp, managedIdentityRequest); - } - /** - * Determines the appropriate query parameter name for user-assigned managed identity - * based on the identity type, API version, and endpoint characteristics. - * Different Azure services and API versions use different parameter names for the same identity types. - * - * @param managedIdentityIdType - The type of user-assigned managed identity (client ID, object ID, or resource ID) - * @param isImds - Whether the request is being made to the IMDS (Instance Metadata Service) endpoint - * @param usesApi2017 - Whether the endpoint uses the 2017-09-01 API version (affects client ID parameter name) - * - * @returns The correct query parameter name for the specified identity type and endpoint - * - * @throws {ManagedIdentityError} When an invalid managed identity ID type is provided - */ - getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityIdType, isImds, usesApi2017) { - switch (managedIdentityIdType) { - case ManagedIdentityIdType.USER_ASSIGNED_CLIENT_ID: - this.logger.info(`[Managed Identity] [API version ${usesApi2017 ? "2017+" : "2019+"}] Adding user assigned client id to the request.`); - // The Machine Learning source uses the 2017-09-01 API version, which uses "clientid" instead of "client_id" - return usesApi2017 - ? ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_CLIENT_ID_2017 - : ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_CLIENT_ID; - case ManagedIdentityIdType.USER_ASSIGNED_RESOURCE_ID: - this.logger.info("[Managed Identity] Adding user assigned resource id to the request."); - return isImds - ? ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_RESOURCE_ID_IMDS - : ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_RESOURCE_ID_NON_IMDS; - case ManagedIdentityIdType.USER_ASSIGNED_OBJECT_ID: - this.logger.info("[Managed Identity] Adding user assigned object id to the request."); - return ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_OBJECT_ID; - default: - throw createManagedIdentityError(invalidManagedIdentityIdType); - } - } -} -/** - * Validates and normalizes an environment variable containing a URL string. - * This static utility method ensures that environment variables used for managed identity - * endpoints contain properly formatted URLs and provides informative error messages when validation fails. - * - * @param envVariableStringName - The name of the environment variable being validated (for error reporting) - * @param envVariable - The environment variable value containing the URL string - * @param sourceName - The name of the managed identity source (for error reporting) - * @param logger - Logger instance for diagnostic information - * - * @returns The validated and normalized URL string - * - * @throws {ManagedIdentityError} When the environment variable contains a malformed URL - */ -BaseManagedIdentitySource.getValidatedEnvVariableUrlString = (envVariableStringName, envVariable, sourceName, logger) => { - try { - return new UrlString(envVariable).urlString; - } - catch (error) { - logger.info(`[Managed Identity] ${sourceName} managed identity is unavailable because the '${envVariableStringName}' environment variable is malformed.`); - throw createManagedIdentityError(MsiEnvironmentVariableUrlMalformedErrorCodes[envVariableStringName]); - } -}; - -export { BaseManagedIdentitySource, ManagedIdentityUserAssignedIdQueryParameterNames }; -//# sourceMappingURL=BaseManagedIdentitySource.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/CloudShell.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/CloudShell.mjs deleted file mode 100644 index 8489cb1a..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/CloudShell.mjs +++ /dev/null @@ -1,103 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs'; -import { BaseManagedIdentitySource } from './BaseManagedIdentitySource.mjs'; -import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityIdType, ManagedIdentityHeaders, ManagedIdentityQueryParameters, HttpMethod } from '../../utils/Constants.mjs'; -import { createManagedIdentityError } from '../../error/ManagedIdentityError.mjs'; -import { unableToCreateCloudShell } from '../../error/ManagedIdentityErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Azure Cloud Shell managed identity source implementation. - * - * This class handles authentication for applications running in Azure Cloud Shell environment. - * Cloud Shell provides a browser-accessible shell for managing Azure resources and includes - * a pre-configured managed identity for authentication. - * - * Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/CloudShellManagedIdentitySource.cs - */ -class CloudShell extends BaseManagedIdentitySource { - /** - * Creates a new CloudShell managed identity source instance. - * - * @param logger - Logger instance for diagnostic logging - * @param nodeStorage - Node.js storage implementation for caching - * @param networkClient - HTTP client for making requests to the managed identity endpoint - * @param cryptoProvider - Cryptographic operations provider - * @param disableInternalRetries - Whether to disable automatic retry logic for failed requests - * @param msiEndpoint - The MSI endpoint URL obtained from environment variables - */ - constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, msiEndpoint) { - super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries); - this.msiEndpoint = msiEndpoint; - } - /** - * Retrieves the required environment variables for Cloud Shell managed identity. - * - * Cloud Shell requires the MSI_ENDPOINT environment variable to be set, which - * contains the URL of the managed identity service endpoint. - * - * @returns An array containing the MSI_ENDPOINT environment variable value (or undefined if not set) - */ - static getEnvironmentVariables() { - const msiEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT]; - return [msiEndpoint]; - } - /** - * Attempts to create a CloudShell managed identity source instance. - * - * This method validates that the required environment variables are present and - * creates a CloudShell instance if the environment is properly configured. - * Cloud Shell only supports system-assigned managed identities. - * - * @param logger - Logger instance for diagnostic logging - * @param nodeStorage - Node.js storage implementation for caching - * @param networkClient - HTTP client for making requests - * @param cryptoProvider - Cryptographic operations provider - * @param disableInternalRetries - Whether to disable automatic retry logic - * @param managedIdentityId - The managed identity configuration (must be system-assigned) - * - * @returns A CloudShell instance if the environment is valid, null otherwise - * - * @throws {ManagedIdentityError} When a user-assigned managed identity is requested, - * as Cloud Shell only supports system-assigned identities - */ - static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) { - const [msiEndpoint] = CloudShell.getEnvironmentVariables(); - // if the msi endpoint environment variable is undefined, this MSI provider is unavailable. - if (!msiEndpoint) { - logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.CLOUD_SHELL} managed identity is unavailable because the '${ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT} environment variable is not defined.`); - return null; - } - const validatedMsiEndpoint = CloudShell.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT, msiEndpoint, ManagedIdentitySourceNames.CLOUD_SHELL, logger); - logger.info(`[Managed Identity] Environment variable validation passed for ${ManagedIdentitySourceNames.CLOUD_SHELL} managed identity. Endpoint URI: ${validatedMsiEndpoint}. Creating ${ManagedIdentitySourceNames.CLOUD_SHELL} managed identity.`); - if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) { - throw createManagedIdentityError(unableToCreateCloudShell); - } - return new CloudShell(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, msiEndpoint); - } - /** - * Creates an HTTP request to acquire an access token from the Cloud Shell managed identity endpoint. - * - * This method constructs a POST request to the MSI endpoint with the required headers and - * body parameters for Cloud Shell authentication. The request includes the target resource - * for which the access token is being requested. - * - * @param resource - The target resource/scope for which to request an access token (e.g., "https://graph.microsoft.com/.default") - * - * @returns A configured ManagedIdentityRequestParameters object ready for network execution - */ - createRequest(resource) { - const request = new ManagedIdentityRequestParameters(HttpMethod.POST, this.msiEndpoint); - request.headers[ManagedIdentityHeaders.METADATA_HEADER_NAME] = "true"; - request.bodyParameters[ManagedIdentityQueryParameters.RESOURCE] = - resource; - return request; - } -} - -export { CloudShell }; -//# sourceMappingURL=CloudShell.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/Imds.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/Imds.mjs deleted file mode 100644 index 002c4764..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/Imds.mjs +++ /dev/null @@ -1,108 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs'; -import { BaseManagedIdentitySource } from './BaseManagedIdentitySource.mjs'; -import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityHeaders, ManagedIdentityQueryParameters, ManagedIdentityIdType, HttpMethod } from '../../utils/Constants.mjs'; -import { ImdsRetryPolicy } from '../../retry/ImdsRetryPolicy.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -// Documentation for IMDS is available at https://docs.microsoft.com/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token#get-a-token-using-http -const IMDS_TOKEN_PATH = "/metadata/identity/oauth2/token"; -const DEFAULT_IMDS_ENDPOINT = `http://169.254.169.254${IMDS_TOKEN_PATH}`; -const IMDS_API_VERSION = "2018-02-01"; -/** - * Managed Identity source implementation for Azure Instance Metadata Service (IMDS). - * - * IMDS is available on Azure Virtual Machines and Virtual Machine Scale Sets and provides - * a REST endpoint to obtain OAuth tokens for managed identities. This implementation - * handles both system-assigned and user-assigned managed identities. - * - * Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/ImdsManagedIdentitySource.cs - */ -class Imds extends BaseManagedIdentitySource { - /** - * Constructs an Imds instance with the specified configuration. - * - * @param logger - Logger instance for recording debug information and errors - * @param nodeStorage - NodeStorage instance used for token caching operations - * @param networkClient - Network client implementation for making HTTP requests to IMDS - * @param cryptoProvider - CryptoProvider for generating correlation IDs and other cryptographic operations - * @param disableInternalRetries - When true, disables the built-in retry logic for IMDS requests - * @param identityEndpoint - The complete IMDS endpoint URL including the token path - */ - constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint) { - super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries); - this.identityEndpoint = identityEndpoint; - } - /** - * Creates an Imds instance with the appropriate endpoint configuration. - * - * This method checks for the presence of the AZURE_POD_IDENTITY_AUTHORITY_HOST environment - * variable, which is used in Azure Kubernetes Service (AKS) environments with Azure AD - * Pod Identity. If found, it uses that endpoint; otherwise, it falls back to the standard - * IMDS endpoint (169.254.169.254). - * - * @param logger - Logger instance for recording endpoint discovery and validation - * @param nodeStorage - NodeStorage instance for token caching - * @param networkClient - Network client for HTTP requests - * @param cryptoProvider - CryptoProvider for cryptographic operations - * @param disableInternalRetries - Whether to disable built-in retry logic - * - * @returns A configured Imds instance ready to make token requests - */ - static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) { - let validatedIdentityEndpoint; - if (process.env[ManagedIdentityEnvironmentVariableNames - .AZURE_POD_IDENTITY_AUTHORITY_HOST]) { - logger.info(`[Managed Identity] Environment variable ${ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST} for ${ManagedIdentitySourceNames.IMDS} returned endpoint: ${process.env[ManagedIdentityEnvironmentVariableNames - .AZURE_POD_IDENTITY_AUTHORITY_HOST]}`); - validatedIdentityEndpoint = Imds.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST, `${process.env[ManagedIdentityEnvironmentVariableNames - .AZURE_POD_IDENTITY_AUTHORITY_HOST]}${IMDS_TOKEN_PATH}`, ManagedIdentitySourceNames.IMDS, logger); - } - else { - logger.info(`[Managed Identity] Unable to find ${ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST} environment variable for ${ManagedIdentitySourceNames.IMDS}, using the default endpoint.`); - validatedIdentityEndpoint = DEFAULT_IMDS_ENDPOINT; - } - return new Imds(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, validatedIdentityEndpoint); - } - /** - * Creates a properly configured HTTP request for acquiring an access token from IMDS. - * - * This method builds a complete request object with all necessary headers, query parameters, - * and retry policies required by the Azure Instance Metadata Service. - * - * Key request components: - * - HTTP GET method to the IMDS token endpoint - * - Metadata header set to "true" (required by IMDS) - * - API version parameter (currently "2018-02-01") - * - Resource parameter specifying the target audience - * - Identity-specific parameters for user-assigned managed identities - * - IMDS-specific retry policy - * - * @param resource - The target resource/scope for which to request an access token (e.g., "https://graph.microsoft.com/.default") - * @param managedIdentityId - The managed identity configuration specifying whether to use system-assigned or user-assigned identity - * - * @returns A configured ManagedIdentityRequestParameters object ready for network execution - */ - createRequest(resource, managedIdentityId) { - const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.identityEndpoint); - request.headers[ManagedIdentityHeaders.METADATA_HEADER_NAME] = "true"; - request.queryParameters[ManagedIdentityQueryParameters.API_VERSION] = - IMDS_API_VERSION; - request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] = - resource; - if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) { - request.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType, true // indicates source is IMDS - )] = managedIdentityId.id; - } - // The bodyParameters are calculated in BaseManagedIdentity.acquireTokenWithManagedIdentity. - request.retryPolicy = new ImdsRetryPolicy(); - return request; - } -} - -export { Imds }; -//# sourceMappingURL=Imds.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/MachineLearning.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/MachineLearning.mjs deleted file mode 100644 index e1312511..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/MachineLearning.mjs +++ /dev/null @@ -1,128 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { BaseManagedIdentitySource, ManagedIdentityUserAssignedIdQueryParameterNames } from './BaseManagedIdentitySource.mjs'; -import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityHeaders, ManagedIdentityQueryParameters, ManagedIdentityIdType, HttpMethod } from '../../utils/Constants.mjs'; -import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const MACHINE_LEARNING_MSI_API_VERSION = "2017-09-01"; -const MANAGED_IDENTITY_MACHINE_LEARNING_UNSUPPORTED_ID_TYPE_ERROR = `Only client id is supported for user-assigned managed identity in ${ManagedIdentitySourceNames.MACHINE_LEARNING}.`; // referenced in unit test -/** - * Machine Learning Managed Identity Source implementation for Azure Machine Learning environments. - * - * This class handles managed identity authentication specifically for Azure Machine Learning services. - * It supports both system-assigned and user-assigned managed identities, using the MSI_ENDPOINT - * and MSI_SECRET environment variables that are automatically provided in Azure ML environments. - */ -class MachineLearning extends BaseManagedIdentitySource { - /** - * Creates a new MachineLearning managed identity source instance. - * - * @param logger - Logger instance for diagnostic information - * @param nodeStorage - Node storage implementation for caching - * @param networkClient - Network client for making HTTP requests - * @param cryptoProvider - Cryptographic operations provider - * @param disableInternalRetries - Whether to disable automatic request retries - * @param msiEndpoint - The MSI endpoint URL from environment variables - * @param secret - The MSI secret from environment variables - */ - constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, msiEndpoint, secret) { - super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries); - this.msiEndpoint = msiEndpoint; - this.secret = secret; - } - /** - * Retrieves the required environment variables for Azure Machine Learning managed identity. - * - * This method checks for the presence of MSI_ENDPOINT and MSI_SECRET environment variables - * that are automatically set by the Azure Machine Learning platform when managed identity - * is enabled for the compute instance or cluster. - * - * @returns An array containing [msiEndpoint, secret] where either value may be undefined - * if the corresponding environment variable is not set - */ - static getEnvironmentVariables() { - const msiEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT]; - const secret = process.env[ManagedIdentityEnvironmentVariableNames.MSI_SECRET]; - return [msiEndpoint, secret]; - } - /** - * Attempts to create a MachineLearning managed identity source. - * - * This method validates the Azure Machine Learning environment by checking for the required - * MSI_ENDPOINT and MSI_SECRET environment variables. If both are present and valid, - * it creates and returns a MachineLearning instance. If either is missing or invalid, - * it returns null, indicating that this managed identity source is not available - * in the current environment. - * - * @param logger - Logger instance for diagnostic information - * @param nodeStorage - Node storage implementation for caching - * @param networkClient - Network client for making HTTP requests - * @param cryptoProvider - Cryptographic operations provider - * @param disableInternalRetries - Whether to disable automatic request retries - * - * @returns A new MachineLearning instance if the environment is valid, null otherwise - */ - static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries) { - const [msiEndpoint, secret] = MachineLearning.getEnvironmentVariables(); - // if either of the MSI endpoint or MSI secret variables are undefined, this MSI provider is unavailable. - if (!msiEndpoint || !secret) { - logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.MACHINE_LEARNING} managed identity is unavailable because one or both of the '${ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT}' and '${ManagedIdentityEnvironmentVariableNames.MSI_SECRET}' environment variables are not defined.`); - return null; - } - const validatedMsiEndpoint = MachineLearning.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT, msiEndpoint, ManagedIdentitySourceNames.MACHINE_LEARNING, logger); - logger.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.MACHINE_LEARNING} managed identity. Endpoint URI: ${validatedMsiEndpoint}. Creating ${ManagedIdentitySourceNames.MACHINE_LEARNING} managed identity.`); - return new MachineLearning(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, msiEndpoint, secret); - } - /** - * Creates a managed identity token request for Azure Machine Learning environments. - * - * This method constructs the HTTP request parameters needed to acquire an access token - * from the Azure Machine Learning managed identity endpoint. It handles both system-assigned - * and user-assigned managed identities with specific logic for each type: - * - * - System-assigned: Uses the DEFAULT_IDENTITY_CLIENT_ID environment variable - * - User-assigned: Only supports client ID-based identification (not object ID or resource ID) - * - * The request uses the 2017-09-01 API version and includes the required secret header - * for authentication with the MSI endpoint. - * - * @param resource - The target resource/scope for which to request an access token (e.g., "https://graph.microsoft.com/.default") - * @param managedIdentityId - The managed identity configuration specifying whether to use system-assigned or user-assigned identity - * - * @returns A configured ManagedIdentityRequestParameters object ready for network execution - * - * @throws Error if an unsupported managed identity ID type is specified (only client ID is supported for user-assigned) - */ - createRequest(resource, managedIdentityId) { - const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.msiEndpoint); - request.headers[ManagedIdentityHeaders.METADATA_HEADER_NAME] = "true"; - request.headers[ManagedIdentityHeaders.ML_AND_SF_SECRET_HEADER_NAME] = - this.secret; - request.queryParameters[ManagedIdentityQueryParameters.API_VERSION] = - MACHINE_LEARNING_MSI_API_VERSION; - request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] = - resource; - if (managedIdentityId.idType === ManagedIdentityIdType.SYSTEM_ASSIGNED) { - request.queryParameters[ManagedIdentityUserAssignedIdQueryParameterNames.MANAGED_IDENTITY_CLIENT_ID_2017] = process.env[ManagedIdentityEnvironmentVariableNames - .DEFAULT_IDENTITY_CLIENT_ID]; // this environment variable is always set in an Azure Machine Learning source - } - else if (managedIdentityId.idType === - ManagedIdentityIdType.USER_ASSIGNED_CLIENT_ID) { - request.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType, false, // isIMDS - true // uses2017API - )] = managedIdentityId.id; - } - else { - throw new Error(MANAGED_IDENTITY_MACHINE_LEARNING_UNSUPPORTED_ID_TYPE_ERROR); - } - // bodyParameters calculated in BaseManagedIdentity.acquireTokenWithManagedIdentity - return request; - } -} - -export { MANAGED_IDENTITY_MACHINE_LEARNING_UNSUPPORTED_ID_TYPE_ERROR, MachineLearning }; -//# sourceMappingURL=MachineLearning.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/ServiceFabric.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/ServiceFabric.mjs deleted file mode 100644 index dbe1e7aa..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/client/ManagedIdentitySources/ServiceFabric.mjs +++ /dev/null @@ -1,122 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { ManagedIdentityRequestParameters } from '../../config/ManagedIdentityRequestParameters.mjs'; -import { BaseManagedIdentitySource } from './BaseManagedIdentitySource.mjs'; -import { ManagedIdentityEnvironmentVariableNames, ManagedIdentitySourceNames, ManagedIdentityIdType, ManagedIdentityHeaders, ManagedIdentityQueryParameters, HttpMethod } from '../../utils/Constants.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const SERVICE_FABRIC_MSI_API_VERSION = "2019-07-01-preview"; -/** - * Original source of code: https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/identity/Azure.Identity/src/ServiceFabricManagedIdentitySource.cs - */ -class ServiceFabric extends BaseManagedIdentitySource { - /** - * Constructs a new ServiceFabric managed identity source for acquiring tokens from Azure Service Fabric clusters. - * - * Service Fabric managed identity allows applications running in Service Fabric clusters to authenticate - * without storing credentials in code. This source handles token acquisition using the Service Fabric - * Managed Identity Token Service (MITS). - * - * @param logger - Logger instance for logging authentication events and debugging information - * @param nodeStorage - NodeStorage instance for caching tokens and other authentication artifacts - * @param networkClient - Network client for making HTTP requests to the Service Fabric identity endpoint - * @param cryptoProvider - Crypto provider for cryptographic operations like token validation - * @param disableInternalRetries - Whether to disable internal retry logic for failed requests - * @param identityEndpoint - The Service Fabric managed identity endpoint URL - * @param identityHeader - The Service Fabric managed identity secret header value - */ - constructor(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint, identityHeader) { - super(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries); - this.identityEndpoint = identityEndpoint; - this.identityHeader = identityHeader; - } - /** - * Retrieves the environment variables required for Service Fabric managed identity authentication. - * - * Service Fabric managed identity requires three specific environment variables to be set by the - * Service Fabric runtime: - * - IDENTITY_ENDPOINT: The endpoint URL for the Managed Identity Token Service (MITS) - * - IDENTITY_HEADER: A secret value used for authentication with the MITS - * - IDENTITY_SERVER_THUMBPRINT: The thumbprint of the MITS server certificate for secure communication - * - * @returns An array containing the identity endpoint, identity header, and identity server thumbprint values. - * Elements will be undefined if the corresponding environment variables are not set. - */ - static getEnvironmentVariables() { - const identityEndpoint = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT]; - const identityHeader = process.env[ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER]; - const identityServerThumbprint = process.env[ManagedIdentityEnvironmentVariableNames - .IDENTITY_SERVER_THUMBPRINT]; - return [identityEndpoint, identityHeader, identityServerThumbprint]; - } - /** - * Attempts to create a ServiceFabric managed identity source if the runtime environment supports it. - * - * Checks for the presence of all required Service Fabric environment variables - * and validates the endpoint URL format. It will only create a ServiceFabric instance if the application - * is running in a properly configured Service Fabric cluster with managed identity enabled. - * - * Note: User-assigned managed identities must be configured at the cluster level, not at runtime. - * This method will log a warning if a user-assigned identity is requested. - * - * @param logger - Logger instance for logging creation events and validation results - * @param nodeStorage - NodeStorage instance for caching tokens and authentication artifacts - * @param networkClient - Network client for making HTTP requests to the identity endpoint - * @param cryptoProvider - Crypto provider for cryptographic operations - * @param disableInternalRetries - Whether to disable internal retry logic for failed requests - * @param managedIdentityId - Managed identity identifier specifying system-assigned or user-assigned identity - * - * @returns A ServiceFabric instance if all environment variables are valid and present, otherwise null - */ - static tryCreate(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, managedIdentityId) { - const [identityEndpoint, identityHeader, identityServerThumbprint] = ServiceFabric.getEnvironmentVariables(); - if (!identityEndpoint || !identityHeader || !identityServerThumbprint) { - logger.info(`[Managed Identity] ${ManagedIdentitySourceNames.SERVICE_FABRIC} managed identity is unavailable because one or all of the '${ManagedIdentityEnvironmentVariableNames.IDENTITY_HEADER}', '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' or '${ManagedIdentityEnvironmentVariableNames.IDENTITY_SERVER_THUMBPRINT}' environment variables are not defined.`); - return null; - } - const validatedIdentityEndpoint = ServiceFabric.getValidatedEnvVariableUrlString(ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT, identityEndpoint, ManagedIdentitySourceNames.SERVICE_FABRIC, logger); - logger.info(`[Managed Identity] Environment variables validation passed for ${ManagedIdentitySourceNames.SERVICE_FABRIC} managed identity. Endpoint URI: ${validatedIdentityEndpoint}. Creating ${ManagedIdentitySourceNames.SERVICE_FABRIC} managed identity.`); - if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) { - logger.warning(`[Managed Identity] ${ManagedIdentitySourceNames.SERVICE_FABRIC} user assigned managed identity is configured in the cluster, not during runtime. See also: https://learn.microsoft.com/en-us/azure/service-fabric/configure-existing-cluster-enable-managed-identity-token-service.`); - } - return new ServiceFabric(logger, nodeStorage, networkClient, cryptoProvider, disableInternalRetries, identityEndpoint, identityHeader); - } - /** - * Creates HTTP request parameters for acquiring an access token from the Service Fabric Managed Identity Token Service (MITS). - * - * This method constructs a properly formatted HTTP GET request that includes: - * - The secret header for authentication with MITS - * - API version parameter for the Service Fabric MSI endpoint - * - Resource parameter specifying the target Azure service - * - Optional identity parameters for user-assigned managed identities - * - * The request follows the Service Fabric managed identity protocol and uses the 2019-07-01-preview API version. - * For user-assigned identities, the appropriate query parameter (client_id, object_id, or resource_id) is added - * based on the identity type. - * - * @param resource - The Azure resource URI for which the access token is requested (e.g., "https://vault.azure.net/") - * @param managedIdentityId - The managed identity configuration specifying system-assigned or user-assigned identity details - * - * @returns A configured ManagedIdentityRequestParameters object ready for network execution - */ - createRequest(resource, managedIdentityId) { - const request = new ManagedIdentityRequestParameters(HttpMethod.GET, this.identityEndpoint); - request.headers[ManagedIdentityHeaders.ML_AND_SF_SECRET_HEADER_NAME] = - this.identityHeader; - request.queryParameters[ManagedIdentityQueryParameters.API_VERSION] = - SERVICE_FABRIC_MSI_API_VERSION; - request.queryParameters[ManagedIdentityQueryParameters.RESOURCE] = - resource; - if (managedIdentityId.idType !== ManagedIdentityIdType.SYSTEM_ASSIGNED) { - request.queryParameters[this.getManagedIdentityUserAssignedIdQueryParameterKey(managedIdentityId.idType)] = managedIdentityId.id; - } - // bodyParameters calculated in BaseManagedIdentity.acquireTokenWithManagedIdentity - return request; - } -} - -export { ServiceFabric }; -//# sourceMappingURL=ServiceFabric.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/OnBehalfOfClient.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/OnBehalfOfClient.mjs deleted file mode 100644 index dafa0be0..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/client/OnBehalfOfClient.mjs +++ /dev/null @@ -1,210 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { BaseClient, ScopeSet, CacheOutcome, createClientAuthError, ClientAuthErrorCodes, TimeUtils, AuthToken, Constants, ResponseHandler, CredentialType, AuthenticationScheme, UrlString, RequestParameterBuilder, GrantType, AADServerParamKeys, getClientAssertion, UrlUtils } from '@azure/msal-common/node'; -import { EncodingUtils } from '../utils/EncodingUtils.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * On-Behalf-Of client - * @public - */ -class OnBehalfOfClient extends BaseClient { - constructor(configuration) { - super(configuration); - } - /** - * Public API to acquire tokens with on behalf of flow - * @param request - developer provided CommonOnBehalfOfRequest - */ - async acquireToken(request) { - this.scopeSet = new ScopeSet(request.scopes || []); - // generate the user_assertion_hash for OBOAssertion - this.userAssertionHash = await this.cryptoUtils.hashString(request.oboAssertion); - if (request.skipCache || request.claims) { - return this.executeTokenRequest(request, this.authority, this.userAssertionHash); - } - try { - return await this.getCachedAuthenticationResult(request); - } - catch (e) { - // Any failure falls back to interactive request, once we implement distributed cache, we plan to handle `createRefreshRequiredError` to refresh using the RT - return await this.executeTokenRequest(request, this.authority, this.userAssertionHash); - } - } - /** - * look up cache for tokens - * Find idtoken in the cache - * Find accessToken based on user assertion and account info in the cache - * Please note we are not yet supported OBO tokens refreshed with long lived RT. User will have to send a new assertion if the current access token expires - * This is to prevent security issues when the assertion changes over time, however, longlived RT helps retaining the session - * @param request - developer provided CommonOnBehalfOfRequest - */ - async getCachedAuthenticationResult(request) { - // look in the cache for the access_token which matches the incoming_assertion - const cachedAccessToken = this.readAccessTokenFromCacheForOBO(this.config.authOptions.clientId, request); - if (!cachedAccessToken) { - // Must refresh due to non-existent access_token. - this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.NO_CACHED_ACCESS_TOKEN); - this.logger.info("SilentFlowClient:acquireCachedToken - No access token found in cache for the given properties."); - throw createClientAuthError(ClientAuthErrorCodes.tokenRefreshRequired); - } - else if (TimeUtils.isTokenExpired(cachedAccessToken.expiresOn, this.config.systemOptions.tokenRenewalOffsetSeconds)) { - // Access token expired, will need to renewed - this.serverTelemetryManager?.setCacheOutcome(CacheOutcome.CACHED_ACCESS_TOKEN_EXPIRED); - this.logger.info(`OnbehalfofFlow:getCachedAuthenticationResult - Cached access token is expired or will expire within ${this.config.systemOptions.tokenRenewalOffsetSeconds} seconds.`); - throw createClientAuthError(ClientAuthErrorCodes.tokenRefreshRequired); - } - // fetch the idToken from cache - const cachedIdToken = this.readIdTokenFromCacheForOBO(cachedAccessToken.homeAccountId, request.correlationId); - let idTokenClaims; - let cachedAccount = null; - if (cachedIdToken) { - idTokenClaims = AuthToken.extractTokenClaims(cachedIdToken.secret, EncodingUtils.base64Decode); - const localAccountId = idTokenClaims.oid || idTokenClaims.sub; - const accountInfo = { - homeAccountId: cachedIdToken.homeAccountId, - environment: cachedIdToken.environment, - tenantId: cachedIdToken.realm, - username: Constants.EMPTY_STRING, - localAccountId: localAccountId || Constants.EMPTY_STRING, - }; - cachedAccount = this.cacheManager.getAccount(this.cacheManager.generateAccountKey(accountInfo), request.correlationId); - } - // increment telemetry cache hit counter - if (this.config.serverTelemetryManager) { - this.config.serverTelemetryManager.incrementCacheHits(); - } - return ResponseHandler.generateAuthenticationResult(this.cryptoUtils, this.authority, { - account: cachedAccount, - accessToken: cachedAccessToken, - idToken: cachedIdToken, - refreshToken: null, - appMetadata: null, - }, true, request, idTokenClaims); - } - /** - * read idtoken from cache, this is a specific implementation for OBO as the requirements differ from a generic lookup in the cacheManager - * Certain use cases of OBO flow do not expect an idToken in the cache/or from the service - * @param atHomeAccountId - account id - */ - readIdTokenFromCacheForOBO(atHomeAccountId, correlationId) { - const idTokenFilter = { - homeAccountId: atHomeAccountId, - environment: this.authority.canonicalAuthorityUrlComponents.HostNameAndPort, - credentialType: CredentialType.ID_TOKEN, - clientId: this.config.authOptions.clientId, - realm: this.authority.tenant, - }; - const idTokenMap = this.cacheManager.getIdTokensByFilter(idTokenFilter, correlationId); - // When acquiring a token on behalf of an application, there might not be an id token in the cache - if (Object.values(idTokenMap).length < 1) { - return null; - } - return Object.values(idTokenMap)[0]; - } - /** - * Fetches the cached access token based on incoming assertion - * @param clientId - client id - * @param request - developer provided CommonOnBehalfOfRequest - */ - readAccessTokenFromCacheForOBO(clientId, request) { - const authScheme = request.authenticationScheme || AuthenticationScheme.BEARER; - /* - * Distinguish between Bearer and PoP/SSH token cache types - * Cast to lowercase to handle "bearer" from ADFS - */ - const credentialType = authScheme && - authScheme.toLowerCase() !== - AuthenticationScheme.BEARER.toLowerCase() - ? CredentialType.ACCESS_TOKEN_WITH_AUTH_SCHEME - : CredentialType.ACCESS_TOKEN; - const accessTokenFilter = { - credentialType: credentialType, - clientId, - target: ScopeSet.createSearchScopes(this.scopeSet.asArray()), - tokenType: authScheme, - keyId: request.sshKid, - requestedClaimsHash: request.requestedClaimsHash, - userAssertionHash: this.userAssertionHash, - }; - const accessTokens = this.cacheManager.getAccessTokensByFilter(accessTokenFilter, request.correlationId); - const numAccessTokens = accessTokens.length; - if (numAccessTokens < 1) { - return null; - } - else if (numAccessTokens > 1) { - throw createClientAuthError(ClientAuthErrorCodes.multipleMatchingTokens); - } - return accessTokens[0]; - } - /** - * Make a network call to the server requesting credentials - * @param request - developer provided CommonOnBehalfOfRequest - * @param authority - authority object - */ - async executeTokenRequest(request, authority, userAssertionHash) { - const queryParametersString = this.createTokenQueryParameters(request); - const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString); - const requestBody = await this.createTokenRequestBody(request); - const headers = this.createTokenRequestHeaders(); - const thumbprint = { - clientId: this.config.authOptions.clientId, - authority: request.authority, - scopes: request.scopes, - claims: request.claims, - authenticationScheme: request.authenticationScheme, - resourceRequestMethod: request.resourceRequestMethod, - resourceRequestUri: request.resourceRequestUri, - shrClaims: request.shrClaims, - sshKid: request.sshKid, - }; - const reqTimestamp = TimeUtils.nowSeconds(); - const response = await this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint, request.correlationId); - const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin); - responseHandler.validateTokenResponse(response.body); - const tokenResponse = await responseHandler.handleServerTokenResponse(response.body, this.authority, reqTimestamp, request, undefined, userAssertionHash); - return tokenResponse; - } - /** - * generate a server request in accepable format - * @param request - developer provided CommonOnBehalfOfRequest - */ - async createTokenRequestBody(request) { - const parameters = new Map(); - RequestParameterBuilder.addClientId(parameters, this.config.authOptions.clientId); - RequestParameterBuilder.addScopes(parameters, request.scopes); - RequestParameterBuilder.addGrantType(parameters, GrantType.JWT_BEARER); - RequestParameterBuilder.addClientInfo(parameters); - RequestParameterBuilder.addLibraryInfo(parameters, this.config.libraryInfo); - RequestParameterBuilder.addApplicationTelemetry(parameters, this.config.telemetry.application); - RequestParameterBuilder.addThrottling(parameters); - if (this.serverTelemetryManager) { - RequestParameterBuilder.addServerTelemetry(parameters, this.serverTelemetryManager); - } - const correlationId = request.correlationId || - this.config.cryptoInterface.createNewGuid(); - RequestParameterBuilder.addCorrelationId(parameters, correlationId); - RequestParameterBuilder.addRequestTokenUse(parameters, AADServerParamKeys.ON_BEHALF_OF); - RequestParameterBuilder.addOboAssertion(parameters, request.oboAssertion); - if (this.config.clientCredentials.clientSecret) { - RequestParameterBuilder.addClientSecret(parameters, this.config.clientCredentials.clientSecret); - } - const clientAssertion = this.config.clientCredentials.clientAssertion; - if (clientAssertion) { - RequestParameterBuilder.addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri)); - RequestParameterBuilder.addClientAssertionType(parameters, clientAssertion.assertionType); - } - if (request.claims || - (this.config.authOptions.clientCapabilities && - this.config.authOptions.clientCapabilities.length > 0)) { - RequestParameterBuilder.addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities); - } - return UrlUtils.mapToQueryString(parameters); - } -} - -export { OnBehalfOfClient }; -//# sourceMappingURL=OnBehalfOfClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/PublicClientApplication.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/PublicClientApplication.mjs deleted file mode 100644 index ebace534..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/client/PublicClientApplication.mjs +++ /dev/null @@ -1,266 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { Constants, ApiId, LOOPBACK_SERVER_CONSTANTS } from '../utils/Constants.mjs'; -import { ServerTelemetryManager, AuthError, OIDC_DEFAULT_SCOPES, CodeChallengeMethodValues, ResponseMode, ServerError, Constants as Constants$1, AADServerParamKeys } from '@azure/msal-common/node'; -import { ClientApplication } from './ClientApplication.mjs'; -import { NodeAuthError, NodeAuthErrorMessage } from '../error/NodeAuthError.mjs'; -import { LoopbackClient } from '../network/LoopbackClient.mjs'; -import { DeviceCodeClient } from './DeviceCodeClient.mjs'; -import { version } from '../packageMetadata.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * This class is to be used to acquire tokens for public client applications (desktop, mobile). Public client applications - * are not trusted to safely store application secrets, and therefore can only request tokens in the name of an user. - * @public - */ -class PublicClientApplication extends ClientApplication { - /** - * Important attributes in the Configuration object for auth are: - * - clientID: the application ID of your application. You can obtain one by registering your application with our Application registration portal. - * - authority: the authority URL for your application. - * - * AAD authorities are of the form https://login.microsoftonline.com/\{Enter_the_Tenant_Info_Here\}. - * - If your application supports Accounts in one organizational directory, replace "Enter_the_Tenant_Info_Here" value with the Tenant Id or Tenant name (for example, contoso.microsoft.com). - * - If your application supports Accounts in any organizational directory, replace "Enter_the_Tenant_Info_Here" value with organizations. - * - If your application supports Accounts in any organizational directory and personal Microsoft accounts, replace "Enter_the_Tenant_Info_Here" value with common. - * - To restrict support to Personal Microsoft accounts only, replace "Enter_the_Tenant_Info_Here" value with consumers. - * - * Azure B2C authorities are of the form https://\{instance\}/\{tenant\}/\{policy\}. Each policy is considered - * its own authority. You will have to set the all of the knownAuthorities at the time of the client application - * construction. - * - * ADFS authorities are of the form https://\{instance\}/adfs. - */ - constructor(configuration) { - super(configuration); - if (this.config.broker.nativeBrokerPlugin) { - if (this.config.broker.nativeBrokerPlugin.isBrokerAvailable) { - this.nativeBrokerPlugin = this.config.broker.nativeBrokerPlugin; - this.nativeBrokerPlugin.setLogger(this.config.system.loggerOptions); - } - else { - this.logger.warning("NativeBroker implementation was provided but the broker is unavailable."); - } - } - this.skus = ServerTelemetryManager.makeExtraSkuString({ - libraryName: Constants.MSAL_SKU, - libraryVersion: version, - }); - } - /** - * Acquires a token from the authority using OAuth2.0 device code flow. - * This flow is designed for devices that do not have access to a browser or have input constraints. - * The authorization server issues a DeviceCode object with a verification code, an end-user code, - * and the end-user verification URI. The DeviceCode object is provided through a callback, and the end-user should be - * instructed to use another device to navigate to the verification URI to input credentials. - * Since the client cannot receive incoming requests, it polls the authorization server repeatedly - * until the end-user completes input of credentials. - */ - async acquireTokenByDeviceCode(request) { - this.logger.info("acquireTokenByDeviceCode called", request.correlationId); - const validRequest = Object.assign(request, await this.initializeBaseRequest(request)); - const serverTelemetryManager = this.initializeServerTelemetryManager(ApiId.acquireTokenByDeviceCode, validRequest.correlationId); - try { - const discoveredAuthority = await this.createAuthority(validRequest.authority, validRequest.correlationId, undefined, request.azureCloudOptions); - const deviceCodeConfig = await this.buildOauthClientConfiguration(discoveredAuthority, validRequest.correlationId, "", serverTelemetryManager); - const deviceCodeClient = new DeviceCodeClient(deviceCodeConfig); - this.logger.verbose("Device code client created", validRequest.correlationId); - return await deviceCodeClient.acquireToken(validRequest); - } - catch (e) { - if (e instanceof AuthError) { - e.setCorrelationId(validRequest.correlationId); - } - serverTelemetryManager.cacheFailedRequest(e); - throw e; - } - } - /** - * Acquires a token interactively via the browser by requesting an authorization code then exchanging it for a token. - */ - async acquireTokenInteractive(request) { - const correlationId = request.correlationId || this.cryptoProvider.createNewGuid(); - this.logger.trace("acquireTokenInteractive called", correlationId); - const { openBrowser, successTemplate, errorTemplate, windowHandle, loopbackClient: customLoopbackClient, ...remainingProperties } = request; - if (this.nativeBrokerPlugin) { - const brokerRequest = { - ...remainingProperties, - clientId: this.config.auth.clientId, - scopes: request.scopes || OIDC_DEFAULT_SCOPES, - redirectUri: request.redirectUri || "", - authority: request.authority || this.config.auth.authority, - correlationId: correlationId, - extraParameters: { - ...remainingProperties.extraQueryParameters, - ...remainingProperties.tokenQueryParameters, - [AADServerParamKeys.X_CLIENT_EXTRA_SKU]: this.skus, - }, - accountId: remainingProperties.account?.nativeAccountId, - }; - return this.nativeBrokerPlugin.acquireTokenInteractive(brokerRequest, windowHandle); - } - if (request.redirectUri) { - // If its not a broker fallback scenario, we throw a error - if (!this.config.broker.nativeBrokerPlugin) { - throw NodeAuthError.createRedirectUriNotSupportedError(); - } - // If a redirect URI is provided for a broker flow but MSAL runtime startup failed, we fall back to the browser flow and will ignore the redirect URI provided for the broker flow - request.redirectUri = ""; - } - const { verifier, challenge } = await this.cryptoProvider.generatePkceCodes(); - const loopbackClient = customLoopbackClient || new LoopbackClient(); - let authCodeResponse = {}; - let authCodeListenerError = null; - try { - const authCodeListener = loopbackClient - .listenForAuthCode(successTemplate, errorTemplate) - .then((response) => { - authCodeResponse = response; - }) - .catch((e) => { - // Store the promise instead of throwing so we can control when its thrown - authCodeListenerError = e; - }); - // Wait for server to be listening - const redirectUri = await this.waitForRedirectUri(loopbackClient); - const validRequest = { - ...remainingProperties, - correlationId: correlationId, - scopes: request.scopes || OIDC_DEFAULT_SCOPES, - redirectUri: redirectUri, - responseMode: ResponseMode.QUERY, - codeChallenge: challenge, - codeChallengeMethod: CodeChallengeMethodValues.S256, - }; - const authCodeUrl = await this.getAuthCodeUrl(validRequest); - await openBrowser(authCodeUrl); - await authCodeListener; - if (authCodeListenerError) { - throw authCodeListenerError; - } - if (authCodeResponse.error) { - throw new ServerError(authCodeResponse.error, authCodeResponse.error_description, authCodeResponse.suberror); - } - else if (!authCodeResponse.code) { - throw NodeAuthError.createNoAuthCodeInResponseError(); - } - const clientInfo = authCodeResponse.client_info; - const tokenRequest = { - code: authCodeResponse.code, - codeVerifier: verifier, - clientInfo: clientInfo || Constants$1.EMPTY_STRING, - ...validRequest, - }; - return await this.acquireTokenByCode(tokenRequest); // Await this so the server doesn't close prematurely - } - finally { - loopbackClient.closeServer(); - } - } - /** - * Returns a token retrieved either from the cache or by exchanging the refresh token for a fresh access token. If brokering is enabled the token request will be serviced by the broker. - * @param request - developer provided SilentFlowRequest - * @returns - */ - async acquireTokenSilent(request) { - const correlationId = request.correlationId || this.cryptoProvider.createNewGuid(); - this.logger.trace("acquireTokenSilent called", correlationId); - if (this.nativeBrokerPlugin) { - const brokerRequest = { - ...request, - clientId: this.config.auth.clientId, - scopes: request.scopes || OIDC_DEFAULT_SCOPES, - redirectUri: request.redirectUri || "", - authority: request.authority || this.config.auth.authority, - correlationId: correlationId, - extraParameters: { - ...request.tokenQueryParameters, - [AADServerParamKeys.X_CLIENT_EXTRA_SKU]: this.skus, - }, - accountId: request.account.nativeAccountId, - forceRefresh: request.forceRefresh || false, - }; - return this.nativeBrokerPlugin.acquireTokenSilent(brokerRequest); - } - if (request.redirectUri) { - // If its not a broker fallback scenario, we throw a error - if (!this.config.broker.nativeBrokerPlugin) { - throw NodeAuthError.createRedirectUriNotSupportedError(); - } - request.redirectUri = ""; - } - return super.acquireTokenSilent(request); - } - /** - * Removes cache artifacts associated with the given account - * @param request - developer provided SignOutRequest - * @returns - */ - async signOut(request) { - if (this.nativeBrokerPlugin && request.account.nativeAccountId) { - const signoutRequest = { - clientId: this.config.auth.clientId, - accountId: request.account.nativeAccountId, - correlationId: request.correlationId || - this.cryptoProvider.createNewGuid(), - }; - await this.nativeBrokerPlugin.signOut(signoutRequest); - } - await this.getTokenCache().removeAccount(request.account, request.correlationId); - } - /** - * Returns all cached accounts for this application. If brokering is enabled this request will be serviced by the broker. - * @returns - */ - async getAllAccounts() { - if (this.nativeBrokerPlugin) { - const correlationId = this.cryptoProvider.createNewGuid(); - return this.nativeBrokerPlugin.getAllAccounts(this.config.auth.clientId, correlationId); - } - return this.getTokenCache().getAllAccounts(); - } - /** - * Attempts to retrieve the redirectUri from the loopback server. If the loopback server does not start listening for requests within the timeout this will throw. - * @param loopbackClient - developer provided custom loopback server implementation - * @returns - */ - async waitForRedirectUri(loopbackClient) { - return new Promise((resolve, reject) => { - let ticks = 0; - const id = setInterval(() => { - if (LOOPBACK_SERVER_CONSTANTS.TIMEOUT_MS / - LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS < - ticks) { - clearInterval(id); - reject(NodeAuthError.createLoopbackServerTimeoutError()); - return; - } - try { - const r = loopbackClient.getRedirectUri(); - clearInterval(id); - resolve(r); - return; - } - catch (e) { - if (e instanceof AuthError && - e.errorCode === - NodeAuthErrorMessage.noLoopbackServerExists.code) { - // Loopback server is not listening yet - ticks++; - return; - } - clearInterval(id); - reject(e); - return; - } - }, LOOPBACK_SERVER_CONSTANTS.INTERVAL_MS); - }); - } -} - -export { PublicClientApplication }; -//# sourceMappingURL=PublicClientApplication.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/client/UsernamePasswordClient.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/client/UsernamePasswordClient.mjs deleted file mode 100644 index f0bfbb3c..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/client/UsernamePasswordClient.mjs +++ /dev/null @@ -1,104 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { BaseClient, TimeUtils, ResponseHandler, UrlString, CcsCredentialType, RequestParameterBuilder, OAuthResponseType, GrantType, getClientAssertion, StringUtils, UrlUtils } from '@azure/msal-common/node'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Oauth2.0 Password grant client - * Note: We are only supporting public clients for password grant and for purely testing purposes - * @public - * @deprecated - Use a more secure flow instead - */ -class UsernamePasswordClient extends BaseClient { - constructor(configuration) { - super(configuration); - } - /** - * API to acquire a token by passing the username and password to the service in exchage of credentials - * password_grant - * @param request - CommonUsernamePasswordRequest - */ - async acquireToken(request) { - this.logger.info("in acquireToken call in username-password client"); - const reqTimestamp = TimeUtils.nowSeconds(); - const response = await this.executeTokenRequest(this.authority, request); - const responseHandler = new ResponseHandler(this.config.authOptions.clientId, this.cacheManager, this.cryptoUtils, this.logger, this.config.serializableCache, this.config.persistencePlugin); - // Validate response. This function throws a server error if an error is returned by the server. - responseHandler.validateTokenResponse(response.body); - const tokenResponse = responseHandler.handleServerTokenResponse(response.body, this.authority, reqTimestamp, request); - return tokenResponse; - } - /** - * Executes POST request to token endpoint - * @param authority - authority object - * @param request - CommonUsernamePasswordRequest provided by the developer - */ - async executeTokenRequest(authority, request) { - const queryParametersString = this.createTokenQueryParameters(request); - const endpoint = UrlString.appendQueryString(authority.tokenEndpoint, queryParametersString); - const requestBody = await this.createTokenRequestBody(request); - const headers = this.createTokenRequestHeaders({ - credential: request.username, - type: CcsCredentialType.UPN, - }); - const thumbprint = { - clientId: this.config.authOptions.clientId, - authority: authority.canonicalAuthority, - scopes: request.scopes, - claims: request.claims, - authenticationScheme: request.authenticationScheme, - resourceRequestMethod: request.resourceRequestMethod, - resourceRequestUri: request.resourceRequestUri, - shrClaims: request.shrClaims, - sshKid: request.sshKid, - }; - return this.executePostToTokenEndpoint(endpoint, requestBody, headers, thumbprint, request.correlationId); - } - /** - * Generates a map for all the params to be sent to the service - * @param request - CommonUsernamePasswordRequest provided by the developer - */ - async createTokenRequestBody(request) { - const parameters = new Map(); - RequestParameterBuilder.addClientId(parameters, this.config.authOptions.clientId); - RequestParameterBuilder.addUsername(parameters, request.username); - RequestParameterBuilder.addPassword(parameters, request.password); - RequestParameterBuilder.addScopes(parameters, request.scopes); - RequestParameterBuilder.addResponseType(parameters, OAuthResponseType.IDTOKEN_TOKEN); - RequestParameterBuilder.addGrantType(parameters, GrantType.RESOURCE_OWNER_PASSWORD_GRANT); - RequestParameterBuilder.addClientInfo(parameters); - RequestParameterBuilder.addLibraryInfo(parameters, this.config.libraryInfo); - RequestParameterBuilder.addApplicationTelemetry(parameters, this.config.telemetry.application); - RequestParameterBuilder.addThrottling(parameters); - if (this.serverTelemetryManager) { - RequestParameterBuilder.addServerTelemetry(parameters, this.serverTelemetryManager); - } - const correlationId = request.correlationId || - this.config.cryptoInterface.createNewGuid(); - RequestParameterBuilder.addCorrelationId(parameters, correlationId); - if (this.config.clientCredentials.clientSecret) { - RequestParameterBuilder.addClientSecret(parameters, this.config.clientCredentials.clientSecret); - } - const clientAssertion = this.config.clientCredentials.clientAssertion; - if (clientAssertion) { - RequestParameterBuilder.addClientAssertion(parameters, await getClientAssertion(clientAssertion.assertion, this.config.authOptions.clientId, request.resourceRequestUri)); - RequestParameterBuilder.addClientAssertionType(parameters, clientAssertion.assertionType); - } - if (!StringUtils.isEmptyObj(request.claims) || - (this.config.authOptions.clientCapabilities && - this.config.authOptions.clientCapabilities.length > 0)) { - RequestParameterBuilder.addClaims(parameters, request.claims, this.config.authOptions.clientCapabilities); - } - if (this.config.systemOptions.preventCorsPreflight && - request.username) { - RequestParameterBuilder.addCcsUpn(parameters, request.username); - } - return UrlUtils.mapToQueryString(parameters); - } -} - -export { UsernamePasswordClient }; -//# sourceMappingURL=UsernamePasswordClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/config/Configuration.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/config/Configuration.mjs deleted file mode 100644 index bbefceb6..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/config/Configuration.mjs +++ /dev/null @@ -1,114 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { Constants, LogLevel, AzureCloudInstance, ProtocolMode } from '@azure/msal-common/node'; -import { HttpClient } from '../network/HttpClient.mjs'; -import { ManagedIdentityId } from './ManagedIdentityId.mjs'; -import { NodeAuthError } from '../error/NodeAuthError.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const DEFAULT_AUTH_OPTIONS = { - clientId: Constants.EMPTY_STRING, - authority: Constants.DEFAULT_AUTHORITY, - clientSecret: Constants.EMPTY_STRING, - clientAssertion: Constants.EMPTY_STRING, - clientCertificate: { - thumbprint: Constants.EMPTY_STRING, - thumbprintSha256: Constants.EMPTY_STRING, - privateKey: Constants.EMPTY_STRING, - x5c: Constants.EMPTY_STRING, - }, - knownAuthorities: [], - cloudDiscoveryMetadata: Constants.EMPTY_STRING, - authorityMetadata: Constants.EMPTY_STRING, - clientCapabilities: [], - protocolMode: ProtocolMode.AAD, - azureCloudOptions: { - azureCloudInstance: AzureCloudInstance.None, - tenant: Constants.EMPTY_STRING, - }, - skipAuthorityMetadataCache: false, - encodeExtraQueryParams: false, -}; -const DEFAULT_CACHE_OPTIONS = { - claimsBasedCachingEnabled: false, -}; -const DEFAULT_LOGGER_OPTIONS = { - loggerCallback: () => { - // allow users to not set logger call back - }, - piiLoggingEnabled: false, - logLevel: LogLevel.Info, -}; -const DEFAULT_SYSTEM_OPTIONS = { - loggerOptions: DEFAULT_LOGGER_OPTIONS, - networkClient: new HttpClient(), - proxyUrl: Constants.EMPTY_STRING, - customAgentOptions: {}, - disableInternalRetries: false, -}; -const DEFAULT_TELEMETRY_OPTIONS = { - application: { - appName: Constants.EMPTY_STRING, - appVersion: Constants.EMPTY_STRING, - }, -}; -/** - * Sets the default options when not explicitly configured from app developer - * - * @param auth - Authentication options - * @param cache - Cache options - * @param system - System options - * @param telemetry - Telemetry options - * - * @returns Configuration - * @internal - */ -function buildAppConfiguration({ auth, broker, cache, system, telemetry, }) { - const systemOptions = { - ...DEFAULT_SYSTEM_OPTIONS, - networkClient: new HttpClient(system?.proxyUrl, system?.customAgentOptions), - loggerOptions: system?.loggerOptions || DEFAULT_LOGGER_OPTIONS, - disableInternalRetries: system?.disableInternalRetries || false, - }; - // if client certificate was provided, ensure that at least one of the SHA-1 or SHA-256 thumbprints were provided - if (!!auth.clientCertificate && - !!!auth.clientCertificate.thumbprint && - !!!auth.clientCertificate.thumbprintSha256) { - throw NodeAuthError.createStateNotFoundError(); - } - return { - auth: { ...DEFAULT_AUTH_OPTIONS, ...auth }, - broker: { ...broker }, - cache: { ...DEFAULT_CACHE_OPTIONS, ...cache }, - system: { ...systemOptions, ...system }, - telemetry: { ...DEFAULT_TELEMETRY_OPTIONS, ...telemetry }, - }; -} -function buildManagedIdentityConfiguration({ clientCapabilities, managedIdentityIdParams, system, }) { - const managedIdentityId = new ManagedIdentityId(managedIdentityIdParams); - const loggerOptions = system?.loggerOptions || DEFAULT_LOGGER_OPTIONS; - let networkClient; - // use developer provided network client if passed in - if (system?.networkClient) { - networkClient = system.networkClient; - // otherwise, create a new one - } - else { - networkClient = new HttpClient(system?.proxyUrl, system?.customAgentOptions); - } - return { - clientCapabilities: clientCapabilities || [], - managedIdentityId: managedIdentityId, - system: { - loggerOptions, - networkClient, - }, - disableInternalRetries: system?.disableInternalRetries || false, - }; -} - -export { buildAppConfiguration, buildManagedIdentityConfiguration }; -//# sourceMappingURL=Configuration.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/config/ManagedIdentityId.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/config/ManagedIdentityId.mjs deleted file mode 100644 index 2f1a5ed2..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/config/ManagedIdentityId.mjs +++ /dev/null @@ -1,57 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { createManagedIdentityError } from '../error/ManagedIdentityError.mjs'; -import { ManagedIdentityIdType, DEFAULT_MANAGED_IDENTITY_ID } from '../utils/Constants.mjs'; -import { invalidManagedIdentityIdType } from '../error/ManagedIdentityErrorCodes.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -class ManagedIdentityId { - get id() { - return this._id; - } - set id(value) { - this._id = value; - } - get idType() { - return this._idType; - } - set idType(value) { - this._idType = value; - } - constructor(managedIdentityIdParams) { - const userAssignedClientId = managedIdentityIdParams?.userAssignedClientId; - const userAssignedResourceId = managedIdentityIdParams?.userAssignedResourceId; - const userAssignedObjectId = managedIdentityIdParams?.userAssignedObjectId; - if (userAssignedClientId) { - if (userAssignedResourceId || userAssignedObjectId) { - throw createManagedIdentityError(invalidManagedIdentityIdType); - } - this.id = userAssignedClientId; - this.idType = ManagedIdentityIdType.USER_ASSIGNED_CLIENT_ID; - } - else if (userAssignedResourceId) { - if (userAssignedClientId || userAssignedObjectId) { - throw createManagedIdentityError(invalidManagedIdentityIdType); - } - this.id = userAssignedResourceId; - this.idType = ManagedIdentityIdType.USER_ASSIGNED_RESOURCE_ID; - } - else if (userAssignedObjectId) { - if (userAssignedClientId || userAssignedResourceId) { - throw createManagedIdentityError(invalidManagedIdentityIdType); - } - this.id = userAssignedObjectId; - this.idType = ManagedIdentityIdType.USER_ASSIGNED_OBJECT_ID; - } - else { - this.id = DEFAULT_MANAGED_IDENTITY_ID; - this.idType = ManagedIdentityIdType.SYSTEM_ASSIGNED; - } - } -} - -export { ManagedIdentityId }; -//# sourceMappingURL=ManagedIdentityId.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/config/ManagedIdentityRequestParameters.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/config/ManagedIdentityRequestParameters.mjs deleted file mode 100644 index 405b78ad..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/config/ManagedIdentityRequestParameters.mjs +++ /dev/null @@ -1,38 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { RequestParameterBuilder, UrlUtils, UrlString } from '@azure/msal-common/node'; -import { DefaultManagedIdentityRetryPolicy } from '../retry/DefaultManagedIdentityRetryPolicy.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -class ManagedIdentityRequestParameters { - constructor(httpMethod, endpoint, retryPolicy) { - this.httpMethod = httpMethod; - this._baseEndpoint = endpoint; - this.headers = {}; - this.bodyParameters = {}; - this.queryParameters = {}; - this.retryPolicy = - retryPolicy || new DefaultManagedIdentityRetryPolicy(); - } - computeUri() { - const parameters = new Map(); - if (this.queryParameters) { - RequestParameterBuilder.addExtraQueryParameters(parameters, this.queryParameters); - } - const queryParametersString = UrlUtils.mapToQueryString(parameters); - return UrlString.appendQueryString(this._baseEndpoint, queryParametersString); - } - computeParametersBodyString() { - const parameters = new Map(); - if (this.bodyParameters) { - RequestParameterBuilder.addExtraQueryParameters(parameters, this.bodyParameters); - } - return UrlUtils.mapToQueryString(parameters); - } -} - -export { ManagedIdentityRequestParameters }; -//# sourceMappingURL=ManagedIdentityRequestParameters.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/crypto/CryptoProvider.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/crypto/CryptoProvider.mjs deleted file mode 100644 index 7ef24091..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/crypto/CryptoProvider.mjs +++ /dev/null @@ -1,100 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { EncodingTypes } from '@azure/msal-common/node'; -import { GuidGenerator } from './GuidGenerator.mjs'; -import { EncodingUtils } from '../utils/EncodingUtils.mjs'; -import { PkceGenerator } from './PkceGenerator.mjs'; -import { HashUtils } from './HashUtils.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * This class implements MSAL node's crypto interface, which allows it to perform base64 encoding and decoding, generating cryptographically random GUIDs and - * implementing Proof Key for Code Exchange specs for the OAuth Authorization Code Flow using PKCE (rfc here: https://tools.ietf.org/html/rfc7636). - * @public - */ -class CryptoProvider { - constructor() { - // Browser crypto needs to be validated first before any other classes can be set. - this.pkceGenerator = new PkceGenerator(); - this.guidGenerator = new GuidGenerator(); - this.hashUtils = new HashUtils(); - } - /** - * base64 URL safe encoded string - */ - base64UrlEncode() { - throw new Error("Method not implemented."); - } - /** - * Stringifies and base64Url encodes input public key - * @param inputKid - public key id - * @returns Base64Url encoded public key - */ - encodeKid() { - throw new Error("Method not implemented."); - } - /** - * Creates a new random GUID - used to populate state and nonce. - * @returns string (GUID) - */ - createNewGuid() { - return this.guidGenerator.generateGuid(); - } - /** - * Encodes input string to base64. - * @param input - string to be encoded - */ - base64Encode(input) { - return EncodingUtils.base64Encode(input); - } - /** - * Decodes input string from base64. - * @param input - string to be decoded - */ - base64Decode(input) { - return EncodingUtils.base64Decode(input); - } - /** - * Generates PKCE codes used in Authorization Code Flow. - */ - generatePkceCodes() { - return this.pkceGenerator.generatePkceCodes(); - } - /** - * Generates a keypair, stores it and returns a thumbprint - not yet implemented for node - */ - getPublicKeyThumbprint() { - throw new Error("Method not implemented."); - } - /** - * Removes cryptographic keypair from key store matching the keyId passed in - * @param kid - public key id - */ - removeTokenBindingKey() { - throw new Error("Method not implemented."); - } - /** - * Removes all cryptographic keys from Keystore - */ - clearKeystore() { - throw new Error("Method not implemented."); - } - /** - * Signs the given object as a jwt payload with private key retrieved by given kid - currently not implemented for node - */ - signJwt() { - throw new Error("Method not implemented."); - } - /** - * Returns the SHA-256 hash of an input string - */ - async hashString(plainText) { - return EncodingUtils.base64EncodeUrl(this.hashUtils.sha256(plainText).toString(EncodingTypes.BASE64), EncodingTypes.BASE64); - } -} - -export { CryptoProvider }; -//# sourceMappingURL=CryptoProvider.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/crypto/GuidGenerator.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/crypto/GuidGenerator.mjs deleted file mode 100644 index bc0ffae7..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/crypto/GuidGenerator.mjs +++ /dev/null @@ -1,29 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { v4 } from 'uuid'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -class GuidGenerator { - /** - * - * RFC4122: The version 4 UUID is meant for generating UUIDs from truly-random or pseudo-random numbers. - * uuidv4 generates guids from cryprtographically-string random - */ - generateGuid() { - return v4(); - } - /** - * verifies if a string is GUID - * @param guid - */ - isGuid(guid) { - const regexGuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; - return regexGuid.test(guid); - } -} - -export { GuidGenerator }; -//# sourceMappingURL=GuidGenerator.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/crypto/HashUtils.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/crypto/HashUtils.mjs deleted file mode 100644 index 00b58181..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/crypto/HashUtils.mjs +++ /dev/null @@ -1,21 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { Hash } from '../utils/Constants.mjs'; -import crypto from 'crypto'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -class HashUtils { - /** - * generate 'SHA256' hash - * @param buffer - */ - sha256(buffer) { - return crypto.createHash(Hash.SHA256).update(buffer).digest(); - } -} - -export { HashUtils }; -//# sourceMappingURL=HashUtils.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/crypto/PkceGenerator.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/crypto/PkceGenerator.mjs deleted file mode 100644 index f70ba56d..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/crypto/PkceGenerator.mjs +++ /dev/null @@ -1,60 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { EncodingTypes, Constants } from '@azure/msal-common/node'; -import { RANDOM_OCTET_SIZE, CharSet } from '../utils/Constants.mjs'; -import { EncodingUtils } from '../utils/EncodingUtils.mjs'; -import { HashUtils } from './HashUtils.mjs'; -import crypto from 'crypto'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * https://tools.ietf.org/html/rfc7636#page-8 - */ -class PkceGenerator { - constructor() { - this.hashUtils = new HashUtils(); - } - /** - * generates the codeVerfier and the challenge from the codeVerfier - * reference: https://tools.ietf.org/html/rfc7636#section-4.1 and https://tools.ietf.org/html/rfc7636#section-4.2 - */ - async generatePkceCodes() { - const verifier = this.generateCodeVerifier(); - const challenge = this.generateCodeChallengeFromVerifier(verifier); - return { verifier, challenge }; - } - /** - * generates the codeVerfier; reference: https://tools.ietf.org/html/rfc7636#section-4.1 - */ - generateCodeVerifier() { - const charArr = []; - const maxNumber = 256 - (256 % CharSet.CV_CHARSET.length); - while (charArr.length <= RANDOM_OCTET_SIZE) { - const byte = crypto.randomBytes(1)[0]; - if (byte >= maxNumber) { - /* - * Ignore this number to maintain randomness. - * Including it would result in an unequal distribution of characters after doing the modulo - */ - continue; - } - const index = byte % CharSet.CV_CHARSET.length; - charArr.push(CharSet.CV_CHARSET[index]); - } - const verifier = charArr.join(Constants.EMPTY_STRING); - return EncodingUtils.base64EncodeUrl(verifier); - } - /** - * generate the challenge from the codeVerfier; reference: https://tools.ietf.org/html/rfc7636#section-4.2 - * @param codeVerifier - */ - generateCodeChallengeFromVerifier(codeVerifier) { - return EncodingUtils.base64EncodeUrl(this.hashUtils.sha256(codeVerifier).toString(EncodingTypes.BASE64), EncodingTypes.BASE64); - } -} - -export { PkceGenerator }; -//# sourceMappingURL=PkceGenerator.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/error/ManagedIdentityError.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/error/ManagedIdentityError.mjs deleted file mode 100644 index 0f5fd694..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/error/ManagedIdentityError.mjs +++ /dev/null @@ -1,50 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { AuthError } from '@azure/msal-common/node'; -import { wwwAuthenticateHeaderUnsupportedFormat, wwwAuthenticateHeaderMissing, userAssignedNotAvailableAtRuntime, unableToReadSecretFile, unableToCreateSource, unableToCreateCloudShell, unableToCreateAzureArc, networkUnavailable, MsiEnvironmentVariableUrlMalformedErrorCodes, missingId, platformNotSupported, invalidSecret, invalidManagedIdentityIdType, invalidFilePath, invalidFileExtension } from './ManagedIdentityErrorCodes.mjs'; -import { ManagedIdentityEnvironmentVariableNames } from '../utils/Constants.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * ManagedIdentityErrorMessage class containing string constants used by error codes and messages. - */ -const ManagedIdentityErrorMessages = { - [invalidFileExtension]: "The file path in the WWW-Authenticate header does not contain a .key file.", - [invalidFilePath]: "The file path in the WWW-Authenticate header is not in a valid Windows or Linux Format.", - [invalidManagedIdentityIdType]: "More than one ManagedIdentityIdType was provided.", - [invalidSecret]: "The secret in the file on the file path in the WWW-Authenticate header is greater than 4096 bytes.", - [platformNotSupported]: "The platform is not supported by Azure Arc. Azure Arc only supports Windows and Linux.", - [missingId]: "A ManagedIdentityId id was not provided.", - [MsiEnvironmentVariableUrlMalformedErrorCodes - .AZURE_POD_IDENTITY_AUTHORITY_HOST]: `The Managed Identity's '${ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST}' environment variable is malformed.`, - [MsiEnvironmentVariableUrlMalformedErrorCodes - .IDENTITY_ENDPOINT]: `The Managed Identity's '${ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT}' environment variable is malformed.`, - [MsiEnvironmentVariableUrlMalformedErrorCodes - .IMDS_ENDPOINT]: `The Managed Identity's '${ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT}' environment variable is malformed.`, - [MsiEnvironmentVariableUrlMalformedErrorCodes - .MSI_ENDPOINT]: `The Managed Identity's '${ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT}' environment variable is malformed.`, - [networkUnavailable]: "Authentication unavailable. The request to the managed identity endpoint timed out.", - [unableToCreateAzureArc]: "Azure Arc Managed Identities can only be system assigned.", - [unableToCreateCloudShell]: "Cloud Shell Managed Identities can only be system assigned.", - [unableToCreateSource]: "Unable to create a Managed Identity source based on environment variables.", - [unableToReadSecretFile]: "Unable to read the secret file.", - [userAssignedNotAvailableAtRuntime]: "Service Fabric user assigned managed identity ClientId or ResourceId is not configurable at runtime.", - [wwwAuthenticateHeaderMissing]: "A 401 response was received form the Azure Arc Managed Identity, but the www-authenticate header is missing.", - [wwwAuthenticateHeaderUnsupportedFormat]: "A 401 response was received form the Azure Arc Managed Identity, but the www-authenticate header is in an unsupported format.", -}; -class ManagedIdentityError extends AuthError { - constructor(errorCode) { - super(errorCode, ManagedIdentityErrorMessages[errorCode]); - this.name = "ManagedIdentityError"; - Object.setPrototypeOf(this, ManagedIdentityError.prototype); - } -} -function createManagedIdentityError(errorCode) { - return new ManagedIdentityError(errorCode); -} - -export { ManagedIdentityError, ManagedIdentityErrorMessages, createManagedIdentityError }; -//# sourceMappingURL=ManagedIdentityError.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/error/ManagedIdentityErrorCodes.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/error/ManagedIdentityErrorCodes.mjs deleted file mode 100644 index df098d74..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/error/ManagedIdentityErrorCodes.mjs +++ /dev/null @@ -1,31 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { ManagedIdentityEnvironmentVariableNames } from '../utils/Constants.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const invalidFileExtension = "invalid_file_extension"; -const invalidFilePath = "invalid_file_path"; -const invalidManagedIdentityIdType = "invalid_managed_identity_id_type"; -const invalidSecret = "invalid_secret"; -const missingId = "missing_client_id"; -const networkUnavailable = "network_unavailable"; -const platformNotSupported = "platform_not_supported"; -const unableToCreateAzureArc = "unable_to_create_azure_arc"; -const unableToCreateCloudShell = "unable_to_create_cloud_shell"; -const unableToCreateSource = "unable_to_create_source"; -const unableToReadSecretFile = "unable_to_read_secret_file"; -const userAssignedNotAvailableAtRuntime = "user_assigned_not_available_at_runtime"; -const wwwAuthenticateHeaderMissing = "www_authenticate_header_missing"; -const wwwAuthenticateHeaderUnsupportedFormat = "www_authenticate_header_unsupported_format"; -const MsiEnvironmentVariableUrlMalformedErrorCodes = { - [ManagedIdentityEnvironmentVariableNames.AZURE_POD_IDENTITY_AUTHORITY_HOST]: "azure_pod_identity_authority_host_url_malformed", - [ManagedIdentityEnvironmentVariableNames.IDENTITY_ENDPOINT]: "identity_endpoint_url_malformed", - [ManagedIdentityEnvironmentVariableNames.IMDS_ENDPOINT]: "imds_endpoint_url_malformed", - [ManagedIdentityEnvironmentVariableNames.MSI_ENDPOINT]: "msi_endpoint_url_malformed", -}; - -export { MsiEnvironmentVariableUrlMalformedErrorCodes, invalidFileExtension, invalidFilePath, invalidManagedIdentityIdType, invalidSecret, missingId, networkUnavailable, platformNotSupported, unableToCreateAzureArc, unableToCreateCloudShell, unableToCreateSource, unableToReadSecretFile, userAssignedNotAvailableAtRuntime, wwwAuthenticateHeaderMissing, wwwAuthenticateHeaderUnsupportedFormat }; -//# sourceMappingURL=ManagedIdentityErrorCodes.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/error/NodeAuthError.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/error/NodeAuthError.mjs deleted file mode 100644 index 017aee1e..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/error/NodeAuthError.mjs +++ /dev/null @@ -1,112 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { AuthError } from '@azure/msal-common/node'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * NodeAuthErrorMessage class containing string constants used by error codes and messages. - */ -const NodeAuthErrorMessage = { - invalidLoopbackAddressType: { - code: "invalid_loopback_server_address_type", - desc: "Loopback server address is not type string. This is unexpected.", - }, - unableToLoadRedirectUri: { - code: "unable_to_load_redirectUrl", - desc: "Loopback server callback was invoked without a url. This is unexpected.", - }, - noAuthCodeInResponse: { - code: "no_auth_code_in_response", - desc: "No auth code found in the server response. Please check your network trace to determine what happened.", - }, - noLoopbackServerExists: { - code: "no_loopback_server_exists", - desc: "No loopback server exists yet.", - }, - loopbackServerAlreadyExists: { - code: "loopback_server_already_exists", - desc: "Loopback server already exists. Cannot create another.", - }, - loopbackServerTimeout: { - code: "loopback_server_timeout", - desc: "Timed out waiting for auth code listener to be registered.", - }, - stateNotFoundError: { - code: "state_not_found", - desc: "State not found. Please verify that the request originated from msal.", - }, - thumbprintMissing: { - code: "thumbprint_missing_from_client_certificate", - desc: "Client certificate does not contain a SHA-1 or SHA-256 thumbprint.", - }, - redirectUriNotSupported: { - code: "redirect_uri_not_supported", - desc: "RedirectUri is not supported in this scenario. Please remove redirectUri from the request.", - }, -}; -class NodeAuthError extends AuthError { - constructor(errorCode, errorMessage) { - super(errorCode, errorMessage); - this.name = "NodeAuthError"; - } - /** - * Creates an error thrown if loopback server address is of type string. - */ - static createInvalidLoopbackAddressTypeError() { - return new NodeAuthError(NodeAuthErrorMessage.invalidLoopbackAddressType.code, `${NodeAuthErrorMessage.invalidLoopbackAddressType.desc}`); - } - /** - * Creates an error thrown if the loopback server is unable to get a url. - */ - static createUnableToLoadRedirectUrlError() { - return new NodeAuthError(NodeAuthErrorMessage.unableToLoadRedirectUri.code, `${NodeAuthErrorMessage.unableToLoadRedirectUri.desc}`); - } - /** - * Creates an error thrown if the server response does not contain an auth code. - */ - static createNoAuthCodeInResponseError() { - return new NodeAuthError(NodeAuthErrorMessage.noAuthCodeInResponse.code, `${NodeAuthErrorMessage.noAuthCodeInResponse.desc}`); - } - /** - * Creates an error thrown if the loopback server has not been spun up yet. - */ - static createNoLoopbackServerExistsError() { - return new NodeAuthError(NodeAuthErrorMessage.noLoopbackServerExists.code, `${NodeAuthErrorMessage.noLoopbackServerExists.desc}`); - } - /** - * Creates an error thrown if a loopback server already exists when attempting to create another one. - */ - static createLoopbackServerAlreadyExistsError() { - return new NodeAuthError(NodeAuthErrorMessage.loopbackServerAlreadyExists.code, `${NodeAuthErrorMessage.loopbackServerAlreadyExists.desc}`); - } - /** - * Creates an error thrown if the loopback server times out registering the auth code listener. - */ - static createLoopbackServerTimeoutError() { - return new NodeAuthError(NodeAuthErrorMessage.loopbackServerTimeout.code, `${NodeAuthErrorMessage.loopbackServerTimeout.desc}`); - } - /** - * Creates an error thrown when the state is not present. - */ - static createStateNotFoundError() { - return new NodeAuthError(NodeAuthErrorMessage.stateNotFoundError.code, NodeAuthErrorMessage.stateNotFoundError.desc); - } - /** - * Creates an error thrown when client certificate was provided, but neither the SHA-1 or SHA-256 thumbprints were provided - */ - static createThumbprintMissingError() { - return new NodeAuthError(NodeAuthErrorMessage.thumbprintMissing.code, NodeAuthErrorMessage.thumbprintMissing.desc); - } - /** - * Creates an error thrown when redirectUri is provided in an unsupported scenario - */ - static createRedirectUriNotSupportedError() { - return new NodeAuthError(NodeAuthErrorMessage.redirectUriNotSupported.code, NodeAuthErrorMessage.redirectUriNotSupported.desc); - } -} - -export { NodeAuthError, NodeAuthErrorMessage }; -//# sourceMappingURL=NodeAuthError.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/index.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/index.mjs deleted file mode 100644 index ca192382..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/index.mjs +++ /dev/null @@ -1,20 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import * as internals from './internals.mjs'; -export { internals }; -export { PublicClientApplication } from './client/PublicClientApplication.mjs'; -export { ConfidentialClientApplication } from './client/ConfidentialClientApplication.mjs'; -export { ClientApplication } from './client/ClientApplication.mjs'; -export { ClientCredentialClient } from './client/ClientCredentialClient.mjs'; -export { DeviceCodeClient } from './client/DeviceCodeClient.mjs'; -export { OnBehalfOfClient } from './client/OnBehalfOfClient.mjs'; -export { ManagedIdentityApplication } from './client/ManagedIdentityApplication.mjs'; -export { UsernamePasswordClient } from './client/UsernamePasswordClient.mjs'; -export { ClientAssertion } from './client/ClientAssertion.mjs'; -export { TokenCache } from './cache/TokenCache.mjs'; -export { DistributedCachePlugin } from './cache/distributed/DistributedCachePlugin.mjs'; -export { ManagedIdentitySourceNames } from './utils/Constants.mjs'; -export { CryptoProvider } from './crypto/CryptoProvider.mjs'; -export { AuthError, AuthErrorCodes, AuthErrorMessage, AzureCloudInstance, ClientAuthError, ClientAuthErrorCodes, ClientAuthErrorMessage, ClientConfigurationError, ClientConfigurationErrorCodes, ClientConfigurationErrorMessage, InteractionRequiredAuthError, InteractionRequiredAuthErrorCodes, InteractionRequiredAuthErrorMessage, LogLevel, Logger, PromptValue, ProtocolMode, ResponseMode, ServerError, TokenCacheContext } from '@azure/msal-common/node'; -export { version } from './packageMetadata.mjs'; -//# sourceMappingURL=index.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/internals.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/internals.mjs deleted file mode 100644 index 05413102..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/internals.mjs +++ /dev/null @@ -1,14 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -export { Serializer } from './cache/serializer/Serializer.mjs'; -export { Deserializer } from './cache/serializer/Deserializer.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Warning: This set of exports is purely intended to be used by other MSAL libraries, and should be considered potentially unstable. We strongly discourage using them directly, you do so at your own risk. - * Breaking changes to these APIs will be shipped under a minor version, instead of a major version. - */ -//# sourceMappingURL=internals.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/network/HttpClient.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/network/HttpClient.mjs deleted file mode 100644 index 7b0669ec..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/network/HttpClient.mjs +++ /dev/null @@ -1,292 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { HttpStatus } from '@azure/msal-common/node'; -import { ProxyStatus, Constants, HttpMethod } from '../utils/Constants.mjs'; -import { NetworkUtils } from '../utils/NetworkUtils.mjs'; -import http from 'http'; -import https from 'https'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * This class implements the API for network requests. - */ -class HttpClient { - constructor(proxyUrl, customAgentOptions) { - this.proxyUrl = proxyUrl || ""; - this.customAgentOptions = customAgentOptions || {}; - } - /** - * Http Get request - * @param url - * @param options - */ - async sendGetRequestAsync(url, options, timeout) { - if (this.proxyUrl) { - return networkRequestViaProxy(url, this.proxyUrl, HttpMethod.GET, options, this.customAgentOptions, timeout); - } - else { - return networkRequestViaHttps(url, HttpMethod.GET, options, this.customAgentOptions, timeout); - } - } - /** - * Http Post request - * @param url - * @param options - */ - async sendPostRequestAsync(url, options) { - if (this.proxyUrl) { - return networkRequestViaProxy(url, this.proxyUrl, HttpMethod.POST, options, this.customAgentOptions); - } - else { - return networkRequestViaHttps(url, HttpMethod.POST, options, this.customAgentOptions); - } - } -} -const networkRequestViaProxy = (destinationUrlString, proxyUrlString, httpMethod, options, agentOptions, timeout) => { - const destinationUrl = new URL(destinationUrlString); - const proxyUrl = new URL(proxyUrlString); - // "method: connect" must be used to establish a connection to the proxy - const headers = options?.headers || {}; - const tunnelRequestOptions = { - host: proxyUrl.hostname, - port: proxyUrl.port, - method: "CONNECT", - path: destinationUrl.hostname, - headers: headers, - }; - if (agentOptions && Object.keys(agentOptions).length) { - tunnelRequestOptions.agent = new http.Agent(agentOptions); - } - // compose a request string for the socket - let postRequestStringContent = ""; - if (httpMethod === HttpMethod.POST) { - const body = options?.body || ""; - postRequestStringContent = - "Content-Type: application/x-www-form-urlencoded\r\n" + - `Content-Length: ${body.length}\r\n` + - `\r\n${body}`; - } - else { - // optional timeout is only for get requests (regionDiscovery, for example) - if (timeout) { - tunnelRequestOptions.timeout = timeout; - } - } - const outgoingRequestString = `${httpMethod.toUpperCase()} ${destinationUrl.href} HTTP/1.1\r\n` + - `Host: ${destinationUrl.host}\r\n` + - "Connection: close\r\n" + - postRequestStringContent + - "\r\n"; - return new Promise((resolve, reject) => { - const request = http.request(tunnelRequestOptions); - if (timeout) { - request.on("timeout", () => { - request.destroy(); - reject(new Error("Request time out")); - }); - } - request.end(); - // establish connection to the proxy - request.on("connect", (response, socket) => { - const proxyStatusCode = response?.statusCode || ProxyStatus.SERVER_ERROR; - if (proxyStatusCode < ProxyStatus.SUCCESS_RANGE_START || - proxyStatusCode > ProxyStatus.SUCCESS_RANGE_END) { - request.destroy(); - socket.destroy(); - reject(new Error(`Error connecting to proxy. Http status code: ${response.statusCode}. Http status message: ${response?.statusMessage || "Unknown"}`)); - } - // make a request over an HTTP tunnel - socket.write(outgoingRequestString); - const data = []; - socket.on("data", (chunk) => { - data.push(chunk); - }); - socket.on("end", () => { - // combine all received buffer streams into one buffer, and then into a string - const dataString = Buffer.concat([...data]).toString(); - // separate each line into it's own entry in an arry - const dataStringArray = dataString.split("\r\n"); - // the first entry will contain the statusCode and statusMessage - const httpStatusCode = parseInt(dataStringArray[0].split(" ")[1]); - // remove "HTTP/1.1" and the status code to get the status message - const statusMessage = dataStringArray[0] - .split(" ") - .slice(2) - .join(" "); - // the last entry will contain the body - const body = dataStringArray[dataStringArray.length - 1]; - // everything in between the first and last entries are the headers - const headersArray = dataStringArray.slice(1, dataStringArray.length - 2); - // build an object out of all the headers - const entries = new Map(); - headersArray.forEach((header) => { - /** - * the header might look like "Content-Length: 1531", but that is just a string - * it needs to be converted to a key/value pair - * split the string at the first instance of ":" - * there may be more than one ":" if the value of the header is supposed to be a JSON object - */ - const headerKeyValue = header.split(new RegExp(/:\s(.*)/s)); - const headerKey = headerKeyValue[0]; - let headerValue = headerKeyValue[1]; - // check if the value of the header is supposed to be a JSON object - try { - const object = JSON.parse(headerValue); - // if it is, then convert it from a string to a JSON object - if (object && typeof object === "object") { - headerValue = object; - } - } - catch (e) { - // otherwise, leave it as a string - } - entries.set(headerKey, headerValue); - }); - const headers = Object.fromEntries(entries); - const parsedHeaders = headers; - const networkResponse = NetworkUtils.getNetworkResponse(parsedHeaders, parseBody(httpStatusCode, statusMessage, parsedHeaders, body), httpStatusCode); - if ((httpStatusCode < HttpStatus.SUCCESS_RANGE_START || - httpStatusCode > HttpStatus.SUCCESS_RANGE_END) && - // do not destroy the request for the device code flow - networkResponse.body["error"] !== - Constants.AUTHORIZATION_PENDING) { - request.destroy(); - } - resolve(networkResponse); - }); - socket.on("error", (chunk) => { - request.destroy(); - socket.destroy(); - reject(new Error(chunk.toString())); - }); - }); - request.on("error", (chunk) => { - request.destroy(); - reject(new Error(chunk.toString())); - }); - }); -}; -const networkRequestViaHttps = (urlString, httpMethod, options, agentOptions, timeout) => { - const isPostRequest = httpMethod === HttpMethod.POST; - const body = options?.body || ""; - const url = new URL(urlString); - const headers = options?.headers || {}; - const customOptions = { - method: httpMethod, - headers: headers, - ...NetworkUtils.urlToHttpOptions(url), - }; - if (agentOptions && Object.keys(agentOptions).length) { - customOptions.agent = new https.Agent(agentOptions); - } - if (isPostRequest) { - // needed for post request to work - customOptions.headers = { - ...customOptions.headers, - "Content-Length": body.length, - }; - } - else { - // optional timeout is only for get requests (regionDiscovery, for example) - if (timeout) { - customOptions.timeout = timeout; - } - } - return new Promise((resolve, reject) => { - let request; - // managed identity sources use http instead of https - if (customOptions.protocol === "http:") { - request = http.request(customOptions); - } - else { - request = https.request(customOptions); - } - if (isPostRequest) { - request.write(body); - } - if (timeout) { - request.on("timeout", () => { - request.destroy(); - reject(new Error("Request time out")); - }); - } - request.end(); - request.on("response", (response) => { - const headers = response.headers; - const statusCode = response.statusCode; - const statusMessage = response.statusMessage; - const data = []; - response.on("data", (chunk) => { - data.push(chunk); - }); - response.on("end", () => { - // combine all received buffer streams into one buffer, and then into a string - const body = Buffer.concat([...data]).toString(); - const parsedHeaders = headers; - const networkResponse = NetworkUtils.getNetworkResponse(parsedHeaders, parseBody(statusCode, statusMessage, parsedHeaders, body), statusCode); - if ((statusCode < HttpStatus.SUCCESS_RANGE_START || - statusCode > HttpStatus.SUCCESS_RANGE_END) && - // do not destroy the request for the device code flow - networkResponse.body["error"] !== - Constants.AUTHORIZATION_PENDING) { - request.destroy(); - } - resolve(networkResponse); - }); - }); - request.on("error", (chunk) => { - request.destroy(); - reject(new Error(chunk.toString())); - }); - }); -}; -/** - * Check if extra parsing is needed on the repsonse from the server - * @param statusCode {number} the status code of the response from the server - * @param statusMessage {string | undefined} the status message of the response from the server - * @param headers {Record} the headers of the response from the server - * @param body {string} the body from the response of the server - * @returns {Object} JSON parsed body or error object - */ -const parseBody = (statusCode, statusMessage, headers, body) => { - /* - * Informational responses (100 – 199) - * Successful responses (200 – 299) - * Redirection messages (300 – 399) - * Client error responses (400 – 499) - * Server error responses (500 – 599) - */ - let parsedBody; - try { - parsedBody = JSON.parse(body); - } - catch (error) { - let errorType; - let errorDescriptionHelper; - if (statusCode >= HttpStatus.CLIENT_ERROR_RANGE_START && - statusCode <= HttpStatus.CLIENT_ERROR_RANGE_END) { - errorType = "client_error"; - errorDescriptionHelper = "A client"; - } - else if (statusCode >= HttpStatus.SERVER_ERROR_RANGE_START && - statusCode <= HttpStatus.SERVER_ERROR_RANGE_END) { - errorType = "server_error"; - errorDescriptionHelper = "A server"; - } - else { - errorType = "unknown_error"; - errorDescriptionHelper = "An unknown"; - } - parsedBody = { - error: errorType, - error_description: `${errorDescriptionHelper} error occured.\nHttp status code: ${statusCode}\nHttp status message: ${statusMessage || "Unknown"}\nHeaders: ${JSON.stringify(headers)}`, - }; - } - return parsedBody; -}; - -export { HttpClient }; -//# sourceMappingURL=HttpClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/network/HttpClientWithRetries.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/network/HttpClientWithRetries.mjs deleted file mode 100644 index 7ba67357..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/network/HttpClientWithRetries.mjs +++ /dev/null @@ -1,46 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { HeaderNames } from '@azure/msal-common/node'; -import { HttpMethod } from '../utils/Constants.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -class HttpClientWithRetries { - constructor(httpClientNoRetries, retryPolicy, logger) { - this.httpClientNoRetries = httpClientNoRetries; - this.retryPolicy = retryPolicy; - this.logger = logger; - } - async sendNetworkRequestAsyncHelper(httpMethod, url, options) { - if (httpMethod === HttpMethod.GET) { - return this.httpClientNoRetries.sendGetRequestAsync(url, options); - } - else { - return this.httpClientNoRetries.sendPostRequestAsync(url, options); - } - } - async sendNetworkRequestAsync(httpMethod, url, options) { - // the underlying network module (custom or HttpClient) will make the call - let response = await this.sendNetworkRequestAsyncHelper(httpMethod, url, options); - if ("isNewRequest" in this.retryPolicy) { - this.retryPolicy.isNewRequest = true; - } - let currentRetry = 0; - while (await this.retryPolicy.pauseForRetry(response.status, currentRetry, this.logger, response.headers[HeaderNames.RETRY_AFTER])) { - response = await this.sendNetworkRequestAsyncHelper(httpMethod, url, options); - currentRetry++; - } - return response; - } - async sendGetRequestAsync(url, options) { - return this.sendNetworkRequestAsync(HttpMethod.GET, url, options); - } - async sendPostRequestAsync(url, options) { - return this.sendNetworkRequestAsync(HttpMethod.POST, url, options); - } -} - -export { HttpClientWithRetries }; -//# sourceMappingURL=HttpClientWithRetries.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/network/LoopbackClient.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/network/LoopbackClient.mjs deleted file mode 100644 index 26e2647e..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/network/LoopbackClient.mjs +++ /dev/null @@ -1,92 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { Constants, UrlUtils, HttpStatus } from '@azure/msal-common/node'; -import http from 'http'; -import { NodeAuthError } from '../error/NodeAuthError.mjs'; -import { Constants as Constants$1 } from '../utils/Constants.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -class LoopbackClient { - /** - * Spins up a loopback server which returns the server response when the localhost redirectUri is hit - * @param successTemplate - * @param errorTemplate - * @returns - */ - async listenForAuthCode(successTemplate, errorTemplate) { - if (this.server) { - throw NodeAuthError.createLoopbackServerAlreadyExistsError(); - } - return new Promise((resolve, reject) => { - this.server = http.createServer((req, res) => { - const url = req.url; - if (!url) { - res.end(errorTemplate || - "Error occurred loading redirectUrl"); - reject(NodeAuthError.createUnableToLoadRedirectUrlError()); - return; - } - else if (url === Constants.FORWARD_SLASH) { - res.end(successTemplate || - "Auth code was successfully acquired. You can close this window now."); - return; - } - const redirectUri = this.getRedirectUri(); - const parsedUrl = new URL(url, redirectUri); - const authCodeResponse = UrlUtils.getDeserializedResponse(parsedUrl.search) || - {}; - if (authCodeResponse.code) { - res.writeHead(HttpStatus.REDIRECT, { - location: redirectUri, - }); // Prevent auth code from being saved in the browser history - res.end(); - } - if (authCodeResponse.error) { - res.end(errorTemplate || - `Error occurred: ${authCodeResponse.error}`); - } - resolve(authCodeResponse); - }); - this.server.listen(0, "127.0.0.1"); // Listen on any available port - }); - } - /** - * Get the port that the loopback server is running on - * @returns - */ - getRedirectUri() { - if (!this.server || !this.server.listening) { - throw NodeAuthError.createNoLoopbackServerExistsError(); - } - const address = this.server.address(); - if (!address || typeof address === "string" || !address.port) { - this.closeServer(); - throw NodeAuthError.createInvalidLoopbackAddressTypeError(); - } - const port = address && address.port; - return `${Constants$1.HTTP_PROTOCOL}${Constants$1.LOCALHOST}:${port}`; - } - /** - * Close the loopback server - */ - closeServer() { - if (this.server) { - // Only stops accepting new connections, server will close once open/idle connections are closed. - this.server.close(); - if (typeof this.server.closeAllConnections === "function") { - /* - * Close open/idle connections. This API is available in Node versions 18.2 and higher - */ - this.server.closeAllConnections(); - } - this.server.unref(); - this.server = undefined; - } - } -} - -export { LoopbackClient }; -//# sourceMappingURL=LoopbackClient.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/packageMetadata.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/packageMetadata.mjs deleted file mode 100644 index eeb69fb4..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/packageMetadata.mjs +++ /dev/null @@ -1,8 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -/* eslint-disable header/header */ -const name = "@azure/msal-node"; -const version = "3.8.1"; - -export { name, version }; -//# sourceMappingURL=packageMetadata.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/protocol/Authorize.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/protocol/Authorize.mjs deleted file mode 100644 index 85e90a92..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/protocol/Authorize.mjs +++ /dev/null @@ -1,43 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { AuthorizeProtocol, RequestParameterBuilder, ProtocolMode, OAuthResponseType } from '@azure/msal-common/node'; -import { Constants } from '../utils/Constants.mjs'; -import { version } from '../packageMetadata.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * Constructs the full /authorize URL with request parameters - * @param config - * @param authority - * @param request - * @param logger - * @returns - */ -function getAuthCodeRequestUrl(config, authority, request, logger) { - const parameters = AuthorizeProtocol.getStandardAuthorizeRequestParameters({ - ...config.auth, - authority: authority, - redirectUri: request.redirectUri || "", - }, request, logger); - RequestParameterBuilder.addLibraryInfo(parameters, { - sku: Constants.MSAL_SKU, - version: version, - cpu: process.arch || "", - os: process.platform || "", - }); - if (config.auth.protocolMode !== ProtocolMode.OIDC) { - RequestParameterBuilder.addApplicationTelemetry(parameters, config.telemetry.application); - } - RequestParameterBuilder.addResponseType(parameters, OAuthResponseType.CODE); - if (request.codeChallenge && request.codeChallengeMethod) { - RequestParameterBuilder.addCodeChallengeParams(parameters, request.codeChallenge, request.codeChallengeMethod); - } - RequestParameterBuilder.addExtraQueryParameters(parameters, request.extraQueryParameters || {}); - return AuthorizeProtocol.getAuthorizeUrl(authority, parameters, config.auth.encodeExtraQueryParams, request.extraQueryParameters); -} - -export { getAuthCodeRequestUrl }; -//# sourceMappingURL=Authorize.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/retry/DefaultManagedIdentityRetryPolicy.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/retry/DefaultManagedIdentityRetryPolicy.mjs deleted file mode 100644 index 67372a64..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/retry/DefaultManagedIdentityRetryPolicy.mjs +++ /dev/null @@ -1,49 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { HttpStatus } from '@azure/msal-common'; -import { LinearRetryStrategy } from './LinearRetryStrategy.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const DEFAULT_MANAGED_IDENTITY_MAX_RETRIES = 3; // referenced in unit test -const DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS = 1000; -const DEFAULT_MANAGED_IDENTITY_HTTP_STATUS_CODES_TO_RETRY_ON = [ - HttpStatus.NOT_FOUND, - HttpStatus.REQUEST_TIMEOUT, - HttpStatus.TOO_MANY_REQUESTS, - HttpStatus.SERVER_ERROR, - HttpStatus.SERVICE_UNAVAILABLE, - HttpStatus.GATEWAY_TIMEOUT, -]; -class DefaultManagedIdentityRetryPolicy { - constructor() { - this.linearRetryStrategy = new LinearRetryStrategy(); - } - /* - * this is defined here as a static variable despite being defined as a constant outside of the - * class because it needs to be overridden in the unit tests so that the unit tests run faster - */ - static get DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS() { - return DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS; - } - async pauseForRetry(httpStatusCode, currentRetry, logger, retryAfterHeader) { - if (DEFAULT_MANAGED_IDENTITY_HTTP_STATUS_CODES_TO_RETRY_ON.includes(httpStatusCode) && - currentRetry < DEFAULT_MANAGED_IDENTITY_MAX_RETRIES) { - const retryAfterDelay = this.linearRetryStrategy.calculateDelay(retryAfterHeader, DefaultManagedIdentityRetryPolicy.DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS); - logger.verbose(`Retrying request in ${retryAfterDelay}ms (retry attempt: ${currentRetry + 1})`); - // pause execution for the calculated delay - await new Promise((resolve) => { - // retryAfterHeader value of 0 evaluates to false, and DEFAULT_MANAGED_IDENTITY_RETRY_DELAY_MS will be used - return setTimeout(resolve, retryAfterDelay); - }); - return true; - } - // if the status code is not retriable or max retries have been reached, do not retry - return false; - } -} - -export { DEFAULT_MANAGED_IDENTITY_MAX_RETRIES, DefaultManagedIdentityRetryPolicy }; -//# sourceMappingURL=DefaultManagedIdentityRetryPolicy.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/retry/ExponentialRetryStrategy.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/retry/ExponentialRetryStrategy.mjs deleted file mode 100644 index 298d2aa4..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/retry/ExponentialRetryStrategy.mjs +++ /dev/null @@ -1,40 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -class ExponentialRetryStrategy { - constructor(minExponentialBackoff, maxExponentialBackoff, exponentialDeltaBackoff) { - this.minExponentialBackoff = minExponentialBackoff; - this.maxExponentialBackoff = maxExponentialBackoff; - this.exponentialDeltaBackoff = exponentialDeltaBackoff; - } - /** - * Calculates the exponential delay based on the current retry attempt. - * - * @param {number} currentRetry - The current retry attempt number. - * @returns {number} - The calculated exponential delay in milliseconds. - * - * The delay is calculated using the formula: - * - If `currentRetry` is 0, it returns the minimum backoff time. - * - Otherwise, it calculates the delay as the minimum of: - * - `(2^(currentRetry - 1)) * deltaBackoff` - * - `maxBackoff` - * - * This ensures that the delay increases exponentially with each retry attempt, - * but does not exceed the maximum backoff time. - */ - calculateDelay(currentRetry) { - // Attempt 1 - if (currentRetry === 0) { - return this.minExponentialBackoff; - } - // Attempt 2+ - const exponentialDelay = Math.min(Math.pow(2, currentRetry - 1) * this.exponentialDeltaBackoff, this.maxExponentialBackoff); - return exponentialDelay; - } -} - -export { ExponentialRetryStrategy }; -//# sourceMappingURL=ExponentialRetryStrategy.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/retry/ImdsRetryPolicy.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/retry/ImdsRetryPolicy.mjs deleted file mode 100644 index 92633d46..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/retry/ImdsRetryPolicy.mjs +++ /dev/null @@ -1,90 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { HttpStatus } from '@azure/msal-common'; -import { ExponentialRetryStrategy } from './ExponentialRetryStrategy.mjs'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -const HTTP_STATUS_400_CODES_FOR_EXPONENTIAL_STRATEGY = [ - HttpStatus.NOT_FOUND, - HttpStatus.REQUEST_TIMEOUT, - HttpStatus.GONE, - HttpStatus.TOO_MANY_REQUESTS, -]; -const EXPONENTIAL_STRATEGY_NUM_RETRIES = 3; -const LINEAR_STRATEGY_NUM_RETRIES = 7; -const MIN_EXPONENTIAL_BACKOFF_MS = 1000; -const MAX_EXPONENTIAL_BACKOFF_MS = 4000; -const EXPONENTIAL_DELTA_BACKOFF_MS = 2000; -const HTTP_STATUS_GONE_RETRY_AFTER_MS = 10 * 1000; // 10 seconds -class ImdsRetryPolicy { - constructor() { - this.exponentialRetryStrategy = new ExponentialRetryStrategy(ImdsRetryPolicy.MIN_EXPONENTIAL_BACKOFF_MS, ImdsRetryPolicy.MAX_EXPONENTIAL_BACKOFF_MS, ImdsRetryPolicy.EXPONENTIAL_DELTA_BACKOFF_MS); - } - /* - * these are defined here as static variables despite being defined as constants outside of the - * class because they need to be overridden in the unit tests so that the unit tests run faster - */ - static get MIN_EXPONENTIAL_BACKOFF_MS() { - return MIN_EXPONENTIAL_BACKOFF_MS; - } - static get MAX_EXPONENTIAL_BACKOFF_MS() { - return MAX_EXPONENTIAL_BACKOFF_MS; - } - static get EXPONENTIAL_DELTA_BACKOFF_MS() { - return EXPONENTIAL_DELTA_BACKOFF_MS; - } - static get HTTP_STATUS_GONE_RETRY_AFTER_MS() { - return HTTP_STATUS_GONE_RETRY_AFTER_MS; - } - set isNewRequest(value) { - this._isNewRequest = value; - } - /** - * Pauses execution for a calculated delay before retrying a request. - * - * @param httpStatusCode - The HTTP status code of the response. - * @param currentRetry - The current retry attempt number. - * @param retryAfterHeader - The value of the "retry-after" header from the response. - * @returns A promise that resolves to a boolean indicating whether a retry should be attempted. - */ - async pauseForRetry(httpStatusCode, currentRetry, logger) { - if (this._isNewRequest) { - this._isNewRequest = false; - // calculate the maxRetries based on the status code, once per request - this.maxRetries = - httpStatusCode === HttpStatus.GONE - ? LINEAR_STRATEGY_NUM_RETRIES - : EXPONENTIAL_STRATEGY_NUM_RETRIES; - } - /** - * (status code is one of the retriable 400 status code - * or - * status code is >= 500 and <= 599) - * and - * current count of retries is less than the max number of retries - */ - if ((HTTP_STATUS_400_CODES_FOR_EXPONENTIAL_STRATEGY.includes(httpStatusCode) || - (httpStatusCode >= HttpStatus.SERVER_ERROR_RANGE_START && - httpStatusCode <= HttpStatus.SERVER_ERROR_RANGE_END && - currentRetry < this.maxRetries)) && - currentRetry < this.maxRetries) { - const retryAfterDelay = httpStatusCode === HttpStatus.GONE - ? ImdsRetryPolicy.HTTP_STATUS_GONE_RETRY_AFTER_MS - : this.exponentialRetryStrategy.calculateDelay(currentRetry); - logger.verbose(`Retrying request in ${retryAfterDelay}ms (retry attempt: ${currentRetry + 1})`); - // pause execution for the calculated delay - await new Promise((resolve) => { - return setTimeout(resolve, retryAfterDelay); - }); - return true; - } - // if the status code is not retriable or max retries have been reached, do not retry - return false; - } -} - -export { ImdsRetryPolicy }; -//# sourceMappingURL=ImdsRetryPolicy.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/retry/LinearRetryStrategy.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/retry/LinearRetryStrategy.mjs deleted file mode 100644 index dbc73b05..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/retry/LinearRetryStrategy.mjs +++ /dev/null @@ -1,36 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -class LinearRetryStrategy { - /** - * Calculates the number of milliseconds to sleep based on the `retry-after` HTTP header. - * - * @param retryHeader - The value of the `retry-after` HTTP header. This can be either a number of seconds - * or an HTTP date string. - * @returns The number of milliseconds to sleep before retrying the request. If the `retry-after` header is not - * present or cannot be parsed, returns 0. - */ - calculateDelay(retryHeader, minimumDelay) { - if (!retryHeader) { - return minimumDelay; - } - // retry-after header is in seconds - let millisToSleep = Math.round(parseFloat(retryHeader) * 1000); - /* - * retry-after header is in HTTP Date format - * , :: GMT - */ - if (isNaN(millisToSleep)) { - // .valueOf() is needed to subtract dates in TypeScript - millisToSleep = - new Date(retryHeader).valueOf() - new Date().valueOf(); - } - return Math.max(minimumDelay, millisToSleep); - } -} - -export { LinearRetryStrategy }; -//# sourceMappingURL=LinearRetryStrategy.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/utils/Constants.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/utils/Constants.mjs deleted file mode 100644 index 2fb43923..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/utils/Constants.mjs +++ /dev/null @@ -1,153 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { HttpStatus } from '@azure/msal-common/node'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -// MSI Constants. Docs for MSI are available here https://docs.microsoft.com/azure/app-service/overview-managed-identity -const DEFAULT_MANAGED_IDENTITY_ID = "system_assigned_managed_identity"; -const MANAGED_IDENTITY_DEFAULT_TENANT = "managed_identity"; -const DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY = `https://login.microsoftonline.com/${MANAGED_IDENTITY_DEFAULT_TENANT}/`; -/** - * Managed Identity Headers - used in network requests - */ -const ManagedIdentityHeaders = { - AUTHORIZATION_HEADER_NAME: "Authorization", - METADATA_HEADER_NAME: "Metadata", - APP_SERVICE_SECRET_HEADER_NAME: "X-IDENTITY-HEADER", - ML_AND_SF_SECRET_HEADER_NAME: "secret", -}; -/** - * Managed Identity Query Parameters - used in network requests - */ -const ManagedIdentityQueryParameters = { - API_VERSION: "api-version", - RESOURCE: "resource", - SHA256_TOKEN_TO_REFRESH: "token_sha256_to_refresh", - XMS_CC: "xms_cc", -}; -/** - * Managed Identity Environment Variable Names - */ -const ManagedIdentityEnvironmentVariableNames = { - AZURE_POD_IDENTITY_AUTHORITY_HOST: "AZURE_POD_IDENTITY_AUTHORITY_HOST", - DEFAULT_IDENTITY_CLIENT_ID: "DEFAULT_IDENTITY_CLIENT_ID", - IDENTITY_ENDPOINT: "IDENTITY_ENDPOINT", - IDENTITY_HEADER: "IDENTITY_HEADER", - IDENTITY_SERVER_THUMBPRINT: "IDENTITY_SERVER_THUMBPRINT", - IMDS_ENDPOINT: "IMDS_ENDPOINT", - MSI_ENDPOINT: "MSI_ENDPOINT", - MSI_SECRET: "MSI_SECRET", -}; -/** - * Managed Identity Source Names - * @public - */ -const ManagedIdentitySourceNames = { - APP_SERVICE: "AppService", - AZURE_ARC: "AzureArc", - CLOUD_SHELL: "CloudShell", - DEFAULT_TO_IMDS: "DefaultToImds", - IMDS: "Imds", - MACHINE_LEARNING: "MachineLearning", - SERVICE_FABRIC: "ServiceFabric", -}; -/** - * Managed Identity Ids - */ -const ManagedIdentityIdType = { - SYSTEM_ASSIGNED: "system-assigned", - USER_ASSIGNED_CLIENT_ID: "user-assigned-client-id", - USER_ASSIGNED_RESOURCE_ID: "user-assigned-resource-id", - USER_ASSIGNED_OBJECT_ID: "user-assigned-object-id", -}; -/** - * http methods - */ -const HttpMethod = { - GET: "get", - POST: "post", -}; -const ProxyStatus = { - SUCCESS_RANGE_START: HttpStatus.SUCCESS_RANGE_START, - SUCCESS_RANGE_END: HttpStatus.SUCCESS_RANGE_END, - SERVER_ERROR: HttpStatus.SERVER_ERROR, -}; -/** - * Constants used for region discovery - */ -const REGION_ENVIRONMENT_VARIABLE = "REGION_NAME"; -const MSAL_FORCE_REGION = "MSAL_FORCE_REGION"; -/** - * Constant used for PKCE - */ -const RANDOM_OCTET_SIZE = 32; -/** - * Constants used in PKCE - */ -const Hash = { - SHA256: "sha256", -}; -/** - * Constants for encoding schemes - */ -const CharSet = { - CV_CHARSET: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~", -}; -/** - * Cache Constants - */ -const CACHE = { - KEY_SEPARATOR: "-", -}; -/** - * Constants - */ -const Constants = { - MSAL_SKU: "msal.js.node", - JWT_BEARER_ASSERTION_TYPE: "urn:ietf:params:oauth:client-assertion-type:jwt-bearer", - AUTHORIZATION_PENDING: "authorization_pending", - HTTP_PROTOCOL: "http://", - LOCALHOST: "localhost", -}; -/** - * API Codes for Telemetry purposes. - * Before adding a new code you must claim it in the MSAL Telemetry tracker as these number spaces are shared across all MSALs - * 0-99 Silent Flow - * 600-699 Device Code Flow - * 800-899 Auth Code Flow - */ -const ApiId = { - acquireTokenSilent: 62, - acquireTokenByUsernamePassword: 371, - acquireTokenByDeviceCode: 671, - acquireTokenByClientCredential: 771, - acquireTokenByCode: 871, - acquireTokenByRefreshToken: 872, -}; -/** - * JWT constants - */ -const JwtConstants = { - RSA_256: "RS256", - PSS_256: "PS256", - X5T_256: "x5t#S256", - X5T: "x5t", - X5C: "x5c", - AUDIENCE: "aud", - EXPIRATION_TIME: "exp", - ISSUER: "iss", - SUBJECT: "sub", - NOT_BEFORE: "nbf", - JWT_ID: "jti", -}; -const LOOPBACK_SERVER_CONSTANTS = { - INTERVAL_MS: 100, - TIMEOUT_MS: 5000, -}; -const AZURE_ARC_SECRET_FILE_MAX_SIZE_BYTES = 4096; // 4 KB - -export { AZURE_ARC_SECRET_FILE_MAX_SIZE_BYTES, ApiId, CACHE, CharSet, Constants, DEFAULT_AUTHORITY_FOR_MANAGED_IDENTITY, DEFAULT_MANAGED_IDENTITY_ID, Hash, HttpMethod, JwtConstants, LOOPBACK_SERVER_CONSTANTS, MANAGED_IDENTITY_DEFAULT_TENANT, MSAL_FORCE_REGION, ManagedIdentityEnvironmentVariableNames, ManagedIdentityHeaders, ManagedIdentityIdType, ManagedIdentityQueryParameters, ManagedIdentitySourceNames, ProxyStatus, RANDOM_OCTET_SIZE, REGION_ENVIRONMENT_VARIABLE }; -//# sourceMappingURL=Constants.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/utils/EncodingUtils.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/utils/EncodingUtils.mjs deleted file mode 100644 index 8a87a890..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/utils/EncodingUtils.mjs +++ /dev/null @@ -1,51 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -import { EncodingTypes, Constants } from '@azure/msal-common/node'; - -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -class EncodingUtils { - /** - * 'utf8': Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8. - * 'base64': Base64 encoding. - * - * @param str text - */ - static base64Encode(str, encoding) { - return Buffer.from(str, encoding).toString(EncodingTypes.BASE64); - } - /** - * encode a URL - * @param str - */ - static base64EncodeUrl(str, encoding) { - return EncodingUtils.base64Encode(str, encoding) - .replace(/=/g, Constants.EMPTY_STRING) - .replace(/\+/g, "-") - .replace(/\//g, "_"); - } - /** - * 'utf8': Multibyte encoded Unicode characters. Many web pages and other document formats use UTF-8. - * 'base64': Base64 encoding. - * - * @param base64Str Base64 encoded text - */ - static base64Decode(base64Str) { - return Buffer.from(base64Str, EncodingTypes.BASE64).toString("utf8"); - } - /** - * @param base64Str Base64 encoded Url - */ - static base64DecodeUrl(base64Str) { - let str = base64Str.replace(/-/g, "+").replace(/_/g, "/"); - while (str.length % 4) { - str += "="; - } - return EncodingUtils.base64Decode(str); - } -} - -export { EncodingUtils }; -//# sourceMappingURL=EncodingUtils.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/utils/NetworkUtils.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/utils/NetworkUtils.mjs deleted file mode 100644 index 5f8de210..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/utils/NetworkUtils.mjs +++ /dev/null @@ -1,43 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -class NetworkUtils { - static getNetworkResponse(headers, body, statusCode) { - return { - headers: headers, - body: body, - status: statusCode, - }; - } - /* - * Utility function that converts a URL object into an ordinary options object as expected by the - * http.request and https.request APIs. - * https://github.com/nodejs/node/blob/main/lib/internal/url.js#L1090 - */ - static urlToHttpOptions(url) { - const options = { - protocol: url.protocol, - hostname: url.hostname && url.hostname.startsWith("[") - ? url.hostname.slice(1, -1) - : url.hostname, - hash: url.hash, - search: url.search, - pathname: url.pathname, - path: `${url.pathname || ""}${url.search || ""}`, - href: url.href, - }; - if (url.port !== "") { - options.port = Number(url.port); - } - if (url.username || url.password) { - options.auth = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`; - } - return options; - } -} - -export { NetworkUtils }; -//# sourceMappingURL=NetworkUtils.mjs.map diff --git a/claude-code-source/node_modules/@azure/msal-node/dist/utils/TimeUtils.mjs b/claude-code-source/node_modules/@azure/msal-node/dist/utils/TimeUtils.mjs deleted file mode 100644 index 6e3328dd..00000000 --- a/claude-code-source/node_modules/@azure/msal-node/dist/utils/TimeUtils.mjs +++ /dev/null @@ -1,23 +0,0 @@ -/*! @azure/msal-node v3.8.1 2025-10-29 */ -'use strict'; -/* - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. - */ -/** - * @internal - * Checks if a given date string is in ISO 8601 format. - * - * @param dateString - The date string to be checked. - * @returns boolean - Returns true if the date string is in ISO 8601 format, otherwise false. - */ -function isIso8601(dateString) { - if (typeof dateString !== "string") { - return false; - } - const date = new Date(dateString); - return !isNaN(date.getTime()) && date.toISOString() === dateString; -} - -export { isIso8601 }; -//# sourceMappingURL=TimeUtils.mjs.map diff --git a/claude-code-source/node_modules/@commander-js/extra-typings/esm.mjs b/claude-code-source/node_modules/@commander-js/extra-typings/esm.mjs deleted file mode 100644 index cfb03d5c..00000000 --- a/claude-code-source/node_modules/@commander-js/extra-typings/esm.mjs +++ /dev/null @@ -1,16 +0,0 @@ -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; diff --git a/claude-code-source/node_modules/@commander-js/extra-typings/index.js b/claude-code-source/node_modules/@commander-js/extra-typings/index.js deleted file mode 100644 index 2dbceeed..00000000 --- a/claude-code-source/node_modules/@commander-js/extra-typings/index.js +++ /dev/null @@ -1,28 +0,0 @@ -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); diff --git a/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/GrowthBook.mjs b/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/GrowthBook.mjs deleted file mode 100644 index b902a53d..00000000 --- a/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/GrowthBook.mjs +++ /dev/null @@ -1,829 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/core.mjs b/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/core.mjs deleted file mode 100644 index 680d131f..00000000 --- a/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/core.mjs +++ /dev/null @@ -1,879 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/feature-repository.mjs b/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/feature-repository.mjs deleted file mode 100644 index 65770931..00000000 --- a/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/feature-repository.mjs +++ /dev/null @@ -1,488 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/index.mjs b/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/index.mjs deleted file mode 100644 index 9344a239..00000000 --- a/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/index.mjs +++ /dev/null @@ -1,8 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/mongrule.mjs b/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/mongrule.mjs deleted file mode 100644 index d7a62b07..00000000 --- a/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/mongrule.mjs +++ /dev/null @@ -1,214 +0,0 @@ -/* 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/util.mjs b/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/util.mjs deleted file mode 100644 index 44dd9a6f..00000000 --- a/claude-code-source/node_modules/@growthbook/growthbook/dist/esm/util.mjs +++ /dev/null @@ -1,312 +0,0 @@ -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 diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/admin.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/admin.js deleted file mode 100644 index 6189c52c..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/admin.js +++ /dev/null @@ -1,30 +0,0 @@ -"use strict"; -/* - * Copyright 2021 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.registerAdminService = registerAdminService; -exports.addAdminServicesToServer = addAdminServicesToServer; -const registeredAdminServices = []; -function registerAdminService(getServiceDefinition, getHandlers) { - registeredAdminServices.push({ getServiceDefinition, getHandlers }); -} -function addAdminServicesToServer(server) { - for (const { getServiceDefinition, getHandlers } of registeredAdminServices) { - server.addService(getServiceDefinition(), getHandlers()); - } -} -//# sourceMappingURL=admin.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/backoff-timeout.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/backoff-timeout.js deleted file mode 100644 index b4721f30..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/backoff-timeout.js +++ /dev/null @@ -1,191 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BackoffTimeout = void 0; -const constants_1 = require("./constants"); -const logging = require("./logging"); -const TRACER_NAME = 'backoff'; -const INITIAL_BACKOFF_MS = 1000; -const BACKOFF_MULTIPLIER = 1.6; -const MAX_BACKOFF_MS = 120000; -const BACKOFF_JITTER = 0.2; -/** - * Get a number uniformly at random in the range [min, max) - * @param min - * @param max - */ -function uniformRandom(min, max) { - return Math.random() * (max - min) + min; -} -class BackoffTimeout { - constructor(callback, options) { - this.callback = callback; - /** - * The delay time at the start, and after each reset. - */ - this.initialDelay = INITIAL_BACKOFF_MS; - /** - * The exponential backoff multiplier. - */ - this.multiplier = BACKOFF_MULTIPLIER; - /** - * The maximum delay time - */ - this.maxDelay = MAX_BACKOFF_MS; - /** - * The maximum fraction by which the delay time can randomly vary after - * applying the multiplier. - */ - this.jitter = BACKOFF_JITTER; - /** - * Indicates whether the timer is currently running. - */ - this.running = false; - /** - * Indicates whether the timer should keep the Node process running if no - * other async operation is doing so. - */ - this.hasRef = true; - /** - * The time that the currently running timer was started. Only valid if - * running is true. - */ - this.startTime = new Date(); - /** - * The approximate time that the currently running timer will end. Only valid - * if running is true. - */ - this.endTime = new Date(); - this.id = BackoffTimeout.getNextId(); - if (options) { - if (options.initialDelay) { - this.initialDelay = options.initialDelay; - } - if (options.multiplier) { - this.multiplier = options.multiplier; - } - if (options.jitter) { - this.jitter = options.jitter; - } - if (options.maxDelay) { - this.maxDelay = options.maxDelay; - } - } - this.trace('constructed initialDelay=' + this.initialDelay + ' multiplier=' + this.multiplier + ' jitter=' + this.jitter + ' maxDelay=' + this.maxDelay); - this.nextDelay = this.initialDelay; - this.timerId = setTimeout(() => { }, 0); - clearTimeout(this.timerId); - } - static getNextId() { - return this.nextId++; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '{' + this.id + '} ' + text); - } - runTimer(delay) { - var _a, _b; - this.trace('runTimer(delay=' + delay + ')'); - this.endTime = this.startTime; - this.endTime.setMilliseconds(this.endTime.getMilliseconds() + delay); - clearTimeout(this.timerId); - this.timerId = setTimeout(() => { - this.trace('timer fired'); - this.running = false; - this.callback(); - }, delay); - if (!this.hasRef) { - (_b = (_a = this.timerId).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - } - /** - * Call the callback after the current amount of delay time - */ - runOnce() { - this.trace('runOnce()'); - this.running = true; - this.startTime = new Date(); - this.runTimer(this.nextDelay); - const nextBackoff = Math.min(this.nextDelay * this.multiplier, this.maxDelay); - const jitterMagnitude = nextBackoff * this.jitter; - this.nextDelay = - nextBackoff + uniformRandom(-jitterMagnitude, jitterMagnitude); - } - /** - * Stop the timer. The callback will not be called until `runOnce` is called - * again. - */ - stop() { - this.trace('stop()'); - clearTimeout(this.timerId); - this.running = false; - } - /** - * Reset the delay time to its initial value. If the timer is still running, - * retroactively apply that reset to the current timer. - */ - reset() { - this.trace('reset() running=' + this.running); - this.nextDelay = this.initialDelay; - if (this.running) { - const now = new Date(); - const newEndTime = this.startTime; - newEndTime.setMilliseconds(newEndTime.getMilliseconds() + this.nextDelay); - clearTimeout(this.timerId); - if (now < newEndTime) { - this.runTimer(newEndTime.getTime() - now.getTime()); - } - else { - this.running = false; - } - } - } - /** - * Check whether the timer is currently running. - */ - isRunning() { - return this.running; - } - /** - * Set that while the timer is running, it should keep the Node process - * running. - */ - ref() { - var _a, _b; - this.hasRef = true; - (_b = (_a = this.timerId).ref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - /** - * Set that while the timer is running, it should not keep the Node process - * running. - */ - unref() { - var _a, _b; - this.hasRef = false; - (_b = (_a = this.timerId).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - /** - * Get the approximate timestamp of when the timer will fire. Only valid if - * this.isRunning() is true. - */ - getEndTime() { - return this.endTime; - } -} -exports.BackoffTimeout = BackoffTimeout; -BackoffTimeout.nextId = 0; -//# sourceMappingURL=backoff-timeout.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/call-credentials.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/call-credentials.js deleted file mode 100644 index 67b92660..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/call-credentials.js +++ /dev/null @@ -1,153 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CallCredentials = void 0; -const metadata_1 = require("./metadata"); -function isCurrentOauth2Client(client) { - return ('getRequestHeaders' in client && - typeof client.getRequestHeaders === 'function'); -} -/** - * A class that represents a generic method of adding authentication-related - * metadata on a per-request basis. - */ -class CallCredentials { - /** - * Creates a new CallCredentials object from a given function that generates - * Metadata objects. - * @param metadataGenerator A function that accepts a set of options, and - * generates a Metadata object based on these options, which is passed back - * to the caller via a supplied (err, metadata) callback. - */ - static createFromMetadataGenerator(metadataGenerator) { - return new SingleCallCredentials(metadataGenerator); - } - /** - * Create a gRPC credential from a Google credential object. - * @param googleCredentials The authentication client to use. - * @return The resulting CallCredentials object. - */ - static createFromGoogleCredential(googleCredentials) { - return CallCredentials.createFromMetadataGenerator((options, callback) => { - let getHeaders; - if (isCurrentOauth2Client(googleCredentials)) { - getHeaders = googleCredentials.getRequestHeaders(options.service_url); - } - else { - getHeaders = new Promise((resolve, reject) => { - googleCredentials.getRequestMetadata(options.service_url, (err, headers) => { - if (err) { - reject(err); - return; - } - if (!headers) { - reject(new Error('Headers not set by metadata plugin')); - return; - } - resolve(headers); - }); - }); - } - getHeaders.then(headers => { - const metadata = new metadata_1.Metadata(); - for (const key of Object.keys(headers)) { - metadata.add(key, headers[key]); - } - callback(null, metadata); - }, err => { - callback(err); - }); - }); - } - static createEmpty() { - return new EmptyCallCredentials(); - } -} -exports.CallCredentials = CallCredentials; -class ComposedCallCredentials extends CallCredentials { - constructor(creds) { - super(); - this.creds = creds; - } - async generateMetadata(options) { - const base = new metadata_1.Metadata(); - const generated = await Promise.all(this.creds.map(cred => cred.generateMetadata(options))); - for (const gen of generated) { - base.merge(gen); - } - return base; - } - compose(other) { - return new ComposedCallCredentials(this.creds.concat([other])); - } - _equals(other) { - if (this === other) { - return true; - } - if (other instanceof ComposedCallCredentials) { - return this.creds.every((value, index) => value._equals(other.creds[index])); - } - else { - return false; - } - } -} -class SingleCallCredentials extends CallCredentials { - constructor(metadataGenerator) { - super(); - this.metadataGenerator = metadataGenerator; - } - generateMetadata(options) { - return new Promise((resolve, reject) => { - this.metadataGenerator(options, (err, metadata) => { - if (metadata !== undefined) { - resolve(metadata); - } - else { - reject(err); - } - }); - }); - } - compose(other) { - return new ComposedCallCredentials([this, other]); - } - _equals(other) { - if (this === other) { - return true; - } - if (other instanceof SingleCallCredentials) { - return this.metadataGenerator === other.metadataGenerator; - } - else { - return false; - } - } -} -class EmptyCallCredentials extends CallCredentials { - generateMetadata(options) { - return Promise.resolve(new metadata_1.Metadata()); - } - compose(other) { - return other; - } - _equals(other) { - return other instanceof EmptyCallCredentials; - } -} -//# sourceMappingURL=call-credentials.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/call-interface.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/call-interface.js deleted file mode 100644 index 88abb512..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/call-interface.js +++ /dev/null @@ -1,100 +0,0 @@ -"use strict"; -/* - * Copyright 2022 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.InterceptingListenerImpl = void 0; -exports.statusOrFromValue = statusOrFromValue; -exports.statusOrFromError = statusOrFromError; -exports.isInterceptingListener = isInterceptingListener; -const metadata_1 = require("./metadata"); -function statusOrFromValue(value) { - return { - ok: true, - value: value - }; -} -function statusOrFromError(error) { - var _a; - return { - ok: false, - error: Object.assign(Object.assign({}, error), { metadata: (_a = error.metadata) !== null && _a !== void 0 ? _a : new metadata_1.Metadata() }) - }; -} -function isInterceptingListener(listener) { - return (listener.onReceiveMetadata !== undefined && - listener.onReceiveMetadata.length === 1); -} -class InterceptingListenerImpl { - constructor(listener, nextListener) { - this.listener = listener; - this.nextListener = nextListener; - this.processingMetadata = false; - this.hasPendingMessage = false; - this.processingMessage = false; - this.pendingStatus = null; - } - processPendingMessage() { - if (this.hasPendingMessage) { - this.nextListener.onReceiveMessage(this.pendingMessage); - this.pendingMessage = null; - this.hasPendingMessage = false; - } - } - processPendingStatus() { - if (this.pendingStatus) { - this.nextListener.onReceiveStatus(this.pendingStatus); - } - } - onReceiveMetadata(metadata) { - this.processingMetadata = true; - this.listener.onReceiveMetadata(metadata, metadata => { - this.processingMetadata = false; - this.nextListener.onReceiveMetadata(metadata); - this.processPendingMessage(); - this.processPendingStatus(); - }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onReceiveMessage(message) { - /* If this listener processes messages asynchronously, the last message may - * be reordered with respect to the status */ - this.processingMessage = true; - this.listener.onReceiveMessage(message, msg => { - this.processingMessage = false; - if (this.processingMetadata) { - this.pendingMessage = msg; - this.hasPendingMessage = true; - } - else { - this.nextListener.onReceiveMessage(msg); - this.processPendingStatus(); - } - }); - } - onReceiveStatus(status) { - this.listener.onReceiveStatus(status, processedStatus => { - if (this.processingMetadata || this.processingMessage) { - this.pendingStatus = processedStatus; - } - else { - this.nextListener.onReceiveStatus(processedStatus); - } - }); - } -} -exports.InterceptingListenerImpl = InterceptingListenerImpl; -//# sourceMappingURL=call-interface.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/call-number.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/call-number.js deleted file mode 100644 index ed8bcdfc..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/call-number.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -/* - * Copyright 2022 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getNextCallNumber = getNextCallNumber; -let nextCallNumber = 0; -function getNextCallNumber() { - return nextCallNumber++; -} -//# sourceMappingURL=call-number.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/call.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/call.js deleted file mode 100644 index ff6d1793..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/call.js +++ /dev/null @@ -1,152 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ClientDuplexStreamImpl = exports.ClientWritableStreamImpl = exports.ClientReadableStreamImpl = exports.ClientUnaryCallImpl = void 0; -exports.callErrorFromStatus = callErrorFromStatus; -const events_1 = require("events"); -const stream_1 = require("stream"); -const constants_1 = require("./constants"); -/** - * Construct a ServiceError from a StatusObject. This function exists primarily - * as an attempt to make the error stack trace clearly communicate that the - * error is not necessarily a problem in gRPC itself. - * @param status - */ -function callErrorFromStatus(status, callerStack) { - const message = `${status.code} ${constants_1.Status[status.code]}: ${status.details}`; - const error = new Error(message); - const stack = `${error.stack}\nfor call at\n${callerStack}`; - return Object.assign(new Error(message), status, { stack }); -} -class ClientUnaryCallImpl extends events_1.EventEmitter { - constructor() { - super(); - } - cancel() { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client'); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown'; - } - getAuthContext() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; - } -} -exports.ClientUnaryCallImpl = ClientUnaryCallImpl; -class ClientReadableStreamImpl extends stream_1.Readable { - constructor(deserialize) { - super({ objectMode: true }); - this.deserialize = deserialize; - } - cancel() { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client'); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown'; - } - getAuthContext() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; - } - _read(_size) { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.startRead(); - } -} -exports.ClientReadableStreamImpl = ClientReadableStreamImpl; -class ClientWritableStreamImpl extends stream_1.Writable { - constructor(serialize) { - super({ objectMode: true }); - this.serialize = serialize; - } - cancel() { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client'); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown'; - } - getAuthContext() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; - } - _write(chunk, encoding, cb) { - var _a; - const context = { - callback: cb, - }; - const flags = Number(encoding); - if (!Number.isNaN(flags)) { - context.flags = flags; - } - (_a = this.call) === null || _a === void 0 ? void 0 : _a.sendMessageWithContext(context, chunk); - } - _final(cb) { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.halfClose(); - cb(); - } -} -exports.ClientWritableStreamImpl = ClientWritableStreamImpl; -class ClientDuplexStreamImpl extends stream_1.Duplex { - constructor(serialize, deserialize) { - super({ objectMode: true }); - this.serialize = serialize; - this.deserialize = deserialize; - } - cancel() { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client'); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown'; - } - getAuthContext() { - var _a, _b; - return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getAuthContext()) !== null && _b !== void 0 ? _b : null; - } - _read(_size) { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.startRead(); - } - _write(chunk, encoding, cb) { - var _a; - const context = { - callback: cb, - }; - const flags = Number(encoding); - if (!Number.isNaN(flags)) { - context.flags = flags; - } - (_a = this.call) === null || _a === void 0 ? void 0 : _a.sendMessageWithContext(context, chunk); - } - _final(cb) { - var _a; - (_a = this.call) === null || _a === void 0 ? void 0 : _a.halfClose(); - cb(); - } -} -exports.ClientDuplexStreamImpl = ClientDuplexStreamImpl; -//# sourceMappingURL=call.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/certificate-provider.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/certificate-provider.js deleted file mode 100644 index 75cd0f82..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/certificate-provider.js +++ /dev/null @@ -1,141 +0,0 @@ -"use strict"; -/* - * Copyright 2024 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.FileWatcherCertificateProvider = void 0; -const fs = require("fs"); -const logging = require("./logging"); -const constants_1 = require("./constants"); -const util_1 = require("util"); -const TRACER_NAME = 'certificate_provider'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -const readFilePromise = (0, util_1.promisify)(fs.readFile); -class FileWatcherCertificateProvider { - constructor(config) { - this.config = config; - this.refreshTimer = null; - this.fileResultPromise = null; - this.latestCaUpdate = undefined; - this.caListeners = new Set(); - this.latestIdentityUpdate = undefined; - this.identityListeners = new Set(); - this.lastUpdateTime = null; - if ((config.certificateFile === undefined) !== (config.privateKeyFile === undefined)) { - throw new Error('certificateFile and privateKeyFile must be set or unset together'); - } - if (config.certificateFile === undefined && config.caCertificateFile === undefined) { - throw new Error('At least one of certificateFile and caCertificateFile must be set'); - } - trace('File watcher constructed with config ' + JSON.stringify(config)); - } - updateCertificates() { - if (this.fileResultPromise) { - return; - } - this.fileResultPromise = Promise.allSettled([ - this.config.certificateFile ? readFilePromise(this.config.certificateFile) : Promise.reject(), - this.config.privateKeyFile ? readFilePromise(this.config.privateKeyFile) : Promise.reject(), - this.config.caCertificateFile ? readFilePromise(this.config.caCertificateFile) : Promise.reject() - ]); - this.fileResultPromise.then(([certificateResult, privateKeyResult, caCertificateResult]) => { - if (!this.refreshTimer) { - return; - } - trace('File watcher read certificates certificate ' + certificateResult.status + ', privateKey ' + privateKeyResult.status + ', CA certificate ' + caCertificateResult.status); - this.lastUpdateTime = new Date(); - this.fileResultPromise = null; - if (certificateResult.status === 'fulfilled' && privateKeyResult.status === 'fulfilled') { - this.latestIdentityUpdate = { - certificate: certificateResult.value, - privateKey: privateKeyResult.value - }; - } - else { - this.latestIdentityUpdate = null; - } - if (caCertificateResult.status === 'fulfilled') { - this.latestCaUpdate = { - caCertificate: caCertificateResult.value - }; - } - else { - this.latestCaUpdate = null; - } - for (const listener of this.identityListeners) { - listener(this.latestIdentityUpdate); - } - for (const listener of this.caListeners) { - listener(this.latestCaUpdate); - } - }); - trace('File watcher initiated certificate update'); - } - maybeStartWatchingFiles() { - if (!this.refreshTimer) { - /* Perform the first read immediately, but only if there was not already - * a recent read, to avoid reading from the filesystem significantly more - * frequently than configured if the provider quickly switches between - * used and unused. */ - const timeSinceLastUpdate = this.lastUpdateTime ? (new Date()).getTime() - this.lastUpdateTime.getTime() : Infinity; - if (timeSinceLastUpdate > this.config.refreshIntervalMs) { - this.updateCertificates(); - } - if (timeSinceLastUpdate > this.config.refreshIntervalMs * 2) { - // Clear out old updates if they are definitely stale - this.latestCaUpdate = undefined; - this.latestIdentityUpdate = undefined; - } - this.refreshTimer = setInterval(() => this.updateCertificates(), this.config.refreshIntervalMs); - trace('File watcher started watching'); - } - } - maybeStopWatchingFiles() { - if (this.caListeners.size === 0 && this.identityListeners.size === 0) { - this.fileResultPromise = null; - if (this.refreshTimer) { - clearInterval(this.refreshTimer); - this.refreshTimer = null; - } - } - } - addCaCertificateListener(listener) { - this.caListeners.add(listener); - this.maybeStartWatchingFiles(); - if (this.latestCaUpdate !== undefined) { - process.nextTick(listener, this.latestCaUpdate); - } - } - removeCaCertificateListener(listener) { - this.caListeners.delete(listener); - this.maybeStopWatchingFiles(); - } - addIdentityCertificateListener(listener) { - this.identityListeners.add(listener); - this.maybeStartWatchingFiles(); - if (this.latestIdentityUpdate !== undefined) { - process.nextTick(listener, this.latestIdentityUpdate); - } - } - removeIdentityCertificateListener(listener) { - this.identityListeners.delete(listener); - this.maybeStopWatchingFiles(); - } -} -exports.FileWatcherCertificateProvider = FileWatcherCertificateProvider; -//# sourceMappingURL=certificate-provider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/channel-credentials.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/channel-credentials.js deleted file mode 100644 index 9be5ea39..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/channel-credentials.js +++ /dev/null @@ -1,430 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ChannelCredentials = void 0; -exports.createCertificateProviderChannelCredentials = createCertificateProviderChannelCredentials; -const tls_1 = require("tls"); -const call_credentials_1 = require("./call-credentials"); -const tls_helpers_1 = require("./tls-helpers"); -const uri_parser_1 = require("./uri-parser"); -const resolver_1 = require("./resolver"); -const logging_1 = require("./logging"); -const constants_1 = require("./constants"); -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function verifyIsBufferOrNull(obj, friendlyName) { - if (obj && !(obj instanceof Buffer)) { - throw new TypeError(`${friendlyName}, if provided, must be a Buffer.`); - } -} -/** - * A class that contains credentials for communicating over a channel, as well - * as a set of per-call credentials, which are applied to every method call made - * over a channel initialized with an instance of this class. - */ -class ChannelCredentials { - /** - * Returns a copy of this object with the included set of per-call credentials - * expanded to include callCredentials. - * @param callCredentials A CallCredentials object to associate with this - * instance. - */ - compose(callCredentials) { - return new ComposedChannelCredentialsImpl(this, callCredentials); - } - /** - * Return a new ChannelCredentials instance with a given set of credentials. - * The resulting instance can be used to construct a Channel that communicates - * over TLS. - * @param rootCerts The root certificate data. - * @param privateKey The client certificate private key, if available. - * @param certChain The client certificate key chain, if available. - * @param verifyOptions Additional options to modify certificate verification - */ - static createSsl(rootCerts, privateKey, certChain, verifyOptions) { - var _a; - verifyIsBufferOrNull(rootCerts, 'Root certificate'); - verifyIsBufferOrNull(privateKey, 'Private key'); - verifyIsBufferOrNull(certChain, 'Certificate chain'); - if (privateKey && !certChain) { - throw new Error('Private key must be given with accompanying certificate chain'); - } - if (!privateKey && certChain) { - throw new Error('Certificate chain must be given with accompanying private key'); - } - const secureContext = (0, tls_1.createSecureContext)({ - ca: (_a = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a !== void 0 ? _a : undefined, - key: privateKey !== null && privateKey !== void 0 ? privateKey : undefined, - cert: certChain !== null && certChain !== void 0 ? certChain : undefined, - ciphers: tls_helpers_1.CIPHER_SUITES, - }); - return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {}); - } - /** - * Return a new ChannelCredentials instance with credentials created using - * the provided secureContext. The resulting instances can be used to - * construct a Channel that communicates over TLS. gRPC will not override - * anything in the provided secureContext, so the environment variables - * GRPC_SSL_CIPHER_SUITES and GRPC_DEFAULT_SSL_ROOTS_FILE_PATH will - * not be applied. - * @param secureContext The return value of tls.createSecureContext() - * @param verifyOptions Additional options to modify certificate verification - */ - static createFromSecureContext(secureContext, verifyOptions) { - return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {}); - } - /** - * Return a new ChannelCredentials instance with no credentials. - */ - static createInsecure() { - return new InsecureChannelCredentialsImpl(); - } -} -exports.ChannelCredentials = ChannelCredentials; -class InsecureChannelCredentialsImpl extends ChannelCredentials { - constructor() { - super(); - } - compose(callCredentials) { - throw new Error('Cannot compose insecure credentials'); - } - _isSecure() { - return false; - } - _equals(other) { - return other instanceof InsecureChannelCredentialsImpl; - } - _createSecureConnector(channelTarget, options, callCredentials) { - return { - connect(socket) { - return Promise.resolve({ - socket, - secure: false - }); - }, - waitForReady: () => { - return Promise.resolve(); - }, - getCallCredentials: () => { - return callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty(); - }, - destroy() { } - }; - } -} -function getConnectionOptions(secureContext, verifyOptions, channelTarget, options) { - var _a, _b; - const connectionOptions = { - secureContext: secureContext - }; - let realTarget = channelTarget; - if ('grpc.http_connect_target' in options) { - const parsedTarget = (0, uri_parser_1.parseUri)(options['grpc.http_connect_target']); - if (parsedTarget) { - realTarget = parsedTarget; - } - } - const targetPath = (0, resolver_1.getDefaultAuthority)(realTarget); - const hostPort = (0, uri_parser_1.splitHostPort)(targetPath); - const remoteHost = (_a = hostPort === null || hostPort === void 0 ? void 0 : hostPort.host) !== null && _a !== void 0 ? _a : targetPath; - connectionOptions.host = remoteHost; - if (verifyOptions.checkServerIdentity) { - connectionOptions.checkServerIdentity = verifyOptions.checkServerIdentity; - } - if (verifyOptions.rejectUnauthorized !== undefined) { - connectionOptions.rejectUnauthorized = verifyOptions.rejectUnauthorized; - } - connectionOptions.ALPNProtocols = ['h2']; - if (options['grpc.ssl_target_name_override']) { - const sslTargetNameOverride = options['grpc.ssl_target_name_override']; - const originalCheckServerIdentity = (_b = connectionOptions.checkServerIdentity) !== null && _b !== void 0 ? _b : tls_1.checkServerIdentity; - connectionOptions.checkServerIdentity = (host, cert) => { - return originalCheckServerIdentity(sslTargetNameOverride, cert); - }; - connectionOptions.servername = sslTargetNameOverride; - } - else { - connectionOptions.servername = remoteHost; - } - if (options['grpc-node.tls_enable_trace']) { - connectionOptions.enableTrace = true; - } - return connectionOptions; -} -class SecureConnectorImpl { - constructor(connectionOptions, callCredentials) { - this.connectionOptions = connectionOptions; - this.callCredentials = callCredentials; - } - connect(socket) { - const tlsConnectOptions = Object.assign({ socket: socket }, this.connectionOptions); - return new Promise((resolve, reject) => { - const tlsSocket = (0, tls_1.connect)(tlsConnectOptions, () => { - var _a; - if (((_a = this.connectionOptions.rejectUnauthorized) !== null && _a !== void 0 ? _a : true) && !tlsSocket.authorized) { - reject(tlsSocket.authorizationError); - return; - } - resolve({ - socket: tlsSocket, - secure: true - }); - }); - tlsSocket.on('error', (error) => { - reject(error); - }); - }); - } - waitForReady() { - return Promise.resolve(); - } - getCallCredentials() { - return this.callCredentials; - } - destroy() { } -} -class SecureChannelCredentialsImpl extends ChannelCredentials { - constructor(secureContext, verifyOptions) { - super(); - this.secureContext = secureContext; - this.verifyOptions = verifyOptions; - } - _isSecure() { - return true; - } - _equals(other) { - if (this === other) { - return true; - } - if (other instanceof SecureChannelCredentialsImpl) { - return (this.secureContext === other.secureContext && - this.verifyOptions.checkServerIdentity === - other.verifyOptions.checkServerIdentity); - } - else { - return false; - } - } - _createSecureConnector(channelTarget, options, callCredentials) { - const connectionOptions = getConnectionOptions(this.secureContext, this.verifyOptions, channelTarget, options); - return new SecureConnectorImpl(connectionOptions, callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); - } -} -class CertificateProviderChannelCredentialsImpl extends ChannelCredentials { - constructor(caCertificateProvider, identityCertificateProvider, verifyOptions) { - super(); - this.caCertificateProvider = caCertificateProvider; - this.identityCertificateProvider = identityCertificateProvider; - this.verifyOptions = verifyOptions; - this.refcount = 0; - /** - * `undefined` means that the certificates have not yet been loaded. `null` - * means that an attempt to load them has completed, and has failed. - */ - this.latestCaUpdate = undefined; - /** - * `undefined` means that the certificates have not yet been loaded. `null` - * means that an attempt to load them has completed, and has failed. - */ - this.latestIdentityUpdate = undefined; - this.caCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this); - this.identityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this); - this.secureContextWatchers = []; - } - _isSecure() { - return true; - } - _equals(other) { - var _a, _b; - if (this === other) { - return true; - } - if (other instanceof CertificateProviderChannelCredentialsImpl) { - return this.caCertificateProvider === other.caCertificateProvider && - this.identityCertificateProvider === other.identityCertificateProvider && - ((_a = this.verifyOptions) === null || _a === void 0 ? void 0 : _a.checkServerIdentity) === ((_b = other.verifyOptions) === null || _b === void 0 ? void 0 : _b.checkServerIdentity); - } - else { - return false; - } - } - ref() { - var _a; - if (this.refcount === 0) { - this.caCertificateProvider.addCaCertificateListener(this.caCertificateUpdateListener); - (_a = this.identityCertificateProvider) === null || _a === void 0 ? void 0 : _a.addIdentityCertificateListener(this.identityCertificateUpdateListener); - } - this.refcount += 1; - } - unref() { - var _a; - this.refcount -= 1; - if (this.refcount === 0) { - this.caCertificateProvider.removeCaCertificateListener(this.caCertificateUpdateListener); - (_a = this.identityCertificateProvider) === null || _a === void 0 ? void 0 : _a.removeIdentityCertificateListener(this.identityCertificateUpdateListener); - } - } - _createSecureConnector(channelTarget, options, callCredentials) { - this.ref(); - return new CertificateProviderChannelCredentialsImpl.SecureConnectorImpl(this, channelTarget, options, callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); - } - maybeUpdateWatchers() { - if (this.hasReceivedUpdates()) { - for (const watcher of this.secureContextWatchers) { - watcher(this.getLatestSecureContext()); - } - this.secureContextWatchers = []; - } - } - handleCaCertificateUpdate(update) { - this.latestCaUpdate = update; - this.maybeUpdateWatchers(); - } - handleIdentityCertitificateUpdate(update) { - this.latestIdentityUpdate = update; - this.maybeUpdateWatchers(); - } - hasReceivedUpdates() { - if (this.latestCaUpdate === undefined) { - return false; - } - if (this.identityCertificateProvider && this.latestIdentityUpdate === undefined) { - return false; - } - return true; - } - getSecureContext() { - if (this.hasReceivedUpdates()) { - return Promise.resolve(this.getLatestSecureContext()); - } - else { - return new Promise(resolve => { - this.secureContextWatchers.push(resolve); - }); - } - } - getLatestSecureContext() { - var _a, _b; - if (!this.latestCaUpdate) { - return null; - } - if (this.identityCertificateProvider !== null && !this.latestIdentityUpdate) { - return null; - } - try { - return (0, tls_1.createSecureContext)({ - ca: this.latestCaUpdate.caCertificate, - key: (_a = this.latestIdentityUpdate) === null || _a === void 0 ? void 0 : _a.privateKey, - cert: (_b = this.latestIdentityUpdate) === null || _b === void 0 ? void 0 : _b.certificate, - ciphers: tls_helpers_1.CIPHER_SUITES - }); - } - catch (e) { - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, 'Failed to createSecureContext with error ' + e.message); - return null; - } - } -} -CertificateProviderChannelCredentialsImpl.SecureConnectorImpl = class { - constructor(parent, channelTarget, options, callCredentials) { - this.parent = parent; - this.channelTarget = channelTarget; - this.options = options; - this.callCredentials = callCredentials; - } - connect(socket) { - return new Promise((resolve, reject) => { - const secureContext = this.parent.getLatestSecureContext(); - if (!secureContext) { - reject(new Error('Failed to load credentials')); - return; - } - if (socket.closed) { - reject(new Error('Socket closed while loading credentials')); - } - const connnectionOptions = getConnectionOptions(secureContext, this.parent.verifyOptions, this.channelTarget, this.options); - const tlsConnectOptions = Object.assign({ socket: socket }, connnectionOptions); - const closeCallback = () => { - reject(new Error('Socket closed')); - }; - const errorCallback = (error) => { - reject(error); - }; - const tlsSocket = (0, tls_1.connect)(tlsConnectOptions, () => { - var _a; - tlsSocket.removeListener('close', closeCallback); - tlsSocket.removeListener('error', errorCallback); - if (((_a = this.parent.verifyOptions.rejectUnauthorized) !== null && _a !== void 0 ? _a : true) && !tlsSocket.authorized) { - reject(tlsSocket.authorizationError); - return; - } - resolve({ - socket: tlsSocket, - secure: true - }); - }); - tlsSocket.once('close', closeCallback); - tlsSocket.once('error', errorCallback); - }); - } - async waitForReady() { - await this.parent.getSecureContext(); - } - getCallCredentials() { - return this.callCredentials; - } - destroy() { - this.parent.unref(); - } -}; -function createCertificateProviderChannelCredentials(caCertificateProvider, identityCertificateProvider, verifyOptions) { - return new CertificateProviderChannelCredentialsImpl(caCertificateProvider, identityCertificateProvider, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {}); -} -class ComposedChannelCredentialsImpl extends ChannelCredentials { - constructor(channelCredentials, callCredentials) { - super(); - this.channelCredentials = channelCredentials; - this.callCredentials = callCredentials; - if (!channelCredentials._isSecure()) { - throw new Error('Cannot compose insecure credentials'); - } - } - compose(callCredentials) { - const combinedCallCredentials = this.callCredentials.compose(callCredentials); - return new ComposedChannelCredentialsImpl(this.channelCredentials, combinedCallCredentials); - } - _isSecure() { - return true; - } - _equals(other) { - if (this === other) { - return true; - } - if (other instanceof ComposedChannelCredentialsImpl) { - return (this.channelCredentials._equals(other.channelCredentials) && - this.callCredentials._equals(other.callCredentials)); - } - else { - return false; - } - } - _createSecureConnector(channelTarget, options, callCredentials) { - const combinedCallCredentials = this.callCredentials.compose(callCredentials !== null && callCredentials !== void 0 ? callCredentials : call_credentials_1.CallCredentials.createEmpty()); - return this.channelCredentials._createSecureConnector(channelTarget, options, combinedCallCredentials); - } -} -//# sourceMappingURL=channel-credentials.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/channel-options.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/channel-options.js deleted file mode 100644 index c6aaa950..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/channel-options.js +++ /dev/null @@ -1,73 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.recognizedOptions = void 0; -exports.channelOptionsEqual = channelOptionsEqual; -/** - * This is for checking provided options at runtime. This is an object for - * easier membership checking. - */ -exports.recognizedOptions = { - 'grpc.ssl_target_name_override': true, - 'grpc.primary_user_agent': true, - 'grpc.secondary_user_agent': true, - 'grpc.default_authority': true, - 'grpc.keepalive_time_ms': true, - 'grpc.keepalive_timeout_ms': true, - 'grpc.keepalive_permit_without_calls': true, - 'grpc.service_config': true, - 'grpc.max_concurrent_streams': true, - 'grpc.initial_reconnect_backoff_ms': true, - 'grpc.max_reconnect_backoff_ms': true, - 'grpc.use_local_subchannel_pool': true, - 'grpc.max_send_message_length': true, - 'grpc.max_receive_message_length': true, - 'grpc.enable_http_proxy': true, - 'grpc.enable_channelz': true, - 'grpc.dns_min_time_between_resolutions_ms': true, - 'grpc.enable_retries': true, - 'grpc.per_rpc_retry_buffer_size': true, - 'grpc.retry_buffer_size': true, - 'grpc.max_connection_age_ms': true, - 'grpc.max_connection_age_grace_ms': true, - 'grpc-node.max_session_memory': true, - 'grpc.service_config_disable_resolution': true, - 'grpc.client_idle_timeout_ms': true, - 'grpc-node.tls_enable_trace': true, - 'grpc.lb.ring_hash.ring_size_cap': true, - 'grpc-node.retry_max_attempts_limit': true, - 'grpc-node.flow_control_window': true, - 'grpc.server_call_metric_recording': true -}; -function channelOptionsEqual(options1, options2) { - const keys1 = Object.keys(options1).sort(); - const keys2 = Object.keys(options2).sort(); - if (keys1.length !== keys2.length) { - return false; - } - for (let i = 0; i < keys1.length; i += 1) { - if (keys1[i] !== keys2[i]) { - return false; - } - if (options1[keys1[i]] !== options2[keys2[i]]) { - return false; - } - } - return true; -} -//# sourceMappingURL=channel-options.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/channel.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/channel.js deleted file mode 100644 index 49e8639a..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/channel.js +++ /dev/null @@ -1,68 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ChannelImplementation = void 0; -const channel_credentials_1 = require("./channel-credentials"); -const internal_channel_1 = require("./internal-channel"); -class ChannelImplementation { - constructor(target, credentials, options) { - if (typeof target !== 'string') { - throw new TypeError('Channel target must be a string'); - } - if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) { - throw new TypeError('Channel credentials must be a ChannelCredentials object'); - } - if (options) { - if (typeof options !== 'object') { - throw new TypeError('Channel options must be an object'); - } - } - this.internalChannel = new internal_channel_1.InternalChannel(target, credentials, options); - } - close() { - this.internalChannel.close(); - } - getTarget() { - return this.internalChannel.getTarget(); - } - getConnectivityState(tryToConnect) { - return this.internalChannel.getConnectivityState(tryToConnect); - } - watchConnectivityState(currentState, deadline, callback) { - this.internalChannel.watchConnectivityState(currentState, deadline, callback); - } - /** - * Get the channelz reference object for this channel. The returned value is - * garbage if channelz is disabled for this channel. - * @returns - */ - getChannelzRef() { - return this.internalChannel.getChannelzRef(); - } - createCall(method, deadline, host, parentCall, propagateFlags) { - if (typeof method !== 'string') { - throw new TypeError('Channel#createCall: method must be a string'); - } - if (!(typeof deadline === 'number' || deadline instanceof Date)) { - throw new TypeError('Channel#createCall: deadline must be a number or Date'); - } - return this.internalChannel.createCall(method, deadline, host, parentCall, propagateFlags); - } -} -exports.ChannelImplementation = ChannelImplementation; -//# sourceMappingURL=channel.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/channelz.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/channelz.js deleted file mode 100644 index 91e9aceb..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/channelz.js +++ /dev/null @@ -1,598 +0,0 @@ -"use strict"; -/* - * Copyright 2021 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.registerChannelzSocket = exports.registerChannelzServer = exports.registerChannelzSubchannel = exports.registerChannelzChannel = exports.ChannelzCallTrackerStub = exports.ChannelzCallTracker = exports.ChannelzChildrenTrackerStub = exports.ChannelzChildrenTracker = exports.ChannelzTrace = exports.ChannelzTraceStub = void 0; -exports.unregisterChannelzRef = unregisterChannelzRef; -exports.getChannelzHandlers = getChannelzHandlers; -exports.getChannelzServiceDefinition = getChannelzServiceDefinition; -exports.setup = setup; -const net_1 = require("net"); -const ordered_map_1 = require("@js-sdsl/ordered-map"); -const connectivity_state_1 = require("./connectivity-state"); -const constants_1 = require("./constants"); -const subchannel_address_1 = require("./subchannel-address"); -const admin_1 = require("./admin"); -const make_client_1 = require("./make-client"); -function channelRefToMessage(ref) { - return { - channel_id: ref.id, - name: ref.name, - }; -} -function subchannelRefToMessage(ref) { - return { - subchannel_id: ref.id, - name: ref.name, - }; -} -function serverRefToMessage(ref) { - return { - server_id: ref.id, - }; -} -function socketRefToMessage(ref) { - return { - socket_id: ref.id, - name: ref.name, - }; -} -/** - * The loose upper bound on the number of events that should be retained in a - * trace. This may be exceeded by up to a factor of 2. Arbitrarily chosen as a - * number that should be large enough to contain the recent relevant - * information, but small enough to not use excessive memory. - */ -const TARGET_RETAINED_TRACES = 32; -/** - * Default number of sockets/servers/channels/subchannels to return - */ -const DEFAULT_MAX_RESULTS = 100; -class ChannelzTraceStub { - constructor() { - this.events = []; - this.creationTimestamp = new Date(); - this.eventsLogged = 0; - } - addTrace() { } - getTraceMessage() { - return { - creation_timestamp: dateToProtoTimestamp(this.creationTimestamp), - num_events_logged: this.eventsLogged, - events: [], - }; - } -} -exports.ChannelzTraceStub = ChannelzTraceStub; -class ChannelzTrace { - constructor() { - this.events = []; - this.eventsLogged = 0; - this.creationTimestamp = new Date(); - } - addTrace(severity, description, child) { - const timestamp = new Date(); - this.events.push({ - description: description, - severity: severity, - timestamp: timestamp, - childChannel: (child === null || child === void 0 ? void 0 : child.kind) === 'channel' ? child : undefined, - childSubchannel: (child === null || child === void 0 ? void 0 : child.kind) === 'subchannel' ? child : undefined, - }); - // Whenever the trace array gets too large, discard the first half - if (this.events.length >= TARGET_RETAINED_TRACES * 2) { - this.events = this.events.slice(TARGET_RETAINED_TRACES); - } - this.eventsLogged += 1; - } - getTraceMessage() { - return { - creation_timestamp: dateToProtoTimestamp(this.creationTimestamp), - num_events_logged: this.eventsLogged, - events: this.events.map(event => { - return { - description: event.description, - severity: event.severity, - timestamp: dateToProtoTimestamp(event.timestamp), - channel_ref: event.childChannel - ? channelRefToMessage(event.childChannel) - : null, - subchannel_ref: event.childSubchannel - ? subchannelRefToMessage(event.childSubchannel) - : null, - }; - }), - }; - } -} -exports.ChannelzTrace = ChannelzTrace; -class ChannelzChildrenTracker { - constructor() { - this.channelChildren = new ordered_map_1.OrderedMap(); - this.subchannelChildren = new ordered_map_1.OrderedMap(); - this.socketChildren = new ordered_map_1.OrderedMap(); - this.trackerMap = { - ["channel" /* EntityTypes.channel */]: this.channelChildren, - ["subchannel" /* EntityTypes.subchannel */]: this.subchannelChildren, - ["socket" /* EntityTypes.socket */]: this.socketChildren, - }; - } - refChild(child) { - const tracker = this.trackerMap[child.kind]; - const trackedChild = tracker.find(child.id); - if (trackedChild.equals(tracker.end())) { - tracker.setElement(child.id, { - ref: child, - count: 1, - }, trackedChild); - } - else { - trackedChild.pointer[1].count += 1; - } - } - unrefChild(child) { - const tracker = this.trackerMap[child.kind]; - const trackedChild = tracker.getElementByKey(child.id); - if (trackedChild !== undefined) { - trackedChild.count -= 1; - if (trackedChild.count === 0) { - tracker.eraseElementByKey(child.id); - } - } - } - getChildLists() { - return { - channels: this.channelChildren, - subchannels: this.subchannelChildren, - sockets: this.socketChildren, - }; - } -} -exports.ChannelzChildrenTracker = ChannelzChildrenTracker; -class ChannelzChildrenTrackerStub extends ChannelzChildrenTracker { - refChild() { } - unrefChild() { } -} -exports.ChannelzChildrenTrackerStub = ChannelzChildrenTrackerStub; -class ChannelzCallTracker { - constructor() { - this.callsStarted = 0; - this.callsSucceeded = 0; - this.callsFailed = 0; - this.lastCallStartedTimestamp = null; - } - addCallStarted() { - this.callsStarted += 1; - this.lastCallStartedTimestamp = new Date(); - } - addCallSucceeded() { - this.callsSucceeded += 1; - } - addCallFailed() { - this.callsFailed += 1; - } -} -exports.ChannelzCallTracker = ChannelzCallTracker; -class ChannelzCallTrackerStub extends ChannelzCallTracker { - addCallStarted() { } - addCallSucceeded() { } - addCallFailed() { } -} -exports.ChannelzCallTrackerStub = ChannelzCallTrackerStub; -const entityMaps = { - ["channel" /* EntityTypes.channel */]: new ordered_map_1.OrderedMap(), - ["subchannel" /* EntityTypes.subchannel */]: new ordered_map_1.OrderedMap(), - ["server" /* EntityTypes.server */]: new ordered_map_1.OrderedMap(), - ["socket" /* EntityTypes.socket */]: new ordered_map_1.OrderedMap(), -}; -const generateRegisterFn = (kind) => { - let nextId = 1; - function getNextId() { - return nextId++; - } - const entityMap = entityMaps[kind]; - return (name, getInfo, channelzEnabled) => { - const id = getNextId(); - const ref = { id, name, kind }; - if (channelzEnabled) { - entityMap.setElement(id, { ref, getInfo }); - } - return ref; - }; -}; -exports.registerChannelzChannel = generateRegisterFn("channel" /* EntityTypes.channel */); -exports.registerChannelzSubchannel = generateRegisterFn("subchannel" /* EntityTypes.subchannel */); -exports.registerChannelzServer = generateRegisterFn("server" /* EntityTypes.server */); -exports.registerChannelzSocket = generateRegisterFn("socket" /* EntityTypes.socket */); -function unregisterChannelzRef(ref) { - entityMaps[ref.kind].eraseElementByKey(ref.id); -} -/** - * Parse a single section of an IPv6 address as two bytes - * @param addressSection A hexadecimal string of length up to 4 - * @returns The pair of bytes representing this address section - */ -function parseIPv6Section(addressSection) { - const numberValue = Number.parseInt(addressSection, 16); - return [(numberValue / 256) | 0, numberValue % 256]; -} -/** - * Parse a chunk of an IPv6 address string to some number of bytes - * @param addressChunk Some number of segments of up to 4 hexadecimal - * characters each, joined by colons. - * @returns The list of bytes representing this address chunk - */ -function parseIPv6Chunk(addressChunk) { - if (addressChunk === '') { - return []; - } - const bytePairs = addressChunk - .split(':') - .map(section => parseIPv6Section(section)); - const result = []; - return result.concat(...bytePairs); -} -function isIPv6MappedIPv4(ipAddress) { - return (0, net_1.isIPv6)(ipAddress) && ipAddress.toLowerCase().startsWith('::ffff:') && (0, net_1.isIPv4)(ipAddress.substring(7)); -} -/** - * Prerequisite: isIPv4(ipAddress) - * @param ipAddress - * @returns - */ -function ipv4AddressStringToBuffer(ipAddress) { - return Buffer.from(Uint8Array.from(ipAddress.split('.').map(segment => Number.parseInt(segment)))); -} -/** - * Converts an IPv4 or IPv6 address from string representation to binary - * representation - * @param ipAddress an IP address in standard IPv4 or IPv6 text format - * @returns - */ -function ipAddressStringToBuffer(ipAddress) { - if ((0, net_1.isIPv4)(ipAddress)) { - return ipv4AddressStringToBuffer(ipAddress); - } - else if (isIPv6MappedIPv4(ipAddress)) { - return ipv4AddressStringToBuffer(ipAddress.substring(7)); - } - else if ((0, net_1.isIPv6)(ipAddress)) { - let leftSection; - let rightSection; - const doubleColonIndex = ipAddress.indexOf('::'); - if (doubleColonIndex === -1) { - leftSection = ipAddress; - rightSection = ''; - } - else { - leftSection = ipAddress.substring(0, doubleColonIndex); - rightSection = ipAddress.substring(doubleColonIndex + 2); - } - const leftBuffer = Buffer.from(parseIPv6Chunk(leftSection)); - const rightBuffer = Buffer.from(parseIPv6Chunk(rightSection)); - const middleBuffer = Buffer.alloc(16 - leftBuffer.length - rightBuffer.length, 0); - return Buffer.concat([leftBuffer, middleBuffer, rightBuffer]); - } - else { - return null; - } -} -function connectivityStateToMessage(state) { - switch (state) { - case connectivity_state_1.ConnectivityState.CONNECTING: - return { - state: 'CONNECTING', - }; - case connectivity_state_1.ConnectivityState.IDLE: - return { - state: 'IDLE', - }; - case connectivity_state_1.ConnectivityState.READY: - return { - state: 'READY', - }; - case connectivity_state_1.ConnectivityState.SHUTDOWN: - return { - state: 'SHUTDOWN', - }; - case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE: - return { - state: 'TRANSIENT_FAILURE', - }; - default: - return { - state: 'UNKNOWN', - }; - } -} -function dateToProtoTimestamp(date) { - if (!date) { - return null; - } - const millisSinceEpoch = date.getTime(); - return { - seconds: (millisSinceEpoch / 1000) | 0, - nanos: (millisSinceEpoch % 1000) * 1000000, - }; -} -function getChannelMessage(channelEntry) { - const resolvedInfo = channelEntry.getInfo(); - const channelRef = []; - const subchannelRef = []; - resolvedInfo.children.channels.forEach(el => { - channelRef.push(channelRefToMessage(el[1].ref)); - }); - resolvedInfo.children.subchannels.forEach(el => { - subchannelRef.push(subchannelRefToMessage(el[1].ref)); - }); - return { - ref: channelRefToMessage(channelEntry.ref), - data: { - target: resolvedInfo.target, - state: connectivityStateToMessage(resolvedInfo.state), - calls_started: resolvedInfo.callTracker.callsStarted, - calls_succeeded: resolvedInfo.callTracker.callsSucceeded, - calls_failed: resolvedInfo.callTracker.callsFailed, - last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), - trace: resolvedInfo.trace.getTraceMessage(), - }, - channel_ref: channelRef, - subchannel_ref: subchannelRef, - }; -} -function GetChannel(call, callback) { - const channelId = parseInt(call.request.channel_id, 10); - const channelEntry = entityMaps["channel" /* EntityTypes.channel */].getElementByKey(channelId); - if (channelEntry === undefined) { - callback({ - code: constants_1.Status.NOT_FOUND, - details: 'No channel data found for id ' + channelId, - }); - return; - } - callback(null, { channel: getChannelMessage(channelEntry) }); -} -function GetTopChannels(call, callback) { - const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; - const resultList = []; - const startId = parseInt(call.request.start_channel_id, 10); - const channelEntries = entityMaps["channel" /* EntityTypes.channel */]; - let i; - for (i = channelEntries.lowerBound(startId); !i.equals(channelEntries.end()) && resultList.length < maxResults; i = i.next()) { - resultList.push(getChannelMessage(i.pointer[1])); - } - callback(null, { - channel: resultList, - end: i.equals(channelEntries.end()), - }); -} -function getServerMessage(serverEntry) { - const resolvedInfo = serverEntry.getInfo(); - const listenSocket = []; - resolvedInfo.listenerChildren.sockets.forEach(el => { - listenSocket.push(socketRefToMessage(el[1].ref)); - }); - return { - ref: serverRefToMessage(serverEntry.ref), - data: { - calls_started: resolvedInfo.callTracker.callsStarted, - calls_succeeded: resolvedInfo.callTracker.callsSucceeded, - calls_failed: resolvedInfo.callTracker.callsFailed, - last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), - trace: resolvedInfo.trace.getTraceMessage(), - }, - listen_socket: listenSocket, - }; -} -function GetServer(call, callback) { - const serverId = parseInt(call.request.server_id, 10); - const serverEntries = entityMaps["server" /* EntityTypes.server */]; - const serverEntry = serverEntries.getElementByKey(serverId); - if (serverEntry === undefined) { - callback({ - code: constants_1.Status.NOT_FOUND, - details: 'No server data found for id ' + serverId, - }); - return; - } - callback(null, { server: getServerMessage(serverEntry) }); -} -function GetServers(call, callback) { - const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; - const startId = parseInt(call.request.start_server_id, 10); - const serverEntries = entityMaps["server" /* EntityTypes.server */]; - const resultList = []; - let i; - for (i = serverEntries.lowerBound(startId); !i.equals(serverEntries.end()) && resultList.length < maxResults; i = i.next()) { - resultList.push(getServerMessage(i.pointer[1])); - } - callback(null, { - server: resultList, - end: i.equals(serverEntries.end()), - }); -} -function GetSubchannel(call, callback) { - const subchannelId = parseInt(call.request.subchannel_id, 10); - const subchannelEntry = entityMaps["subchannel" /* EntityTypes.subchannel */].getElementByKey(subchannelId); - if (subchannelEntry === undefined) { - callback({ - code: constants_1.Status.NOT_FOUND, - details: 'No subchannel data found for id ' + subchannelId, - }); - return; - } - const resolvedInfo = subchannelEntry.getInfo(); - const listenSocket = []; - resolvedInfo.children.sockets.forEach(el => { - listenSocket.push(socketRefToMessage(el[1].ref)); - }); - const subchannelMessage = { - ref: subchannelRefToMessage(subchannelEntry.ref), - data: { - target: resolvedInfo.target, - state: connectivityStateToMessage(resolvedInfo.state), - calls_started: resolvedInfo.callTracker.callsStarted, - calls_succeeded: resolvedInfo.callTracker.callsSucceeded, - calls_failed: resolvedInfo.callTracker.callsFailed, - last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), - trace: resolvedInfo.trace.getTraceMessage(), - }, - socket_ref: listenSocket, - }; - callback(null, { subchannel: subchannelMessage }); -} -function subchannelAddressToAddressMessage(subchannelAddress) { - var _a; - if ((0, subchannel_address_1.isTcpSubchannelAddress)(subchannelAddress)) { - return { - address: 'tcpip_address', - tcpip_address: { - ip_address: (_a = ipAddressStringToBuffer(subchannelAddress.host)) !== null && _a !== void 0 ? _a : undefined, - port: subchannelAddress.port, - }, - }; - } - else { - return { - address: 'uds_address', - uds_address: { - filename: subchannelAddress.path, - }, - }; - } -} -function GetSocket(call, callback) { - var _a, _b, _c, _d, _e; - const socketId = parseInt(call.request.socket_id, 10); - const socketEntry = entityMaps["socket" /* EntityTypes.socket */].getElementByKey(socketId); - if (socketEntry === undefined) { - callback({ - code: constants_1.Status.NOT_FOUND, - details: 'No socket data found for id ' + socketId, - }); - return; - } - const resolvedInfo = socketEntry.getInfo(); - const securityMessage = resolvedInfo.security - ? { - model: 'tls', - tls: { - cipher_suite: resolvedInfo.security.cipherSuiteStandardName - ? 'standard_name' - : 'other_name', - standard_name: (_a = resolvedInfo.security.cipherSuiteStandardName) !== null && _a !== void 0 ? _a : undefined, - other_name: (_b = resolvedInfo.security.cipherSuiteOtherName) !== null && _b !== void 0 ? _b : undefined, - local_certificate: (_c = resolvedInfo.security.localCertificate) !== null && _c !== void 0 ? _c : undefined, - remote_certificate: (_d = resolvedInfo.security.remoteCertificate) !== null && _d !== void 0 ? _d : undefined, - }, - } - : null; - const socketMessage = { - ref: socketRefToMessage(socketEntry.ref), - local: resolvedInfo.localAddress - ? subchannelAddressToAddressMessage(resolvedInfo.localAddress) - : null, - remote: resolvedInfo.remoteAddress - ? subchannelAddressToAddressMessage(resolvedInfo.remoteAddress) - : null, - remote_name: (_e = resolvedInfo.remoteName) !== null && _e !== void 0 ? _e : undefined, - security: securityMessage, - data: { - keep_alives_sent: resolvedInfo.keepAlivesSent, - streams_started: resolvedInfo.streamsStarted, - streams_succeeded: resolvedInfo.streamsSucceeded, - streams_failed: resolvedInfo.streamsFailed, - last_local_stream_created_timestamp: dateToProtoTimestamp(resolvedInfo.lastLocalStreamCreatedTimestamp), - last_remote_stream_created_timestamp: dateToProtoTimestamp(resolvedInfo.lastRemoteStreamCreatedTimestamp), - messages_received: resolvedInfo.messagesReceived, - messages_sent: resolvedInfo.messagesSent, - last_message_received_timestamp: dateToProtoTimestamp(resolvedInfo.lastMessageReceivedTimestamp), - last_message_sent_timestamp: dateToProtoTimestamp(resolvedInfo.lastMessageSentTimestamp), - local_flow_control_window: resolvedInfo.localFlowControlWindow - ? { value: resolvedInfo.localFlowControlWindow } - : null, - remote_flow_control_window: resolvedInfo.remoteFlowControlWindow - ? { value: resolvedInfo.remoteFlowControlWindow } - : null, - }, - }; - callback(null, { socket: socketMessage }); -} -function GetServerSockets(call, callback) { - const serverId = parseInt(call.request.server_id, 10); - const serverEntry = entityMaps["server" /* EntityTypes.server */].getElementByKey(serverId); - if (serverEntry === undefined) { - callback({ - code: constants_1.Status.NOT_FOUND, - details: 'No server data found for id ' + serverId, - }); - return; - } - const startId = parseInt(call.request.start_socket_id, 10); - const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; - const resolvedInfo = serverEntry.getInfo(); - // If we wanted to include listener sockets in the result, this line would - // instead say - // const allSockets = resolvedInfo.listenerChildren.sockets.concat(resolvedInfo.sessionChildren.sockets).sort((ref1, ref2) => ref1.id - ref2.id); - const allSockets = resolvedInfo.sessionChildren.sockets; - const resultList = []; - let i; - for (i = allSockets.lowerBound(startId); !i.equals(allSockets.end()) && resultList.length < maxResults; i = i.next()) { - resultList.push(socketRefToMessage(i.pointer[1].ref)); - } - callback(null, { - socket_ref: resultList, - end: i.equals(allSockets.end()), - }); -} -function getChannelzHandlers() { - return { - GetChannel, - GetTopChannels, - GetServer, - GetServers, - GetSubchannel, - GetSocket, - GetServerSockets, - }; -} -let loadedChannelzDefinition = null; -function getChannelzServiceDefinition() { - if (loadedChannelzDefinition) { - return loadedChannelzDefinition; - } - /* The purpose of this complexity is to avoid loading @grpc/proto-loader at - * runtime for users who will not use/enable channelz. */ - const loaderLoadSync = require('@grpc/proto-loader') - .loadSync; - const loadedProto = loaderLoadSync('channelz.proto', { - keepCase: true, - longs: String, - enums: String, - defaults: true, - oneofs: true, - includeDirs: [`${__dirname}/../../proto`], - }); - const channelzGrpcObject = (0, make_client_1.loadPackageDefinition)(loadedProto); - loadedChannelzDefinition = - channelzGrpcObject.grpc.channelz.v1.Channelz.service; - return loadedChannelzDefinition; -} -function setup() { - (0, admin_1.registerAdminService)(getChannelzServiceDefinition, getChannelzHandlers); -} -//# sourceMappingURL=channelz.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/client-interceptors.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/client-interceptors.js deleted file mode 100644 index 51fa9794..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/client-interceptors.js +++ /dev/null @@ -1,434 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.InterceptingCall = exports.RequesterBuilder = exports.ListenerBuilder = exports.InterceptorConfigurationError = void 0; -exports.getInterceptingCall = getInterceptingCall; -const metadata_1 = require("./metadata"); -const call_interface_1 = require("./call-interface"); -const constants_1 = require("./constants"); -const error_1 = require("./error"); -/** - * Error class associated with passing both interceptors and interceptor - * providers to a client constructor or as call options. - */ -class InterceptorConfigurationError extends Error { - constructor(message) { - super(message); - this.name = 'InterceptorConfigurationError'; - Error.captureStackTrace(this, InterceptorConfigurationError); - } -} -exports.InterceptorConfigurationError = InterceptorConfigurationError; -class ListenerBuilder { - constructor() { - this.metadata = undefined; - this.message = undefined; - this.status = undefined; - } - withOnReceiveMetadata(onReceiveMetadata) { - this.metadata = onReceiveMetadata; - return this; - } - withOnReceiveMessage(onReceiveMessage) { - this.message = onReceiveMessage; - return this; - } - withOnReceiveStatus(onReceiveStatus) { - this.status = onReceiveStatus; - return this; - } - build() { - return { - onReceiveMetadata: this.metadata, - onReceiveMessage: this.message, - onReceiveStatus: this.status, - }; - } -} -exports.ListenerBuilder = ListenerBuilder; -class RequesterBuilder { - constructor() { - this.start = undefined; - this.message = undefined; - this.halfClose = undefined; - this.cancel = undefined; - } - withStart(start) { - this.start = start; - return this; - } - withSendMessage(sendMessage) { - this.message = sendMessage; - return this; - } - withHalfClose(halfClose) { - this.halfClose = halfClose; - return this; - } - withCancel(cancel) { - this.cancel = cancel; - return this; - } - build() { - return { - start: this.start, - sendMessage: this.message, - halfClose: this.halfClose, - cancel: this.cancel, - }; - } -} -exports.RequesterBuilder = RequesterBuilder; -/** - * A Listener with a default pass-through implementation of each method. Used - * for filling out Listeners with some methods omitted. - */ -const defaultListener = { - onReceiveMetadata: (metadata, next) => { - next(metadata); - }, - onReceiveMessage: (message, next) => { - next(message); - }, - onReceiveStatus: (status, next) => { - next(status); - }, -}; -/** - * A Requester with a default pass-through implementation of each method. Used - * for filling out Requesters with some methods omitted. - */ -const defaultRequester = { - start: (metadata, listener, next) => { - next(metadata, listener); - }, - sendMessage: (message, next) => { - next(message); - }, - halfClose: next => { - next(); - }, - cancel: next => { - next(); - }, -}; -class InterceptingCall { - constructor(nextCall, requester) { - var _a, _b, _c, _d; - this.nextCall = nextCall; - /** - * Indicates that metadata has been passed to the requester's start - * method but it has not been passed to the corresponding next callback - */ - this.processingMetadata = false; - /** - * Message context for a pending message that is waiting for - */ - this.pendingMessageContext = null; - /** - * Indicates that a message has been passed to the requester's sendMessage - * method but it has not been passed to the corresponding next callback - */ - this.processingMessage = false; - /** - * Indicates that a status was received but could not be propagated because - * a message was still being processed. - */ - this.pendingHalfClose = false; - if (requester) { - this.requester = { - start: (_a = requester.start) !== null && _a !== void 0 ? _a : defaultRequester.start, - sendMessage: (_b = requester.sendMessage) !== null && _b !== void 0 ? _b : defaultRequester.sendMessage, - halfClose: (_c = requester.halfClose) !== null && _c !== void 0 ? _c : defaultRequester.halfClose, - cancel: (_d = requester.cancel) !== null && _d !== void 0 ? _d : defaultRequester.cancel, - }; - } - else { - this.requester = defaultRequester; - } - } - cancelWithStatus(status, details) { - this.requester.cancel(() => { - this.nextCall.cancelWithStatus(status, details); - }); - } - getPeer() { - return this.nextCall.getPeer(); - } - processPendingMessage() { - if (this.pendingMessageContext) { - this.nextCall.sendMessageWithContext(this.pendingMessageContext, this.pendingMessage); - this.pendingMessageContext = null; - this.pendingMessage = null; - } - } - processPendingHalfClose() { - if (this.pendingHalfClose) { - this.nextCall.halfClose(); - } - } - start(metadata, interceptingListener) { - var _a, _b, _c, _d, _e, _f; - const fullInterceptingListener = { - onReceiveMetadata: (_b = (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.bind(interceptingListener)) !== null && _b !== void 0 ? _b : (metadata => { }), - onReceiveMessage: (_d = (_c = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _c === void 0 ? void 0 : _c.bind(interceptingListener)) !== null && _d !== void 0 ? _d : (message => { }), - onReceiveStatus: (_f = (_e = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _e === void 0 ? void 0 : _e.bind(interceptingListener)) !== null && _f !== void 0 ? _f : (status => { }), - }; - this.processingMetadata = true; - this.requester.start(metadata, fullInterceptingListener, (md, listener) => { - var _a, _b, _c; - this.processingMetadata = false; - let finalInterceptingListener; - if ((0, call_interface_1.isInterceptingListener)(listener)) { - finalInterceptingListener = listener; - } - else { - const fullListener = { - onReceiveMetadata: (_a = listener.onReceiveMetadata) !== null && _a !== void 0 ? _a : defaultListener.onReceiveMetadata, - onReceiveMessage: (_b = listener.onReceiveMessage) !== null && _b !== void 0 ? _b : defaultListener.onReceiveMessage, - onReceiveStatus: (_c = listener.onReceiveStatus) !== null && _c !== void 0 ? _c : defaultListener.onReceiveStatus, - }; - finalInterceptingListener = new call_interface_1.InterceptingListenerImpl(fullListener, fullInterceptingListener); - } - this.nextCall.start(md, finalInterceptingListener); - this.processPendingMessage(); - this.processPendingHalfClose(); - }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sendMessageWithContext(context, message) { - this.processingMessage = true; - this.requester.sendMessage(message, finalMessage => { - this.processingMessage = false; - if (this.processingMetadata) { - this.pendingMessageContext = context; - this.pendingMessage = message; - } - else { - this.nextCall.sendMessageWithContext(context, finalMessage); - this.processPendingHalfClose(); - } - }); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sendMessage(message) { - this.sendMessageWithContext({}, message); - } - startRead() { - this.nextCall.startRead(); - } - halfClose() { - this.requester.halfClose(() => { - if (this.processingMetadata || this.processingMessage) { - this.pendingHalfClose = true; - } - else { - this.nextCall.halfClose(); - } - }); - } - getAuthContext() { - return this.nextCall.getAuthContext(); - } -} -exports.InterceptingCall = InterceptingCall; -function getCall(channel, path, options) { - var _a, _b; - const deadline = (_a = options.deadline) !== null && _a !== void 0 ? _a : Infinity; - const host = options.host; - const parent = (_b = options.parent) !== null && _b !== void 0 ? _b : null; - const propagateFlags = options.propagate_flags; - const credentials = options.credentials; - const call = channel.createCall(path, deadline, host, parent, propagateFlags); - if (credentials) { - call.setCredentials(credentials); - } - return call; -} -/** - * InterceptingCall implementation that directly owns the underlying Call - * object and handles serialization and deseraizliation. - */ -class BaseInterceptingCall { - constructor(call, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - methodDefinition) { - this.call = call; - this.methodDefinition = methodDefinition; - } - cancelWithStatus(status, details) { - this.call.cancelWithStatus(status, details); - } - getPeer() { - return this.call.getPeer(); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sendMessageWithContext(context, message) { - let serialized; - try { - serialized = this.methodDefinition.requestSerialize(message); - } - catch (e) { - this.call.cancelWithStatus(constants_1.Status.INTERNAL, `Request message serialization failure: ${(0, error_1.getErrorMessage)(e)}`); - return; - } - this.call.sendMessageWithContext(context, serialized); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - sendMessage(message) { - this.sendMessageWithContext({}, message); - } - start(metadata, interceptingListener) { - let readError = null; - this.call.start(metadata, { - onReceiveMetadata: metadata => { - var _a; - (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, metadata); - }, - onReceiveMessage: message => { - var _a; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - let deserialized; - try { - deserialized = this.methodDefinition.responseDeserialize(message); - } - catch (e) { - readError = { - code: constants_1.Status.INTERNAL, - details: `Response message parsing error: ${(0, error_1.getErrorMessage)(e)}`, - metadata: new metadata_1.Metadata(), - }; - this.call.cancelWithStatus(readError.code, readError.details); - return; - } - (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, deserialized); - }, - onReceiveStatus: status => { - var _a, _b; - if (readError) { - (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, readError); - } - else { - (_b = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _b === void 0 ? void 0 : _b.call(interceptingListener, status); - } - }, - }); - } - startRead() { - this.call.startRead(); - } - halfClose() { - this.call.halfClose(); - } - getAuthContext() { - return this.call.getAuthContext(); - } -} -/** - * BaseInterceptingCall with special-cased behavior for methods with unary - * responses. - */ -class BaseUnaryInterceptingCall extends BaseInterceptingCall { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - constructor(call, methodDefinition) { - super(call, methodDefinition); - } - start(metadata, listener) { - var _a, _b; - let receivedMessage = false; - const wrapperListener = { - onReceiveMetadata: (_b = (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.bind(listener)) !== null && _b !== void 0 ? _b : (metadata => { }), - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onReceiveMessage: (message) => { - var _a; - receivedMessage = true; - (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(listener, message); - }, - onReceiveStatus: (status) => { - var _a, _b; - if (!receivedMessage) { - (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(listener, null); - } - (_b = listener === null || listener === void 0 ? void 0 : listener.onReceiveStatus) === null || _b === void 0 ? void 0 : _b.call(listener, status); - }, - }; - super.start(metadata, wrapperListener); - this.call.startRead(); - } -} -/** - * BaseInterceptingCall with special-cased behavior for methods with streaming - * responses. - */ -class BaseStreamingInterceptingCall extends BaseInterceptingCall { -} -function getBottomInterceptingCall(channel, options, -// eslint-disable-next-line @typescript-eslint/no-explicit-any -methodDefinition) { - const call = getCall(channel, methodDefinition.path, options); - if (methodDefinition.responseStream) { - return new BaseStreamingInterceptingCall(call, methodDefinition); - } - else { - return new BaseUnaryInterceptingCall(call, methodDefinition); - } -} -function getInterceptingCall(interceptorArgs, -// eslint-disable-next-line @typescript-eslint/no-explicit-any -methodDefinition, options, channel) { - if (interceptorArgs.clientInterceptors.length > 0 && - interceptorArgs.clientInterceptorProviders.length > 0) { - throw new InterceptorConfigurationError('Both interceptors and interceptor_providers were passed as options ' + - 'to the client constructor. Only one of these is allowed.'); - } - if (interceptorArgs.callInterceptors.length > 0 && - interceptorArgs.callInterceptorProviders.length > 0) { - throw new InterceptorConfigurationError('Both interceptors and interceptor_providers were passed as call ' + - 'options. Only one of these is allowed.'); - } - let interceptors = []; - // Interceptors passed to the call override interceptors passed to the client constructor - if (interceptorArgs.callInterceptors.length > 0 || - interceptorArgs.callInterceptorProviders.length > 0) { - interceptors = [] - .concat(interceptorArgs.callInterceptors, interceptorArgs.callInterceptorProviders.map(provider => provider(methodDefinition))) - .filter(interceptor => interceptor); - // Filter out falsy values when providers return nothing - } - else { - interceptors = [] - .concat(interceptorArgs.clientInterceptors, interceptorArgs.clientInterceptorProviders.map(provider => provider(methodDefinition))) - .filter(interceptor => interceptor); - // Filter out falsy values when providers return nothing - } - const interceptorOptions = Object.assign({}, options, { - method_definition: methodDefinition, - }); - /* For each interceptor in the list, the nextCall function passed to it is - * based on the next interceptor in the list, using a nextCall function - * constructed with the following interceptor in the list, and so on. The - * initialValue, which is effectively at the end of the list, is a nextCall - * function that invokes getBottomInterceptingCall, the result of which - * handles (de)serialization and also gets the underlying call from the - * channel. */ - const getCall = interceptors.reduceRight((nextCall, nextInterceptor) => { - return currentOptions => nextInterceptor(currentOptions, nextCall); - }, (finalOptions) => getBottomInterceptingCall(channel, finalOptions, methodDefinition)); - return getCall(interceptorOptions); -} -//# sourceMappingURL=client-interceptors.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/client.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/client.js deleted file mode 100644 index 9cd559a9..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/client.js +++ /dev/null @@ -1,433 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Client = void 0; -const call_1 = require("./call"); -const channel_1 = require("./channel"); -const connectivity_state_1 = require("./connectivity-state"); -const constants_1 = require("./constants"); -const metadata_1 = require("./metadata"); -const client_interceptors_1 = require("./client-interceptors"); -const CHANNEL_SYMBOL = Symbol(); -const INTERCEPTOR_SYMBOL = Symbol(); -const INTERCEPTOR_PROVIDER_SYMBOL = Symbol(); -const CALL_INVOCATION_TRANSFORMER_SYMBOL = Symbol(); -function isFunction(arg) { - return typeof arg === 'function'; -} -function getErrorStackString(error) { - var _a; - return ((_a = error.stack) === null || _a === void 0 ? void 0 : _a.split('\n').slice(1).join('\n')) || 'no stack trace available'; -} -/** - * A generic gRPC client. Primarily useful as a base class for all generated - * clients. - */ -class Client { - constructor(address, credentials, options = {}) { - var _a, _b; - options = Object.assign({}, options); - this[INTERCEPTOR_SYMBOL] = (_a = options.interceptors) !== null && _a !== void 0 ? _a : []; - delete options.interceptors; - this[INTERCEPTOR_PROVIDER_SYMBOL] = (_b = options.interceptor_providers) !== null && _b !== void 0 ? _b : []; - delete options.interceptor_providers; - if (this[INTERCEPTOR_SYMBOL].length > 0 && - this[INTERCEPTOR_PROVIDER_SYMBOL].length > 0) { - throw new Error('Both interceptors and interceptor_providers were passed as options ' + - 'to the client constructor. Only one of these is allowed.'); - } - this[CALL_INVOCATION_TRANSFORMER_SYMBOL] = - options.callInvocationTransformer; - delete options.callInvocationTransformer; - if (options.channelOverride) { - this[CHANNEL_SYMBOL] = options.channelOverride; - } - else if (options.channelFactoryOverride) { - const channelFactoryOverride = options.channelFactoryOverride; - delete options.channelFactoryOverride; - this[CHANNEL_SYMBOL] = channelFactoryOverride(address, credentials, options); - } - else { - this[CHANNEL_SYMBOL] = new channel_1.ChannelImplementation(address, credentials, options); - } - } - close() { - this[CHANNEL_SYMBOL].close(); - } - getChannel() { - return this[CHANNEL_SYMBOL]; - } - waitForReady(deadline, callback) { - const checkState = (err) => { - if (err) { - callback(new Error('Failed to connect before the deadline')); - return; - } - let newState; - try { - newState = this[CHANNEL_SYMBOL].getConnectivityState(true); - } - catch (e) { - callback(new Error('The channel has been closed')); - return; - } - if (newState === connectivity_state_1.ConnectivityState.READY) { - callback(); - } - else { - try { - this[CHANNEL_SYMBOL].watchConnectivityState(newState, deadline, checkState); - } - catch (e) { - callback(new Error('The channel has been closed')); - } - } - }; - setImmediate(checkState); - } - checkOptionalUnaryResponseArguments(arg1, arg2, arg3) { - if (isFunction(arg1)) { - return { metadata: new metadata_1.Metadata(), options: {}, callback: arg1 }; - } - else if (isFunction(arg2)) { - if (arg1 instanceof metadata_1.Metadata) { - return { metadata: arg1, options: {}, callback: arg2 }; - } - else { - return { metadata: new metadata_1.Metadata(), options: arg1, callback: arg2 }; - } - } - else { - if (!(arg1 instanceof metadata_1.Metadata && - arg2 instanceof Object && - isFunction(arg3))) { - throw new Error('Incorrect arguments passed'); - } - return { metadata: arg1, options: arg2, callback: arg3 }; - } - } - makeUnaryRequest(method, serialize, deserialize, argument, metadata, options, callback) { - var _a, _b; - const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options, callback); - const methodDefinition = { - path: method, - requestStream: false, - responseStream: false, - requestSerialize: serialize, - responseDeserialize: deserialize, - }; - let callProperties = { - argument: argument, - metadata: checkedArguments.metadata, - call: new call_1.ClientUnaryCallImpl(), - channel: this[CHANNEL_SYMBOL], - methodDefinition: methodDefinition, - callOptions: checkedArguments.options, - callback: checkedArguments.callback, - }; - if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { - callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); - } - const emitter = callProperties.call; - const interceptorArgs = { - clientInterceptors: this[INTERCEPTOR_SYMBOL], - clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], - callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], - callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [], - }; - const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); - /* This needs to happen before the emitter is used. Unfortunately we can't - * enforce this with the type system. We need to construct this emitter - * before calling the CallInvocationTransformer, and we need to create the - * call after that. */ - emitter.call = call; - let responseMessage = null; - let receivedStatus = false; - let callerStackError = new Error(); - call.start(callProperties.metadata, { - onReceiveMetadata: metadata => { - emitter.emit('metadata', metadata); - }, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onReceiveMessage(message) { - if (responseMessage !== null) { - call.cancelWithStatus(constants_1.Status.UNIMPLEMENTED, 'Too many responses received'); - } - responseMessage = message; - }, - onReceiveStatus(status) { - if (receivedStatus) { - return; - } - receivedStatus = true; - if (status.code === constants_1.Status.OK) { - if (responseMessage === null) { - const callerStack = getErrorStackString(callerStackError); - callProperties.callback((0, call_1.callErrorFromStatus)({ - code: constants_1.Status.UNIMPLEMENTED, - details: 'No message received', - metadata: status.metadata, - }, callerStack)); - } - else { - callProperties.callback(null, responseMessage); - } - } - else { - const callerStack = getErrorStackString(callerStackError); - callProperties.callback((0, call_1.callErrorFromStatus)(status, callerStack)); - } - /* Avoid retaining the callerStackError object in the call context of - * the status event handler. */ - callerStackError = null; - emitter.emit('status', status); - }, - }); - call.sendMessage(argument); - call.halfClose(); - return emitter; - } - makeClientStreamRequest(method, serialize, deserialize, metadata, options, callback) { - var _a, _b; - const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options, callback); - const methodDefinition = { - path: method, - requestStream: true, - responseStream: false, - requestSerialize: serialize, - responseDeserialize: deserialize, - }; - let callProperties = { - metadata: checkedArguments.metadata, - call: new call_1.ClientWritableStreamImpl(serialize), - channel: this[CHANNEL_SYMBOL], - methodDefinition: methodDefinition, - callOptions: checkedArguments.options, - callback: checkedArguments.callback, - }; - if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { - callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); - } - const emitter = callProperties.call; - const interceptorArgs = { - clientInterceptors: this[INTERCEPTOR_SYMBOL], - clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], - callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], - callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [], - }; - const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); - /* This needs to happen before the emitter is used. Unfortunately we can't - * enforce this with the type system. We need to construct this emitter - * before calling the CallInvocationTransformer, and we need to create the - * call after that. */ - emitter.call = call; - let responseMessage = null; - let receivedStatus = false; - let callerStackError = new Error(); - call.start(callProperties.metadata, { - onReceiveMetadata: metadata => { - emitter.emit('metadata', metadata); - }, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onReceiveMessage(message) { - if (responseMessage !== null) { - call.cancelWithStatus(constants_1.Status.UNIMPLEMENTED, 'Too many responses received'); - } - responseMessage = message; - call.startRead(); - }, - onReceiveStatus(status) { - if (receivedStatus) { - return; - } - receivedStatus = true; - if (status.code === constants_1.Status.OK) { - if (responseMessage === null) { - const callerStack = getErrorStackString(callerStackError); - callProperties.callback((0, call_1.callErrorFromStatus)({ - code: constants_1.Status.UNIMPLEMENTED, - details: 'No message received', - metadata: status.metadata, - }, callerStack)); - } - else { - callProperties.callback(null, responseMessage); - } - } - else { - const callerStack = getErrorStackString(callerStackError); - callProperties.callback((0, call_1.callErrorFromStatus)(status, callerStack)); - } - /* Avoid retaining the callerStackError object in the call context of - * the status event handler. */ - callerStackError = null; - emitter.emit('status', status); - }, - }); - return emitter; - } - checkMetadataAndOptions(arg1, arg2) { - let metadata; - let options; - if (arg1 instanceof metadata_1.Metadata) { - metadata = arg1; - if (arg2) { - options = arg2; - } - else { - options = {}; - } - } - else { - if (arg1) { - options = arg1; - } - else { - options = {}; - } - metadata = new metadata_1.Metadata(); - } - return { metadata, options }; - } - makeServerStreamRequest(method, serialize, deserialize, argument, metadata, options) { - var _a, _b; - const checkedArguments = this.checkMetadataAndOptions(metadata, options); - const methodDefinition = { - path: method, - requestStream: false, - responseStream: true, - requestSerialize: serialize, - responseDeserialize: deserialize, - }; - let callProperties = { - argument: argument, - metadata: checkedArguments.metadata, - call: new call_1.ClientReadableStreamImpl(deserialize), - channel: this[CHANNEL_SYMBOL], - methodDefinition: methodDefinition, - callOptions: checkedArguments.options, - }; - if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { - callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); - } - const stream = callProperties.call; - const interceptorArgs = { - clientInterceptors: this[INTERCEPTOR_SYMBOL], - clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], - callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], - callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [], - }; - const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); - /* This needs to happen before the emitter is used. Unfortunately we can't - * enforce this with the type system. We need to construct this emitter - * before calling the CallInvocationTransformer, and we need to create the - * call after that. */ - stream.call = call; - let receivedStatus = false; - let callerStackError = new Error(); - call.start(callProperties.metadata, { - onReceiveMetadata(metadata) { - stream.emit('metadata', metadata); - }, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - onReceiveMessage(message) { - stream.push(message); - }, - onReceiveStatus(status) { - if (receivedStatus) { - return; - } - receivedStatus = true; - stream.push(null); - if (status.code !== constants_1.Status.OK) { - const callerStack = getErrorStackString(callerStackError); - stream.emit('error', (0, call_1.callErrorFromStatus)(status, callerStack)); - } - /* Avoid retaining the callerStackError object in the call context of - * the status event handler. */ - callerStackError = null; - stream.emit('status', status); - }, - }); - call.sendMessage(argument); - call.halfClose(); - return stream; - } - makeBidiStreamRequest(method, serialize, deserialize, metadata, options) { - var _a, _b; - const checkedArguments = this.checkMetadataAndOptions(metadata, options); - const methodDefinition = { - path: method, - requestStream: true, - responseStream: true, - requestSerialize: serialize, - responseDeserialize: deserialize, - }; - let callProperties = { - metadata: checkedArguments.metadata, - call: new call_1.ClientDuplexStreamImpl(serialize, deserialize), - channel: this[CHANNEL_SYMBOL], - methodDefinition: methodDefinition, - callOptions: checkedArguments.options, - }; - if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { - callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); - } - const stream = callProperties.call; - const interceptorArgs = { - clientInterceptors: this[INTERCEPTOR_SYMBOL], - clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], - callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], - callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [], - }; - const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); - /* This needs to happen before the emitter is used. Unfortunately we can't - * enforce this with the type system. We need to construct this emitter - * before calling the CallInvocationTransformer, and we need to create the - * call after that. */ - stream.call = call; - let receivedStatus = false; - let callerStackError = new Error(); - call.start(callProperties.metadata, { - onReceiveMetadata(metadata) { - stream.emit('metadata', metadata); - }, - onReceiveMessage(message) { - stream.push(message); - }, - onReceiveStatus(status) { - if (receivedStatus) { - return; - } - receivedStatus = true; - stream.push(null); - if (status.code !== constants_1.Status.OK) { - const callerStack = getErrorStackString(callerStackError); - stream.emit('error', (0, call_1.callErrorFromStatus)(status, callerStack)); - } - /* Avoid retaining the callerStackError object in the call context of - * the status event handler. */ - callerStackError = null; - stream.emit('status', status); - }, - }); - return stream; - } -} -exports.Client = Client; -//# sourceMappingURL=client.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/compression-algorithms.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/compression-algorithms.js deleted file mode 100644 index 15a4f00b..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/compression-algorithms.js +++ /dev/null @@ -1,26 +0,0 @@ -"use strict"; -/* - * Copyright 2021 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CompressionAlgorithms = void 0; -var CompressionAlgorithms; -(function (CompressionAlgorithms) { - CompressionAlgorithms[CompressionAlgorithms["identity"] = 0] = "identity"; - CompressionAlgorithms[CompressionAlgorithms["deflate"] = 1] = "deflate"; - CompressionAlgorithms[CompressionAlgorithms["gzip"] = 2] = "gzip"; -})(CompressionAlgorithms || (exports.CompressionAlgorithms = CompressionAlgorithms = {})); -//# sourceMappingURL=compression-algorithms.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/compression-filter.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/compression-filter.js deleted file mode 100644 index a0af9f99..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/compression-filter.js +++ /dev/null @@ -1,295 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CompressionFilterFactory = exports.CompressionFilter = void 0; -const zlib = require("zlib"); -const compression_algorithms_1 = require("./compression-algorithms"); -const constants_1 = require("./constants"); -const filter_1 = require("./filter"); -const logging = require("./logging"); -const isCompressionAlgorithmKey = (key) => { - return (typeof key === 'number' && typeof compression_algorithms_1.CompressionAlgorithms[key] === 'string'); -}; -class CompressionHandler { - /** - * @param message Raw uncompressed message bytes - * @param compress Indicates whether the message should be compressed - * @return Framed message, compressed if applicable - */ - async writeMessage(message, compress) { - let messageBuffer = message; - if (compress) { - messageBuffer = await this.compressMessage(messageBuffer); - } - const output = Buffer.allocUnsafe(messageBuffer.length + 5); - output.writeUInt8(compress ? 1 : 0, 0); - output.writeUInt32BE(messageBuffer.length, 1); - messageBuffer.copy(output, 5); - return output; - } - /** - * @param data Framed message, possibly compressed - * @return Uncompressed message - */ - async readMessage(data) { - const compressed = data.readUInt8(0) === 1; - let messageBuffer = data.slice(5); - if (compressed) { - messageBuffer = await this.decompressMessage(messageBuffer); - } - return messageBuffer; - } -} -class IdentityHandler extends CompressionHandler { - async compressMessage(message) { - return message; - } - async writeMessage(message, compress) { - const output = Buffer.allocUnsafe(message.length + 5); - /* With "identity" compression, messages should always be marked as - * uncompressed */ - output.writeUInt8(0, 0); - output.writeUInt32BE(message.length, 1); - message.copy(output, 5); - return output; - } - decompressMessage(message) { - return Promise.reject(new Error('Received compressed message but "grpc-encoding" header was identity')); - } -} -class DeflateHandler extends CompressionHandler { - constructor(maxRecvMessageLength) { - super(); - this.maxRecvMessageLength = maxRecvMessageLength; - } - compressMessage(message) { - return new Promise((resolve, reject) => { - zlib.deflate(message, (err, output) => { - if (err) { - reject(err); - } - else { - resolve(output); - } - }); - }); - } - decompressMessage(message) { - return new Promise((resolve, reject) => { - let totalLength = 0; - const messageParts = []; - const decompresser = zlib.createInflate(); - decompresser.on('data', (chunk) => { - messageParts.push(chunk); - totalLength += chunk.byteLength; - if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) { - decompresser.destroy(); - reject({ - code: constants_1.Status.RESOURCE_EXHAUSTED, - details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}` - }); - } - }); - decompresser.on('end', () => { - resolve(Buffer.concat(messageParts)); - }); - decompresser.write(message); - decompresser.end(); - }); - } -} -class GzipHandler extends CompressionHandler { - constructor(maxRecvMessageLength) { - super(); - this.maxRecvMessageLength = maxRecvMessageLength; - } - compressMessage(message) { - return new Promise((resolve, reject) => { - zlib.gzip(message, (err, output) => { - if (err) { - reject(err); - } - else { - resolve(output); - } - }); - }); - } - decompressMessage(message) { - return new Promise((resolve, reject) => { - let totalLength = 0; - const messageParts = []; - const decompresser = zlib.createGunzip(); - decompresser.on('data', (chunk) => { - messageParts.push(chunk); - totalLength += chunk.byteLength; - if (this.maxRecvMessageLength !== -1 && totalLength > this.maxRecvMessageLength) { - decompresser.destroy(); - reject({ - code: constants_1.Status.RESOURCE_EXHAUSTED, - details: `Received message that decompresses to a size larger than ${this.maxRecvMessageLength}` - }); - } - }); - decompresser.on('end', () => { - resolve(Buffer.concat(messageParts)); - }); - decompresser.write(message); - decompresser.end(); - }); - } -} -class UnknownHandler extends CompressionHandler { - constructor(compressionName) { - super(); - this.compressionName = compressionName; - } - compressMessage(message) { - return Promise.reject(new Error(`Received message compressed with unsupported compression method ${this.compressionName}`)); - } - decompressMessage(message) { - // This should be unreachable - return Promise.reject(new Error(`Compression method not supported: ${this.compressionName}`)); - } -} -function getCompressionHandler(compressionName, maxReceiveMessageSize) { - switch (compressionName) { - case 'identity': - return new IdentityHandler(); - case 'deflate': - return new DeflateHandler(maxReceiveMessageSize); - case 'gzip': - return new GzipHandler(maxReceiveMessageSize); - default: - return new UnknownHandler(compressionName); - } -} -class CompressionFilter extends filter_1.BaseFilter { - constructor(channelOptions, sharedFilterConfig) { - var _a, _b, _c; - super(); - this.sharedFilterConfig = sharedFilterConfig; - this.sendCompression = new IdentityHandler(); - this.receiveCompression = new IdentityHandler(); - this.currentCompressionAlgorithm = 'identity'; - const compressionAlgorithmKey = channelOptions['grpc.default_compression_algorithm']; - this.maxReceiveMessageLength = (_a = channelOptions['grpc.max_receive_message_length']) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; - this.maxSendMessageLength = (_b = channelOptions['grpc.max_send_message_length']) !== null && _b !== void 0 ? _b : constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH; - if (compressionAlgorithmKey !== undefined) { - if (isCompressionAlgorithmKey(compressionAlgorithmKey)) { - const clientSelectedEncoding = compression_algorithms_1.CompressionAlgorithms[compressionAlgorithmKey]; - const serverSupportedEncodings = (_c = sharedFilterConfig.serverSupportedEncodingHeader) === null || _c === void 0 ? void 0 : _c.split(','); - /** - * There are two possible situations here: - * 1) We don't have any info yet from the server about what compression it supports - * In that case we should just use what the client tells us to use - * 2) We've previously received a response from the server including a grpc-accept-encoding header - * In that case we only want to use the encoding chosen by the client if the server supports it - */ - if (!serverSupportedEncodings || - serverSupportedEncodings.includes(clientSelectedEncoding)) { - this.currentCompressionAlgorithm = clientSelectedEncoding; - this.sendCompression = getCompressionHandler(this.currentCompressionAlgorithm, -1); - } - } - else { - logging.log(constants_1.LogVerbosity.ERROR, `Invalid value provided for grpc.default_compression_algorithm option: ${compressionAlgorithmKey}`); - } - } - } - async sendMetadata(metadata) { - const headers = await metadata; - headers.set('grpc-accept-encoding', 'identity,deflate,gzip'); - headers.set('accept-encoding', 'identity'); - // No need to send the header if it's "identity" - behavior is identical; save the bandwidth - if (this.currentCompressionAlgorithm === 'identity') { - headers.remove('grpc-encoding'); - } - else { - headers.set('grpc-encoding', this.currentCompressionAlgorithm); - } - return headers; - } - receiveMetadata(metadata) { - const receiveEncoding = metadata.get('grpc-encoding'); - if (receiveEncoding.length > 0) { - const encoding = receiveEncoding[0]; - if (typeof encoding === 'string') { - this.receiveCompression = getCompressionHandler(encoding, this.maxReceiveMessageLength); - } - } - metadata.remove('grpc-encoding'); - /* Check to see if the compression we're using to send messages is supported by the server - * If not, reset the sendCompression filter and have it use the default IdentityHandler */ - const serverSupportedEncodingsHeader = metadata.get('grpc-accept-encoding')[0]; - if (serverSupportedEncodingsHeader) { - this.sharedFilterConfig.serverSupportedEncodingHeader = - serverSupportedEncodingsHeader; - const serverSupportedEncodings = serverSupportedEncodingsHeader.split(','); - if (!serverSupportedEncodings.includes(this.currentCompressionAlgorithm)) { - this.sendCompression = new IdentityHandler(); - this.currentCompressionAlgorithm = 'identity'; - } - } - metadata.remove('grpc-accept-encoding'); - return metadata; - } - async sendMessage(message) { - var _a; - /* This filter is special. The input message is the bare message bytes, - * and the output is a framed and possibly compressed message. For this - * reason, this filter should be at the bottom of the filter stack */ - const resolvedMessage = await message; - if (this.maxSendMessageLength !== -1 && resolvedMessage.message.length > this.maxSendMessageLength) { - throw { - code: constants_1.Status.RESOURCE_EXHAUSTED, - details: `Attempted to send message with a size larger than ${this.maxSendMessageLength}` - }; - } - let compress; - if (this.sendCompression instanceof IdentityHandler) { - compress = false; - } - else { - compress = (((_a = resolvedMessage.flags) !== null && _a !== void 0 ? _a : 0) & 2 /* WriteFlags.NoCompress */) === 0; - } - return { - message: await this.sendCompression.writeMessage(resolvedMessage.message, compress), - flags: resolvedMessage.flags, - }; - } - async receiveMessage(message) { - /* This filter is also special. The input message is framed and possibly - * compressed, and the output message is deframed and uncompressed. So - * this is another reason that this filter should be at the bottom of the - * filter stack. */ - return this.receiveCompression.readMessage(await message); - } -} -exports.CompressionFilter = CompressionFilter; -class CompressionFilterFactory { - constructor(channel, options) { - this.options = options; - this.sharedFilterConfig = {}; - } - createFilter() { - return new CompressionFilter(this.options, this.sharedFilterConfig); - } -} -exports.CompressionFilterFactory = CompressionFilterFactory; -//# sourceMappingURL=compression-filter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/connectivity-state.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/connectivity-state.js deleted file mode 100644 index c8540b00..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/connectivity-state.js +++ /dev/null @@ -1,28 +0,0 @@ -"use strict"; -/* - * Copyright 2021 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConnectivityState = void 0; -var ConnectivityState; -(function (ConnectivityState) { - ConnectivityState[ConnectivityState["IDLE"] = 0] = "IDLE"; - ConnectivityState[ConnectivityState["CONNECTING"] = 1] = "CONNECTING"; - ConnectivityState[ConnectivityState["READY"] = 2] = "READY"; - ConnectivityState[ConnectivityState["TRANSIENT_FAILURE"] = 3] = "TRANSIENT_FAILURE"; - ConnectivityState[ConnectivityState["SHUTDOWN"] = 4] = "SHUTDOWN"; -})(ConnectivityState || (exports.ConnectivityState = ConnectivityState = {})); -//# sourceMappingURL=connectivity-state.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/constants.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/constants.js deleted file mode 100644 index 6e6b8ede..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/constants.js +++ /dev/null @@ -1,64 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = exports.DEFAULT_MAX_SEND_MESSAGE_LENGTH = exports.Propagate = exports.LogVerbosity = exports.Status = void 0; -var Status; -(function (Status) { - Status[Status["OK"] = 0] = "OK"; - Status[Status["CANCELLED"] = 1] = "CANCELLED"; - Status[Status["UNKNOWN"] = 2] = "UNKNOWN"; - Status[Status["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT"; - Status[Status["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED"; - Status[Status["NOT_FOUND"] = 5] = "NOT_FOUND"; - Status[Status["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS"; - Status[Status["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED"; - Status[Status["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED"; - Status[Status["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION"; - Status[Status["ABORTED"] = 10] = "ABORTED"; - Status[Status["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE"; - Status[Status["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED"; - Status[Status["INTERNAL"] = 13] = "INTERNAL"; - Status[Status["UNAVAILABLE"] = 14] = "UNAVAILABLE"; - Status[Status["DATA_LOSS"] = 15] = "DATA_LOSS"; - Status[Status["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED"; -})(Status || (exports.Status = Status = {})); -var LogVerbosity; -(function (LogVerbosity) { - LogVerbosity[LogVerbosity["DEBUG"] = 0] = "DEBUG"; - LogVerbosity[LogVerbosity["INFO"] = 1] = "INFO"; - LogVerbosity[LogVerbosity["ERROR"] = 2] = "ERROR"; - LogVerbosity[LogVerbosity["NONE"] = 3] = "NONE"; -})(LogVerbosity || (exports.LogVerbosity = LogVerbosity = {})); -/** - * NOTE: This enum is not currently used in any implemented API in this - * library. It is included only for type parity with the other implementation. - */ -var Propagate; -(function (Propagate) { - Propagate[Propagate["DEADLINE"] = 1] = "DEADLINE"; - Propagate[Propagate["CENSUS_STATS_CONTEXT"] = 2] = "CENSUS_STATS_CONTEXT"; - Propagate[Propagate["CENSUS_TRACING_CONTEXT"] = 4] = "CENSUS_TRACING_CONTEXT"; - Propagate[Propagate["CANCELLATION"] = 8] = "CANCELLATION"; - // https://github.com/grpc/grpc/blob/master/include/grpc/impl/codegen/propagation_bits.h#L43 - Propagate[Propagate["DEFAULTS"] = 65535] = "DEFAULTS"; -})(Propagate || (exports.Propagate = Propagate = {})); -// -1 means unlimited -exports.DEFAULT_MAX_SEND_MESSAGE_LENGTH = -1; -// 4 MB default -exports.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = 4 * 1024 * 1024; -//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/control-plane-status.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/control-plane-status.js deleted file mode 100644 index 5d55796b..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/control-plane-status.js +++ /dev/null @@ -1,42 +0,0 @@ -"use strict"; -/* - * Copyright 2022 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.restrictControlPlaneStatusCode = restrictControlPlaneStatusCode; -const constants_1 = require("./constants"); -const INAPPROPRIATE_CONTROL_PLANE_CODES = [ - constants_1.Status.OK, - constants_1.Status.INVALID_ARGUMENT, - constants_1.Status.NOT_FOUND, - constants_1.Status.ALREADY_EXISTS, - constants_1.Status.FAILED_PRECONDITION, - constants_1.Status.ABORTED, - constants_1.Status.OUT_OF_RANGE, - constants_1.Status.DATA_LOSS, -]; -function restrictControlPlaneStatusCode(code, details) { - if (INAPPROPRIATE_CONTROL_PLANE_CODES.includes(code)) { - return { - code: constants_1.Status.INTERNAL, - details: `Invalid status from control plane: ${code} ${constants_1.Status[code]} ${details}`, - }; - } - else { - return { code, details }; - } -} -//# sourceMappingURL=control-plane-status.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/deadline.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/deadline.js deleted file mode 100644 index 8b4a39e1..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/deadline.js +++ /dev/null @@ -1,108 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.minDeadline = minDeadline; -exports.getDeadlineTimeoutString = getDeadlineTimeoutString; -exports.getRelativeTimeout = getRelativeTimeout; -exports.deadlineToString = deadlineToString; -exports.formatDateDifference = formatDateDifference; -function minDeadline(...deadlineList) { - let minValue = Infinity; - for (const deadline of deadlineList) { - const deadlineMsecs = deadline instanceof Date ? deadline.getTime() : deadline; - if (deadlineMsecs < minValue) { - minValue = deadlineMsecs; - } - } - return minValue; -} -const units = [ - ['m', 1], - ['S', 1000], - ['M', 60 * 1000], - ['H', 60 * 60 * 1000], -]; -function getDeadlineTimeoutString(deadline) { - const now = new Date().getTime(); - if (deadline instanceof Date) { - deadline = deadline.getTime(); - } - const timeoutMs = Math.max(deadline - now, 0); - for (const [unit, factor] of units) { - const amount = timeoutMs / factor; - if (amount < 1e8) { - return String(Math.ceil(amount)) + unit; - } - } - throw new Error('Deadline is too far in the future'); -} -/** - * See https://nodejs.org/api/timers.html#settimeoutcallback-delay-args - * In particular, "When delay is larger than 2147483647 or less than 1, the - * delay will be set to 1. Non-integer delays are truncated to an integer." - * This number of milliseconds is almost 25 days. - */ -const MAX_TIMEOUT_TIME = 2147483647; -/** - * Get the timeout value that should be passed to setTimeout now for the timer - * to end at the deadline. For any deadline before now, the timer should end - * immediately, represented by a value of 0. For any deadline more than - * MAX_TIMEOUT_TIME milliseconds in the future, a timer cannot be set that will - * end at that time, so it is treated as infinitely far in the future. - * @param deadline - * @returns - */ -function getRelativeTimeout(deadline) { - const deadlineMs = deadline instanceof Date ? deadline.getTime() : deadline; - const now = new Date().getTime(); - const timeout = deadlineMs - now; - if (timeout < 0) { - return 0; - } - else if (timeout > MAX_TIMEOUT_TIME) { - return Infinity; - } - else { - return timeout; - } -} -function deadlineToString(deadline) { - if (deadline instanceof Date) { - return deadline.toISOString(); - } - else { - const dateDeadline = new Date(deadline); - if (Number.isNaN(dateDeadline.getTime())) { - return '' + deadline; - } - else { - return dateDeadline.toISOString(); - } - } -} -/** - * Calculate the difference between two dates as a number of seconds and format - * it as a string. - * @param startDate - * @param endDate - * @returns - */ -function formatDateDifference(startDate, endDate) { - return ((endDate.getTime() - startDate.getTime()) / 1000).toFixed(3) + 's'; -} -//# sourceMappingURL=deadline.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/duration.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/duration.js deleted file mode 100644 index f48caa57..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/duration.js +++ /dev/null @@ -1,74 +0,0 @@ -"use strict"; -/* - * Copyright 2022 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.durationMessageToDuration = durationMessageToDuration; -exports.msToDuration = msToDuration; -exports.durationToMs = durationToMs; -exports.isDuration = isDuration; -exports.isDurationMessage = isDurationMessage; -exports.parseDuration = parseDuration; -exports.durationToString = durationToString; -function durationMessageToDuration(message) { - return { - seconds: Number.parseInt(message.seconds), - nanos: message.nanos - }; -} -function msToDuration(millis) { - return { - seconds: (millis / 1000) | 0, - nanos: ((millis % 1000) * 1000000) | 0, - }; -} -function durationToMs(duration) { - return (duration.seconds * 1000 + duration.nanos / 1000000) | 0; -} -function isDuration(value) { - return typeof value.seconds === 'number' && typeof value.nanos === 'number'; -} -function isDurationMessage(value) { - return typeof value.seconds === 'string' && typeof value.nanos === 'number'; -} -const durationRegex = /^(\d+)(?:\.(\d+))?s$/; -function parseDuration(value) { - const match = value.match(durationRegex); - if (!match) { - return null; - } - return { - seconds: Number.parseInt(match[1], 10), - nanos: match[2] ? Number.parseInt(match[2].padEnd(9, '0'), 10) : 0 - }; -} -function durationToString(duration) { - if (duration.nanos === 0) { - return `${duration.seconds}s`; - } - let scaleFactor; - if (duration.nanos % 1000000 === 0) { - scaleFactor = 1000000; - } - else if (duration.nanos % 1000 === 0) { - scaleFactor = 1000; - } - else { - scaleFactor = 1; - } - return `${duration.seconds}.${duration.nanos / scaleFactor}s`; -} -//# sourceMappingURL=duration.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/environment.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/environment.js deleted file mode 100644 index e8d67c2a..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/environment.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -/* - * Copyright 2024 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -var _a; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = void 0; -exports.GRPC_NODE_USE_ALTERNATIVE_RESOLVER = ((_a = process.env.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) !== null && _a !== void 0 ? _a : 'false') === 'true'; -//# sourceMappingURL=environment.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/error.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/error.js deleted file mode 100644 index 5cb15398..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/error.js +++ /dev/null @@ -1,40 +0,0 @@ -"use strict"; -/* - * Copyright 2022 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getErrorMessage = getErrorMessage; -exports.getErrorCode = getErrorCode; -function getErrorMessage(error) { - if (error instanceof Error) { - return error.message; - } - else { - return String(error); - } -} -function getErrorCode(error) { - if (typeof error === 'object' && - error !== null && - 'code' in error && - typeof error.code === 'number') { - return error.code; - } - else { - return null; - } -} -//# sourceMappingURL=error.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/experimental.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/experimental.js deleted file mode 100644 index 3f2835c6..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/experimental.js +++ /dev/null @@ -1,58 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = exports.createCertificateProviderChannelCredentials = exports.FileWatcherCertificateProvider = exports.createCertificateProviderServerCredentials = exports.createServerCredentialsWithInterceptors = exports.BaseSubchannelWrapper = exports.registerAdminService = exports.FilterStackFactory = exports.BaseFilter = exports.statusOrFromError = exports.statusOrFromValue = exports.PickResultType = exports.QueuePicker = exports.UnavailablePicker = exports.ChildLoadBalancerHandler = exports.EndpointMap = exports.endpointHasAddress = exports.endpointToString = exports.subchannelAddressToString = exports.LeafLoadBalancer = exports.isLoadBalancerNameRegistered = exports.parseLoadBalancingConfig = exports.selectLbConfigFromList = exports.registerLoadBalancerType = exports.createChildChannelControlHelper = exports.BackoffTimeout = exports.parseDuration = exports.durationToMs = exports.splitHostPort = exports.uriToString = exports.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = exports.createResolver = exports.registerResolver = exports.log = exports.trace = void 0; -var logging_1 = require("./logging"); -Object.defineProperty(exports, "trace", { enumerable: true, get: function () { return logging_1.trace; } }); -Object.defineProperty(exports, "log", { enumerable: true, get: function () { return logging_1.log; } }); -var resolver_1 = require("./resolver"); -Object.defineProperty(exports, "registerResolver", { enumerable: true, get: function () { return resolver_1.registerResolver; } }); -Object.defineProperty(exports, "createResolver", { enumerable: true, get: function () { return resolver_1.createResolver; } }); -Object.defineProperty(exports, "CHANNEL_ARGS_CONFIG_SELECTOR_KEY", { enumerable: true, get: function () { return resolver_1.CHANNEL_ARGS_CONFIG_SELECTOR_KEY; } }); -var uri_parser_1 = require("./uri-parser"); -Object.defineProperty(exports, "uriToString", { enumerable: true, get: function () { return uri_parser_1.uriToString; } }); -Object.defineProperty(exports, "splitHostPort", { enumerable: true, get: function () { return uri_parser_1.splitHostPort; } }); -var duration_1 = require("./duration"); -Object.defineProperty(exports, "durationToMs", { enumerable: true, get: function () { return duration_1.durationToMs; } }); -Object.defineProperty(exports, "parseDuration", { enumerable: true, get: function () { return duration_1.parseDuration; } }); -var backoff_timeout_1 = require("./backoff-timeout"); -Object.defineProperty(exports, "BackoffTimeout", { enumerable: true, get: function () { return backoff_timeout_1.BackoffTimeout; } }); -var load_balancer_1 = require("./load-balancer"); -Object.defineProperty(exports, "createChildChannelControlHelper", { enumerable: true, get: function () { return load_balancer_1.createChildChannelControlHelper; } }); -Object.defineProperty(exports, "registerLoadBalancerType", { enumerable: true, get: function () { return load_balancer_1.registerLoadBalancerType; } }); -Object.defineProperty(exports, "selectLbConfigFromList", { enumerable: true, get: function () { return load_balancer_1.selectLbConfigFromList; } }); -Object.defineProperty(exports, "parseLoadBalancingConfig", { enumerable: true, get: function () { return load_balancer_1.parseLoadBalancingConfig; } }); -Object.defineProperty(exports, "isLoadBalancerNameRegistered", { enumerable: true, get: function () { return load_balancer_1.isLoadBalancerNameRegistered; } }); -var load_balancer_pick_first_1 = require("./load-balancer-pick-first"); -Object.defineProperty(exports, "LeafLoadBalancer", { enumerable: true, get: function () { return load_balancer_pick_first_1.LeafLoadBalancer; } }); -var subchannel_address_1 = require("./subchannel-address"); -Object.defineProperty(exports, "subchannelAddressToString", { enumerable: true, get: function () { return subchannel_address_1.subchannelAddressToString; } }); -Object.defineProperty(exports, "endpointToString", { enumerable: true, get: function () { return subchannel_address_1.endpointToString; } }); -Object.defineProperty(exports, "endpointHasAddress", { enumerable: true, get: function () { return subchannel_address_1.endpointHasAddress; } }); -Object.defineProperty(exports, "EndpointMap", { enumerable: true, get: function () { return subchannel_address_1.EndpointMap; } }); -var load_balancer_child_handler_1 = require("./load-balancer-child-handler"); -Object.defineProperty(exports, "ChildLoadBalancerHandler", { enumerable: true, get: function () { return load_balancer_child_handler_1.ChildLoadBalancerHandler; } }); -var picker_1 = require("./picker"); -Object.defineProperty(exports, "UnavailablePicker", { enumerable: true, get: function () { return picker_1.UnavailablePicker; } }); -Object.defineProperty(exports, "QueuePicker", { enumerable: true, get: function () { return picker_1.QueuePicker; } }); -Object.defineProperty(exports, "PickResultType", { enumerable: true, get: function () { return picker_1.PickResultType; } }); -var call_interface_1 = require("./call-interface"); -Object.defineProperty(exports, "statusOrFromValue", { enumerable: true, get: function () { return call_interface_1.statusOrFromValue; } }); -Object.defineProperty(exports, "statusOrFromError", { enumerable: true, get: function () { return call_interface_1.statusOrFromError; } }); -var filter_1 = require("./filter"); -Object.defineProperty(exports, "BaseFilter", { enumerable: true, get: function () { return filter_1.BaseFilter; } }); -var filter_stack_1 = require("./filter-stack"); -Object.defineProperty(exports, "FilterStackFactory", { enumerable: true, get: function () { return filter_stack_1.FilterStackFactory; } }); -var admin_1 = require("./admin"); -Object.defineProperty(exports, "registerAdminService", { enumerable: true, get: function () { return admin_1.registerAdminService; } }); -var subchannel_interface_1 = require("./subchannel-interface"); -Object.defineProperty(exports, "BaseSubchannelWrapper", { enumerable: true, get: function () { return subchannel_interface_1.BaseSubchannelWrapper; } }); -var server_credentials_1 = require("./server-credentials"); -Object.defineProperty(exports, "createServerCredentialsWithInterceptors", { enumerable: true, get: function () { return server_credentials_1.createServerCredentialsWithInterceptors; } }); -Object.defineProperty(exports, "createCertificateProviderServerCredentials", { enumerable: true, get: function () { return server_credentials_1.createCertificateProviderServerCredentials; } }); -var certificate_provider_1 = require("./certificate-provider"); -Object.defineProperty(exports, "FileWatcherCertificateProvider", { enumerable: true, get: function () { return certificate_provider_1.FileWatcherCertificateProvider; } }); -var channel_credentials_1 = require("./channel-credentials"); -Object.defineProperty(exports, "createCertificateProviderChannelCredentials", { enumerable: true, get: function () { return channel_credentials_1.createCertificateProviderChannelCredentials; } }); -var internal_channel_1 = require("./internal-channel"); -Object.defineProperty(exports, "SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX", { enumerable: true, get: function () { return internal_channel_1.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX; } }); -//# sourceMappingURL=experimental.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/filter-stack.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/filter-stack.js deleted file mode 100644 index 6cf2e1a0..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/filter-stack.js +++ /dev/null @@ -1,82 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.FilterStackFactory = exports.FilterStack = void 0; -class FilterStack { - constructor(filters) { - this.filters = filters; - } - sendMetadata(metadata) { - let result = metadata; - for (let i = 0; i < this.filters.length; i++) { - result = this.filters[i].sendMetadata(result); - } - return result; - } - receiveMetadata(metadata) { - let result = metadata; - for (let i = this.filters.length - 1; i >= 0; i--) { - result = this.filters[i].receiveMetadata(result); - } - return result; - } - sendMessage(message) { - let result = message; - for (let i = 0; i < this.filters.length; i++) { - result = this.filters[i].sendMessage(result); - } - return result; - } - receiveMessage(message) { - let result = message; - for (let i = this.filters.length - 1; i >= 0; i--) { - result = this.filters[i].receiveMessage(result); - } - return result; - } - receiveTrailers(status) { - let result = status; - for (let i = this.filters.length - 1; i >= 0; i--) { - result = this.filters[i].receiveTrailers(result); - } - return result; - } - push(filters) { - this.filters.unshift(...filters); - } - getFilters() { - return this.filters; - } -} -exports.FilterStack = FilterStack; -class FilterStackFactory { - constructor(factories) { - this.factories = factories; - } - push(filterFactories) { - this.factories.unshift(...filterFactories); - } - clone() { - return new FilterStackFactory([...this.factories]); - } - createFilter() { - return new FilterStack(this.factories.map(factory => factory.createFilter())); - } -} -exports.FilterStackFactory = FilterStackFactory; -//# sourceMappingURL=filter-stack.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/filter.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/filter.js deleted file mode 100644 index d888a82e..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/filter.js +++ /dev/null @@ -1,38 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BaseFilter = void 0; -class BaseFilter { - async sendMetadata(metadata) { - return metadata; - } - receiveMetadata(metadata) { - return metadata; - } - async sendMessage(message) { - return message; - } - async receiveMessage(message) { - return message; - } - receiveTrailers(status) { - return status; - } -} -exports.BaseFilter = BaseFilter; -//# sourceMappingURL=filter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/http_proxy.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/http_proxy.js deleted file mode 100644 index 114017cd..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/http_proxy.js +++ /dev/null @@ -1,274 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.parseCIDR = parseCIDR; -exports.mapProxyName = mapProxyName; -exports.getProxiedConnection = getProxiedConnection; -const logging_1 = require("./logging"); -const constants_1 = require("./constants"); -const net_1 = require("net"); -const http = require("http"); -const logging = require("./logging"); -const subchannel_address_1 = require("./subchannel-address"); -const uri_parser_1 = require("./uri-parser"); -const url_1 = require("url"); -const resolver_dns_1 = require("./resolver-dns"); -const TRACER_NAME = 'proxy'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -function getProxyInfo() { - let proxyEnv = ''; - let envVar = ''; - /* Prefer using 'grpc_proxy'. Fallback on 'http_proxy' if it is not set. - * Also prefer using 'https_proxy' with fallback on 'http_proxy'. The - * fallback behavior can be removed if there's a demand for it. - */ - if (process.env.grpc_proxy) { - envVar = 'grpc_proxy'; - proxyEnv = process.env.grpc_proxy; - } - else if (process.env.https_proxy) { - envVar = 'https_proxy'; - proxyEnv = process.env.https_proxy; - } - else if (process.env.http_proxy) { - envVar = 'http_proxy'; - proxyEnv = process.env.http_proxy; - } - else { - return {}; - } - let proxyUrl; - try { - proxyUrl = new url_1.URL(proxyEnv); - } - catch (e) { - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, `cannot parse value of "${envVar}" env var`); - return {}; - } - if (proxyUrl.protocol !== 'http:') { - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, `"${proxyUrl.protocol}" scheme not supported in proxy URI`); - return {}; - } - let userCred = null; - if (proxyUrl.username) { - if (proxyUrl.password) { - (0, logging_1.log)(constants_1.LogVerbosity.INFO, 'userinfo found in proxy URI'); - userCred = decodeURIComponent(`${proxyUrl.username}:${proxyUrl.password}`); - } - else { - userCred = proxyUrl.username; - } - } - const hostname = proxyUrl.hostname; - let port = proxyUrl.port; - /* The proxy URL uses the scheme "http:", which has a default port number of - * 80. We need to set that explicitly here if it is omitted because otherwise - * it will use gRPC's default port 443. */ - if (port === '') { - port = '80'; - } - const result = { - address: `${hostname}:${port}`, - }; - if (userCred) { - result.creds = userCred; - } - trace('Proxy server ' + result.address + ' set by environment variable ' + envVar); - return result; -} -function getNoProxyHostList() { - /* Prefer using 'no_grpc_proxy'. Fallback on 'no_proxy' if it is not set. */ - let noProxyStr = process.env.no_grpc_proxy; - let envVar = 'no_grpc_proxy'; - if (!noProxyStr) { - noProxyStr = process.env.no_proxy; - envVar = 'no_proxy'; - } - if (noProxyStr) { - trace('No proxy server list set by environment variable ' + envVar); - return noProxyStr.split(','); - } - else { - return []; - } -} -/* - * The groups correspond to CIDR parts as follows: - * 1. ip - * 2. prefixLength - */ -function parseCIDR(cidrString) { - const splitRange = cidrString.split('/'); - if (splitRange.length !== 2) { - return null; - } - const prefixLength = parseInt(splitRange[1], 10); - if (!(0, net_1.isIPv4)(splitRange[0]) || Number.isNaN(prefixLength) || prefixLength < 0 || prefixLength > 32) { - return null; - } - return { - ip: ipToInt(splitRange[0]), - prefixLength: prefixLength - }; -} -function ipToInt(ip) { - return ip.split(".").reduce((acc, octet) => (acc << 8) + parseInt(octet, 10), 0); -} -function isIpInCIDR(cidr, serverHost) { - const ip = cidr.ip; - const mask = -1 << (32 - cidr.prefixLength); - const hostIP = ipToInt(serverHost); - return (hostIP & mask) === (ip & mask); -} -function hostMatchesNoProxyList(serverHost) { - for (const host of getNoProxyHostList()) { - const parsedCIDR = parseCIDR(host); - // host is a CIDR and serverHost is an IP address - if ((0, net_1.isIPv4)(serverHost) && parsedCIDR && isIpInCIDR(parsedCIDR, serverHost)) { - return true; - } - else if (serverHost.endsWith(host)) { - // host is a single IP or a domain name suffix - return true; - } - } - return false; -} -function mapProxyName(target, options) { - var _a; - const noProxyResult = { - target: target, - extraOptions: {}, - }; - if (((_a = options['grpc.enable_http_proxy']) !== null && _a !== void 0 ? _a : 1) === 0) { - return noProxyResult; - } - if (target.scheme === 'unix') { - return noProxyResult; - } - const proxyInfo = getProxyInfo(); - if (!proxyInfo.address) { - return noProxyResult; - } - const hostPort = (0, uri_parser_1.splitHostPort)(target.path); - if (!hostPort) { - return noProxyResult; - } - const serverHost = hostPort.host; - if (hostMatchesNoProxyList(serverHost)) { - trace('Not using proxy for target in no_proxy list: ' + (0, uri_parser_1.uriToString)(target)); - return noProxyResult; - } - const extraOptions = { - 'grpc.http_connect_target': (0, uri_parser_1.uriToString)(target), - }; - if (proxyInfo.creds) { - extraOptions['grpc.http_connect_creds'] = proxyInfo.creds; - } - return { - target: { - scheme: 'dns', - path: proxyInfo.address, - }, - extraOptions: extraOptions, - }; -} -function getProxiedConnection(address, channelOptions) { - var _a; - if (!('grpc.http_connect_target' in channelOptions)) { - return Promise.resolve(null); - } - const realTarget = channelOptions['grpc.http_connect_target']; - const parsedTarget = (0, uri_parser_1.parseUri)(realTarget); - if (parsedTarget === null) { - return Promise.resolve(null); - } - const splitHostPost = (0, uri_parser_1.splitHostPort)(parsedTarget.path); - if (splitHostPost === null) { - return Promise.resolve(null); - } - const hostPort = `${splitHostPost.host}:${(_a = splitHostPost.port) !== null && _a !== void 0 ? _a : resolver_dns_1.DEFAULT_PORT}`; - const options = { - method: 'CONNECT', - path: hostPort, - }; - const headers = { - Host: hostPort, - }; - // Connect to the subchannel address as a proxy - if ((0, subchannel_address_1.isTcpSubchannelAddress)(address)) { - options.host = address.host; - options.port = address.port; - } - else { - options.socketPath = address.path; - } - if ('grpc.http_connect_creds' in channelOptions) { - headers['Proxy-Authorization'] = - 'Basic ' + - Buffer.from(channelOptions['grpc.http_connect_creds']).toString('base64'); - } - options.headers = headers; - const proxyAddressString = (0, subchannel_address_1.subchannelAddressToString)(address); - trace('Using proxy ' + proxyAddressString + ' to connect to ' + options.path); - return new Promise((resolve, reject) => { - const request = http.request(options); - request.once('connect', (res, socket, head) => { - request.removeAllListeners(); - socket.removeAllListeners(); - if (res.statusCode === 200) { - trace('Successfully connected to ' + - options.path + - ' through proxy ' + - proxyAddressString); - // The HTTP client may have already read a few bytes of the proxied - // connection. If that's the case, put them back into the socket. - // See https://github.com/grpc/grpc-node/issues/2744. - if (head.length > 0) { - socket.unshift(head); - } - trace('Successfully established a plaintext connection to ' + - options.path + - ' through proxy ' + - proxyAddressString); - resolve(socket); - } - else { - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, 'Failed to connect to ' + - options.path + - ' through proxy ' + - proxyAddressString + - ' with status ' + - res.statusCode); - reject(); - } - }); - request.once('error', err => { - request.removeAllListeners(); - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, 'Failed to connect to proxy ' + - proxyAddressString + - ' with error ' + - err.message); - reject(); - }); - request.end(); - }); -} -//# sourceMappingURL=http_proxy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/index.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/index.js deleted file mode 100644 index 0c5c58ab..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/index.js +++ /dev/null @@ -1,148 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.experimental = exports.ServerMetricRecorder = exports.ServerInterceptingCall = exports.ResponderBuilder = exports.ServerListenerBuilder = exports.addAdminServicesToServer = exports.getChannelzHandlers = exports.getChannelzServiceDefinition = exports.InterceptorConfigurationError = exports.InterceptingCall = exports.RequesterBuilder = exports.ListenerBuilder = exports.StatusBuilder = exports.getClientChannel = exports.ServerCredentials = exports.Server = exports.setLogVerbosity = exports.setLogger = exports.load = exports.loadObject = exports.CallCredentials = exports.ChannelCredentials = exports.waitForClientReady = exports.closeClient = exports.Channel = exports.makeGenericClientConstructor = exports.makeClientConstructor = exports.loadPackageDefinition = exports.Client = exports.compressionAlgorithms = exports.propagate = exports.connectivityState = exports.status = exports.logVerbosity = exports.Metadata = exports.credentials = void 0; -const call_credentials_1 = require("./call-credentials"); -Object.defineProperty(exports, "CallCredentials", { enumerable: true, get: function () { return call_credentials_1.CallCredentials; } }); -const channel_1 = require("./channel"); -Object.defineProperty(exports, "Channel", { enumerable: true, get: function () { return channel_1.ChannelImplementation; } }); -const compression_algorithms_1 = require("./compression-algorithms"); -Object.defineProperty(exports, "compressionAlgorithms", { enumerable: true, get: function () { return compression_algorithms_1.CompressionAlgorithms; } }); -const connectivity_state_1 = require("./connectivity-state"); -Object.defineProperty(exports, "connectivityState", { enumerable: true, get: function () { return connectivity_state_1.ConnectivityState; } }); -const channel_credentials_1 = require("./channel-credentials"); -Object.defineProperty(exports, "ChannelCredentials", { enumerable: true, get: function () { return channel_credentials_1.ChannelCredentials; } }); -const client_1 = require("./client"); -Object.defineProperty(exports, "Client", { enumerable: true, get: function () { return client_1.Client; } }); -const constants_1 = require("./constants"); -Object.defineProperty(exports, "logVerbosity", { enumerable: true, get: function () { return constants_1.LogVerbosity; } }); -Object.defineProperty(exports, "status", { enumerable: true, get: function () { return constants_1.Status; } }); -Object.defineProperty(exports, "propagate", { enumerable: true, get: function () { return constants_1.Propagate; } }); -const logging = require("./logging"); -const make_client_1 = require("./make-client"); -Object.defineProperty(exports, "loadPackageDefinition", { enumerable: true, get: function () { return make_client_1.loadPackageDefinition; } }); -Object.defineProperty(exports, "makeClientConstructor", { enumerable: true, get: function () { return make_client_1.makeClientConstructor; } }); -Object.defineProperty(exports, "makeGenericClientConstructor", { enumerable: true, get: function () { return make_client_1.makeClientConstructor; } }); -const metadata_1 = require("./metadata"); -Object.defineProperty(exports, "Metadata", { enumerable: true, get: function () { return metadata_1.Metadata; } }); -const server_1 = require("./server"); -Object.defineProperty(exports, "Server", { enumerable: true, get: function () { return server_1.Server; } }); -const server_credentials_1 = require("./server-credentials"); -Object.defineProperty(exports, "ServerCredentials", { enumerable: true, get: function () { return server_credentials_1.ServerCredentials; } }); -const status_builder_1 = require("./status-builder"); -Object.defineProperty(exports, "StatusBuilder", { enumerable: true, get: function () { return status_builder_1.StatusBuilder; } }); -/**** Client Credentials ****/ -// Using assign only copies enumerable properties, which is what we want -exports.credentials = { - /** - * Combine a ChannelCredentials with any number of CallCredentials into a - * single ChannelCredentials object. - * @param channelCredentials The ChannelCredentials object. - * @param callCredentials Any number of CallCredentials objects. - * @return The resulting ChannelCredentials object. - */ - combineChannelCredentials: (channelCredentials, ...callCredentials) => { - return callCredentials.reduce((acc, other) => acc.compose(other), channelCredentials); - }, - /** - * Combine any number of CallCredentials into a single CallCredentials - * object. - * @param first The first CallCredentials object. - * @param additional Any number of additional CallCredentials objects. - * @return The resulting CallCredentials object. - */ - combineCallCredentials: (first, ...additional) => { - return additional.reduce((acc, other) => acc.compose(other), first); - }, - // from channel-credentials.ts - createInsecure: channel_credentials_1.ChannelCredentials.createInsecure, - createSsl: channel_credentials_1.ChannelCredentials.createSsl, - createFromSecureContext: channel_credentials_1.ChannelCredentials.createFromSecureContext, - // from call-credentials.ts - createFromMetadataGenerator: call_credentials_1.CallCredentials.createFromMetadataGenerator, - createFromGoogleCredential: call_credentials_1.CallCredentials.createFromGoogleCredential, - createEmpty: call_credentials_1.CallCredentials.createEmpty, -}; -/** - * Close a Client object. - * @param client The client to close. - */ -const closeClient = (client) => client.close(); -exports.closeClient = closeClient; -const waitForClientReady = (client, deadline, callback) => client.waitForReady(deadline, callback); -exports.waitForClientReady = waitForClientReady; -/* eslint-enable @typescript-eslint/no-explicit-any */ -/**** Unimplemented function stubs ****/ -/* eslint-disable @typescript-eslint/no-explicit-any */ -const loadObject = (value, options) => { - throw new Error('Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead'); -}; -exports.loadObject = loadObject; -const load = (filename, format, options) => { - throw new Error('Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead'); -}; -exports.load = load; -const setLogger = (logger) => { - logging.setLogger(logger); -}; -exports.setLogger = setLogger; -const setLogVerbosity = (verbosity) => { - logging.setLoggerVerbosity(verbosity); -}; -exports.setLogVerbosity = setLogVerbosity; -const getClientChannel = (client) => { - return client_1.Client.prototype.getChannel.call(client); -}; -exports.getClientChannel = getClientChannel; -var client_interceptors_1 = require("./client-interceptors"); -Object.defineProperty(exports, "ListenerBuilder", { enumerable: true, get: function () { return client_interceptors_1.ListenerBuilder; } }); -Object.defineProperty(exports, "RequesterBuilder", { enumerable: true, get: function () { return client_interceptors_1.RequesterBuilder; } }); -Object.defineProperty(exports, "InterceptingCall", { enumerable: true, get: function () { return client_interceptors_1.InterceptingCall; } }); -Object.defineProperty(exports, "InterceptorConfigurationError", { enumerable: true, get: function () { return client_interceptors_1.InterceptorConfigurationError; } }); -var channelz_1 = require("./channelz"); -Object.defineProperty(exports, "getChannelzServiceDefinition", { enumerable: true, get: function () { return channelz_1.getChannelzServiceDefinition; } }); -Object.defineProperty(exports, "getChannelzHandlers", { enumerable: true, get: function () { return channelz_1.getChannelzHandlers; } }); -var admin_1 = require("./admin"); -Object.defineProperty(exports, "addAdminServicesToServer", { enumerable: true, get: function () { return admin_1.addAdminServicesToServer; } }); -var server_interceptors_1 = require("./server-interceptors"); -Object.defineProperty(exports, "ServerListenerBuilder", { enumerable: true, get: function () { return server_interceptors_1.ServerListenerBuilder; } }); -Object.defineProperty(exports, "ResponderBuilder", { enumerable: true, get: function () { return server_interceptors_1.ResponderBuilder; } }); -Object.defineProperty(exports, "ServerInterceptingCall", { enumerable: true, get: function () { return server_interceptors_1.ServerInterceptingCall; } }); -var orca_1 = require("./orca"); -Object.defineProperty(exports, "ServerMetricRecorder", { enumerable: true, get: function () { return orca_1.ServerMetricRecorder; } }); -const experimental = require("./experimental"); -exports.experimental = experimental; -const resolver_dns = require("./resolver-dns"); -const resolver_uds = require("./resolver-uds"); -const resolver_ip = require("./resolver-ip"); -const load_balancer_pick_first = require("./load-balancer-pick-first"); -const load_balancer_round_robin = require("./load-balancer-round-robin"); -const load_balancer_outlier_detection = require("./load-balancer-outlier-detection"); -const load_balancer_weighted_round_robin = require("./load-balancer-weighted-round-robin"); -const channelz = require("./channelz"); -(() => { - resolver_dns.setup(); - resolver_uds.setup(); - resolver_ip.setup(); - load_balancer_pick_first.setup(); - load_balancer_round_robin.setup(); - load_balancer_outlier_detection.setup(); - load_balancer_weighted_round_robin.setup(); - channelz.setup(); -})(); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/internal-channel.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/internal-channel.js deleted file mode 100644 index e52f8817..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/internal-channel.js +++ /dev/null @@ -1,605 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.InternalChannel = exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = void 0; -const channel_credentials_1 = require("./channel-credentials"); -const resolving_load_balancer_1 = require("./resolving-load-balancer"); -const subchannel_pool_1 = require("./subchannel-pool"); -const picker_1 = require("./picker"); -const metadata_1 = require("./metadata"); -const constants_1 = require("./constants"); -const filter_stack_1 = require("./filter-stack"); -const compression_filter_1 = require("./compression-filter"); -const resolver_1 = require("./resolver"); -const logging_1 = require("./logging"); -const http_proxy_1 = require("./http_proxy"); -const uri_parser_1 = require("./uri-parser"); -const connectivity_state_1 = require("./connectivity-state"); -const channelz_1 = require("./channelz"); -const load_balancing_call_1 = require("./load-balancing-call"); -const deadline_1 = require("./deadline"); -const resolving_call_1 = require("./resolving-call"); -const call_number_1 = require("./call-number"); -const control_plane_status_1 = require("./control-plane-status"); -const retrying_call_1 = require("./retrying-call"); -const subchannel_interface_1 = require("./subchannel-interface"); -/** - * See https://nodejs.org/api/timers.html#timers_setinterval_callback_delay_args - */ -const MAX_TIMEOUT_TIME = 2147483647; -const MIN_IDLE_TIMEOUT_MS = 1000; -// 30 minutes -const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000; -const RETRY_THROTTLER_MAP = new Map(); -const DEFAULT_RETRY_BUFFER_SIZE_BYTES = 1 << 24; // 16 MB -const DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES = 1 << 20; // 1 MB -class ChannelSubchannelWrapper extends subchannel_interface_1.BaseSubchannelWrapper { - constructor(childSubchannel, channel) { - super(childSubchannel); - this.channel = channel; - this.refCount = 0; - this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime) => { - channel.throttleKeepalive(keepaliveTime); - }; - } - ref() { - if (this.refCount === 0) { - this.child.addConnectivityStateListener(this.subchannelStateListener); - this.channel.addWrappedSubchannel(this); - } - this.child.ref(); - this.refCount += 1; - } - unref() { - this.child.unref(); - this.refCount -= 1; - if (this.refCount <= 0) { - this.child.removeConnectivityStateListener(this.subchannelStateListener); - this.channel.removeWrappedSubchannel(this); - } - } -} -class ShutdownPicker { - pick(pickArgs) { - return { - pickResultType: picker_1.PickResultType.DROP, - status: { - code: constants_1.Status.UNAVAILABLE, - details: 'Channel closed before call started', - metadata: new metadata_1.Metadata() - }, - subchannel: null, - onCallStarted: null, - onCallEnded: null - }; - } -} -exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX = 'grpc.internal.no_subchannel'; -class ChannelzInfoTracker { - constructor(target) { - this.target = target; - this.trace = new channelz_1.ChannelzTrace(); - this.callTracker = new channelz_1.ChannelzCallTracker(); - this.childrenTracker = new channelz_1.ChannelzChildrenTracker(); - this.state = connectivity_state_1.ConnectivityState.IDLE; - } - getChannelzInfoCallback() { - return () => { - return { - target: this.target, - state: this.state, - trace: this.trace, - callTracker: this.callTracker, - children: this.childrenTracker.getChildLists() - }; - }; - } -} -class InternalChannel { - constructor(target, credentials, options) { - var _a, _b, _c, _d, _e, _f; - this.credentials = credentials; - this.options = options; - this.connectivityState = connectivity_state_1.ConnectivityState.IDLE; - this.currentPicker = new picker_1.UnavailablePicker(); - /** - * Calls queued up to get a call config. Should only be populated before the - * first time the resolver returns a result, which includes the ConfigSelector. - */ - this.configSelectionQueue = []; - this.pickQueue = []; - this.connectivityStateWatchers = []; - /** - * This timer does not do anything on its own. Its purpose is to hold the - * event loop open while there are any pending calls for the channel that - * have not yet been assigned to specific subchannels. In other words, - * the invariant is that callRefTimer is reffed if and only if pickQueue - * is non-empty. In addition, the timer is null while the state is IDLE or - * SHUTDOWN and there are no pending calls. - */ - this.callRefTimer = null; - this.configSelector = null; - /** - * This is the error from the name resolver if it failed most recently. It - * is only used to end calls that start while there is no config selector - * and the name resolver is in backoff, so it should be nulled if - * configSelector becomes set or the channel state becomes anything other - * than TRANSIENT_FAILURE. - */ - this.currentResolutionError = null; - this.wrappedSubchannels = new Set(); - this.callCount = 0; - this.idleTimer = null; - // Channelz info - this.channelzEnabled = true; - /** - * Randomly generated ID to be passed to the config selector, for use by - * ring_hash in xDS. An integer distributed approximately uniformly between - * 0 and MAX_SAFE_INTEGER. - */ - this.randomChannelId = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER); - if (typeof target !== 'string') { - throw new TypeError('Channel target must be a string'); - } - if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) { - throw new TypeError('Channel credentials must be a ChannelCredentials object'); - } - if (options) { - if (typeof options !== 'object') { - throw new TypeError('Channel options must be an object'); - } - } - this.channelzInfoTracker = new ChannelzInfoTracker(target); - const originalTargetUri = (0, uri_parser_1.parseUri)(target); - if (originalTargetUri === null) { - throw new Error(`Could not parse target name "${target}"`); - } - /* This ensures that the target has a scheme that is registered with the - * resolver */ - const defaultSchemeMapResult = (0, resolver_1.mapUriDefaultScheme)(originalTargetUri); - if (defaultSchemeMapResult === null) { - throw new Error(`Could not find a default scheme for target name "${target}"`); - } - if (this.options['grpc.enable_channelz'] === 0) { - this.channelzEnabled = false; - } - this.channelzRef = (0, channelz_1.registerChannelzChannel)(target, this.channelzInfoTracker.getChannelzInfoCallback(), this.channelzEnabled); - if (this.channelzEnabled) { - this.channelzInfoTracker.trace.addTrace('CT_INFO', 'Channel created'); - } - if (this.options['grpc.default_authority']) { - this.defaultAuthority = this.options['grpc.default_authority']; - } - else { - this.defaultAuthority = (0, resolver_1.getDefaultAuthority)(defaultSchemeMapResult); - } - const proxyMapResult = (0, http_proxy_1.mapProxyName)(defaultSchemeMapResult, options); - this.target = proxyMapResult.target; - this.options = Object.assign({}, this.options, proxyMapResult.extraOptions); - /* The global boolean parameter to getSubchannelPool has the inverse meaning to what - * the grpc.use_local_subchannel_pool channel option means. */ - this.subchannelPool = (0, subchannel_pool_1.getSubchannelPool)(((_a = this.options['grpc.use_local_subchannel_pool']) !== null && _a !== void 0 ? _a : 0) === 0); - this.retryBufferTracker = new retrying_call_1.MessageBufferTracker((_b = this.options['grpc.retry_buffer_size']) !== null && _b !== void 0 ? _b : DEFAULT_RETRY_BUFFER_SIZE_BYTES, (_c = this.options['grpc.per_rpc_retry_buffer_size']) !== null && _c !== void 0 ? _c : DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES); - this.keepaliveTime = (_d = this.options['grpc.keepalive_time_ms']) !== null && _d !== void 0 ? _d : -1; - this.idleTimeoutMs = Math.max((_e = this.options['grpc.client_idle_timeout_ms']) !== null && _e !== void 0 ? _e : DEFAULT_IDLE_TIMEOUT_MS, MIN_IDLE_TIMEOUT_MS); - const channelControlHelper = { - createSubchannel: (subchannelAddress, subchannelArgs) => { - const finalSubchannelArgs = {}; - for (const [key, value] of Object.entries(subchannelArgs)) { - if (!key.startsWith(exports.SUBCHANNEL_ARGS_EXCLUDE_KEY_PREFIX)) { - finalSubchannelArgs[key] = value; - } - } - const subchannel = this.subchannelPool.getOrCreateSubchannel(this.target, subchannelAddress, finalSubchannelArgs, this.credentials); - subchannel.throttleKeepalive(this.keepaliveTime); - if (this.channelzEnabled) { - this.channelzInfoTracker.trace.addTrace('CT_INFO', 'Created subchannel or used existing subchannel', subchannel.getChannelzRef()); - } - const wrappedSubchannel = new ChannelSubchannelWrapper(subchannel, this); - return wrappedSubchannel; - }, - updateState: (connectivityState, picker) => { - this.currentPicker = picker; - const queueCopy = this.pickQueue.slice(); - this.pickQueue = []; - if (queueCopy.length > 0) { - this.callRefTimerUnref(); - } - for (const call of queueCopy) { - call.doPick(); - } - this.updateState(connectivityState); - }, - requestReresolution: () => { - // This should never be called. - throw new Error('Resolving load balancer should never call requestReresolution'); - }, - addChannelzChild: (child) => { - if (this.channelzEnabled) { - this.channelzInfoTracker.childrenTracker.refChild(child); - } - }, - removeChannelzChild: (child) => { - if (this.channelzEnabled) { - this.channelzInfoTracker.childrenTracker.unrefChild(child); - } - }, - }; - this.resolvingLoadBalancer = new resolving_load_balancer_1.ResolvingLoadBalancer(this.target, channelControlHelper, this.options, (serviceConfig, configSelector) => { - var _a; - if (serviceConfig.retryThrottling) { - RETRY_THROTTLER_MAP.set(this.getTarget(), new retrying_call_1.RetryThrottler(serviceConfig.retryThrottling.maxTokens, serviceConfig.retryThrottling.tokenRatio, RETRY_THROTTLER_MAP.get(this.getTarget()))); - } - else { - RETRY_THROTTLER_MAP.delete(this.getTarget()); - } - if (this.channelzEnabled) { - this.channelzInfoTracker.trace.addTrace('CT_INFO', 'Address resolution succeeded'); - } - (_a = this.configSelector) === null || _a === void 0 ? void 0 : _a.unref(); - this.configSelector = configSelector; - this.currentResolutionError = null; - /* We process the queue asynchronously to ensure that the corresponding - * load balancer update has completed. */ - process.nextTick(() => { - const localQueue = this.configSelectionQueue; - this.configSelectionQueue = []; - if (localQueue.length > 0) { - this.callRefTimerUnref(); - } - for (const call of localQueue) { - call.getConfig(); - } - }); - }, status => { - if (this.channelzEnabled) { - this.channelzInfoTracker.trace.addTrace('CT_WARNING', 'Address resolution failed with code ' + - status.code + - ' and details "' + - status.details + - '"'); - } - if (this.configSelectionQueue.length > 0) { - this.trace('Name resolution failed with calls queued for config selection'); - } - if (this.configSelector === null) { - this.currentResolutionError = Object.assign(Object.assign({}, (0, control_plane_status_1.restrictControlPlaneStatusCode)(status.code, status.details)), { metadata: status.metadata }); - } - const localQueue = this.configSelectionQueue; - this.configSelectionQueue = []; - if (localQueue.length > 0) { - this.callRefTimerUnref(); - } - for (const call of localQueue) { - call.reportResolverError(status); - } - }); - this.filterStackFactory = new filter_stack_1.FilterStackFactory([ - new compression_filter_1.CompressionFilterFactory(this, this.options), - ]); - this.trace('Channel constructed with options ' + - JSON.stringify(options, undefined, 2)); - const error = new Error(); - if ((0, logging_1.isTracerEnabled)('channel_stacktrace')) { - (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, 'channel_stacktrace', '(' + - this.channelzRef.id + - ') ' + - 'Channel constructed \n' + - ((_f = error.stack) === null || _f === void 0 ? void 0 : _f.substring(error.stack.indexOf('\n') + 1))); - } - this.lastActivityTimestamp = new Date(); - } - trace(text, verbosityOverride) { - (0, logging_1.trace)(verbosityOverride !== null && verbosityOverride !== void 0 ? verbosityOverride : constants_1.LogVerbosity.DEBUG, 'channel', '(' + this.channelzRef.id + ') ' + (0, uri_parser_1.uriToString)(this.target) + ' ' + text); - } - callRefTimerRef() { - var _a, _b, _c, _d; - if (!this.callRefTimer) { - this.callRefTimer = setInterval(() => { }, MAX_TIMEOUT_TIME); - } - // If the hasRef function does not exist, always run the code - if (!((_b = (_a = this.callRefTimer).hasRef) === null || _b === void 0 ? void 0 : _b.call(_a))) { - this.trace('callRefTimer.ref | configSelectionQueue.length=' + - this.configSelectionQueue.length + - ' pickQueue.length=' + - this.pickQueue.length); - (_d = (_c = this.callRefTimer).ref) === null || _d === void 0 ? void 0 : _d.call(_c); - } - } - callRefTimerUnref() { - var _a, _b, _c; - // If the timer or the hasRef function does not exist, always run the code - if (!((_a = this.callRefTimer) === null || _a === void 0 ? void 0 : _a.hasRef) || this.callRefTimer.hasRef()) { - this.trace('callRefTimer.unref | configSelectionQueue.length=' + - this.configSelectionQueue.length + - ' pickQueue.length=' + - this.pickQueue.length); - (_c = (_b = this.callRefTimer) === null || _b === void 0 ? void 0 : _b.unref) === null || _c === void 0 ? void 0 : _c.call(_b); - } - } - removeConnectivityStateWatcher(watcherObject) { - const watcherIndex = this.connectivityStateWatchers.findIndex(value => value === watcherObject); - if (watcherIndex >= 0) { - this.connectivityStateWatchers.splice(watcherIndex, 1); - } - } - updateState(newState) { - (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, 'connectivity_state', '(' + - this.channelzRef.id + - ') ' + - (0, uri_parser_1.uriToString)(this.target) + - ' ' + - connectivity_state_1.ConnectivityState[this.connectivityState] + - ' -> ' + - connectivity_state_1.ConnectivityState[newState]); - if (this.channelzEnabled) { - this.channelzInfoTracker.trace.addTrace('CT_INFO', 'Connectivity state change to ' + connectivity_state_1.ConnectivityState[newState]); - } - this.connectivityState = newState; - this.channelzInfoTracker.state = newState; - const watchersCopy = this.connectivityStateWatchers.slice(); - for (const watcherObject of watchersCopy) { - if (newState !== watcherObject.currentState) { - if (watcherObject.timer) { - clearTimeout(watcherObject.timer); - } - this.removeConnectivityStateWatcher(watcherObject); - watcherObject.callback(); - } - } - if (newState !== connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { - this.currentResolutionError = null; - } - } - throttleKeepalive(newKeepaliveTime) { - if (newKeepaliveTime > this.keepaliveTime) { - this.keepaliveTime = newKeepaliveTime; - for (const wrappedSubchannel of this.wrappedSubchannels) { - wrappedSubchannel.throttleKeepalive(newKeepaliveTime); - } - } - } - addWrappedSubchannel(wrappedSubchannel) { - this.wrappedSubchannels.add(wrappedSubchannel); - } - removeWrappedSubchannel(wrappedSubchannel) { - this.wrappedSubchannels.delete(wrappedSubchannel); - } - doPick(metadata, extraPickInfo) { - return this.currentPicker.pick({ - metadata: metadata, - extraPickInfo: extraPickInfo, - }); - } - queueCallForPick(call) { - this.pickQueue.push(call); - this.callRefTimerRef(); - } - getConfig(method, metadata) { - if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN) { - this.resolvingLoadBalancer.exitIdle(); - } - if (this.configSelector) { - return { - type: 'SUCCESS', - config: this.configSelector.invoke(method, metadata, this.randomChannelId), - }; - } - else { - if (this.currentResolutionError) { - return { - type: 'ERROR', - error: this.currentResolutionError, - }; - } - else { - return { - type: 'NONE', - }; - } - } - } - queueCallForConfig(call) { - this.configSelectionQueue.push(call); - this.callRefTimerRef(); - } - enterIdle() { - this.resolvingLoadBalancer.destroy(); - this.updateState(connectivity_state_1.ConnectivityState.IDLE); - this.currentPicker = new picker_1.QueuePicker(this.resolvingLoadBalancer); - if (this.idleTimer) { - clearTimeout(this.idleTimer); - this.idleTimer = null; - } - if (this.callRefTimer) { - clearInterval(this.callRefTimer); - this.callRefTimer = null; - } - } - startIdleTimeout(timeoutMs) { - var _a, _b; - this.idleTimer = setTimeout(() => { - if (this.callCount > 0) { - /* If there is currently a call, the channel will not go idle for a - * period of at least idleTimeoutMs, so check again after that time. - */ - this.startIdleTimeout(this.idleTimeoutMs); - return; - } - const now = new Date(); - const timeSinceLastActivity = now.valueOf() - this.lastActivityTimestamp.valueOf(); - if (timeSinceLastActivity >= this.idleTimeoutMs) { - this.trace('Idle timer triggered after ' + - this.idleTimeoutMs + - 'ms of inactivity'); - this.enterIdle(); - } - else { - /* Whenever the timer fires with the latest activity being too recent, - * set the timer again for the time when the time since the last - * activity is equal to the timeout. This should result in the timer - * firing no more than once every idleTimeoutMs/2 on average. */ - this.startIdleTimeout(this.idleTimeoutMs - timeSinceLastActivity); - } - }, timeoutMs); - (_b = (_a = this.idleTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - maybeStartIdleTimer() { - if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN && - !this.idleTimer) { - this.startIdleTimeout(this.idleTimeoutMs); - } - } - onCallStart() { - if (this.channelzEnabled) { - this.channelzInfoTracker.callTracker.addCallStarted(); - } - this.callCount += 1; - } - onCallEnd(status) { - if (this.channelzEnabled) { - if (status.code === constants_1.Status.OK) { - this.channelzInfoTracker.callTracker.addCallSucceeded(); - } - else { - this.channelzInfoTracker.callTracker.addCallFailed(); - } - } - this.callCount -= 1; - this.lastActivityTimestamp = new Date(); - this.maybeStartIdleTimer(); - } - createLoadBalancingCall(callConfig, method, host, credentials, deadline) { - const callNumber = (0, call_number_1.getNextCallNumber)(); - this.trace('createLoadBalancingCall [' + callNumber + '] method="' + method + '"'); - return new load_balancing_call_1.LoadBalancingCall(this, callConfig, method, host, credentials, deadline, callNumber); - } - createRetryingCall(callConfig, method, host, credentials, deadline) { - const callNumber = (0, call_number_1.getNextCallNumber)(); - this.trace('createRetryingCall [' + callNumber + '] method="' + method + '"'); - return new retrying_call_1.RetryingCall(this, callConfig, method, host, credentials, deadline, callNumber, this.retryBufferTracker, RETRY_THROTTLER_MAP.get(this.getTarget())); - } - createResolvingCall(method, deadline, host, parentCall, propagateFlags) { - const callNumber = (0, call_number_1.getNextCallNumber)(); - this.trace('createResolvingCall [' + - callNumber + - '] method="' + - method + - '", deadline=' + - (0, deadline_1.deadlineToString)(deadline)); - const finalOptions = { - deadline: deadline, - flags: propagateFlags !== null && propagateFlags !== void 0 ? propagateFlags : constants_1.Propagate.DEFAULTS, - host: host !== null && host !== void 0 ? host : this.defaultAuthority, - parentCall: parentCall, - }; - const call = new resolving_call_1.ResolvingCall(this, method, finalOptions, this.filterStackFactory.clone(), callNumber); - this.onCallStart(); - call.addStatusWatcher(status => { - this.onCallEnd(status); - }); - return call; - } - close() { - var _a; - this.resolvingLoadBalancer.destroy(); - this.updateState(connectivity_state_1.ConnectivityState.SHUTDOWN); - this.currentPicker = new ShutdownPicker(); - for (const call of this.configSelectionQueue) { - call.cancelWithStatus(constants_1.Status.UNAVAILABLE, 'Channel closed before call started'); - } - this.configSelectionQueue = []; - for (const call of this.pickQueue) { - call.cancelWithStatus(constants_1.Status.UNAVAILABLE, 'Channel closed before call started'); - } - this.pickQueue = []; - if (this.callRefTimer) { - clearInterval(this.callRefTimer); - } - if (this.idleTimer) { - clearTimeout(this.idleTimer); - } - if (this.channelzEnabled) { - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - } - this.subchannelPool.unrefUnusedSubchannels(); - (_a = this.configSelector) === null || _a === void 0 ? void 0 : _a.unref(); - this.configSelector = null; - } - getTarget() { - return (0, uri_parser_1.uriToString)(this.target); - } - getConnectivityState(tryToConnect) { - const connectivityState = this.connectivityState; - if (tryToConnect) { - this.resolvingLoadBalancer.exitIdle(); - this.lastActivityTimestamp = new Date(); - this.maybeStartIdleTimer(); - } - return connectivityState; - } - watchConnectivityState(currentState, deadline, callback) { - if (this.connectivityState === connectivity_state_1.ConnectivityState.SHUTDOWN) { - throw new Error('Channel has been shut down'); - } - let timer = null; - if (deadline !== Infinity) { - const deadlineDate = deadline instanceof Date ? deadline : new Date(deadline); - const now = new Date(); - if (deadline === -Infinity || deadlineDate <= now) { - process.nextTick(callback, new Error('Deadline passed without connectivity state change')); - return; - } - timer = setTimeout(() => { - this.removeConnectivityStateWatcher(watcherObject); - callback(new Error('Deadline passed without connectivity state change')); - }, deadlineDate.getTime() - now.getTime()); - } - const watcherObject = { - currentState, - callback, - timer, - }; - this.connectivityStateWatchers.push(watcherObject); - } - /** - * Get the channelz reference object for this channel. The returned value is - * garbage if channelz is disabled for this channel. - * @returns - */ - getChannelzRef() { - return this.channelzRef; - } - createCall(method, deadline, host, parentCall, propagateFlags) { - if (typeof method !== 'string') { - throw new TypeError('Channel#createCall: method must be a string'); - } - if (!(typeof deadline === 'number' || deadline instanceof Date)) { - throw new TypeError('Channel#createCall: deadline must be a number or Date'); - } - if (this.connectivityState === connectivity_state_1.ConnectivityState.SHUTDOWN) { - throw new Error('Channel has been shut down'); - } - return this.createResolvingCall(method, deadline, host, parentCall, propagateFlags); - } - getOptions() { - return this.options; - } -} -exports.InternalChannel = InternalChannel; -//# sourceMappingURL=internal-channel.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js deleted file mode 100644 index d8c37a94..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js +++ /dev/null @@ -1,151 +0,0 @@ -"use strict"; -/* - * Copyright 2020 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ChildLoadBalancerHandler = void 0; -const load_balancer_1 = require("./load-balancer"); -const connectivity_state_1 = require("./connectivity-state"); -const TYPE_NAME = 'child_load_balancer_helper'; -class ChildLoadBalancerHandler { - constructor(channelControlHelper) { - this.channelControlHelper = channelControlHelper; - this.currentChild = null; - this.pendingChild = null; - this.latestConfig = null; - this.ChildPolicyHelper = class { - constructor(parent) { - this.parent = parent; - this.child = null; - } - createSubchannel(subchannelAddress, subchannelArgs) { - return this.parent.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); - } - updateState(connectivityState, picker, errorMessage) { - var _a; - if (this.calledByPendingChild()) { - if (connectivityState === connectivity_state_1.ConnectivityState.CONNECTING) { - return; - } - (_a = this.parent.currentChild) === null || _a === void 0 ? void 0 : _a.destroy(); - this.parent.currentChild = this.parent.pendingChild; - this.parent.pendingChild = null; - } - else if (!this.calledByCurrentChild()) { - return; - } - this.parent.channelControlHelper.updateState(connectivityState, picker, errorMessage); - } - requestReresolution() { - var _a; - const latestChild = (_a = this.parent.pendingChild) !== null && _a !== void 0 ? _a : this.parent.currentChild; - if (this.child === latestChild) { - this.parent.channelControlHelper.requestReresolution(); - } - } - setChild(newChild) { - this.child = newChild; - } - addChannelzChild(child) { - this.parent.channelControlHelper.addChannelzChild(child); - } - removeChannelzChild(child) { - this.parent.channelControlHelper.removeChannelzChild(child); - } - calledByPendingChild() { - return this.child === this.parent.pendingChild; - } - calledByCurrentChild() { - return this.child === this.parent.currentChild; - } - }; - } - configUpdateRequiresNewPolicyInstance(oldConfig, newConfig) { - return oldConfig.getLoadBalancerName() !== newConfig.getLoadBalancerName(); - } - /** - * Prerequisites: lbConfig !== null and lbConfig.name is registered - * @param endpointList - * @param lbConfig - * @param attributes - */ - updateAddressList(endpointList, lbConfig, options, resolutionNote) { - let childToUpdate; - if (this.currentChild === null || - this.latestConfig === null || - this.configUpdateRequiresNewPolicyInstance(this.latestConfig, lbConfig)) { - const newHelper = new this.ChildPolicyHelper(this); - const newChild = (0, load_balancer_1.createLoadBalancer)(lbConfig, newHelper); - newHelper.setChild(newChild); - if (this.currentChild === null) { - this.currentChild = newChild; - childToUpdate = this.currentChild; - } - else { - if (this.pendingChild) { - this.pendingChild.destroy(); - } - this.pendingChild = newChild; - childToUpdate = this.pendingChild; - } - } - else { - if (this.pendingChild === null) { - childToUpdate = this.currentChild; - } - else { - childToUpdate = this.pendingChild; - } - } - this.latestConfig = lbConfig; - return childToUpdate.updateAddressList(endpointList, lbConfig, options, resolutionNote); - } - exitIdle() { - if (this.currentChild) { - this.currentChild.exitIdle(); - if (this.pendingChild) { - this.pendingChild.exitIdle(); - } - } - } - resetBackoff() { - if (this.currentChild) { - this.currentChild.resetBackoff(); - if (this.pendingChild) { - this.pendingChild.resetBackoff(); - } - } - } - destroy() { - /* Note: state updates are only propagated from the child balancer if that - * object is equal to this.currentChild or this.pendingChild. Since this - * function sets both of those to null, no further state updates will - * occur after this function returns. */ - if (this.currentChild) { - this.currentChild.destroy(); - this.currentChild = null; - } - if (this.pendingChild) { - this.pendingChild.destroy(); - this.pendingChild = null; - } - } - getTypeName() { - return TYPE_NAME; - } -} -exports.ChildLoadBalancerHandler = ChildLoadBalancerHandler; -//# sourceMappingURL=load-balancer-child-handler.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js deleted file mode 100644 index ee32bf3d..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js +++ /dev/null @@ -1,571 +0,0 @@ -"use strict"; -/* - * Copyright 2022 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -var _a; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OutlierDetectionLoadBalancer = exports.OutlierDetectionLoadBalancingConfig = void 0; -exports.setup = setup; -const connectivity_state_1 = require("./connectivity-state"); -const constants_1 = require("./constants"); -const duration_1 = require("./duration"); -const experimental_1 = require("./experimental"); -const load_balancer_1 = require("./load-balancer"); -const load_balancer_child_handler_1 = require("./load-balancer-child-handler"); -const picker_1 = require("./picker"); -const subchannel_address_1 = require("./subchannel-address"); -const subchannel_interface_1 = require("./subchannel-interface"); -const logging = require("./logging"); -const TRACER_NAME = 'outlier_detection'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -const TYPE_NAME = 'outlier_detection'; -const OUTLIER_DETECTION_ENABLED = ((_a = process.env.GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION) !== null && _a !== void 0 ? _a : 'true') === 'true'; -const defaultSuccessRateEjectionConfig = { - stdev_factor: 1900, - enforcement_percentage: 100, - minimum_hosts: 5, - request_volume: 100, -}; -const defaultFailurePercentageEjectionConfig = { - threshold: 85, - enforcement_percentage: 100, - minimum_hosts: 5, - request_volume: 50, -}; -function validateFieldType(obj, fieldName, expectedType, objectName) { - if (fieldName in obj && - obj[fieldName] !== undefined && - typeof obj[fieldName] !== expectedType) { - const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; - throw new Error(`outlier detection config ${fullFieldName} parse error: expected ${expectedType}, got ${typeof obj[fieldName]}`); - } -} -function validatePositiveDuration(obj, fieldName, objectName) { - const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; - if (fieldName in obj && obj[fieldName] !== undefined) { - if (!(0, duration_1.isDuration)(obj[fieldName])) { - throw new Error(`outlier detection config ${fullFieldName} parse error: expected Duration, got ${typeof obj[fieldName]}`); - } - if (!(obj[fieldName].seconds >= 0 && - obj[fieldName].seconds <= 315576000000 && - obj[fieldName].nanos >= 0 && - obj[fieldName].nanos <= 999999999)) { - throw new Error(`outlier detection config ${fullFieldName} parse error: values out of range for non-negative Duaration`); - } - } -} -function validatePercentage(obj, fieldName, objectName) { - const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; - validateFieldType(obj, fieldName, 'number', objectName); - if (fieldName in obj && - obj[fieldName] !== undefined && - !(obj[fieldName] >= 0 && obj[fieldName] <= 100)) { - throw new Error(`outlier detection config ${fullFieldName} parse error: value out of range for percentage (0-100)`); - } -} -class OutlierDetectionLoadBalancingConfig { - constructor(intervalMs, baseEjectionTimeMs, maxEjectionTimeMs, maxEjectionPercent, successRateEjection, failurePercentageEjection, childPolicy) { - this.childPolicy = childPolicy; - if (childPolicy.getLoadBalancerName() === 'pick_first') { - throw new Error('outlier_detection LB policy cannot have a pick_first child policy'); - } - this.intervalMs = intervalMs !== null && intervalMs !== void 0 ? intervalMs : 10000; - this.baseEjectionTimeMs = baseEjectionTimeMs !== null && baseEjectionTimeMs !== void 0 ? baseEjectionTimeMs : 30000; - this.maxEjectionTimeMs = maxEjectionTimeMs !== null && maxEjectionTimeMs !== void 0 ? maxEjectionTimeMs : 300000; - this.maxEjectionPercent = maxEjectionPercent !== null && maxEjectionPercent !== void 0 ? maxEjectionPercent : 10; - this.successRateEjection = successRateEjection - ? Object.assign(Object.assign({}, defaultSuccessRateEjectionConfig), successRateEjection) : null; - this.failurePercentageEjection = failurePercentageEjection - ? Object.assign(Object.assign({}, defaultFailurePercentageEjectionConfig), failurePercentageEjection) : null; - } - getLoadBalancerName() { - return TYPE_NAME; - } - toJsonObject() { - var _a, _b; - return { - outlier_detection: { - interval: (0, duration_1.msToDuration)(this.intervalMs), - base_ejection_time: (0, duration_1.msToDuration)(this.baseEjectionTimeMs), - max_ejection_time: (0, duration_1.msToDuration)(this.maxEjectionTimeMs), - max_ejection_percent: this.maxEjectionPercent, - success_rate_ejection: (_a = this.successRateEjection) !== null && _a !== void 0 ? _a : undefined, - failure_percentage_ejection: (_b = this.failurePercentageEjection) !== null && _b !== void 0 ? _b : undefined, - child_policy: [this.childPolicy.toJsonObject()], - }, - }; - } - getIntervalMs() { - return this.intervalMs; - } - getBaseEjectionTimeMs() { - return this.baseEjectionTimeMs; - } - getMaxEjectionTimeMs() { - return this.maxEjectionTimeMs; - } - getMaxEjectionPercent() { - return this.maxEjectionPercent; - } - getSuccessRateEjectionConfig() { - return this.successRateEjection; - } - getFailurePercentageEjectionConfig() { - return this.failurePercentageEjection; - } - getChildPolicy() { - return this.childPolicy; - } - static createFromJson(obj) { - var _a; - validatePositiveDuration(obj, 'interval'); - validatePositiveDuration(obj, 'base_ejection_time'); - validatePositiveDuration(obj, 'max_ejection_time'); - validatePercentage(obj, 'max_ejection_percent'); - if ('success_rate_ejection' in obj && - obj.success_rate_ejection !== undefined) { - if (typeof obj.success_rate_ejection !== 'object') { - throw new Error('outlier detection config success_rate_ejection must be an object'); - } - validateFieldType(obj.success_rate_ejection, 'stdev_factor', 'number', 'success_rate_ejection'); - validatePercentage(obj.success_rate_ejection, 'enforcement_percentage', 'success_rate_ejection'); - validateFieldType(obj.success_rate_ejection, 'minimum_hosts', 'number', 'success_rate_ejection'); - validateFieldType(obj.success_rate_ejection, 'request_volume', 'number', 'success_rate_ejection'); - } - if ('failure_percentage_ejection' in obj && - obj.failure_percentage_ejection !== undefined) { - if (typeof obj.failure_percentage_ejection !== 'object') { - throw new Error('outlier detection config failure_percentage_ejection must be an object'); - } - validatePercentage(obj.failure_percentage_ejection, 'threshold', 'failure_percentage_ejection'); - validatePercentage(obj.failure_percentage_ejection, 'enforcement_percentage', 'failure_percentage_ejection'); - validateFieldType(obj.failure_percentage_ejection, 'minimum_hosts', 'number', 'failure_percentage_ejection'); - validateFieldType(obj.failure_percentage_ejection, 'request_volume', 'number', 'failure_percentage_ejection'); - } - if (!('child_policy' in obj) || !Array.isArray(obj.child_policy)) { - throw new Error('outlier detection config child_policy must be an array'); - } - const childPolicy = (0, load_balancer_1.selectLbConfigFromList)(obj.child_policy); - if (!childPolicy) { - throw new Error('outlier detection config child_policy: no valid recognized policy found'); - } - return new OutlierDetectionLoadBalancingConfig(obj.interval ? (0, duration_1.durationToMs)(obj.interval) : null, obj.base_ejection_time ? (0, duration_1.durationToMs)(obj.base_ejection_time) : null, obj.max_ejection_time ? (0, duration_1.durationToMs)(obj.max_ejection_time) : null, (_a = obj.max_ejection_percent) !== null && _a !== void 0 ? _a : null, obj.success_rate_ejection, obj.failure_percentage_ejection, childPolicy); - } -} -exports.OutlierDetectionLoadBalancingConfig = OutlierDetectionLoadBalancingConfig; -class OutlierDetectionSubchannelWrapper extends subchannel_interface_1.BaseSubchannelWrapper { - constructor(childSubchannel, mapEntry) { - super(childSubchannel); - this.mapEntry = mapEntry; - this.refCount = 0; - } - ref() { - this.child.ref(); - this.refCount += 1; - } - unref() { - this.child.unref(); - this.refCount -= 1; - if (this.refCount <= 0) { - if (this.mapEntry) { - const index = this.mapEntry.subchannelWrappers.indexOf(this); - if (index >= 0) { - this.mapEntry.subchannelWrappers.splice(index, 1); - } - } - } - } - eject() { - this.setHealthy(false); - } - uneject() { - this.setHealthy(true); - } - getMapEntry() { - return this.mapEntry; - } - getWrappedSubchannel() { - return this.child; - } -} -function createEmptyBucket() { - return { - success: 0, - failure: 0, - }; -} -class CallCounter { - constructor() { - this.activeBucket = createEmptyBucket(); - this.inactiveBucket = createEmptyBucket(); - } - addSuccess() { - this.activeBucket.success += 1; - } - addFailure() { - this.activeBucket.failure += 1; - } - switchBuckets() { - this.inactiveBucket = this.activeBucket; - this.activeBucket = createEmptyBucket(); - } - getLastSuccesses() { - return this.inactiveBucket.success; - } - getLastFailures() { - return this.inactiveBucket.failure; - } -} -class OutlierDetectionPicker { - constructor(wrappedPicker, countCalls) { - this.wrappedPicker = wrappedPicker; - this.countCalls = countCalls; - } - pick(pickArgs) { - const wrappedPick = this.wrappedPicker.pick(pickArgs); - if (wrappedPick.pickResultType === picker_1.PickResultType.COMPLETE) { - const subchannelWrapper = wrappedPick.subchannel; - const mapEntry = subchannelWrapper.getMapEntry(); - if (mapEntry) { - let onCallEnded = wrappedPick.onCallEnded; - if (this.countCalls) { - onCallEnded = (statusCode, details, metadata) => { - var _a; - if (statusCode === constants_1.Status.OK) { - mapEntry.counter.addSuccess(); - } - else { - mapEntry.counter.addFailure(); - } - (_a = wrappedPick.onCallEnded) === null || _a === void 0 ? void 0 : _a.call(wrappedPick, statusCode, details, metadata); - }; - } - return Object.assign(Object.assign({}, wrappedPick), { subchannel: subchannelWrapper.getWrappedSubchannel(), onCallEnded: onCallEnded }); - } - else { - return Object.assign(Object.assign({}, wrappedPick), { subchannel: subchannelWrapper.getWrappedSubchannel() }); - } - } - else { - return wrappedPick; - } - } -} -class OutlierDetectionLoadBalancer { - constructor(channelControlHelper) { - this.entryMap = new subchannel_address_1.EndpointMap(); - this.latestConfig = null; - this.timerStartTime = null; - this.childBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler((0, experimental_1.createChildChannelControlHelper)(channelControlHelper, { - createSubchannel: (subchannelAddress, subchannelArgs) => { - const originalSubchannel = channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); - const mapEntry = this.entryMap.getForSubchannelAddress(subchannelAddress); - const subchannelWrapper = new OutlierDetectionSubchannelWrapper(originalSubchannel, mapEntry); - if ((mapEntry === null || mapEntry === void 0 ? void 0 : mapEntry.currentEjectionTimestamp) !== null) { - // If the address is ejected, propagate that to the new subchannel wrapper - subchannelWrapper.eject(); - } - mapEntry === null || mapEntry === void 0 ? void 0 : mapEntry.subchannelWrappers.push(subchannelWrapper); - return subchannelWrapper; - }, - updateState: (connectivityState, picker, errorMessage) => { - if (connectivityState === connectivity_state_1.ConnectivityState.READY) { - channelControlHelper.updateState(connectivityState, new OutlierDetectionPicker(picker, this.isCountingEnabled()), errorMessage); - } - else { - channelControlHelper.updateState(connectivityState, picker, errorMessage); - } - }, - })); - this.ejectionTimer = setInterval(() => { }, 0); - clearInterval(this.ejectionTimer); - } - isCountingEnabled() { - return (this.latestConfig !== null && - (this.latestConfig.getSuccessRateEjectionConfig() !== null || - this.latestConfig.getFailurePercentageEjectionConfig() !== null)); - } - getCurrentEjectionPercent() { - let ejectionCount = 0; - for (const mapEntry of this.entryMap.values()) { - if (mapEntry.currentEjectionTimestamp !== null) { - ejectionCount += 1; - } - } - return (ejectionCount * 100) / this.entryMap.size; - } - runSuccessRateCheck(ejectionTimestamp) { - if (!this.latestConfig) { - return; - } - const successRateConfig = this.latestConfig.getSuccessRateEjectionConfig(); - if (!successRateConfig) { - return; - } - trace('Running success rate check'); - // Step 1 - const targetRequestVolume = successRateConfig.request_volume; - let addresesWithTargetVolume = 0; - const successRates = []; - for (const [endpoint, mapEntry] of this.entryMap.entries()) { - const successes = mapEntry.counter.getLastSuccesses(); - const failures = mapEntry.counter.getLastFailures(); - trace('Stats for ' + - (0, subchannel_address_1.endpointToString)(endpoint) + - ': successes=' + - successes + - ' failures=' + - failures + - ' targetRequestVolume=' + - targetRequestVolume); - if (successes + failures >= targetRequestVolume) { - addresesWithTargetVolume += 1; - successRates.push(successes / (successes + failures)); - } - } - trace('Found ' + - addresesWithTargetVolume + - ' success rate candidates; currentEjectionPercent=' + - this.getCurrentEjectionPercent() + - ' successRates=[' + - successRates + - ']'); - if (addresesWithTargetVolume < successRateConfig.minimum_hosts) { - return; - } - // Step 2 - const successRateMean = successRates.reduce((a, b) => a + b) / successRates.length; - let successRateDeviationSum = 0; - for (const rate of successRates) { - const deviation = rate - successRateMean; - successRateDeviationSum += deviation * deviation; - } - const successRateVariance = successRateDeviationSum / successRates.length; - const successRateStdev = Math.sqrt(successRateVariance); - const ejectionThreshold = successRateMean - - successRateStdev * (successRateConfig.stdev_factor / 1000); - trace('stdev=' + successRateStdev + ' ejectionThreshold=' + ejectionThreshold); - // Step 3 - for (const [address, mapEntry] of this.entryMap.entries()) { - // Step 3.i - if (this.getCurrentEjectionPercent() >= - this.latestConfig.getMaxEjectionPercent()) { - break; - } - // Step 3.ii - const successes = mapEntry.counter.getLastSuccesses(); - const failures = mapEntry.counter.getLastFailures(); - if (successes + failures < targetRequestVolume) { - continue; - } - // Step 3.iii - const successRate = successes / (successes + failures); - trace('Checking candidate ' + address + ' successRate=' + successRate); - if (successRate < ejectionThreshold) { - const randomNumber = Math.random() * 100; - trace('Candidate ' + - address + - ' randomNumber=' + - randomNumber + - ' enforcement_percentage=' + - successRateConfig.enforcement_percentage); - if (randomNumber < successRateConfig.enforcement_percentage) { - trace('Ejecting candidate ' + address); - this.eject(mapEntry, ejectionTimestamp); - } - } - } - } - runFailurePercentageCheck(ejectionTimestamp) { - if (!this.latestConfig) { - return; - } - const failurePercentageConfig = this.latestConfig.getFailurePercentageEjectionConfig(); - if (!failurePercentageConfig) { - return; - } - trace('Running failure percentage check. threshold=' + - failurePercentageConfig.threshold + - ' request volume threshold=' + - failurePercentageConfig.request_volume); - // Step 1 - let addressesWithTargetVolume = 0; - for (const mapEntry of this.entryMap.values()) { - const successes = mapEntry.counter.getLastSuccesses(); - const failures = mapEntry.counter.getLastFailures(); - if (successes + failures >= failurePercentageConfig.request_volume) { - addressesWithTargetVolume += 1; - } - } - if (addressesWithTargetVolume < failurePercentageConfig.minimum_hosts) { - return; - } - // Step 2 - for (const [address, mapEntry] of this.entryMap.entries()) { - // Step 2.i - if (this.getCurrentEjectionPercent() >= - this.latestConfig.getMaxEjectionPercent()) { - break; - } - // Step 2.ii - const successes = mapEntry.counter.getLastSuccesses(); - const failures = mapEntry.counter.getLastFailures(); - trace('Candidate successes=' + successes + ' failures=' + failures); - if (successes + failures < failurePercentageConfig.request_volume) { - continue; - } - // Step 2.iii - const failurePercentage = (failures * 100) / (failures + successes); - if (failurePercentage > failurePercentageConfig.threshold) { - const randomNumber = Math.random() * 100; - trace('Candidate ' + - address + - ' randomNumber=' + - randomNumber + - ' enforcement_percentage=' + - failurePercentageConfig.enforcement_percentage); - if (randomNumber < failurePercentageConfig.enforcement_percentage) { - trace('Ejecting candidate ' + address); - this.eject(mapEntry, ejectionTimestamp); - } - } - } - } - eject(mapEntry, ejectionTimestamp) { - mapEntry.currentEjectionTimestamp = new Date(); - mapEntry.ejectionTimeMultiplier += 1; - for (const subchannelWrapper of mapEntry.subchannelWrappers) { - subchannelWrapper.eject(); - } - } - uneject(mapEntry) { - mapEntry.currentEjectionTimestamp = null; - for (const subchannelWrapper of mapEntry.subchannelWrappers) { - subchannelWrapper.uneject(); - } - } - switchAllBuckets() { - for (const mapEntry of this.entryMap.values()) { - mapEntry.counter.switchBuckets(); - } - } - startTimer(delayMs) { - var _a, _b; - this.ejectionTimer = setTimeout(() => this.runChecks(), delayMs); - (_b = (_a = this.ejectionTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - runChecks() { - const ejectionTimestamp = new Date(); - trace('Ejection timer running'); - this.switchAllBuckets(); - if (!this.latestConfig) { - return; - } - this.timerStartTime = ejectionTimestamp; - this.startTimer(this.latestConfig.getIntervalMs()); - this.runSuccessRateCheck(ejectionTimestamp); - this.runFailurePercentageCheck(ejectionTimestamp); - for (const [address, mapEntry] of this.entryMap.entries()) { - if (mapEntry.currentEjectionTimestamp === null) { - if (mapEntry.ejectionTimeMultiplier > 0) { - mapEntry.ejectionTimeMultiplier -= 1; - } - } - else { - const baseEjectionTimeMs = this.latestConfig.getBaseEjectionTimeMs(); - const maxEjectionTimeMs = this.latestConfig.getMaxEjectionTimeMs(); - const returnTime = new Date(mapEntry.currentEjectionTimestamp.getTime()); - returnTime.setMilliseconds(returnTime.getMilliseconds() + - Math.min(baseEjectionTimeMs * mapEntry.ejectionTimeMultiplier, Math.max(baseEjectionTimeMs, maxEjectionTimeMs))); - if (returnTime < new Date()) { - trace('Unejecting ' + address); - this.uneject(mapEntry); - } - } - } - } - updateAddressList(endpointList, lbConfig, options, resolutionNote) { - if (!(lbConfig instanceof OutlierDetectionLoadBalancingConfig)) { - return false; - } - trace('Received update with config: ' + JSON.stringify(lbConfig.toJsonObject(), undefined, 2)); - if (endpointList.ok) { - for (const endpoint of endpointList.value) { - if (!this.entryMap.has(endpoint)) { - trace('Adding map entry for ' + (0, subchannel_address_1.endpointToString)(endpoint)); - this.entryMap.set(endpoint, { - counter: new CallCounter(), - currentEjectionTimestamp: null, - ejectionTimeMultiplier: 0, - subchannelWrappers: [], - }); - } - } - this.entryMap.deleteMissing(endpointList.value); - } - const childPolicy = lbConfig.getChildPolicy(); - this.childBalancer.updateAddressList(endpointList, childPolicy, options, resolutionNote); - if (lbConfig.getSuccessRateEjectionConfig() || - lbConfig.getFailurePercentageEjectionConfig()) { - if (this.timerStartTime) { - trace('Previous timer existed. Replacing timer'); - clearTimeout(this.ejectionTimer); - const remainingDelay = lbConfig.getIntervalMs() - - (new Date().getTime() - this.timerStartTime.getTime()); - this.startTimer(remainingDelay); - } - else { - trace('Starting new timer'); - this.timerStartTime = new Date(); - this.startTimer(lbConfig.getIntervalMs()); - this.switchAllBuckets(); - } - } - else { - trace('Counting disabled. Cancelling timer.'); - this.timerStartTime = null; - clearTimeout(this.ejectionTimer); - for (const mapEntry of this.entryMap.values()) { - this.uneject(mapEntry); - mapEntry.ejectionTimeMultiplier = 0; - } - } - this.latestConfig = lbConfig; - return true; - } - exitIdle() { - this.childBalancer.exitIdle(); - } - resetBackoff() { - this.childBalancer.resetBackoff(); - } - destroy() { - clearTimeout(this.ejectionTimer); - this.childBalancer.destroy(); - } - getTypeName() { - return TYPE_NAME; - } -} -exports.OutlierDetectionLoadBalancer = OutlierDetectionLoadBalancer; -function setup() { - if (OUTLIER_DETECTION_ENABLED) { - (0, experimental_1.registerLoadBalancerType)(TYPE_NAME, OutlierDetectionLoadBalancer, OutlierDetectionLoadBalancingConfig); - } -} -//# sourceMappingURL=load-balancer-outlier-detection.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js deleted file mode 100644 index c68ef128..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js +++ /dev/null @@ -1,514 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.LeafLoadBalancer = exports.PickFirstLoadBalancer = exports.PickFirstLoadBalancingConfig = void 0; -exports.shuffled = shuffled; -exports.setup = setup; -const load_balancer_1 = require("./load-balancer"); -const connectivity_state_1 = require("./connectivity-state"); -const picker_1 = require("./picker"); -const subchannel_address_1 = require("./subchannel-address"); -const logging = require("./logging"); -const constants_1 = require("./constants"); -const subchannel_address_2 = require("./subchannel-address"); -const net_1 = require("net"); -const call_interface_1 = require("./call-interface"); -const TRACER_NAME = 'pick_first'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -const TYPE_NAME = 'pick_first'; -/** - * Delay after starting a connection on a subchannel before starting a - * connection on the next subchannel in the list, for Happy Eyeballs algorithm. - */ -const CONNECTION_DELAY_INTERVAL_MS = 250; -class PickFirstLoadBalancingConfig { - constructor(shuffleAddressList) { - this.shuffleAddressList = shuffleAddressList; - } - getLoadBalancerName() { - return TYPE_NAME; - } - toJsonObject() { - return { - [TYPE_NAME]: { - shuffleAddressList: this.shuffleAddressList, - }, - }; - } - getShuffleAddressList() { - return this.shuffleAddressList; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static createFromJson(obj) { - if ('shuffleAddressList' in obj && - !(typeof obj.shuffleAddressList === 'boolean')) { - throw new Error('pick_first config field shuffleAddressList must be a boolean if provided'); - } - return new PickFirstLoadBalancingConfig(obj.shuffleAddressList === true); - } -} -exports.PickFirstLoadBalancingConfig = PickFirstLoadBalancingConfig; -/** - * Picker for a `PickFirstLoadBalancer` in the READY state. Always returns the - * picked subchannel. - */ -class PickFirstPicker { - constructor(subchannel) { - this.subchannel = subchannel; - } - pick(pickArgs) { - return { - pickResultType: picker_1.PickResultType.COMPLETE, - subchannel: this.subchannel, - status: null, - onCallStarted: null, - onCallEnded: null, - }; - } -} -/** - * Return a new array with the elements of the input array in a random order - * @param list The input array - * @returns A shuffled array of the elements of list - */ -function shuffled(list) { - const result = list.slice(); - for (let i = result.length - 1; i > 1; i--) { - const j = Math.floor(Math.random() * (i + 1)); - const temp = result[i]; - result[i] = result[j]; - result[j] = temp; - } - return result; -} -/** - * Interleave addresses in addressList by family in accordance with RFC-8304 section 4 - * @param addressList - * @returns - */ -function interleaveAddressFamilies(addressList) { - if (addressList.length === 0) { - return []; - } - const result = []; - const ipv6Addresses = []; - const ipv4Addresses = []; - const ipv6First = (0, subchannel_address_2.isTcpSubchannelAddress)(addressList[0]) && (0, net_1.isIPv6)(addressList[0].host); - for (const address of addressList) { - if ((0, subchannel_address_2.isTcpSubchannelAddress)(address) && (0, net_1.isIPv6)(address.host)) { - ipv6Addresses.push(address); - } - else { - ipv4Addresses.push(address); - } - } - const firstList = ipv6First ? ipv6Addresses : ipv4Addresses; - const secondList = ipv6First ? ipv4Addresses : ipv6Addresses; - for (let i = 0; i < Math.max(firstList.length, secondList.length); i++) { - if (i < firstList.length) { - result.push(firstList[i]); - } - if (i < secondList.length) { - result.push(secondList[i]); - } - } - return result; -} -const REPORT_HEALTH_STATUS_OPTION_NAME = 'grpc-node.internal.pick-first.report_health_status'; -class PickFirstLoadBalancer { - /** - * Load balancer that attempts to connect to each backend in the address list - * in order, and picks the first one that connects, using it for every - * request. - * @param channelControlHelper `ChannelControlHelper` instance provided by - * this load balancer's owner. - */ - constructor(channelControlHelper) { - this.channelControlHelper = channelControlHelper; - /** - * The list of subchannels this load balancer is currently attempting to - * connect to. - */ - this.children = []; - /** - * The current connectivity state of the load balancer. - */ - this.currentState = connectivity_state_1.ConnectivityState.IDLE; - /** - * The index within the `subchannels` array of the subchannel with the most - * recently started connection attempt. - */ - this.currentSubchannelIndex = 0; - /** - * The currently picked subchannel used for making calls. Populated if - * and only if the load balancer's current state is READY. In that case, - * the subchannel's current state is also READY. - */ - this.currentPick = null; - /** - * Listener callback attached to each subchannel in the `subchannels` list - * while establishing a connection. - */ - this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime, errorMessage) => { - this.onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage); - }; - this.pickedSubchannelHealthListener = () => this.calculateAndReportNewState(); - /** - * The LB policy enters sticky TRANSIENT_FAILURE mode when all - * subchannels have failed to connect at least once, and it stays in that - * mode until a connection attempt is successful. While in sticky TF mode, - * the LB policy continuously attempts to connect to all of its subchannels. - */ - this.stickyTransientFailureMode = false; - this.reportHealthStatus = false; - /** - * The most recent error reported by any subchannel as it transitioned to - * TRANSIENT_FAILURE. - */ - this.lastError = null; - this.latestAddressList = null; - this.latestOptions = {}; - this.latestResolutionNote = ''; - this.connectionDelayTimeout = setTimeout(() => { }, 0); - clearTimeout(this.connectionDelayTimeout); - } - allChildrenHaveReportedTF() { - return this.children.every(child => child.hasReportedTransientFailure); - } - resetChildrenReportedTF() { - this.children.every(child => child.hasReportedTransientFailure = false); - } - calculateAndReportNewState() { - var _a; - if (this.currentPick) { - if (this.reportHealthStatus && !this.currentPick.isHealthy()) { - const errorMessage = `Picked subchannel ${this.currentPick.getAddress()} is unhealthy`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ - details: errorMessage, - }), errorMessage); - } - else { - this.updateState(connectivity_state_1.ConnectivityState.READY, new PickFirstPicker(this.currentPick), null); - } - } - else if (((_a = this.latestAddressList) === null || _a === void 0 ? void 0 : _a.length) === 0) { - const errorMessage = `No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ - details: errorMessage, - }), errorMessage); - } - else if (this.children.length === 0) { - this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); - } - else { - if (this.stickyTransientFailureMode) { - const errorMessage = `No connection established. Last error: ${this.lastError}. Resolution note: ${this.latestResolutionNote}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ - details: errorMessage, - }), errorMessage); - } - else { - this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); - } - } - } - requestReresolution() { - this.channelControlHelper.requestReresolution(); - } - maybeEnterStickyTransientFailureMode() { - if (!this.allChildrenHaveReportedTF()) { - return; - } - this.requestReresolution(); - this.resetChildrenReportedTF(); - if (this.stickyTransientFailureMode) { - this.calculateAndReportNewState(); - return; - } - this.stickyTransientFailureMode = true; - for (const { subchannel } of this.children) { - subchannel.startConnecting(); - } - this.calculateAndReportNewState(); - } - removeCurrentPick() { - if (this.currentPick !== null) { - this.currentPick.removeConnectivityStateListener(this.subchannelStateListener); - this.channelControlHelper.removeChannelzChild(this.currentPick.getChannelzRef()); - this.currentPick.removeHealthStateWatcher(this.pickedSubchannelHealthListener); - // Unref last, to avoid triggering listeners - this.currentPick.unref(); - this.currentPick = null; - } - } - onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage) { - var _a; - if ((_a = this.currentPick) === null || _a === void 0 ? void 0 : _a.realSubchannelEquals(subchannel)) { - if (newState !== connectivity_state_1.ConnectivityState.READY) { - this.removeCurrentPick(); - this.calculateAndReportNewState(); - } - return; - } - for (const [index, child] of this.children.entries()) { - if (subchannel.realSubchannelEquals(child.subchannel)) { - if (newState === connectivity_state_1.ConnectivityState.READY) { - this.pickSubchannel(child.subchannel); - } - if (newState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { - child.hasReportedTransientFailure = true; - if (errorMessage) { - this.lastError = errorMessage; - } - this.maybeEnterStickyTransientFailureMode(); - if (index === this.currentSubchannelIndex) { - this.startNextSubchannelConnecting(index + 1); - } - } - child.subchannel.startConnecting(); - return; - } - } - } - startNextSubchannelConnecting(startIndex) { - clearTimeout(this.connectionDelayTimeout); - for (const [index, child] of this.children.entries()) { - if (index >= startIndex) { - const subchannelState = child.subchannel.getConnectivityState(); - if (subchannelState === connectivity_state_1.ConnectivityState.IDLE || - subchannelState === connectivity_state_1.ConnectivityState.CONNECTING) { - this.startConnecting(index); - return; - } - } - } - this.maybeEnterStickyTransientFailureMode(); - } - /** - * Have a single subchannel in the `subchannels` list start connecting. - * @param subchannelIndex The index into the `subchannels` list. - */ - startConnecting(subchannelIndex) { - var _a, _b; - clearTimeout(this.connectionDelayTimeout); - this.currentSubchannelIndex = subchannelIndex; - if (this.children[subchannelIndex].subchannel.getConnectivityState() === - connectivity_state_1.ConnectivityState.IDLE) { - trace('Start connecting to subchannel with address ' + - this.children[subchannelIndex].subchannel.getAddress()); - process.nextTick(() => { - var _a; - (_a = this.children[subchannelIndex]) === null || _a === void 0 ? void 0 : _a.subchannel.startConnecting(); - }); - } - this.connectionDelayTimeout = setTimeout(() => { - this.startNextSubchannelConnecting(subchannelIndex + 1); - }, CONNECTION_DELAY_INTERVAL_MS); - (_b = (_a = this.connectionDelayTimeout).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - /** - * Declare that the specified subchannel should be used to make requests. - * This functions the same independent of whether subchannel is a member of - * this.children and whether it is equal to this.currentPick. - * Prerequisite: subchannel.getConnectivityState() === READY. - * @param subchannel - */ - pickSubchannel(subchannel) { - trace('Pick subchannel with address ' + subchannel.getAddress()); - this.stickyTransientFailureMode = false; - /* Ref before removeCurrentPick and resetSubchannelList to avoid the - * refcount dropping to 0 during this process. */ - subchannel.ref(); - this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef()); - this.removeCurrentPick(); - this.resetSubchannelList(); - subchannel.addConnectivityStateListener(this.subchannelStateListener); - subchannel.addHealthStateWatcher(this.pickedSubchannelHealthListener); - this.currentPick = subchannel; - clearTimeout(this.connectionDelayTimeout); - this.calculateAndReportNewState(); - } - updateState(newState, picker, errorMessage) { - trace(connectivity_state_1.ConnectivityState[this.currentState] + - ' -> ' + - connectivity_state_1.ConnectivityState[newState]); - this.currentState = newState; - this.channelControlHelper.updateState(newState, picker, errorMessage); - } - resetSubchannelList() { - for (const child of this.children) { - /* Always remoev the connectivity state listener. If the subchannel is - getting picked, it will be re-added then. */ - child.subchannel.removeConnectivityStateListener(this.subchannelStateListener); - /* Refs are counted independently for the children list and the - * currentPick, so we call unref whether or not the child is the - * currentPick. Channelz child references are also refcounted, so - * removeChannelzChild can be handled the same way. */ - child.subchannel.unref(); - this.channelControlHelper.removeChannelzChild(child.subchannel.getChannelzRef()); - } - this.currentSubchannelIndex = 0; - this.children = []; - } - connectToAddressList(addressList, options) { - trace('connectToAddressList([' + addressList.map(address => (0, subchannel_address_1.subchannelAddressToString)(address)) + '])'); - const newChildrenList = addressList.map(address => ({ - subchannel: this.channelControlHelper.createSubchannel(address, options), - hasReportedTransientFailure: false, - })); - for (const { subchannel } of newChildrenList) { - if (subchannel.getConnectivityState() === connectivity_state_1.ConnectivityState.READY) { - this.pickSubchannel(subchannel); - return; - } - } - /* Ref each subchannel before resetting the list, to ensure that - * subchannels shared between the list don't drop to 0 refs during the - * transition. */ - for (const { subchannel } of newChildrenList) { - subchannel.ref(); - this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef()); - } - this.resetSubchannelList(); - this.children = newChildrenList; - for (const { subchannel } of this.children) { - subchannel.addConnectivityStateListener(this.subchannelStateListener); - } - for (const child of this.children) { - if (child.subchannel.getConnectivityState() === - connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { - child.hasReportedTransientFailure = true; - } - } - this.startNextSubchannelConnecting(0); - this.calculateAndReportNewState(); - } - updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { - if (!(lbConfig instanceof PickFirstLoadBalancingConfig)) { - return false; - } - if (!maybeEndpointList.ok) { - if (this.children.length === 0 && this.currentPick === null) { - this.channelControlHelper.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); - } - return true; - } - let endpointList = maybeEndpointList.value; - this.reportHealthStatus = options[REPORT_HEALTH_STATUS_OPTION_NAME]; - /* Previously, an update would be discarded if it was identical to the - * previous update, to minimize churn. Now the DNS resolver is - * rate-limited, so that is less of a concern. */ - if (lbConfig.getShuffleAddressList()) { - endpointList = shuffled(endpointList); - } - const rawAddressList = [].concat(...endpointList.map(endpoint => endpoint.addresses)); - trace('updateAddressList([' + rawAddressList.map(address => (0, subchannel_address_1.subchannelAddressToString)(address)) + '])'); - const addressList = interleaveAddressFamilies(rawAddressList); - this.latestAddressList = addressList; - this.latestOptions = options; - this.connectToAddressList(addressList, options); - this.latestResolutionNote = resolutionNote; - if (rawAddressList.length > 0) { - return true; - } - else { - this.lastError = 'No addresses resolved'; - return false; - } - } - exitIdle() { - if (this.currentState === connectivity_state_1.ConnectivityState.IDLE && - this.latestAddressList) { - this.connectToAddressList(this.latestAddressList, this.latestOptions); - } - } - resetBackoff() { - /* The pick first load balancer does not have a connection backoff, so this - * does nothing */ - } - destroy() { - this.resetSubchannelList(); - this.removeCurrentPick(); - } - getTypeName() { - return TYPE_NAME; - } -} -exports.PickFirstLoadBalancer = PickFirstLoadBalancer; -const LEAF_CONFIG = new PickFirstLoadBalancingConfig(false); -/** - * This class handles the leaf load balancing operations for a single endpoint. - * It is a thin wrapper around a PickFirstLoadBalancer with a different API - * that more closely reflects how it will be used as a leaf balancer. - */ -class LeafLoadBalancer { - constructor(endpoint, channelControlHelper, options, resolutionNote) { - this.endpoint = endpoint; - this.options = options; - this.resolutionNote = resolutionNote; - this.latestState = connectivity_state_1.ConnectivityState.IDLE; - const childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, { - updateState: (connectivityState, picker, errorMessage) => { - this.latestState = connectivityState; - this.latestPicker = picker; - channelControlHelper.updateState(connectivityState, picker, errorMessage); - }, - }); - this.pickFirstBalancer = new PickFirstLoadBalancer(childChannelControlHelper); - this.latestPicker = new picker_1.QueuePicker(this.pickFirstBalancer); - } - startConnecting() { - this.pickFirstBalancer.updateAddressList((0, call_interface_1.statusOrFromValue)([this.endpoint]), LEAF_CONFIG, Object.assign(Object.assign({}, this.options), { [REPORT_HEALTH_STATUS_OPTION_NAME]: true }), this.resolutionNote); - } - /** - * Update the endpoint associated with this LeafLoadBalancer to a new - * endpoint. Does not trigger connection establishment if a connection - * attempt is not already in progress. - * @param newEndpoint - */ - updateEndpoint(newEndpoint, newOptions) { - this.options = newOptions; - this.endpoint = newEndpoint; - if (this.latestState !== connectivity_state_1.ConnectivityState.IDLE) { - this.startConnecting(); - } - } - getConnectivityState() { - return this.latestState; - } - getPicker() { - return this.latestPicker; - } - getEndpoint() { - return this.endpoint; - } - exitIdle() { - this.pickFirstBalancer.exitIdle(); - } - destroy() { - this.pickFirstBalancer.destroy(); - } -} -exports.LeafLoadBalancer = LeafLoadBalancer; -function setup() { - (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, PickFirstLoadBalancer, PickFirstLoadBalancingConfig); - (0, load_balancer_1.registerDefaultLoadBalancerType)(TYPE_NAME); -} -//# sourceMappingURL=load-balancer-pick-first.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js deleted file mode 100644 index a49d0e0f..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js +++ /dev/null @@ -1,204 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RoundRobinLoadBalancer = void 0; -exports.setup = setup; -const load_balancer_1 = require("./load-balancer"); -const connectivity_state_1 = require("./connectivity-state"); -const picker_1 = require("./picker"); -const logging = require("./logging"); -const constants_1 = require("./constants"); -const subchannel_address_1 = require("./subchannel-address"); -const load_balancer_pick_first_1 = require("./load-balancer-pick-first"); -const TRACER_NAME = 'round_robin'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -const TYPE_NAME = 'round_robin'; -class RoundRobinLoadBalancingConfig { - getLoadBalancerName() { - return TYPE_NAME; - } - constructor() { } - toJsonObject() { - return { - [TYPE_NAME]: {}, - }; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - static createFromJson(obj) { - return new RoundRobinLoadBalancingConfig(); - } -} -class RoundRobinPicker { - constructor(children, nextIndex = 0) { - this.children = children; - this.nextIndex = nextIndex; - } - pick(pickArgs) { - const childPicker = this.children[this.nextIndex].picker; - this.nextIndex = (this.nextIndex + 1) % this.children.length; - return childPicker.pick(pickArgs); - } - /** - * Check what the next subchannel returned would be. Used by the load - * balancer implementation to preserve this part of the picker state if - * possible when a subchannel connects or disconnects. - */ - peekNextEndpoint() { - return this.children[this.nextIndex].endpoint; - } -} -function rotateArray(list, startIndex) { - return [...list.slice(startIndex), ...list.slice(0, startIndex)]; -} -class RoundRobinLoadBalancer { - constructor(channelControlHelper) { - this.channelControlHelper = channelControlHelper; - this.children = []; - this.currentState = connectivity_state_1.ConnectivityState.IDLE; - this.currentReadyPicker = null; - this.updatesPaused = false; - this.lastError = null; - this.childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, { - updateState: (connectivityState, picker, errorMessage) => { - /* Ensure that name resolution is requested again after active - * connections are dropped. This is more aggressive than necessary to - * accomplish that, so we are counting on resolvers to have - * reasonable rate limits. */ - if (this.currentState === connectivity_state_1.ConnectivityState.READY && connectivityState !== connectivity_state_1.ConnectivityState.READY) { - this.channelControlHelper.requestReresolution(); - } - if (errorMessage) { - this.lastError = errorMessage; - } - this.calculateAndUpdateState(); - }, - }); - } - countChildrenWithState(state) { - return this.children.filter(child => child.getConnectivityState() === state) - .length; - } - calculateAndUpdateState() { - if (this.updatesPaused) { - return; - } - if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.READY) > 0) { - const readyChildren = this.children.filter(child => child.getConnectivityState() === connectivity_state_1.ConnectivityState.READY); - let index = 0; - if (this.currentReadyPicker !== null) { - const nextPickedEndpoint = this.currentReadyPicker.peekNextEndpoint(); - index = readyChildren.findIndex(child => (0, subchannel_address_1.endpointEqual)(child.getEndpoint(), nextPickedEndpoint)); - if (index < 0) { - index = 0; - } - } - this.updateState(connectivity_state_1.ConnectivityState.READY, new RoundRobinPicker(readyChildren.map(child => ({ - endpoint: child.getEndpoint(), - picker: child.getPicker(), - })), index), null); - } - else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.CONNECTING) > 0) { - this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); - } - else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) > 0) { - const errorMessage = `round_robin: No connection established. Last error: ${this.lastError}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ - details: errorMessage, - }), errorMessage); - } - else { - this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); - } - /* round_robin should keep all children connected, this is how we do that. - * We can't do this more efficiently in the individual child's updateState - * callback because that doesn't have a reference to which child the state - * change is associated with. */ - for (const child of this.children) { - if (child.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) { - child.exitIdle(); - } - } - } - updateState(newState, picker, errorMessage) { - trace(connectivity_state_1.ConnectivityState[this.currentState] + - ' -> ' + - connectivity_state_1.ConnectivityState[newState]); - if (newState === connectivity_state_1.ConnectivityState.READY) { - this.currentReadyPicker = picker; - } - else { - this.currentReadyPicker = null; - } - this.currentState = newState; - this.channelControlHelper.updateState(newState, picker, errorMessage); - } - resetSubchannelList() { - for (const child of this.children) { - child.destroy(); - } - this.children = []; - } - updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { - if (!(lbConfig instanceof RoundRobinLoadBalancingConfig)) { - return false; - } - if (!maybeEndpointList.ok) { - if (this.children.length === 0) { - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); - } - return true; - } - const startIndex = (Math.random() * maybeEndpointList.value.length) | 0; - const endpointList = rotateArray(maybeEndpointList.value, startIndex); - this.resetSubchannelList(); - if (endpointList.length === 0) { - const errorMessage = `No addresses resolved. Resolution note: ${resolutionNote}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ details: errorMessage }), errorMessage); - } - trace('Connect to endpoint list ' + endpointList.map(subchannel_address_1.endpointToString)); - this.updatesPaused = true; - this.children = endpointList.map(endpoint => new load_balancer_pick_first_1.LeafLoadBalancer(endpoint, this.childChannelControlHelper, options, resolutionNote)); - for (const child of this.children) { - child.startConnecting(); - } - this.updatesPaused = false; - this.calculateAndUpdateState(); - return true; - } - exitIdle() { - /* The round_robin LB policy is only in the IDLE state if it has no - * addresses to try to connect to and it has no picked subchannel. - * In that case, there is no meaningful action that can be taken here. */ - } - resetBackoff() { - // This LB policy has no backoff to reset - } - destroy() { - this.resetSubchannelList(); - } - getTypeName() { - return TYPE_NAME; - } -} -exports.RoundRobinLoadBalancer = RoundRobinLoadBalancer; -function setup() { - (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, RoundRobinLoadBalancer, RoundRobinLoadBalancingConfig); -} -//# sourceMappingURL=load-balancer-round-robin.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.js deleted file mode 100644 index 919c36a3..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancer-weighted-round-robin.js +++ /dev/null @@ -1,392 +0,0 @@ -"use strict"; -/* - * Copyright 2025 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.WeightedRoundRobinLoadBalancingConfig = void 0; -exports.setup = setup; -const connectivity_state_1 = require("./connectivity-state"); -const constants_1 = require("./constants"); -const duration_1 = require("./duration"); -const load_balancer_1 = require("./load-balancer"); -const load_balancer_pick_first_1 = require("./load-balancer-pick-first"); -const logging = require("./logging"); -const orca_1 = require("./orca"); -const picker_1 = require("./picker"); -const priority_queue_1 = require("./priority-queue"); -const subchannel_address_1 = require("./subchannel-address"); -const TRACER_NAME = 'weighted_round_robin'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -const TYPE_NAME = 'weighted_round_robin'; -const DEFAULT_OOB_REPORTING_PERIOD_MS = 10000; -const DEFAULT_BLACKOUT_PERIOD_MS = 10000; -const DEFAULT_WEIGHT_EXPIRATION_PERIOD_MS = 3 * 60000; -const DEFAULT_WEIGHT_UPDATE_PERIOD_MS = 1000; -const DEFAULT_ERROR_UTILIZATION_PENALTY = 1; -function validateFieldType(obj, fieldName, expectedType) { - if (fieldName in obj && - obj[fieldName] !== undefined && - typeof obj[fieldName] !== expectedType) { - throw new Error(`weighted round robin config ${fieldName} parse error: expected ${expectedType}, got ${typeof obj[fieldName]}`); - } -} -function parseDurationField(obj, fieldName) { - if (fieldName in obj && obj[fieldName] !== undefined && obj[fieldName] !== null) { - let durationObject; - if ((0, duration_1.isDuration)(obj[fieldName])) { - durationObject = obj[fieldName]; - } - else if ((0, duration_1.isDurationMessage)(obj[fieldName])) { - durationObject = (0, duration_1.durationMessageToDuration)(obj[fieldName]); - } - else if (typeof obj[fieldName] === 'string') { - const parsedDuration = (0, duration_1.parseDuration)(obj[fieldName]); - if (!parsedDuration) { - throw new Error(`weighted round robin config ${fieldName}: failed to parse duration string ${obj[fieldName]}`); - } - durationObject = parsedDuration; - } - else { - throw new Error(`weighted round robin config ${fieldName}: expected duration, got ${typeof obj[fieldName]}`); - } - return (0, duration_1.durationToMs)(durationObject); - } - return null; -} -class WeightedRoundRobinLoadBalancingConfig { - constructor(enableOobLoadReport, oobLoadReportingPeriodMs, blackoutPeriodMs, weightExpirationPeriodMs, weightUpdatePeriodMs, errorUtilizationPenalty) { - this.enableOobLoadReport = enableOobLoadReport !== null && enableOobLoadReport !== void 0 ? enableOobLoadReport : false; - this.oobLoadReportingPeriodMs = oobLoadReportingPeriodMs !== null && oobLoadReportingPeriodMs !== void 0 ? oobLoadReportingPeriodMs : DEFAULT_OOB_REPORTING_PERIOD_MS; - this.blackoutPeriodMs = blackoutPeriodMs !== null && blackoutPeriodMs !== void 0 ? blackoutPeriodMs : DEFAULT_BLACKOUT_PERIOD_MS; - this.weightExpirationPeriodMs = weightExpirationPeriodMs !== null && weightExpirationPeriodMs !== void 0 ? weightExpirationPeriodMs : DEFAULT_WEIGHT_EXPIRATION_PERIOD_MS; - this.weightUpdatePeriodMs = Math.max(weightUpdatePeriodMs !== null && weightUpdatePeriodMs !== void 0 ? weightUpdatePeriodMs : DEFAULT_WEIGHT_UPDATE_PERIOD_MS, 100); - this.errorUtilizationPenalty = errorUtilizationPenalty !== null && errorUtilizationPenalty !== void 0 ? errorUtilizationPenalty : DEFAULT_ERROR_UTILIZATION_PENALTY; - } - getLoadBalancerName() { - return TYPE_NAME; - } - toJsonObject() { - return { - enable_oob_load_report: this.enableOobLoadReport, - oob_load_reporting_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.oobLoadReportingPeriodMs)), - blackout_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.blackoutPeriodMs)), - weight_expiration_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.weightExpirationPeriodMs)), - weight_update_period: (0, duration_1.durationToString)((0, duration_1.msToDuration)(this.weightUpdatePeriodMs)), - error_utilization_penalty: this.errorUtilizationPenalty - }; - } - static createFromJson(obj) { - validateFieldType(obj, 'enable_oob_load_report', 'boolean'); - validateFieldType(obj, 'error_utilization_penalty', 'number'); - if (obj.error_utilization_penalty < 0) { - throw new Error('weighted round robin config error_utilization_penalty < 0'); - } - return new WeightedRoundRobinLoadBalancingConfig(obj.enable_oob_load_report, parseDurationField(obj, 'oob_load_reporting_period'), parseDurationField(obj, 'blackout_period'), parseDurationField(obj, 'weight_expiration_period'), parseDurationField(obj, 'weight_update_period'), obj.error_utilization_penalty); - } - getEnableOobLoadReport() { - return this.enableOobLoadReport; - } - getOobLoadReportingPeriodMs() { - return this.oobLoadReportingPeriodMs; - } - getBlackoutPeriodMs() { - return this.blackoutPeriodMs; - } - getWeightExpirationPeriodMs() { - return this.weightExpirationPeriodMs; - } - getWeightUpdatePeriodMs() { - return this.weightUpdatePeriodMs; - } - getErrorUtilizationPenalty() { - return this.errorUtilizationPenalty; - } -} -exports.WeightedRoundRobinLoadBalancingConfig = WeightedRoundRobinLoadBalancingConfig; -class WeightedRoundRobinPicker { - constructor(children, metricsHandler) { - this.metricsHandler = metricsHandler; - this.queue = new priority_queue_1.PriorityQueue((a, b) => a.deadline < b.deadline); - const positiveWeight = children.filter(picker => picker.weight > 0); - let averageWeight; - if (positiveWeight.length < 2) { - averageWeight = 1; - } - else { - let weightSum = 0; - for (const { weight } of positiveWeight) { - weightSum += weight; - } - averageWeight = weightSum / positiveWeight.length; - } - for (const child of children) { - const period = child.weight > 0 ? 1 / child.weight : averageWeight; - this.queue.push({ - endpointName: child.endpointName, - picker: child.picker, - period: period, - deadline: Math.random() * period - }); - } - } - pick(pickArgs) { - const entry = this.queue.pop(); - this.queue.push(Object.assign(Object.assign({}, entry), { deadline: entry.deadline + entry.period })); - const childPick = entry.picker.pick(pickArgs); - if (childPick.pickResultType === picker_1.PickResultType.COMPLETE) { - if (this.metricsHandler) { - return Object.assign(Object.assign({}, childPick), { onCallEnded: (0, orca_1.createMetricsReader)(loadReport => this.metricsHandler(loadReport, entry.endpointName), childPick.onCallEnded) }); - } - else { - const subchannelWrapper = childPick.subchannel; - return Object.assign(Object.assign({}, childPick), { subchannel: subchannelWrapper.getWrappedSubchannel() }); - } - } - else { - return childPick; - } - } -} -class WeightedRoundRobinLoadBalancer { - constructor(channelControlHelper) { - this.channelControlHelper = channelControlHelper; - this.latestConfig = null; - this.children = new Map(); - this.currentState = connectivity_state_1.ConnectivityState.IDLE; - this.updatesPaused = false; - this.lastError = null; - this.weightUpdateTimer = null; - } - countChildrenWithState(state) { - let count = 0; - for (const entry of this.children.values()) { - if (entry.child.getConnectivityState() === state) { - count += 1; - } - } - return count; - } - updateWeight(entry, loadReport) { - var _a, _b; - const qps = loadReport.rps_fractional; - let utilization = loadReport.application_utilization; - if (utilization > 0 && qps > 0) { - utilization += (loadReport.eps / qps) * ((_b = (_a = this.latestConfig) === null || _a === void 0 ? void 0 : _a.getErrorUtilizationPenalty()) !== null && _b !== void 0 ? _b : 0); - } - const newWeight = utilization === 0 ? 0 : qps / utilization; - if (newWeight === 0) { - return; - } - const now = new Date(); - if (entry.nonEmptySince === null) { - entry.nonEmptySince = now; - } - entry.lastUpdated = now; - entry.weight = newWeight; - } - getWeight(entry) { - if (!this.latestConfig) { - return 0; - } - const now = new Date().getTime(); - if (now - entry.lastUpdated.getTime() >= this.latestConfig.getWeightExpirationPeriodMs()) { - entry.nonEmptySince = null; - return 0; - } - const blackoutPeriod = this.latestConfig.getBlackoutPeriodMs(); - if (blackoutPeriod > 0 && (entry.nonEmptySince === null || now - entry.nonEmptySince.getTime() < blackoutPeriod)) { - return 0; - } - return entry.weight; - } - calculateAndUpdateState() { - if (this.updatesPaused || !this.latestConfig) { - return; - } - if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.READY) > 0) { - const weightedPickers = []; - for (const [endpoint, entry] of this.children) { - if (entry.child.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { - continue; - } - weightedPickers.push({ - endpointName: endpoint, - picker: entry.child.getPicker(), - weight: this.getWeight(entry) - }); - } - trace('Created picker with weights: ' + weightedPickers.map(entry => entry.endpointName + ':' + entry.weight).join(',')); - let metricsHandler; - if (!this.latestConfig.getEnableOobLoadReport()) { - metricsHandler = (loadReport, endpointName) => { - const childEntry = this.children.get(endpointName); - if (childEntry) { - this.updateWeight(childEntry, loadReport); - } - }; - } - else { - metricsHandler = null; - } - this.updateState(connectivity_state_1.ConnectivityState.READY, new WeightedRoundRobinPicker(weightedPickers, metricsHandler), null); - } - else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.CONNECTING) > 0) { - this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this), null); - } - else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) > 0) { - const errorMessage = `weighted_round_robin: No connection established. Last error: ${this.lastError}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ - details: errorMessage, - }), errorMessage); - } - else { - this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); - } - /* round_robin should keep all children connected, this is how we do that. - * We can't do this more efficiently in the individual child's updateState - * callback because that doesn't have a reference to which child the state - * change is associated with. */ - for (const { child } of this.children.values()) { - if (child.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) { - child.exitIdle(); - } - } - } - updateState(newState, picker, errorMessage) { - trace(connectivity_state_1.ConnectivityState[this.currentState] + - ' -> ' + - connectivity_state_1.ConnectivityState[newState]); - this.currentState = newState; - this.channelControlHelper.updateState(newState, picker, errorMessage); - } - updateAddressList(maybeEndpointList, lbConfig, options, resolutionNote) { - var _a, _b; - if (!(lbConfig instanceof WeightedRoundRobinLoadBalancingConfig)) { - return false; - } - if (!maybeEndpointList.ok) { - if (this.children.size === 0) { - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(maybeEndpointList.error), maybeEndpointList.error.details); - } - return true; - } - if (maybeEndpointList.value.length === 0) { - const errorMessage = `No addresses resolved. Resolution note: ${resolutionNote}`; - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ details: errorMessage }), errorMessage); - return false; - } - trace('Connect to endpoint list ' + maybeEndpointList.value.map(subchannel_address_1.endpointToString)); - const now = new Date(); - const seenEndpointNames = new Set(); - this.updatesPaused = true; - this.latestConfig = lbConfig; - for (const endpoint of maybeEndpointList.value) { - const name = (0, subchannel_address_1.endpointToString)(endpoint); - seenEndpointNames.add(name); - let entry = this.children.get(name); - if (!entry) { - entry = { - child: new load_balancer_pick_first_1.LeafLoadBalancer(endpoint, (0, load_balancer_1.createChildChannelControlHelper)(this.channelControlHelper, { - updateState: (connectivityState, picker, errorMessage) => { - /* Ensure that name resolution is requested again after active - * connections are dropped. This is more aggressive than necessary to - * accomplish that, so we are counting on resolvers to have - * reasonable rate limits. */ - if (this.currentState === connectivity_state_1.ConnectivityState.READY && connectivityState !== connectivity_state_1.ConnectivityState.READY) { - this.channelControlHelper.requestReresolution(); - } - if (connectivityState === connectivity_state_1.ConnectivityState.READY) { - entry.nonEmptySince = null; - } - if (errorMessage) { - this.lastError = errorMessage; - } - this.calculateAndUpdateState(); - }, - createSubchannel: (subchannelAddress, subchannelArgs) => { - const subchannel = this.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); - if (entry === null || entry === void 0 ? void 0 : entry.oobMetricsListener) { - return new orca_1.OrcaOobMetricsSubchannelWrapper(subchannel, entry.oobMetricsListener, this.latestConfig.getOobLoadReportingPeriodMs()); - } - else { - return subchannel; - } - } - }), options, resolutionNote), - lastUpdated: now, - nonEmptySince: null, - weight: 0, - oobMetricsListener: null - }; - this.children.set(name, entry); - } - if (lbConfig.getEnableOobLoadReport()) { - entry.oobMetricsListener = loadReport => { - this.updateWeight(entry, loadReport); - }; - } - else { - entry.oobMetricsListener = null; - } - } - for (const [endpointName, entry] of this.children) { - if (seenEndpointNames.has(endpointName)) { - entry.child.startConnecting(); - } - else { - entry.child.destroy(); - this.children.delete(endpointName); - } - } - this.updatesPaused = false; - this.calculateAndUpdateState(); - if (this.weightUpdateTimer) { - clearInterval(this.weightUpdateTimer); - } - this.weightUpdateTimer = (_b = (_a = setInterval(() => { - if (this.currentState === connectivity_state_1.ConnectivityState.READY) { - this.calculateAndUpdateState(); - } - }, lbConfig.getWeightUpdatePeriodMs())).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - return true; - } - exitIdle() { - /* The weighted_round_robin LB policy is only in the IDLE state if it has - * no addresses to try to connect to and it has no picked subchannel. - * In that case, there is no meaningful action that can be taken here. */ - } - resetBackoff() { - // This LB policy has no backoff to reset - } - destroy() { - for (const entry of this.children.values()) { - entry.child.destroy(); - } - this.children.clear(); - if (this.weightUpdateTimer) { - clearInterval(this.weightUpdateTimer); - } - } - getTypeName() { - return TYPE_NAME; - } -} -function setup() { - (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, WeightedRoundRobinLoadBalancer, WeightedRoundRobinLoadBalancingConfig); -} -//# sourceMappingURL=load-balancer-weighted-round-robin.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancer.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancer.js deleted file mode 100644 index adda9c64..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancer.js +++ /dev/null @@ -1,116 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createChildChannelControlHelper = createChildChannelControlHelper; -exports.registerLoadBalancerType = registerLoadBalancerType; -exports.registerDefaultLoadBalancerType = registerDefaultLoadBalancerType; -exports.createLoadBalancer = createLoadBalancer; -exports.isLoadBalancerNameRegistered = isLoadBalancerNameRegistered; -exports.parseLoadBalancingConfig = parseLoadBalancingConfig; -exports.getDefaultConfig = getDefaultConfig; -exports.selectLbConfigFromList = selectLbConfigFromList; -const logging_1 = require("./logging"); -const constants_1 = require("./constants"); -/** - * Create a child ChannelControlHelper that overrides some methods of the - * parent while letting others pass through to the parent unmodified. This - * allows other code to create these children without needing to know about - * all of the methods to be passed through. - * @param parent - * @param overrides - */ -function createChildChannelControlHelper(parent, overrides) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; - return { - createSubchannel: (_b = (_a = overrides.createSubchannel) === null || _a === void 0 ? void 0 : _a.bind(overrides)) !== null && _b !== void 0 ? _b : parent.createSubchannel.bind(parent), - updateState: (_d = (_c = overrides.updateState) === null || _c === void 0 ? void 0 : _c.bind(overrides)) !== null && _d !== void 0 ? _d : parent.updateState.bind(parent), - requestReresolution: (_f = (_e = overrides.requestReresolution) === null || _e === void 0 ? void 0 : _e.bind(overrides)) !== null && _f !== void 0 ? _f : parent.requestReresolution.bind(parent), - addChannelzChild: (_h = (_g = overrides.addChannelzChild) === null || _g === void 0 ? void 0 : _g.bind(overrides)) !== null && _h !== void 0 ? _h : parent.addChannelzChild.bind(parent), - removeChannelzChild: (_k = (_j = overrides.removeChannelzChild) === null || _j === void 0 ? void 0 : _j.bind(overrides)) !== null && _k !== void 0 ? _k : parent.removeChannelzChild.bind(parent), - }; -} -const registeredLoadBalancerTypes = {}; -let defaultLoadBalancerType = null; -function registerLoadBalancerType(typeName, loadBalancerType, loadBalancingConfigType) { - registeredLoadBalancerTypes[typeName] = { - LoadBalancer: loadBalancerType, - LoadBalancingConfig: loadBalancingConfigType, - }; -} -function registerDefaultLoadBalancerType(typeName) { - defaultLoadBalancerType = typeName; -} -function createLoadBalancer(config, channelControlHelper) { - const typeName = config.getLoadBalancerName(); - if (typeName in registeredLoadBalancerTypes) { - return new registeredLoadBalancerTypes[typeName].LoadBalancer(channelControlHelper); - } - else { - return null; - } -} -function isLoadBalancerNameRegistered(typeName) { - return typeName in registeredLoadBalancerTypes; -} -function parseLoadBalancingConfig(rawConfig) { - const keys = Object.keys(rawConfig); - if (keys.length !== 1) { - throw new Error('Provided load balancing config has multiple conflicting entries'); - } - const typeName = keys[0]; - if (typeName in registeredLoadBalancerTypes) { - try { - return registeredLoadBalancerTypes[typeName].LoadBalancingConfig.createFromJson(rawConfig[typeName]); - } - catch (e) { - throw new Error(`${typeName}: ${e.message}`); - } - } - else { - throw new Error(`Unrecognized load balancing config name ${typeName}`); - } -} -function getDefaultConfig() { - if (!defaultLoadBalancerType) { - throw new Error('No default load balancer type registered'); - } - return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig(); -} -function selectLbConfigFromList(configs, fallbackTodefault = false) { - for (const config of configs) { - try { - return parseLoadBalancingConfig(config); - } - catch (e) { - (0, logging_1.log)(constants_1.LogVerbosity.DEBUG, 'Config parsing failed with error', e.message); - continue; - } - } - if (fallbackTodefault) { - if (defaultLoadBalancerType) { - return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig(); - } - else { - return null; - } - } - else { - return null; - } -} -//# sourceMappingURL=load-balancer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancing-call.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancing-call.js deleted file mode 100644 index 44edbd06..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/load-balancing-call.js +++ /dev/null @@ -1,302 +0,0 @@ -"use strict"; -/* - * Copyright 2022 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.LoadBalancingCall = void 0; -const connectivity_state_1 = require("./connectivity-state"); -const constants_1 = require("./constants"); -const deadline_1 = require("./deadline"); -const metadata_1 = require("./metadata"); -const picker_1 = require("./picker"); -const uri_parser_1 = require("./uri-parser"); -const logging = require("./logging"); -const control_plane_status_1 = require("./control-plane-status"); -const http2 = require("http2"); -const TRACER_NAME = 'load_balancing_call'; -class LoadBalancingCall { - constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber) { - var _a, _b; - this.channel = channel; - this.callConfig = callConfig; - this.methodName = methodName; - this.host = host; - this.credentials = credentials; - this.deadline = deadline; - this.callNumber = callNumber; - this.child = null; - this.readPending = false; - this.pendingMessage = null; - this.pendingHalfClose = false; - this.ended = false; - this.metadata = null; - this.listener = null; - this.onCallEnded = null; - this.childStartTime = null; - const splitPath = this.methodName.split('/'); - let serviceName = ''; - /* The standard path format is "/{serviceName}/{methodName}", so if we split - * by '/', the first item should be empty and the second should be the - * service name */ - if (splitPath.length >= 2) { - serviceName = splitPath[1]; - } - const hostname = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : 'localhost'; - /* Currently, call credentials are only allowed on HTTPS connections, so we - * can assume that the scheme is "https" */ - this.serviceUrl = `https://${hostname}/${serviceName}`; - this.startTime = new Date(); - } - getDeadlineInfo() { - var _a, _b; - const deadlineInfo = []; - if (this.childStartTime) { - if (this.childStartTime > this.startTime) { - if ((_a = this.metadata) === null || _a === void 0 ? void 0 : _a.getOptions().waitForReady) { - deadlineInfo.push('wait_for_ready'); - } - deadlineInfo.push(`LB pick: ${(0, deadline_1.formatDateDifference)(this.startTime, this.childStartTime)}`); - } - deadlineInfo.push(...this.child.getDeadlineInfo()); - return deadlineInfo; - } - else { - if ((_b = this.metadata) === null || _b === void 0 ? void 0 : _b.getOptions().waitForReady) { - deadlineInfo.push('wait_for_ready'); - } - deadlineInfo.push('Waiting for LB pick'); - } - return deadlineInfo; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callNumber + '] ' + text); - } - outputStatus(status, progress) { - var _a, _b; - if (!this.ended) { - this.ended = true; - this.trace('ended with status: code=' + - status.code + - ' details="' + - status.details + - '" start time=' + - this.startTime.toISOString()); - const finalStatus = Object.assign(Object.assign({}, status), { progress }); - (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus(finalStatus); - (_b = this.onCallEnded) === null || _b === void 0 ? void 0 : _b.call(this, finalStatus.code, finalStatus.details, finalStatus.metadata); - } - } - doPick() { - var _a, _b; - if (this.ended) { - return; - } - if (!this.metadata) { - throw new Error('doPick called before start'); - } - this.trace('Pick called'); - const finalMetadata = this.metadata.clone(); - const pickResult = this.channel.doPick(finalMetadata, this.callConfig.pickInformation); - const subchannelString = pickResult.subchannel - ? '(' + - pickResult.subchannel.getChannelzRef().id + - ') ' + - pickResult.subchannel.getAddress() - : '' + pickResult.subchannel; - this.trace('Pick result: ' + - picker_1.PickResultType[pickResult.pickResultType] + - ' subchannel: ' + - subchannelString + - ' status: ' + - ((_a = pickResult.status) === null || _a === void 0 ? void 0 : _a.code) + - ' ' + - ((_b = pickResult.status) === null || _b === void 0 ? void 0 : _b.details)); - switch (pickResult.pickResultType) { - case picker_1.PickResultType.COMPLETE: - const combinedCallCredentials = this.credentials.compose(pickResult.subchannel.getCallCredentials()); - combinedCallCredentials - .generateMetadata({ method_name: this.methodName, service_url: this.serviceUrl }) - .then(credsMetadata => { - var _a; - /* If this call was cancelled (e.g. by the deadline) before - * metadata generation finished, we shouldn't do anything with - * it. */ - if (this.ended) { - this.trace('Credentials metadata generation finished after call ended'); - return; - } - finalMetadata.merge(credsMetadata); - if (finalMetadata.get('authorization').length > 1) { - this.outputStatus({ - code: constants_1.Status.INTERNAL, - details: '"authorization" metadata cannot have multiple values', - metadata: new metadata_1.Metadata(), - }, 'PROCESSED'); - } - if (pickResult.subchannel.getConnectivityState() !== - connectivity_state_1.ConnectivityState.READY) { - this.trace('Picked subchannel ' + - subchannelString + - ' has state ' + - connectivity_state_1.ConnectivityState[pickResult.subchannel.getConnectivityState()] + - ' after getting credentials metadata. Retrying pick'); - this.doPick(); - return; - } - if (this.deadline !== Infinity) { - finalMetadata.set('grpc-timeout', (0, deadline_1.getDeadlineTimeoutString)(this.deadline)); - } - try { - this.child = pickResult - .subchannel.getRealSubchannel() - .createCall(finalMetadata, this.host, this.methodName, { - onReceiveMetadata: metadata => { - this.trace('Received metadata'); - this.listener.onReceiveMetadata(metadata); - }, - onReceiveMessage: message => { - this.trace('Received message'); - this.listener.onReceiveMessage(message); - }, - onReceiveStatus: status => { - this.trace('Received status'); - if (status.rstCode === - http2.constants.NGHTTP2_REFUSED_STREAM) { - this.outputStatus(status, 'REFUSED'); - } - else { - this.outputStatus(status, 'PROCESSED'); - } - }, - }); - this.childStartTime = new Date(); - } - catch (error) { - this.trace('Failed to start call on picked subchannel ' + - subchannelString + - ' with error ' + - error.message); - this.outputStatus({ - code: constants_1.Status.INTERNAL, - details: 'Failed to start HTTP/2 stream with error ' + - error.message, - metadata: new metadata_1.Metadata(), - }, 'NOT_STARTED'); - return; - } - (_a = pickResult.onCallStarted) === null || _a === void 0 ? void 0 : _a.call(pickResult); - this.onCallEnded = pickResult.onCallEnded; - this.trace('Created child call [' + this.child.getCallNumber() + ']'); - if (this.readPending) { - this.child.startRead(); - } - if (this.pendingMessage) { - this.child.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message); - } - if (this.pendingHalfClose) { - this.child.halfClose(); - } - }, (error) => { - // We assume the error code isn't 0 (Status.OK) - const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(typeof error.code === 'number' ? error.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error.message}`); - this.outputStatus({ - code: code, - details: details, - metadata: new metadata_1.Metadata(), - }, 'PROCESSED'); - }); - break; - case picker_1.PickResultType.DROP: - const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(pickResult.status.code, pickResult.status.details); - setImmediate(() => { - this.outputStatus({ code, details, metadata: pickResult.status.metadata }, 'DROP'); - }); - break; - case picker_1.PickResultType.TRANSIENT_FAILURE: - if (this.metadata.getOptions().waitForReady) { - this.channel.queueCallForPick(this); - } - else { - const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(pickResult.status.code, pickResult.status.details); - setImmediate(() => { - this.outputStatus({ code, details, metadata: pickResult.status.metadata }, 'PROCESSED'); - }); - } - break; - case picker_1.PickResultType.QUEUE: - this.channel.queueCallForPick(this); - } - } - cancelWithStatus(status, details) { - var _a; - this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"'); - (_a = this.child) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(status, details); - this.outputStatus({ code: status, details: details, metadata: new metadata_1.Metadata() }, 'PROCESSED'); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.child) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.channel.getTarget(); - } - start(metadata, listener) { - this.trace('start called'); - this.listener = listener; - this.metadata = metadata; - this.doPick(); - } - sendMessageWithContext(context, message) { - this.trace('write() called with message of length ' + message.length); - if (this.child) { - this.child.sendMessageWithContext(context, message); - } - else { - this.pendingMessage = { context, message }; - } - } - startRead() { - this.trace('startRead called'); - if (this.child) { - this.child.startRead(); - } - else { - this.readPending = true; - } - } - halfClose() { - this.trace('halfClose called'); - if (this.child) { - this.child.halfClose(); - } - else { - this.pendingHalfClose = true; - } - } - setCredentials(credentials) { - throw new Error('Method not implemented.'); - } - getCallNumber() { - return this.callNumber; - } - getAuthContext() { - if (this.child) { - return this.child.getAuthContext(); - } - else { - return null; - } - } -} -exports.LoadBalancingCall = LoadBalancingCall; -//# sourceMappingURL=load-balancing-call.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/logging.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/logging.js deleted file mode 100644 index af7a8c86..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/logging.js +++ /dev/null @@ -1,122 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -var _a, _b, _c, _d; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.log = exports.setLoggerVerbosity = exports.setLogger = exports.getLogger = void 0; -exports.trace = trace; -exports.isTracerEnabled = isTracerEnabled; -const constants_1 = require("./constants"); -const process_1 = require("process"); -const clientVersion = require('../../package.json').version; -const DEFAULT_LOGGER = { - error: (message, ...optionalParams) => { - console.error('E ' + message, ...optionalParams); - }, - info: (message, ...optionalParams) => { - console.error('I ' + message, ...optionalParams); - }, - debug: (message, ...optionalParams) => { - console.error('D ' + message, ...optionalParams); - }, -}; -let _logger = DEFAULT_LOGGER; -let _logVerbosity = constants_1.LogVerbosity.ERROR; -const verbosityString = (_b = (_a = process.env.GRPC_NODE_VERBOSITY) !== null && _a !== void 0 ? _a : process.env.GRPC_VERBOSITY) !== null && _b !== void 0 ? _b : ''; -switch (verbosityString.toUpperCase()) { - case 'DEBUG': - _logVerbosity = constants_1.LogVerbosity.DEBUG; - break; - case 'INFO': - _logVerbosity = constants_1.LogVerbosity.INFO; - break; - case 'ERROR': - _logVerbosity = constants_1.LogVerbosity.ERROR; - break; - case 'NONE': - _logVerbosity = constants_1.LogVerbosity.NONE; - break; - default: - // Ignore any other values -} -const getLogger = () => { - return _logger; -}; -exports.getLogger = getLogger; -const setLogger = (logger) => { - _logger = logger; -}; -exports.setLogger = setLogger; -const setLoggerVerbosity = (verbosity) => { - _logVerbosity = verbosity; -}; -exports.setLoggerVerbosity = setLoggerVerbosity; -// eslint-disable-next-line @typescript-eslint/no-explicit-any -const log = (severity, ...args) => { - let logFunction; - if (severity >= _logVerbosity) { - switch (severity) { - case constants_1.LogVerbosity.DEBUG: - logFunction = _logger.debug; - break; - case constants_1.LogVerbosity.INFO: - logFunction = _logger.info; - break; - case constants_1.LogVerbosity.ERROR: - logFunction = _logger.error; - break; - } - /* Fall back to _logger.error when other methods are not available for - * compatiblity with older behavior that always logged to _logger.error */ - if (!logFunction) { - logFunction = _logger.error; - } - if (logFunction) { - logFunction.bind(_logger)(...args); - } - } -}; -exports.log = log; -const tracersString = (_d = (_c = process.env.GRPC_NODE_TRACE) !== null && _c !== void 0 ? _c : process.env.GRPC_TRACE) !== null && _d !== void 0 ? _d : ''; -const enabledTracers = new Set(); -const disabledTracers = new Set(); -for (const tracerName of tracersString.split(',')) { - if (tracerName.startsWith('-')) { - disabledTracers.add(tracerName.substring(1)); - } - else { - enabledTracers.add(tracerName); - } -} -const allEnabled = enabledTracers.has('all'); -function trace(severity, tracer, text) { - if (isTracerEnabled(tracer)) { - (0, exports.log)(severity, new Date().toISOString() + - ' | v' + - clientVersion + - ' ' + - process_1.pid + - ' | ' + - tracer + - ' | ' + - text); - } -} -function isTracerEnabled(tracer) { - return (!disabledTracers.has(tracer) && (allEnabled || enabledTracers.has(tracer))); -} -//# sourceMappingURL=logging.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/make-client.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/make-client.js deleted file mode 100644 index c7d9958a..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/make-client.js +++ /dev/null @@ -1,143 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.makeClientConstructor = makeClientConstructor; -exports.loadPackageDefinition = loadPackageDefinition; -const client_1 = require("./client"); -/** - * Map with short names for each of the requester maker functions. Used in - * makeClientConstructor - * @private - */ -const requesterFuncs = { - unary: client_1.Client.prototype.makeUnaryRequest, - server_stream: client_1.Client.prototype.makeServerStreamRequest, - client_stream: client_1.Client.prototype.makeClientStreamRequest, - bidi: client_1.Client.prototype.makeBidiStreamRequest, -}; -/** - * Returns true, if given key is included in the blacklisted - * keys. - * @param key key for check, string. - */ -function isPrototypePolluted(key) { - return ['__proto__', 'prototype', 'constructor'].includes(key); -} -/** - * Creates a constructor for a client with the given methods, as specified in - * the methods argument. The resulting class will have an instance method for - * each method in the service, which is a partial application of one of the - * [Client]{@link grpc.Client} request methods, depending on `requestSerialize` - * and `responseSerialize`, with the `method`, `serialize`, and `deserialize` - * arguments predefined. - * @param methods An object mapping method names to - * method attributes - * @param serviceName The fully qualified name of the service - * @param classOptions An options object. - * @return New client constructor, which is a subclass of - * {@link grpc.Client}, and has the same arguments as that constructor. - */ -function makeClientConstructor(methods, serviceName, classOptions) { - if (!classOptions) { - classOptions = {}; - } - class ServiceClientImpl extends client_1.Client { - } - Object.keys(methods).forEach(name => { - if (isPrototypePolluted(name)) { - return; - } - const attrs = methods[name]; - let methodType; - // TODO(murgatroid99): Verify that we don't need this anymore - if (typeof name === 'string' && name.charAt(0) === '$') { - throw new Error('Method names cannot start with $'); - } - if (attrs.requestStream) { - if (attrs.responseStream) { - methodType = 'bidi'; - } - else { - methodType = 'client_stream'; - } - } - else { - if (attrs.responseStream) { - methodType = 'server_stream'; - } - else { - methodType = 'unary'; - } - } - const serialize = attrs.requestSerialize; - const deserialize = attrs.responseDeserialize; - const methodFunc = partial(requesterFuncs[methodType], attrs.path, serialize, deserialize); - ServiceClientImpl.prototype[name] = methodFunc; - // Associate all provided attributes with the method - Object.assign(ServiceClientImpl.prototype[name], attrs); - if (attrs.originalName && !isPrototypePolluted(attrs.originalName)) { - ServiceClientImpl.prototype[attrs.originalName] = - ServiceClientImpl.prototype[name]; - } - }); - ServiceClientImpl.service = methods; - ServiceClientImpl.serviceName = serviceName; - return ServiceClientImpl; -} -function partial(fn, path, serialize, deserialize) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return function (...args) { - return fn.call(this, path, serialize, deserialize, ...args); - }; -} -function isProtobufTypeDefinition(obj) { - return 'format' in obj; -} -/** - * Load a gRPC package definition as a gRPC object hierarchy. - * @param packageDef The package definition object. - * @return The resulting gRPC object. - */ -function loadPackageDefinition(packageDef) { - const result = {}; - for (const serviceFqn in packageDef) { - if (Object.prototype.hasOwnProperty.call(packageDef, serviceFqn)) { - const service = packageDef[serviceFqn]; - const nameComponents = serviceFqn.split('.'); - if (nameComponents.some((comp) => isPrototypePolluted(comp))) { - continue; - } - const serviceName = nameComponents[nameComponents.length - 1]; - let current = result; - for (const packageName of nameComponents.slice(0, -1)) { - if (!current[packageName]) { - current[packageName] = {}; - } - current = current[packageName]; - } - if (isProtobufTypeDefinition(service)) { - current[serviceName] = service; - } - else { - current[serviceName] = makeClientConstructor(service, serviceName, {}); - } - } - } - return result; -} -//# sourceMappingURL=make-client.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/metadata.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/metadata.js deleted file mode 100644 index d4773d41..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/metadata.js +++ /dev/null @@ -1,272 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Metadata = void 0; -const logging_1 = require("./logging"); -const constants_1 = require("./constants"); -const error_1 = require("./error"); -const LEGAL_KEY_REGEX = /^[:0-9a-z_.-]+$/; -const LEGAL_NON_BINARY_VALUE_REGEX = /^[ -~]*$/; -function isLegalKey(key) { - return LEGAL_KEY_REGEX.test(key); -} -function isLegalNonBinaryValue(value) { - return LEGAL_NON_BINARY_VALUE_REGEX.test(value); -} -function isBinaryKey(key) { - return key.endsWith('-bin'); -} -function isCustomMetadata(key) { - return !key.startsWith('grpc-'); -} -function normalizeKey(key) { - return key.toLowerCase(); -} -function validate(key, value) { - if (!isLegalKey(key)) { - throw new Error('Metadata key "' + key + '" contains illegal characters'); - } - if (value !== null && value !== undefined) { - if (isBinaryKey(key)) { - if (!Buffer.isBuffer(value)) { - throw new Error("keys that end with '-bin' must have Buffer values"); - } - } - else { - if (Buffer.isBuffer(value)) { - throw new Error("keys that don't end with '-bin' must have String values"); - } - if (!isLegalNonBinaryValue(value)) { - throw new Error('Metadata string value "' + value + '" contains illegal characters'); - } - } - } -} -/** - * A class for storing metadata. Keys are normalized to lowercase ASCII. - */ -class Metadata { - constructor(options = {}) { - this.internalRepr = new Map(); - this.opaqueData = new Map(); - this.options = options; - } - /** - * Sets the given value for the given key by replacing any other values - * associated with that key. Normalizes the key. - * @param key The key to whose value should be set. - * @param value The value to set. Must be a buffer if and only - * if the normalized key ends with '-bin'. - */ - set(key, value) { - key = normalizeKey(key); - validate(key, value); - this.internalRepr.set(key, [value]); - } - /** - * Adds the given value for the given key by appending to a list of previous - * values associated with that key. Normalizes the key. - * @param key The key for which a new value should be appended. - * @param value The value to add. Must be a buffer if and only - * if the normalized key ends with '-bin'. - */ - add(key, value) { - key = normalizeKey(key); - validate(key, value); - const existingValue = this.internalRepr.get(key); - if (existingValue === undefined) { - this.internalRepr.set(key, [value]); - } - else { - existingValue.push(value); - } - } - /** - * Removes the given key and any associated values. Normalizes the key. - * @param key The key whose values should be removed. - */ - remove(key) { - key = normalizeKey(key); - // validate(key); - this.internalRepr.delete(key); - } - /** - * Gets a list of all values associated with the key. Normalizes the key. - * @param key The key whose value should be retrieved. - * @return A list of values associated with the given key. - */ - get(key) { - key = normalizeKey(key); - // validate(key); - return this.internalRepr.get(key) || []; - } - /** - * Gets a plain object mapping each key to the first value associated with it. - * This reflects the most common way that people will want to see metadata. - * @return A key/value mapping of the metadata. - */ - getMap() { - const result = {}; - for (const [key, values] of this.internalRepr) { - if (values.length > 0) { - const v = values[0]; - result[key] = Buffer.isBuffer(v) ? Buffer.from(v) : v; - } - } - return result; - } - /** - * Clones the metadata object. - * @return The newly cloned object. - */ - clone() { - const newMetadata = new Metadata(this.options); - const newInternalRepr = newMetadata.internalRepr; - for (const [key, value] of this.internalRepr) { - const clonedValue = value.map(v => { - if (Buffer.isBuffer(v)) { - return Buffer.from(v); - } - else { - return v; - } - }); - newInternalRepr.set(key, clonedValue); - } - return newMetadata; - } - /** - * Merges all key-value pairs from a given Metadata object into this one. - * If both this object and the given object have values in the same key, - * values from the other Metadata object will be appended to this object's - * values. - * @param other A Metadata object. - */ - merge(other) { - for (const [key, values] of other.internalRepr) { - const mergedValue = (this.internalRepr.get(key) || []).concat(values); - this.internalRepr.set(key, mergedValue); - } - } - setOptions(options) { - this.options = options; - } - getOptions() { - return this.options; - } - /** - * Creates an OutgoingHttpHeaders object that can be used with the http2 API. - */ - toHttp2Headers() { - // NOTE: Node <8.9 formats http2 headers incorrectly. - const result = {}; - for (const [key, values] of this.internalRepr) { - if (key.startsWith(':')) { - continue; - } - // We assume that the user's interaction with this object is limited to - // through its public API (i.e. keys and values are already validated). - result[key] = values.map(bufToString); - } - return result; - } - /** - * This modifies the behavior of JSON.stringify to show an object - * representation of the metadata map. - */ - toJSON() { - const result = {}; - for (const [key, values] of this.internalRepr) { - result[key] = values; - } - return result; - } - /** - * Attach additional data of any type to the metadata object, which will not - * be included when sending headers. The data can later be retrieved with - * `getOpaque`. Keys with the prefix `grpc` are reserved for use by this - * library. - * @param key - * @param value - */ - setOpaque(key, value) { - this.opaqueData.set(key, value); - } - /** - * Retrieve data previously added with `setOpaque`. - * @param key - * @returns - */ - getOpaque(key) { - return this.opaqueData.get(key); - } - /** - * Returns a new Metadata object based fields in a given IncomingHttpHeaders - * object. - * @param headers An IncomingHttpHeaders object. - */ - static fromHttp2Headers(headers) { - const result = new Metadata(); - for (const key of Object.keys(headers)) { - // Reserved headers (beginning with `:`) are not valid keys. - if (key.charAt(0) === ':') { - continue; - } - const values = headers[key]; - try { - if (isBinaryKey(key)) { - if (Array.isArray(values)) { - values.forEach(value => { - result.add(key, Buffer.from(value, 'base64')); - }); - } - else if (values !== undefined) { - if (isCustomMetadata(key)) { - values.split(',').forEach(v => { - result.add(key, Buffer.from(v.trim(), 'base64')); - }); - } - else { - result.add(key, Buffer.from(values, 'base64')); - } - } - } - else { - if (Array.isArray(values)) { - values.forEach(value => { - result.add(key, value); - }); - } - else if (values !== undefined) { - result.add(key, values); - } - } - } - catch (error) { - const message = `Failed to add metadata entry ${key}: ${values}. ${(0, error_1.getErrorMessage)(error)}. For more information see https://github.com/grpc/grpc-node/issues/1173`; - (0, logging_1.log)(constants_1.LogVerbosity.ERROR, message); - } - } - return result; - } -} -exports.Metadata = Metadata; -const bufToString = (val) => { - return Buffer.isBuffer(val) ? val.toString('base64') : val; -}; -//# sourceMappingURL=metadata.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/orca.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/orca.js deleted file mode 100644 index 5bcd57ee..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/orca.js +++ /dev/null @@ -1,323 +0,0 @@ -"use strict"; -/* - * Copyright 2025 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OrcaOobMetricsSubchannelWrapper = exports.GRPC_METRICS_HEADER = exports.ServerMetricRecorder = exports.PerRequestMetricRecorder = void 0; -exports.createOrcaClient = createOrcaClient; -exports.createMetricsReader = createMetricsReader; -const make_client_1 = require("./make-client"); -const duration_1 = require("./duration"); -const channel_credentials_1 = require("./channel-credentials"); -const subchannel_interface_1 = require("./subchannel-interface"); -const constants_1 = require("./constants"); -const backoff_timeout_1 = require("./backoff-timeout"); -const connectivity_state_1 = require("./connectivity-state"); -const loadedOrcaProto = null; -function loadOrcaProto() { - if (loadedOrcaProto) { - return loadedOrcaProto; - } - /* The purpose of this complexity is to avoid loading @grpc/proto-loader at - * runtime for users who will not use/enable ORCA. */ - const loaderLoadSync = require('@grpc/proto-loader') - .loadSync; - const loadedProto = loaderLoadSync('xds/service/orca/v3/orca.proto', { - keepCase: true, - longs: String, - enums: String, - defaults: true, - oneofs: true, - includeDirs: [ - `${__dirname}/../../proto/xds`, - `${__dirname}/../../proto/protoc-gen-validate` - ], - }); - return (0, make_client_1.loadPackageDefinition)(loadedProto); -} -/** - * ORCA metrics recorder for a single request - */ -class PerRequestMetricRecorder { - constructor() { - this.message = {}; - } - /** - * Records a request cost metric measurement for the call. - * @param name - * @param value - */ - recordRequestCostMetric(name, value) { - if (!this.message.request_cost) { - this.message.request_cost = {}; - } - this.message.request_cost[name] = value; - } - /** - * Records a request cost metric measurement for the call. - * @param name - * @param value - */ - recordUtilizationMetric(name, value) { - if (!this.message.utilization) { - this.message.utilization = {}; - } - this.message.utilization[name] = value; - } - /** - * Records an opaque named metric measurement for the call. - * @param name - * @param value - */ - recordNamedMetric(name, value) { - if (!this.message.named_metrics) { - this.message.named_metrics = {}; - } - this.message.named_metrics[name] = value; - } - /** - * Records the CPU utilization metric measurement for the call. - * @param value - */ - recordCPUUtilizationMetric(value) { - this.message.cpu_utilization = value; - } - /** - * Records the memory utilization metric measurement for the call. - * @param value - */ - recordMemoryUtilizationMetric(value) { - this.message.mem_utilization = value; - } - /** - * Records the memory utilization metric measurement for the call. - * @param value - */ - recordApplicationUtilizationMetric(value) { - this.message.application_utilization = value; - } - /** - * Records the queries per second measurement. - * @param value - */ - recordQpsMetric(value) { - this.message.rps_fractional = value; - } - /** - * Records the errors per second measurement. - * @param value - */ - recordEpsMetric(value) { - this.message.eps = value; - } - serialize() { - const orcaProto = loadOrcaProto(); - return orcaProto.xds.data.orca.v3.OrcaLoadReport.serialize(this.message); - } -} -exports.PerRequestMetricRecorder = PerRequestMetricRecorder; -const DEFAULT_REPORT_INTERVAL_MS = 30000; -class ServerMetricRecorder { - constructor() { - this.message = {}; - this.serviceImplementation = { - StreamCoreMetrics: call => { - const reportInterval = call.request.report_interval ? - (0, duration_1.durationToMs)((0, duration_1.durationMessageToDuration)(call.request.report_interval)) : - DEFAULT_REPORT_INTERVAL_MS; - const reportTimer = setInterval(() => { - call.write(this.message); - }, reportInterval); - call.on('cancelled', () => { - clearInterval(reportTimer); - }); - } - }; - } - putUtilizationMetric(name, value) { - if (!this.message.utilization) { - this.message.utilization = {}; - } - this.message.utilization[name] = value; - } - setAllUtilizationMetrics(metrics) { - this.message.utilization = Object.assign({}, metrics); - } - deleteUtilizationMetric(name) { - var _a; - (_a = this.message.utilization) === null || _a === void 0 ? true : delete _a[name]; - } - setCpuUtilizationMetric(value) { - this.message.cpu_utilization = value; - } - deleteCpuUtilizationMetric() { - delete this.message.cpu_utilization; - } - setApplicationUtilizationMetric(value) { - this.message.application_utilization = value; - } - deleteApplicationUtilizationMetric() { - delete this.message.application_utilization; - } - setQpsMetric(value) { - this.message.rps_fractional = value; - } - deleteQpsMetric() { - delete this.message.rps_fractional; - } - setEpsMetric(value) { - this.message.eps = value; - } - deleteEpsMetric() { - delete this.message.eps; - } - addToServer(server) { - const serviceDefinition = loadOrcaProto().xds.service.orca.v3.OpenRcaService.service; - server.addService(serviceDefinition, this.serviceImplementation); - } -} -exports.ServerMetricRecorder = ServerMetricRecorder; -function createOrcaClient(channel) { - const ClientClass = loadOrcaProto().xds.service.orca.v3.OpenRcaService; - return new ClientClass('unused', channel_credentials_1.ChannelCredentials.createInsecure(), { channelOverride: channel }); -} -exports.GRPC_METRICS_HEADER = 'endpoint-load-metrics-bin'; -const PARSED_LOAD_REPORT_KEY = 'grpc_orca_load_report'; -/** - * Create an onCallEnded callback for use in a picker. - * @param listener The listener to handle metrics, whenever they are provided. - * @param previousOnCallEnded The previous onCallEnded callback to propagate - * to, if applicable. - * @returns - */ -function createMetricsReader(listener, previousOnCallEnded) { - return (code, details, metadata) => { - let parsedLoadReport = metadata.getOpaque(PARSED_LOAD_REPORT_KEY); - if (parsedLoadReport) { - listener(parsedLoadReport); - } - else { - const serializedLoadReport = metadata.get(exports.GRPC_METRICS_HEADER); - if (serializedLoadReport.length > 0) { - const orcaProto = loadOrcaProto(); - parsedLoadReport = orcaProto.xds.data.orca.v3.OrcaLoadReport.deserialize(serializedLoadReport[0]); - listener(parsedLoadReport); - metadata.setOpaque(PARSED_LOAD_REPORT_KEY, parsedLoadReport); - } - } - if (previousOnCallEnded) { - previousOnCallEnded(code, details, metadata); - } - }; -} -const DATA_PRODUCER_KEY = 'orca_oob_metrics'; -class OobMetricsDataWatcher { - constructor(metricsListener, intervalMs) { - this.metricsListener = metricsListener; - this.intervalMs = intervalMs; - this.dataProducer = null; - } - setSubchannel(subchannel) { - const producer = subchannel.getOrCreateDataProducer(DATA_PRODUCER_KEY, createOobMetricsDataProducer); - this.dataProducer = producer; - producer.addDataWatcher(this); - } - destroy() { - var _a; - (_a = this.dataProducer) === null || _a === void 0 ? void 0 : _a.removeDataWatcher(this); - } - getInterval() { - return this.intervalMs; - } - onMetricsUpdate(metrics) { - this.metricsListener(metrics); - } -} -class OobMetricsDataProducer { - constructor(subchannel) { - this.subchannel = subchannel; - this.dataWatchers = new Set(); - this.orcaSupported = true; - this.metricsCall = null; - this.currentInterval = Infinity; - this.backoffTimer = new backoff_timeout_1.BackoffTimeout(() => this.updateMetricsSubscription()); - this.subchannelStateListener = () => this.updateMetricsSubscription(); - const channel = subchannel.getChannel(); - this.client = createOrcaClient(channel); - subchannel.addConnectivityStateListener(this.subchannelStateListener); - } - addDataWatcher(dataWatcher) { - this.dataWatchers.add(dataWatcher); - this.updateMetricsSubscription(); - } - removeDataWatcher(dataWatcher) { - var _a; - this.dataWatchers.delete(dataWatcher); - if (this.dataWatchers.size === 0) { - this.subchannel.removeDataProducer(DATA_PRODUCER_KEY); - (_a = this.metricsCall) === null || _a === void 0 ? void 0 : _a.cancel(); - this.metricsCall = null; - this.client.close(); - this.subchannel.removeConnectivityStateListener(this.subchannelStateListener); - } - else { - this.updateMetricsSubscription(); - } - } - updateMetricsSubscription() { - var _a; - if (this.dataWatchers.size === 0 || !this.orcaSupported || this.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { - return; - } - const newInterval = Math.min(...Array.from(this.dataWatchers).map(watcher => watcher.getInterval())); - if (!this.metricsCall || newInterval !== this.currentInterval) { - (_a = this.metricsCall) === null || _a === void 0 ? void 0 : _a.cancel(); - this.currentInterval = newInterval; - const metricsCall = this.client.streamCoreMetrics({ report_interval: (0, duration_1.msToDuration)(newInterval) }); - this.metricsCall = metricsCall; - metricsCall.on('data', (report) => { - this.dataWatchers.forEach(watcher => { - watcher.onMetricsUpdate(report); - }); - }); - metricsCall.on('error', (error) => { - this.metricsCall = null; - if (error.code === constants_1.Status.UNIMPLEMENTED) { - this.orcaSupported = false; - return; - } - if (error.code === constants_1.Status.CANCELLED) { - return; - } - this.backoffTimer.runOnce(); - }); - } - } -} -class OrcaOobMetricsSubchannelWrapper extends subchannel_interface_1.BaseSubchannelWrapper { - constructor(child, metricsListener, intervalMs) { - super(child); - this.addDataWatcher(new OobMetricsDataWatcher(metricsListener, intervalMs)); - } - getWrappedSubchannel() { - return this.child; - } -} -exports.OrcaOobMetricsSubchannelWrapper = OrcaOobMetricsSubchannelWrapper; -function createOobMetricsDataProducer(subchannel) { - return new OobMetricsDataProducer(subchannel); -} -//# sourceMappingURL=orca.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/picker.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/picker.js deleted file mode 100644 index e796f096..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/picker.js +++ /dev/null @@ -1,86 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.QueuePicker = exports.UnavailablePicker = exports.PickResultType = void 0; -const metadata_1 = require("./metadata"); -const constants_1 = require("./constants"); -var PickResultType; -(function (PickResultType) { - PickResultType[PickResultType["COMPLETE"] = 0] = "COMPLETE"; - PickResultType[PickResultType["QUEUE"] = 1] = "QUEUE"; - PickResultType[PickResultType["TRANSIENT_FAILURE"] = 2] = "TRANSIENT_FAILURE"; - PickResultType[PickResultType["DROP"] = 3] = "DROP"; -})(PickResultType || (exports.PickResultType = PickResultType = {})); -/** - * A standard picker representing a load balancer in the TRANSIENT_FAILURE - * state. Always responds to every pick request with an UNAVAILABLE status. - */ -class UnavailablePicker { - constructor(status) { - this.status = Object.assign({ code: constants_1.Status.UNAVAILABLE, details: 'No connection established', metadata: new metadata_1.Metadata() }, status); - } - pick(pickArgs) { - return { - pickResultType: PickResultType.TRANSIENT_FAILURE, - subchannel: null, - status: this.status, - onCallStarted: null, - onCallEnded: null, - }; - } -} -exports.UnavailablePicker = UnavailablePicker; -/** - * A standard picker representing a load balancer in the IDLE or CONNECTING - * state. Always responds to every pick request with a QUEUE pick result - * indicating that the pick should be tried again with the next `Picker`. Also - * reports back to the load balancer that a connection should be established - * once any pick is attempted. - * If the childPicker is provided, delegate to it instead of returning the - * hardcoded QUEUE pick result, but still calls exitIdle. - */ -class QueuePicker { - // Constructed with a load balancer. Calls exitIdle on it the first time pick is called - constructor(loadBalancer, childPicker) { - this.loadBalancer = loadBalancer; - this.childPicker = childPicker; - this.calledExitIdle = false; - } - pick(pickArgs) { - if (!this.calledExitIdle) { - process.nextTick(() => { - this.loadBalancer.exitIdle(); - }); - this.calledExitIdle = true; - } - if (this.childPicker) { - return this.childPicker.pick(pickArgs); - } - else { - return { - pickResultType: PickResultType.QUEUE, - subchannel: null, - status: null, - onCallStarted: null, - onCallEnded: null, - }; - } - } -} -exports.QueuePicker = QueuePicker; -//# sourceMappingURL=picker.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/priority-queue.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/priority-queue.js deleted file mode 100644 index 8628b56b..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/priority-queue.js +++ /dev/null @@ -1,120 +0,0 @@ -"use strict"; -/* - * Copyright 2025 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PriorityQueue = void 0; -const top = 0; -const parent = (i) => Math.floor(i / 2); -const left = (i) => i * 2 + 1; -const right = (i) => i * 2 + 2; -/** - * A generic priority queue implemented as an array-based binary heap. - * Adapted from https://stackoverflow.com/a/42919752/159388 - */ -class PriorityQueue { - /** - * - * @param comparator Returns true if the first argument should precede the - * second in the queue. Defaults to `(a, b) => a > b` - */ - constructor(comparator = (a, b) => a > b) { - this.comparator = comparator; - this.heap = []; - } - /** - * @returns The number of items currently in the queue - */ - size() { - return this.heap.length; - } - /** - * @returns True if there are no items in the queue, false otherwise - */ - isEmpty() { - return this.size() == 0; - } - /** - * Look at the front item that would be popped, without modifying the contents - * of the queue - * @returns The front item in the queue, or undefined if the queue is empty - */ - peek() { - return this.heap[top]; - } - /** - * Add the items to the queue - * @param values The items to add - * @returns The new size of the queue after adding the items - */ - push(...values) { - values.forEach(value => { - this.heap.push(value); - this.siftUp(); - }); - return this.size(); - } - /** - * Remove the front item in the queue and return it - * @returns The front item in the queue, or undefined if the queue is empty - */ - pop() { - const poppedValue = this.peek(); - const bottom = this.size() - 1; - if (bottom > top) { - this.swap(top, bottom); - } - this.heap.pop(); - this.siftDown(); - return poppedValue; - } - /** - * Simultaneously remove the front item in the queue and add the provided - * item. - * @param value The item to add - * @returns The front item in the queue, or undefined if the queue is empty - */ - replace(value) { - const replacedValue = this.peek(); - this.heap[top] = value; - this.siftDown(); - return replacedValue; - } - greater(i, j) { - return this.comparator(this.heap[i], this.heap[j]); - } - swap(i, j) { - [this.heap[i], this.heap[j]] = [this.heap[j], this.heap[i]]; - } - siftUp() { - let node = this.size() - 1; - while (node > top && this.greater(node, parent(node))) { - this.swap(node, parent(node)); - node = parent(node); - } - } - siftDown() { - let node = top; - while ((left(node) < this.size() && this.greater(left(node), node)) || - (right(node) < this.size() && this.greater(right(node), node))) { - let maxChild = (right(node) < this.size() && this.greater(right(node), left(node))) ? right(node) : left(node); - this.swap(node, maxChild); - node = maxChild; - } - } -} -exports.PriorityQueue = PriorityQueue; -//# sourceMappingURL=priority-queue.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/resolver-dns.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/resolver-dns.js deleted file mode 100644 index 1221464b..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/resolver-dns.js +++ /dev/null @@ -1,363 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DEFAULT_PORT = void 0; -exports.setup = setup; -const resolver_1 = require("./resolver"); -const dns_1 = require("dns"); -const service_config_1 = require("./service-config"); -const constants_1 = require("./constants"); -const call_interface_1 = require("./call-interface"); -const metadata_1 = require("./metadata"); -const logging = require("./logging"); -const constants_2 = require("./constants"); -const uri_parser_1 = require("./uri-parser"); -const net_1 = require("net"); -const backoff_timeout_1 = require("./backoff-timeout"); -const environment_1 = require("./environment"); -const TRACER_NAME = 'dns_resolver'; -function trace(text) { - logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text); -} -/** - * The default TCP port to connect to if not explicitly specified in the target. - */ -exports.DEFAULT_PORT = 443; -const DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS = 30000; -/** - * Resolver implementation that handles DNS names and IP addresses. - */ -class DnsResolver { - constructor(target, listener, channelOptions) { - var _a, _b, _c; - this.target = target; - this.listener = listener; - this.pendingLookupPromise = null; - this.pendingTxtPromise = null; - this.latestLookupResult = null; - this.latestServiceConfigResult = null; - this.continueResolving = false; - this.isNextResolutionTimerRunning = false; - this.isServiceConfigEnabled = true; - this.returnedIpResult = false; - this.alternativeResolver = new dns_1.promises.Resolver(); - trace('Resolver constructed for target ' + (0, uri_parser_1.uriToString)(target)); - if (target.authority) { - this.alternativeResolver.setServers([target.authority]); - } - const hostPort = (0, uri_parser_1.splitHostPort)(target.path); - if (hostPort === null) { - this.ipResult = null; - this.dnsHostname = null; - this.port = null; - } - else { - if ((0, net_1.isIPv4)(hostPort.host) || (0, net_1.isIPv6)(hostPort.host)) { - this.ipResult = [ - { - addresses: [ - { - host: hostPort.host, - port: (_a = hostPort.port) !== null && _a !== void 0 ? _a : exports.DEFAULT_PORT, - }, - ], - }, - ]; - this.dnsHostname = null; - this.port = null; - } - else { - this.ipResult = null; - this.dnsHostname = hostPort.host; - this.port = (_b = hostPort.port) !== null && _b !== void 0 ? _b : exports.DEFAULT_PORT; - } - } - this.percentage = Math.random() * 100; - if (channelOptions['grpc.service_config_disable_resolution'] === 1) { - this.isServiceConfigEnabled = false; - } - this.defaultResolutionError = { - code: constants_1.Status.UNAVAILABLE, - details: `Name resolution failed for target ${(0, uri_parser_1.uriToString)(this.target)}`, - metadata: new metadata_1.Metadata(), - }; - const backoffOptions = { - initialDelay: channelOptions['grpc.initial_reconnect_backoff_ms'], - maxDelay: channelOptions['grpc.max_reconnect_backoff_ms'], - }; - this.backoff = new backoff_timeout_1.BackoffTimeout(() => { - if (this.continueResolving) { - this.startResolutionWithBackoff(); - } - }, backoffOptions); - this.backoff.unref(); - this.minTimeBetweenResolutionsMs = - (_c = channelOptions['grpc.dns_min_time_between_resolutions_ms']) !== null && _c !== void 0 ? _c : DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS; - this.nextResolutionTimer = setTimeout(() => { }, 0); - clearTimeout(this.nextResolutionTimer); - } - /** - * If the target is an IP address, just provide that address as a result. - * Otherwise, initiate A, AAAA, and TXT lookups - */ - startResolution() { - if (this.ipResult !== null) { - if (!this.returnedIpResult) { - trace('Returning IP address for target ' + (0, uri_parser_1.uriToString)(this.target)); - setImmediate(() => { - this.listener((0, call_interface_1.statusOrFromValue)(this.ipResult), {}, null, ''); - }); - this.returnedIpResult = true; - } - this.backoff.stop(); - this.backoff.reset(); - this.stopNextResolutionTimer(); - return; - } - if (this.dnsHostname === null) { - trace('Failed to parse DNS address ' + (0, uri_parser_1.uriToString)(this.target)); - setImmediate(() => { - this.listener((0, call_interface_1.statusOrFromError)({ - code: constants_1.Status.UNAVAILABLE, - details: `Failed to parse DNS address ${(0, uri_parser_1.uriToString)(this.target)}` - }), {}, null, ''); - }); - this.stopNextResolutionTimer(); - } - else { - if (this.pendingLookupPromise !== null) { - return; - } - trace('Looking up DNS hostname ' + this.dnsHostname); - /* We clear out latestLookupResult here to ensure that it contains the - * latest result since the last time we started resolving. That way, the - * TXT resolution handler can use it, but only if it finishes second. We - * don't clear out any previous service config results because it's - * better to use a service config that's slightly out of date than to - * revert to an effectively blank one. */ - this.latestLookupResult = null; - const hostname = this.dnsHostname; - this.pendingLookupPromise = this.lookup(hostname); - this.pendingLookupPromise.then(addressList => { - if (this.pendingLookupPromise === null) { - return; - } - this.pendingLookupPromise = null; - this.latestLookupResult = (0, call_interface_1.statusOrFromValue)(addressList.map(address => ({ - addresses: [address], - }))); - const allAddressesString = '[' + - addressList.map(addr => addr.host + ':' + addr.port).join(',') + - ']'; - trace('Resolved addresses for target ' + - (0, uri_parser_1.uriToString)(this.target) + - ': ' + - allAddressesString); - /* If the TXT lookup has not yet finished, both of the last two - * arguments will be null, which is the equivalent of getting an - * empty TXT response. When the TXT lookup does finish, its handler - * can update the service config by using the same address list */ - const healthStatus = this.listener(this.latestLookupResult, {}, this.latestServiceConfigResult, ''); - this.handleHealthStatus(healthStatus); - }, err => { - if (this.pendingLookupPromise === null) { - return; - } - trace('Resolution error for target ' + - (0, uri_parser_1.uriToString)(this.target) + - ': ' + - err.message); - this.pendingLookupPromise = null; - this.stopNextResolutionTimer(); - this.listener((0, call_interface_1.statusOrFromError)(this.defaultResolutionError), {}, this.latestServiceConfigResult, ''); - }); - /* If there already is a still-pending TXT resolution, we can just use - * that result when it comes in */ - if (this.isServiceConfigEnabled && this.pendingTxtPromise === null) { - /* We handle the TXT query promise differently than the others because - * the name resolution attempt as a whole is a success even if the TXT - * lookup fails */ - this.pendingTxtPromise = this.resolveTxt(hostname); - this.pendingTxtPromise.then(txtRecord => { - if (this.pendingTxtPromise === null) { - return; - } - this.pendingTxtPromise = null; - let serviceConfig; - try { - serviceConfig = (0, service_config_1.extractAndSelectServiceConfig)(txtRecord, this.percentage); - if (serviceConfig) { - this.latestServiceConfigResult = (0, call_interface_1.statusOrFromValue)(serviceConfig); - } - else { - this.latestServiceConfigResult = null; - } - } - catch (err) { - this.latestServiceConfigResult = (0, call_interface_1.statusOrFromError)({ - code: constants_1.Status.UNAVAILABLE, - details: `Parsing service config failed with error ${err.message}` - }); - } - if (this.latestLookupResult !== null) { - /* We rely here on the assumption that calling this function with - * identical parameters will be essentialy idempotent, and calling - * it with the same address list and a different service config - * should result in a fast and seamless switchover. */ - this.listener(this.latestLookupResult, {}, this.latestServiceConfigResult, ''); - } - }, err => { - /* If TXT lookup fails we should do nothing, which means that we - * continue to use the result of the most recent successful lookup, - * or the default null config object if there has never been a - * successful lookup. We do not set the latestServiceConfigError - * here because that is specifically used for response validation - * errors. We still need to handle this error so that it does not - * bubble up as an unhandled promise rejection. */ - }); - } - } - } - /** - * The ResolverListener returns a boolean indicating whether the LB policy - * accepted the resolution result. A false result on an otherwise successful - * resolution should be treated as a resolution failure. - * @param healthStatus - */ - handleHealthStatus(healthStatus) { - if (healthStatus) { - this.backoff.stop(); - this.backoff.reset(); - } - else { - this.continueResolving = true; - } - } - async lookup(hostname) { - if (environment_1.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) { - trace('Using alternative DNS resolver.'); - const records = await Promise.allSettled([ - this.alternativeResolver.resolve4(hostname), - this.alternativeResolver.resolve6(hostname), - ]); - if (records.every(result => result.status === 'rejected')) { - throw new Error(records[0].reason); - } - return records - .reduce((acc, result) => { - return result.status === 'fulfilled' - ? [...acc, ...result.value] - : acc; - }, []) - .map(addr => ({ - host: addr, - port: +this.port, - })); - } - /* We lookup both address families here and then split them up later - * because when looking up a single family, dns.lookup outputs an error - * if the name exists but there are no records for that family, and that - * error is indistinguishable from other kinds of errors */ - const addressList = await dns_1.promises.lookup(hostname, { all: true }); - return addressList.map(addr => ({ host: addr.address, port: +this.port })); - } - async resolveTxt(hostname) { - if (environment_1.GRPC_NODE_USE_ALTERNATIVE_RESOLVER) { - trace('Using alternative DNS resolver.'); - return this.alternativeResolver.resolveTxt(hostname); - } - return dns_1.promises.resolveTxt(hostname); - } - startNextResolutionTimer() { - var _a, _b; - clearTimeout(this.nextResolutionTimer); - this.nextResolutionTimer = setTimeout(() => { - this.stopNextResolutionTimer(); - if (this.continueResolving) { - this.startResolutionWithBackoff(); - } - }, this.minTimeBetweenResolutionsMs); - (_b = (_a = this.nextResolutionTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - this.isNextResolutionTimerRunning = true; - } - stopNextResolutionTimer() { - clearTimeout(this.nextResolutionTimer); - this.isNextResolutionTimerRunning = false; - } - startResolutionWithBackoff() { - if (this.pendingLookupPromise === null) { - this.continueResolving = false; - this.backoff.runOnce(); - this.startNextResolutionTimer(); - this.startResolution(); - } - } - updateResolution() { - /* If there is a pending lookup, just let it finish. Otherwise, if the - * nextResolutionTimer or backoff timer is running, set the - * continueResolving flag to resolve when whichever of those timers - * fires. Otherwise, start resolving immediately. */ - if (this.pendingLookupPromise === null) { - if (this.isNextResolutionTimerRunning || this.backoff.isRunning()) { - if (this.isNextResolutionTimerRunning) { - trace('resolution update delayed by "min time between resolutions" rate limit'); - } - else { - trace('resolution update delayed by backoff timer until ' + - this.backoff.getEndTime().toISOString()); - } - this.continueResolving = true; - } - else { - this.startResolutionWithBackoff(); - } - } - } - /** - * Reset the resolver to the same state it had when it was created. In-flight - * DNS requests cannot be cancelled, but they are discarded and their results - * will be ignored. - */ - destroy() { - this.continueResolving = false; - this.backoff.reset(); - this.backoff.stop(); - this.stopNextResolutionTimer(); - this.pendingLookupPromise = null; - this.pendingTxtPromise = null; - this.latestLookupResult = null; - this.latestServiceConfigResult = null; - this.returnedIpResult = false; - } - /** - * Get the default authority for the given target. For IP targets, that is - * the IP address. For DNS targets, it is the hostname. - * @param target - */ - static getDefaultAuthority(target) { - return target.path; - } -} -/** - * Set up the DNS resolver class by registering it as the handler for the - * "dns:" prefix and as the default resolver. - */ -function setup() { - (0, resolver_1.registerResolver)('dns', DnsResolver); - (0, resolver_1.registerDefaultScheme)('dns'); -} -//# sourceMappingURL=resolver-dns.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/resolver-ip.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/resolver-ip.js deleted file mode 100644 index 411d64c0..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/resolver-ip.js +++ /dev/null @@ -1,106 +0,0 @@ -"use strict"; -/* - * Copyright 2021 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.setup = setup; -const net_1 = require("net"); -const call_interface_1 = require("./call-interface"); -const constants_1 = require("./constants"); -const metadata_1 = require("./metadata"); -const resolver_1 = require("./resolver"); -const subchannel_address_1 = require("./subchannel-address"); -const uri_parser_1 = require("./uri-parser"); -const logging = require("./logging"); -const TRACER_NAME = 'ip_resolver'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -const IPV4_SCHEME = 'ipv4'; -const IPV6_SCHEME = 'ipv6'; -/** - * The default TCP port to connect to if not explicitly specified in the target. - */ -const DEFAULT_PORT = 443; -class IpResolver { - constructor(target, listener, channelOptions) { - var _a; - this.listener = listener; - this.endpoints = []; - this.error = null; - this.hasReturnedResult = false; - trace('Resolver constructed for target ' + (0, uri_parser_1.uriToString)(target)); - const addresses = []; - if (!(target.scheme === IPV4_SCHEME || target.scheme === IPV6_SCHEME)) { - this.error = { - code: constants_1.Status.UNAVAILABLE, - details: `Unrecognized scheme ${target.scheme} in IP resolver`, - metadata: new metadata_1.Metadata(), - }; - return; - } - const pathList = target.path.split(','); - for (const path of pathList) { - const hostPort = (0, uri_parser_1.splitHostPort)(path); - if (hostPort === null) { - this.error = { - code: constants_1.Status.UNAVAILABLE, - details: `Failed to parse ${target.scheme} address ${path}`, - metadata: new metadata_1.Metadata(), - }; - return; - } - if ((target.scheme === IPV4_SCHEME && !(0, net_1.isIPv4)(hostPort.host)) || - (target.scheme === IPV6_SCHEME && !(0, net_1.isIPv6)(hostPort.host))) { - this.error = { - code: constants_1.Status.UNAVAILABLE, - details: `Failed to parse ${target.scheme} address ${path}`, - metadata: new metadata_1.Metadata(), - }; - return; - } - addresses.push({ - host: hostPort.host, - port: (_a = hostPort.port) !== null && _a !== void 0 ? _a : DEFAULT_PORT, - }); - } - this.endpoints = addresses.map(address => ({ addresses: [address] })); - trace('Parsed ' + target.scheme + ' address list ' + addresses.map(subchannel_address_1.subchannelAddressToString)); - } - updateResolution() { - if (!this.hasReturnedResult) { - this.hasReturnedResult = true; - process.nextTick(() => { - if (this.error) { - this.listener((0, call_interface_1.statusOrFromError)(this.error), {}, null, ''); - } - else { - this.listener((0, call_interface_1.statusOrFromValue)(this.endpoints), {}, null, ''); - } - }); - } - } - destroy() { - this.hasReturnedResult = false; - } - static getDefaultAuthority(target) { - return target.path.split(',')[0]; - } -} -function setup() { - (0, resolver_1.registerResolver)(IPV4_SCHEME, IpResolver); - (0, resolver_1.registerResolver)(IPV6_SCHEME, IpResolver); -} -//# sourceMappingURL=resolver-ip.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/resolver-uds.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/resolver-uds.js deleted file mode 100644 index 79290d45..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/resolver-uds.js +++ /dev/null @@ -1,51 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.setup = setup; -const resolver_1 = require("./resolver"); -const call_interface_1 = require("./call-interface"); -class UdsResolver { - constructor(target, listener, channelOptions) { - this.listener = listener; - this.hasReturnedResult = false; - this.endpoints = []; - let path; - if (target.authority === '') { - path = '/' + target.path; - } - else { - path = target.path; - } - this.endpoints = [{ addresses: [{ path }] }]; - } - updateResolution() { - if (!this.hasReturnedResult) { - this.hasReturnedResult = true; - process.nextTick(this.listener, (0, call_interface_1.statusOrFromValue)(this.endpoints), {}, null, ''); - } - } - destroy() { - this.hasReturnedResult = false; - } - static getDefaultAuthority(target) { - return 'localhost'; - } -} -function setup() { - (0, resolver_1.registerResolver)('unix', UdsResolver); -} -//# sourceMappingURL=resolver-uds.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/resolver.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/resolver.js deleted file mode 100644 index 6b1a7c9c..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/resolver.js +++ /dev/null @@ -1,89 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = void 0; -exports.registerResolver = registerResolver; -exports.registerDefaultScheme = registerDefaultScheme; -exports.createResolver = createResolver; -exports.getDefaultAuthority = getDefaultAuthority; -exports.mapUriDefaultScheme = mapUriDefaultScheme; -const uri_parser_1 = require("./uri-parser"); -exports.CHANNEL_ARGS_CONFIG_SELECTOR_KEY = 'grpc.internal.config_selector'; -const registeredResolvers = {}; -let defaultScheme = null; -/** - * Register a resolver class to handle target names prefixed with the `prefix` - * string. This prefix should correspond to a URI scheme name listed in the - * [gRPC Name Resolution document](https://github.com/grpc/grpc/blob/master/doc/naming.md) - * @param prefix - * @param resolverClass - */ -function registerResolver(scheme, resolverClass) { - registeredResolvers[scheme] = resolverClass; -} -/** - * Register a default resolver to handle target names that do not start with - * any registered prefix. - * @param resolverClass - */ -function registerDefaultScheme(scheme) { - defaultScheme = scheme; -} -/** - * Create a name resolver for the specified target, if possible. Throws an - * error if no such name resolver can be created. - * @param target - * @param listener - */ -function createResolver(target, listener, options) { - if (target.scheme !== undefined && target.scheme in registeredResolvers) { - return new registeredResolvers[target.scheme](target, listener, options); - } - else { - throw new Error(`No resolver could be created for target ${(0, uri_parser_1.uriToString)(target)}`); - } -} -/** - * Get the default authority for the specified target, if possible. Throws an - * error if no registered name resolver can parse that target string. - * @param target - */ -function getDefaultAuthority(target) { - if (target.scheme !== undefined && target.scheme in registeredResolvers) { - return registeredResolvers[target.scheme].getDefaultAuthority(target); - } - else { - throw new Error(`Invalid target ${(0, uri_parser_1.uriToString)(target)}`); - } -} -function mapUriDefaultScheme(target) { - if (target.scheme === undefined || !(target.scheme in registeredResolvers)) { - if (defaultScheme !== null) { - return { - scheme: defaultScheme, - authority: undefined, - path: (0, uri_parser_1.uriToString)(target), - }; - } - else { - return null; - } - } - return target; -} -//# sourceMappingURL=resolver.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/resolving-call.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/resolving-call.js deleted file mode 100644 index 8a471666..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/resolving-call.js +++ /dev/null @@ -1,319 +0,0 @@ -"use strict"; -/* - * Copyright 2022 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ResolvingCall = void 0; -const call_credentials_1 = require("./call-credentials"); -const constants_1 = require("./constants"); -const deadline_1 = require("./deadline"); -const metadata_1 = require("./metadata"); -const logging = require("./logging"); -const control_plane_status_1 = require("./control-plane-status"); -const TRACER_NAME = 'resolving_call'; -class ResolvingCall { - constructor(channel, method, options, filterStackFactory, callNumber) { - this.channel = channel; - this.method = method; - this.filterStackFactory = filterStackFactory; - this.callNumber = callNumber; - this.child = null; - this.readPending = false; - this.pendingMessage = null; - this.pendingHalfClose = false; - this.ended = false; - this.readFilterPending = false; - this.writeFilterPending = false; - this.pendingChildStatus = null; - this.metadata = null; - this.listener = null; - this.statusWatchers = []; - this.deadlineTimer = setTimeout(() => { }, 0); - this.filterStack = null; - this.deadlineStartTime = null; - this.configReceivedTime = null; - this.childStartTime = null; - /** - * Credentials configured for this specific call. Does not include - * call credentials associated with the channel credentials used to create - * the channel. - */ - this.credentials = call_credentials_1.CallCredentials.createEmpty(); - this.deadline = options.deadline; - this.host = options.host; - if (options.parentCall) { - if (options.flags & constants_1.Propagate.CANCELLATION) { - options.parentCall.on('cancelled', () => { - this.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled by parent call'); - }); - } - if (options.flags & constants_1.Propagate.DEADLINE) { - this.trace('Propagating deadline from parent: ' + - options.parentCall.getDeadline()); - this.deadline = (0, deadline_1.minDeadline)(this.deadline, options.parentCall.getDeadline()); - } - } - this.trace('Created'); - this.runDeadlineTimer(); - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callNumber + '] ' + text); - } - runDeadlineTimer() { - clearTimeout(this.deadlineTimer); - this.deadlineStartTime = new Date(); - this.trace('Deadline: ' + (0, deadline_1.deadlineToString)(this.deadline)); - const timeout = (0, deadline_1.getRelativeTimeout)(this.deadline); - if (timeout !== Infinity) { - this.trace('Deadline will be reached in ' + timeout + 'ms'); - const handleDeadline = () => { - if (!this.deadlineStartTime) { - this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, 'Deadline exceeded'); - return; - } - const deadlineInfo = []; - const deadlineEndTime = new Date(); - deadlineInfo.push(`Deadline exceeded after ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, deadlineEndTime)}`); - if (this.configReceivedTime) { - if (this.configReceivedTime > this.deadlineStartTime) { - deadlineInfo.push(`name resolution: ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, this.configReceivedTime)}`); - } - if (this.childStartTime) { - if (this.childStartTime > this.configReceivedTime) { - deadlineInfo.push(`metadata filters: ${(0, deadline_1.formatDateDifference)(this.configReceivedTime, this.childStartTime)}`); - } - } - else { - deadlineInfo.push('waiting for metadata filters'); - } - } - else { - deadlineInfo.push('waiting for name resolution'); - } - if (this.child) { - deadlineInfo.push(...this.child.getDeadlineInfo()); - } - this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, deadlineInfo.join(',')); - }; - if (timeout <= 0) { - process.nextTick(handleDeadline); - } - else { - this.deadlineTimer = setTimeout(handleDeadline, timeout); - } - } - } - outputStatus(status) { - if (!this.ended) { - this.ended = true; - if (!this.filterStack) { - this.filterStack = this.filterStackFactory.createFilter(); - } - clearTimeout(this.deadlineTimer); - const filteredStatus = this.filterStack.receiveTrailers(status); - this.trace('ended with status: code=' + - filteredStatus.code + - ' details="' + - filteredStatus.details + - '"'); - this.statusWatchers.forEach(watcher => watcher(filteredStatus)); - process.nextTick(() => { - var _a; - (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus(filteredStatus); - }); - } - } - sendMessageOnChild(context, message) { - if (!this.child) { - throw new Error('sendMessageonChild called with child not populated'); - } - const child = this.child; - this.writeFilterPending = true; - this.filterStack.sendMessage(Promise.resolve({ message: message, flags: context.flags })).then(filteredMessage => { - this.writeFilterPending = false; - child.sendMessageWithContext(context, filteredMessage.message); - if (this.pendingHalfClose) { - child.halfClose(); - } - }, (status) => { - this.cancelWithStatus(status.code, status.details); - }); - } - getConfig() { - if (this.ended) { - return; - } - if (!this.metadata || !this.listener) { - throw new Error('getConfig called before start'); - } - const configResult = this.channel.getConfig(this.method, this.metadata); - if (configResult.type === 'NONE') { - this.channel.queueCallForConfig(this); - return; - } - else if (configResult.type === 'ERROR') { - if (this.metadata.getOptions().waitForReady) { - this.channel.queueCallForConfig(this); - } - else { - this.outputStatus(configResult.error); - } - return; - } - // configResult.type === 'SUCCESS' - this.configReceivedTime = new Date(); - const config = configResult.config; - if (config.status !== constants_1.Status.OK) { - const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(config.status, 'Failed to route call to method ' + this.method); - this.outputStatus({ - code: code, - details: details, - metadata: new metadata_1.Metadata(), - }); - return; - } - if (config.methodConfig.timeout) { - const configDeadline = new Date(); - configDeadline.setSeconds(configDeadline.getSeconds() + config.methodConfig.timeout.seconds); - configDeadline.setMilliseconds(configDeadline.getMilliseconds() + - config.methodConfig.timeout.nanos / 1000000); - this.deadline = (0, deadline_1.minDeadline)(this.deadline, configDeadline); - this.runDeadlineTimer(); - } - this.filterStackFactory.push(config.dynamicFilterFactories); - this.filterStack = this.filterStackFactory.createFilter(); - this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then(filteredMetadata => { - this.child = this.channel.createRetryingCall(config, this.method, this.host, this.credentials, this.deadline); - this.trace('Created child [' + this.child.getCallNumber() + ']'); - this.childStartTime = new Date(); - this.child.start(filteredMetadata, { - onReceiveMetadata: metadata => { - this.trace('Received metadata'); - this.listener.onReceiveMetadata(this.filterStack.receiveMetadata(metadata)); - }, - onReceiveMessage: message => { - this.trace('Received message'); - this.readFilterPending = true; - this.filterStack.receiveMessage(message).then(filteredMesssage => { - this.trace('Finished filtering received message'); - this.readFilterPending = false; - this.listener.onReceiveMessage(filteredMesssage); - if (this.pendingChildStatus) { - this.outputStatus(this.pendingChildStatus); - } - }, (status) => { - this.cancelWithStatus(status.code, status.details); - }); - }, - onReceiveStatus: status => { - this.trace('Received status'); - if (this.readFilterPending) { - this.pendingChildStatus = status; - } - else { - this.outputStatus(status); - } - }, - }); - if (this.readPending) { - this.child.startRead(); - } - if (this.pendingMessage) { - this.sendMessageOnChild(this.pendingMessage.context, this.pendingMessage.message); - } - else if (this.pendingHalfClose) { - this.child.halfClose(); - } - }, (status) => { - this.outputStatus(status); - }); - } - reportResolverError(status) { - var _a; - if ((_a = this.metadata) === null || _a === void 0 ? void 0 : _a.getOptions().waitForReady) { - this.channel.queueCallForConfig(this); - } - else { - this.outputStatus(status); - } - } - cancelWithStatus(status, details) { - var _a; - this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"'); - (_a = this.child) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(status, details); - this.outputStatus({ - code: status, - details: details, - metadata: new metadata_1.Metadata(), - }); - } - getPeer() { - var _a, _b; - return (_b = (_a = this.child) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.channel.getTarget(); - } - start(metadata, listener) { - this.trace('start called'); - this.metadata = metadata.clone(); - this.listener = listener; - this.getConfig(); - } - sendMessageWithContext(context, message) { - this.trace('write() called with message of length ' + message.length); - if (this.child) { - this.sendMessageOnChild(context, message); - } - else { - this.pendingMessage = { context, message }; - } - } - startRead() { - this.trace('startRead called'); - if (this.child) { - this.child.startRead(); - } - else { - this.readPending = true; - } - } - halfClose() { - this.trace('halfClose called'); - if (this.child && !this.writeFilterPending) { - this.child.halfClose(); - } - else { - this.pendingHalfClose = true; - } - } - setCredentials(credentials) { - this.credentials = credentials; - } - addStatusWatcher(watcher) { - this.statusWatchers.push(watcher); - } - getCallNumber() { - return this.callNumber; - } - getAuthContext() { - if (this.child) { - return this.child.getAuthContext(); - } - else { - return null; - } - } -} -exports.ResolvingCall = ResolvingCall; -//# sourceMappingURL=resolving-call.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js deleted file mode 100644 index ca614744..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js +++ /dev/null @@ -1,304 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ResolvingLoadBalancer = void 0; -const load_balancer_1 = require("./load-balancer"); -const service_config_1 = require("./service-config"); -const connectivity_state_1 = require("./connectivity-state"); -const resolver_1 = require("./resolver"); -const picker_1 = require("./picker"); -const backoff_timeout_1 = require("./backoff-timeout"); -const constants_1 = require("./constants"); -const metadata_1 = require("./metadata"); -const logging = require("./logging"); -const constants_2 = require("./constants"); -const uri_parser_1 = require("./uri-parser"); -const load_balancer_child_handler_1 = require("./load-balancer-child-handler"); -const TRACER_NAME = 'resolving_load_balancer'; -function trace(text) { - logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text); -} -/** - * Name match levels in order from most to least specific. This is the order in - * which searches will be performed. - */ -const NAME_MATCH_LEVEL_ORDER = [ - 'SERVICE_AND_METHOD', - 'SERVICE', - 'EMPTY', -]; -function hasMatchingName(service, method, methodConfig, matchLevel) { - for (const name of methodConfig.name) { - switch (matchLevel) { - case 'EMPTY': - if (!name.service && !name.method) { - return true; - } - break; - case 'SERVICE': - if (name.service === service && !name.method) { - return true; - } - break; - case 'SERVICE_AND_METHOD': - if (name.service === service && name.method === method) { - return true; - } - } - } - return false; -} -function findMatchingConfig(service, method, methodConfigs, matchLevel) { - for (const config of methodConfigs) { - if (hasMatchingName(service, method, config, matchLevel)) { - return config; - } - } - return null; -} -function getDefaultConfigSelector(serviceConfig) { - return { - invoke(methodName, metadata) { - var _a, _b; - const splitName = methodName.split('/').filter(x => x.length > 0); - const service = (_a = splitName[0]) !== null && _a !== void 0 ? _a : ''; - const method = (_b = splitName[1]) !== null && _b !== void 0 ? _b : ''; - if (serviceConfig && serviceConfig.methodConfig) { - /* Check for the following in order, and return the first method - * config that matches: - * 1. A name that exactly matches the service and method - * 2. A name with no method set that matches the service - * 3. An empty name - */ - for (const matchLevel of NAME_MATCH_LEVEL_ORDER) { - const matchingConfig = findMatchingConfig(service, method, serviceConfig.methodConfig, matchLevel); - if (matchingConfig) { - return { - methodConfig: matchingConfig, - pickInformation: {}, - status: constants_1.Status.OK, - dynamicFilterFactories: [], - }; - } - } - } - return { - methodConfig: { name: [] }, - pickInformation: {}, - status: constants_1.Status.OK, - dynamicFilterFactories: [], - }; - }, - unref() { } - }; -} -class ResolvingLoadBalancer { - /** - * Wrapper class that behaves like a `LoadBalancer` and also handles name - * resolution internally. - * @param target The address of the backend to connect to. - * @param channelControlHelper `ChannelControlHelper` instance provided by - * this load balancer's owner. - * @param defaultServiceConfig The default service configuration to be used - * if none is provided by the name resolver. A `null` value indicates - * that the default behavior should be the default unconfigured behavior. - * In practice, that means using the "pick first" load balancer - * implmentation - */ - constructor(target, channelControlHelper, channelOptions, onSuccessfulResolution, onFailedResolution) { - this.target = target; - this.channelControlHelper = channelControlHelper; - this.channelOptions = channelOptions; - this.onSuccessfulResolution = onSuccessfulResolution; - this.onFailedResolution = onFailedResolution; - this.latestChildState = connectivity_state_1.ConnectivityState.IDLE; - this.latestChildPicker = new picker_1.QueuePicker(this); - this.latestChildErrorMessage = null; - /** - * This resolving load balancer's current connectivity state. - */ - this.currentState = connectivity_state_1.ConnectivityState.IDLE; - /** - * The service config object from the last successful resolution, if - * available. A value of null indicates that we have not yet received a valid - * service config from the resolver. - */ - this.previousServiceConfig = null; - /** - * Indicates whether we should attempt to resolve again after the backoff - * timer runs out. - */ - this.continueResolving = false; - if (channelOptions['grpc.service_config']) { - this.defaultServiceConfig = (0, service_config_1.validateServiceConfig)(JSON.parse(channelOptions['grpc.service_config'])); - } - else { - this.defaultServiceConfig = { - loadBalancingConfig: [], - methodConfig: [], - }; - } - this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this), null); - this.childLoadBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler({ - createSubchannel: channelControlHelper.createSubchannel.bind(channelControlHelper), - requestReresolution: () => { - /* If the backoffTimeout is running, we're still backing off from - * making resolve requests, so we shouldn't make another one here. - * In that case, the backoff timer callback will call - * updateResolution */ - if (this.backoffTimeout.isRunning()) { - trace('requestReresolution delayed by backoff timer until ' + - this.backoffTimeout.getEndTime().toISOString()); - this.continueResolving = true; - } - else { - this.updateResolution(); - } - }, - updateState: (newState, picker, errorMessage) => { - this.latestChildState = newState; - this.latestChildPicker = picker; - this.latestChildErrorMessage = errorMessage; - this.updateState(newState, picker, errorMessage); - }, - addChannelzChild: channelControlHelper.addChannelzChild.bind(channelControlHelper), - removeChannelzChild: channelControlHelper.removeChannelzChild.bind(channelControlHelper), - }); - this.innerResolver = (0, resolver_1.createResolver)(target, this.handleResolverResult.bind(this), channelOptions); - const backoffOptions = { - initialDelay: channelOptions['grpc.initial_reconnect_backoff_ms'], - maxDelay: channelOptions['grpc.max_reconnect_backoff_ms'], - }; - this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => { - if (this.continueResolving) { - this.updateResolution(); - this.continueResolving = false; - } - else { - this.updateState(this.latestChildState, this.latestChildPicker, this.latestChildErrorMessage); - } - }, backoffOptions); - this.backoffTimeout.unref(); - } - handleResolverResult(endpointList, attributes, serviceConfig, resolutionNote) { - var _a, _b; - this.backoffTimeout.stop(); - this.backoffTimeout.reset(); - let resultAccepted = true; - let workingServiceConfig = null; - if (serviceConfig === null) { - workingServiceConfig = this.defaultServiceConfig; - } - else if (serviceConfig.ok) { - workingServiceConfig = serviceConfig.value; - } - else { - if (this.previousServiceConfig !== null) { - workingServiceConfig = this.previousServiceConfig; - } - else { - resultAccepted = false; - this.handleResolutionFailure(serviceConfig.error); - } - } - if (workingServiceConfig !== null) { - const workingConfigList = (_a = workingServiceConfig === null || workingServiceConfig === void 0 ? void 0 : workingServiceConfig.loadBalancingConfig) !== null && _a !== void 0 ? _a : []; - const loadBalancingConfig = (0, load_balancer_1.selectLbConfigFromList)(workingConfigList, true); - if (loadBalancingConfig === null) { - resultAccepted = false; - this.handleResolutionFailure({ - code: constants_1.Status.UNAVAILABLE, - details: 'All load balancer options in service config are not compatible', - metadata: new metadata_1.Metadata(), - }); - } - else { - resultAccepted = this.childLoadBalancer.updateAddressList(endpointList, loadBalancingConfig, Object.assign(Object.assign({}, this.channelOptions), attributes), resolutionNote); - } - } - if (resultAccepted) { - this.onSuccessfulResolution(workingServiceConfig, (_b = attributes[resolver_1.CHANNEL_ARGS_CONFIG_SELECTOR_KEY]) !== null && _b !== void 0 ? _b : getDefaultConfigSelector(workingServiceConfig)); - } - return resultAccepted; - } - updateResolution() { - this.innerResolver.updateResolution(); - if (this.currentState === connectivity_state_1.ConnectivityState.IDLE) { - /* this.latestChildPicker is initialized as new QueuePicker(this), which - * is an appropriate value here if the child LB policy is unset. - * Otherwise, we want to delegate to the child here, in case that - * triggers something. */ - this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, this.latestChildPicker, this.latestChildErrorMessage); - } - this.backoffTimeout.runOnce(); - } - updateState(connectivityState, picker, errorMessage) { - trace((0, uri_parser_1.uriToString)(this.target) + - ' ' + - connectivity_state_1.ConnectivityState[this.currentState] + - ' -> ' + - connectivity_state_1.ConnectivityState[connectivityState]); - // Ensure that this.exitIdle() is called by the picker - if (connectivityState === connectivity_state_1.ConnectivityState.IDLE) { - picker = new picker_1.QueuePicker(this, picker); - } - this.currentState = connectivityState; - this.channelControlHelper.updateState(connectivityState, picker, errorMessage); - } - handleResolutionFailure(error) { - if (this.latestChildState === connectivity_state_1.ConnectivityState.IDLE) { - this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(error), error.details); - this.onFailedResolution(error); - } - } - exitIdle() { - if (this.currentState === connectivity_state_1.ConnectivityState.IDLE || - this.currentState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { - if (this.backoffTimeout.isRunning()) { - this.continueResolving = true; - } - else { - this.updateResolution(); - } - } - this.childLoadBalancer.exitIdle(); - } - updateAddressList(endpointList, lbConfig) { - throw new Error('updateAddressList not supported on ResolvingLoadBalancer'); - } - resetBackoff() { - this.backoffTimeout.reset(); - this.childLoadBalancer.resetBackoff(); - } - destroy() { - this.childLoadBalancer.destroy(); - this.innerResolver.destroy(); - this.backoffTimeout.reset(); - this.backoffTimeout.stop(); - this.latestChildState = connectivity_state_1.ConnectivityState.IDLE; - this.latestChildPicker = new picker_1.QueuePicker(this); - this.currentState = connectivity_state_1.ConnectivityState.IDLE; - this.previousServiceConfig = null; - this.continueResolving = false; - } - getTypeName() { - return 'resolving_load_balancer'; - } -} -exports.ResolvingLoadBalancer = ResolvingLoadBalancer; -//# sourceMappingURL=resolving-load-balancer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/retrying-call.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/retrying-call.js deleted file mode 100644 index 890df244..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/retrying-call.js +++ /dev/null @@ -1,700 +0,0 @@ -"use strict"; -/* - * Copyright 2022 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RetryingCall = exports.MessageBufferTracker = exports.RetryThrottler = void 0; -const constants_1 = require("./constants"); -const deadline_1 = require("./deadline"); -const metadata_1 = require("./metadata"); -const logging = require("./logging"); -const TRACER_NAME = 'retrying_call'; -class RetryThrottler { - constructor(maxTokens, tokenRatio, previousRetryThrottler) { - this.maxTokens = maxTokens; - this.tokenRatio = tokenRatio; - if (previousRetryThrottler) { - /* When carrying over tokens from a previous config, rescale them to the - * new max value */ - this.tokens = - previousRetryThrottler.tokens * - (maxTokens / previousRetryThrottler.maxTokens); - } - else { - this.tokens = maxTokens; - } - } - addCallSucceeded() { - this.tokens = Math.min(this.tokens + this.tokenRatio, this.maxTokens); - } - addCallFailed() { - this.tokens = Math.max(this.tokens - 1, 0); - } - canRetryCall() { - return this.tokens > (this.maxTokens / 2); - } -} -exports.RetryThrottler = RetryThrottler; -class MessageBufferTracker { - constructor(totalLimit, limitPerCall) { - this.totalLimit = totalLimit; - this.limitPerCall = limitPerCall; - this.totalAllocated = 0; - this.allocatedPerCall = new Map(); - } - allocate(size, callId) { - var _a; - const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; - if (this.limitPerCall - currentPerCall < size || - this.totalLimit - this.totalAllocated < size) { - return false; - } - this.allocatedPerCall.set(callId, currentPerCall + size); - this.totalAllocated += size; - return true; - } - free(size, callId) { - var _a; - if (this.totalAllocated < size) { - throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > total allocated ${this.totalAllocated}`); - } - this.totalAllocated -= size; - const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; - if (currentPerCall < size) { - throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > allocated for call ${currentPerCall}`); - } - this.allocatedPerCall.set(callId, currentPerCall - size); - } - freeAll(callId) { - var _a; - const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; - if (this.totalAllocated < currentPerCall) { - throw new Error(`Invalid buffer allocation state: call ${callId} allocated ${currentPerCall} > total allocated ${this.totalAllocated}`); - } - this.totalAllocated -= currentPerCall; - this.allocatedPerCall.delete(callId); - } -} -exports.MessageBufferTracker = MessageBufferTracker; -const PREVIONS_RPC_ATTEMPTS_METADATA_KEY = 'grpc-previous-rpc-attempts'; -const DEFAULT_MAX_ATTEMPTS_LIMIT = 5; -class RetryingCall { - constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber, bufferTracker, retryThrottler) { - var _a; - this.channel = channel; - this.callConfig = callConfig; - this.methodName = methodName; - this.host = host; - this.credentials = credentials; - this.deadline = deadline; - this.callNumber = callNumber; - this.bufferTracker = bufferTracker; - this.retryThrottler = retryThrottler; - this.listener = null; - this.initialMetadata = null; - this.underlyingCalls = []; - this.writeBuffer = []; - /** - * The offset of message indices in the writeBuffer. For example, if - * writeBufferOffset is 10, message 10 is in writeBuffer[0] and message 15 - * is in writeBuffer[5]. - */ - this.writeBufferOffset = 0; - /** - * Tracks whether a read has been started, so that we know whether to start - * reads on new child calls. This only matters for the first read, because - * once a message comes in the child call becomes committed and there will - * be no new child calls. - */ - this.readStarted = false; - this.transparentRetryUsed = false; - /** - * Number of attempts so far - */ - this.attempts = 0; - this.hedgingTimer = null; - this.committedCallIndex = null; - this.initialRetryBackoffSec = 0; - this.nextRetryBackoffSec = 0; - const maxAttemptsLimit = (_a = channel.getOptions()['grpc-node.retry_max_attempts_limit']) !== null && _a !== void 0 ? _a : DEFAULT_MAX_ATTEMPTS_LIMIT; - if (channel.getOptions()['grpc.enable_retries'] === 0) { - this.state = 'NO_RETRY'; - this.maxAttempts = 1; - } - else if (callConfig.methodConfig.retryPolicy) { - this.state = 'RETRY'; - const retryPolicy = callConfig.methodConfig.retryPolicy; - this.nextRetryBackoffSec = this.initialRetryBackoffSec = Number(retryPolicy.initialBackoff.substring(0, retryPolicy.initialBackoff.length - 1)); - this.maxAttempts = Math.min(retryPolicy.maxAttempts, maxAttemptsLimit); - } - else if (callConfig.methodConfig.hedgingPolicy) { - this.state = 'HEDGING'; - this.maxAttempts = Math.min(callConfig.methodConfig.hedgingPolicy.maxAttempts, maxAttemptsLimit); - } - else { - this.state = 'TRANSPARENT_ONLY'; - this.maxAttempts = 1; - } - this.startTime = new Date(); - } - getDeadlineInfo() { - if (this.underlyingCalls.length === 0) { - return []; - } - const deadlineInfo = []; - const latestCall = this.underlyingCalls[this.underlyingCalls.length - 1]; - if (this.underlyingCalls.length > 1) { - deadlineInfo.push(`previous attempts: ${this.underlyingCalls.length - 1}`); - } - if (latestCall.startTime > this.startTime) { - deadlineInfo.push(`time to current attempt start: ${(0, deadline_1.formatDateDifference)(this.startTime, latestCall.startTime)}`); - } - deadlineInfo.push(...latestCall.call.getDeadlineInfo()); - return deadlineInfo; - } - getCallNumber() { - return this.callNumber; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callNumber + '] ' + text); - } - reportStatus(statusObject) { - this.trace('ended with status: code=' + - statusObject.code + - ' details="' + - statusObject.details + - '" start time=' + - this.startTime.toISOString()); - this.bufferTracker.freeAll(this.callNumber); - this.writeBufferOffset = this.writeBufferOffset + this.writeBuffer.length; - this.writeBuffer = []; - process.nextTick(() => { - var _a; - // Explicitly construct status object to remove progress field - (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus({ - code: statusObject.code, - details: statusObject.details, - metadata: statusObject.metadata, - }); - }); - } - cancelWithStatus(status, details) { - this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"'); - this.reportStatus({ code: status, details, metadata: new metadata_1.Metadata() }); - for (const { call } of this.underlyingCalls) { - call.cancelWithStatus(status, details); - } - } - getPeer() { - if (this.committedCallIndex !== null) { - return this.underlyingCalls[this.committedCallIndex].call.getPeer(); - } - else { - return 'unknown'; - } - } - getBufferEntry(messageIndex) { - var _a; - return ((_a = this.writeBuffer[messageIndex - this.writeBufferOffset]) !== null && _a !== void 0 ? _a : { - entryType: 'FREED', - allocated: false, - }); - } - getNextBufferIndex() { - return this.writeBufferOffset + this.writeBuffer.length; - } - clearSentMessages() { - if (this.state !== 'COMMITTED') { - return; - } - let earliestNeededMessageIndex; - if (this.underlyingCalls[this.committedCallIndex].state === 'COMPLETED') { - /* If the committed call is completed, clear all messages, even if some - * have not been sent. */ - earliestNeededMessageIndex = this.getNextBufferIndex(); - } - else { - earliestNeededMessageIndex = - this.underlyingCalls[this.committedCallIndex].nextMessageToSend; - } - for (let messageIndex = this.writeBufferOffset; messageIndex < earliestNeededMessageIndex; messageIndex++) { - const bufferEntry = this.getBufferEntry(messageIndex); - if (bufferEntry.allocated) { - this.bufferTracker.free(bufferEntry.message.message.length, this.callNumber); - } - } - this.writeBuffer = this.writeBuffer.slice(earliestNeededMessageIndex - this.writeBufferOffset); - this.writeBufferOffset = earliestNeededMessageIndex; - } - commitCall(index) { - var _a, _b; - if (this.state === 'COMMITTED') { - return; - } - this.trace('Committing call [' + - this.underlyingCalls[index].call.getCallNumber() + - '] at index ' + - index); - this.state = 'COMMITTED'; - (_b = (_a = this.callConfig).onCommitted) === null || _b === void 0 ? void 0 : _b.call(_a); - this.committedCallIndex = index; - for (let i = 0; i < this.underlyingCalls.length; i++) { - if (i === index) { - continue; - } - if (this.underlyingCalls[i].state === 'COMPLETED') { - continue; - } - this.underlyingCalls[i].state = 'COMPLETED'; - this.underlyingCalls[i].call.cancelWithStatus(constants_1.Status.CANCELLED, 'Discarded in favor of other hedged attempt'); - } - this.clearSentMessages(); - } - commitCallWithMostMessages() { - if (this.state === 'COMMITTED') { - return; - } - let mostMessages = -1; - let callWithMostMessages = -1; - for (const [index, childCall] of this.underlyingCalls.entries()) { - if (childCall.state === 'ACTIVE' && - childCall.nextMessageToSend > mostMessages) { - mostMessages = childCall.nextMessageToSend; - callWithMostMessages = index; - } - } - if (callWithMostMessages === -1) { - /* There are no active calls, disable retries to force the next call that - * is started to be committed. */ - this.state = 'TRANSPARENT_ONLY'; - } - else { - this.commitCall(callWithMostMessages); - } - } - isStatusCodeInList(list, code) { - return list.some(value => { - var _a; - return value === code || - value.toString().toLowerCase() === ((_a = constants_1.Status[code]) === null || _a === void 0 ? void 0 : _a.toLowerCase()); - }); - } - getNextRetryJitter() { - /* Jitter of +-20% is applied: https://github.com/grpc/proposal/blob/master/A6-client-retries.md#exponential-backoff */ - return Math.random() * (1.2 - 0.8) + 0.8; - } - getNextRetryBackoffMs() { - var _a; - const retryPolicy = (_a = this.callConfig) === null || _a === void 0 ? void 0 : _a.methodConfig.retryPolicy; - if (!retryPolicy) { - return 0; - } - const jitter = this.getNextRetryJitter(); - const nextBackoffMs = jitter * this.nextRetryBackoffSec * 1000; - const maxBackoffSec = Number(retryPolicy.maxBackoff.substring(0, retryPolicy.maxBackoff.length - 1)); - this.nextRetryBackoffSec = Math.min(this.nextRetryBackoffSec * retryPolicy.backoffMultiplier, maxBackoffSec); - return nextBackoffMs; - } - maybeRetryCall(pushback, callback) { - if (this.state !== 'RETRY') { - callback(false); - return; - } - if (this.attempts >= this.maxAttempts) { - callback(false); - return; - } - let retryDelayMs; - if (pushback === null) { - retryDelayMs = this.getNextRetryBackoffMs(); - } - else if (pushback < 0) { - this.state = 'TRANSPARENT_ONLY'; - callback(false); - return; - } - else { - retryDelayMs = pushback; - this.nextRetryBackoffSec = this.initialRetryBackoffSec; - } - setTimeout(() => { - var _a, _b; - if (this.state !== 'RETRY') { - callback(false); - return; - } - if ((_b = (_a = this.retryThrottler) === null || _a === void 0 ? void 0 : _a.canRetryCall()) !== null && _b !== void 0 ? _b : true) { - callback(true); - this.attempts += 1; - this.startNewAttempt(); - } - else { - this.trace('Retry attempt denied by throttling policy'); - callback(false); - } - }, retryDelayMs); - } - countActiveCalls() { - let count = 0; - for (const call of this.underlyingCalls) { - if ((call === null || call === void 0 ? void 0 : call.state) === 'ACTIVE') { - count += 1; - } - } - return count; - } - handleProcessedStatus(status, callIndex, pushback) { - var _a, _b, _c; - switch (this.state) { - case 'COMMITTED': - case 'NO_RETRY': - case 'TRANSPARENT_ONLY': - this.commitCall(callIndex); - this.reportStatus(status); - break; - case 'HEDGING': - if (this.isStatusCodeInList((_a = this.callConfig.methodConfig.hedgingPolicy.nonFatalStatusCodes) !== null && _a !== void 0 ? _a : [], status.code)) { - (_b = this.retryThrottler) === null || _b === void 0 ? void 0 : _b.addCallFailed(); - let delayMs; - if (pushback === null) { - delayMs = 0; - } - else if (pushback < 0) { - this.state = 'TRANSPARENT_ONLY'; - this.commitCall(callIndex); - this.reportStatus(status); - return; - } - else { - delayMs = pushback; - } - setTimeout(() => { - this.maybeStartHedgingAttempt(); - // If after trying to start a call there are no active calls, this was the last one - if (this.countActiveCalls() === 0) { - this.commitCall(callIndex); - this.reportStatus(status); - } - }, delayMs); - } - else { - this.commitCall(callIndex); - this.reportStatus(status); - } - break; - case 'RETRY': - if (this.isStatusCodeInList(this.callConfig.methodConfig.retryPolicy.retryableStatusCodes, status.code)) { - (_c = this.retryThrottler) === null || _c === void 0 ? void 0 : _c.addCallFailed(); - this.maybeRetryCall(pushback, retried => { - if (!retried) { - this.commitCall(callIndex); - this.reportStatus(status); - } - }); - } - else { - this.commitCall(callIndex); - this.reportStatus(status); - } - break; - } - } - getPushback(metadata) { - const mdValue = metadata.get('grpc-retry-pushback-ms'); - if (mdValue.length === 0) { - return null; - } - try { - return parseInt(mdValue[0]); - } - catch (e) { - return -1; - } - } - handleChildStatus(status, callIndex) { - var _a; - if (this.underlyingCalls[callIndex].state === 'COMPLETED') { - return; - } - this.trace('state=' + - this.state + - ' handling status with progress ' + - status.progress + - ' from child [' + - this.underlyingCalls[callIndex].call.getCallNumber() + - '] in state ' + - this.underlyingCalls[callIndex].state); - this.underlyingCalls[callIndex].state = 'COMPLETED'; - if (status.code === constants_1.Status.OK) { - (_a = this.retryThrottler) === null || _a === void 0 ? void 0 : _a.addCallSucceeded(); - this.commitCall(callIndex); - this.reportStatus(status); - return; - } - if (this.state === 'NO_RETRY') { - this.commitCall(callIndex); - this.reportStatus(status); - return; - } - if (this.state === 'COMMITTED') { - this.reportStatus(status); - return; - } - const pushback = this.getPushback(status.metadata); - switch (status.progress) { - case 'NOT_STARTED': - // RPC never leaves the client, always safe to retry - this.startNewAttempt(); - break; - case 'REFUSED': - // RPC reaches the server library, but not the server application logic - if (this.transparentRetryUsed) { - this.handleProcessedStatus(status, callIndex, pushback); - } - else { - this.transparentRetryUsed = true; - this.startNewAttempt(); - } - break; - case 'DROP': - this.commitCall(callIndex); - this.reportStatus(status); - break; - case 'PROCESSED': - this.handleProcessedStatus(status, callIndex, pushback); - break; - } - } - maybeStartHedgingAttempt() { - if (this.state !== 'HEDGING') { - return; - } - if (!this.callConfig.methodConfig.hedgingPolicy) { - return; - } - if (this.attempts >= this.maxAttempts) { - return; - } - this.attempts += 1; - this.startNewAttempt(); - this.maybeStartHedgingTimer(); - } - maybeStartHedgingTimer() { - var _a, _b, _c; - if (this.hedgingTimer) { - clearTimeout(this.hedgingTimer); - } - if (this.state !== 'HEDGING') { - return; - } - if (!this.callConfig.methodConfig.hedgingPolicy) { - return; - } - const hedgingPolicy = this.callConfig.methodConfig.hedgingPolicy; - if (this.attempts >= this.maxAttempts) { - return; - } - const hedgingDelayString = (_a = hedgingPolicy.hedgingDelay) !== null && _a !== void 0 ? _a : '0s'; - const hedgingDelaySec = Number(hedgingDelayString.substring(0, hedgingDelayString.length - 1)); - this.hedgingTimer = setTimeout(() => { - this.maybeStartHedgingAttempt(); - }, hedgingDelaySec * 1000); - (_c = (_b = this.hedgingTimer).unref) === null || _c === void 0 ? void 0 : _c.call(_b); - } - startNewAttempt() { - const child = this.channel.createLoadBalancingCall(this.callConfig, this.methodName, this.host, this.credentials, this.deadline); - this.trace('Created child call [' + - child.getCallNumber() + - '] for attempt ' + - this.attempts); - const index = this.underlyingCalls.length; - this.underlyingCalls.push({ - state: 'ACTIVE', - call: child, - nextMessageToSend: 0, - startTime: new Date(), - }); - const previousAttempts = this.attempts - 1; - const initialMetadata = this.initialMetadata.clone(); - if (previousAttempts > 0) { - initialMetadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); - } - let receivedMetadata = false; - child.start(initialMetadata, { - onReceiveMetadata: metadata => { - this.trace('Received metadata from child [' + child.getCallNumber() + ']'); - this.commitCall(index); - receivedMetadata = true; - if (previousAttempts > 0) { - metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); - } - if (this.underlyingCalls[index].state === 'ACTIVE') { - this.listener.onReceiveMetadata(metadata); - } - }, - onReceiveMessage: message => { - this.trace('Received message from child [' + child.getCallNumber() + ']'); - this.commitCall(index); - if (this.underlyingCalls[index].state === 'ACTIVE') { - this.listener.onReceiveMessage(message); - } - }, - onReceiveStatus: status => { - this.trace('Received status from child [' + child.getCallNumber() + ']'); - if (!receivedMetadata && previousAttempts > 0) { - status.metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); - } - this.handleChildStatus(status, index); - }, - }); - this.sendNextChildMessage(index); - if (this.readStarted) { - child.startRead(); - } - } - start(metadata, listener) { - this.trace('start called'); - this.listener = listener; - this.initialMetadata = metadata; - this.attempts += 1; - this.startNewAttempt(); - this.maybeStartHedgingTimer(); - } - handleChildWriteCompleted(childIndex) { - var _a, _b; - const childCall = this.underlyingCalls[childIndex]; - const messageIndex = childCall.nextMessageToSend; - (_b = (_a = this.getBufferEntry(messageIndex)).callback) === null || _b === void 0 ? void 0 : _b.call(_a); - this.clearSentMessages(); - childCall.nextMessageToSend += 1; - this.sendNextChildMessage(childIndex); - } - sendNextChildMessage(childIndex) { - const childCall = this.underlyingCalls[childIndex]; - if (childCall.state === 'COMPLETED') { - return; - } - if (this.getBufferEntry(childCall.nextMessageToSend)) { - const bufferEntry = this.getBufferEntry(childCall.nextMessageToSend); - switch (bufferEntry.entryType) { - case 'MESSAGE': - childCall.call.sendMessageWithContext({ - callback: error => { - // Ignore error - this.handleChildWriteCompleted(childIndex); - }, - }, bufferEntry.message.message); - break; - case 'HALF_CLOSE': - childCall.nextMessageToSend += 1; - childCall.call.halfClose(); - break; - case 'FREED': - // Should not be possible - break; - } - } - } - sendMessageWithContext(context, message) { - var _a; - this.trace('write() called with message of length ' + message.length); - const writeObj = { - message, - flags: context.flags, - }; - const messageIndex = this.getNextBufferIndex(); - const bufferEntry = { - entryType: 'MESSAGE', - message: writeObj, - allocated: this.bufferTracker.allocate(message.length, this.callNumber), - }; - this.writeBuffer.push(bufferEntry); - if (bufferEntry.allocated) { - (_a = context.callback) === null || _a === void 0 ? void 0 : _a.call(context); - for (const [callIndex, call] of this.underlyingCalls.entries()) { - if (call.state === 'ACTIVE' && - call.nextMessageToSend === messageIndex) { - call.call.sendMessageWithContext({ - callback: error => { - // Ignore error - this.handleChildWriteCompleted(callIndex); - }, - }, message); - } - } - } - else { - this.commitCallWithMostMessages(); - // commitCallWithMostMessages can fail if we are between ping attempts - if (this.committedCallIndex === null) { - return; - } - const call = this.underlyingCalls[this.committedCallIndex]; - bufferEntry.callback = context.callback; - if (call.state === 'ACTIVE' && call.nextMessageToSend === messageIndex) { - call.call.sendMessageWithContext({ - callback: error => { - // Ignore error - this.handleChildWriteCompleted(this.committedCallIndex); - }, - }, message); - } - } - } - startRead() { - this.trace('startRead called'); - this.readStarted = true; - for (const underlyingCall of this.underlyingCalls) { - if ((underlyingCall === null || underlyingCall === void 0 ? void 0 : underlyingCall.state) === 'ACTIVE') { - underlyingCall.call.startRead(); - } - } - } - halfClose() { - this.trace('halfClose called'); - const halfCloseIndex = this.getNextBufferIndex(); - this.writeBuffer.push({ - entryType: 'HALF_CLOSE', - allocated: false, - }); - for (const call of this.underlyingCalls) { - if ((call === null || call === void 0 ? void 0 : call.state) === 'ACTIVE' && - call.nextMessageToSend === halfCloseIndex) { - call.nextMessageToSend += 1; - call.call.halfClose(); - } - } - } - setCredentials(newCredentials) { - throw new Error('Method not implemented.'); - } - getMethod() { - return this.methodName; - } - getHost() { - return this.host; - } - getAuthContext() { - if (this.committedCallIndex !== null) { - return this.underlyingCalls[this.committedCallIndex].call.getAuthContext(); - } - else { - return null; - } - } -} -exports.RetryingCall = RetryingCall; -//# sourceMappingURL=retrying-call.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/server-call.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/server-call.js deleted file mode 100644 index 521f4d37..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/server-call.js +++ /dev/null @@ -1,226 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ServerDuplexStreamImpl = exports.ServerWritableStreamImpl = exports.ServerReadableStreamImpl = exports.ServerUnaryCallImpl = void 0; -exports.serverErrorToStatus = serverErrorToStatus; -const events_1 = require("events"); -const stream_1 = require("stream"); -const constants_1 = require("./constants"); -const metadata_1 = require("./metadata"); -function serverErrorToStatus(error, overrideTrailers) { - var _a; - const status = { - code: constants_1.Status.UNKNOWN, - details: 'message' in error ? error.message : 'Unknown Error', - metadata: (_a = overrideTrailers !== null && overrideTrailers !== void 0 ? overrideTrailers : error.metadata) !== null && _a !== void 0 ? _a : null, - }; - if ('code' in error && - typeof error.code === 'number' && - Number.isInteger(error.code)) { - status.code = error.code; - if ('details' in error && typeof error.details === 'string') { - status.details = error.details; - } - } - return status; -} -class ServerUnaryCallImpl extends events_1.EventEmitter { - constructor(path, call, metadata, request) { - super(); - this.path = path; - this.call = call; - this.metadata = metadata; - this.request = request; - this.cancelled = false; - } - getPeer() { - return this.call.getPeer(); - } - sendMetadata(responseMetadata) { - this.call.sendMetadata(responseMetadata); - } - getDeadline() { - return this.call.getDeadline(); - } - getPath() { - return this.path; - } - getHost() { - return this.call.getHost(); - } - getAuthContext() { - return this.call.getAuthContext(); - } - getMetricsRecorder() { - return this.call.getMetricsRecorder(); - } -} -exports.ServerUnaryCallImpl = ServerUnaryCallImpl; -class ServerReadableStreamImpl extends stream_1.Readable { - constructor(path, call, metadata) { - super({ objectMode: true }); - this.path = path; - this.call = call; - this.metadata = metadata; - this.cancelled = false; - } - _read(size) { - this.call.startRead(); - } - getPeer() { - return this.call.getPeer(); - } - sendMetadata(responseMetadata) { - this.call.sendMetadata(responseMetadata); - } - getDeadline() { - return this.call.getDeadline(); - } - getPath() { - return this.path; - } - getHost() { - return this.call.getHost(); - } - getAuthContext() { - return this.call.getAuthContext(); - } - getMetricsRecorder() { - return this.call.getMetricsRecorder(); - } -} -exports.ServerReadableStreamImpl = ServerReadableStreamImpl; -class ServerWritableStreamImpl extends stream_1.Writable { - constructor(path, call, metadata, request) { - super({ objectMode: true }); - this.path = path; - this.call = call; - this.metadata = metadata; - this.request = request; - this.pendingStatus = { - code: constants_1.Status.OK, - details: 'OK', - }; - this.cancelled = false; - this.trailingMetadata = new metadata_1.Metadata(); - this.on('error', err => { - this.pendingStatus = serverErrorToStatus(err); - this.end(); - }); - } - getPeer() { - return this.call.getPeer(); - } - sendMetadata(responseMetadata) { - this.call.sendMetadata(responseMetadata); - } - getDeadline() { - return this.call.getDeadline(); - } - getPath() { - return this.path; - } - getHost() { - return this.call.getHost(); - } - getAuthContext() { - return this.call.getAuthContext(); - } - getMetricsRecorder() { - return this.call.getMetricsRecorder(); - } - _write(chunk, encoding, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - callback) { - this.call.sendMessage(chunk, callback); - } - _final(callback) { - var _a; - callback(null); - this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a = this.pendingStatus.metadata) !== null && _a !== void 0 ? _a : this.trailingMetadata })); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - end(metadata) { - if (metadata) { - this.trailingMetadata = metadata; - } - return super.end(); - } -} -exports.ServerWritableStreamImpl = ServerWritableStreamImpl; -class ServerDuplexStreamImpl extends stream_1.Duplex { - constructor(path, call, metadata) { - super({ objectMode: true }); - this.path = path; - this.call = call; - this.metadata = metadata; - this.pendingStatus = { - code: constants_1.Status.OK, - details: 'OK', - }; - this.cancelled = false; - this.trailingMetadata = new metadata_1.Metadata(); - this.on('error', err => { - this.pendingStatus = serverErrorToStatus(err); - this.end(); - }); - } - getPeer() { - return this.call.getPeer(); - } - sendMetadata(responseMetadata) { - this.call.sendMetadata(responseMetadata); - } - getDeadline() { - return this.call.getDeadline(); - } - getPath() { - return this.path; - } - getHost() { - return this.call.getHost(); - } - getAuthContext() { - return this.call.getAuthContext(); - } - getMetricsRecorder() { - return this.call.getMetricsRecorder(); - } - _read(size) { - this.call.startRead(); - } - _write(chunk, encoding, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - callback) { - this.call.sendMessage(chunk, callback); - } - _final(callback) { - var _a; - callback(null); - this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a = this.pendingStatus.metadata) !== null && _a !== void 0 ? _a : this.trailingMetadata })); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - end(metadata) { - if (metadata) { - this.trailingMetadata = metadata; - } - return super.end(); - } -} -exports.ServerDuplexStreamImpl = ServerDuplexStreamImpl; -//# sourceMappingURL=server-call.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/server-credentials.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/server-credentials.js deleted file mode 100644 index f8800f8d..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/server-credentials.js +++ /dev/null @@ -1,314 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ServerCredentials = void 0; -exports.createCertificateProviderServerCredentials = createCertificateProviderServerCredentials; -exports.createServerCredentialsWithInterceptors = createServerCredentialsWithInterceptors; -const tls_helpers_1 = require("./tls-helpers"); -class ServerCredentials { - constructor(serverConstructorOptions, contextOptions) { - this.serverConstructorOptions = serverConstructorOptions; - this.watchers = new Set(); - this.latestContextOptions = null; - this.latestContextOptions = contextOptions !== null && contextOptions !== void 0 ? contextOptions : null; - } - _addWatcher(watcher) { - this.watchers.add(watcher); - } - _removeWatcher(watcher) { - this.watchers.delete(watcher); - } - getWatcherCount() { - return this.watchers.size; - } - updateSecureContextOptions(options) { - this.latestContextOptions = options; - for (const watcher of this.watchers) { - watcher(this.latestContextOptions); - } - } - _isSecure() { - return this.serverConstructorOptions !== null; - } - _getSecureContextOptions() { - return this.latestContextOptions; - } - _getConstructorOptions() { - return this.serverConstructorOptions; - } - _getInterceptors() { - return []; - } - static createInsecure() { - return new InsecureServerCredentials(); - } - static createSsl(rootCerts, keyCertPairs, checkClientCertificate = false) { - var _a; - if (rootCerts !== null && !Buffer.isBuffer(rootCerts)) { - throw new TypeError('rootCerts must be null or a Buffer'); - } - if (!Array.isArray(keyCertPairs)) { - throw new TypeError('keyCertPairs must be an array'); - } - if (typeof checkClientCertificate !== 'boolean') { - throw new TypeError('checkClientCertificate must be a boolean'); - } - const cert = []; - const key = []; - for (let i = 0; i < keyCertPairs.length; i++) { - const pair = keyCertPairs[i]; - if (pair === null || typeof pair !== 'object') { - throw new TypeError(`keyCertPair[${i}] must be an object`); - } - if (!Buffer.isBuffer(pair.private_key)) { - throw new TypeError(`keyCertPair[${i}].private_key must be a Buffer`); - } - if (!Buffer.isBuffer(pair.cert_chain)) { - throw new TypeError(`keyCertPair[${i}].cert_chain must be a Buffer`); - } - cert.push(pair.cert_chain); - key.push(pair.private_key); - } - return new SecureServerCredentials({ - requestCert: checkClientCertificate, - ciphers: tls_helpers_1.CIPHER_SUITES, - }, { - ca: (_a = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a !== void 0 ? _a : undefined, - cert, - key, - }); - } -} -exports.ServerCredentials = ServerCredentials; -class InsecureServerCredentials extends ServerCredentials { - constructor() { - super(null); - } - _getSettings() { - return null; - } - _equals(other) { - return other instanceof InsecureServerCredentials; - } -} -class SecureServerCredentials extends ServerCredentials { - constructor(constructorOptions, contextOptions) { - super(constructorOptions, contextOptions); - this.options = Object.assign(Object.assign({}, constructorOptions), contextOptions); - } - /** - * Checks equality by checking the options that are actually set by - * createSsl. - * @param other - * @returns - */ - _equals(other) { - if (this === other) { - return true; - } - if (!(other instanceof SecureServerCredentials)) { - return false; - } - // options.ca equality check - if (Buffer.isBuffer(this.options.ca) && Buffer.isBuffer(other.options.ca)) { - if (!this.options.ca.equals(other.options.ca)) { - return false; - } - } - else { - if (this.options.ca !== other.options.ca) { - return false; - } - } - // options.cert equality check - if (Array.isArray(this.options.cert) && Array.isArray(other.options.cert)) { - if (this.options.cert.length !== other.options.cert.length) { - return false; - } - for (let i = 0; i < this.options.cert.length; i++) { - const thisCert = this.options.cert[i]; - const otherCert = other.options.cert[i]; - if (Buffer.isBuffer(thisCert) && Buffer.isBuffer(otherCert)) { - if (!thisCert.equals(otherCert)) { - return false; - } - } - else { - if (thisCert !== otherCert) { - return false; - } - } - } - } - else { - if (this.options.cert !== other.options.cert) { - return false; - } - } - // options.key equality check - if (Array.isArray(this.options.key) && Array.isArray(other.options.key)) { - if (this.options.key.length !== other.options.key.length) { - return false; - } - for (let i = 0; i < this.options.key.length; i++) { - const thisKey = this.options.key[i]; - const otherKey = other.options.key[i]; - if (Buffer.isBuffer(thisKey) && Buffer.isBuffer(otherKey)) { - if (!thisKey.equals(otherKey)) { - return false; - } - } - else { - if (thisKey !== otherKey) { - return false; - } - } - } - } - else { - if (this.options.key !== other.options.key) { - return false; - } - } - // options.requestCert equality check - if (this.options.requestCert !== other.options.requestCert) { - return false; - } - /* ciphers is derived from a value that is constant for the process, so no - * equality check is needed. */ - return true; - } -} -class CertificateProviderServerCredentials extends ServerCredentials { - constructor(identityCertificateProvider, caCertificateProvider, requireClientCertificate) { - super({ - requestCert: caCertificateProvider !== null, - rejectUnauthorized: requireClientCertificate, - ciphers: tls_helpers_1.CIPHER_SUITES - }); - this.identityCertificateProvider = identityCertificateProvider; - this.caCertificateProvider = caCertificateProvider; - this.requireClientCertificate = requireClientCertificate; - this.latestCaUpdate = null; - this.latestIdentityUpdate = null; - this.caCertificateUpdateListener = this.handleCaCertificateUpdate.bind(this); - this.identityCertificateUpdateListener = this.handleIdentityCertitificateUpdate.bind(this); - } - _addWatcher(watcher) { - var _a; - if (this.getWatcherCount() === 0) { - (_a = this.caCertificateProvider) === null || _a === void 0 ? void 0 : _a.addCaCertificateListener(this.caCertificateUpdateListener); - this.identityCertificateProvider.addIdentityCertificateListener(this.identityCertificateUpdateListener); - } - super._addWatcher(watcher); - } - _removeWatcher(watcher) { - var _a; - super._removeWatcher(watcher); - if (this.getWatcherCount() === 0) { - (_a = this.caCertificateProvider) === null || _a === void 0 ? void 0 : _a.removeCaCertificateListener(this.caCertificateUpdateListener); - this.identityCertificateProvider.removeIdentityCertificateListener(this.identityCertificateUpdateListener); - } - } - _equals(other) { - if (this === other) { - return true; - } - if (!(other instanceof CertificateProviderServerCredentials)) { - return false; - } - return (this.caCertificateProvider === other.caCertificateProvider && - this.identityCertificateProvider === other.identityCertificateProvider && - this.requireClientCertificate === other.requireClientCertificate); - } - calculateSecureContextOptions() { - var _a; - if (this.latestIdentityUpdate === null) { - return null; - } - if (this.caCertificateProvider !== null && this.latestCaUpdate === null) { - return null; - } - return { - ca: (_a = this.latestCaUpdate) === null || _a === void 0 ? void 0 : _a.caCertificate, - cert: [this.latestIdentityUpdate.certificate], - key: [this.latestIdentityUpdate.privateKey], - }; - } - finalizeUpdate() { - const secureContextOptions = this.calculateSecureContextOptions(); - this.updateSecureContextOptions(secureContextOptions); - } - handleCaCertificateUpdate(update) { - this.latestCaUpdate = update; - this.finalizeUpdate(); - } - handleIdentityCertitificateUpdate(update) { - this.latestIdentityUpdate = update; - this.finalizeUpdate(); - } -} -function createCertificateProviderServerCredentials(caCertificateProvider, identityCertificateProvider, requireClientCertificate) { - return new CertificateProviderServerCredentials(caCertificateProvider, identityCertificateProvider, requireClientCertificate); -} -class InterceptorServerCredentials extends ServerCredentials { - constructor(childCredentials, interceptors) { - super({}); - this.childCredentials = childCredentials; - this.interceptors = interceptors; - } - _isSecure() { - return this.childCredentials._isSecure(); - } - _equals(other) { - if (!(other instanceof InterceptorServerCredentials)) { - return false; - } - if (!(this.childCredentials._equals(other.childCredentials))) { - return false; - } - if (this.interceptors.length !== other.interceptors.length) { - return false; - } - for (let i = 0; i < this.interceptors.length; i++) { - if (this.interceptors[i] !== other.interceptors[i]) { - return false; - } - } - return true; - } - _getInterceptors() { - return this.interceptors; - } - _addWatcher(watcher) { - this.childCredentials._addWatcher(watcher); - } - _removeWatcher(watcher) { - this.childCredentials._removeWatcher(watcher); - } - _getConstructorOptions() { - return this.childCredentials._getConstructorOptions(); - } - _getSecureContextOptions() { - return this.childCredentials._getSecureContextOptions(); - } -} -function createServerCredentialsWithInterceptors(credentials, interceptors) { - return new InterceptorServerCredentials(credentials, interceptors); -} -//# sourceMappingURL=server-credentials.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/server-interceptors.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/server-interceptors.js deleted file mode 100644 index a1597073..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/server-interceptors.js +++ /dev/null @@ -1,817 +0,0 @@ -"use strict"; -/* - * Copyright 2024 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BaseServerInterceptingCall = exports.ServerInterceptingCall = exports.ResponderBuilder = exports.ServerListenerBuilder = void 0; -exports.isInterceptingServerListener = isInterceptingServerListener; -exports.getServerInterceptingCall = getServerInterceptingCall; -const metadata_1 = require("./metadata"); -const constants_1 = require("./constants"); -const http2 = require("http2"); -const error_1 = require("./error"); -const zlib = require("zlib"); -const stream_decoder_1 = require("./stream-decoder"); -const logging = require("./logging"); -const tls_1 = require("tls"); -const orca_1 = require("./orca"); -const TRACER_NAME = 'server_call'; -function trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); -} -class ServerListenerBuilder { - constructor() { - this.metadata = undefined; - this.message = undefined; - this.halfClose = undefined; - this.cancel = undefined; - } - withOnReceiveMetadata(onReceiveMetadata) { - this.metadata = onReceiveMetadata; - return this; - } - withOnReceiveMessage(onReceiveMessage) { - this.message = onReceiveMessage; - return this; - } - withOnReceiveHalfClose(onReceiveHalfClose) { - this.halfClose = onReceiveHalfClose; - return this; - } - withOnCancel(onCancel) { - this.cancel = onCancel; - return this; - } - build() { - return { - onReceiveMetadata: this.metadata, - onReceiveMessage: this.message, - onReceiveHalfClose: this.halfClose, - onCancel: this.cancel, - }; - } -} -exports.ServerListenerBuilder = ServerListenerBuilder; -function isInterceptingServerListener(listener) { - return (listener.onReceiveMetadata !== undefined && - listener.onReceiveMetadata.length === 1); -} -class InterceptingServerListenerImpl { - constructor(listener, nextListener) { - this.listener = listener; - this.nextListener = nextListener; - /** - * Once the call is cancelled, ignore all other events. - */ - this.cancelled = false; - this.processingMetadata = false; - this.hasPendingMessage = false; - this.pendingMessage = null; - this.processingMessage = false; - this.hasPendingHalfClose = false; - } - processPendingMessage() { - if (this.hasPendingMessage) { - this.nextListener.onReceiveMessage(this.pendingMessage); - this.pendingMessage = null; - this.hasPendingMessage = false; - } - } - processPendingHalfClose() { - if (this.hasPendingHalfClose) { - this.nextListener.onReceiveHalfClose(); - this.hasPendingHalfClose = false; - } - } - onReceiveMetadata(metadata) { - if (this.cancelled) { - return; - } - this.processingMetadata = true; - this.listener.onReceiveMetadata(metadata, interceptedMetadata => { - this.processingMetadata = false; - if (this.cancelled) { - return; - } - this.nextListener.onReceiveMetadata(interceptedMetadata); - this.processPendingMessage(); - this.processPendingHalfClose(); - }); - } - onReceiveMessage(message) { - if (this.cancelled) { - return; - } - this.processingMessage = true; - this.listener.onReceiveMessage(message, msg => { - this.processingMessage = false; - if (this.cancelled) { - return; - } - if (this.processingMetadata) { - this.pendingMessage = msg; - this.hasPendingMessage = true; - } - else { - this.nextListener.onReceiveMessage(msg); - this.processPendingHalfClose(); - } - }); - } - onReceiveHalfClose() { - if (this.cancelled) { - return; - } - this.listener.onReceiveHalfClose(() => { - if (this.cancelled) { - return; - } - if (this.processingMetadata || this.processingMessage) { - this.hasPendingHalfClose = true; - } - else { - this.nextListener.onReceiveHalfClose(); - } - }); - } - onCancel() { - this.cancelled = true; - this.listener.onCancel(); - this.nextListener.onCancel(); - } -} -class ResponderBuilder { - constructor() { - this.start = undefined; - this.metadata = undefined; - this.message = undefined; - this.status = undefined; - } - withStart(start) { - this.start = start; - return this; - } - withSendMetadata(sendMetadata) { - this.metadata = sendMetadata; - return this; - } - withSendMessage(sendMessage) { - this.message = sendMessage; - return this; - } - withSendStatus(sendStatus) { - this.status = sendStatus; - return this; - } - build() { - return { - start: this.start, - sendMetadata: this.metadata, - sendMessage: this.message, - sendStatus: this.status, - }; - } -} -exports.ResponderBuilder = ResponderBuilder; -const defaultServerListener = { - onReceiveMetadata: (metadata, next) => { - next(metadata); - }, - onReceiveMessage: (message, next) => { - next(message); - }, - onReceiveHalfClose: next => { - next(); - }, - onCancel: () => { }, -}; -const defaultResponder = { - start: next => { - next(); - }, - sendMetadata: (metadata, next) => { - next(metadata); - }, - sendMessage: (message, next) => { - next(message); - }, - sendStatus: (status, next) => { - next(status); - }, -}; -class ServerInterceptingCall { - constructor(nextCall, responder) { - var _a, _b, _c, _d; - this.nextCall = nextCall; - this.processingMetadata = false; - this.sentMetadata = false; - this.processingMessage = false; - this.pendingMessage = null; - this.pendingMessageCallback = null; - this.pendingStatus = null; - this.responder = { - start: (_a = responder === null || responder === void 0 ? void 0 : responder.start) !== null && _a !== void 0 ? _a : defaultResponder.start, - sendMetadata: (_b = responder === null || responder === void 0 ? void 0 : responder.sendMetadata) !== null && _b !== void 0 ? _b : defaultResponder.sendMetadata, - sendMessage: (_c = responder === null || responder === void 0 ? void 0 : responder.sendMessage) !== null && _c !== void 0 ? _c : defaultResponder.sendMessage, - sendStatus: (_d = responder === null || responder === void 0 ? void 0 : responder.sendStatus) !== null && _d !== void 0 ? _d : defaultResponder.sendStatus, - }; - } - processPendingMessage() { - if (this.pendingMessageCallback) { - this.nextCall.sendMessage(this.pendingMessage, this.pendingMessageCallback); - this.pendingMessage = null; - this.pendingMessageCallback = null; - } - } - processPendingStatus() { - if (this.pendingStatus) { - this.nextCall.sendStatus(this.pendingStatus); - this.pendingStatus = null; - } - } - start(listener) { - this.responder.start(interceptedListener => { - var _a, _b, _c, _d; - const fullInterceptedListener = { - onReceiveMetadata: (_a = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveMetadata) !== null && _a !== void 0 ? _a : defaultServerListener.onReceiveMetadata, - onReceiveMessage: (_b = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveMessage) !== null && _b !== void 0 ? _b : defaultServerListener.onReceiveMessage, - onReceiveHalfClose: (_c = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveHalfClose) !== null && _c !== void 0 ? _c : defaultServerListener.onReceiveHalfClose, - onCancel: (_d = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onCancel) !== null && _d !== void 0 ? _d : defaultServerListener.onCancel, - }; - const finalInterceptingListener = new InterceptingServerListenerImpl(fullInterceptedListener, listener); - this.nextCall.start(finalInterceptingListener); - }); - } - sendMetadata(metadata) { - this.processingMetadata = true; - this.sentMetadata = true; - this.responder.sendMetadata(metadata, interceptedMetadata => { - this.processingMetadata = false; - this.nextCall.sendMetadata(interceptedMetadata); - this.processPendingMessage(); - this.processPendingStatus(); - }); - } - sendMessage(message, callback) { - this.processingMessage = true; - if (!this.sentMetadata) { - this.sendMetadata(new metadata_1.Metadata()); - } - this.responder.sendMessage(message, interceptedMessage => { - this.processingMessage = false; - if (this.processingMetadata) { - this.pendingMessage = interceptedMessage; - this.pendingMessageCallback = callback; - } - else { - this.nextCall.sendMessage(interceptedMessage, callback); - } - }); - } - sendStatus(status) { - this.responder.sendStatus(status, interceptedStatus => { - if (this.processingMetadata || this.processingMessage) { - this.pendingStatus = interceptedStatus; - } - else { - this.nextCall.sendStatus(interceptedStatus); - } - }); - } - startRead() { - this.nextCall.startRead(); - } - getPeer() { - return this.nextCall.getPeer(); - } - getDeadline() { - return this.nextCall.getDeadline(); - } - getHost() { - return this.nextCall.getHost(); - } - getAuthContext() { - return this.nextCall.getAuthContext(); - } - getConnectionInfo() { - return this.nextCall.getConnectionInfo(); - } - getMetricsRecorder() { - return this.nextCall.getMetricsRecorder(); - } -} -exports.ServerInterceptingCall = ServerInterceptingCall; -const GRPC_ACCEPT_ENCODING_HEADER = 'grpc-accept-encoding'; -const GRPC_ENCODING_HEADER = 'grpc-encoding'; -const GRPC_MESSAGE_HEADER = 'grpc-message'; -const GRPC_STATUS_HEADER = 'grpc-status'; -const GRPC_TIMEOUT_HEADER = 'grpc-timeout'; -const DEADLINE_REGEX = /(\d{1,8})\s*([HMSmun])/; -const deadlineUnitsToMs = { - H: 3600000, - M: 60000, - S: 1000, - m: 1, - u: 0.001, - n: 0.000001, -}; -const defaultCompressionHeaders = { - // TODO(cjihrig): Remove these encoding headers from the default response - // once compression is integrated. - [GRPC_ACCEPT_ENCODING_HEADER]: 'identity,deflate,gzip', - [GRPC_ENCODING_HEADER]: 'identity', -}; -const defaultResponseHeaders = { - [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, - [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: 'application/grpc+proto', -}; -const defaultResponseOptions = { - waitForTrailers: true, -}; -class BaseServerInterceptingCall { - constructor(stream, headers, callEventTracker, handler, options) { - var _a, _b; - this.stream = stream; - this.callEventTracker = callEventTracker; - this.handler = handler; - this.listener = null; - this.deadlineTimer = null; - this.deadline = Infinity; - this.maxSendMessageSize = constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH; - this.maxReceiveMessageSize = constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; - this.cancelled = false; - this.metadataSent = false; - this.wantTrailers = false; - this.cancelNotified = false; - this.incomingEncoding = 'identity'; - this.readQueue = []; - this.isReadPending = false; - this.receivedHalfClose = false; - this.streamEnded = false; - this.metricsRecorder = new orca_1.PerRequestMetricRecorder(); - this.stream.once('error', (err) => { - /* We need an error handler to avoid uncaught error event exceptions, but - * there is nothing we can reasonably do here. Any error event should - * have a corresponding close event, which handles emitting the cancelled - * event. And the stream is now in a bad state, so we can't reasonably - * expect to be able to send an error over it. */ - }); - this.stream.once('close', () => { - var _a; - trace('Request to method ' + - ((_a = this.handler) === null || _a === void 0 ? void 0 : _a.path) + - ' stream closed with rstCode ' + - this.stream.rstCode); - if (this.callEventTracker && !this.streamEnded) { - this.streamEnded = true; - this.callEventTracker.onStreamEnd(false); - this.callEventTracker.onCallEnd({ - code: constants_1.Status.CANCELLED, - details: 'Stream closed before sending status', - metadata: null, - }); - } - this.notifyOnCancel(); - }); - this.stream.on('data', (data) => { - this.handleDataFrame(data); - }); - this.stream.pause(); - this.stream.on('end', () => { - this.handleEndEvent(); - }); - if ('grpc.max_send_message_length' in options) { - this.maxSendMessageSize = options['grpc.max_send_message_length']; - } - if ('grpc.max_receive_message_length' in options) { - this.maxReceiveMessageSize = options['grpc.max_receive_message_length']; - } - this.host = (_a = headers[':authority']) !== null && _a !== void 0 ? _a : headers.host; - this.decoder = new stream_decoder_1.StreamDecoder(this.maxReceiveMessageSize); - const metadata = metadata_1.Metadata.fromHttp2Headers(headers); - if (logging.isTracerEnabled(TRACER_NAME)) { - trace('Request to ' + - this.handler.path + - ' received headers ' + - JSON.stringify(metadata.toJSON())); - } - const timeoutHeader = metadata.get(GRPC_TIMEOUT_HEADER); - if (timeoutHeader.length > 0) { - this.handleTimeoutHeader(timeoutHeader[0]); - } - const encodingHeader = metadata.get(GRPC_ENCODING_HEADER); - if (encodingHeader.length > 0) { - this.incomingEncoding = encodingHeader[0]; - } - // Remove several headers that should not be propagated to the application - metadata.remove(GRPC_TIMEOUT_HEADER); - metadata.remove(GRPC_ENCODING_HEADER); - metadata.remove(GRPC_ACCEPT_ENCODING_HEADER); - metadata.remove(http2.constants.HTTP2_HEADER_ACCEPT_ENCODING); - metadata.remove(http2.constants.HTTP2_HEADER_TE); - metadata.remove(http2.constants.HTTP2_HEADER_CONTENT_TYPE); - this.metadata = metadata; - const socket = (_b = stream.session) === null || _b === void 0 ? void 0 : _b.socket; - this.connectionInfo = { - localAddress: socket === null || socket === void 0 ? void 0 : socket.localAddress, - localPort: socket === null || socket === void 0 ? void 0 : socket.localPort, - remoteAddress: socket === null || socket === void 0 ? void 0 : socket.remoteAddress, - remotePort: socket === null || socket === void 0 ? void 0 : socket.remotePort - }; - this.shouldSendMetrics = !!options['grpc.server_call_metric_recording']; - } - handleTimeoutHeader(timeoutHeader) { - const match = timeoutHeader.toString().match(DEADLINE_REGEX); - if (match === null) { - const status = { - code: constants_1.Status.INTERNAL, - details: `Invalid ${GRPC_TIMEOUT_HEADER} value "${timeoutHeader}"`, - metadata: null, - }; - // Wait for the constructor to complete before sending the error. - process.nextTick(() => { - this.sendStatus(status); - }); - return; - } - const timeout = (+match[1] * deadlineUnitsToMs[match[2]]) | 0; - const now = new Date(); - this.deadline = now.setMilliseconds(now.getMilliseconds() + timeout); - this.deadlineTimer = setTimeout(() => { - const status = { - code: constants_1.Status.DEADLINE_EXCEEDED, - details: 'Deadline exceeded', - metadata: null, - }; - this.sendStatus(status); - }, timeout); - } - checkCancelled() { - /* In some cases the stream can become destroyed before the close event - * fires. That creates a race condition that this check works around */ - if (!this.cancelled && (this.stream.destroyed || this.stream.closed)) { - this.notifyOnCancel(); - this.cancelled = true; - } - return this.cancelled; - } - notifyOnCancel() { - if (this.cancelNotified) { - return; - } - this.cancelNotified = true; - this.cancelled = true; - process.nextTick(() => { - var _a; - (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onCancel(); - }); - if (this.deadlineTimer) { - clearTimeout(this.deadlineTimer); - } - // Flush incoming data frames - this.stream.resume(); - } - /** - * A server handler can start sending messages without explicitly sending - * metadata. In that case, we need to send headers before sending any - * messages. This function does that if necessary. - */ - maybeSendMetadata() { - if (!this.metadataSent) { - this.sendMetadata(new metadata_1.Metadata()); - } - } - /** - * Serialize a message to a length-delimited byte string. - * @param value - * @returns - */ - serializeMessage(value) { - const messageBuffer = this.handler.serialize(value); - const byteLength = messageBuffer.byteLength; - const output = Buffer.allocUnsafe(byteLength + 5); - /* Note: response compression is currently not supported, so this - * compressed bit is always 0. */ - output.writeUInt8(0, 0); - output.writeUInt32BE(byteLength, 1); - messageBuffer.copy(output, 5); - return output; - } - decompressMessage(message, encoding) { - const messageContents = message.subarray(5); - if (encoding === 'identity') { - return messageContents; - } - else if (encoding === 'deflate' || encoding === 'gzip') { - let decompresser; - if (encoding === 'deflate') { - decompresser = zlib.createInflate(); - } - else { - decompresser = zlib.createGunzip(); - } - return new Promise((resolve, reject) => { - let totalLength = 0; - const messageParts = []; - decompresser.on('data', (chunk) => { - messageParts.push(chunk); - totalLength += chunk.byteLength; - if (this.maxReceiveMessageSize !== -1 && totalLength > this.maxReceiveMessageSize) { - decompresser.destroy(); - reject({ - code: constants_1.Status.RESOURCE_EXHAUSTED, - details: `Received message that decompresses to a size larger than ${this.maxReceiveMessageSize}` - }); - } - }); - decompresser.on('end', () => { - resolve(Buffer.concat(messageParts)); - }); - decompresser.write(messageContents); - decompresser.end(); - }); - } - else { - return Promise.reject({ - code: constants_1.Status.UNIMPLEMENTED, - details: `Received message compressed with unsupported encoding "${encoding}"`, - }); - } - } - async decompressAndMaybePush(queueEntry) { - if (queueEntry.type !== 'COMPRESSED') { - throw new Error(`Invalid queue entry type: ${queueEntry.type}`); - } - const compressed = queueEntry.compressedMessage.readUInt8(0) === 1; - const compressedMessageEncoding = compressed - ? this.incomingEncoding - : 'identity'; - let decompressedMessage; - try { - decompressedMessage = await this.decompressMessage(queueEntry.compressedMessage, compressedMessageEncoding); - } - catch (err) { - this.sendStatus(err); - return; - } - try { - queueEntry.parsedMessage = this.handler.deserialize(decompressedMessage); - } - catch (err) { - this.sendStatus({ - code: constants_1.Status.INTERNAL, - details: `Error deserializing request: ${err.message}`, - }); - return; - } - queueEntry.type = 'READABLE'; - this.maybePushNextMessage(); - } - maybePushNextMessage() { - if (this.listener && - this.isReadPending && - this.readQueue.length > 0 && - this.readQueue[0].type !== 'COMPRESSED') { - this.isReadPending = false; - const nextQueueEntry = this.readQueue.shift(); - if (nextQueueEntry.type === 'READABLE') { - this.listener.onReceiveMessage(nextQueueEntry.parsedMessage); - } - else { - // nextQueueEntry.type === 'HALF_CLOSE' - this.listener.onReceiveHalfClose(); - } - } - } - handleDataFrame(data) { - var _a; - if (this.checkCancelled()) { - return; - } - trace('Request to ' + - this.handler.path + - ' received data frame of size ' + - data.length); - let rawMessages; - try { - rawMessages = this.decoder.write(data); - } - catch (e) { - this.sendStatus({ code: constants_1.Status.RESOURCE_EXHAUSTED, details: e.message }); - return; - } - for (const messageBytes of rawMessages) { - this.stream.pause(); - const queueEntry = { - type: 'COMPRESSED', - compressedMessage: messageBytes, - parsedMessage: null, - }; - this.readQueue.push(queueEntry); - this.decompressAndMaybePush(queueEntry); - (_a = this.callEventTracker) === null || _a === void 0 ? void 0 : _a.addMessageReceived(); - } - } - handleEndEvent() { - this.readQueue.push({ - type: 'HALF_CLOSE', - compressedMessage: null, - parsedMessage: null, - }); - this.receivedHalfClose = true; - this.maybePushNextMessage(); - } - start(listener) { - trace('Request to ' + this.handler.path + ' start called'); - if (this.checkCancelled()) { - return; - } - this.listener = listener; - listener.onReceiveMetadata(this.metadata); - } - sendMetadata(metadata) { - if (this.checkCancelled()) { - return; - } - if (this.metadataSent) { - return; - } - this.metadataSent = true; - const custom = metadata ? metadata.toHttp2Headers() : null; - const headers = Object.assign(Object.assign(Object.assign({}, defaultResponseHeaders), defaultCompressionHeaders), custom); - this.stream.respond(headers, defaultResponseOptions); - } - sendMessage(message, callback) { - if (this.checkCancelled()) { - return; - } - let response; - try { - response = this.serializeMessage(message); - } - catch (e) { - this.sendStatus({ - code: constants_1.Status.INTERNAL, - details: `Error serializing response: ${(0, error_1.getErrorMessage)(e)}`, - metadata: null, - }); - return; - } - if (this.maxSendMessageSize !== -1 && - response.length - 5 > this.maxSendMessageSize) { - this.sendStatus({ - code: constants_1.Status.RESOURCE_EXHAUSTED, - details: `Sent message larger than max (${response.length} vs. ${this.maxSendMessageSize})`, - metadata: null, - }); - return; - } - this.maybeSendMetadata(); - trace('Request to ' + - this.handler.path + - ' sent data frame of size ' + - response.length); - this.stream.write(response, error => { - var _a; - if (error) { - this.sendStatus({ - code: constants_1.Status.INTERNAL, - details: `Error writing message: ${(0, error_1.getErrorMessage)(error)}`, - metadata: null, - }); - return; - } - (_a = this.callEventTracker) === null || _a === void 0 ? void 0 : _a.addMessageSent(); - callback(); - }); - } - sendStatus(status) { - var _a, _b, _c; - if (this.checkCancelled()) { - return; - } - trace('Request to method ' + - ((_a = this.handler) === null || _a === void 0 ? void 0 : _a.path) + - ' ended with status code: ' + - constants_1.Status[status.code] + - ' details: ' + - status.details); - const statusMetadata = (_c = (_b = status.metadata) === null || _b === void 0 ? void 0 : _b.clone()) !== null && _c !== void 0 ? _c : new metadata_1.Metadata(); - if (this.shouldSendMetrics) { - statusMetadata.set(orca_1.GRPC_METRICS_HEADER, this.metricsRecorder.serialize()); - } - if (this.metadataSent) { - if (!this.wantTrailers) { - this.wantTrailers = true; - this.stream.once('wantTrailers', () => { - if (this.callEventTracker && !this.streamEnded) { - this.streamEnded = true; - this.callEventTracker.onStreamEnd(true); - this.callEventTracker.onCallEnd(status); - } - const trailersToSend = Object.assign({ [GRPC_STATUS_HEADER]: status.code, [GRPC_MESSAGE_HEADER]: encodeURI(status.details) }, statusMetadata.toHttp2Headers()); - this.stream.sendTrailers(trailersToSend); - this.notifyOnCancel(); - }); - this.stream.end(); - } - else { - this.notifyOnCancel(); - } - } - else { - if (this.callEventTracker && !this.streamEnded) { - this.streamEnded = true; - this.callEventTracker.onStreamEnd(true); - this.callEventTracker.onCallEnd(status); - } - // Trailers-only response - const trailersToSend = Object.assign(Object.assign({ [GRPC_STATUS_HEADER]: status.code, [GRPC_MESSAGE_HEADER]: encodeURI(status.details) }, defaultResponseHeaders), statusMetadata.toHttp2Headers()); - this.stream.respond(trailersToSend, { endStream: true }); - this.notifyOnCancel(); - } - } - startRead() { - trace('Request to ' + this.handler.path + ' startRead called'); - if (this.checkCancelled()) { - return; - } - this.isReadPending = true; - if (this.readQueue.length === 0) { - if (!this.receivedHalfClose) { - this.stream.resume(); - } - } - else { - this.maybePushNextMessage(); - } - } - getPeer() { - var _a; - const socket = (_a = this.stream.session) === null || _a === void 0 ? void 0 : _a.socket; - if (socket === null || socket === void 0 ? void 0 : socket.remoteAddress) { - if (socket.remotePort) { - return `${socket.remoteAddress}:${socket.remotePort}`; - } - else { - return socket.remoteAddress; - } - } - else { - return 'unknown'; - } - } - getDeadline() { - return this.deadline; - } - getHost() { - return this.host; - } - getAuthContext() { - var _a; - if (((_a = this.stream.session) === null || _a === void 0 ? void 0 : _a.socket) instanceof tls_1.TLSSocket) { - const peerCertificate = this.stream.session.socket.getPeerCertificate(); - return { - transportSecurityType: 'ssl', - sslPeerCertificate: peerCertificate.raw ? peerCertificate : undefined - }; - } - else { - return {}; - } - } - getConnectionInfo() { - return this.connectionInfo; - } - getMetricsRecorder() { - return this.metricsRecorder; - } -} -exports.BaseServerInterceptingCall = BaseServerInterceptingCall; -function getServerInterceptingCall(interceptors, stream, headers, callEventTracker, handler, options) { - const methodDefinition = { - path: handler.path, - requestStream: handler.type === 'clientStream' || handler.type === 'bidi', - responseStream: handler.type === 'serverStream' || handler.type === 'bidi', - requestDeserialize: handler.deserialize, - responseSerialize: handler.serialize, - }; - const baseCall = new BaseServerInterceptingCall(stream, headers, callEventTracker, handler, options); - return interceptors.reduce((call, interceptor) => { - return interceptor(methodDefinition, call); - }, baseCall); -} -//# sourceMappingURL=server-interceptors.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/server.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/server.js deleted file mode 100644 index bf302679..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/server.js +++ /dev/null @@ -1,1608 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { - var useValue = arguments.length > 2; - for (var i = 0; i < initializers.length; i++) { - value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); - } - return useValue ? value : void 0; -}; -var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { - function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } - var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; - var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; - var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); - var _, done = false; - for (var i = decorators.length - 1; i >= 0; i--) { - var context = {}; - for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; - for (var p in contextIn.access) context.access[p] = contextIn.access[p]; - context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; - var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); - if (kind === "accessor") { - if (result === void 0) continue; - if (result === null || typeof result !== "object") throw new TypeError("Object expected"); - if (_ = accept(result.get)) descriptor.get = _; - if (_ = accept(result.set)) descriptor.set = _; - if (_ = accept(result.init)) initializers.unshift(_); - } - else if (_ = accept(result)) { - if (kind === "field") initializers.unshift(_); - else descriptor[key] = _; - } - } - if (target) Object.defineProperty(target, contextIn.name, descriptor); - done = true; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Server = void 0; -const http2 = require("http2"); -const util = require("util"); -const constants_1 = require("./constants"); -const server_call_1 = require("./server-call"); -const server_credentials_1 = require("./server-credentials"); -const resolver_1 = require("./resolver"); -const logging = require("./logging"); -const subchannel_address_1 = require("./subchannel-address"); -const uri_parser_1 = require("./uri-parser"); -const channelz_1 = require("./channelz"); -const server_interceptors_1 = require("./server-interceptors"); -const UNLIMITED_CONNECTION_AGE_MS = ~(1 << 31); -const KEEPALIVE_MAX_TIME_MS = ~(1 << 31); -const KEEPALIVE_TIMEOUT_MS = 20000; -const MAX_CONNECTION_IDLE_MS = ~(1 << 31); -const { HTTP2_HEADER_PATH } = http2.constants; -const TRACER_NAME = 'server'; -const kMaxAge = Buffer.from('max_age'); -function serverCallTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, 'server_call', text); -} -function noop() { } -/** - * Decorator to wrap a class method with util.deprecate - * @param message The message to output if the deprecated method is called - * @returns - */ -function deprecate(message) { - return function (target, context) { - return util.deprecate(target, message); - }; -} -function getUnimplementedStatusResponse(methodName) { - return { - code: constants_1.Status.UNIMPLEMENTED, - details: `The server does not implement the method ${methodName}`, - }; -} -function getDefaultHandler(handlerType, methodName) { - const unimplementedStatusResponse = getUnimplementedStatusResponse(methodName); - switch (handlerType) { - case 'unary': - return (call, callback) => { - callback(unimplementedStatusResponse, null); - }; - case 'clientStream': - return (call, callback) => { - callback(unimplementedStatusResponse, null); - }; - case 'serverStream': - return (call) => { - call.emit('error', unimplementedStatusResponse); - }; - case 'bidi': - return (call) => { - call.emit('error', unimplementedStatusResponse); - }; - default: - throw new Error(`Invalid handlerType ${handlerType}`); - } -} -let Server = (() => { - var _a; - let _instanceExtraInitializers = []; - let _start_decorators; - return _a = class Server { - constructor(options) { - var _b, _c, _d, _e, _f, _g; - this.boundPorts = (__runInitializers(this, _instanceExtraInitializers), new Map()); - this.http2Servers = new Map(); - this.sessionIdleTimeouts = new Map(); - this.handlers = new Map(); - this.sessions = new Map(); - /** - * This field only exists to ensure that the start method throws an error if - * it is called twice, as it did previously. - */ - this.started = false; - this.shutdown = false; - this.serverAddressString = 'null'; - // Channelz Info - this.channelzEnabled = true; - this.options = options !== null && options !== void 0 ? options : {}; - if (this.options['grpc.enable_channelz'] === 0) { - this.channelzEnabled = false; - this.channelzTrace = new channelz_1.ChannelzTraceStub(); - this.callTracker = new channelz_1.ChannelzCallTrackerStub(); - this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); - this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); - } - else { - this.channelzTrace = new channelz_1.ChannelzTrace(); - this.callTracker = new channelz_1.ChannelzCallTracker(); - this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTracker(); - this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTracker(); - } - this.channelzRef = (0, channelz_1.registerChannelzServer)('server', () => this.getChannelzInfo(), this.channelzEnabled); - this.channelzTrace.addTrace('CT_INFO', 'Server created'); - this.maxConnectionAgeMs = - (_b = this.options['grpc.max_connection_age_ms']) !== null && _b !== void 0 ? _b : UNLIMITED_CONNECTION_AGE_MS; - this.maxConnectionAgeGraceMs = - (_c = this.options['grpc.max_connection_age_grace_ms']) !== null && _c !== void 0 ? _c : UNLIMITED_CONNECTION_AGE_MS; - this.keepaliveTimeMs = - (_d = this.options['grpc.keepalive_time_ms']) !== null && _d !== void 0 ? _d : KEEPALIVE_MAX_TIME_MS; - this.keepaliveTimeoutMs = - (_e = this.options['grpc.keepalive_timeout_ms']) !== null && _e !== void 0 ? _e : KEEPALIVE_TIMEOUT_MS; - this.sessionIdleTimeout = - (_f = this.options['grpc.max_connection_idle_ms']) !== null && _f !== void 0 ? _f : MAX_CONNECTION_IDLE_MS; - this.commonServerOptions = { - maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER, - }; - if ('grpc-node.max_session_memory' in this.options) { - this.commonServerOptions.maxSessionMemory = - this.options['grpc-node.max_session_memory']; - } - else { - /* By default, set a very large max session memory limit, to effectively - * disable enforcement of the limit. Some testing indicates that Node's - * behavior degrades badly when this limit is reached, so we solve that - * by disabling the check entirely. */ - this.commonServerOptions.maxSessionMemory = Number.MAX_SAFE_INTEGER; - } - if ('grpc.max_concurrent_streams' in this.options) { - this.commonServerOptions.settings = { - maxConcurrentStreams: this.options['grpc.max_concurrent_streams'], - }; - } - this.interceptors = (_g = this.options.interceptors) !== null && _g !== void 0 ? _g : []; - this.trace('Server constructed'); - } - getChannelzInfo() { - return { - trace: this.channelzTrace, - callTracker: this.callTracker, - listenerChildren: this.listenerChildrenTracker.getChildLists(), - sessionChildren: this.sessionChildrenTracker.getChildLists(), - }; - } - getChannelzSessionInfo(session) { - var _b, _c, _d; - const sessionInfo = this.sessions.get(session); - const sessionSocket = session.socket; - const remoteAddress = sessionSocket.remoteAddress - ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.remoteAddress, sessionSocket.remotePort) - : null; - const localAddress = sessionSocket.localAddress - ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.localAddress, sessionSocket.localPort) - : null; - let tlsInfo; - if (session.encrypted) { - const tlsSocket = sessionSocket; - const cipherInfo = tlsSocket.getCipher(); - const certificate = tlsSocket.getCertificate(); - const peerCertificate = tlsSocket.getPeerCertificate(); - tlsInfo = { - cipherSuiteStandardName: (_b = cipherInfo.standardName) !== null && _b !== void 0 ? _b : null, - cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, - localCertificate: certificate && 'raw' in certificate ? certificate.raw : null, - remoteCertificate: peerCertificate && 'raw' in peerCertificate - ? peerCertificate.raw - : null, - }; - } - else { - tlsInfo = null; - } - const socketInfo = { - remoteAddress: remoteAddress, - localAddress: localAddress, - security: tlsInfo, - remoteName: null, - streamsStarted: sessionInfo.streamTracker.callsStarted, - streamsSucceeded: sessionInfo.streamTracker.callsSucceeded, - streamsFailed: sessionInfo.streamTracker.callsFailed, - messagesSent: sessionInfo.messagesSent, - messagesReceived: sessionInfo.messagesReceived, - keepAlivesSent: sessionInfo.keepAlivesSent, - lastLocalStreamCreatedTimestamp: null, - lastRemoteStreamCreatedTimestamp: sessionInfo.streamTracker.lastCallStartedTimestamp, - lastMessageSentTimestamp: sessionInfo.lastMessageSentTimestamp, - lastMessageReceivedTimestamp: sessionInfo.lastMessageReceivedTimestamp, - localFlowControlWindow: (_c = session.state.localWindowSize) !== null && _c !== void 0 ? _c : null, - remoteFlowControlWindow: (_d = session.state.remoteWindowSize) !== null && _d !== void 0 ? _d : null, - }; - return socketInfo; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '(' + this.channelzRef.id + ') ' + text); - } - keepaliveTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, 'keepalive', '(' + this.channelzRef.id + ') ' + text); - } - addProtoService() { - throw new Error('Not implemented. Use addService() instead'); - } - addService(service, implementation) { - if (service === null || - typeof service !== 'object' || - implementation === null || - typeof implementation !== 'object') { - throw new Error('addService() requires two objects as arguments'); - } - const serviceKeys = Object.keys(service); - if (serviceKeys.length === 0) { - throw new Error('Cannot add an empty service to a server'); - } - serviceKeys.forEach(name => { - const attrs = service[name]; - let methodType; - if (attrs.requestStream) { - if (attrs.responseStream) { - methodType = 'bidi'; - } - else { - methodType = 'clientStream'; - } - } - else { - if (attrs.responseStream) { - methodType = 'serverStream'; - } - else { - methodType = 'unary'; - } - } - let implFn = implementation[name]; - let impl; - if (implFn === undefined && typeof attrs.originalName === 'string') { - implFn = implementation[attrs.originalName]; - } - if (implFn !== undefined) { - impl = implFn.bind(implementation); - } - else { - impl = getDefaultHandler(methodType, name); - } - const success = this.register(attrs.path, impl, attrs.responseSerialize, attrs.requestDeserialize, methodType); - if (success === false) { - throw new Error(`Method handler for ${attrs.path} already provided.`); - } - }); - } - removeService(service) { - if (service === null || typeof service !== 'object') { - throw new Error('removeService() requires object as argument'); - } - const serviceKeys = Object.keys(service); - serviceKeys.forEach(name => { - const attrs = service[name]; - this.unregister(attrs.path); - }); - } - bind(port, creds) { - throw new Error('Not implemented. Use bindAsync() instead'); - } - /** - * This API is experimental, so API stability is not guaranteed across minor versions. - * @param boundAddress - * @returns - */ - experimentalRegisterListenerToChannelz(boundAddress) { - return (0, channelz_1.registerChannelzSocket)((0, subchannel_address_1.subchannelAddressToString)(boundAddress), () => { - return { - localAddress: boundAddress, - remoteAddress: null, - security: null, - remoteName: null, - streamsStarted: 0, - streamsSucceeded: 0, - streamsFailed: 0, - messagesSent: 0, - messagesReceived: 0, - keepAlivesSent: 0, - lastLocalStreamCreatedTimestamp: null, - lastRemoteStreamCreatedTimestamp: null, - lastMessageSentTimestamp: null, - lastMessageReceivedTimestamp: null, - localFlowControlWindow: null, - remoteFlowControlWindow: null, - }; - }, this.channelzEnabled); - } - experimentalUnregisterListenerFromChannelz(channelzRef) { - (0, channelz_1.unregisterChannelzRef)(channelzRef); - } - createHttp2Server(credentials) { - let http2Server; - if (credentials._isSecure()) { - const constructorOptions = credentials._getConstructorOptions(); - const contextOptions = credentials._getSecureContextOptions(); - const secureServerOptions = Object.assign(Object.assign(Object.assign(Object.assign({}, this.commonServerOptions), constructorOptions), contextOptions), { enableTrace: this.options['grpc-node.tls_enable_trace'] === 1 }); - let areCredentialsValid = contextOptions !== null; - this.trace('Initial credentials valid: ' + areCredentialsValid); - http2Server = http2.createSecureServer(secureServerOptions); - http2Server.prependListener('connection', (socket) => { - if (!areCredentialsValid) { - this.trace('Dropped connection from ' + JSON.stringify(socket.address()) + ' due to unloaded credentials'); - socket.destroy(); - } - }); - http2Server.on('secureConnection', (socket) => { - /* These errors need to be handled by the user of Http2SecureServer, - * according to https://github.com/nodejs/node/issues/35824 */ - socket.on('error', (e) => { - this.trace('An incoming TLS connection closed with error: ' + e.message); - }); - }); - const credsWatcher = options => { - if (options) { - const secureServer = http2Server; - try { - secureServer.setSecureContext(options); - } - catch (e) { - logging.log(constants_1.LogVerbosity.ERROR, 'Failed to set secure context with error ' + e.message); - options = null; - } - } - areCredentialsValid = options !== null; - this.trace('Post-update credentials valid: ' + areCredentialsValid); - }; - credentials._addWatcher(credsWatcher); - http2Server.on('close', () => { - credentials._removeWatcher(credsWatcher); - }); - } - else { - http2Server = http2.createServer(this.commonServerOptions); - } - http2Server.setTimeout(0, noop); - this._setupHandlers(http2Server, credentials._getInterceptors()); - return http2Server; - } - bindOneAddress(address, boundPortObject) { - this.trace('Attempting to bind ' + (0, subchannel_address_1.subchannelAddressToString)(address)); - const http2Server = this.createHttp2Server(boundPortObject.credentials); - return new Promise((resolve, reject) => { - const onError = (err) => { - this.trace('Failed to bind ' + - (0, subchannel_address_1.subchannelAddressToString)(address) + - ' with error ' + - err.message); - resolve({ - port: 'port' in address ? address.port : 1, - error: err.message, - }); - }; - http2Server.once('error', onError); - http2Server.listen(address, () => { - const boundAddress = http2Server.address(); - let boundSubchannelAddress; - if (typeof boundAddress === 'string') { - boundSubchannelAddress = { - path: boundAddress, - }; - } - else { - boundSubchannelAddress = { - host: boundAddress.address, - port: boundAddress.port, - }; - } - const channelzRef = this.experimentalRegisterListenerToChannelz(boundSubchannelAddress); - this.listenerChildrenTracker.refChild(channelzRef); - this.http2Servers.set(http2Server, { - channelzRef: channelzRef, - sessions: new Set(), - ownsChannelzRef: true - }); - boundPortObject.listeningServers.add(http2Server); - this.trace('Successfully bound ' + - (0, subchannel_address_1.subchannelAddressToString)(boundSubchannelAddress)); - resolve({ - port: 'port' in boundSubchannelAddress ? boundSubchannelAddress.port : 1, - }); - http2Server.removeListener('error', onError); - }); - }); - } - async bindManyPorts(addressList, boundPortObject) { - if (addressList.length === 0) { - return { - count: 0, - port: 0, - errors: [], - }; - } - if ((0, subchannel_address_1.isTcpSubchannelAddress)(addressList[0]) && addressList[0].port === 0) { - /* If binding to port 0, first try to bind the first address, then bind - * the rest of the address list to the specific port that it binds. */ - const firstAddressResult = await this.bindOneAddress(addressList[0], boundPortObject); - if (firstAddressResult.error) { - /* If the first address fails to bind, try the same operation starting - * from the second item in the list. */ - const restAddressResult = await this.bindManyPorts(addressList.slice(1), boundPortObject); - return Object.assign(Object.assign({}, restAddressResult), { errors: [firstAddressResult.error, ...restAddressResult.errors] }); - } - else { - const restAddresses = addressList - .slice(1) - .map(address => (0, subchannel_address_1.isTcpSubchannelAddress)(address) - ? { host: address.host, port: firstAddressResult.port } - : address); - const restAddressResult = await Promise.all(restAddresses.map(address => this.bindOneAddress(address, boundPortObject))); - const allResults = [firstAddressResult, ...restAddressResult]; - return { - count: allResults.filter(result => result.error === undefined).length, - port: firstAddressResult.port, - errors: allResults - .filter(result => result.error) - .map(result => result.error), - }; - } - } - else { - const allResults = await Promise.all(addressList.map(address => this.bindOneAddress(address, boundPortObject))); - return { - count: allResults.filter(result => result.error === undefined).length, - port: allResults[0].port, - errors: allResults - .filter(result => result.error) - .map(result => result.error), - }; - } - } - async bindAddressList(addressList, boundPortObject) { - const bindResult = await this.bindManyPorts(addressList, boundPortObject); - if (bindResult.count > 0) { - if (bindResult.count < addressList.length) { - logging.log(constants_1.LogVerbosity.INFO, `WARNING Only ${bindResult.count} addresses added out of total ${addressList.length} resolved`); - } - return bindResult.port; - } - else { - const errorString = `No address added out of total ${addressList.length} resolved`; - logging.log(constants_1.LogVerbosity.ERROR, errorString); - throw new Error(`${errorString} errors: [${bindResult.errors.join(',')}]`); - } - } - resolvePort(port) { - return new Promise((resolve, reject) => { - let seenResolution = false; - const resolverListener = (endpointList, attributes, serviceConfig, resolutionNote) => { - if (seenResolution) { - return true; - } - seenResolution = true; - if (!endpointList.ok) { - reject(new Error(endpointList.error.details)); - return true; - } - const addressList = [].concat(...endpointList.value.map(endpoint => endpoint.addresses)); - if (addressList.length === 0) { - reject(new Error(`No addresses resolved for port ${port}`)); - return true; - } - resolve(addressList); - return true; - }; - const resolver = (0, resolver_1.createResolver)(port, resolverListener, this.options); - resolver.updateResolution(); - }); - } - async bindPort(port, boundPortObject) { - const addressList = await this.resolvePort(port); - if (boundPortObject.cancelled) { - this.completeUnbind(boundPortObject); - throw new Error('bindAsync operation cancelled by unbind call'); - } - const portNumber = await this.bindAddressList(addressList, boundPortObject); - if (boundPortObject.cancelled) { - this.completeUnbind(boundPortObject); - throw new Error('bindAsync operation cancelled by unbind call'); - } - return portNumber; - } - normalizePort(port) { - const initialPortUri = (0, uri_parser_1.parseUri)(port); - if (initialPortUri === null) { - throw new Error(`Could not parse port "${port}"`); - } - const portUri = (0, resolver_1.mapUriDefaultScheme)(initialPortUri); - if (portUri === null) { - throw new Error(`Could not get a default scheme for port "${port}"`); - } - return portUri; - } - bindAsync(port, creds, callback) { - if (this.shutdown) { - throw new Error('bindAsync called after shutdown'); - } - if (typeof port !== 'string') { - throw new TypeError('port must be a string'); - } - if (creds === null || !(creds instanceof server_credentials_1.ServerCredentials)) { - throw new TypeError('creds must be a ServerCredentials object'); - } - if (typeof callback !== 'function') { - throw new TypeError('callback must be a function'); - } - this.trace('bindAsync port=' + port); - const portUri = this.normalizePort(port); - const deferredCallback = (error, port) => { - process.nextTick(() => callback(error, port)); - }; - /* First, if this port is already bound or that bind operation is in - * progress, use that result. */ - let boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); - if (boundPortObject) { - if (!creds._equals(boundPortObject.credentials)) { - deferredCallback(new Error(`${port} already bound with incompatible credentials`), 0); - return; - } - /* If that operation has previously been cancelled by an unbind call, - * uncancel it. */ - boundPortObject.cancelled = false; - if (boundPortObject.completionPromise) { - boundPortObject.completionPromise.then(portNum => callback(null, portNum), error => callback(error, 0)); - } - else { - deferredCallback(null, boundPortObject.portNumber); - } - return; - } - boundPortObject = { - mapKey: (0, uri_parser_1.uriToString)(portUri), - originalUri: portUri, - completionPromise: null, - cancelled: false, - portNumber: 0, - credentials: creds, - listeningServers: new Set(), - }; - const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); - const completionPromise = this.bindPort(portUri, boundPortObject); - boundPortObject.completionPromise = completionPromise; - /* If the port number is 0, defer populating the map entry until after the - * bind operation completes and we have a specific port number. Otherwise, - * populate it immediately. */ - if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { - completionPromise.then(portNum => { - const finalUri = { - scheme: portUri.scheme, - authority: portUri.authority, - path: (0, uri_parser_1.combineHostPort)({ host: splitPort.host, port: portNum }), - }; - boundPortObject.mapKey = (0, uri_parser_1.uriToString)(finalUri); - boundPortObject.completionPromise = null; - boundPortObject.portNumber = portNum; - this.boundPorts.set(boundPortObject.mapKey, boundPortObject); - callback(null, portNum); - }, error => { - callback(error, 0); - }); - } - else { - this.boundPorts.set(boundPortObject.mapKey, boundPortObject); - completionPromise.then(portNum => { - boundPortObject.completionPromise = null; - boundPortObject.portNumber = portNum; - callback(null, portNum); - }, error => { - callback(error, 0); - }); - } - } - registerInjectorToChannelz() { - return (0, channelz_1.registerChannelzSocket)('injector', () => { - return { - localAddress: null, - remoteAddress: null, - security: null, - remoteName: null, - streamsStarted: 0, - streamsSucceeded: 0, - streamsFailed: 0, - messagesSent: 0, - messagesReceived: 0, - keepAlivesSent: 0, - lastLocalStreamCreatedTimestamp: null, - lastRemoteStreamCreatedTimestamp: null, - lastMessageSentTimestamp: null, - lastMessageReceivedTimestamp: null, - localFlowControlWindow: null, - remoteFlowControlWindow: null, - }; - }, this.channelzEnabled); - } - /** - * This API is experimental, so API stability is not guaranteed across minor versions. - * @param credentials - * @param channelzRef - * @returns - */ - experimentalCreateConnectionInjectorWithChannelzRef(credentials, channelzRef, ownsChannelzRef = false) { - if (credentials === null || !(credentials instanceof server_credentials_1.ServerCredentials)) { - throw new TypeError('creds must be a ServerCredentials object'); - } - if (this.channelzEnabled) { - this.listenerChildrenTracker.refChild(channelzRef); - } - const server = this.createHttp2Server(credentials); - const sessionsSet = new Set(); - this.http2Servers.set(server, { - channelzRef: channelzRef, - sessions: sessionsSet, - ownsChannelzRef - }); - return { - injectConnection: (connection) => { - server.emit('connection', connection); - }, - drain: (graceTimeMs) => { - var _b, _c; - for (const session of sessionsSet) { - this.closeSession(session); - } - (_c = (_b = setTimeout(() => { - for (const session of sessionsSet) { - session.destroy(http2.constants.NGHTTP2_CANCEL); - } - }, graceTimeMs)).unref) === null || _c === void 0 ? void 0 : _c.call(_b); - }, - destroy: () => { - this.closeServer(server); - for (const session of sessionsSet) { - this.closeSession(session); - } - } - }; - } - createConnectionInjector(credentials) { - if (credentials === null || !(credentials instanceof server_credentials_1.ServerCredentials)) { - throw new TypeError('creds must be a ServerCredentials object'); - } - const channelzRef = this.registerInjectorToChannelz(); - return this.experimentalCreateConnectionInjectorWithChannelzRef(credentials, channelzRef, true); - } - closeServer(server, callback) { - this.trace('Closing server with address ' + JSON.stringify(server.address())); - const serverInfo = this.http2Servers.get(server); - server.close(() => { - if (serverInfo && serverInfo.ownsChannelzRef) { - this.listenerChildrenTracker.unrefChild(serverInfo.channelzRef); - (0, channelz_1.unregisterChannelzRef)(serverInfo.channelzRef); - } - this.http2Servers.delete(server); - callback === null || callback === void 0 ? void 0 : callback(); - }); - } - closeSession(session, callback) { - var _b; - this.trace('Closing session initiated by ' + ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress)); - const sessionInfo = this.sessions.get(session); - const closeCallback = () => { - if (sessionInfo) { - this.sessionChildrenTracker.unrefChild(sessionInfo.ref); - (0, channelz_1.unregisterChannelzRef)(sessionInfo.ref); - } - callback === null || callback === void 0 ? void 0 : callback(); - }; - if (session.closed) { - queueMicrotask(closeCallback); - } - else { - session.close(closeCallback); - } - } - completeUnbind(boundPortObject) { - for (const server of boundPortObject.listeningServers) { - const serverInfo = this.http2Servers.get(server); - this.closeServer(server, () => { - boundPortObject.listeningServers.delete(server); - }); - if (serverInfo) { - for (const session of serverInfo.sessions) { - this.closeSession(session); - } - } - } - this.boundPorts.delete(boundPortObject.mapKey); - } - /** - * Unbind a previously bound port, or cancel an in-progress bindAsync - * operation. If port 0 was bound, only the actual bound port can be - * unbound. For example, if bindAsync was called with "localhost:0" and the - * bound port result was 54321, it can be unbound as "localhost:54321". - * @param port - */ - unbind(port) { - this.trace('unbind port=' + port); - const portUri = this.normalizePort(port); - const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); - if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { - throw new Error('Cannot unbind port 0'); - } - const boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); - if (boundPortObject) { - this.trace('unbinding ' + - boundPortObject.mapKey + - ' originally bound as ' + - (0, uri_parser_1.uriToString)(boundPortObject.originalUri)); - /* If the bind operation is pending, the cancelled flag will trigger - * the unbind operation later. */ - if (boundPortObject.completionPromise) { - boundPortObject.cancelled = true; - } - else { - this.completeUnbind(boundPortObject); - } - } - } - /** - * Gracefully close all connections associated with a previously bound port. - * After the grace time, forcefully close all remaining open connections. - * - * If port 0 was bound, only the actual bound port can be - * drained. For example, if bindAsync was called with "localhost:0" and the - * bound port result was 54321, it can be drained as "localhost:54321". - * @param port - * @param graceTimeMs - * @returns - */ - drain(port, graceTimeMs) { - var _b, _c; - this.trace('drain port=' + port + ' graceTimeMs=' + graceTimeMs); - const portUri = this.normalizePort(port); - const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); - if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { - throw new Error('Cannot drain port 0'); - } - const boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); - if (!boundPortObject) { - return; - } - const allSessions = new Set(); - for (const http2Server of boundPortObject.listeningServers) { - const serverEntry = this.http2Servers.get(http2Server); - if (serverEntry) { - for (const session of serverEntry.sessions) { - allSessions.add(session); - this.closeSession(session, () => { - allSessions.delete(session); - }); - } - } - } - /* After the grace time ends, send another goaway to all remaining sessions - * with the CANCEL code. */ - (_c = (_b = setTimeout(() => { - for (const session of allSessions) { - session.destroy(http2.constants.NGHTTP2_CANCEL); - } - }, graceTimeMs)).unref) === null || _c === void 0 ? void 0 : _c.call(_b); - } - forceShutdown() { - for (const boundPortObject of this.boundPorts.values()) { - boundPortObject.cancelled = true; - } - this.boundPorts.clear(); - // Close the server if it is still running. - for (const server of this.http2Servers.keys()) { - this.closeServer(server); - } - // Always destroy any available sessions. It's possible that one or more - // tryShutdown() calls are in progress. Don't wait on them to finish. - this.sessions.forEach((channelzInfo, session) => { - this.closeSession(session); - // Cast NGHTTP2_CANCEL to any because TypeScript doesn't seem to - // recognize destroy(code) as a valid signature. - // eslint-disable-next-line @typescript-eslint/no-explicit-any - session.destroy(http2.constants.NGHTTP2_CANCEL); - }); - this.sessions.clear(); - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - this.shutdown = true; - } - register(name, handler, serialize, deserialize, type) { - if (this.handlers.has(name)) { - return false; - } - this.handlers.set(name, { - func: handler, - serialize, - deserialize, - type, - path: name, - }); - return true; - } - unregister(name) { - return this.handlers.delete(name); - } - /** - * @deprecated No longer needed as of version 1.10.x - */ - start() { - if (this.http2Servers.size === 0 || - [...this.http2Servers.keys()].every(server => !server.listening)) { - throw new Error('server must be bound in order to start'); - } - if (this.started === true) { - throw new Error('server is already started'); - } - this.started = true; - } - tryShutdown(callback) { - var _b; - const wrappedCallback = (error) => { - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - callback(error); - }; - let pendingChecks = 0; - function maybeCallback() { - pendingChecks--; - if (pendingChecks === 0) { - wrappedCallback(); - } - } - this.shutdown = true; - for (const [serverKey, server] of this.http2Servers.entries()) { - pendingChecks++; - const serverString = server.channelzRef.name; - this.trace('Waiting for server ' + serverString + ' to close'); - this.closeServer(serverKey, () => { - this.trace('Server ' + serverString + ' finished closing'); - maybeCallback(); - }); - for (const session of server.sessions.keys()) { - pendingChecks++; - const sessionString = (_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress; - this.trace('Waiting for session ' + sessionString + ' to close'); - this.closeSession(session, () => { - this.trace('Session ' + sessionString + ' finished closing'); - maybeCallback(); - }); - } - } - if (pendingChecks === 0) { - wrappedCallback(); - } - } - addHttp2Port() { - throw new Error('Not yet implemented'); - } - /** - * Get the channelz reference object for this server. The returned value is - * garbage if channelz is disabled for this server. - * @returns - */ - getChannelzRef() { - return this.channelzRef; - } - _verifyContentType(stream, headers) { - const contentType = headers[http2.constants.HTTP2_HEADER_CONTENT_TYPE]; - if (typeof contentType !== 'string' || - !contentType.startsWith('application/grpc')) { - stream.respond({ - [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, - }, { endStream: true }); - return false; - } - return true; - } - _retrieveHandler(path) { - serverCallTrace('Received call to method ' + - path + - ' at address ' + - this.serverAddressString); - const handler = this.handlers.get(path); - if (handler === undefined) { - serverCallTrace('No handler registered for method ' + - path + - '. Sending UNIMPLEMENTED status.'); - return null; - } - return handler; - } - _respondWithError(err, stream, channelzSessionInfo = null) { - var _b, _c; - const trailersToSend = Object.assign({ 'grpc-status': (_b = err.code) !== null && _b !== void 0 ? _b : constants_1.Status.INTERNAL, 'grpc-message': err.details, [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: 'application/grpc+proto' }, (_c = err.metadata) === null || _c === void 0 ? void 0 : _c.toHttp2Headers()); - stream.respond(trailersToSend, { endStream: true }); - this.callTracker.addCallFailed(); - channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); - } - _channelzHandler(extraInterceptors, stream, headers) { - // for handling idle timeout - this.onStreamOpened(stream); - const channelzSessionInfo = this.sessions.get(stream.session); - this.callTracker.addCallStarted(); - channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallStarted(); - if (!this._verifyContentType(stream, headers)) { - this.callTracker.addCallFailed(); - channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); - return; - } - const path = headers[HTTP2_HEADER_PATH]; - const handler = this._retrieveHandler(path); - if (!handler) { - this._respondWithError(getUnimplementedStatusResponse(path), stream, channelzSessionInfo); - return; - } - const callEventTracker = { - addMessageSent: () => { - if (channelzSessionInfo) { - channelzSessionInfo.messagesSent += 1; - channelzSessionInfo.lastMessageSentTimestamp = new Date(); - } - }, - addMessageReceived: () => { - if (channelzSessionInfo) { - channelzSessionInfo.messagesReceived += 1; - channelzSessionInfo.lastMessageReceivedTimestamp = new Date(); - } - }, - onCallEnd: status => { - if (status.code === constants_1.Status.OK) { - this.callTracker.addCallSucceeded(); - } - else { - this.callTracker.addCallFailed(); - } - }, - onStreamEnd: success => { - if (channelzSessionInfo) { - if (success) { - channelzSessionInfo.streamTracker.addCallSucceeded(); - } - else { - channelzSessionInfo.streamTracker.addCallFailed(); - } - } - }, - }; - const call = (0, server_interceptors_1.getServerInterceptingCall)([...extraInterceptors, ...this.interceptors], stream, headers, callEventTracker, handler, this.options); - if (!this._runHandlerForCall(call, handler)) { - this.callTracker.addCallFailed(); - channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); - call.sendStatus({ - code: constants_1.Status.INTERNAL, - details: `Unknown handler type: ${handler.type}`, - }); - } - } - _streamHandler(extraInterceptors, stream, headers) { - // for handling idle timeout - this.onStreamOpened(stream); - if (this._verifyContentType(stream, headers) !== true) { - return; - } - const path = headers[HTTP2_HEADER_PATH]; - const handler = this._retrieveHandler(path); - if (!handler) { - this._respondWithError(getUnimplementedStatusResponse(path), stream, null); - return; - } - const call = (0, server_interceptors_1.getServerInterceptingCall)([...extraInterceptors, ...this.interceptors], stream, headers, null, handler, this.options); - if (!this._runHandlerForCall(call, handler)) { - call.sendStatus({ - code: constants_1.Status.INTERNAL, - details: `Unknown handler type: ${handler.type}`, - }); - } - } - _runHandlerForCall(call, handler) { - const { type } = handler; - if (type === 'unary') { - handleUnary(call, handler); - } - else if (type === 'clientStream') { - handleClientStreaming(call, handler); - } - else if (type === 'serverStream') { - handleServerStreaming(call, handler); - } - else if (type === 'bidi') { - handleBidiStreaming(call, handler); - } - else { - return false; - } - return true; - } - _setupHandlers(http2Server, extraInterceptors) { - if (http2Server === null) { - return; - } - const serverAddress = http2Server.address(); - let serverAddressString = 'null'; - if (serverAddress) { - if (typeof serverAddress === 'string') { - serverAddressString = serverAddress; - } - else { - serverAddressString = serverAddress.address + ':' + serverAddress.port; - } - } - this.serverAddressString = serverAddressString; - const handler = this.channelzEnabled - ? this._channelzHandler - : this._streamHandler; - const sessionHandler = this.channelzEnabled - ? this._channelzSessionHandler(http2Server) - : this._sessionHandler(http2Server); - http2Server.on('stream', handler.bind(this, extraInterceptors)); - http2Server.on('session', sessionHandler); - } - _sessionHandler(http2Server) { - return (session) => { - var _b, _c; - (_b = this.http2Servers.get(http2Server)) === null || _b === void 0 ? void 0 : _b.sessions.add(session); - let connectionAgeTimer = null; - let connectionAgeGraceTimer = null; - let keepaliveTimer = null; - let sessionClosedByServer = false; - const idleTimeoutObj = this.enableIdleTimeout(session); - if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) { - // Apply a random jitter within a +/-10% range - const jitterMagnitude = this.maxConnectionAgeMs / 10; - const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude; - connectionAgeTimer = setTimeout(() => { - var _b, _c; - sessionClosedByServer = true; - this.trace('Connection dropped by max connection age: ' + - ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress)); - try { - session.goaway(http2.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge); - } - catch (e) { - // The goaway can't be sent because the session is already closed - session.destroy(); - return; - } - session.close(); - /* Allow a grace period after sending the GOAWAY before forcibly - * closing the connection. */ - if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) { - connectionAgeGraceTimer = setTimeout(() => { - session.destroy(); - }, this.maxConnectionAgeGraceMs); - (_c = connectionAgeGraceTimer.unref) === null || _c === void 0 ? void 0 : _c.call(connectionAgeGraceTimer); - } - }, this.maxConnectionAgeMs + jitter); - (_c = connectionAgeTimer.unref) === null || _c === void 0 ? void 0 : _c.call(connectionAgeTimer); - } - const clearKeepaliveTimeout = () => { - if (keepaliveTimer) { - clearTimeout(keepaliveTimer); - keepaliveTimer = null; - } - }; - const canSendPing = () => { - return (!session.destroyed && - this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && - this.keepaliveTimeMs > 0); - }; - /* eslint-disable-next-line prefer-const */ - let sendPing; // hoisted for use in maybeStartKeepalivePingTimer - const maybeStartKeepalivePingTimer = () => { - var _b; - if (!canSendPing()) { - return; - } - this.keepaliveTrace('Starting keepalive timer for ' + this.keepaliveTimeMs + 'ms'); - keepaliveTimer = setTimeout(() => { - clearKeepaliveTimeout(); - sendPing(); - }, this.keepaliveTimeMs); - (_b = keepaliveTimer.unref) === null || _b === void 0 ? void 0 : _b.call(keepaliveTimer); - }; - sendPing = () => { - var _b; - if (!canSendPing()) { - return; - } - this.keepaliveTrace('Sending ping with timeout ' + this.keepaliveTimeoutMs + 'ms'); - let pingSendError = ''; - try { - const pingSentSuccessfully = session.ping((err, duration, payload) => { - clearKeepaliveTimeout(); - if (err) { - this.keepaliveTrace('Ping failed with error: ' + err.message); - sessionClosedByServer = true; - session.close(); - } - else { - this.keepaliveTrace('Received ping response'); - maybeStartKeepalivePingTimer(); - } - }); - if (!pingSentSuccessfully) { - pingSendError = 'Ping returned false'; - } - } - catch (e) { - // grpc/grpc-node#2139 - pingSendError = - (e instanceof Error ? e.message : '') || 'Unknown error'; - } - if (pingSendError) { - this.keepaliveTrace('Ping send failed: ' + pingSendError); - this.trace('Connection dropped due to ping send error: ' + pingSendError); - sessionClosedByServer = true; - session.close(); - return; - } - keepaliveTimer = setTimeout(() => { - clearKeepaliveTimeout(); - this.keepaliveTrace('Ping timeout passed without response'); - this.trace('Connection dropped by keepalive timeout'); - sessionClosedByServer = true; - session.close(); - }, this.keepaliveTimeoutMs); - (_b = keepaliveTimer.unref) === null || _b === void 0 ? void 0 : _b.call(keepaliveTimer); - }; - maybeStartKeepalivePingTimer(); - session.on('close', () => { - var _b, _c; - if (!sessionClosedByServer) { - this.trace(`Connection dropped by client ${(_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress}`); - } - if (connectionAgeTimer) { - clearTimeout(connectionAgeTimer); - } - if (connectionAgeGraceTimer) { - clearTimeout(connectionAgeGraceTimer); - } - clearKeepaliveTimeout(); - if (idleTimeoutObj !== null) { - clearTimeout(idleTimeoutObj.timeout); - this.sessionIdleTimeouts.delete(session); - } - (_c = this.http2Servers.get(http2Server)) === null || _c === void 0 ? void 0 : _c.sessions.delete(session); - }); - }; - } - _channelzSessionHandler(http2Server) { - return (session) => { - var _b, _c, _d, _e; - const channelzRef = (0, channelz_1.registerChannelzSocket)((_c = (_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress) !== null && _c !== void 0 ? _c : 'unknown', this.getChannelzSessionInfo.bind(this, session), this.channelzEnabled); - const channelzSessionInfo = { - ref: channelzRef, - streamTracker: new channelz_1.ChannelzCallTracker(), - messagesSent: 0, - messagesReceived: 0, - keepAlivesSent: 0, - lastMessageSentTimestamp: null, - lastMessageReceivedTimestamp: null, - }; - (_d = this.http2Servers.get(http2Server)) === null || _d === void 0 ? void 0 : _d.sessions.add(session); - this.sessions.set(session, channelzSessionInfo); - const clientAddress = `${session.socket.remoteAddress}:${session.socket.remotePort}`; - this.channelzTrace.addTrace('CT_INFO', 'Connection established by client ' + clientAddress); - this.trace('Connection established by client ' + clientAddress); - this.sessionChildrenTracker.refChild(channelzRef); - let connectionAgeTimer = null; - let connectionAgeGraceTimer = null; - let keepaliveTimeout = null; - let sessionClosedByServer = false; - const idleTimeoutObj = this.enableIdleTimeout(session); - if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) { - // Apply a random jitter within a +/-10% range - const jitterMagnitude = this.maxConnectionAgeMs / 10; - const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude; - connectionAgeTimer = setTimeout(() => { - var _b; - sessionClosedByServer = true; - this.channelzTrace.addTrace('CT_INFO', 'Connection dropped by max connection age from ' + clientAddress); - try { - session.goaway(http2.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge); - } - catch (e) { - // The goaway can't be sent because the session is already closed - session.destroy(); - return; - } - session.close(); - /* Allow a grace period after sending the GOAWAY before forcibly - * closing the connection. */ - if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) { - connectionAgeGraceTimer = setTimeout(() => { - session.destroy(); - }, this.maxConnectionAgeGraceMs); - (_b = connectionAgeGraceTimer.unref) === null || _b === void 0 ? void 0 : _b.call(connectionAgeGraceTimer); - } - }, this.maxConnectionAgeMs + jitter); - (_e = connectionAgeTimer.unref) === null || _e === void 0 ? void 0 : _e.call(connectionAgeTimer); - } - const clearKeepaliveTimeout = () => { - if (keepaliveTimeout) { - clearTimeout(keepaliveTimeout); - keepaliveTimeout = null; - } - }; - const canSendPing = () => { - return (!session.destroyed && - this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS && - this.keepaliveTimeMs > 0); - }; - /* eslint-disable-next-line prefer-const */ - let sendPing; // hoisted for use in maybeStartKeepalivePingTimer - const maybeStartKeepalivePingTimer = () => { - var _b; - if (!canSendPing()) { - return; - } - this.keepaliveTrace('Starting keepalive timer for ' + this.keepaliveTimeMs + 'ms'); - keepaliveTimeout = setTimeout(() => { - clearKeepaliveTimeout(); - sendPing(); - }, this.keepaliveTimeMs); - (_b = keepaliveTimeout.unref) === null || _b === void 0 ? void 0 : _b.call(keepaliveTimeout); - }; - sendPing = () => { - var _b; - if (!canSendPing()) { - return; - } - this.keepaliveTrace('Sending ping with timeout ' + this.keepaliveTimeoutMs + 'ms'); - let pingSendError = ''; - try { - const pingSentSuccessfully = session.ping((err, duration, payload) => { - clearKeepaliveTimeout(); - if (err) { - this.keepaliveTrace('Ping failed with error: ' + err.message); - this.channelzTrace.addTrace('CT_INFO', 'Connection dropped due to error of a ping frame ' + - err.message + - ' return in ' + - duration); - sessionClosedByServer = true; - session.close(); - } - else { - this.keepaliveTrace('Received ping response'); - maybeStartKeepalivePingTimer(); - } - }); - if (!pingSentSuccessfully) { - pingSendError = 'Ping returned false'; - } - } - catch (e) { - // grpc/grpc-node#2139 - pingSendError = - (e instanceof Error ? e.message : '') || 'Unknown error'; - } - if (pingSendError) { - this.keepaliveTrace('Ping send failed: ' + pingSendError); - this.channelzTrace.addTrace('CT_INFO', 'Connection dropped due to ping send error: ' + pingSendError); - sessionClosedByServer = true; - session.close(); - return; - } - channelzSessionInfo.keepAlivesSent += 1; - keepaliveTimeout = setTimeout(() => { - clearKeepaliveTimeout(); - this.keepaliveTrace('Ping timeout passed without response'); - this.channelzTrace.addTrace('CT_INFO', 'Connection dropped by keepalive timeout from ' + clientAddress); - sessionClosedByServer = true; - session.close(); - }, this.keepaliveTimeoutMs); - (_b = keepaliveTimeout.unref) === null || _b === void 0 ? void 0 : _b.call(keepaliveTimeout); - }; - maybeStartKeepalivePingTimer(); - session.on('close', () => { - var _b; - if (!sessionClosedByServer) { - this.channelzTrace.addTrace('CT_INFO', 'Connection dropped by client ' + clientAddress); - } - this.sessionChildrenTracker.unrefChild(channelzRef); - (0, channelz_1.unregisterChannelzRef)(channelzRef); - if (connectionAgeTimer) { - clearTimeout(connectionAgeTimer); - } - if (connectionAgeGraceTimer) { - clearTimeout(connectionAgeGraceTimer); - } - clearKeepaliveTimeout(); - if (idleTimeoutObj !== null) { - clearTimeout(idleTimeoutObj.timeout); - this.sessionIdleTimeouts.delete(session); - } - (_b = this.http2Servers.get(http2Server)) === null || _b === void 0 ? void 0 : _b.sessions.delete(session); - this.sessions.delete(session); - }); - }; - } - enableIdleTimeout(session) { - var _b, _c; - if (this.sessionIdleTimeout >= MAX_CONNECTION_IDLE_MS) { - return null; - } - const idleTimeoutObj = { - activeStreams: 0, - lastIdle: Date.now(), - onClose: this.onStreamClose.bind(this, session), - timeout: setTimeout(this.onIdleTimeout, this.sessionIdleTimeout, this, session), - }; - (_c = (_b = idleTimeoutObj.timeout).unref) === null || _c === void 0 ? void 0 : _c.call(_b); - this.sessionIdleTimeouts.set(session, idleTimeoutObj); - const { socket } = session; - this.trace('Enable idle timeout for ' + - socket.remoteAddress + - ':' + - socket.remotePort); - return idleTimeoutObj; - } - onIdleTimeout(ctx, session) { - const { socket } = session; - const sessionInfo = ctx.sessionIdleTimeouts.get(session); - // if it is called while we have activeStreams - timer will not be rescheduled - // until last active stream is closed, then it will call .refresh() on the timer - // important part is to not clearTimeout(timer) or it becomes unusable - // for future refreshes - if (sessionInfo !== undefined && - sessionInfo.activeStreams === 0) { - if (Date.now() - sessionInfo.lastIdle >= ctx.sessionIdleTimeout) { - ctx.trace('Session idle timeout triggered for ' + - (socket === null || socket === void 0 ? void 0 : socket.remoteAddress) + - ':' + - (socket === null || socket === void 0 ? void 0 : socket.remotePort) + - ' last idle at ' + - sessionInfo.lastIdle); - ctx.closeSession(session); - } - else { - sessionInfo.timeout.refresh(); - } - } - } - onStreamOpened(stream) { - const session = stream.session; - const idleTimeoutObj = this.sessionIdleTimeouts.get(session); - if (idleTimeoutObj) { - idleTimeoutObj.activeStreams += 1; - stream.once('close', idleTimeoutObj.onClose); - } - } - onStreamClose(session) { - var _b, _c; - const idleTimeoutObj = this.sessionIdleTimeouts.get(session); - if (idleTimeoutObj) { - idleTimeoutObj.activeStreams -= 1; - if (idleTimeoutObj.activeStreams === 0) { - idleTimeoutObj.lastIdle = Date.now(); - idleTimeoutObj.timeout.refresh(); - this.trace('Session onStreamClose' + - ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress) + - ':' + - ((_c = session.socket) === null || _c === void 0 ? void 0 : _c.remotePort) + - ' at ' + - idleTimeoutObj.lastIdle); - } - } - } - }, - (() => { - const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; - _start_decorators = [deprecate('Calling start() is no longer necessary. It can be safely omitted.')]; - __esDecorate(_a, null, _start_decorators, { kind: "method", name: "start", static: false, private: false, access: { has: obj => "start" in obj, get: obj => obj.start }, metadata: _metadata }, null, _instanceExtraInitializers); - if (_metadata) Object.defineProperty(_a, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); - })(), - _a; -})(); -exports.Server = Server; -async function handleUnary(call, handler) { - let stream; - function respond(err, value, trailer, flags) { - if (err) { - call.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer)); - return; - } - call.sendMessage(value, () => { - call.sendStatus({ - code: constants_1.Status.OK, - details: 'OK', - metadata: trailer !== null && trailer !== void 0 ? trailer : null, - }); - }); - } - let requestMetadata; - let requestMessage = null; - call.start({ - onReceiveMetadata(metadata) { - requestMetadata = metadata; - call.startRead(); - }, - onReceiveMessage(message) { - if (requestMessage) { - call.sendStatus({ - code: constants_1.Status.UNIMPLEMENTED, - details: `Received a second request message for server streaming method ${handler.path}`, - metadata: null, - }); - return; - } - requestMessage = message; - call.startRead(); - }, - onReceiveHalfClose() { - if (!requestMessage) { - call.sendStatus({ - code: constants_1.Status.UNIMPLEMENTED, - details: `Received no request message for server streaming method ${handler.path}`, - metadata: null, - }); - return; - } - stream = new server_call_1.ServerWritableStreamImpl(handler.path, call, requestMetadata, requestMessage); - try { - handler.func(stream, respond); - } - catch (err) { - call.sendStatus({ - code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, - metadata: null, - }); - } - }, - onCancel() { - if (stream) { - stream.cancelled = true; - stream.emit('cancelled', 'cancelled'); - } - }, - }); -} -function handleClientStreaming(call, handler) { - let stream; - function respond(err, value, trailer, flags) { - if (err) { - call.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer)); - return; - } - call.sendMessage(value, () => { - call.sendStatus({ - code: constants_1.Status.OK, - details: 'OK', - metadata: trailer !== null && trailer !== void 0 ? trailer : null, - }); - }); - } - call.start({ - onReceiveMetadata(metadata) { - stream = new server_call_1.ServerDuplexStreamImpl(handler.path, call, metadata); - try { - handler.func(stream, respond); - } - catch (err) { - call.sendStatus({ - code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, - metadata: null, - }); - } - }, - onReceiveMessage(message) { - stream.push(message); - }, - onReceiveHalfClose() { - stream.push(null); - }, - onCancel() { - if (stream) { - stream.cancelled = true; - stream.emit('cancelled', 'cancelled'); - stream.destroy(); - } - }, - }); -} -function handleServerStreaming(call, handler) { - let stream; - let requestMetadata; - let requestMessage = null; - call.start({ - onReceiveMetadata(metadata) { - requestMetadata = metadata; - call.startRead(); - }, - onReceiveMessage(message) { - if (requestMessage) { - call.sendStatus({ - code: constants_1.Status.UNIMPLEMENTED, - details: `Received a second request message for server streaming method ${handler.path}`, - metadata: null, - }); - return; - } - requestMessage = message; - call.startRead(); - }, - onReceiveHalfClose() { - if (!requestMessage) { - call.sendStatus({ - code: constants_1.Status.UNIMPLEMENTED, - details: `Received no request message for server streaming method ${handler.path}`, - metadata: null, - }); - return; - } - stream = new server_call_1.ServerWritableStreamImpl(handler.path, call, requestMetadata, requestMessage); - try { - handler.func(stream); - } - catch (err) { - call.sendStatus({ - code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, - metadata: null, - }); - } - }, - onCancel() { - if (stream) { - stream.cancelled = true; - stream.emit('cancelled', 'cancelled'); - stream.destroy(); - } - }, - }); -} -function handleBidiStreaming(call, handler) { - let stream; - call.start({ - onReceiveMetadata(metadata) { - stream = new server_call_1.ServerDuplexStreamImpl(handler.path, call, metadata); - try { - handler.func(stream); - } - catch (err) { - call.sendStatus({ - code: constants_1.Status.UNKNOWN, - details: `Server method handler threw error ${err.message}`, - metadata: null, - }); - } - }, - onReceiveMessage(message) { - stream.push(message); - }, - onReceiveHalfClose() { - stream.push(null); - }, - onCancel() { - if (stream) { - stream.cancelled = true; - stream.emit('cancelled', 'cancelled'); - stream.destroy(); - } - }, - }); -} -//# sourceMappingURL=server.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/service-config.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/service-config.js deleted file mode 100644 index d7accd3f..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/service-config.js +++ /dev/null @@ -1,430 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.validateRetryThrottling = validateRetryThrottling; -exports.validateServiceConfig = validateServiceConfig; -exports.extractAndSelectServiceConfig = extractAndSelectServiceConfig; -/* This file implements gRFC A2 and the service config spec: - * https://github.com/grpc/proposal/blob/master/A2-service-configs-in-dns.md - * https://github.com/grpc/grpc/blob/master/doc/service_config.md. Each - * function here takes an object with unknown structure and returns its - * specific object type if the input has the right structure, and throws an - * error otherwise. */ -/* The any type is purposely used here. All functions validate their input at - * runtime */ -/* eslint-disable @typescript-eslint/no-explicit-any */ -const os = require("os"); -const constants_1 = require("./constants"); -/** - * Recognizes a number with up to 9 digits after the decimal point, followed by - * an "s", representing a number of seconds. - */ -const DURATION_REGEX = /^\d+(\.\d{1,9})?s$/; -/** - * Client language name used for determining whether this client matches a - * `ServiceConfigCanaryConfig`'s `clientLanguage` list. - */ -const CLIENT_LANGUAGE_STRING = 'node'; -function validateName(obj) { - // In this context, and unset field and '' are considered the same - if ('service' in obj && obj.service !== '') { - if (typeof obj.service !== 'string') { - throw new Error(`Invalid method config name: invalid service: expected type string, got ${typeof obj.service}`); - } - if ('method' in obj && obj.method !== '') { - if (typeof obj.method !== 'string') { - throw new Error(`Invalid method config name: invalid method: expected type string, got ${typeof obj.service}`); - } - return { - service: obj.service, - method: obj.method, - }; - } - else { - return { - service: obj.service, - }; - } - } - else { - if ('method' in obj && obj.method !== undefined) { - throw new Error(`Invalid method config name: method set with empty or unset service`); - } - return {}; - } -} -function validateRetryPolicy(obj) { - if (!('maxAttempts' in obj) || - !Number.isInteger(obj.maxAttempts) || - obj.maxAttempts < 2) { - throw new Error('Invalid method config retry policy: maxAttempts must be an integer at least 2'); - } - if (!('initialBackoff' in obj) || - typeof obj.initialBackoff !== 'string' || - !DURATION_REGEX.test(obj.initialBackoff)) { - throw new Error('Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer or decimal followed by s'); - } - if (!('maxBackoff' in obj) || - typeof obj.maxBackoff !== 'string' || - !DURATION_REGEX.test(obj.maxBackoff)) { - throw new Error('Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer or decimal followed by s'); - } - if (!('backoffMultiplier' in obj) || - typeof obj.backoffMultiplier !== 'number' || - obj.backoffMultiplier <= 0) { - throw new Error('Invalid method config retry policy: backoffMultiplier must be a number greater than 0'); - } - if (!('retryableStatusCodes' in obj && Array.isArray(obj.retryableStatusCodes))) { - throw new Error('Invalid method config retry policy: retryableStatusCodes is required'); - } - if (obj.retryableStatusCodes.length === 0) { - throw new Error('Invalid method config retry policy: retryableStatusCodes must be non-empty'); - } - for (const value of obj.retryableStatusCodes) { - if (typeof value === 'number') { - if (!Object.values(constants_1.Status).includes(value)) { - throw new Error('Invalid method config retry policy: retryableStatusCodes value not in status code range'); - } - } - else if (typeof value === 'string') { - if (!Object.values(constants_1.Status).includes(value.toUpperCase())) { - throw new Error('Invalid method config retry policy: retryableStatusCodes value not a status code name'); - } - } - else { - throw new Error('Invalid method config retry policy: retryableStatusCodes value must be a string or number'); - } - } - return { - maxAttempts: obj.maxAttempts, - initialBackoff: obj.initialBackoff, - maxBackoff: obj.maxBackoff, - backoffMultiplier: obj.backoffMultiplier, - retryableStatusCodes: obj.retryableStatusCodes, - }; -} -function validateHedgingPolicy(obj) { - if (!('maxAttempts' in obj) || - !Number.isInteger(obj.maxAttempts) || - obj.maxAttempts < 2) { - throw new Error('Invalid method config hedging policy: maxAttempts must be an integer at least 2'); - } - if ('hedgingDelay' in obj && - (typeof obj.hedgingDelay !== 'string' || - !DURATION_REGEX.test(obj.hedgingDelay))) { - throw new Error('Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s'); - } - if ('nonFatalStatusCodes' in obj && Array.isArray(obj.nonFatalStatusCodes)) { - for (const value of obj.nonFatalStatusCodes) { - if (typeof value === 'number') { - if (!Object.values(constants_1.Status).includes(value)) { - throw new Error('Invalid method config hedging policy: nonFatalStatusCodes value not in status code range'); - } - } - else if (typeof value === 'string') { - if (!Object.values(constants_1.Status).includes(value.toUpperCase())) { - throw new Error('Invalid method config hedging policy: nonFatalStatusCodes value not a status code name'); - } - } - else { - throw new Error('Invalid method config hedging policy: nonFatalStatusCodes value must be a string or number'); - } - } - } - const result = { - maxAttempts: obj.maxAttempts, - }; - if (obj.hedgingDelay) { - result.hedgingDelay = obj.hedgingDelay; - } - if (obj.nonFatalStatusCodes) { - result.nonFatalStatusCodes = obj.nonFatalStatusCodes; - } - return result; -} -function validateMethodConfig(obj) { - var _a; - const result = { - name: [], - }; - if (!('name' in obj) || !Array.isArray(obj.name)) { - throw new Error('Invalid method config: invalid name array'); - } - for (const name of obj.name) { - result.name.push(validateName(name)); - } - if ('waitForReady' in obj) { - if (typeof obj.waitForReady !== 'boolean') { - throw new Error('Invalid method config: invalid waitForReady'); - } - result.waitForReady = obj.waitForReady; - } - if ('timeout' in obj) { - if (typeof obj.timeout === 'object') { - if (!('seconds' in obj.timeout) || - !(typeof obj.timeout.seconds === 'number')) { - throw new Error('Invalid method config: invalid timeout.seconds'); - } - if (!('nanos' in obj.timeout) || - !(typeof obj.timeout.nanos === 'number')) { - throw new Error('Invalid method config: invalid timeout.nanos'); - } - result.timeout = obj.timeout; - } - else if (typeof obj.timeout === 'string' && - DURATION_REGEX.test(obj.timeout)) { - const timeoutParts = obj.timeout - .substring(0, obj.timeout.length - 1) - .split('.'); - result.timeout = { - seconds: timeoutParts[0] | 0, - nanos: ((_a = timeoutParts[1]) !== null && _a !== void 0 ? _a : 0) | 0, - }; - } - else { - throw new Error('Invalid method config: invalid timeout'); - } - } - if ('maxRequestBytes' in obj) { - if (typeof obj.maxRequestBytes !== 'number') { - throw new Error('Invalid method config: invalid maxRequestBytes'); - } - result.maxRequestBytes = obj.maxRequestBytes; - } - if ('maxResponseBytes' in obj) { - if (typeof obj.maxResponseBytes !== 'number') { - throw new Error('Invalid method config: invalid maxRequestBytes'); - } - result.maxResponseBytes = obj.maxResponseBytes; - } - if ('retryPolicy' in obj) { - if ('hedgingPolicy' in obj) { - throw new Error('Invalid method config: retryPolicy and hedgingPolicy cannot both be specified'); - } - else { - result.retryPolicy = validateRetryPolicy(obj.retryPolicy); - } - } - else if ('hedgingPolicy' in obj) { - result.hedgingPolicy = validateHedgingPolicy(obj.hedgingPolicy); - } - return result; -} -function validateRetryThrottling(obj) { - if (!('maxTokens' in obj) || - typeof obj.maxTokens !== 'number' || - obj.maxTokens <= 0 || - obj.maxTokens > 1000) { - throw new Error('Invalid retryThrottling: maxTokens must be a number in (0, 1000]'); - } - if (!('tokenRatio' in obj) || - typeof obj.tokenRatio !== 'number' || - obj.tokenRatio <= 0) { - throw new Error('Invalid retryThrottling: tokenRatio must be a number greater than 0'); - } - return { - maxTokens: +obj.maxTokens.toFixed(3), - tokenRatio: +obj.tokenRatio.toFixed(3), - }; -} -function validateLoadBalancingConfig(obj) { - if (!(typeof obj === 'object' && obj !== null)) { - throw new Error(`Invalid loadBalancingConfig: unexpected type ${typeof obj}`); - } - const keys = Object.keys(obj); - if (keys.length > 1) { - throw new Error(`Invalid loadBalancingConfig: unexpected multiple keys ${keys}`); - } - if (keys.length === 0) { - throw new Error('Invalid loadBalancingConfig: load balancing policy name required'); - } - return { - [keys[0]]: obj[keys[0]], - }; -} -function validateServiceConfig(obj) { - const result = { - loadBalancingConfig: [], - methodConfig: [], - }; - if ('loadBalancingPolicy' in obj) { - if (typeof obj.loadBalancingPolicy === 'string') { - result.loadBalancingPolicy = obj.loadBalancingPolicy; - } - else { - throw new Error('Invalid service config: invalid loadBalancingPolicy'); - } - } - if ('loadBalancingConfig' in obj) { - if (Array.isArray(obj.loadBalancingConfig)) { - for (const config of obj.loadBalancingConfig) { - result.loadBalancingConfig.push(validateLoadBalancingConfig(config)); - } - } - else { - throw new Error('Invalid service config: invalid loadBalancingConfig'); - } - } - if ('methodConfig' in obj) { - if (Array.isArray(obj.methodConfig)) { - for (const methodConfig of obj.methodConfig) { - result.methodConfig.push(validateMethodConfig(methodConfig)); - } - } - } - if ('retryThrottling' in obj) { - result.retryThrottling = validateRetryThrottling(obj.retryThrottling); - } - // Validate method name uniqueness - const seenMethodNames = []; - for (const methodConfig of result.methodConfig) { - for (const name of methodConfig.name) { - for (const seenName of seenMethodNames) { - if (name.service === seenName.service && - name.method === seenName.method) { - throw new Error(`Invalid service config: duplicate name ${name.service}/${name.method}`); - } - } - seenMethodNames.push(name); - } - } - return result; -} -function validateCanaryConfig(obj) { - if (!('serviceConfig' in obj)) { - throw new Error('Invalid service config choice: missing service config'); - } - const result = { - serviceConfig: validateServiceConfig(obj.serviceConfig), - }; - if ('clientLanguage' in obj) { - if (Array.isArray(obj.clientLanguage)) { - result.clientLanguage = []; - for (const lang of obj.clientLanguage) { - if (typeof lang === 'string') { - result.clientLanguage.push(lang); - } - else { - throw new Error('Invalid service config choice: invalid clientLanguage'); - } - } - } - else { - throw new Error('Invalid service config choice: invalid clientLanguage'); - } - } - if ('clientHostname' in obj) { - if (Array.isArray(obj.clientHostname)) { - result.clientHostname = []; - for (const lang of obj.clientHostname) { - if (typeof lang === 'string') { - result.clientHostname.push(lang); - } - else { - throw new Error('Invalid service config choice: invalid clientHostname'); - } - } - } - else { - throw new Error('Invalid service config choice: invalid clientHostname'); - } - } - if ('percentage' in obj) { - if (typeof obj.percentage === 'number' && - 0 <= obj.percentage && - obj.percentage <= 100) { - result.percentage = obj.percentage; - } - else { - throw new Error('Invalid service config choice: invalid percentage'); - } - } - // Validate that no unexpected fields are present - const allowedFields = [ - 'clientLanguage', - 'percentage', - 'clientHostname', - 'serviceConfig', - ]; - for (const field in obj) { - if (!allowedFields.includes(field)) { - throw new Error(`Invalid service config choice: unexpected field ${field}`); - } - } - return result; -} -function validateAndSelectCanaryConfig(obj, percentage) { - if (!Array.isArray(obj)) { - throw new Error('Invalid service config list'); - } - for (const config of obj) { - const validatedConfig = validateCanaryConfig(config); - /* For each field, we check if it is present, then only discard the - * config if the field value does not match the current client */ - if (typeof validatedConfig.percentage === 'number' && - percentage > validatedConfig.percentage) { - continue; - } - if (Array.isArray(validatedConfig.clientHostname)) { - let hostnameMatched = false; - for (const hostname of validatedConfig.clientHostname) { - if (hostname === os.hostname()) { - hostnameMatched = true; - } - } - if (!hostnameMatched) { - continue; - } - } - if (Array.isArray(validatedConfig.clientLanguage)) { - let languageMatched = false; - for (const language of validatedConfig.clientLanguage) { - if (language === CLIENT_LANGUAGE_STRING) { - languageMatched = true; - } - } - if (!languageMatched) { - continue; - } - } - return validatedConfig.serviceConfig; - } - throw new Error('No matching service config found'); -} -/** - * Find the "grpc_config" record among the TXT records, parse its value as JSON, validate its contents, - * and select a service config with selection fields that all match this client. Most of these steps - * can fail with an error; the caller must handle any errors thrown this way. - * @param txtRecord The TXT record array that is output from a successful call to dns.resolveTxt - * @param percentage A number chosen from the range [0, 100) that is used to select which config to use - * @return The service configuration to use, given the percentage value, or null if the service config - * data has a valid format but none of the options match the current client. - */ -function extractAndSelectServiceConfig(txtRecord, percentage) { - for (const record of txtRecord) { - if (record.length > 0 && record[0].startsWith('grpc_config=')) { - /* Treat the list of strings in this record as a single string and remove - * "grpc_config=" from the beginning. The rest should be a JSON string */ - const recordString = record.join('').substring('grpc_config='.length); - const recordJson = JSON.parse(recordString); - return validateAndSelectCanaryConfig(recordJson, percentage); - } - } - return null; -} -//# sourceMappingURL=service-config.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.js deleted file mode 100644 index 72343f52..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/single-subchannel-channel.js +++ /dev/null @@ -1,245 +0,0 @@ -"use strict"; -/* - * Copyright 2025 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SingleSubchannelChannel = void 0; -const call_number_1 = require("./call-number"); -const channelz_1 = require("./channelz"); -const compression_filter_1 = require("./compression-filter"); -const connectivity_state_1 = require("./connectivity-state"); -const constants_1 = require("./constants"); -const control_plane_status_1 = require("./control-plane-status"); -const deadline_1 = require("./deadline"); -const filter_stack_1 = require("./filter-stack"); -const metadata_1 = require("./metadata"); -const resolver_1 = require("./resolver"); -const uri_parser_1 = require("./uri-parser"); -class SubchannelCallWrapper { - constructor(subchannel, method, filterStackFactory, options, callNumber) { - var _a, _b; - this.subchannel = subchannel; - this.method = method; - this.options = options; - this.callNumber = callNumber; - this.childCall = null; - this.pendingMessage = null; - this.readPending = false; - this.halfClosePending = false; - this.pendingStatus = null; - this.readFilterPending = false; - this.writeFilterPending = false; - const splitPath = this.method.split('/'); - let serviceName = ''; - /* The standard path format is "/{serviceName}/{methodName}", so if we split - * by '/', the first item should be empty and the second should be the - * service name */ - if (splitPath.length >= 2) { - serviceName = splitPath[1]; - } - const hostname = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.options.host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : 'localhost'; - /* Currently, call credentials are only allowed on HTTPS connections, so we - * can assume that the scheme is "https" */ - this.serviceUrl = `https://${hostname}/${serviceName}`; - const timeout = (0, deadline_1.getRelativeTimeout)(options.deadline); - if (timeout !== Infinity) { - if (timeout <= 0) { - this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, 'Deadline exceeded'); - } - else { - setTimeout(() => { - this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, 'Deadline exceeded'); - }, timeout); - } - } - this.filterStack = filterStackFactory.createFilter(); - } - cancelWithStatus(status, details) { - if (this.childCall) { - this.childCall.cancelWithStatus(status, details); - } - else { - this.pendingStatus = { - code: status, - details: details, - metadata: new metadata_1.Metadata() - }; - } - } - getPeer() { - var _a, _b; - return (_b = (_a = this.childCall) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.subchannel.getAddress(); - } - async start(metadata, listener) { - if (this.pendingStatus) { - listener.onReceiveStatus(this.pendingStatus); - return; - } - if (this.subchannel.getConnectivityState() !== connectivity_state_1.ConnectivityState.READY) { - listener.onReceiveStatus({ - code: constants_1.Status.UNAVAILABLE, - details: 'Subchannel not ready', - metadata: new metadata_1.Metadata() - }); - return; - } - const filteredMetadata = await this.filterStack.sendMetadata(Promise.resolve(metadata)); - let credsMetadata; - try { - credsMetadata = await this.subchannel.getCallCredentials() - .generateMetadata({ method_name: this.method, service_url: this.serviceUrl }); - } - catch (e) { - const error = e; - const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(typeof error.code === 'number' ? error.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error.message}`); - listener.onReceiveStatus({ - code: code, - details: details, - metadata: new metadata_1.Metadata(), - }); - return; - } - credsMetadata.merge(filteredMetadata); - const childListener = { - onReceiveMetadata: async (metadata) => { - listener.onReceiveMetadata(await this.filterStack.receiveMetadata(metadata)); - }, - onReceiveMessage: async (message) => { - this.readFilterPending = true; - const filteredMessage = await this.filterStack.receiveMessage(message); - this.readFilterPending = false; - listener.onReceiveMessage(filteredMessage); - if (this.pendingStatus) { - listener.onReceiveStatus(this.pendingStatus); - } - }, - onReceiveStatus: async (status) => { - const filteredStatus = await this.filterStack.receiveTrailers(status); - if (this.readFilterPending) { - this.pendingStatus = filteredStatus; - } - else { - listener.onReceiveStatus(filteredStatus); - } - } - }; - this.childCall = this.subchannel.createCall(credsMetadata, this.options.host, this.method, childListener); - if (this.readPending) { - this.childCall.startRead(); - } - if (this.pendingMessage) { - this.childCall.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message); - } - if (this.halfClosePending && !this.writeFilterPending) { - this.childCall.halfClose(); - } - } - async sendMessageWithContext(context, message) { - this.writeFilterPending = true; - const filteredMessage = await this.filterStack.sendMessage(Promise.resolve({ message: message, flags: context.flags })); - this.writeFilterPending = false; - if (this.childCall) { - this.childCall.sendMessageWithContext(context, filteredMessage.message); - if (this.halfClosePending) { - this.childCall.halfClose(); - } - } - else { - this.pendingMessage = { context, message: filteredMessage.message }; - } - } - startRead() { - if (this.childCall) { - this.childCall.startRead(); - } - else { - this.readPending = true; - } - } - halfClose() { - if (this.childCall && !this.writeFilterPending) { - this.childCall.halfClose(); - } - else { - this.halfClosePending = true; - } - } - getCallNumber() { - return this.callNumber; - } - setCredentials(credentials) { - throw new Error("Method not implemented."); - } - getAuthContext() { - if (this.childCall) { - return this.childCall.getAuthContext(); - } - else { - return null; - } - } -} -class SingleSubchannelChannel { - constructor(subchannel, target, options) { - this.subchannel = subchannel; - this.target = target; - this.channelzEnabled = false; - this.channelzTrace = new channelz_1.ChannelzTrace(); - this.callTracker = new channelz_1.ChannelzCallTracker(); - this.childrenTracker = new channelz_1.ChannelzChildrenTracker(); - this.channelzEnabled = options['grpc.enable_channelz'] !== 0; - this.channelzRef = (0, channelz_1.registerChannelzChannel)((0, uri_parser_1.uriToString)(target), () => ({ - target: `${(0, uri_parser_1.uriToString)(target)} (${subchannel.getAddress()})`, - state: this.subchannel.getConnectivityState(), - trace: this.channelzTrace, - callTracker: this.callTracker, - children: this.childrenTracker.getChildLists() - }), this.channelzEnabled); - if (this.channelzEnabled) { - this.childrenTracker.refChild(subchannel.getChannelzRef()); - } - this.filterStackFactory = new filter_stack_1.FilterStackFactory([new compression_filter_1.CompressionFilterFactory(this, options)]); - } - close() { - if (this.channelzEnabled) { - this.childrenTracker.unrefChild(this.subchannel.getChannelzRef()); - } - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - } - getTarget() { - return (0, uri_parser_1.uriToString)(this.target); - } - getConnectivityState(tryToConnect) { - throw new Error("Method not implemented."); - } - watchConnectivityState(currentState, deadline, callback) { - throw new Error("Method not implemented."); - } - getChannelzRef() { - return this.channelzRef; - } - createCall(method, deadline) { - const callOptions = { - deadline: deadline, - host: (0, resolver_1.getDefaultAuthority)(this.target), - flags: constants_1.Propagate.DEFAULTS, - parentCall: null - }; - return new SubchannelCallWrapper(this.subchannel, method, this.filterStackFactory, callOptions, (0, call_number_1.getNextCallNumber)()); - } -} -exports.SingleSubchannelChannel = SingleSubchannelChannel; -//# sourceMappingURL=single-subchannel-channel.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/status-builder.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/status-builder.js deleted file mode 100644 index 7426e54b..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/status-builder.js +++ /dev/null @@ -1,68 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.StatusBuilder = void 0; -/** - * A builder for gRPC status objects. - */ -class StatusBuilder { - constructor() { - this.code = null; - this.details = null; - this.metadata = null; - } - /** - * Adds a status code to the builder. - */ - withCode(code) { - this.code = code; - return this; - } - /** - * Adds details to the builder. - */ - withDetails(details) { - this.details = details; - return this; - } - /** - * Adds metadata to the builder. - */ - withMetadata(metadata) { - this.metadata = metadata; - return this; - } - /** - * Builds the status object. - */ - build() { - const status = {}; - if (this.code !== null) { - status.code = this.code; - } - if (this.details !== null) { - status.details = this.details; - } - if (this.metadata !== null) { - status.metadata = this.metadata; - } - return status; - } -} -exports.StatusBuilder = StatusBuilder; -//# sourceMappingURL=status-builder.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/stream-decoder.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/stream-decoder.js deleted file mode 100644 index b3857c03..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/stream-decoder.js +++ /dev/null @@ -1,100 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.StreamDecoder = void 0; -var ReadState; -(function (ReadState) { - ReadState[ReadState["NO_DATA"] = 0] = "NO_DATA"; - ReadState[ReadState["READING_SIZE"] = 1] = "READING_SIZE"; - ReadState[ReadState["READING_MESSAGE"] = 2] = "READING_MESSAGE"; -})(ReadState || (ReadState = {})); -class StreamDecoder { - constructor(maxReadMessageLength) { - this.maxReadMessageLength = maxReadMessageLength; - this.readState = ReadState.NO_DATA; - this.readCompressFlag = Buffer.alloc(1); - this.readPartialSize = Buffer.alloc(4); - this.readSizeRemaining = 4; - this.readMessageSize = 0; - this.readPartialMessage = []; - this.readMessageRemaining = 0; - } - write(data) { - let readHead = 0; - let toRead; - const result = []; - while (readHead < data.length) { - switch (this.readState) { - case ReadState.NO_DATA: - this.readCompressFlag = data.slice(readHead, readHead + 1); - readHead += 1; - this.readState = ReadState.READING_SIZE; - this.readPartialSize.fill(0); - this.readSizeRemaining = 4; - this.readMessageSize = 0; - this.readMessageRemaining = 0; - this.readPartialMessage = []; - break; - case ReadState.READING_SIZE: - toRead = Math.min(data.length - readHead, this.readSizeRemaining); - data.copy(this.readPartialSize, 4 - this.readSizeRemaining, readHead, readHead + toRead); - this.readSizeRemaining -= toRead; - readHead += toRead; - // readSizeRemaining >=0 here - if (this.readSizeRemaining === 0) { - this.readMessageSize = this.readPartialSize.readUInt32BE(0); - if (this.maxReadMessageLength !== -1 && this.readMessageSize > this.maxReadMessageLength) { - throw new Error(`Received message larger than max (${this.readMessageSize} vs ${this.maxReadMessageLength})`); - } - this.readMessageRemaining = this.readMessageSize; - if (this.readMessageRemaining > 0) { - this.readState = ReadState.READING_MESSAGE; - } - else { - const message = Buffer.concat([this.readCompressFlag, this.readPartialSize], 5); - this.readState = ReadState.NO_DATA; - result.push(message); - } - } - break; - case ReadState.READING_MESSAGE: - toRead = Math.min(data.length - readHead, this.readMessageRemaining); - this.readPartialMessage.push(data.slice(readHead, readHead + toRead)); - this.readMessageRemaining -= toRead; - readHead += toRead; - // readMessageRemaining >=0 here - if (this.readMessageRemaining === 0) { - // At this point, we have read a full message - const framedMessageBuffers = [ - this.readCompressFlag, - this.readPartialSize, - ].concat(this.readPartialMessage); - const framedMessage = Buffer.concat(framedMessageBuffers, this.readMessageSize + 5); - this.readState = ReadState.NO_DATA; - result.push(framedMessage); - } - break; - default: - throw new Error('Unexpected read state'); - } - } - return result; - } -} -exports.StreamDecoder = StreamDecoder; -//# sourceMappingURL=stream-decoder.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/subchannel-address.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/subchannel-address.js deleted file mode 100644 index d48d0c20..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/subchannel-address.js +++ /dev/null @@ -1,202 +0,0 @@ -"use strict"; -/* - * Copyright 2021 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.EndpointMap = void 0; -exports.isTcpSubchannelAddress = isTcpSubchannelAddress; -exports.subchannelAddressEqual = subchannelAddressEqual; -exports.subchannelAddressToString = subchannelAddressToString; -exports.stringToSubchannelAddress = stringToSubchannelAddress; -exports.endpointEqual = endpointEqual; -exports.endpointToString = endpointToString; -exports.endpointHasAddress = endpointHasAddress; -const net_1 = require("net"); -function isTcpSubchannelAddress(address) { - return 'port' in address; -} -function subchannelAddressEqual(address1, address2) { - if (!address1 && !address2) { - return true; - } - if (!address1 || !address2) { - return false; - } - if (isTcpSubchannelAddress(address1)) { - return (isTcpSubchannelAddress(address2) && - address1.host === address2.host && - address1.port === address2.port); - } - else { - return !isTcpSubchannelAddress(address2) && address1.path === address2.path; - } -} -function subchannelAddressToString(address) { - if (isTcpSubchannelAddress(address)) { - if ((0, net_1.isIPv6)(address.host)) { - return '[' + address.host + ']:' + address.port; - } - else { - return address.host + ':' + address.port; - } - } - else { - return address.path; - } -} -const DEFAULT_PORT = 443; -function stringToSubchannelAddress(addressString, port) { - if ((0, net_1.isIP)(addressString)) { - return { - host: addressString, - port: port !== null && port !== void 0 ? port : DEFAULT_PORT, - }; - } - else { - return { - path: addressString, - }; - } -} -function endpointEqual(endpoint1, endpoint2) { - if (endpoint1.addresses.length !== endpoint2.addresses.length) { - return false; - } - for (let i = 0; i < endpoint1.addresses.length; i++) { - if (!subchannelAddressEqual(endpoint1.addresses[i], endpoint2.addresses[i])) { - return false; - } - } - return true; -} -function endpointToString(endpoint) { - return ('[' + endpoint.addresses.map(subchannelAddressToString).join(', ') + ']'); -} -function endpointHasAddress(endpoint, expectedAddress) { - for (const address of endpoint.addresses) { - if (subchannelAddressEqual(address, expectedAddress)) { - return true; - } - } - return false; -} -function endpointEqualUnordered(endpoint1, endpoint2) { - if (endpoint1.addresses.length !== endpoint2.addresses.length) { - return false; - } - for (const address1 of endpoint1.addresses) { - let matchFound = false; - for (const address2 of endpoint2.addresses) { - if (subchannelAddressEqual(address1, address2)) { - matchFound = true; - break; - } - } - if (!matchFound) { - return false; - } - } - return true; -} -class EndpointMap { - constructor() { - this.map = new Set(); - } - get size() { - return this.map.size; - } - getForSubchannelAddress(address) { - for (const entry of this.map) { - if (endpointHasAddress(entry.key, address)) { - return entry.value; - } - } - return undefined; - } - /** - * Delete any entries in this map with keys that are not in endpoints - * @param endpoints - */ - deleteMissing(endpoints) { - const removedValues = []; - for (const entry of this.map) { - let foundEntry = false; - for (const endpoint of endpoints) { - if (endpointEqualUnordered(endpoint, entry.key)) { - foundEntry = true; - } - } - if (!foundEntry) { - removedValues.push(entry.value); - this.map.delete(entry); - } - } - return removedValues; - } - get(endpoint) { - for (const entry of this.map) { - if (endpointEqualUnordered(endpoint, entry.key)) { - return entry.value; - } - } - return undefined; - } - set(endpoint, mapEntry) { - for (const entry of this.map) { - if (endpointEqualUnordered(endpoint, entry.key)) { - entry.value = mapEntry; - return; - } - } - this.map.add({ key: endpoint, value: mapEntry }); - } - delete(endpoint) { - for (const entry of this.map) { - if (endpointEqualUnordered(endpoint, entry.key)) { - this.map.delete(entry); - return; - } - } - } - has(endpoint) { - for (const entry of this.map) { - if (endpointEqualUnordered(endpoint, entry.key)) { - return true; - } - } - return false; - } - clear() { - this.map.clear(); - } - *keys() { - for (const entry of this.map) { - yield entry.key; - } - } - *values() { - for (const entry of this.map) { - yield entry.value; - } - } - *entries() { - for (const entry of this.map) { - yield [entry.key, entry.value]; - } - } -} -exports.EndpointMap = EndpointMap; -//# sourceMappingURL=subchannel-address.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/subchannel-call.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/subchannel-call.js deleted file mode 100644 index e448ad37..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/subchannel-call.js +++ /dev/null @@ -1,545 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Http2SubchannelCall = void 0; -const http2 = require("http2"); -const os = require("os"); -const constants_1 = require("./constants"); -const metadata_1 = require("./metadata"); -const stream_decoder_1 = require("./stream-decoder"); -const logging = require("./logging"); -const constants_2 = require("./constants"); -const TRACER_NAME = 'subchannel_call'; -/** - * Should do approximately the same thing as util.getSystemErrorName but the - * TypeScript types don't have that function for some reason so I just made my - * own. - * @param errno - */ -function getSystemErrorName(errno) { - for (const [name, num] of Object.entries(os.constants.errno)) { - if (num === errno) { - return name; - } - } - return 'Unknown system error ' + errno; -} -function mapHttpStatusCode(code) { - const details = `Received HTTP status code ${code}`; - let mappedStatusCode; - switch (code) { - // TODO(murgatroid99): handle 100 and 101 - case 400: - mappedStatusCode = constants_1.Status.INTERNAL; - break; - case 401: - mappedStatusCode = constants_1.Status.UNAUTHENTICATED; - break; - case 403: - mappedStatusCode = constants_1.Status.PERMISSION_DENIED; - break; - case 404: - mappedStatusCode = constants_1.Status.UNIMPLEMENTED; - break; - case 429: - case 502: - case 503: - case 504: - mappedStatusCode = constants_1.Status.UNAVAILABLE; - break; - default: - mappedStatusCode = constants_1.Status.UNKNOWN; - } - return { - code: mappedStatusCode, - details: details, - metadata: new metadata_1.Metadata() - }; -} -class Http2SubchannelCall { - constructor(http2Stream, callEventTracker, listener, transport, callId) { - var _a; - this.http2Stream = http2Stream; - this.callEventTracker = callEventTracker; - this.listener = listener; - this.transport = transport; - this.callId = callId; - this.isReadFilterPending = false; - this.isPushPending = false; - this.canPush = false; - /** - * Indicates that an 'end' event has come from the http2 stream, so there - * will be no more data events. - */ - this.readsClosed = false; - this.statusOutput = false; - this.unpushedReadMessages = []; - // This is populated (non-null) if and only if the call has ended - this.finalStatus = null; - this.internalError = null; - this.serverEndedCall = false; - this.connectionDropped = false; - const maxReceiveMessageLength = (_a = transport.getOptions()['grpc.max_receive_message_length']) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; - this.decoder = new stream_decoder_1.StreamDecoder(maxReceiveMessageLength); - http2Stream.on('response', (headers, flags) => { - let headersString = ''; - for (const header of Object.keys(headers)) { - headersString += '\t\t' + header + ': ' + headers[header] + '\n'; - } - this.trace('Received server headers:\n' + headersString); - this.httpStatusCode = headers[':status']; - if (flags & http2.constants.NGHTTP2_FLAG_END_STREAM) { - this.handleTrailers(headers); - } - else { - let metadata; - try { - metadata = metadata_1.Metadata.fromHttp2Headers(headers); - } - catch (error) { - this.endCall({ - code: constants_1.Status.UNKNOWN, - details: error.message, - metadata: new metadata_1.Metadata(), - }); - return; - } - this.listener.onReceiveMetadata(metadata); - } - }); - http2Stream.on('trailers', (headers) => { - this.handleTrailers(headers); - }); - http2Stream.on('data', (data) => { - /* If the status has already been output, allow the http2 stream to - * drain without processing the data. */ - if (this.statusOutput) { - return; - } - this.trace('receive HTTP/2 data frame of length ' + data.length); - let messages; - try { - messages = this.decoder.write(data); - } - catch (e) { - /* Some servers send HTML error pages along with HTTP status codes. - * When the client attempts to parse this as a length-delimited - * message, the parsed message size is greater than the default limit, - * resulting in a message decoding error. In that situation, the HTTP - * error code information is more useful to the user than the - * RESOURCE_EXHAUSTED error is, so we report that instead. Normally, - * we delay processing the HTTP status until after the stream ends, to - * prioritize reporting the gRPC status from trailers if it is present, - * but when there is a message parsing error we end the stream early - * before processing trailers. */ - if (this.httpStatusCode !== undefined && this.httpStatusCode !== 200) { - const mappedStatus = mapHttpStatusCode(this.httpStatusCode); - this.cancelWithStatus(mappedStatus.code, mappedStatus.details); - } - else { - this.cancelWithStatus(constants_1.Status.RESOURCE_EXHAUSTED, e.message); - } - return; - } - for (const message of messages) { - this.trace('parsed message of length ' + message.length); - this.callEventTracker.addMessageReceived(); - this.tryPush(message); - } - }); - http2Stream.on('end', () => { - this.readsClosed = true; - this.maybeOutputStatus(); - }); - http2Stream.on('close', () => { - this.serverEndedCall = true; - /* Use process.next tick to ensure that this code happens after any - * "error" event that may be emitted at about the same time, so that - * we can bubble up the error message from that event. */ - process.nextTick(() => { - var _a; - this.trace('HTTP/2 stream closed with code ' + http2Stream.rstCode); - /* If we have a final status with an OK status code, that means that - * we have received all of the messages and we have processed the - * trailers and the call completed successfully, so it doesn't matter - * how the stream ends after that */ - if (((_a = this.finalStatus) === null || _a === void 0 ? void 0 : _a.code) === constants_1.Status.OK) { - return; - } - let code; - let details = ''; - switch (http2Stream.rstCode) { - case http2.constants.NGHTTP2_NO_ERROR: - /* If we get a NO_ERROR code and we already have a status, the - * stream completed properly and we just haven't fully processed - * it yet */ - if (this.finalStatus !== null) { - return; - } - if (this.httpStatusCode && this.httpStatusCode !== 200) { - const mappedStatus = mapHttpStatusCode(this.httpStatusCode); - code = mappedStatus.code; - details = mappedStatus.details; - } - else { - code = constants_1.Status.INTERNAL; - details = `Received RST_STREAM with code ${http2Stream.rstCode} (Call ended without gRPC status)`; - } - break; - case http2.constants.NGHTTP2_REFUSED_STREAM: - code = constants_1.Status.UNAVAILABLE; - details = 'Stream refused by server'; - break; - case http2.constants.NGHTTP2_CANCEL: - /* Bug reports indicate that Node synthesizes a NGHTTP2_CANCEL - * code from connection drops. We want to prioritize reporting - * an unavailable status when that happens. */ - if (this.connectionDropped) { - code = constants_1.Status.UNAVAILABLE; - details = 'Connection dropped'; - } - else { - code = constants_1.Status.CANCELLED; - details = 'Call cancelled'; - } - break; - case http2.constants.NGHTTP2_ENHANCE_YOUR_CALM: - code = constants_1.Status.RESOURCE_EXHAUSTED; - details = 'Bandwidth exhausted or memory limit exceeded'; - break; - case http2.constants.NGHTTP2_INADEQUATE_SECURITY: - code = constants_1.Status.PERMISSION_DENIED; - details = 'Protocol not secure enough'; - break; - case http2.constants.NGHTTP2_INTERNAL_ERROR: - code = constants_1.Status.INTERNAL; - if (this.internalError === null) { - /* This error code was previously handled in the default case, and - * there are several instances of it online, so I wanted to - * preserve the original error message so that people find existing - * information in searches, but also include the more recognizable - * "Internal server error" message. */ - details = `Received RST_STREAM with code ${http2Stream.rstCode} (Internal server error)`; - } - else { - if (this.internalError.code === 'ECONNRESET' || - this.internalError.code === 'ETIMEDOUT') { - code = constants_1.Status.UNAVAILABLE; - details = this.internalError.message; - } - else { - /* The "Received RST_STREAM with code ..." error is preserved - * here for continuity with errors reported online, but the - * error message at the end will probably be more relevant in - * most cases. */ - details = `Received RST_STREAM with code ${http2Stream.rstCode} triggered by internal client error: ${this.internalError.message}`; - } - } - break; - default: - code = constants_1.Status.INTERNAL; - details = `Received RST_STREAM with code ${http2Stream.rstCode}`; - } - // This is a no-op if trailers were received at all. - // This is OK, because status codes emitted here correspond to more - // catastrophic issues that prevent us from receiving trailers in the - // first place. - this.endCall({ - code, - details, - metadata: new metadata_1.Metadata(), - rstCode: http2Stream.rstCode, - }); - }); - }); - http2Stream.on('error', (err) => { - /* We need an error handler here to stop "Uncaught Error" exceptions - * from bubbling up. However, errors here should all correspond to - * "close" events, where we will handle the error more granularly */ - /* Specifically looking for stream errors that were *not* constructed - * from a RST_STREAM response here: - * https://github.com/nodejs/node/blob/8b8620d580314050175983402dfddf2674e8e22a/lib/internal/http2/core.js#L2267 - */ - if (err.code !== 'ERR_HTTP2_STREAM_ERROR') { - this.trace('Node error event: message=' + - err.message + - ' code=' + - err.code + - ' errno=' + - getSystemErrorName(err.errno) + - ' syscall=' + - err.syscall); - this.internalError = err; - } - this.callEventTracker.onStreamEnd(false); - }); - } - getDeadlineInfo() { - return [`remote_addr=${this.getPeer()}`]; - } - onDisconnect() { - this.connectionDropped = true; - /* Give the call an event loop cycle to finish naturally before reporting - * the disconnection as an error. */ - setImmediate(() => { - this.endCall({ - code: constants_1.Status.UNAVAILABLE, - details: 'Connection dropped', - metadata: new metadata_1.Metadata(), - }); - }); - } - outputStatus() { - /* Precondition: this.finalStatus !== null */ - if (!this.statusOutput) { - this.statusOutput = true; - this.trace('ended with status: code=' + - this.finalStatus.code + - ' details="' + - this.finalStatus.details + - '"'); - this.callEventTracker.onCallEnd(this.finalStatus); - /* We delay the actual action of bubbling up the status to insulate the - * cleanup code in this class from any errors that may be thrown in the - * upper layers as a result of bubbling up the status. In particular, - * if the status is not OK, the "error" event may be emitted - * synchronously at the top level, which will result in a thrown error if - * the user does not handle that event. */ - process.nextTick(() => { - this.listener.onReceiveStatus(this.finalStatus); - }); - /* Leave the http2 stream in flowing state to drain incoming messages, to - * ensure that the stream closure completes. The call stream already does - * not push more messages after the status is output, so the messages go - * nowhere either way. */ - this.http2Stream.resume(); - } - } - trace(text) { - logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callId + '] ' + text); - } - /** - * On first call, emits a 'status' event with the given StatusObject. - * Subsequent calls are no-ops. - * @param status The status of the call. - */ - endCall(status) { - /* If the status is OK and a new status comes in (e.g. from a - * deserialization failure), that new status takes priority */ - if (this.finalStatus === null || this.finalStatus.code === constants_1.Status.OK) { - this.finalStatus = status; - this.maybeOutputStatus(); - } - this.destroyHttp2Stream(); - } - maybeOutputStatus() { - if (this.finalStatus !== null) { - /* The combination check of readsClosed and that the two message buffer - * arrays are empty checks that there all incoming data has been fully - * processed */ - if (this.finalStatus.code !== constants_1.Status.OK || - (this.readsClosed && - this.unpushedReadMessages.length === 0 && - !this.isReadFilterPending && - !this.isPushPending)) { - this.outputStatus(); - } - } - } - push(message) { - this.trace('pushing to reader message of length ' + - (message instanceof Buffer ? message.length : null)); - this.canPush = false; - this.isPushPending = true; - process.nextTick(() => { - this.isPushPending = false; - /* If we have already output the status any later messages should be - * ignored, and can cause out-of-order operation errors higher up in the - * stack. Checking as late as possible here to avoid any race conditions. - */ - if (this.statusOutput) { - return; - } - this.listener.onReceiveMessage(message); - this.maybeOutputStatus(); - }); - } - tryPush(messageBytes) { - if (this.canPush) { - this.http2Stream.pause(); - this.push(messageBytes); - } - else { - this.trace('unpushedReadMessages.push message of length ' + messageBytes.length); - this.unpushedReadMessages.push(messageBytes); - } - } - handleTrailers(headers) { - this.serverEndedCall = true; - this.callEventTracker.onStreamEnd(true); - let headersString = ''; - for (const header of Object.keys(headers)) { - headersString += '\t\t' + header + ': ' + headers[header] + '\n'; - } - this.trace('Received server trailers:\n' + headersString); - let metadata; - try { - metadata = metadata_1.Metadata.fromHttp2Headers(headers); - } - catch (e) { - metadata = new metadata_1.Metadata(); - } - const metadataMap = metadata.getMap(); - let status; - if (typeof metadataMap['grpc-status'] === 'string') { - const receivedStatus = Number(metadataMap['grpc-status']); - this.trace('received status code ' + receivedStatus + ' from server'); - metadata.remove('grpc-status'); - let details = ''; - if (typeof metadataMap['grpc-message'] === 'string') { - try { - details = decodeURI(metadataMap['grpc-message']); - } - catch (e) { - details = metadataMap['grpc-message']; - } - metadata.remove('grpc-message'); - this.trace('received status details string "' + details + '" from server'); - } - status = { - code: receivedStatus, - details: details, - metadata: metadata - }; - } - else if (this.httpStatusCode) { - status = mapHttpStatusCode(this.httpStatusCode); - status.metadata = metadata; - } - else { - status = { - code: constants_1.Status.UNKNOWN, - details: 'No status information received', - metadata: metadata - }; - } - // This is a no-op if the call was already ended when handling headers. - this.endCall(status); - } - destroyHttp2Stream() { - var _a; - // The http2 stream could already have been destroyed if cancelWithStatus - // is called in response to an internal http2 error. - if (this.http2Stream.destroyed) { - return; - } - /* If the server ended the call, sending an RST_STREAM is redundant, so we - * just half close on the client side instead to finish closing the stream. - */ - if (this.serverEndedCall) { - this.http2Stream.end(); - } - else { - /* If the call has ended with an OK status, communicate that when closing - * the stream, partly to avoid a situation in which we detect an error - * RST_STREAM as a result after we have the status */ - let code; - if (((_a = this.finalStatus) === null || _a === void 0 ? void 0 : _a.code) === constants_1.Status.OK) { - code = http2.constants.NGHTTP2_NO_ERROR; - } - else { - code = http2.constants.NGHTTP2_CANCEL; - } - this.trace('close http2 stream with code ' + code); - this.http2Stream.close(code); - } - } - cancelWithStatus(status, details) { - this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"'); - this.endCall({ code: status, details, metadata: new metadata_1.Metadata() }); - } - getStatus() { - return this.finalStatus; - } - getPeer() { - return this.transport.getPeerName(); - } - getCallNumber() { - return this.callId; - } - getAuthContext() { - return this.transport.getAuthContext(); - } - startRead() { - /* If the stream has ended with an error, we should not emit any more - * messages and we should communicate that the stream has ended */ - if (this.finalStatus !== null && this.finalStatus.code !== constants_1.Status.OK) { - this.readsClosed = true; - this.maybeOutputStatus(); - return; - } - this.canPush = true; - if (this.unpushedReadMessages.length > 0) { - const nextMessage = this.unpushedReadMessages.shift(); - this.push(nextMessage); - return; - } - /* Only resume reading from the http2Stream if we don't have any pending - * messages to emit */ - this.http2Stream.resume(); - } - sendMessageWithContext(context, message) { - this.trace('write() called with message of length ' + message.length); - const cb = (error) => { - /* nextTick here ensures that no stream action can be taken in the call - * stack of the write callback, in order to hopefully work around - * https://github.com/nodejs/node/issues/49147 */ - process.nextTick(() => { - var _a; - let code = constants_1.Status.UNAVAILABLE; - if ((error === null || error === void 0 ? void 0 : error.code) === - 'ERR_STREAM_WRITE_AFTER_END') { - code = constants_1.Status.INTERNAL; - } - if (error) { - this.cancelWithStatus(code, `Write error: ${error.message}`); - } - (_a = context.callback) === null || _a === void 0 ? void 0 : _a.call(context); - }); - }; - this.trace('sending data chunk of length ' + message.length); - this.callEventTracker.addMessageSent(); - try { - this.http2Stream.write(message, cb); - } - catch (error) { - this.endCall({ - code: constants_1.Status.UNAVAILABLE, - details: `Write failed with error ${error.message}`, - metadata: new metadata_1.Metadata(), - }); - } - } - halfClose() { - this.trace('end() called'); - this.trace('calling end() on HTTP/2 stream'); - this.http2Stream.end(); - } -} -exports.Http2SubchannelCall = Http2SubchannelCall; -//# sourceMappingURL=subchannel-call.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/subchannel-interface.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/subchannel-interface.js deleted file mode 100644 index 6faf71a2..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/subchannel-interface.js +++ /dev/null @@ -1,114 +0,0 @@ -"use strict"; -/* - * Copyright 2022 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BaseSubchannelWrapper = void 0; -class BaseSubchannelWrapper { - constructor(child) { - this.child = child; - this.healthy = true; - this.healthListeners = new Set(); - this.refcount = 0; - this.dataWatchers = new Set(); - child.addHealthStateWatcher(childHealthy => { - /* A change to the child health state only affects this wrapper's overall - * health state if this wrapper is reporting healthy. */ - if (this.healthy) { - this.updateHealthListeners(); - } - }); - } - updateHealthListeners() { - for (const listener of this.healthListeners) { - listener(this.isHealthy()); - } - } - getConnectivityState() { - return this.child.getConnectivityState(); - } - addConnectivityStateListener(listener) { - this.child.addConnectivityStateListener(listener); - } - removeConnectivityStateListener(listener) { - this.child.removeConnectivityStateListener(listener); - } - startConnecting() { - this.child.startConnecting(); - } - getAddress() { - return this.child.getAddress(); - } - throttleKeepalive(newKeepaliveTime) { - this.child.throttleKeepalive(newKeepaliveTime); - } - ref() { - this.child.ref(); - this.refcount += 1; - } - unref() { - this.child.unref(); - this.refcount -= 1; - if (this.refcount === 0) { - this.destroy(); - } - } - destroy() { - for (const watcher of this.dataWatchers) { - watcher.destroy(); - } - } - getChannelzRef() { - return this.child.getChannelzRef(); - } - isHealthy() { - return this.healthy && this.child.isHealthy(); - } - addHealthStateWatcher(listener) { - this.healthListeners.add(listener); - } - removeHealthStateWatcher(listener) { - this.healthListeners.delete(listener); - } - addDataWatcher(dataWatcher) { - dataWatcher.setSubchannel(this.getRealSubchannel()); - this.dataWatchers.add(dataWatcher); - } - setHealthy(healthy) { - if (healthy !== this.healthy) { - this.healthy = healthy; - /* A change to this wrapper's health state only affects the overall - * reported health state if the child is healthy. */ - if (this.child.isHealthy()) { - this.updateHealthListeners(); - } - } - } - getRealSubchannel() { - return this.child.getRealSubchannel(); - } - realSubchannelEquals(other) { - return this.getRealSubchannel() === other.getRealSubchannel(); - } - getCallCredentials() { - return this.child.getCallCredentials(); - } - getChannel() { - return this.child.getChannel(); - } -} -exports.BaseSubchannelWrapper = BaseSubchannelWrapper; -//# sourceMappingURL=subchannel-interface.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/subchannel-pool.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/subchannel-pool.js deleted file mode 100644 index e10d66d0..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/subchannel-pool.js +++ /dev/null @@ -1,137 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SubchannelPool = void 0; -exports.getSubchannelPool = getSubchannelPool; -const channel_options_1 = require("./channel-options"); -const subchannel_1 = require("./subchannel"); -const subchannel_address_1 = require("./subchannel-address"); -const uri_parser_1 = require("./uri-parser"); -const transport_1 = require("./transport"); -// 10 seconds in milliseconds. This value is arbitrary. -/** - * The amount of time in between checks for dropping subchannels that have no - * other references - */ -const REF_CHECK_INTERVAL = 10000; -class SubchannelPool { - /** - * A pool of subchannels use for making connections. Subchannels with the - * exact same parameters will be reused. - */ - constructor() { - this.pool = Object.create(null); - /** - * A timer of a task performing a periodic subchannel cleanup. - */ - this.cleanupTimer = null; - } - /** - * Unrefs all unused subchannels and cancels the cleanup task if all - * subchannels have been unrefed. - */ - unrefUnusedSubchannels() { - let allSubchannelsUnrefed = true; - /* These objects are created with Object.create(null), so they do not - * have a prototype, which means that for (... in ...) loops over them - * do not need to be filtered */ - // eslint-disable-disable-next-line:forin - for (const channelTarget in this.pool) { - const subchannelObjArray = this.pool[channelTarget]; - const refedSubchannels = subchannelObjArray.filter(value => !value.subchannel.unrefIfOneRef()); - if (refedSubchannels.length > 0) { - allSubchannelsUnrefed = false; - } - /* For each subchannel in the pool, try to unref it if it has - * exactly one ref (which is the ref from the pool itself). If that - * does happen, remove the subchannel from the pool */ - this.pool[channelTarget] = refedSubchannels; - } - /* Currently we do not delete keys with empty values. If that results - * in significant memory usage we should change it. */ - // Cancel the cleanup task if all subchannels have been unrefed. - if (allSubchannelsUnrefed && this.cleanupTimer !== null) { - clearInterval(this.cleanupTimer); - this.cleanupTimer = null; - } - } - /** - * Ensures that the cleanup task is spawned. - */ - ensureCleanupTask() { - var _a, _b; - if (this.cleanupTimer === null) { - this.cleanupTimer = setInterval(() => { - this.unrefUnusedSubchannels(); - }, REF_CHECK_INTERVAL); - // Unref because this timer should not keep the event loop running. - // Call unref only if it exists to address electron/electron#21162 - (_b = (_a = this.cleanupTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - } - /** - * Get a subchannel if one already exists with exactly matching parameters. - * Otherwise, create and save a subchannel with those parameters. - * @param channelTarget - * @param subchannelTarget - * @param channelArguments - * @param channelCredentials - */ - getOrCreateSubchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials) { - this.ensureCleanupTask(); - const channelTarget = (0, uri_parser_1.uriToString)(channelTargetUri); - if (channelTarget in this.pool) { - const subchannelObjArray = this.pool[channelTarget]; - for (const subchannelObj of subchannelObjArray) { - if ((0, subchannel_address_1.subchannelAddressEqual)(subchannelTarget, subchannelObj.subchannelAddress) && - (0, channel_options_1.channelOptionsEqual)(channelArguments, subchannelObj.channelArguments) && - channelCredentials._equals(subchannelObj.channelCredentials)) { - return subchannelObj.subchannel; - } - } - } - // If we get here, no matching subchannel was found - const subchannel = new subchannel_1.Subchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials, new transport_1.Http2SubchannelConnector(channelTargetUri)); - if (!(channelTarget in this.pool)) { - this.pool[channelTarget] = []; - } - this.pool[channelTarget].push({ - subchannelAddress: subchannelTarget, - channelArguments, - channelCredentials, - subchannel, - }); - subchannel.ref(); - return subchannel; - } -} -exports.SubchannelPool = SubchannelPool; -const globalSubchannelPool = new SubchannelPool(); -/** - * Get either the global subchannel pool, or a new subchannel pool. - * @param global - */ -function getSubchannelPool(global) { - if (global) { - return globalSubchannelPool; - } - else { - return new SubchannelPool(); - } -} -//# sourceMappingURL=subchannel-pool.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/subchannel.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/subchannel.js deleted file mode 100644 index abdb420a..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/subchannel.js +++ /dev/null @@ -1,397 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Subchannel = void 0; -const connectivity_state_1 = require("./connectivity-state"); -const backoff_timeout_1 = require("./backoff-timeout"); -const logging = require("./logging"); -const constants_1 = require("./constants"); -const uri_parser_1 = require("./uri-parser"); -const subchannel_address_1 = require("./subchannel-address"); -const channelz_1 = require("./channelz"); -const single_subchannel_channel_1 = require("./single-subchannel-channel"); -const TRACER_NAME = 'subchannel'; -/* setInterval and setTimeout only accept signed 32 bit integers. JS doesn't - * have a constant for the max signed 32 bit integer, so this is a simple way - * to calculate it */ -const KEEPALIVE_MAX_TIME_MS = ~(1 << 31); -class Subchannel { - /** - * A class representing a connection to a single backend. - * @param channelTarget The target string for the channel as a whole - * @param subchannelAddress The address for the backend that this subchannel - * will connect to - * @param options The channel options, plus any specific subchannel options - * for this subchannel - * @param credentials The channel credentials used to establish this - * connection - */ - constructor(channelTarget, subchannelAddress, options, credentials, connector) { - var _a; - this.channelTarget = channelTarget; - this.subchannelAddress = subchannelAddress; - this.options = options; - this.connector = connector; - /** - * The subchannel's current connectivity state. Invariant: `session` === `null` - * if and only if `connectivityState` is IDLE or TRANSIENT_FAILURE. - */ - this.connectivityState = connectivity_state_1.ConnectivityState.IDLE; - /** - * The underlying http2 session used to make requests. - */ - this.transport = null; - /** - * Indicates that the subchannel should transition from TRANSIENT_FAILURE to - * CONNECTING instead of IDLE when the backoff timeout ends. - */ - this.continueConnecting = false; - /** - * A list of listener functions that will be called whenever the connectivity - * state changes. Will be modified by `addConnectivityStateListener` and - * `removeConnectivityStateListener` - */ - this.stateListeners = new Set(); - /** - * Tracks channels and subchannel pools with references to this subchannel - */ - this.refcount = 0; - // Channelz info - this.channelzEnabled = true; - this.dataProducers = new Map(); - this.subchannelChannel = null; - const backoffOptions = { - initialDelay: options['grpc.initial_reconnect_backoff_ms'], - maxDelay: options['grpc.max_reconnect_backoff_ms'], - }; - this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => { - this.handleBackoffTimer(); - }, backoffOptions); - this.backoffTimeout.unref(); - this.subchannelAddressString = (0, subchannel_address_1.subchannelAddressToString)(subchannelAddress); - this.keepaliveTime = (_a = options['grpc.keepalive_time_ms']) !== null && _a !== void 0 ? _a : -1; - if (options['grpc.enable_channelz'] === 0) { - this.channelzEnabled = false; - this.channelzTrace = new channelz_1.ChannelzTraceStub(); - this.callTracker = new channelz_1.ChannelzCallTrackerStub(); - this.childrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); - this.streamTracker = new channelz_1.ChannelzCallTrackerStub(); - } - else { - this.channelzTrace = new channelz_1.ChannelzTrace(); - this.callTracker = new channelz_1.ChannelzCallTracker(); - this.childrenTracker = new channelz_1.ChannelzChildrenTracker(); - this.streamTracker = new channelz_1.ChannelzCallTracker(); - } - this.channelzRef = (0, channelz_1.registerChannelzSubchannel)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled); - this.channelzTrace.addTrace('CT_INFO', 'Subchannel created'); - this.trace('Subchannel constructed with options ' + - JSON.stringify(options, undefined, 2)); - this.secureConnector = credentials._createSecureConnector(channelTarget, options); - } - getChannelzInfo() { - return { - state: this.connectivityState, - trace: this.channelzTrace, - callTracker: this.callTracker, - children: this.childrenTracker.getChildLists(), - target: this.subchannelAddressString, - }; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '(' + - this.channelzRef.id + - ') ' + - this.subchannelAddressString + - ' ' + - text); - } - refTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, 'subchannel_refcount', '(' + - this.channelzRef.id + - ') ' + - this.subchannelAddressString + - ' ' + - text); - } - handleBackoffTimer() { - if (this.continueConnecting) { - this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING); - } - else { - this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.IDLE); - } - } - /** - * Start a backoff timer with the current nextBackoff timeout - */ - startBackoff() { - this.backoffTimeout.runOnce(); - } - stopBackoff() { - this.backoffTimeout.stop(); - this.backoffTimeout.reset(); - } - startConnectingInternal() { - let options = this.options; - if (options['grpc.keepalive_time_ms']) { - const adjustedKeepaliveTime = Math.min(this.keepaliveTime, KEEPALIVE_MAX_TIME_MS); - options = Object.assign(Object.assign({}, options), { 'grpc.keepalive_time_ms': adjustedKeepaliveTime }); - } - this.connector - .connect(this.subchannelAddress, this.secureConnector, options) - .then(transport => { - if (this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.READY)) { - this.transport = transport; - if (this.channelzEnabled) { - this.childrenTracker.refChild(transport.getChannelzRef()); - } - transport.addDisconnectListener(tooManyPings => { - this.transitionToState([connectivity_state_1.ConnectivityState.READY], connectivity_state_1.ConnectivityState.IDLE); - if (tooManyPings && this.keepaliveTime > 0) { - this.keepaliveTime *= 2; - logging.log(constants_1.LogVerbosity.ERROR, `Connection to ${(0, uri_parser_1.uriToString)(this.channelTarget)} at ${this.subchannelAddressString} rejected by server because of excess pings. Increasing ping interval to ${this.keepaliveTime} ms`); - } - }); - } - else { - /* If we can't transition from CONNECTING to READY here, we will - * not be using this transport, so release its resources. */ - transport.shutdown(); - } - }, error => { - this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, `${error}`); - }); - } - /** - * Initiate a state transition from any element of oldStates to the new - * state. If the current connectivityState is not in oldStates, do nothing. - * @param oldStates The set of states to transition from - * @param newState The state to transition to - * @returns True if the state changed, false otherwise - */ - transitionToState(oldStates, newState, errorMessage) { - var _a, _b; - if (oldStates.indexOf(this.connectivityState) === -1) { - return false; - } - if (errorMessage) { - this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + - ' -> ' + - connectivity_state_1.ConnectivityState[newState] + - ' with error "' + errorMessage + '"'); - } - else { - this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + - ' -> ' + - connectivity_state_1.ConnectivityState[newState]); - } - if (this.channelzEnabled) { - this.channelzTrace.addTrace('CT_INFO', 'Connectivity state change to ' + connectivity_state_1.ConnectivityState[newState]); - } - const previousState = this.connectivityState; - this.connectivityState = newState; - switch (newState) { - case connectivity_state_1.ConnectivityState.READY: - this.stopBackoff(); - break; - case connectivity_state_1.ConnectivityState.CONNECTING: - this.startBackoff(); - this.startConnectingInternal(); - this.continueConnecting = false; - break; - case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE: - if (this.channelzEnabled && this.transport) { - this.childrenTracker.unrefChild(this.transport.getChannelzRef()); - } - (_a = this.transport) === null || _a === void 0 ? void 0 : _a.shutdown(); - this.transport = null; - /* If the backoff timer has already ended by the time we get to the - * TRANSIENT_FAILURE state, we want to immediately transition out of - * TRANSIENT_FAILURE as though the backoff timer is ending right now */ - if (!this.backoffTimeout.isRunning()) { - process.nextTick(() => { - this.handleBackoffTimer(); - }); - } - break; - case connectivity_state_1.ConnectivityState.IDLE: - if (this.channelzEnabled && this.transport) { - this.childrenTracker.unrefChild(this.transport.getChannelzRef()); - } - (_b = this.transport) === null || _b === void 0 ? void 0 : _b.shutdown(); - this.transport = null; - break; - default: - throw new Error(`Invalid state: unknown ConnectivityState ${newState}`); - } - for (const listener of this.stateListeners) { - listener(this, previousState, newState, this.keepaliveTime, errorMessage); - } - return true; - } - ref() { - this.refTrace('refcount ' + this.refcount + ' -> ' + (this.refcount + 1)); - this.refcount += 1; - } - unref() { - this.refTrace('refcount ' + this.refcount + ' -> ' + (this.refcount - 1)); - this.refcount -= 1; - if (this.refcount === 0) { - this.channelzTrace.addTrace('CT_INFO', 'Shutting down'); - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - this.secureConnector.destroy(); - process.nextTick(() => { - this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING, connectivity_state_1.ConnectivityState.READY], connectivity_state_1.ConnectivityState.IDLE); - }); - } - } - unrefIfOneRef() { - if (this.refcount === 1) { - this.unref(); - return true; - } - return false; - } - createCall(metadata, host, method, listener) { - if (!this.transport) { - throw new Error('Cannot create call, subchannel not READY'); - } - let statsTracker; - if (this.channelzEnabled) { - this.callTracker.addCallStarted(); - this.streamTracker.addCallStarted(); - statsTracker = { - onCallEnd: status => { - if (status.code === constants_1.Status.OK) { - this.callTracker.addCallSucceeded(); - } - else { - this.callTracker.addCallFailed(); - } - }, - }; - } - else { - statsTracker = {}; - } - return this.transport.createCall(metadata, host, method, listener, statsTracker); - } - /** - * If the subchannel is currently IDLE, start connecting and switch to the - * CONNECTING state. If the subchannel is current in TRANSIENT_FAILURE, - * the next time it would transition to IDLE, start connecting again instead. - * Otherwise, do nothing. - */ - startConnecting() { - process.nextTick(() => { - /* First, try to transition from IDLE to connecting. If that doesn't happen - * because the state is not currently IDLE, check if it is - * TRANSIENT_FAILURE, and if so indicate that it should go back to - * connecting after the backoff timer ends. Otherwise do nothing */ - if (!this.transitionToState([connectivity_state_1.ConnectivityState.IDLE], connectivity_state_1.ConnectivityState.CONNECTING)) { - if (this.connectivityState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { - this.continueConnecting = true; - } - } - }); - } - /** - * Get the subchannel's current connectivity state. - */ - getConnectivityState() { - return this.connectivityState; - } - /** - * Add a listener function to be called whenever the subchannel's - * connectivity state changes. - * @param listener - */ - addConnectivityStateListener(listener) { - this.stateListeners.add(listener); - } - /** - * Remove a listener previously added with `addConnectivityStateListener` - * @param listener A reference to a function previously passed to - * `addConnectivityStateListener` - */ - removeConnectivityStateListener(listener) { - this.stateListeners.delete(listener); - } - /** - * Reset the backoff timeout, and immediately start connecting if in backoff. - */ - resetBackoff() { - process.nextTick(() => { - this.backoffTimeout.reset(); - this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING); - }); - } - getAddress() { - return this.subchannelAddressString; - } - getChannelzRef() { - return this.channelzRef; - } - isHealthy() { - return true; - } - addHealthStateWatcher(listener) { - // Do nothing with the listener - } - removeHealthStateWatcher(listener) { - // Do nothing with the listener - } - getRealSubchannel() { - return this; - } - realSubchannelEquals(other) { - return other.getRealSubchannel() === this; - } - throttleKeepalive(newKeepaliveTime) { - if (newKeepaliveTime > this.keepaliveTime) { - this.keepaliveTime = newKeepaliveTime; - } - } - getCallCredentials() { - return this.secureConnector.getCallCredentials(); - } - getChannel() { - if (!this.subchannelChannel) { - this.subchannelChannel = new single_subchannel_channel_1.SingleSubchannelChannel(this, this.channelTarget, this.options); - } - return this.subchannelChannel; - } - addDataWatcher(dataWatcher) { - throw new Error('Not implemented'); - } - getOrCreateDataProducer(name, createDataProducer) { - const existingProducer = this.dataProducers.get(name); - if (existingProducer) { - return existingProducer; - } - const newProducer = createDataProducer(this); - this.dataProducers.set(name, newProducer); - return newProducer; - } - removeDataProducer(name) { - this.dataProducers.delete(name); - } -} -exports.Subchannel = Subchannel; -//# sourceMappingURL=subchannel.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/tls-helpers.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/tls-helpers.js deleted file mode 100644 index 14c521de..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/tls-helpers.js +++ /dev/null @@ -1,34 +0,0 @@ -"use strict"; -/* - * Copyright 2019 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CIPHER_SUITES = void 0; -exports.getDefaultRootsData = getDefaultRootsData; -const fs = require("fs"); -exports.CIPHER_SUITES = process.env.GRPC_SSL_CIPHER_SUITES; -const DEFAULT_ROOTS_FILE_PATH = process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH; -let defaultRootsData = null; -function getDefaultRootsData() { - if (DEFAULT_ROOTS_FILE_PATH) { - if (defaultRootsData === null) { - defaultRootsData = fs.readFileSync(DEFAULT_ROOTS_FILE_PATH); - } - return defaultRootsData; - } - return null; -} -//# sourceMappingURL=tls-helpers.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/transport.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/transport.js deleted file mode 100644 index 4a5cb7ab..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/transport.js +++ /dev/null @@ -1,634 +0,0 @@ -"use strict"; -/* - * Copyright 2023 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Http2SubchannelConnector = void 0; -const http2 = require("http2"); -const tls_1 = require("tls"); -const channelz_1 = require("./channelz"); -const constants_1 = require("./constants"); -const http_proxy_1 = require("./http_proxy"); -const logging = require("./logging"); -const resolver_1 = require("./resolver"); -const subchannel_address_1 = require("./subchannel-address"); -const uri_parser_1 = require("./uri-parser"); -const net = require("net"); -const subchannel_call_1 = require("./subchannel-call"); -const call_number_1 = require("./call-number"); -const TRACER_NAME = 'transport'; -const FLOW_CONTROL_TRACER_NAME = 'transport_flowctrl'; -const clientVersion = require('../../package.json').version; -const { HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_TE, HTTP2_HEADER_USER_AGENT, } = http2.constants; -const KEEPALIVE_TIMEOUT_MS = 20000; -const tooManyPingsData = Buffer.from('too_many_pings', 'ascii'); -class Http2Transport { - constructor(session, subchannelAddress, options, - /** - * Name of the remote server, if it is not the same as the subchannel - * address, i.e. if connecting through an HTTP CONNECT proxy. - */ - remoteName) { - this.session = session; - this.options = options; - this.remoteName = remoteName; - /** - * Timer reference indicating when to send the next ping or when the most recent ping will be considered lost. - */ - this.keepaliveTimer = null; - /** - * Indicates that the keepalive timer ran out while there were no active - * calls, and a ping should be sent the next time a call starts. - */ - this.pendingSendKeepalivePing = false; - this.activeCalls = new Set(); - this.disconnectListeners = []; - this.disconnectHandled = false; - this.channelzEnabled = true; - this.keepalivesSent = 0; - this.messagesSent = 0; - this.messagesReceived = 0; - this.lastMessageSentTimestamp = null; - this.lastMessageReceivedTimestamp = null; - /* Populate subchannelAddressString and channelzRef before doing anything - * else, because they are used in the trace methods. */ - this.subchannelAddressString = (0, subchannel_address_1.subchannelAddressToString)(subchannelAddress); - if (options['grpc.enable_channelz'] === 0) { - this.channelzEnabled = false; - this.streamTracker = new channelz_1.ChannelzCallTrackerStub(); - } - else { - this.streamTracker = new channelz_1.ChannelzCallTracker(); - } - this.channelzRef = (0, channelz_1.registerChannelzSocket)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled); - // Build user-agent string. - this.userAgent = [ - options['grpc.primary_user_agent'], - `grpc-node-js/${clientVersion}`, - options['grpc.secondary_user_agent'], - ] - .filter(e => e) - .join(' '); // remove falsey values first - if ('grpc.keepalive_time_ms' in options) { - this.keepaliveTimeMs = options['grpc.keepalive_time_ms']; - } - else { - this.keepaliveTimeMs = -1; - } - if ('grpc.keepalive_timeout_ms' in options) { - this.keepaliveTimeoutMs = options['grpc.keepalive_timeout_ms']; - } - else { - this.keepaliveTimeoutMs = KEEPALIVE_TIMEOUT_MS; - } - if ('grpc.keepalive_permit_without_calls' in options) { - this.keepaliveWithoutCalls = - options['grpc.keepalive_permit_without_calls'] === 1; - } - else { - this.keepaliveWithoutCalls = false; - } - session.once('close', () => { - this.trace('session closed'); - this.handleDisconnect(); - }); - session.once('goaway', (errorCode, lastStreamID, opaqueData) => { - let tooManyPings = false; - /* See the last paragraph of - * https://github.com/grpc/proposal/blob/master/A8-client-side-keepalive.md#basic-keepalive */ - if (errorCode === http2.constants.NGHTTP2_ENHANCE_YOUR_CALM && - opaqueData && - opaqueData.equals(tooManyPingsData)) { - tooManyPings = true; - } - this.trace('connection closed by GOAWAY with code ' + - errorCode + - ' and data ' + - (opaqueData === null || opaqueData === void 0 ? void 0 : opaqueData.toString())); - this.reportDisconnectToOwner(tooManyPings); - }); - session.once('error', error => { - this.trace('connection closed with error ' + error.message); - this.handleDisconnect(); - }); - session.socket.once('close', (hadError) => { - this.trace('connection closed. hadError=' + hadError); - this.handleDisconnect(); - }); - if (logging.isTracerEnabled(TRACER_NAME)) { - session.on('remoteSettings', (settings) => { - this.trace('new settings received' + - (this.session !== session ? ' on the old connection' : '') + - ': ' + - JSON.stringify(settings)); - }); - session.on('localSettings', (settings) => { - this.trace('local settings acknowledged by remote' + - (this.session !== session ? ' on the old connection' : '') + - ': ' + - JSON.stringify(settings)); - }); - } - /* Start the keepalive timer last, because this can trigger trace logs, - * which should only happen after everything else is set up. */ - if (this.keepaliveWithoutCalls) { - this.maybeStartKeepalivePingTimer(); - } - if (session.socket instanceof tls_1.TLSSocket) { - this.authContext = { - transportSecurityType: 'ssl', - sslPeerCertificate: session.socket.getPeerCertificate() - }; - } - else { - this.authContext = {}; - } - } - getChannelzInfo() { - var _a, _b, _c; - const sessionSocket = this.session.socket; - const remoteAddress = sessionSocket.remoteAddress - ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.remoteAddress, sessionSocket.remotePort) - : null; - const localAddress = sessionSocket.localAddress - ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.localAddress, sessionSocket.localPort) - : null; - let tlsInfo; - if (this.session.encrypted) { - const tlsSocket = sessionSocket; - const cipherInfo = tlsSocket.getCipher(); - const certificate = tlsSocket.getCertificate(); - const peerCertificate = tlsSocket.getPeerCertificate(); - tlsInfo = { - cipherSuiteStandardName: (_a = cipherInfo.standardName) !== null && _a !== void 0 ? _a : null, - cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, - localCertificate: certificate && 'raw' in certificate ? certificate.raw : null, - remoteCertificate: peerCertificate && 'raw' in peerCertificate - ? peerCertificate.raw - : null, - }; - } - else { - tlsInfo = null; - } - const socketInfo = { - remoteAddress: remoteAddress, - localAddress: localAddress, - security: tlsInfo, - remoteName: this.remoteName, - streamsStarted: this.streamTracker.callsStarted, - streamsSucceeded: this.streamTracker.callsSucceeded, - streamsFailed: this.streamTracker.callsFailed, - messagesSent: this.messagesSent, - messagesReceived: this.messagesReceived, - keepAlivesSent: this.keepalivesSent, - lastLocalStreamCreatedTimestamp: this.streamTracker.lastCallStartedTimestamp, - lastRemoteStreamCreatedTimestamp: null, - lastMessageSentTimestamp: this.lastMessageSentTimestamp, - lastMessageReceivedTimestamp: this.lastMessageReceivedTimestamp, - localFlowControlWindow: (_b = this.session.state.localWindowSize) !== null && _b !== void 0 ? _b : null, - remoteFlowControlWindow: (_c = this.session.state.remoteWindowSize) !== null && _c !== void 0 ? _c : null, - }; - return socketInfo; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '(' + - this.channelzRef.id + - ') ' + - this.subchannelAddressString + - ' ' + - text); - } - keepaliveTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, 'keepalive', '(' + - this.channelzRef.id + - ') ' + - this.subchannelAddressString + - ' ' + - text); - } - flowControlTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, FLOW_CONTROL_TRACER_NAME, '(' + - this.channelzRef.id + - ') ' + - this.subchannelAddressString + - ' ' + - text); - } - internalsTrace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, 'transport_internals', '(' + - this.channelzRef.id + - ') ' + - this.subchannelAddressString + - ' ' + - text); - } - /** - * Indicate to the owner of this object that this transport should no longer - * be used. That happens if the connection drops, or if the server sends a - * GOAWAY. - * @param tooManyPings If true, this was triggered by a GOAWAY with data - * indicating that the session was closed becaues the client sent too many - * pings. - * @returns - */ - reportDisconnectToOwner(tooManyPings) { - if (this.disconnectHandled) { - return; - } - this.disconnectHandled = true; - this.disconnectListeners.forEach(listener => listener(tooManyPings)); - } - /** - * Handle connection drops, but not GOAWAYs. - */ - handleDisconnect() { - this.clearKeepaliveTimeout(); - this.reportDisconnectToOwner(false); - for (const call of this.activeCalls) { - call.onDisconnect(); - } - // Wait an event loop cycle before destroying the connection - setImmediate(() => { - this.session.destroy(); - }); - } - addDisconnectListener(listener) { - this.disconnectListeners.push(listener); - } - canSendPing() { - return (!this.session.destroyed && - this.keepaliveTimeMs > 0 && - (this.keepaliveWithoutCalls || this.activeCalls.size > 0)); - } - maybeSendPing() { - var _a, _b; - if (!this.canSendPing()) { - this.pendingSendKeepalivePing = true; - return; - } - if (this.keepaliveTimer) { - console.error('keepaliveTimeout is not null'); - return; - } - if (this.channelzEnabled) { - this.keepalivesSent += 1; - } - this.keepaliveTrace('Sending ping with timeout ' + this.keepaliveTimeoutMs + 'ms'); - this.keepaliveTimer = setTimeout(() => { - this.keepaliveTimer = null; - this.keepaliveTrace('Ping timeout passed without response'); - this.handleDisconnect(); - }, this.keepaliveTimeoutMs); - (_b = (_a = this.keepaliveTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - let pingSendError = ''; - try { - const pingSentSuccessfully = this.session.ping((err, duration, payload) => { - this.clearKeepaliveTimeout(); - if (err) { - this.keepaliveTrace('Ping failed with error ' + err.message); - this.handleDisconnect(); - } - else { - this.keepaliveTrace('Received ping response'); - this.maybeStartKeepalivePingTimer(); - } - }); - if (!pingSentSuccessfully) { - pingSendError = 'Ping returned false'; - } - } - catch (e) { - // grpc/grpc-node#2139 - pingSendError = (e instanceof Error ? e.message : '') || 'Unknown error'; - } - if (pingSendError) { - this.keepaliveTrace('Ping send failed: ' + pingSendError); - this.handleDisconnect(); - } - } - /** - * Starts the keepalive ping timer if appropriate. If the timer already ran - * out while there were no active requests, instead send a ping immediately. - * If the ping timer is already running or a ping is currently in flight, - * instead do nothing and wait for them to resolve. - */ - maybeStartKeepalivePingTimer() { - var _a, _b; - if (!this.canSendPing()) { - return; - } - if (this.pendingSendKeepalivePing) { - this.pendingSendKeepalivePing = false; - this.maybeSendPing(); - } - else if (!this.keepaliveTimer) { - this.keepaliveTrace('Starting keepalive timer for ' + this.keepaliveTimeMs + 'ms'); - this.keepaliveTimer = setTimeout(() => { - this.keepaliveTimer = null; - this.maybeSendPing(); - }, this.keepaliveTimeMs); - (_b = (_a = this.keepaliveTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); - } - /* Otherwise, there is already either a keepalive timer or a ping pending, - * wait for those to resolve. */ - } - /** - * Clears whichever keepalive timeout is currently active, if any. - */ - clearKeepaliveTimeout() { - if (this.keepaliveTimer) { - clearTimeout(this.keepaliveTimer); - this.keepaliveTimer = null; - } - } - removeActiveCall(call) { - this.activeCalls.delete(call); - if (this.activeCalls.size === 0) { - this.session.unref(); - } - } - addActiveCall(call) { - this.activeCalls.add(call); - if (this.activeCalls.size === 1) { - this.session.ref(); - if (!this.keepaliveWithoutCalls) { - this.maybeStartKeepalivePingTimer(); - } - } - } - createCall(metadata, host, method, listener, subchannelCallStatsTracker) { - const headers = metadata.toHttp2Headers(); - headers[HTTP2_HEADER_AUTHORITY] = host; - headers[HTTP2_HEADER_USER_AGENT] = this.userAgent; - headers[HTTP2_HEADER_CONTENT_TYPE] = 'application/grpc'; - headers[HTTP2_HEADER_METHOD] = 'POST'; - headers[HTTP2_HEADER_PATH] = method; - headers[HTTP2_HEADER_TE] = 'trailers'; - let http2Stream; - /* In theory, if an error is thrown by session.request because session has - * become unusable (e.g. because it has received a goaway), this subchannel - * should soon see the corresponding close or goaway event anyway and leave - * READY. But we have seen reports that this does not happen - * (https://github.com/googleapis/nodejs-firestore/issues/1023#issuecomment-653204096) - * so for defense in depth, we just discard the session when we see an - * error here. - */ - try { - http2Stream = this.session.request(headers); - } - catch (e) { - this.handleDisconnect(); - throw e; - } - this.flowControlTrace('local window size: ' + - this.session.state.localWindowSize + - ' remote window size: ' + - this.session.state.remoteWindowSize); - this.internalsTrace('session.closed=' + - this.session.closed + - ' session.destroyed=' + - this.session.destroyed + - ' session.socket.destroyed=' + - this.session.socket.destroyed); - let eventTracker; - // eslint-disable-next-line prefer-const - let call; - if (this.channelzEnabled) { - this.streamTracker.addCallStarted(); - eventTracker = { - addMessageSent: () => { - var _a; - this.messagesSent += 1; - this.lastMessageSentTimestamp = new Date(); - (_a = subchannelCallStatsTracker.addMessageSent) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); - }, - addMessageReceived: () => { - var _a; - this.messagesReceived += 1; - this.lastMessageReceivedTimestamp = new Date(); - (_a = subchannelCallStatsTracker.addMessageReceived) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); - }, - onCallEnd: status => { - var _a; - (_a = subchannelCallStatsTracker.onCallEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, status); - this.removeActiveCall(call); - }, - onStreamEnd: success => { - var _a; - if (success) { - this.streamTracker.addCallSucceeded(); - } - else { - this.streamTracker.addCallFailed(); - } - (_a = subchannelCallStatsTracker.onStreamEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, success); - }, - }; - } - else { - eventTracker = { - addMessageSent: () => { - var _a; - (_a = subchannelCallStatsTracker.addMessageSent) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); - }, - addMessageReceived: () => { - var _a; - (_a = subchannelCallStatsTracker.addMessageReceived) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); - }, - onCallEnd: status => { - var _a; - (_a = subchannelCallStatsTracker.onCallEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, status); - this.removeActiveCall(call); - }, - onStreamEnd: success => { - var _a; - (_a = subchannelCallStatsTracker.onStreamEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, success); - }, - }; - } - call = new subchannel_call_1.Http2SubchannelCall(http2Stream, eventTracker, listener, this, (0, call_number_1.getNextCallNumber)()); - this.addActiveCall(call); - return call; - } - getChannelzRef() { - return this.channelzRef; - } - getPeerName() { - return this.subchannelAddressString; - } - getOptions() { - return this.options; - } - getAuthContext() { - return this.authContext; - } - shutdown() { - this.session.close(); - (0, channelz_1.unregisterChannelzRef)(this.channelzRef); - } -} -class Http2SubchannelConnector { - constructor(channelTarget) { - this.channelTarget = channelTarget; - this.session = null; - this.isShutdown = false; - } - trace(text) { - logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, (0, uri_parser_1.uriToString)(this.channelTarget) + ' ' + text); - } - createSession(secureConnectResult, address, options) { - if (this.isShutdown) { - return Promise.reject(); - } - if (secureConnectResult.socket.closed) { - return Promise.reject('Connection closed before starting HTTP/2 handshake'); - } - return new Promise((resolve, reject) => { - var _a, _b, _c, _d, _e, _f, _g; - let remoteName = null; - let realTarget = this.channelTarget; - if ('grpc.http_connect_target' in options) { - const parsedTarget = (0, uri_parser_1.parseUri)(options['grpc.http_connect_target']); - if (parsedTarget) { - realTarget = parsedTarget; - remoteName = (0, uri_parser_1.uriToString)(parsedTarget); - } - } - const scheme = secureConnectResult.secure ? 'https' : 'http'; - const targetPath = (0, resolver_1.getDefaultAuthority)(realTarget); - const closeHandler = () => { - var _a; - (_a = this.session) === null || _a === void 0 ? void 0 : _a.destroy(); - this.session = null; - // Leave time for error event to happen before rejecting - setImmediate(() => { - if (!reportedError) { - reportedError = true; - reject(`${errorMessage.trim()} (${new Date().toISOString()})`); - } - }); - }; - const errorHandler = (error) => { - var _a; - (_a = this.session) === null || _a === void 0 ? void 0 : _a.destroy(); - errorMessage = error.message; - this.trace('connection failed with error ' + errorMessage); - if (!reportedError) { - reportedError = true; - reject(`${errorMessage} (${new Date().toISOString()})`); - } - }; - const sessionOptions = { - createConnection: (authority, option) => { - return secureConnectResult.socket; - }, - settings: { - initialWindowSize: (_d = (_a = options['grpc-node.flow_control_window']) !== null && _a !== void 0 ? _a : (_c = (_b = http2.getDefaultSettings) === null || _b === void 0 ? void 0 : _b.call(http2)) === null || _c === void 0 ? void 0 : _c.initialWindowSize) !== null && _d !== void 0 ? _d : 65535, - } - }; - const session = http2.connect(`${scheme}://${targetPath}`, sessionOptions); - // Prepare window size configuration for remoteSettings handler - const defaultWin = (_g = (_f = (_e = http2.getDefaultSettings) === null || _e === void 0 ? void 0 : _e.call(http2)) === null || _f === void 0 ? void 0 : _f.initialWindowSize) !== null && _g !== void 0 ? _g : 65535; // 65 535 B - const connWin = options['grpc-node.flow_control_window']; - this.session = session; - let errorMessage = 'Failed to connect'; - let reportedError = false; - session.unref(); - session.once('remoteSettings', () => { - var _a; - // Send WINDOW_UPDATE now to avoid 65 KB start-window stall. - if (connWin && connWin > defaultWin) { - try { - // Node ≥ 14.18 - session.setLocalWindowSize(connWin); - } - catch (_b) { - // Older Node: bump by the delta - const delta = connWin - ((_a = session.state.localWindowSize) !== null && _a !== void 0 ? _a : defaultWin); - if (delta > 0) - session.incrementWindowSize(delta); - } - } - session.removeAllListeners(); - secureConnectResult.socket.removeListener('close', closeHandler); - secureConnectResult.socket.removeListener('error', errorHandler); - resolve(new Http2Transport(session, address, options, remoteName)); - this.session = null; - }); - session.once('close', closeHandler); - session.once('error', errorHandler); - secureConnectResult.socket.once('close', closeHandler); - secureConnectResult.socket.once('error', errorHandler); - }); - } - tcpConnect(address, options) { - return (0, http_proxy_1.getProxiedConnection)(address, options).then(proxiedSocket => { - if (proxiedSocket) { - return proxiedSocket; - } - else { - return new Promise((resolve, reject) => { - const closeCallback = () => { - reject(new Error('Socket closed')); - }; - const errorCallback = (error) => { - reject(error); - }; - const socket = net.connect(address, () => { - socket.removeListener('close', closeCallback); - socket.removeListener('error', errorCallback); - resolve(socket); - }); - socket.once('close', closeCallback); - socket.once('error', errorCallback); - }); - } - }); - } - async connect(address, secureConnector, options) { - if (this.isShutdown) { - return Promise.reject(); - } - let tcpConnection = null; - let secureConnectResult = null; - const addressString = (0, subchannel_address_1.subchannelAddressToString)(address); - try { - this.trace(addressString + ' Waiting for secureConnector to be ready'); - await secureConnector.waitForReady(); - this.trace(addressString + ' secureConnector is ready'); - tcpConnection = await this.tcpConnect(address, options); - tcpConnection.setNoDelay(); - this.trace(addressString + ' Established TCP connection'); - secureConnectResult = await secureConnector.connect(tcpConnection); - this.trace(addressString + ' Established secure connection'); - return this.createSession(secureConnectResult, address, options); - } - catch (e) { - tcpConnection === null || tcpConnection === void 0 ? void 0 : tcpConnection.destroy(); - secureConnectResult === null || secureConnectResult === void 0 ? void 0 : secureConnectResult.socket.destroy(); - throw e; - } - } - shutdown() { - var _a; - this.isShutdown = true; - (_a = this.session) === null || _a === void 0 ? void 0 : _a.close(); - this.session = null; - } -} -exports.Http2SubchannelConnector = Http2SubchannelConnector; -//# sourceMappingURL=transport.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/grpc-js/build/src/uri-parser.js b/claude-code-source/node_modules/@grpc/grpc-js/build/src/uri-parser.js deleted file mode 100644 index 5b4e6d53..00000000 --- a/claude-code-source/node_modules/@grpc/grpc-js/build/src/uri-parser.js +++ /dev/null @@ -1,125 +0,0 @@ -"use strict"; -/* - * Copyright 2020 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.parseUri = parseUri; -exports.splitHostPort = splitHostPort; -exports.combineHostPort = combineHostPort; -exports.uriToString = uriToString; -/* - * The groups correspond to URI parts as follows: - * 1. scheme - * 2. authority - * 3. path - */ -const URI_REGEX = /^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/; -function parseUri(uriString) { - const parsedUri = URI_REGEX.exec(uriString); - if (parsedUri === null) { - return null; - } - return { - scheme: parsedUri[1], - authority: parsedUri[2], - path: parsedUri[3], - }; -} -const NUMBER_REGEX = /^\d+$/; -function splitHostPort(path) { - if (path.startsWith('[')) { - const hostEnd = path.indexOf(']'); - if (hostEnd === -1) { - return null; - } - const host = path.substring(1, hostEnd); - /* Only an IPv6 address should be in bracketed notation, and an IPv6 - * address should have at least one colon */ - if (host.indexOf(':') === -1) { - return null; - } - if (path.length > hostEnd + 1) { - if (path[hostEnd + 1] === ':') { - const portString = path.substring(hostEnd + 2); - if (NUMBER_REGEX.test(portString)) { - return { - host: host, - port: +portString, - }; - } - else { - return null; - } - } - else { - return null; - } - } - else { - return { - host, - }; - } - } - else { - const splitPath = path.split(':'); - /* Exactly one colon means that this is host:port. Zero colons means that - * there is no port. And multiple colons means that this is a bare IPv6 - * address with no port */ - if (splitPath.length === 2) { - if (NUMBER_REGEX.test(splitPath[1])) { - return { - host: splitPath[0], - port: +splitPath[1], - }; - } - else { - return null; - } - } - else { - return { - host: path, - }; - } - } -} -function combineHostPort(hostPort) { - if (hostPort.port === undefined) { - return hostPort.host; - } - else { - // Only an IPv6 host should include a colon - if (hostPort.host.includes(':')) { - return `[${hostPort.host}]:${hostPort.port}`; - } - else { - return `${hostPort.host}:${hostPort.port}`; - } - } -} -function uriToString(uri) { - let result = ''; - if (uri.scheme !== undefined) { - result += uri.scheme + ':'; - } - if (uri.authority !== undefined) { - result += '//' + uri.authority + '/'; - } - result += uri.path; - return result; -} -//# sourceMappingURL=uri-parser.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/proto-loader/build/src/index.js b/claude-code-source/node_modules/@grpc/proto-loader/build/src/index.js deleted file mode 100644 index 69b4431c..00000000 --- a/claude-code-source/node_modules/@grpc/proto-loader/build/src/index.js +++ /dev/null @@ -1,246 +0,0 @@ -"use strict"; -/** - * @license - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.loadFileDescriptorSetFromObject = exports.loadFileDescriptorSetFromBuffer = exports.fromJSON = exports.loadSync = exports.load = exports.IdempotencyLevel = exports.isAnyExtension = exports.Long = void 0; -const camelCase = require("lodash.camelcase"); -const Protobuf = require("protobufjs"); -const descriptor = require("protobufjs/ext/descriptor"); -const util_1 = require("./util"); -const Long = require("long"); -exports.Long = Long; -function isAnyExtension(obj) { - return ('@type' in obj) && (typeof obj['@type'] === 'string'); -} -exports.isAnyExtension = isAnyExtension; -var IdempotencyLevel; -(function (IdempotencyLevel) { - IdempotencyLevel["IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN"; - IdempotencyLevel["NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS"; - IdempotencyLevel["IDEMPOTENT"] = "IDEMPOTENT"; -})(IdempotencyLevel = exports.IdempotencyLevel || (exports.IdempotencyLevel = {})); -const descriptorOptions = { - longs: String, - enums: String, - bytes: String, - defaults: true, - oneofs: true, - json: true, -}; -function joinName(baseName, name) { - if (baseName === '') { - return name; - } - else { - return baseName + '.' + name; - } -} -function isHandledReflectionObject(obj) { - return (obj instanceof Protobuf.Service || - obj instanceof Protobuf.Type || - obj instanceof Protobuf.Enum); -} -function isNamespaceBase(obj) { - return obj instanceof Protobuf.Namespace || obj instanceof Protobuf.Root; -} -function getAllHandledReflectionObjects(obj, parentName) { - const objName = joinName(parentName, obj.name); - if (isHandledReflectionObject(obj)) { - return [[objName, obj]]; - } - else { - if (isNamespaceBase(obj) && typeof obj.nested !== 'undefined') { - return Object.keys(obj.nested) - .map(name => { - return getAllHandledReflectionObjects(obj.nested[name], objName); - }) - .reduce((accumulator, currentValue) => accumulator.concat(currentValue), []); - } - } - return []; -} -function createDeserializer(cls, options) { - return function deserialize(argBuf) { - return cls.toObject(cls.decode(argBuf), options); - }; -} -function createSerializer(cls) { - return function serialize(arg) { - if (Array.isArray(arg)) { - throw new Error(`Failed to serialize message: expected object with ${cls.name} structure, got array instead`); - } - const message = cls.fromObject(arg); - return cls.encode(message).finish(); - }; -} -function mapMethodOptions(options) { - return (options || []).reduce((obj, item) => { - for (const [key, value] of Object.entries(item)) { - switch (key) { - case 'uninterpreted_option': - obj.uninterpreted_option.push(item.uninterpreted_option); - break; - default: - obj[key] = value; - } - } - return obj; - }, { - deprecated: false, - idempotency_level: IdempotencyLevel.IDEMPOTENCY_UNKNOWN, - uninterpreted_option: [], - }); -} -function createMethodDefinition(method, serviceName, options, fileDescriptors) { - /* This is only ever called after the corresponding root.resolveAll(), so we - * can assume that the resolved request and response types are non-null */ - const requestType = method.resolvedRequestType; - const responseType = method.resolvedResponseType; - return { - path: '/' + serviceName + '/' + method.name, - requestStream: !!method.requestStream, - responseStream: !!method.responseStream, - requestSerialize: createSerializer(requestType), - requestDeserialize: createDeserializer(requestType, options), - responseSerialize: createSerializer(responseType), - responseDeserialize: createDeserializer(responseType, options), - // TODO(murgatroid99): Find a better way to handle this - originalName: camelCase(method.name), - requestType: createMessageDefinition(requestType, options, fileDescriptors), - responseType: createMessageDefinition(responseType, options, fileDescriptors), - options: mapMethodOptions(method.parsedOptions), - }; -} -function createServiceDefinition(service, name, options, fileDescriptors) { - const def = {}; - for (const method of service.methodsArray) { - def[method.name] = createMethodDefinition(method, name, options, fileDescriptors); - } - return def; -} -function createMessageDefinition(message, options, fileDescriptors) { - const messageDescriptor = message.toDescriptor('proto3'); - return { - format: 'Protocol Buffer 3 DescriptorProto', - type: messageDescriptor.$type.toObject(messageDescriptor, descriptorOptions), - fileDescriptorProtos: fileDescriptors, - serialize: createSerializer(message), - deserialize: createDeserializer(message, options) - }; -} -function createEnumDefinition(enumType, fileDescriptors) { - const enumDescriptor = enumType.toDescriptor('proto3'); - return { - format: 'Protocol Buffer 3 EnumDescriptorProto', - type: enumDescriptor.$type.toObject(enumDescriptor, descriptorOptions), - fileDescriptorProtos: fileDescriptors, - }; -} -/** - * function createDefinition(obj: Protobuf.Service, name: string, options: - * Options): ServiceDefinition; function createDefinition(obj: Protobuf.Type, - * name: string, options: Options): MessageTypeDefinition; function - * createDefinition(obj: Protobuf.Enum, name: string, options: Options): - * EnumTypeDefinition; - */ -function createDefinition(obj, name, options, fileDescriptors) { - if (obj instanceof Protobuf.Service) { - return createServiceDefinition(obj, name, options, fileDescriptors); - } - else if (obj instanceof Protobuf.Type) { - return createMessageDefinition(obj, options, fileDescriptors); - } - else if (obj instanceof Protobuf.Enum) { - return createEnumDefinition(obj, fileDescriptors); - } - else { - throw new Error('Type mismatch in reflection object handling'); - } -} -function createPackageDefinition(root, options) { - const def = {}; - root.resolveAll(); - const descriptorList = root.toDescriptor('proto3').file; - const bufferList = descriptorList.map(value => Buffer.from(descriptor.FileDescriptorProto.encode(value).finish())); - for (const [name, obj] of getAllHandledReflectionObjects(root, '')) { - def[name] = createDefinition(obj, name, options, bufferList); - } - return def; -} -function createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options) { - options = options || {}; - const root = Protobuf.Root.fromDescriptor(decodedDescriptorSet); - root.resolveAll(); - return createPackageDefinition(root, options); -} -/** - * Load a .proto file with the specified options. - * @param filename One or multiple file paths to load. Can be an absolute path - * or relative to an include path. - * @param options.keepCase Preserve field names. The default is to change them - * to camel case. - * @param options.longs The type that should be used to represent `long` values. - * Valid options are `Number` and `String`. Defaults to a `Long` object type - * from a library. - * @param options.enums The type that should be used to represent `enum` values. - * The only valid option is `String`. Defaults to the numeric value. - * @param options.bytes The type that should be used to represent `bytes` - * values. Valid options are `Array` and `String`. The default is to use - * `Buffer`. - * @param options.defaults Set default values on output objects. Defaults to - * `false`. - * @param options.arrays Set empty arrays for missing array values even if - * `defaults` is `false`. Defaults to `false`. - * @param options.objects Set empty objects for missing object values even if - * `defaults` is `false`. Defaults to `false`. - * @param options.oneofs Set virtual oneof properties to the present field's - * name - * @param options.json Represent Infinity and NaN as strings in float fields, - * and automatically decode google.protobuf.Any values. - * @param options.includeDirs Paths to search for imported `.proto` files. - */ -function load(filename, options) { - return (0, util_1.loadProtosWithOptions)(filename, options).then(loadedRoot => { - return createPackageDefinition(loadedRoot, options); - }); -} -exports.load = load; -function loadSync(filename, options) { - const loadedRoot = (0, util_1.loadProtosWithOptionsSync)(filename, options); - return createPackageDefinition(loadedRoot, options); -} -exports.loadSync = loadSync; -function fromJSON(json, options) { - options = options || {}; - const loadedRoot = Protobuf.Root.fromJSON(json); - loadedRoot.resolveAll(); - return createPackageDefinition(loadedRoot, options); -} -exports.fromJSON = fromJSON; -function loadFileDescriptorSetFromBuffer(descriptorSet, options) { - const decodedDescriptorSet = descriptor.FileDescriptorSet.decode(descriptorSet); - return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); -} -exports.loadFileDescriptorSetFromBuffer = loadFileDescriptorSetFromBuffer; -function loadFileDescriptorSetFromObject(descriptorSet, options) { - const decodedDescriptorSet = descriptor.FileDescriptorSet.fromObject(descriptorSet); - return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); -} -exports.loadFileDescriptorSetFromObject = loadFileDescriptorSetFromObject; -(0, util_1.addCommonProtos)(); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/proto-loader/build/src/util.js b/claude-code-source/node_modules/@grpc/proto-loader/build/src/util.js deleted file mode 100644 index 7ade36b6..00000000 --- a/claude-code-source/node_modules/@grpc/proto-loader/build/src/util.js +++ /dev/null @@ -1,89 +0,0 @@ -"use strict"; -/** - * @license - * Copyright 2018 gRPC authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.addCommonProtos = exports.loadProtosWithOptionsSync = exports.loadProtosWithOptions = void 0; -const fs = require("fs"); -const path = require("path"); -const Protobuf = require("protobufjs"); -function addIncludePathResolver(root, includePaths) { - const originalResolvePath = root.resolvePath; - root.resolvePath = (origin, target) => { - if (path.isAbsolute(target)) { - return target; - } - for (const directory of includePaths) { - const fullPath = path.join(directory, target); - try { - fs.accessSync(fullPath, fs.constants.R_OK); - return fullPath; - } - catch (err) { - continue; - } - } - process.emitWarning(`${target} not found in any of the include paths ${includePaths}`); - return originalResolvePath(origin, target); - }; -} -async function loadProtosWithOptions(filename, options) { - const root = new Protobuf.Root(); - options = options || {}; - if (!!options.includeDirs) { - if (!Array.isArray(options.includeDirs)) { - return Promise.reject(new Error('The includeDirs option must be an array')); - } - addIncludePathResolver(root, options.includeDirs); - } - const loadedRoot = await root.load(filename, options); - loadedRoot.resolveAll(); - return loadedRoot; -} -exports.loadProtosWithOptions = loadProtosWithOptions; -function loadProtosWithOptionsSync(filename, options) { - const root = new Protobuf.Root(); - options = options || {}; - if (!!options.includeDirs) { - if (!Array.isArray(options.includeDirs)) { - throw new Error('The includeDirs option must be an array'); - } - addIncludePathResolver(root, options.includeDirs); - } - const loadedRoot = root.loadSync(filename, options); - loadedRoot.resolveAll(); - return loadedRoot; -} -exports.loadProtosWithOptionsSync = loadProtosWithOptionsSync; -/** - * Load Google's well-known proto files that aren't exposed by Protobuf.js. - */ -function addCommonProtos() { - // Protobuf.js exposes: any, duration, empty, field_mask, struct, timestamp, - // and wrappers. compiler/plugin is excluded in Protobuf.js and here. - // Using constant strings for compatibility with tools like Webpack - const apiDescriptor = require('protobufjs/google/protobuf/api.json'); - const descriptorDescriptor = require('protobufjs/google/protobuf/descriptor.json'); - const sourceContextDescriptor = require('protobufjs/google/protobuf/source_context.json'); - const typeDescriptor = require('protobufjs/google/protobuf/type.json'); - Protobuf.common('api', apiDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common('descriptor', descriptorDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common('source_context', sourceContextDescriptor.nested.google.nested.protobuf.nested); - Protobuf.common('type', typeDescriptor.nested.google.nested.protobuf.nested); -} -exports.addCommonProtos = addCommonProtos; -//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@grpc/proto-loader/node_modules/long/umd/index.js b/claude-code-source/node_modules/@grpc/proto-loader/node_modules/long/umd/index.js deleted file mode 100644 index 8351d62a..00000000 --- a/claude-code-source/node_modules/@grpc/proto-loader/node_modules/long/umd/index.js +++ /dev/null @@ -1,1622 +0,0 @@ -// GENERATED FILE. DO NOT EDIT. -(function (global, factory) { - function unwrapDefault(exports) { - return "default" in exports ? exports.default : exports; - } - if (typeof define === "function" && define.amd) { - define([], function () { - var exports = {}; - factory(exports); - return unwrapDefault(exports); - }); - } else if (typeof exports === "object") { - factory(exports); - if (typeof module === "object") module.exports = unwrapDefault(exports); - } else { - (function () { - var exports = {}; - factory(exports); - global.Long = unwrapDefault(exports); - })(); - } -})( - typeof globalThis !== "undefined" - ? globalThis - : typeof self !== "undefined" - ? self - : this, - function (_exports) { - "use strict"; - - Object.defineProperty(_exports, "__esModule", { - value: true, - }); - _exports.default = void 0; - /** - * @license - * Copyright 2009 The Closure Library Authors - * Copyright 2020 Daniel Wirtz / The long.js Authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - */ - - // WebAssembly optimizations to do native i64 multiplication and divide - var wasm = null; - try { - wasm = new WebAssembly.Instance( - new WebAssembly.Module( - new Uint8Array([ - // \0asm - 0, 97, 115, 109, - // version 1 - 1, 0, 0, 0, - // section "type" - 1, 13, 2, - // 0, () => i32 - 96, 0, 1, 127, - // 1, (i32, i32, i32, i32) => i32 - 96, 4, 127, 127, 127, 127, 1, 127, - // section "function" - 3, 7, 6, - // 0, type 0 - 0, - // 1, type 1 - 1, - // 2, type 1 - 1, - // 3, type 1 - 1, - // 4, type 1 - 1, - // 5, type 1 - 1, - // section "global" - 6, 6, 1, - // 0, "high", mutable i32 - 127, 1, 65, 0, 11, - // section "export" - 7, 50, 6, - // 0, "mul" - 3, 109, 117, 108, 0, 1, - // 1, "div_s" - 5, 100, 105, 118, 95, 115, 0, 2, - // 2, "div_u" - 5, 100, 105, 118, 95, 117, 0, 3, - // 3, "rem_s" - 5, 114, 101, 109, 95, 115, 0, 4, - // 4, "rem_u" - 5, 114, 101, 109, 95, 117, 0, 5, - // 5, "get_high" - 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, - // section "code" - 10, 191, 1, 6, - // 0, "get_high" - 4, 0, 35, 0, 11, - // 1, "mul" - 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, - 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, - 32, 4, 167, 11, - // 2, "div_s" - 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, - 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, - 32, 4, 167, 11, - // 3, "div_u" - 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, - 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, - 32, 4, 167, 11, - // 4, "rem_s" - 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, - 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, - 32, 4, 167, 11, - // 5, "rem_u" - 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, - 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, - 32, 4, 167, 11, - ]), - ), - {}, - ).exports; - } catch { - // no wasm support :( - } - - /** - * Constructs a 64 bit two's-complement integer, given its low and high 32 bit values as *signed* integers. - * See the from* functions below for more convenient ways of constructing Longs. - * @exports Long - * @class A Long class for representing a 64 bit two's-complement integer value. - * @param {number} low The low (signed) 32 bits of the long - * @param {number} high The high (signed) 32 bits of the long - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @constructor - */ - function Long(low, high, unsigned) { - /** - * The low 32 bits as a signed value. - * @type {number} - */ - this.low = low | 0; - - /** - * The high 32 bits as a signed value. - * @type {number} - */ - this.high = high | 0; - - /** - * Whether unsigned or not. - * @type {boolean} - */ - this.unsigned = !!unsigned; - } - - // The internal representation of a long is the two given signed, 32-bit values. - // We use 32-bit pieces because these are the size of integers on which - // Javascript performs bit-operations. For operations like addition and - // multiplication, we split each number into 16 bit pieces, which can easily be - // multiplied within Javascript's floating-point representation without overflow - // or change in sign. - // - // In the algorithms below, we frequently reduce the negative case to the - // positive case by negating the input(s) and then post-processing the result. - // Note that we must ALWAYS check specially whether those values are MIN_VALUE - // (-2^63) because -MIN_VALUE == MIN_VALUE (since 2^63 cannot be represented as - // a positive number, it overflows back into a negative). Not handling this - // case would often result in infinite recursion. - // - // Common constant values ZERO, ONE, NEG_ONE, etc. are defined below the from* - // methods on which they depend. - - /** - * An indicator used to reliably determine if an object is a Long or not. - * @type {boolean} - * @const - * @private - */ - Long.prototype.__isLong__; - Object.defineProperty(Long.prototype, "__isLong__", { - value: true, - }); - - /** - * @function - * @param {*} obj Object - * @returns {boolean} - * @inner - */ - function isLong(obj) { - return (obj && obj["__isLong__"]) === true; - } - - /** - * @function - * @param {*} value number - * @returns {number} - * @inner - */ - function ctz32(value) { - var c = Math.clz32(value & -value); - return value ? 31 - c : c; - } - - /** - * Tests if the specified object is a Long. - * @function - * @param {*} obj Object - * @returns {boolean} - */ - Long.isLong = isLong; - - /** - * A cache of the Long representations of small integer values. - * @type {!Object} - * @inner - */ - var INT_CACHE = {}; - - /** - * A cache of the Long representations of small unsigned integer values. - * @type {!Object} - * @inner - */ - var UINT_CACHE = {}; - - /** - * @param {number} value - * @param {boolean=} unsigned - * @returns {!Long} - * @inner - */ - function fromInt(value, unsigned) { - var obj, cachedObj, cache; - if (unsigned) { - value >>>= 0; - if ((cache = 0 <= value && value < 256)) { - cachedObj = UINT_CACHE[value]; - if (cachedObj) return cachedObj; - } - obj = fromBits(value, 0, true); - if (cache) UINT_CACHE[value] = obj; - return obj; - } else { - value |= 0; - if ((cache = -128 <= value && value < 128)) { - cachedObj = INT_CACHE[value]; - if (cachedObj) return cachedObj; - } - obj = fromBits(value, value < 0 ? -1 : 0, false); - if (cache) INT_CACHE[value] = obj; - return obj; - } - } - - /** - * Returns a Long representing the given 32 bit integer value. - * @function - * @param {number} value The 32 bit integer in question - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {!Long} The corresponding Long value - */ - Long.fromInt = fromInt; - - /** - * @param {number} value - * @param {boolean=} unsigned - * @returns {!Long} - * @inner - */ - function fromNumber(value, unsigned) { - if (isNaN(value)) return unsigned ? UZERO : ZERO; - if (unsigned) { - if (value < 0) return UZERO; - if (value >= TWO_PWR_64_DBL) return MAX_UNSIGNED_VALUE; - } else { - if (value <= -TWO_PWR_63_DBL) return MIN_VALUE; - if (value + 1 >= TWO_PWR_63_DBL) return MAX_VALUE; - } - if (value < 0) return fromNumber(-value, unsigned).neg(); - return fromBits( - value % TWO_PWR_32_DBL | 0, - (value / TWO_PWR_32_DBL) | 0, - unsigned, - ); - } - - /** - * Returns a Long representing the given value, provided that it is a finite number. Otherwise, zero is returned. - * @function - * @param {number} value The number in question - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {!Long} The corresponding Long value - */ - Long.fromNumber = fromNumber; - - /** - * @param {number} lowBits - * @param {number} highBits - * @param {boolean=} unsigned - * @returns {!Long} - * @inner - */ - function fromBits(lowBits, highBits, unsigned) { - return new Long(lowBits, highBits, unsigned); - } - - /** - * Returns a Long representing the 64 bit integer that comes by concatenating the given low and high bits. Each is - * assumed to use 32 bits. - * @function - * @param {number} lowBits The low 32 bits - * @param {number} highBits The high 32 bits - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {!Long} The corresponding Long value - */ - Long.fromBits = fromBits; - - /** - * @function - * @param {number} base - * @param {number} exponent - * @returns {number} - * @inner - */ - var pow_dbl = Math.pow; // Used 4 times (4*8 to 15+4) - - /** - * @param {string} str - * @param {(boolean|number)=} unsigned - * @param {number=} radix - * @returns {!Long} - * @inner - */ - function fromString(str, unsigned, radix) { - if (str.length === 0) throw Error("empty string"); - if (typeof unsigned === "number") { - // For goog.math.long compatibility - radix = unsigned; - unsigned = false; - } else { - unsigned = !!unsigned; - } - if ( - str === "NaN" || - str === "Infinity" || - str === "+Infinity" || - str === "-Infinity" - ) - return unsigned ? UZERO : ZERO; - radix = radix || 10; - if (radix < 2 || 36 < radix) throw RangeError("radix"); - var p; - if ((p = str.indexOf("-")) > 0) throw Error("interior hyphen"); - else if (p === 0) { - return fromString(str.substring(1), unsigned, radix).neg(); - } - - // Do several (8) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = fromNumber(pow_dbl(radix, 8)); - var result = ZERO; - for (var i = 0; i < str.length; i += 8) { - var size = Math.min(8, str.length - i), - value = parseInt(str.substring(i, i + size), radix); - if (size < 8) { - var power = fromNumber(pow_dbl(radix, size)); - result = result.mul(power).add(fromNumber(value)); - } else { - result = result.mul(radixToPower); - result = result.add(fromNumber(value)); - } - } - result.unsigned = unsigned; - return result; - } - - /** - * Returns a Long representation of the given string, written using the specified radix. - * @function - * @param {string} str The textual representation of the Long - * @param {(boolean|number)=} unsigned Whether unsigned or not, defaults to signed - * @param {number=} radix The radix in which the text is written (2-36), defaults to 10 - * @returns {!Long} The corresponding Long value - */ - Long.fromString = fromString; - - /** - * @function - * @param {!Long|number|string|!{low: number, high: number, unsigned: boolean}} val - * @param {boolean=} unsigned - * @returns {!Long} - * @inner - */ - function fromValue(val, unsigned) { - if (typeof val === "number") return fromNumber(val, unsigned); - if (typeof val === "string") return fromString(val, unsigned); - // Throws for non-objects, converts non-instanceof Long: - return fromBits( - val.low, - val.high, - typeof unsigned === "boolean" ? unsigned : val.unsigned, - ); - } - - /** - * Converts the specified value to a Long using the appropriate from* function for its type. - * @function - * @param {!Long|number|bigint|string|!{low: number, high: number, unsigned: boolean}} val Value - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {!Long} - */ - Long.fromValue = fromValue; - - // NOTE: the compiler should inline these constant values below and then remove these variables, so there should be - // no runtime penalty for these. - - /** - * @type {number} - * @const - * @inner - */ - var TWO_PWR_16_DBL = 1 << 16; - - /** - * @type {number} - * @const - * @inner - */ - var TWO_PWR_24_DBL = 1 << 24; - - /** - * @type {number} - * @const - * @inner - */ - var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL; - - /** - * @type {number} - * @const - * @inner - */ - var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL; - - /** - * @type {number} - * @const - * @inner - */ - var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2; - - /** - * @type {!Long} - * @const - * @inner - */ - var TWO_PWR_24 = fromInt(TWO_PWR_24_DBL); - - /** - * @type {!Long} - * @inner - */ - var ZERO = fromInt(0); - - /** - * Signed zero. - * @type {!Long} - */ - Long.ZERO = ZERO; - - /** - * @type {!Long} - * @inner - */ - var UZERO = fromInt(0, true); - - /** - * Unsigned zero. - * @type {!Long} - */ - Long.UZERO = UZERO; - - /** - * @type {!Long} - * @inner - */ - var ONE = fromInt(1); - - /** - * Signed one. - * @type {!Long} - */ - Long.ONE = ONE; - - /** - * @type {!Long} - * @inner - */ - var UONE = fromInt(1, true); - - /** - * Unsigned one. - * @type {!Long} - */ - Long.UONE = UONE; - - /** - * @type {!Long} - * @inner - */ - var NEG_ONE = fromInt(-1); - - /** - * Signed negative one. - * @type {!Long} - */ - Long.NEG_ONE = NEG_ONE; - - /** - * @type {!Long} - * @inner - */ - var MAX_VALUE = fromBits(0xffffffff | 0, 0x7fffffff | 0, false); - - /** - * Maximum signed value. - * @type {!Long} - */ - Long.MAX_VALUE = MAX_VALUE; - - /** - * @type {!Long} - * @inner - */ - var MAX_UNSIGNED_VALUE = fromBits(0xffffffff | 0, 0xffffffff | 0, true); - - /** - * Maximum unsigned value. - * @type {!Long} - */ - Long.MAX_UNSIGNED_VALUE = MAX_UNSIGNED_VALUE; - - /** - * @type {!Long} - * @inner - */ - var MIN_VALUE = fromBits(0, 0x80000000 | 0, false); - - /** - * Minimum signed value. - * @type {!Long} - */ - Long.MIN_VALUE = MIN_VALUE; - - /** - * @alias Long.prototype - * @inner - */ - var LongPrototype = Long.prototype; - - /** - * Converts the Long to a 32 bit integer, assuming it is a 32 bit integer. - * @this {!Long} - * @returns {number} - */ - LongPrototype.toInt = function toInt() { - return this.unsigned ? this.low >>> 0 : this.low; - }; - - /** - * Converts the Long to a the nearest floating-point representation of this value (double, 53 bit mantissa). - * @this {!Long} - * @returns {number} - */ - LongPrototype.toNumber = function toNumber() { - if (this.unsigned) - return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0); - return this.high * TWO_PWR_32_DBL + (this.low >>> 0); - }; - - /** - * Converts the Long to a string written in the specified radix. - * @this {!Long} - * @param {number=} radix Radix (2-36), defaults to 10 - * @returns {string} - * @override - * @throws {RangeError} If `radix` is out of range - */ - LongPrototype.toString = function toString(radix) { - radix = radix || 10; - if (radix < 2 || 36 < radix) throw RangeError("radix"); - if (this.isZero()) return "0"; - if (this.isNegative()) { - // Unsigned Longs are never negative - if (this.eq(MIN_VALUE)) { - // We need to change the Long value before it can be negated, so we remove - // the bottom-most digit in this base and then recurse to do the rest. - var radixLong = fromNumber(radix), - div = this.div(radixLong), - rem1 = div.mul(radixLong).sub(this); - return div.toString(radix) + rem1.toInt().toString(radix); - } else return "-" + this.neg().toString(radix); - } - - // Do several (6) digits each time through the loop, so as to - // minimize the calls to the very expensive emulated div. - var radixToPower = fromNumber(pow_dbl(radix, 6), this.unsigned), - rem = this; - var result = ""; - while (true) { - var remDiv = rem.div(radixToPower), - intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0, - digits = intval.toString(radix); - rem = remDiv; - if (rem.isZero()) return digits + result; - else { - while (digits.length < 6) digits = "0" + digits; - result = "" + digits + result; - } - } - }; - - /** - * Gets the high 32 bits as a signed integer. - * @this {!Long} - * @returns {number} Signed high bits - */ - LongPrototype.getHighBits = function getHighBits() { - return this.high; - }; - - /** - * Gets the high 32 bits as an unsigned integer. - * @this {!Long} - * @returns {number} Unsigned high bits - */ - LongPrototype.getHighBitsUnsigned = function getHighBitsUnsigned() { - return this.high >>> 0; - }; - - /** - * Gets the low 32 bits as a signed integer. - * @this {!Long} - * @returns {number} Signed low bits - */ - LongPrototype.getLowBits = function getLowBits() { - return this.low; - }; - - /** - * Gets the low 32 bits as an unsigned integer. - * @this {!Long} - * @returns {number} Unsigned low bits - */ - LongPrototype.getLowBitsUnsigned = function getLowBitsUnsigned() { - return this.low >>> 0; - }; - - /** - * Gets the number of bits needed to represent the absolute value of this Long. - * @this {!Long} - * @returns {number} - */ - LongPrototype.getNumBitsAbs = function getNumBitsAbs() { - if (this.isNegative()) - // Unsigned Longs are never negative - return this.eq(MIN_VALUE) ? 64 : this.neg().getNumBitsAbs(); - var val = this.high != 0 ? this.high : this.low; - for (var bit = 31; bit > 0; bit--) if ((val & (1 << bit)) != 0) break; - return this.high != 0 ? bit + 33 : bit + 1; - }; - - /** - * Tests if this Long can be safely represented as a JavaScript number. - * @this {!Long} - * @returns {boolean} - */ - LongPrototype.isSafeInteger = function isSafeInteger() { - // 2^53-1 is the maximum safe value - var top11Bits = this.high >> 21; - // [0, 2^53-1] - if (!top11Bits) return true; - // > 2^53-1 - if (this.unsigned) return false; - // [-2^53, -1] except -2^53 - return top11Bits === -1 && !(this.low === 0 && this.high === -0x200000); - }; - - /** - * Tests if this Long's value equals zero. - * @this {!Long} - * @returns {boolean} - */ - LongPrototype.isZero = function isZero() { - return this.high === 0 && this.low === 0; - }; - - /** - * Tests if this Long's value equals zero. This is an alias of {@link Long#isZero}. - * @returns {boolean} - */ - LongPrototype.eqz = LongPrototype.isZero; - - /** - * Tests if this Long's value is negative. - * @this {!Long} - * @returns {boolean} - */ - LongPrototype.isNegative = function isNegative() { - return !this.unsigned && this.high < 0; - }; - - /** - * Tests if this Long's value is positive or zero. - * @this {!Long} - * @returns {boolean} - */ - LongPrototype.isPositive = function isPositive() { - return this.unsigned || this.high >= 0; - }; - - /** - * Tests if this Long's value is odd. - * @this {!Long} - * @returns {boolean} - */ - LongPrototype.isOdd = function isOdd() { - return (this.low & 1) === 1; - }; - - /** - * Tests if this Long's value is even. - * @this {!Long} - * @returns {boolean} - */ - LongPrototype.isEven = function isEven() { - return (this.low & 1) === 0; - }; - - /** - * Tests if this Long's value equals the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.equals = function equals(other) { - if (!isLong(other)) other = fromValue(other); - if ( - this.unsigned !== other.unsigned && - this.high >>> 31 === 1 && - other.high >>> 31 === 1 - ) - return false; - return this.high === other.high && this.low === other.low; - }; - - /** - * Tests if this Long's value equals the specified's. This is an alias of {@link Long#equals}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.eq = LongPrototype.equals; - - /** - * Tests if this Long's value differs from the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.notEquals = function notEquals(other) { - return !this.eq(/* validates */ other); - }; - - /** - * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.neq = LongPrototype.notEquals; - - /** - * Tests if this Long's value differs from the specified's. This is an alias of {@link Long#notEquals}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.ne = LongPrototype.notEquals; - - /** - * Tests if this Long's value is less than the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.lessThan = function lessThan(other) { - return this.comp(/* validates */ other) < 0; - }; - - /** - * Tests if this Long's value is less than the specified's. This is an alias of {@link Long#lessThan}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.lt = LongPrototype.lessThan; - - /** - * Tests if this Long's value is less than or equal the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.lessThanOrEqual = function lessThanOrEqual(other) { - return this.comp(/* validates */ other) <= 0; - }; - - /** - * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.lte = LongPrototype.lessThanOrEqual; - - /** - * Tests if this Long's value is less than or equal the specified's. This is an alias of {@link Long#lessThanOrEqual}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.le = LongPrototype.lessThanOrEqual; - - /** - * Tests if this Long's value is greater than the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.greaterThan = function greaterThan(other) { - return this.comp(/* validates */ other) > 0; - }; - - /** - * Tests if this Long's value is greater than the specified's. This is an alias of {@link Long#greaterThan}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.gt = LongPrototype.greaterThan; - - /** - * Tests if this Long's value is greater than or equal the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.greaterThanOrEqual = function greaterThanOrEqual(other) { - return this.comp(/* validates */ other) >= 0; - }; - - /** - * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.gte = LongPrototype.greaterThanOrEqual; - - /** - * Tests if this Long's value is greater than or equal the specified's. This is an alias of {@link Long#greaterThanOrEqual}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {boolean} - */ - LongPrototype.ge = LongPrototype.greaterThanOrEqual; - - /** - * Compares this Long's value with the specified's. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other value - * @returns {number} 0 if they are the same, 1 if the this is greater and -1 - * if the given one is greater - */ - LongPrototype.compare = function compare(other) { - if (!isLong(other)) other = fromValue(other); - if (this.eq(other)) return 0; - var thisNeg = this.isNegative(), - otherNeg = other.isNegative(); - if (thisNeg && !otherNeg) return -1; - if (!thisNeg && otherNeg) return 1; - // At this point the sign bits are the same - if (!this.unsigned) return this.sub(other).isNegative() ? -1 : 1; - // Both are positive if at least one is unsigned - return other.high >>> 0 > this.high >>> 0 || - (other.high === this.high && other.low >>> 0 > this.low >>> 0) - ? -1 - : 1; - }; - - /** - * Compares this Long's value with the specified's. This is an alias of {@link Long#compare}. - * @function - * @param {!Long|number|bigint|string} other Other value - * @returns {number} 0 if they are the same, 1 if the this is greater and -1 - * if the given one is greater - */ - LongPrototype.comp = LongPrototype.compare; - - /** - * Negates this Long's value. - * @this {!Long} - * @returns {!Long} Negated Long - */ - LongPrototype.negate = function negate() { - if (!this.unsigned && this.eq(MIN_VALUE)) return MIN_VALUE; - return this.not().add(ONE); - }; - - /** - * Negates this Long's value. This is an alias of {@link Long#negate}. - * @function - * @returns {!Long} Negated Long - */ - LongPrototype.neg = LongPrototype.negate; - - /** - * Returns the sum of this and the specified Long. - * @this {!Long} - * @param {!Long|number|bigint|string} addend Addend - * @returns {!Long} Sum - */ - LongPrototype.add = function add(addend) { - if (!isLong(addend)) addend = fromValue(addend); - - // Divide each number into 4 chunks of 16 bits, and then sum the chunks. - - var a48 = this.high >>> 16; - var a32 = this.high & 0xffff; - var a16 = this.low >>> 16; - var a00 = this.low & 0xffff; - var b48 = addend.high >>> 16; - var b32 = addend.high & 0xffff; - var b16 = addend.low >>> 16; - var b00 = addend.low & 0xffff; - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 + b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 + b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 + b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 + b48; - c48 &= 0xffff; - return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - }; - - /** - * Returns the difference of this and the specified Long. - * @this {!Long} - * @param {!Long|number|bigint|string} subtrahend Subtrahend - * @returns {!Long} Difference - */ - LongPrototype.subtract = function subtract(subtrahend) { - if (!isLong(subtrahend)) subtrahend = fromValue(subtrahend); - return this.add(subtrahend.neg()); - }; - - /** - * Returns the difference of this and the specified Long. This is an alias of {@link Long#subtract}. - * @function - * @param {!Long|number|bigint|string} subtrahend Subtrahend - * @returns {!Long} Difference - */ - LongPrototype.sub = LongPrototype.subtract; - - /** - * Returns the product of this and the specified Long. - * @this {!Long} - * @param {!Long|number|bigint|string} multiplier Multiplier - * @returns {!Long} Product - */ - LongPrototype.multiply = function multiply(multiplier) { - if (this.isZero()) return this; - if (!isLong(multiplier)) multiplier = fromValue(multiplier); - - // use wasm support if present - if (wasm) { - var low = wasm["mul"]( - this.low, - this.high, - multiplier.low, - multiplier.high, - ); - return fromBits(low, wasm["get_high"](), this.unsigned); - } - if (multiplier.isZero()) return this.unsigned ? UZERO : ZERO; - if (this.eq(MIN_VALUE)) return multiplier.isOdd() ? MIN_VALUE : ZERO; - if (multiplier.eq(MIN_VALUE)) return this.isOdd() ? MIN_VALUE : ZERO; - if (this.isNegative()) { - if (multiplier.isNegative()) return this.neg().mul(multiplier.neg()); - else return this.neg().mul(multiplier).neg(); - } else if (multiplier.isNegative()) - return this.mul(multiplier.neg()).neg(); - - // If both longs are small, use float multiplication - if (this.lt(TWO_PWR_24) && multiplier.lt(TWO_PWR_24)) - return fromNumber( - this.toNumber() * multiplier.toNumber(), - this.unsigned, - ); - - // Divide each long into 4 chunks of 16 bits, and then add up 4x4 products. - // We can skip products that would overflow. - - var a48 = this.high >>> 16; - var a32 = this.high & 0xffff; - var a16 = this.low >>> 16; - var a00 = this.low & 0xffff; - var b48 = multiplier.high >>> 16; - var b32 = multiplier.high & 0xffff; - var b16 = multiplier.low >>> 16; - var b00 = multiplier.low & 0xffff; - var c48 = 0, - c32 = 0, - c16 = 0, - c00 = 0; - c00 += a00 * b00; - c16 += c00 >>> 16; - c00 &= 0xffff; - c16 += a16 * b00; - c32 += c16 >>> 16; - c16 &= 0xffff; - c16 += a00 * b16; - c32 += c16 >>> 16; - c16 &= 0xffff; - c32 += a32 * b00; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a16 * b16; - c48 += c32 >>> 16; - c32 &= 0xffff; - c32 += a00 * b32; - c48 += c32 >>> 16; - c32 &= 0xffff; - c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48; - c48 &= 0xffff; - return fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned); - }; - - /** - * Returns the product of this and the specified Long. This is an alias of {@link Long#multiply}. - * @function - * @param {!Long|number|bigint|string} multiplier Multiplier - * @returns {!Long} Product - */ - LongPrototype.mul = LongPrototype.multiply; - - /** - * Returns this Long divided by the specified. The result is signed if this Long is signed or - * unsigned if this Long is unsigned. - * @this {!Long} - * @param {!Long|number|bigint|string} divisor Divisor - * @returns {!Long} Quotient - */ - LongPrototype.divide = function divide(divisor) { - if (!isLong(divisor)) divisor = fromValue(divisor); - if (divisor.isZero()) throw Error("division by zero"); - - // use wasm support if present - if (wasm) { - // guard against signed division overflow: the largest - // negative number / -1 would be 1 larger than the largest - // positive number, due to two's complement. - if ( - !this.unsigned && - this.high === -0x80000000 && - divisor.low === -1 && - divisor.high === -1 - ) { - // be consistent with non-wasm code path - return this; - } - var low = (this.unsigned ? wasm["div_u"] : wasm["div_s"])( - this.low, - this.high, - divisor.low, - divisor.high, - ); - return fromBits(low, wasm["get_high"](), this.unsigned); - } - if (this.isZero()) return this.unsigned ? UZERO : ZERO; - var approx, rem, res; - if (!this.unsigned) { - // This section is only relevant for signed longs and is derived from the - // closure library as a whole. - if (this.eq(MIN_VALUE)) { - if (divisor.eq(ONE) || divisor.eq(NEG_ONE)) - return MIN_VALUE; // recall that -MIN_VALUE == MIN_VALUE - else if (divisor.eq(MIN_VALUE)) return ONE; - else { - // At this point, we have |other| >= 2, so |this/other| < |MIN_VALUE|. - var halfThis = this.shr(1); - approx = halfThis.div(divisor).shl(1); - if (approx.eq(ZERO)) { - return divisor.isNegative() ? ONE : NEG_ONE; - } else { - rem = this.sub(divisor.mul(approx)); - res = approx.add(rem.div(divisor)); - return res; - } - } - } else if (divisor.eq(MIN_VALUE)) return this.unsigned ? UZERO : ZERO; - if (this.isNegative()) { - if (divisor.isNegative()) return this.neg().div(divisor.neg()); - return this.neg().div(divisor).neg(); - } else if (divisor.isNegative()) return this.div(divisor.neg()).neg(); - res = ZERO; - } else { - // The algorithm below has not been made for unsigned longs. It's therefore - // required to take special care of the MSB prior to running it. - if (!divisor.unsigned) divisor = divisor.toUnsigned(); - if (divisor.gt(this)) return UZERO; - if (divisor.gt(this.shru(1))) - // 15 >>> 1 = 7 ; with divisor = 8 ; true - return UONE; - res = UZERO; - } - - // Repeat the following until the remainder is less than other: find a - // floating-point that approximates remainder / other *from below*, add this - // into the result, and subtract it from the remainder. It is critical that - // the approximate value is less than or equal to the real value so that the - // remainder never becomes negative. - rem = this; - while (rem.gte(divisor)) { - // Approximate the result of division. This may be a little greater or - // smaller than the actual value. - approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber())); - - // We will tweak the approximate result by changing it in the 48-th digit or - // the smallest non-fractional digit, whichever is larger. - var log2 = Math.ceil(Math.log(approx) / Math.LN2), - delta = log2 <= 48 ? 1 : pow_dbl(2, log2 - 48), - // Decrease the approximation until it is smaller than the remainder. Note - // that if it is too large, the product overflows and is negative. - approxRes = fromNumber(approx), - approxRem = approxRes.mul(divisor); - while (approxRem.isNegative() || approxRem.gt(rem)) { - approx -= delta; - approxRes = fromNumber(approx, this.unsigned); - approxRem = approxRes.mul(divisor); - } - - // We know the answer can't be zero... and actually, zero would cause - // infinite recursion since we would make no progress. - if (approxRes.isZero()) approxRes = ONE; - res = res.add(approxRes); - rem = rem.sub(approxRem); - } - return res; - }; - - /** - * Returns this Long divided by the specified. This is an alias of {@link Long#divide}. - * @function - * @param {!Long|number|bigint|string} divisor Divisor - * @returns {!Long} Quotient - */ - LongPrototype.div = LongPrototype.divide; - - /** - * Returns this Long modulo the specified. - * @this {!Long} - * @param {!Long|number|bigint|string} divisor Divisor - * @returns {!Long} Remainder - */ - LongPrototype.modulo = function modulo(divisor) { - if (!isLong(divisor)) divisor = fromValue(divisor); - - // use wasm support if present - if (wasm) { - var low = (this.unsigned ? wasm["rem_u"] : wasm["rem_s"])( - this.low, - this.high, - divisor.low, - divisor.high, - ); - return fromBits(low, wasm["get_high"](), this.unsigned); - } - return this.sub(this.div(divisor).mul(divisor)); - }; - - /** - * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}. - * @function - * @param {!Long|number|bigint|string} divisor Divisor - * @returns {!Long} Remainder - */ - LongPrototype.mod = LongPrototype.modulo; - - /** - * Returns this Long modulo the specified. This is an alias of {@link Long#modulo}. - * @function - * @param {!Long|number|bigint|string} divisor Divisor - * @returns {!Long} Remainder - */ - LongPrototype.rem = LongPrototype.modulo; - - /** - * Returns the bitwise NOT of this Long. - * @this {!Long} - * @returns {!Long} - */ - LongPrototype.not = function not() { - return fromBits(~this.low, ~this.high, this.unsigned); - }; - - /** - * Returns count leading zeros of this Long. - * @this {!Long} - * @returns {!number} - */ - LongPrototype.countLeadingZeros = function countLeadingZeros() { - return this.high ? Math.clz32(this.high) : Math.clz32(this.low) + 32; - }; - - /** - * Returns count leading zeros. This is an alias of {@link Long#countLeadingZeros}. - * @function - * @param {!Long} - * @returns {!number} - */ - LongPrototype.clz = LongPrototype.countLeadingZeros; - - /** - * Returns count trailing zeros of this Long. - * @this {!Long} - * @returns {!number} - */ - LongPrototype.countTrailingZeros = function countTrailingZeros() { - return this.low ? ctz32(this.low) : ctz32(this.high) + 32; - }; - - /** - * Returns count trailing zeros. This is an alias of {@link Long#countTrailingZeros}. - * @function - * @param {!Long} - * @returns {!number} - */ - LongPrototype.ctz = LongPrototype.countTrailingZeros; - - /** - * Returns the bitwise AND of this Long and the specified. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other Long - * @returns {!Long} - */ - LongPrototype.and = function and(other) { - if (!isLong(other)) other = fromValue(other); - return fromBits( - this.low & other.low, - this.high & other.high, - this.unsigned, - ); - }; - - /** - * Returns the bitwise OR of this Long and the specified. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other Long - * @returns {!Long} - */ - LongPrototype.or = function or(other) { - if (!isLong(other)) other = fromValue(other); - return fromBits( - this.low | other.low, - this.high | other.high, - this.unsigned, - ); - }; - - /** - * Returns the bitwise XOR of this Long and the given one. - * @this {!Long} - * @param {!Long|number|bigint|string} other Other Long - * @returns {!Long} - */ - LongPrototype.xor = function xor(other) { - if (!isLong(other)) other = fromValue(other); - return fromBits( - this.low ^ other.low, - this.high ^ other.high, - this.unsigned, - ); - }; - - /** - * Returns this Long with bits shifted to the left by the given amount. - * @this {!Long} - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shiftLeft = function shiftLeft(numBits) { - if (isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - else if (numBits < 32) - return fromBits( - this.low << numBits, - (this.high << numBits) | (this.low >>> (32 - numBits)), - this.unsigned, - ); - else return fromBits(0, this.low << (numBits - 32), this.unsigned); - }; - - /** - * Returns this Long with bits shifted to the left by the given amount. This is an alias of {@link Long#shiftLeft}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shl = LongPrototype.shiftLeft; - - /** - * Returns this Long with bits arithmetically shifted to the right by the given amount. - * @this {!Long} - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shiftRight = function shiftRight(numBits) { - if (isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - else if (numBits < 32) - return fromBits( - (this.low >>> numBits) | (this.high << (32 - numBits)), - this.high >> numBits, - this.unsigned, - ); - else - return fromBits( - this.high >> (numBits - 32), - this.high >= 0 ? 0 : -1, - this.unsigned, - ); - }; - - /** - * Returns this Long with bits arithmetically shifted to the right by the given amount. This is an alias of {@link Long#shiftRight}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shr = LongPrototype.shiftRight; - - /** - * Returns this Long with bits logically shifted to the right by the given amount. - * @this {!Long} - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shiftRightUnsigned = function shiftRightUnsigned(numBits) { - if (isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - if (numBits < 32) - return fromBits( - (this.low >>> numBits) | (this.high << (32 - numBits)), - this.high >>> numBits, - this.unsigned, - ); - if (numBits === 32) return fromBits(this.high, 0, this.unsigned); - return fromBits(this.high >>> (numBits - 32), 0, this.unsigned); - }; - - /** - * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shru = LongPrototype.shiftRightUnsigned; - - /** - * Returns this Long with bits logically shifted to the right by the given amount. This is an alias of {@link Long#shiftRightUnsigned}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Shifted Long - */ - LongPrototype.shr_u = LongPrototype.shiftRightUnsigned; - - /** - * Returns this Long with bits rotated to the left by the given amount. - * @this {!Long} - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Rotated Long - */ - LongPrototype.rotateLeft = function rotateLeft(numBits) { - var b; - if (isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); - if (numBits < 32) { - b = 32 - numBits; - return fromBits( - (this.low << numBits) | (this.high >>> b), - (this.high << numBits) | (this.low >>> b), - this.unsigned, - ); - } - numBits -= 32; - b = 32 - numBits; - return fromBits( - (this.high << numBits) | (this.low >>> b), - (this.low << numBits) | (this.high >>> b), - this.unsigned, - ); - }; - /** - * Returns this Long with bits rotated to the left by the given amount. This is an alias of {@link Long#rotateLeft}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Rotated Long - */ - LongPrototype.rotl = LongPrototype.rotateLeft; - - /** - * Returns this Long with bits rotated to the right by the given amount. - * @this {!Long} - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Rotated Long - */ - LongPrototype.rotateRight = function rotateRight(numBits) { - var b; - if (isLong(numBits)) numBits = numBits.toInt(); - if ((numBits &= 63) === 0) return this; - if (numBits === 32) return fromBits(this.high, this.low, this.unsigned); - if (numBits < 32) { - b = 32 - numBits; - return fromBits( - (this.high << b) | (this.low >>> numBits), - (this.low << b) | (this.high >>> numBits), - this.unsigned, - ); - } - numBits -= 32; - b = 32 - numBits; - return fromBits( - (this.low << b) | (this.high >>> numBits), - (this.high << b) | (this.low >>> numBits), - this.unsigned, - ); - }; - /** - * Returns this Long with bits rotated to the right by the given amount. This is an alias of {@link Long#rotateRight}. - * @function - * @param {number|!Long} numBits Number of bits - * @returns {!Long} Rotated Long - */ - LongPrototype.rotr = LongPrototype.rotateRight; - - /** - * Converts this Long to signed. - * @this {!Long} - * @returns {!Long} Signed long - */ - LongPrototype.toSigned = function toSigned() { - if (!this.unsigned) return this; - return fromBits(this.low, this.high, false); - }; - - /** - * Converts this Long to unsigned. - * @this {!Long} - * @returns {!Long} Unsigned long - */ - LongPrototype.toUnsigned = function toUnsigned() { - if (this.unsigned) return this; - return fromBits(this.low, this.high, true); - }; - - /** - * Converts this Long to its byte representation. - * @param {boolean=} le Whether little or big endian, defaults to big endian - * @this {!Long} - * @returns {!Array.} Byte representation - */ - LongPrototype.toBytes = function toBytes(le) { - return le ? this.toBytesLE() : this.toBytesBE(); - }; - - /** - * Converts this Long to its little endian byte representation. - * @this {!Long} - * @returns {!Array.} Little endian byte representation - */ - LongPrototype.toBytesLE = function toBytesLE() { - var hi = this.high, - lo = this.low; - return [ - lo & 0xff, - (lo >>> 8) & 0xff, - (lo >>> 16) & 0xff, - lo >>> 24, - hi & 0xff, - (hi >>> 8) & 0xff, - (hi >>> 16) & 0xff, - hi >>> 24, - ]; - }; - - /** - * Converts this Long to its big endian byte representation. - * @this {!Long} - * @returns {!Array.} Big endian byte representation - */ - LongPrototype.toBytesBE = function toBytesBE() { - var hi = this.high, - lo = this.low; - return [ - hi >>> 24, - (hi >>> 16) & 0xff, - (hi >>> 8) & 0xff, - hi & 0xff, - lo >>> 24, - (lo >>> 16) & 0xff, - (lo >>> 8) & 0xff, - lo & 0xff, - ]; - }; - - /** - * Creates a Long from its byte representation. - * @param {!Array.} bytes Byte representation - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @param {boolean=} le Whether little or big endian, defaults to big endian - * @returns {Long} The corresponding Long value - */ - Long.fromBytes = function fromBytes(bytes, unsigned, le) { - return le - ? Long.fromBytesLE(bytes, unsigned) - : Long.fromBytesBE(bytes, unsigned); - }; - - /** - * Creates a Long from its little endian byte representation. - * @param {!Array.} bytes Little endian byte representation - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {Long} The corresponding Long value - */ - Long.fromBytesLE = function fromBytesLE(bytes, unsigned) { - return new Long( - bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), - bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), - unsigned, - ); - }; - - /** - * Creates a Long from its big endian byte representation. - * @param {!Array.} bytes Big endian byte representation - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {Long} The corresponding Long value - */ - Long.fromBytesBE = function fromBytesBE(bytes, unsigned) { - return new Long( - (bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], - (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], - unsigned, - ); - }; - - // Support conversion to/from BigInt where available - if (typeof BigInt === "function") { - /** - * Returns a Long representing the given big integer. - * @function - * @param {number} value The big integer value - * @param {boolean=} unsigned Whether unsigned or not, defaults to signed - * @returns {!Long} The corresponding Long value - */ - Long.fromBigInt = function fromBigInt(value, unsigned) { - var lowBits = Number(BigInt.asIntN(32, value)); - var highBits = Number(BigInt.asIntN(32, value >> BigInt(32))); - return fromBits(lowBits, highBits, unsigned); - }; - - // Override - Long.fromValue = function fromValueWithBigInt(value, unsigned) { - if (typeof value === "bigint") return fromBigInt(value, unsigned); - return fromValue(value, unsigned); - }; - - /** - * Converts the Long to its big integer representation. - * @this {!Long} - * @returns {bigint} - */ - LongPrototype.toBigInt = function toBigInt() { - var lowBigInt = BigInt(this.low >>> 0); - var highBigInt = BigInt(this.unsigned ? this.high >>> 0 : this.high); - return (highBigInt << BigInt(32)) | lowBigInt; - }; - } - var _default = (_exports.default = Long); - }, -); diff --git a/claude-code-source/node_modules/@img/colour/color.cjs b/claude-code-source/node_modules/@img/colour/color.cjs deleted file mode 100644 index ac055fa9..00000000 --- a/claude-code-source/node_modules/@img/colour/color.cjs +++ /dev/null @@ -1,1594 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// node_modules/color/index.js -var index_exports = {}; -__export(index_exports, { - default: () => index_default -}); -module.exports = __toCommonJS(index_exports); - -// node_modules/color-name/index.js -var color_name_default = { - aliceblue: [240, 248, 255], - antiquewhite: [250, 235, 215], - aqua: [0, 255, 255], - aquamarine: [127, 255, 212], - azure: [240, 255, 255], - beige: [245, 245, 220], - bisque: [255, 228, 196], - black: [0, 0, 0], - blanchedalmond: [255, 235, 205], - blue: [0, 0, 255], - blueviolet: [138, 43, 226], - brown: [165, 42, 42], - burlywood: [222, 184, 135], - cadetblue: [95, 158, 160], - chartreuse: [127, 255, 0], - chocolate: [210, 105, 30], - coral: [255, 127, 80], - cornflowerblue: [100, 149, 237], - cornsilk: [255, 248, 220], - crimson: [220, 20, 60], - cyan: [0, 255, 255], - darkblue: [0, 0, 139], - darkcyan: [0, 139, 139], - darkgoldenrod: [184, 134, 11], - darkgray: [169, 169, 169], - darkgreen: [0, 100, 0], - darkgrey: [169, 169, 169], - darkkhaki: [189, 183, 107], - darkmagenta: [139, 0, 139], - darkolivegreen: [85, 107, 47], - darkorange: [255, 140, 0], - darkorchid: [153, 50, 204], - darkred: [139, 0, 0], - darksalmon: [233, 150, 122], - darkseagreen: [143, 188, 143], - darkslateblue: [72, 61, 139], - darkslategray: [47, 79, 79], - darkslategrey: [47, 79, 79], - darkturquoise: [0, 206, 209], - darkviolet: [148, 0, 211], - deeppink: [255, 20, 147], - deepskyblue: [0, 191, 255], - dimgray: [105, 105, 105], - dimgrey: [105, 105, 105], - dodgerblue: [30, 144, 255], - firebrick: [178, 34, 34], - floralwhite: [255, 250, 240], - forestgreen: [34, 139, 34], - fuchsia: [255, 0, 255], - gainsboro: [220, 220, 220], - ghostwhite: [248, 248, 255], - gold: [255, 215, 0], - goldenrod: [218, 165, 32], - gray: [128, 128, 128], - green: [0, 128, 0], - greenyellow: [173, 255, 47], - grey: [128, 128, 128], - honeydew: [240, 255, 240], - hotpink: [255, 105, 180], - indianred: [205, 92, 92], - indigo: [75, 0, 130], - ivory: [255, 255, 240], - khaki: [240, 230, 140], - lavender: [230, 230, 250], - lavenderblush: [255, 240, 245], - lawngreen: [124, 252, 0], - lemonchiffon: [255, 250, 205], - lightblue: [173, 216, 230], - lightcoral: [240, 128, 128], - lightcyan: [224, 255, 255], - lightgoldenrodyellow: [250, 250, 210], - lightgray: [211, 211, 211], - lightgreen: [144, 238, 144], - lightgrey: [211, 211, 211], - lightpink: [255, 182, 193], - lightsalmon: [255, 160, 122], - lightseagreen: [32, 178, 170], - lightskyblue: [135, 206, 250], - lightslategray: [119, 136, 153], - lightslategrey: [119, 136, 153], - lightsteelblue: [176, 196, 222], - lightyellow: [255, 255, 224], - lime: [0, 255, 0], - limegreen: [50, 205, 50], - linen: [250, 240, 230], - magenta: [255, 0, 255], - maroon: [128, 0, 0], - mediumaquamarine: [102, 205, 170], - mediumblue: [0, 0, 205], - mediumorchid: [186, 85, 211], - mediumpurple: [147, 112, 219], - mediumseagreen: [60, 179, 113], - mediumslateblue: [123, 104, 238], - mediumspringgreen: [0, 250, 154], - mediumturquoise: [72, 209, 204], - mediumvioletred: [199, 21, 133], - midnightblue: [25, 25, 112], - mintcream: [245, 255, 250], - mistyrose: [255, 228, 225], - moccasin: [255, 228, 181], - navajowhite: [255, 222, 173], - navy: [0, 0, 128], - oldlace: [253, 245, 230], - olive: [128, 128, 0], - olivedrab: [107, 142, 35], - orange: [255, 165, 0], - orangered: [255, 69, 0], - orchid: [218, 112, 214], - palegoldenrod: [238, 232, 170], - palegreen: [152, 251, 152], - paleturquoise: [175, 238, 238], - palevioletred: [219, 112, 147], - papayawhip: [255, 239, 213], - peachpuff: [255, 218, 185], - peru: [205, 133, 63], - pink: [255, 192, 203], - plum: [221, 160, 221], - powderblue: [176, 224, 230], - purple: [128, 0, 128], - rebeccapurple: [102, 51, 153], - red: [255, 0, 0], - rosybrown: [188, 143, 143], - royalblue: [65, 105, 225], - saddlebrown: [139, 69, 19], - salmon: [250, 128, 114], - sandybrown: [244, 164, 96], - seagreen: [46, 139, 87], - seashell: [255, 245, 238], - sienna: [160, 82, 45], - silver: [192, 192, 192], - skyblue: [135, 206, 235], - slateblue: [106, 90, 205], - slategray: [112, 128, 144], - slategrey: [112, 128, 144], - snow: [255, 250, 250], - springgreen: [0, 255, 127], - steelblue: [70, 130, 180], - tan: [210, 180, 140], - teal: [0, 128, 128], - thistle: [216, 191, 216], - tomato: [255, 99, 71], - turquoise: [64, 224, 208], - violet: [238, 130, 238], - wheat: [245, 222, 179], - white: [255, 255, 255], - whitesmoke: [245, 245, 245], - yellow: [255, 255, 0], - yellowgreen: [154, 205, 50] -}; - -// node_modules/color-string/index.js -var reverseNames = /* @__PURE__ */ Object.create(null); -for (const name in color_name_default) { - if (Object.hasOwn(color_name_default, name)) { - reverseNames[color_name_default[name]] = name; - } -} -var cs = { - to: {}, - get: {} -}; -cs.get = function(string) { - const prefix = string.slice(0, 3).toLowerCase(); - let value; - let model; - switch (prefix) { - case "hsl": { - value = cs.get.hsl(string); - model = "hsl"; - break; - } - case "hwb": { - value = cs.get.hwb(string); - model = "hwb"; - break; - } - default: { - value = cs.get.rgb(string); - model = "rgb"; - break; - } - } - if (!value) { - return null; - } - return { model, value }; -}; -cs.get.rgb = function(string) { - if (!string) { - return null; - } - const abbr = /^#([a-f\d]{3,4})$/i; - const hex = /^#([a-f\d]{6})([a-f\d]{2})?$/i; - const rgba = /^rgba?\(\s*([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)(?=[\s,])\s*(?:,\s*)?([+-]?\d+)\s*(?:[\s,|/]\s*([+-]?[\d.]+)(%?)\s*)?\)$/; - const per = /^rgba?\(\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*(?:[\s,|/]\s*([+-]?[\d.]+)(%?)\s*)?\)$/; - const keyword = /^(\w+)$/; - let rgb = [0, 0, 0, 1]; - let match; - let i; - let hexAlpha; - if (match = string.match(hex)) { - hexAlpha = match[2]; - match = match[1]; - for (i = 0; i < 3; i++) { - const i2 = i * 2; - rgb[i] = Number.parseInt(match.slice(i2, i2 + 2), 16); - } - if (hexAlpha) { - rgb[3] = Number.parseInt(hexAlpha, 16) / 255; - } - } else if (match = string.match(abbr)) { - match = match[1]; - hexAlpha = match[3]; - for (i = 0; i < 3; i++) { - rgb[i] = Number.parseInt(match[i] + match[i], 16); - } - if (hexAlpha) { - rgb[3] = Number.parseInt(hexAlpha + hexAlpha, 16) / 255; - } - } else if (match = string.match(rgba)) { - for (i = 0; i < 3; i++) { - rgb[i] = Number.parseInt(match[i + 1], 10); - } - if (match[4]) { - rgb[3] = match[5] ? Number.parseFloat(match[4]) * 0.01 : Number.parseFloat(match[4]); - } - } else if (match = string.match(per)) { - for (i = 0; i < 3; i++) { - rgb[i] = Math.round(Number.parseFloat(match[i + 1]) * 2.55); - } - if (match[4]) { - rgb[3] = match[5] ? Number.parseFloat(match[4]) * 0.01 : Number.parseFloat(match[4]); - } - } else if (match = string.match(keyword)) { - if (match[1] === "transparent") { - return [0, 0, 0, 0]; - } - if (!Object.hasOwn(color_name_default, match[1])) { - return null; - } - rgb = color_name_default[match[1]]; - rgb[3] = 1; - return rgb; - } else { - return null; - } - for (i = 0; i < 3; i++) { - rgb[i] = clamp(rgb[i], 0, 255); - } - rgb[3] = clamp(rgb[3], 0, 1); - return rgb; -}; -cs.get.hsl = function(string) { - if (!string) { - return null; - } - const hsl = /^hsla?\(\s*([+-]?(?:\d{0,3}\.)?\d+)(?:deg)?\s*,?\s*([+-]?[\d.]+)%\s*,?\s*([+-]?[\d.]+)%\s*(?:[,|/]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; - const match = string.match(hsl); - if (match) { - const alpha = Number.parseFloat(match[4]); - const h = (Number.parseFloat(match[1]) % 360 + 360) % 360; - const s = clamp(Number.parseFloat(match[2]), 0, 100); - const l = clamp(Number.parseFloat(match[3]), 0, 100); - const a = clamp(Number.isNaN(alpha) ? 1 : alpha, 0, 1); - return [h, s, l, a]; - } - return null; -}; -cs.get.hwb = function(string) { - if (!string) { - return null; - } - const hwb = /^hwb\(\s*([+-]?\d{0,3}(?:\.\d+)?)(?:deg)?\s*[\s,]\s*([+-]?[\d.]+)%\s*[\s,]\s*([+-]?[\d.]+)%\s*(?:[\s,]\s*([+-]?(?=\.\d|\d)(?:0|[1-9]\d*)?(?:\.\d*)?(?:[eE][+-]?\d+)?)\s*)?\)$/; - const match = string.match(hwb); - if (match) { - const alpha = Number.parseFloat(match[4]); - const h = (Number.parseFloat(match[1]) % 360 + 360) % 360; - const w = clamp(Number.parseFloat(match[2]), 0, 100); - const b = clamp(Number.parseFloat(match[3]), 0, 100); - const a = clamp(Number.isNaN(alpha) ? 1 : alpha, 0, 1); - return [h, w, b, a]; - } - return null; -}; -cs.to.hex = function(...rgba) { - return "#" + hexDouble(rgba[0]) + hexDouble(rgba[1]) + hexDouble(rgba[2]) + (rgba[3] < 1 ? hexDouble(Math.round(rgba[3] * 255)) : ""); -}; -cs.to.rgb = function(...rgba) { - return rgba.length < 4 || rgba[3] === 1 ? "rgb(" + Math.round(rgba[0]) + ", " + Math.round(rgba[1]) + ", " + Math.round(rgba[2]) + ")" : "rgba(" + Math.round(rgba[0]) + ", " + Math.round(rgba[1]) + ", " + Math.round(rgba[2]) + ", " + rgba[3] + ")"; -}; -cs.to.rgb.percent = function(...rgba) { - const r = Math.round(rgba[0] / 255 * 100); - const g = Math.round(rgba[1] / 255 * 100); - const b = Math.round(rgba[2] / 255 * 100); - return rgba.length < 4 || rgba[3] === 1 ? "rgb(" + r + "%, " + g + "%, " + b + "%)" : "rgba(" + r + "%, " + g + "%, " + b + "%, " + rgba[3] + ")"; -}; -cs.to.hsl = function(...hsla) { - return hsla.length < 4 || hsla[3] === 1 ? "hsl(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%)" : "hsla(" + hsla[0] + ", " + hsla[1] + "%, " + hsla[2] + "%, " + hsla[3] + ")"; -}; -cs.to.hwb = function(...hwba) { - let a = ""; - if (hwba.length >= 4 && hwba[3] !== 1) { - a = ", " + hwba[3]; - } - return "hwb(" + hwba[0] + ", " + hwba[1] + "%, " + hwba[2] + "%" + a + ")"; -}; -cs.to.keyword = function(...rgb) { - return reverseNames[rgb.slice(0, 3)]; -}; -function clamp(number_, min, max) { - return Math.min(Math.max(min, number_), max); -} -function hexDouble(number_) { - const string_ = Math.round(number_).toString(16).toUpperCase(); - return string_.length < 2 ? "0" + string_ : string_; -} -var color_string_default = cs; - -// node_modules/color-convert/conversions.js -var reverseKeywords = {}; -for (const key of Object.keys(color_name_default)) { - reverseKeywords[color_name_default[key]] = key; -} -var convert = { - rgb: { channels: 3, labels: "rgb" }, - hsl: { channels: 3, labels: "hsl" }, - hsv: { channels: 3, labels: "hsv" }, - hwb: { channels: 3, labels: "hwb" }, - cmyk: { channels: 4, labels: "cmyk" }, - xyz: { channels: 3, labels: "xyz" }, - lab: { channels: 3, labels: "lab" }, - oklab: { channels: 3, labels: ["okl", "oka", "okb"] }, - lch: { channels: 3, labels: "lch" }, - oklch: { channels: 3, labels: ["okl", "okc", "okh"] }, - hex: { channels: 1, labels: ["hex"] }, - keyword: { channels: 1, labels: ["keyword"] }, - ansi16: { channels: 1, labels: ["ansi16"] }, - ansi256: { channels: 1, labels: ["ansi256"] }, - hcg: { channels: 3, labels: ["h", "c", "g"] }, - apple: { channels: 3, labels: ["r16", "g16", "b16"] }, - gray: { channels: 1, labels: ["gray"] } -}; -var conversions_default = convert; -var LAB_FT = (6 / 29) ** 3; -function srgbNonlinearTransform(c) { - const cc = c > 31308e-7 ? 1.055 * c ** (1 / 2.4) - 0.055 : c * 12.92; - return Math.min(Math.max(0, cc), 1); -} -function srgbNonlinearTransformInv(c) { - return c > 0.04045 ? ((c + 0.055) / 1.055) ** 2.4 : c / 12.92; -} -for (const model of Object.keys(convert)) { - if (!("channels" in convert[model])) { - throw new Error("missing channels property: " + model); - } - if (!("labels" in convert[model])) { - throw new Error("missing channel labels property: " + model); - } - if (convert[model].labels.length !== convert[model].channels) { - throw new Error("channel and label counts mismatch: " + model); - } - const { channels, labels } = convert[model]; - delete convert[model].channels; - delete convert[model].labels; - Object.defineProperty(convert[model], "channels", { value: channels }); - Object.defineProperty(convert[model], "labels", { value: labels }); -} -convert.rgb.hsl = function(rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const min = Math.min(r, g, b); - const max = Math.max(r, g, b); - const delta = max - min; - let h; - let s; - switch (max) { - case min: { - h = 0; - break; - } - case r: { - h = (g - b) / delta; - break; - } - case g: { - h = 2 + (b - r) / delta; - break; - } - case b: { - h = 4 + (r - g) / delta; - break; - } - } - h = Math.min(h * 60, 360); - if (h < 0) { - h += 360; - } - const l = (min + max) / 2; - if (max === min) { - s = 0; - } else if (l <= 0.5) { - s = delta / (max + min); - } else { - s = delta / (2 - max - min); - } - return [h, s * 100, l * 100]; -}; -convert.rgb.hsv = function(rgb) { - let rdif; - let gdif; - let bdif; - let h; - let s; - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const v = Math.max(r, g, b); - const diff = v - Math.min(r, g, b); - const diffc = function(c) { - return (v - c) / 6 / diff + 1 / 2; - }; - if (diff === 0) { - h = 0; - s = 0; - } else { - s = diff / v; - rdif = diffc(r); - gdif = diffc(g); - bdif = diffc(b); - switch (v) { - case r: { - h = bdif - gdif; - break; - } - case g: { - h = 1 / 3 + rdif - bdif; - break; - } - case b: { - h = 2 / 3 + gdif - rdif; - break; - } - } - if (h < 0) { - h += 1; - } else if (h > 1) { - h -= 1; - } - } - return [ - h * 360, - s * 100, - v * 100 - ]; -}; -convert.rgb.hwb = function(rgb) { - const r = rgb[0]; - const g = rgb[1]; - let b = rgb[2]; - const h = convert.rgb.hsl(rgb)[0]; - const w = 1 / 255 * Math.min(r, Math.min(g, b)); - b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); - return [h, w * 100, b * 100]; -}; -convert.rgb.oklab = function(rgb) { - const r = srgbNonlinearTransformInv(rgb[0] / 255); - const g = srgbNonlinearTransformInv(rgb[1] / 255); - const b = srgbNonlinearTransformInv(rgb[2] / 255); - const lp = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b); - const mp = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b); - const sp = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b); - const l = 0.2104542553 * lp + 0.793617785 * mp - 0.0040720468 * sp; - const aa = 1.9779984951 * lp - 2.428592205 * mp + 0.4505937099 * sp; - const bb = 0.0259040371 * lp + 0.7827717662 * mp - 0.808675766 * sp; - return [l * 100, aa * 100, bb * 100]; -}; -convert.rgb.cmyk = function(rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const k = Math.min(1 - r, 1 - g, 1 - b); - const c = (1 - r - k) / (1 - k) || 0; - const m = (1 - g - k) / (1 - k) || 0; - const y = (1 - b - k) / (1 - k) || 0; - return [c * 100, m * 100, y * 100, k * 100]; -}; -function comparativeDistance(x, y) { - return (x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2 + (x[2] - y[2]) ** 2; -} -convert.rgb.keyword = function(rgb) { - const reversed = reverseKeywords[rgb]; - if (reversed) { - return reversed; - } - let currentClosestDistance = Number.POSITIVE_INFINITY; - let currentClosestKeyword; - for (const keyword of Object.keys(color_name_default)) { - const value = color_name_default[keyword]; - const distance = comparativeDistance(rgb, value); - if (distance < currentClosestDistance) { - currentClosestDistance = distance; - currentClosestKeyword = keyword; - } - } - return currentClosestKeyword; -}; -convert.keyword.rgb = function(keyword) { - return color_name_default[keyword]; -}; -convert.rgb.xyz = function(rgb) { - const r = srgbNonlinearTransformInv(rgb[0] / 255); - const g = srgbNonlinearTransformInv(rgb[1] / 255); - const b = srgbNonlinearTransformInv(rgb[2] / 255); - const x = r * 0.4124564 + g * 0.3575761 + b * 0.1804375; - const y = r * 0.2126729 + g * 0.7151522 + b * 0.072175; - const z = r * 0.0193339 + g * 0.119192 + b * 0.9503041; - return [x * 100, y * 100, z * 100]; -}; -convert.rgb.lab = function(rgb) { - const xyz = convert.rgb.xyz(rgb); - let x = xyz[0]; - let y = xyz[1]; - let z = xyz[2]; - x /= 95.047; - y /= 100; - z /= 108.883; - x = x > LAB_FT ? x ** (1 / 3) : 7.787 * x + 16 / 116; - y = y > LAB_FT ? y ** (1 / 3) : 7.787 * y + 16 / 116; - z = z > LAB_FT ? z ** (1 / 3) : 7.787 * z + 16 / 116; - const l = 116 * y - 16; - const a = 500 * (x - y); - const b = 200 * (y - z); - return [l, a, b]; -}; -convert.hsl.rgb = function(hsl) { - const h = hsl[0] / 360; - const s = hsl[1] / 100; - const l = hsl[2] / 100; - let t3; - let value; - if (s === 0) { - value = l * 255; - return [value, value, value]; - } - const t2 = l < 0.5 ? l * (1 + s) : l + s - l * s; - const t1 = 2 * l - t2; - const rgb = [0, 0, 0]; - for (let i = 0; i < 3; i++) { - t3 = h + 1 / 3 * -(i - 1); - if (t3 < 0) { - t3++; - } - if (t3 > 1) { - t3--; - } - if (6 * t3 < 1) { - value = t1 + (t2 - t1) * 6 * t3; - } else if (2 * t3 < 1) { - value = t2; - } else if (3 * t3 < 2) { - value = t1 + (t2 - t1) * (2 / 3 - t3) * 6; - } else { - value = t1; - } - rgb[i] = value * 255; - } - return rgb; -}; -convert.hsl.hsv = function(hsl) { - const h = hsl[0]; - let s = hsl[1] / 100; - let l = hsl[2] / 100; - let smin = s; - const lmin = Math.max(l, 0.01); - l *= 2; - s *= l <= 1 ? l : 2 - l; - smin *= lmin <= 1 ? lmin : 2 - lmin; - const v = (l + s) / 2; - const sv = l === 0 ? 2 * smin / (lmin + smin) : 2 * s / (l + s); - return [h, sv * 100, v * 100]; -}; -convert.hsv.rgb = function(hsv) { - const h = hsv[0] / 60; - const s = hsv[1] / 100; - let v = hsv[2] / 100; - const hi = Math.floor(h) % 6; - const f = h - Math.floor(h); - const p = 255 * v * (1 - s); - const q = 255 * v * (1 - s * f); - const t = 255 * v * (1 - s * (1 - f)); - v *= 255; - switch (hi) { - case 0: { - return [v, t, p]; - } - case 1: { - return [q, v, p]; - } - case 2: { - return [p, v, t]; - } - case 3: { - return [p, q, v]; - } - case 4: { - return [t, p, v]; - } - case 5: { - return [v, p, q]; - } - } -}; -convert.hsv.hsl = function(hsv) { - const h = hsv[0]; - const s = hsv[1] / 100; - const v = hsv[2] / 100; - const vmin = Math.max(v, 0.01); - let sl; - let l; - l = (2 - s) * v; - const lmin = (2 - s) * vmin; - sl = s * vmin; - sl /= lmin <= 1 ? lmin : 2 - lmin; - sl = sl || 0; - l /= 2; - return [h, sl * 100, l * 100]; -}; -convert.hwb.rgb = function(hwb) { - const h = hwb[0] / 360; - let wh = hwb[1] / 100; - let bl = hwb[2] / 100; - const ratio = wh + bl; - let f; - if (ratio > 1) { - wh /= ratio; - bl /= ratio; - } - const i = Math.floor(6 * h); - const v = 1 - bl; - f = 6 * h - i; - if ((i & 1) !== 0) { - f = 1 - f; - } - const n = wh + f * (v - wh); - let r; - let g; - let b; - switch (i) { - default: - case 6: - case 0: { - r = v; - g = n; - b = wh; - break; - } - case 1: { - r = n; - g = v; - b = wh; - break; - } - case 2: { - r = wh; - g = v; - b = n; - break; - } - case 3: { - r = wh; - g = n; - b = v; - break; - } - case 4: { - r = n; - g = wh; - b = v; - break; - } - case 5: { - r = v; - g = wh; - b = n; - break; - } - } - return [r * 255, g * 255, b * 255]; -}; -convert.cmyk.rgb = function(cmyk) { - const c = cmyk[0] / 100; - const m = cmyk[1] / 100; - const y = cmyk[2] / 100; - const k = cmyk[3] / 100; - const r = 1 - Math.min(1, c * (1 - k) + k); - const g = 1 - Math.min(1, m * (1 - k) + k); - const b = 1 - Math.min(1, y * (1 - k) + k); - return [r * 255, g * 255, b * 255]; -}; -convert.xyz.rgb = function(xyz) { - const x = xyz[0] / 100; - const y = xyz[1] / 100; - const z = xyz[2] / 100; - let r; - let g; - let b; - r = x * 3.2404542 + y * -1.5371385 + z * -0.4985314; - g = x * -0.969266 + y * 1.8760108 + z * 0.041556; - b = x * 0.0556434 + y * -0.2040259 + z * 1.0572252; - r = srgbNonlinearTransform(r); - g = srgbNonlinearTransform(g); - b = srgbNonlinearTransform(b); - return [r * 255, g * 255, b * 255]; -}; -convert.xyz.lab = function(xyz) { - let x = xyz[0]; - let y = xyz[1]; - let z = xyz[2]; - x /= 95.047; - y /= 100; - z /= 108.883; - x = x > LAB_FT ? x ** (1 / 3) : 7.787 * x + 16 / 116; - y = y > LAB_FT ? y ** (1 / 3) : 7.787 * y + 16 / 116; - z = z > LAB_FT ? z ** (1 / 3) : 7.787 * z + 16 / 116; - const l = 116 * y - 16; - const a = 500 * (x - y); - const b = 200 * (y - z); - return [l, a, b]; -}; -convert.xyz.oklab = function(xyz) { - const x = xyz[0] / 100; - const y = xyz[1] / 100; - const z = xyz[2] / 100; - const lp = Math.cbrt(0.8189330101 * x + 0.3618667424 * y - 0.1288597137 * z); - const mp = Math.cbrt(0.0329845436 * x + 0.9293118715 * y + 0.0361456387 * z); - const sp = Math.cbrt(0.0482003018 * x + 0.2643662691 * y + 0.633851707 * z); - const l = 0.2104542553 * lp + 0.793617785 * mp - 0.0040720468 * sp; - const a = 1.9779984951 * lp - 2.428592205 * mp + 0.4505937099 * sp; - const b = 0.0259040371 * lp + 0.7827717662 * mp - 0.808675766 * sp; - return [l * 100, a * 100, b * 100]; -}; -convert.oklab.oklch = function(oklab) { - return convert.lab.lch(oklab); -}; -convert.oklab.xyz = function(oklab) { - const ll = oklab[0] / 100; - const a = oklab[1] / 100; - const b = oklab[2] / 100; - const l = (0.999999998 * ll + 0.396337792 * a + 0.215803758 * b) ** 3; - const m = (1.000000008 * ll - 0.105561342 * a - 0.063854175 * b) ** 3; - const s = (1.000000055 * ll - 0.089484182 * a - 1.291485538 * b) ** 3; - const x = 1.227013851 * l - 0.55779998 * m + 0.281256149 * s; - const y = -0.040580178 * l + 1.11225687 * m - 0.071676679 * s; - const z = -0.076381285 * l - 0.421481978 * m + 1.58616322 * s; - return [x * 100, y * 100, z * 100]; -}; -convert.oklab.rgb = function(oklab) { - const ll = oklab[0] / 100; - const aa = oklab[1] / 100; - const bb = oklab[2] / 100; - const l = (ll + 0.3963377774 * aa + 0.2158037573 * bb) ** 3; - const m = (ll - 0.1055613458 * aa - 0.0638541728 * bb) ** 3; - const s = (ll - 0.0894841775 * aa - 1.291485548 * bb) ** 3; - const r = srgbNonlinearTransform(4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s); - const g = srgbNonlinearTransform(-1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s); - const b = srgbNonlinearTransform(-0.0041960863 * l - 0.7034186147 * m + 1.707614701 * s); - return [r * 255, g * 255, b * 255]; -}; -convert.oklch.oklab = function(oklch) { - return convert.lch.lab(oklch); -}; -convert.lab.xyz = function(lab) { - const l = lab[0]; - const a = lab[1]; - const b = lab[2]; - let x; - let y; - let z; - y = (l + 16) / 116; - x = a / 500 + y; - z = y - b / 200; - const y2 = y ** 3; - const x2 = x ** 3; - const z2 = z ** 3; - y = y2 > LAB_FT ? y2 : (y - 16 / 116) / 7.787; - x = x2 > LAB_FT ? x2 : (x - 16 / 116) / 7.787; - z = z2 > LAB_FT ? z2 : (z - 16 / 116) / 7.787; - x *= 95.047; - y *= 100; - z *= 108.883; - return [x, y, z]; -}; -convert.lab.lch = function(lab) { - const l = lab[0]; - const a = lab[1]; - const b = lab[2]; - let h; - const hr = Math.atan2(b, a); - h = hr * 360 / 2 / Math.PI; - if (h < 0) { - h += 360; - } - const c = Math.sqrt(a * a + b * b); - return [l, c, h]; -}; -convert.lch.lab = function(lch) { - const l = lch[0]; - const c = lch[1]; - const h = lch[2]; - const hr = h / 360 * 2 * Math.PI; - const a = c * Math.cos(hr); - const b = c * Math.sin(hr); - return [l, a, b]; -}; -convert.rgb.ansi16 = function(args, saturation = null) { - const [r, g, b] = args; - let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; - value = Math.round(value / 50); - if (value === 0) { - return 30; - } - let ansi = 30 + (Math.round(b / 255) << 2 | Math.round(g / 255) << 1 | Math.round(r / 255)); - if (value === 2) { - ansi += 60; - } - return ansi; -}; -convert.hsv.ansi16 = function(args) { - return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); -}; -convert.rgb.ansi256 = function(args) { - const r = args[0]; - const g = args[1]; - const b = args[2]; - if (r >> 4 === g >> 4 && g >> 4 === b >> 4) { - if (r < 8) { - return 16; - } - if (r > 248) { - return 231; - } - return Math.round((r - 8) / 247 * 24) + 232; - } - const ansi = 16 + 36 * Math.round(r / 255 * 5) + 6 * Math.round(g / 255 * 5) + Math.round(b / 255 * 5); - return ansi; -}; -convert.ansi16.rgb = function(args) { - args = args[0]; - let color = args % 10; - if (color === 0 || color === 7) { - if (args > 50) { - color += 3.5; - } - color = color / 10.5 * 255; - return [color, color, color]; - } - const mult = (Math.trunc(args > 50) + 1) * 0.5; - const r = (color & 1) * mult * 255; - const g = (color >> 1 & 1) * mult * 255; - const b = (color >> 2 & 1) * mult * 255; - return [r, g, b]; -}; -convert.ansi256.rgb = function(args) { - args = args[0]; - if (args >= 232) { - const c = (args - 232) * 10 + 8; - return [c, c, c]; - } - args -= 16; - let rem; - const r = Math.floor(args / 36) / 5 * 255; - const g = Math.floor((rem = args % 36) / 6) / 5 * 255; - const b = rem % 6 / 5 * 255; - return [r, g, b]; -}; -convert.rgb.hex = function(args) { - const integer = ((Math.round(args[0]) & 255) << 16) + ((Math.round(args[1]) & 255) << 8) + (Math.round(args[2]) & 255); - const string = integer.toString(16).toUpperCase(); - return "000000".slice(string.length) + string; -}; -convert.hex.rgb = function(args) { - const match = args.toString(16).match(/[a-f\d]{6}|[a-f\d]{3}/i); - if (!match) { - return [0, 0, 0]; - } - let colorString = match[0]; - if (match[0].length === 3) { - colorString = [...colorString].map((char) => char + char).join(""); - } - const integer = Number.parseInt(colorString, 16); - const r = integer >> 16 & 255; - const g = integer >> 8 & 255; - const b = integer & 255; - return [r, g, b]; -}; -convert.rgb.hcg = function(rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const max = Math.max(Math.max(r, g), b); - const min = Math.min(Math.min(r, g), b); - const chroma = max - min; - let hue; - const grayscale = chroma < 1 ? min / (1 - chroma) : 0; - if (chroma <= 0) { - hue = 0; - } else if (max === r) { - hue = (g - b) / chroma % 6; - } else if (max === g) { - hue = 2 + (b - r) / chroma; - } else { - hue = 4 + (r - g) / chroma; - } - hue /= 6; - hue %= 1; - return [hue * 360, chroma * 100, grayscale * 100]; -}; -convert.hsl.hcg = function(hsl) { - const s = hsl[1] / 100; - const l = hsl[2] / 100; - const c = l < 0.5 ? 2 * s * l : 2 * s * (1 - l); - let f = 0; - if (c < 1) { - f = (l - 0.5 * c) / (1 - c); - } - return [hsl[0], c * 100, f * 100]; -}; -convert.hsv.hcg = function(hsv) { - const s = hsv[1] / 100; - const v = hsv[2] / 100; - const c = s * v; - let f = 0; - if (c < 1) { - f = (v - c) / (1 - c); - } - return [hsv[0], c * 100, f * 100]; -}; -convert.hcg.rgb = function(hcg) { - const h = hcg[0] / 360; - const c = hcg[1] / 100; - const g = hcg[2] / 100; - if (c === 0) { - return [g * 255, g * 255, g * 255]; - } - const pure = [0, 0, 0]; - const hi = h % 1 * 6; - const v = hi % 1; - const w = 1 - v; - let mg = 0; - switch (Math.floor(hi)) { - case 0: { - pure[0] = 1; - pure[1] = v; - pure[2] = 0; - break; - } - case 1: { - pure[0] = w; - pure[1] = 1; - pure[2] = 0; - break; - } - case 2: { - pure[0] = 0; - pure[1] = 1; - pure[2] = v; - break; - } - case 3: { - pure[0] = 0; - pure[1] = w; - pure[2] = 1; - break; - } - case 4: { - pure[0] = v; - pure[1] = 0; - pure[2] = 1; - break; - } - default: { - pure[0] = 1; - pure[1] = 0; - pure[2] = w; - } - } - mg = (1 - c) * g; - return [ - (c * pure[0] + mg) * 255, - (c * pure[1] + mg) * 255, - (c * pure[2] + mg) * 255 - ]; -}; -convert.hcg.hsv = function(hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - const v = c + g * (1 - c); - let f = 0; - if (v > 0) { - f = c / v; - } - return [hcg[0], f * 100, v * 100]; -}; -convert.hcg.hsl = function(hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - const l = g * (1 - c) + 0.5 * c; - let s = 0; - if (l > 0 && l < 0.5) { - s = c / (2 * l); - } else if (l >= 0.5 && l < 1) { - s = c / (2 * (1 - l)); - } - return [hcg[0], s * 100, l * 100]; -}; -convert.hcg.hwb = function(hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - const v = c + g * (1 - c); - return [hcg[0], (v - c) * 100, (1 - v) * 100]; -}; -convert.hwb.hcg = function(hwb) { - const w = hwb[1] / 100; - const b = hwb[2] / 100; - const v = 1 - b; - const c = v - w; - let g = 0; - if (c < 1) { - g = (v - c) / (1 - c); - } - return [hwb[0], c * 100, g * 100]; -}; -convert.apple.rgb = function(apple) { - return [apple[0] / 65535 * 255, apple[1] / 65535 * 255, apple[2] / 65535 * 255]; -}; -convert.rgb.apple = function(rgb) { - return [rgb[0] / 255 * 65535, rgb[1] / 255 * 65535, rgb[2] / 255 * 65535]; -}; -convert.gray.rgb = function(args) { - return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; -}; -convert.gray.hsl = function(args) { - return [0, 0, args[0]]; -}; -convert.gray.hsv = convert.gray.hsl; -convert.gray.hwb = function(gray) { - return [0, 100, gray[0]]; -}; -convert.gray.cmyk = function(gray) { - return [0, 0, 0, gray[0]]; -}; -convert.gray.lab = function(gray) { - return [gray[0], 0, 0]; -}; -convert.gray.hex = function(gray) { - const value = Math.round(gray[0] / 100 * 255) & 255; - const integer = (value << 16) + (value << 8) + value; - const string = integer.toString(16).toUpperCase(); - return "000000".slice(string.length) + string; -}; -convert.rgb.gray = function(rgb) { - const value = (rgb[0] + rgb[1] + rgb[2]) / 3; - return [value / 255 * 100]; -}; - -// node_modules/color-convert/route.js -function buildGraph() { - const graph = {}; - const models2 = Object.keys(conversions_default); - for (let { length } = models2, i = 0; i < length; i++) { - graph[models2[i]] = { - // http://jsperf.com/1-vs-infinity - // micro-opt, but this is simple. - distance: -1, - parent: null - }; - } - return graph; -} -function deriveBFS(fromModel) { - const graph = buildGraph(); - const queue = [fromModel]; - graph[fromModel].distance = 0; - while (queue.length > 0) { - const current = queue.pop(); - const adjacents = Object.keys(conversions_default[current]); - for (let { length } = adjacents, i = 0; i < length; i++) { - const adjacent = adjacents[i]; - const node = graph[adjacent]; - if (node.distance === -1) { - node.distance = graph[current].distance + 1; - node.parent = current; - queue.unshift(adjacent); - } - } - } - return graph; -} -function link(from, to) { - return function(args) { - return to(from(args)); - }; -} -function wrapConversion(toModel, graph) { - const path = [graph[toModel].parent, toModel]; - let fn = conversions_default[graph[toModel].parent][toModel]; - let cur = graph[toModel].parent; - while (graph[cur].parent) { - path.unshift(graph[cur].parent); - fn = link(conversions_default[graph[cur].parent][cur], fn); - cur = graph[cur].parent; - } - fn.conversion = path; - return fn; -} -function route(fromModel) { - const graph = deriveBFS(fromModel); - const conversion = {}; - const models2 = Object.keys(graph); - for (let { length } = models2, i = 0; i < length; i++) { - const toModel = models2[i]; - const node = graph[toModel]; - if (node.parent === null) { - continue; - } - conversion[toModel] = wrapConversion(toModel, graph); - } - return conversion; -} -var route_default = route; - -// node_modules/color-convert/index.js -var convert2 = {}; -var models = Object.keys(conversions_default); -function wrapRaw(fn) { - const wrappedFn = function(...args) { - const arg0 = args[0]; - if (arg0 === void 0 || arg0 === null) { - return arg0; - } - if (arg0.length > 1) { - args = arg0; - } - return fn(args); - }; - if ("conversion" in fn) { - wrappedFn.conversion = fn.conversion; - } - return wrappedFn; -} -function wrapRounded(fn) { - const wrappedFn = function(...args) { - const arg0 = args[0]; - if (arg0 === void 0 || arg0 === null) { - return arg0; - } - if (arg0.length > 1) { - args = arg0; - } - const result = fn(args); - if (typeof result === "object") { - for (let { length } = result, i = 0; i < length; i++) { - result[i] = Math.round(result[i]); - } - } - return result; - }; - if ("conversion" in fn) { - wrappedFn.conversion = fn.conversion; - } - return wrappedFn; -} -for (const fromModel of models) { - convert2[fromModel] = {}; - Object.defineProperty(convert2[fromModel], "channels", { value: conversions_default[fromModel].channels }); - Object.defineProperty(convert2[fromModel], "labels", { value: conversions_default[fromModel].labels }); - const routes = route_default(fromModel); - const routeModels = Object.keys(routes); - for (const toModel of routeModels) { - const fn = routes[toModel]; - convert2[fromModel][toModel] = wrapRounded(fn); - convert2[fromModel][toModel].raw = wrapRaw(fn); - } -} -var color_convert_default = convert2; - -// node_modules/color/index.js -var skippedModels = [ - // To be honest, I don't really feel like keyword belongs in color convert, but eh. - "keyword", - // Gray conflicts with some method names, and has its own method defined. - "gray", - // Shouldn't really be in color-convert either... - "hex" -]; -var hashedModelKeys = {}; -for (const model of Object.keys(color_convert_default)) { - hashedModelKeys[[...color_convert_default[model].labels].sort().join("")] = model; -} -var limiters = {}; -function Color(object, model) { - if (!(this instanceof Color)) { - return new Color(object, model); - } - if (model && model in skippedModels) { - model = null; - } - if (model && !(model in color_convert_default)) { - throw new Error("Unknown model: " + model); - } - let i; - let channels; - if (object == null) { - this.model = "rgb"; - this.color = [0, 0, 0]; - this.valpha = 1; - } else if (object instanceof Color) { - this.model = object.model; - this.color = [...object.color]; - this.valpha = object.valpha; - } else if (typeof object === "string") { - const result = color_string_default.get(object); - if (result === null) { - throw new Error("Unable to parse color from string: " + object); - } - this.model = result.model; - channels = color_convert_default[this.model].channels; - this.color = result.value.slice(0, channels); - this.valpha = typeof result.value[channels] === "number" ? result.value[channels] : 1; - } else if (object.length > 0) { - this.model = model || "rgb"; - channels = color_convert_default[this.model].channels; - const newArray = Array.prototype.slice.call(object, 0, channels); - this.color = zeroArray(newArray, channels); - this.valpha = typeof object[channels] === "number" ? object[channels] : 1; - } else if (typeof object === "number") { - this.model = "rgb"; - this.color = [ - object >> 16 & 255, - object >> 8 & 255, - object & 255 - ]; - this.valpha = 1; - } else { - this.valpha = 1; - const keys = Object.keys(object); - if ("alpha" in object) { - keys.splice(keys.indexOf("alpha"), 1); - this.valpha = typeof object.alpha === "number" ? object.alpha : 0; - } - const hashedKeys = keys.sort().join(""); - if (!(hashedKeys in hashedModelKeys)) { - throw new Error("Unable to parse color from object: " + JSON.stringify(object)); - } - this.model = hashedModelKeys[hashedKeys]; - const { labels } = color_convert_default[this.model]; - const color = []; - for (i = 0; i < labels.length; i++) { - color.push(object[labels[i]]); - } - this.color = zeroArray(color); - } - if (limiters[this.model]) { - channels = color_convert_default[this.model].channels; - for (i = 0; i < channels; i++) { - const limit = limiters[this.model][i]; - if (limit) { - this.color[i] = limit(this.color[i]); - } - } - } - this.valpha = Math.max(0, Math.min(1, this.valpha)); - if (Object.freeze) { - Object.freeze(this); - } -} -Color.prototype = { - toString() { - return this.string(); - }, - toJSON() { - return this[this.model](); - }, - string(places) { - let self = this.model in color_string_default.to ? this : this.rgb(); - self = self.round(typeof places === "number" ? places : 1); - const arguments_ = self.valpha === 1 ? self.color : [...self.color, this.valpha]; - return color_string_default.to[self.model](...arguments_); - }, - percentString(places) { - const self = this.rgb().round(typeof places === "number" ? places : 1); - const arguments_ = self.valpha === 1 ? self.color : [...self.color, this.valpha]; - return color_string_default.to.rgb.percent(...arguments_); - }, - array() { - return this.valpha === 1 ? [...this.color] : [...this.color, this.valpha]; - }, - object() { - const result = {}; - const { channels } = color_convert_default[this.model]; - const { labels } = color_convert_default[this.model]; - for (let i = 0; i < channels; i++) { - result[labels[i]] = this.color[i]; - } - if (this.valpha !== 1) { - result.alpha = this.valpha; - } - return result; - }, - unitArray() { - const rgb = this.rgb().color; - rgb[0] /= 255; - rgb[1] /= 255; - rgb[2] /= 255; - if (this.valpha !== 1) { - rgb.push(this.valpha); - } - return rgb; - }, - unitObject() { - const rgb = this.rgb().object(); - rgb.r /= 255; - rgb.g /= 255; - rgb.b /= 255; - if (this.valpha !== 1) { - rgb.alpha = this.valpha; - } - return rgb; - }, - round(places) { - places = Math.max(places || 0, 0); - return new Color([...this.color.map(roundToPlace(places)), this.valpha], this.model); - }, - alpha(value) { - if (value !== void 0) { - return new Color([...this.color, Math.max(0, Math.min(1, value))], this.model); - } - return this.valpha; - }, - // Rgb - red: getset("rgb", 0, maxfn(255)), - green: getset("rgb", 1, maxfn(255)), - blue: getset("rgb", 2, maxfn(255)), - hue: getset(["hsl", "hsv", "hsl", "hwb", "hcg"], 0, (value) => (value % 360 + 360) % 360), - saturationl: getset("hsl", 1, maxfn(100)), - lightness: getset("hsl", 2, maxfn(100)), - saturationv: getset("hsv", 1, maxfn(100)), - value: getset("hsv", 2, maxfn(100)), - chroma: getset("hcg", 1, maxfn(100)), - gray: getset("hcg", 2, maxfn(100)), - white: getset("hwb", 1, maxfn(100)), - wblack: getset("hwb", 2, maxfn(100)), - cyan: getset("cmyk", 0, maxfn(100)), - magenta: getset("cmyk", 1, maxfn(100)), - yellow: getset("cmyk", 2, maxfn(100)), - black: getset("cmyk", 3, maxfn(100)), - x: getset("xyz", 0, maxfn(95.047)), - y: getset("xyz", 1, maxfn(100)), - z: getset("xyz", 2, maxfn(108.833)), - l: getset("lab", 0, maxfn(100)), - a: getset("lab", 1), - b: getset("lab", 2), - keyword(value) { - if (value !== void 0) { - return new Color(value); - } - return color_convert_default[this.model].keyword(this.color); - }, - hex(value) { - if (value !== void 0) { - return new Color(value); - } - return color_string_default.to.hex(...this.rgb().round().color); - }, - hexa(value) { - if (value !== void 0) { - return new Color(value); - } - const rgbArray = this.rgb().round().color; - let alphaHex = Math.round(this.valpha * 255).toString(16).toUpperCase(); - if (alphaHex.length === 1) { - alphaHex = "0" + alphaHex; - } - return color_string_default.to.hex(...rgbArray) + alphaHex; - }, - rgbNumber() { - const rgb = this.rgb().color; - return (rgb[0] & 255) << 16 | (rgb[1] & 255) << 8 | rgb[2] & 255; - }, - luminosity() { - const rgb = this.rgb().color; - const lum = []; - for (const [i, element] of rgb.entries()) { - const chan = element / 255; - lum[i] = chan <= 0.04045 ? chan / 12.92 : ((chan + 0.055) / 1.055) ** 2.4; - } - return 0.2126 * lum[0] + 0.7152 * lum[1] + 0.0722 * lum[2]; - }, - contrast(color2) { - const lum1 = this.luminosity(); - const lum2 = color2.luminosity(); - if (lum1 > lum2) { - return (lum1 + 0.05) / (lum2 + 0.05); - } - return (lum2 + 0.05) / (lum1 + 0.05); - }, - level(color2) { - const contrastRatio = this.contrast(color2); - if (contrastRatio >= 7) { - return "AAA"; - } - return contrastRatio >= 4.5 ? "AA" : ""; - }, - isDark() { - const rgb = this.rgb().color; - const yiq = (rgb[0] * 2126 + rgb[1] * 7152 + rgb[2] * 722) / 1e4; - return yiq < 128; - }, - isLight() { - return !this.isDark(); - }, - negate() { - const rgb = this.rgb(); - for (let i = 0; i < 3; i++) { - rgb.color[i] = 255 - rgb.color[i]; - } - return rgb; - }, - lighten(ratio) { - const hsl = this.hsl(); - hsl.color[2] += hsl.color[2] * ratio; - return hsl; - }, - darken(ratio) { - const hsl = this.hsl(); - hsl.color[2] -= hsl.color[2] * ratio; - return hsl; - }, - saturate(ratio) { - const hsl = this.hsl(); - hsl.color[1] += hsl.color[1] * ratio; - return hsl; - }, - desaturate(ratio) { - const hsl = this.hsl(); - hsl.color[1] -= hsl.color[1] * ratio; - return hsl; - }, - whiten(ratio) { - const hwb = this.hwb(); - hwb.color[1] += hwb.color[1] * ratio; - return hwb; - }, - blacken(ratio) { - const hwb = this.hwb(); - hwb.color[2] += hwb.color[2] * ratio; - return hwb; - }, - grayscale() { - const rgb = this.rgb().color; - const value = rgb[0] * 0.3 + rgb[1] * 0.59 + rgb[2] * 0.11; - return Color.rgb(value, value, value); - }, - fade(ratio) { - return this.alpha(this.valpha - this.valpha * ratio); - }, - opaquer(ratio) { - return this.alpha(this.valpha + this.valpha * ratio); - }, - rotate(degrees) { - const hsl = this.hsl(); - let hue = hsl.color[0]; - hue = (hue + degrees) % 360; - hue = hue < 0 ? 360 + hue : hue; - hsl.color[0] = hue; - return hsl; - }, - mix(mixinColor, weight) { - if (!mixinColor || !mixinColor.rgb) { - throw new Error('Argument to "mix" was not a Color instance, but rather an instance of ' + typeof mixinColor); - } - const color1 = mixinColor.rgb(); - const color2 = this.rgb(); - const p = weight === void 0 ? 0.5 : weight; - const w = 2 * p - 1; - const a = color1.alpha() - color2.alpha(); - const w1 = ((w * a === -1 ? w : (w + a) / (1 + w * a)) + 1) / 2; - const w2 = 1 - w1; - return Color.rgb( - w1 * color1.red() + w2 * color2.red(), - w1 * color1.green() + w2 * color2.green(), - w1 * color1.blue() + w2 * color2.blue(), - color1.alpha() * p + color2.alpha() * (1 - p) - ); - } -}; -for (const model of Object.keys(color_convert_default)) { - if (skippedModels.includes(model)) { - continue; - } - const { channels } = color_convert_default[model]; - Color.prototype[model] = function(...arguments_) { - if (this.model === model) { - return new Color(this); - } - if (arguments_.length > 0) { - return new Color(arguments_, model); - } - return new Color([...assertArray(color_convert_default[this.model][model].raw(this.color)), this.valpha], model); - }; - Color[model] = function(...arguments_) { - let color = arguments_[0]; - if (typeof color === "number") { - color = zeroArray(arguments_, channels); - } - return new Color(color, model); - }; -} -function roundTo(number, places) { - return Number(number.toFixed(places)); -} -function roundToPlace(places) { - return function(number) { - return roundTo(number, places); - }; -} -function getset(model, channel, modifier) { - model = Array.isArray(model) ? model : [model]; - for (const m of model) { - (limiters[m] ||= [])[channel] = modifier; - } - model = model[0]; - return function(value) { - let result; - if (value !== void 0) { - if (modifier) { - value = modifier(value); - } - result = this[model](); - result.color[channel] = value; - return result; - } - result = this[model]().color[channel]; - if (modifier) { - result = modifier(result); - } - return result; - }; -} -function maxfn(max) { - return function(v) { - return Math.max(0, Math.min(max, v)); - }; -} -function assertArray(value) { - return Array.isArray(value) ? value : [value]; -} -function zeroArray(array, length) { - for (let i = 0; i < length; i++) { - if (typeof array[i] !== "number") { - array[i] = 0; - } - } - return array; -} -var index_default = Color; diff --git a/claude-code-source/node_modules/@img/colour/index.cjs b/claude-code-source/node_modules/@img/colour/index.cjs deleted file mode 100644 index 25596b2b..00000000 --- a/claude-code-source/node_modules/@img/colour/index.cjs +++ /dev/null @@ -1 +0,0 @@ -module.exports = require("./color.cjs").default; diff --git a/claude-code-source/node_modules/@inquirer/confirm/dist/esm/index.mjs b/claude-code-source/node_modules/@inquirer/confirm/dist/esm/index.mjs deleted file mode 100644 index ec2dcf79..00000000 --- a/claude-code-source/node_modules/@inquirer/confirm/dist/esm/index.mjs +++ /dev/null @@ -1,33 +0,0 @@ -import { createPrompt, useState, useKeypress, isEnterKey, usePrefix, makeTheme, } from '@inquirer/core'; -export default createPrompt((config, done) => { - const { transformer = (answer) => (answer ? 'yes' : 'no') } = config; - const [status, setStatus] = useState('idle'); - const [value, setValue] = useState(''); - const theme = makeTheme(config.theme); - const prefix = usePrefix({ status, theme }); - useKeypress((key, rl) => { - if (isEnterKey(key)) { - let answer = config.default !== false; - if (/^(y|yes)/i.test(value)) - answer = true; - else if (/^(n|no)/i.test(value)) - answer = false; - setValue(transformer(answer)); - setStatus('done'); - done(answer); - } - else { - setValue(rl.line); - } - }); - let formattedValue = value; - let defaultValue = ''; - if (status === 'done') { - formattedValue = theme.style.answer(value); - } - else { - defaultValue = ` ${theme.style.defaultAnswer(config.default === false ? 'y/N' : 'Y/n')}`; - } - const message = theme.style.message(config.message, status); - return `${prefix} ${message}${defaultValue} ${formattedValue}`; -}); diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/index.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/index.mjs deleted file mode 100644 index 772ef6c0..00000000 --- a/claude-code-source/node_modules/@inquirer/core/dist/esm/index.mjs +++ /dev/null @@ -1,12 +0,0 @@ -export * from './lib/key.mjs'; -export * from './lib/errors.mjs'; -export { usePrefix } from './lib/use-prefix.mjs'; -export { useState } from './lib/use-state.mjs'; -export { useEffect } from './lib/use-effect.mjs'; -export { useMemo } from './lib/use-memo.mjs'; -export { useRef } from './lib/use-ref.mjs'; -export { useKeypress } from './lib/use-keypress.mjs'; -export { makeTheme } from './lib/make-theme.mjs'; -export { usePagination } from './lib/pagination/use-pagination.mjs'; -export { createPrompt } from './lib/create-prompt.mjs'; -export { Separator } from './lib/Separator.mjs'; diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/Separator.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/Separator.mjs deleted file mode 100644 index f0d8409a..00000000 --- a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/Separator.mjs +++ /dev/null @@ -1,21 +0,0 @@ -import colors from 'yoctocolors-cjs'; -import figures from '@inquirer/figures'; -/** - * Separator object - * Used to space/separate choices group - */ -export class Separator { - separator = colors.dim(Array.from({ length: 15 }).join(figures.line)); - type = 'separator'; - constructor(separator) { - if (separator) { - this.separator = separator; - } - } - static isSeparator(choice) { - return Boolean(choice && - typeof choice === 'object' && - 'type' in choice && - choice.type === 'separator'); - } -} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/create-prompt.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/create-prompt.mjs deleted file mode 100644 index 379e2dd6..00000000 --- a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/create-prompt.mjs +++ /dev/null @@ -1,84 +0,0 @@ -import * as readline from 'node:readline'; -import { AsyncResource } from 'node:async_hooks'; -import MuteStream from 'mute-stream'; -import { onExit as onSignalExit } from 'signal-exit'; -import ScreenManager from './screen-manager.mjs'; -import { PromisePolyfill } from './promise-polyfill.mjs'; -import { withHooks, effectScheduler } from './hook-engine.mjs'; -import { AbortPromptError, CancelPromptError, ExitPromptError } from './errors.mjs'; -export function createPrompt(view) { - const prompt = (config, context = {}) => { - // Default `input` to stdin - const { input = process.stdin, signal } = context; - const cleanups = new Set(); - // Add mute capabilities to the output - const output = new MuteStream(); - output.pipe(context.output ?? process.stdout); - const rl = readline.createInterface({ - terminal: true, - input, - output, - }); - const screen = new ScreenManager(rl); - const { promise, resolve, reject } = PromisePolyfill.withResolver(); - /** @deprecated pass an AbortSignal in the context options instead. See {@link https://github.com/SBoudrias/Inquirer.js#canceling-prompt} */ - const cancel = () => reject(new CancelPromptError()); - if (signal) { - const abort = () => reject(new AbortPromptError({ cause: signal.reason })); - if (signal.aborted) { - abort(); - return Object.assign(promise, { cancel }); - } - signal.addEventListener('abort', abort); - cleanups.add(() => signal.removeEventListener('abort', abort)); - } - cleanups.add(onSignalExit((code, signal) => { - reject(new ExitPromptError(`User force closed the prompt with ${code} ${signal}`)); - })); - // Re-renders only happen when the state change; but the readline cursor could change position - // and that also requires a re-render (and a manual one because we mute the streams). - // We set the listener after the initial workLoop to avoid a double render if render triggered - // by a state change sets the cursor to the right position. - const checkCursorPos = () => screen.checkCursorPos(); - rl.input.on('keypress', checkCursorPos); - cleanups.add(() => rl.input.removeListener('keypress', checkCursorPos)); - return withHooks(rl, (cycle) => { - // The close event triggers immediately when the user press ctrl+c. SignalExit on the other hand - // triggers after the process is done (which happens after timeouts are done triggering.) - // We triggers the hooks cleanup phase on rl `close` so active timeouts can be cleared. - const hooksCleanup = AsyncResource.bind(() => effectScheduler.clearAll()); - rl.on('close', hooksCleanup); - cleanups.add(() => rl.removeListener('close', hooksCleanup)); - cycle(() => { - try { - const nextView = view(config, (value) => { - setImmediate(() => resolve(value)); - }); - const [content, bottomContent] = typeof nextView === 'string' ? [nextView] : nextView; - screen.render(content, bottomContent); - effectScheduler.run(); - } - catch (error) { - reject(error); - } - }); - return Object.assign(promise - .then((answer) => { - effectScheduler.clearAll(); - return answer; - }, (error) => { - effectScheduler.clearAll(); - throw error; - }) - // Wait for the promise to settle, then cleanup. - .finally(() => { - cleanups.forEach((cleanup) => cleanup()); - screen.done({ clearContent: Boolean(context?.clearPromptOnDone) }); - output.end(); - }) - // Once cleanup is done, let the expose promise resolve/reject to the internal one. - .then(() => promise), { cancel }); - }); - }; - return prompt; -} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/errors.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/errors.mjs deleted file mode 100644 index 153a9363..00000000 --- a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/errors.mjs +++ /dev/null @@ -1,21 +0,0 @@ -export class AbortPromptError extends Error { - name = 'AbortPromptError'; - message = 'Prompt was aborted'; - constructor(options) { - super(); - this.cause = options?.cause; - } -} -export class CancelPromptError extends Error { - name = 'CancelPromptError'; - message = 'Prompt was canceled'; -} -export class ExitPromptError extends Error { - name = 'ExitPromptError'; -} -export class HookError extends Error { - name = 'HookError'; -} -export class ValidationError extends Error { - name = 'ValidationError'; -} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/hook-engine.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/hook-engine.mjs deleted file mode 100644 index b2712e0a..00000000 --- a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/hook-engine.mjs +++ /dev/null @@ -1,110 +0,0 @@ -/* eslint @typescript-eslint/no-explicit-any: ["off"] */ -import { AsyncLocalStorage, AsyncResource } from 'node:async_hooks'; -import { HookError, ValidationError } from './errors.mjs'; -const hookStorage = new AsyncLocalStorage(); -function createStore(rl) { - const store = { - rl, - hooks: [], - hooksCleanup: [], - hooksEffect: [], - index: 0, - handleChange() { }, - }; - return store; -} -// Run callback in with the hook engine setup. -export function withHooks(rl, cb) { - const store = createStore(rl); - return hookStorage.run(store, () => { - function cycle(render) { - store.handleChange = () => { - store.index = 0; - render(); - }; - store.handleChange(); - } - return cb(cycle); - }); -} -// Safe getStore utility that'll return the store or throw if undefined. -function getStore() { - const store = hookStorage.getStore(); - if (!store) { - throw new HookError('[Inquirer] Hook functions can only be called from within a prompt'); - } - return store; -} -export function readline() { - return getStore().rl; -} -// Merge state updates happening within the callback function to avoid multiple renders. -export function withUpdates(fn) { - const wrapped = (...args) => { - const store = getStore(); - let shouldUpdate = false; - const oldHandleChange = store.handleChange; - store.handleChange = () => { - shouldUpdate = true; - }; - const returnValue = fn(...args); - if (shouldUpdate) { - oldHandleChange(); - } - store.handleChange = oldHandleChange; - return returnValue; - }; - return AsyncResource.bind(wrapped); -} -export function withPointer(cb) { - const store = getStore(); - const { index } = store; - const pointer = { - get() { - return store.hooks[index]; - }, - set(value) { - store.hooks[index] = value; - }, - initialized: index in store.hooks, - }; - const returnValue = cb(pointer); - store.index++; - return returnValue; -} -export function handleChange() { - getStore().handleChange(); -} -export const effectScheduler = { - queue(cb) { - const store = getStore(); - const { index } = store; - store.hooksEffect.push(() => { - store.hooksCleanup[index]?.(); - const cleanFn = cb(readline()); - if (cleanFn != null && typeof cleanFn !== 'function') { - throw new ValidationError('useEffect return value must be a cleanup function or nothing.'); - } - store.hooksCleanup[index] = cleanFn; - }); - }, - run() { - const store = getStore(); - withUpdates(() => { - store.hooksEffect.forEach((effect) => { - effect(); - }); - // Warning: Clean the hooks before exiting the `withUpdates` block. - // Failure to do so means an updates would hit the same effects again. - store.hooksEffect.length = 0; - })(); - }, - clearAll() { - const store = getStore(); - store.hooksCleanup.forEach((cleanFn) => { - cleanFn?.(); - }); - store.hooksEffect.length = 0; - store.hooksCleanup.length = 0; - }, -}; diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/key.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/key.mjs deleted file mode 100644 index a6f25125..00000000 --- a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/key.mjs +++ /dev/null @@ -1,18 +0,0 @@ -export const isUpKey = (key) => -// The up key -key.name === 'up' || - // Vim keybinding - key.name === 'k' || - // Emacs keybinding - (key.ctrl && key.name === 'p'); -export const isDownKey = (key) => -// The down key -key.name === 'down' || - // Vim keybinding - key.name === 'j' || - // Emacs keybinding - (key.ctrl && key.name === 'n'); -export const isSpaceKey = (key) => key.name === 'space'; -export const isBackspaceKey = (key) => key.name === 'backspace'; -export const isNumberKey = (key) => '123456789'.includes(key.name); -export const isEnterKey = (key) => key.name === 'enter' || key.name === 'return'; diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/make-theme.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/make-theme.mjs deleted file mode 100644 index 504da44e..00000000 --- a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/make-theme.mjs +++ /dev/null @@ -1,30 +0,0 @@ -import { defaultTheme } from './theme.mjs'; -function isPlainObject(value) { - if (typeof value !== 'object' || value === null) - return false; - let proto = value; - while (Object.getPrototypeOf(proto) !== null) { - proto = Object.getPrototypeOf(proto); - } - return Object.getPrototypeOf(value) === proto; -} -function deepMerge(...objects) { - const output = {}; - for (const obj of objects) { - for (const [key, value] of Object.entries(obj)) { - const prevValue = output[key]; - output[key] = - isPlainObject(prevValue) && isPlainObject(value) - ? deepMerge(prevValue, value) - : value; - } - } - return output; -} -export function makeTheme(...themes) { - const themesToMerge = [ - defaultTheme, - ...themes.filter((theme) => theme != null), - ]; - return deepMerge(...themesToMerge); -} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/lines.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/lines.mjs deleted file mode 100644 index 2969033c..00000000 --- a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/lines.mjs +++ /dev/null @@ -1,59 +0,0 @@ -import { breakLines } from '../utils.mjs'; -function split(content, width) { - return breakLines(content, width).split('\n'); -} -/** - * Rotates an array of items by an integer number of positions. - * @param {number} count The number of positions to rotate by - * @param {T[]} items The items to rotate - */ -function rotate(count, items) { - const max = items.length; - const offset = ((count % max) + max) % max; - return [...items.slice(offset), ...items.slice(0, offset)]; -} -/** - * Renders a page of items as lines that fit within the given width ensuring - * that the number of lines is not greater than the page size, and the active - * item renders at the provided position, while prioritizing that as many lines - * of the active item get rendered as possible. - */ -export function lines({ items, width, renderItem, active, position: requested, pageSize, }) { - const layouts = items.map((item, index) => ({ - item, - index, - isActive: index === active, - })); - const layoutsInPage = rotate(active - requested, layouts).slice(0, pageSize); - const renderItemAt = (index) => layoutsInPage[index] == null ? [] : split(renderItem(layoutsInPage[index]), width); - // Create a blank array of lines for the page - const pageBuffer = Array.from({ length: pageSize }); - // Render the active item to decide the position - const activeItem = renderItemAt(requested).slice(0, pageSize); - const position = requested + activeItem.length <= pageSize ? requested : pageSize - activeItem.length; - // Add the lines of the active item into the page - pageBuffer.splice(position, activeItem.length, ...activeItem); - // Fill the page under the active item - let bufferPointer = position + activeItem.length; - let layoutPointer = requested + 1; - while (bufferPointer < pageSize && layoutPointer < layoutsInPage.length) { - for (const line of renderItemAt(layoutPointer)) { - pageBuffer[bufferPointer++] = line; - if (bufferPointer >= pageSize) - break; - } - layoutPointer++; - } - // Fill the page over the active item - bufferPointer = position - 1; - layoutPointer = requested - 1; - while (bufferPointer >= 0 && layoutPointer >= 0) { - for (const line of renderItemAt(layoutPointer).reverse()) { - pageBuffer[bufferPointer--] = line; - if (bufferPointer < 0) - break; - } - layoutPointer--; - } - return pageBuffer.filter((line) => typeof line === 'string'); -} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/position.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/position.mjs deleted file mode 100644 index 9e3cc2eb..00000000 --- a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/position.mjs +++ /dev/null @@ -1,27 +0,0 @@ -/** - * Creates the next position for the active item considering a finite list of - * items to be rendered on a page. - */ -export function finite({ active, pageSize, total, }) { - const middle = Math.floor(pageSize / 2); - if (total <= pageSize || active < middle) - return active; - if (active >= total - middle) - return active + pageSize - total; - return middle; -} -/** - * Creates the next position for the active item considering an infinitely - * looping list of items to be rendered on the page. - */ -export function infinite({ active, lastActive, total, pageSize, pointer, }) { - if (total <= pageSize) - return active; - // Move the position only when the user moves down, and when the - // navigation fits within a single page - if (lastActive < active && active - lastActive < pageSize) { - // Limit it to the middle of the list - return Math.min(Math.floor(pageSize / 2), pointer + active - lastActive); - } - return pointer; -} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/use-pagination.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/use-pagination.mjs deleted file mode 100644 index b8459233..00000000 --- a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/pagination/use-pagination.mjs +++ /dev/null @@ -1,30 +0,0 @@ -import { useRef } from '../use-ref.mjs'; -import { readlineWidth } from '../utils.mjs'; -import { lines } from './lines.mjs'; -import { finite, infinite } from './position.mjs'; -export function usePagination({ items, active, renderItem, pageSize, loop = true, }) { - const state = useRef({ position: 0, lastActive: 0 }); - const position = loop - ? infinite({ - active, - lastActive: state.current.lastActive, - total: items.length, - pageSize, - pointer: state.current.position, - }) - : finite({ - active, - total: items.length, - pageSize, - }); - state.current.position = position; - state.current.lastActive = active; - return lines({ - items, - width: readlineWidth(), - renderItem, - active, - position, - pageSize, - }).join('\n'); -} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/promise-polyfill.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/promise-polyfill.mjs deleted file mode 100644 index 621708ee..00000000 --- a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/promise-polyfill.mjs +++ /dev/null @@ -1,14 +0,0 @@ -// TODO: Remove this class once Node 22 becomes the minimum supported version. -export class PromisePolyfill extends Promise { - // Available starting from Node 22 - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/withResolvers - static withResolver() { - let resolve; - let reject; - const promise = new Promise((res, rej) => { - resolve = res; - reject = rej; - }); - return { promise, resolve: resolve, reject: reject }; - } -} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/screen-manager.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/screen-manager.mjs deleted file mode 100644 index 40ac8f55..00000000 --- a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/screen-manager.mjs +++ /dev/null @@ -1,85 +0,0 @@ -import stripAnsi from 'strip-ansi'; -import ansiEscapes from 'ansi-escapes'; -import { breakLines, readlineWidth } from './utils.mjs'; -const height = (content) => content.split('\n').length; -const lastLine = (content) => content.split('\n').pop() ?? ''; -function cursorDown(n) { - return n > 0 ? ansiEscapes.cursorDown(n) : ''; -} -export default class ScreenManager { - rl; - // These variables are keeping information to allow correct prompt re-rendering - height = 0; - extraLinesUnderPrompt = 0; - cursorPos; - constructor(rl) { - this.rl = rl; - this.rl = rl; - this.cursorPos = rl.getCursorPos(); - } - write(content) { - this.rl.output.unmute(); - this.rl.output.write(content); - this.rl.output.mute(); - } - render(content, bottomContent = '') { - // Write message to screen and setPrompt to control backspace - const promptLine = lastLine(content); - const rawPromptLine = stripAnsi(promptLine); - // Remove the rl.line from our prompt. We can't rely on the content of - // rl.line (mainly because of the password prompt), so just rely on it's - // length. - let prompt = rawPromptLine; - if (this.rl.line.length > 0) { - prompt = prompt.slice(0, -this.rl.line.length); - } - this.rl.setPrompt(prompt); - // SetPrompt will change cursor position, now we can get correct value - this.cursorPos = this.rl.getCursorPos(); - const width = readlineWidth(); - content = breakLines(content, width); - bottomContent = breakLines(bottomContent, width); - // Manually insert an extra line if we're at the end of the line. - // This prevent the cursor from appearing at the beginning of the - // current line. - if (rawPromptLine.length % width === 0) { - content += '\n'; - } - let output = content + (bottomContent ? '\n' + bottomContent : ''); - /** - * Re-adjust the cursor at the correct position. - */ - // We need to consider parts of the prompt under the cursor as part of the bottom - // content in order to correctly cleanup and re-render. - const promptLineUpDiff = Math.floor(rawPromptLine.length / width) - this.cursorPos.rows; - const bottomContentHeight = promptLineUpDiff + (bottomContent ? height(bottomContent) : 0); - // Return cursor to the input position (on top of the bottomContent) - if (bottomContentHeight > 0) - output += ansiEscapes.cursorUp(bottomContentHeight); - // Return cursor to the initial left offset. - output += ansiEscapes.cursorTo(this.cursorPos.cols); - /** - * Render and store state for future re-rendering - */ - this.write(cursorDown(this.extraLinesUnderPrompt) + - ansiEscapes.eraseLines(this.height) + - output); - this.extraLinesUnderPrompt = bottomContentHeight; - this.height = height(output); - } - checkCursorPos() { - const cursorPos = this.rl.getCursorPos(); - if (cursorPos.cols !== this.cursorPos.cols) { - this.write(ansiEscapes.cursorTo(cursorPos.cols)); - this.cursorPos = cursorPos; - } - } - done({ clearContent }) { - this.rl.setPrompt(''); - let output = cursorDown(this.extraLinesUnderPrompt); - output += clearContent ? ansiEscapes.eraseLines(this.height) : '\n'; - output += ansiEscapes.cursorShow; - this.write(output); - this.rl.close(); - } -} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/theme.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/theme.mjs deleted file mode 100644 index d52a2da8..00000000 --- a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/theme.mjs +++ /dev/null @@ -1,22 +0,0 @@ -import colors from 'yoctocolors-cjs'; -import figures from '@inquirer/figures'; -export const defaultTheme = { - prefix: { - idle: colors.blue('?'), - // TODO: use figure - done: colors.green(figures.tick), - }, - spinner: { - interval: 80, - frames: ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'].map((frame) => colors.yellow(frame)), - }, - style: { - answer: colors.cyan, - message: colors.bold, - error: (text) => colors.red(`> ${text}`), - defaultAnswer: (text) => colors.dim(`(${text})`), - help: colors.dim, - highlight: colors.cyan, - key: (text) => colors.cyan(colors.bold(`<${text}>`)), - }, -}; diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-effect.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-effect.mjs deleted file mode 100644 index 8c30102e..00000000 --- a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-effect.mjs +++ /dev/null @@ -1,11 +0,0 @@ -import { withPointer, effectScheduler } from './hook-engine.mjs'; -export function useEffect(cb, depArray) { - withPointer((pointer) => { - const oldDeps = pointer.get(); - const hasChanged = !Array.isArray(oldDeps) || depArray.some((dep, i) => !Object.is(dep, oldDeps[i])); - if (hasChanged) { - effectScheduler.queue(cb); - } - pointer.set(depArray); - }); -} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-keypress.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-keypress.mjs deleted file mode 100644 index 2649502f..00000000 --- a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-keypress.mjs +++ /dev/null @@ -1,20 +0,0 @@ -import { useRef } from './use-ref.mjs'; -import { useEffect } from './use-effect.mjs'; -import { withUpdates } from './hook-engine.mjs'; -export function useKeypress(userHandler) { - const signal = useRef(userHandler); - signal.current = userHandler; - useEffect((rl) => { - let ignore = false; - const handler = withUpdates((_input, event) => { - if (ignore) - return; - void signal.current(event, rl); - }); - rl.input.on('keypress', handler); - return () => { - ignore = true; - rl.input.removeListener('keypress', handler); - }; - }, []); -} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-memo.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-memo.mjs deleted file mode 100644 index a6558e82..00000000 --- a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-memo.mjs +++ /dev/null @@ -1,14 +0,0 @@ -import { withPointer } from './hook-engine.mjs'; -export function useMemo(fn, dependencies) { - return withPointer((pointer) => { - const prev = pointer.get(); - if (!prev || - prev.dependencies.length !== dependencies.length || - prev.dependencies.some((dep, i) => dep !== dependencies[i])) { - const value = fn(); - pointer.set({ value, dependencies }); - return value; - } - return prev.value; - }); -} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-prefix.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-prefix.mjs deleted file mode 100644 index c849f395..00000000 --- a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-prefix.mjs +++ /dev/null @@ -1,36 +0,0 @@ -import { AsyncResource } from 'node:async_hooks'; -import { useState } from './use-state.mjs'; -import { useEffect } from './use-effect.mjs'; -import { makeTheme } from './make-theme.mjs'; -export function usePrefix({ status = 'idle', theme, }) { - const [showLoader, setShowLoader] = useState(false); - const [tick, setTick] = useState(0); - const { prefix, spinner } = makeTheme(theme); - useEffect(() => { - if (status === 'loading') { - let tickInterval; - let inc = -1; - // Delay displaying spinner by 300ms, to avoid flickering - const delayTimeout = setTimeout(AsyncResource.bind(() => { - setShowLoader(true); - tickInterval = setInterval(AsyncResource.bind(() => { - inc = inc + 1; - setTick(inc % spinner.frames.length); - }), spinner.interval); - }), 300); - return () => { - clearTimeout(delayTimeout); - clearInterval(tickInterval); - }; - } - else { - setShowLoader(false); - } - }, [status]); - if (showLoader) { - return spinner.frames[tick]; - } - // There's a delay before we show the loader. So we want to ignore `loading` here, and pass idle instead. - const iconName = status === 'loading' ? 'idle' : status; - return typeof prefix === 'string' ? prefix : prefix[iconName]; -} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-ref.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-ref.mjs deleted file mode 100644 index 69ecc68c..00000000 --- a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-ref.mjs +++ /dev/null @@ -1,4 +0,0 @@ -import { useState } from './use-state.mjs'; -export function useRef(val) { - return useState({ current: val })[0]; -} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-state.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-state.mjs deleted file mode 100644 index 3629bf09..00000000 --- a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/use-state.mjs +++ /dev/null @@ -1,19 +0,0 @@ -import { withPointer, handleChange } from './hook-engine.mjs'; -export function useState(defaultValue) { - return withPointer((pointer) => { - const setFn = (newValue) => { - // Noop if the value is still the same. - if (pointer.get() !== newValue) { - pointer.set(newValue); - // Trigger re-render - handleChange(); - } - }; - if (pointer.initialized) { - return [pointer.get(), setFn]; - } - const value = typeof defaultValue === 'function' ? defaultValue() : defaultValue; - pointer.set(value); - return [value, setFn]; - }); -} diff --git a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/utils.mjs b/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/utils.mjs deleted file mode 100644 index 1e7ae89d..00000000 --- a/claude-code-source/node_modules/@inquirer/core/dist/esm/lib/utils.mjs +++ /dev/null @@ -1,25 +0,0 @@ -import cliWidth from 'cli-width'; -import wrapAnsi from 'wrap-ansi'; -import { readline } from './hook-engine.mjs'; -/** - * Force line returns at specific width. This function is ANSI code friendly and it'll - * ignore invisible codes during width calculation. - * @param {string} content - * @param {number} width - * @return {string} - */ -export function breakLines(content, width) { - return content - .split('\n') - .flatMap((line) => wrapAnsi(line, width, { trim: false, hard: true }) - .split('\n') - .map((str) => str.trimEnd())) - .join('\n'); -} -/** - * Returns the width of the active readline, or 80 as default value. - * @returns {number} - */ -export function readlineWidth() { - return cliWidth({ defaultWidth: 80, output: readline().output }); -} diff --git a/claude-code-source/node_modules/@inquirer/core/node_modules/ansi-escapes/index.js b/claude-code-source/node_modules/@inquirer/core/node_modules/ansi-escapes/index.js deleted file mode 100644 index 28333185..00000000 --- a/claude-code-source/node_modules/@inquirer/core/node_modules/ansi-escapes/index.js +++ /dev/null @@ -1,157 +0,0 @@ -'use strict'; -const ansiEscapes = module.exports; -// TODO: remove this in the next major version -module.exports.default = ansiEscapes; - -const ESC = '\u001B['; -const OSC = '\u001B]'; -const BEL = '\u0007'; -const SEP = ';'; -const isTerminalApp = process.env.TERM_PROGRAM === 'Apple_Terminal'; - -ansiEscapes.cursorTo = (x, y) => { - if (typeof x !== 'number') { - throw new TypeError('The `x` argument is required'); - } - - if (typeof y !== 'number') { - return ESC + (x + 1) + 'G'; - } - - return ESC + (y + 1) + ';' + (x + 1) + 'H'; -}; - -ansiEscapes.cursorMove = (x, y) => { - if (typeof x !== 'number') { - throw new TypeError('The `x` argument is required'); - } - - let ret = ''; - - if (x < 0) { - ret += ESC + (-x) + 'D'; - } else if (x > 0) { - ret += ESC + x + 'C'; - } - - if (y < 0) { - ret += ESC + (-y) + 'A'; - } else if (y > 0) { - ret += ESC + y + 'B'; - } - - return ret; -}; - -ansiEscapes.cursorUp = (count = 1) => ESC + count + 'A'; -ansiEscapes.cursorDown = (count = 1) => ESC + count + 'B'; -ansiEscapes.cursorForward = (count = 1) => ESC + count + 'C'; -ansiEscapes.cursorBackward = (count = 1) => ESC + count + 'D'; - -ansiEscapes.cursorLeft = ESC + 'G'; -ansiEscapes.cursorSavePosition = isTerminalApp ? '\u001B7' : ESC + 's'; -ansiEscapes.cursorRestorePosition = isTerminalApp ? '\u001B8' : ESC + 'u'; -ansiEscapes.cursorGetPosition = ESC + '6n'; -ansiEscapes.cursorNextLine = ESC + 'E'; -ansiEscapes.cursorPrevLine = ESC + 'F'; -ansiEscapes.cursorHide = ESC + '?25l'; -ansiEscapes.cursorShow = ESC + '?25h'; - -ansiEscapes.eraseLines = count => { - let clear = ''; - - for (let i = 0; i < count; i++) { - clear += ansiEscapes.eraseLine + (i < count - 1 ? ansiEscapes.cursorUp() : ''); - } - - if (count) { - clear += ansiEscapes.cursorLeft; - } - - return clear; -}; - -ansiEscapes.eraseEndLine = ESC + 'K'; -ansiEscapes.eraseStartLine = ESC + '1K'; -ansiEscapes.eraseLine = ESC + '2K'; -ansiEscapes.eraseDown = ESC + 'J'; -ansiEscapes.eraseUp = ESC + '1J'; -ansiEscapes.eraseScreen = ESC + '2J'; -ansiEscapes.scrollUp = ESC + 'S'; -ansiEscapes.scrollDown = ESC + 'T'; - -ansiEscapes.clearScreen = '\u001Bc'; - -ansiEscapes.clearTerminal = process.platform === 'win32' ? - `${ansiEscapes.eraseScreen}${ESC}0f` : - // 1. Erases the screen (Only done in case `2` is not supported) - // 2. Erases the whole screen including scrollback buffer - // 3. Moves cursor to the top-left position - // More info: https://www.real-world-systems.com/docs/ANSIcode.html - `${ansiEscapes.eraseScreen}${ESC}3J${ESC}H`; - -ansiEscapes.beep = BEL; - -ansiEscapes.link = (text, url) => { - return [ - OSC, - '8', - SEP, - SEP, - url, - BEL, - text, - OSC, - '8', - SEP, - SEP, - BEL - ].join(''); -}; - -ansiEscapes.image = (buffer, options = {}) => { - let ret = `${OSC}1337;File=inline=1`; - - if (options.width) { - ret += `;width=${options.width}`; - } - - if (options.height) { - ret += `;height=${options.height}`; - } - - if (options.preserveAspectRatio === false) { - ret += ';preserveAspectRatio=0'; - } - - return ret + ':' + buffer.toString('base64') + BEL; -}; - -ansiEscapes.iTerm = { - setCwd: (cwd = process.cwd()) => `${OSC}50;CurrentDir=${cwd}${BEL}`, - - annotation: (message, options = {}) => { - let ret = `${OSC}1337;`; - - const hasX = typeof options.x !== 'undefined'; - const hasY = typeof options.y !== 'undefined'; - if ((hasX || hasY) && !(hasX && hasY && typeof options.length !== 'undefined')) { - throw new Error('`x`, `y` and `length` must be defined when `x` or `y` is defined'); - } - - message = message.replace(/\|/g, ''); - - ret += options.isHidden ? 'AddHiddenAnnotation=' : 'AddAnnotation='; - - if (options.length > 0) { - ret += - (hasX ? - [message, options.length, options.x, options.y] : - [options.length, message]).join('|'); - } else { - ret += message; - } - - return ret + BEL; - } -}; diff --git a/claude-code-source/node_modules/@inquirer/core/node_modules/mute-stream/lib/index.js b/claude-code-source/node_modules/@inquirer/core/node_modules/mute-stream/lib/index.js deleted file mode 100644 index 368f727e..00000000 --- a/claude-code-source/node_modules/@inquirer/core/node_modules/mute-stream/lib/index.js +++ /dev/null @@ -1,142 +0,0 @@ -const Stream = require('stream') - -class MuteStream extends Stream { - #isTTY = null - - constructor (opts = {}) { - super(opts) - this.writable = this.readable = true - this.muted = false - this.on('pipe', this._onpipe) - this.replace = opts.replace - - // For readline-type situations - // This much at the start of a line being redrawn after a ctrl char - // is seen (such as backspace) won't be redrawn as the replacement - this._prompt = opts.prompt || null - this._hadControl = false - } - - #destSrc (key, def) { - if (this._dest) { - return this._dest[key] - } - if (this._src) { - return this._src[key] - } - return def - } - - #proxy (method, ...args) { - if (typeof this._dest?.[method] === 'function') { - this._dest[method](...args) - } - if (typeof this._src?.[method] === 'function') { - this._src[method](...args) - } - } - - get isTTY () { - if (this.#isTTY !== null) { - return this.#isTTY - } - return this.#destSrc('isTTY', false) - } - - // basically just get replace the getter/setter with a regular value - set isTTY (val) { - this.#isTTY = val - } - - get rows () { - return this.#destSrc('rows') - } - - get columns () { - return this.#destSrc('columns') - } - - mute () { - this.muted = true - } - - unmute () { - this.muted = false - } - - _onpipe (src) { - this._src = src - } - - pipe (dest, options) { - this._dest = dest - return super.pipe(dest, options) - } - - pause () { - if (this._src) { - return this._src.pause() - } - } - - resume () { - if (this._src) { - return this._src.resume() - } - } - - write (c) { - if (this.muted) { - if (!this.replace) { - return true - } - // eslint-disable-next-line no-control-regex - if (c.match(/^\u001b/)) { - if (c.indexOf(this._prompt) === 0) { - c = c.slice(this._prompt.length) - c = c.replace(/./g, this.replace) - c = this._prompt + c - } - this._hadControl = true - return this.emit('data', c) - } else { - if (this._prompt && this._hadControl && - c.indexOf(this._prompt) === 0) { - this._hadControl = false - this.emit('data', this._prompt) - c = c.slice(this._prompt.length) - } - c = c.toString().replace(/./g, this.replace) - } - } - this.emit('data', c) - } - - end (c) { - if (this.muted) { - if (c && this.replace) { - c = c.toString().replace(/./g, this.replace) - } else { - c = null - } - } - if (c) { - this.emit('data', c) - } - this.emit('end') - } - - destroy (...args) { - return this.#proxy('destroy', ...args) - } - - destroySoon (...args) { - return this.#proxy('destroySoon', ...args) - } - - close (...args) { - return this.#proxy('close', ...args) - } -} - -module.exports = MuteStream diff --git a/claude-code-source/node_modules/@inquirer/core/node_modules/strip-ansi/index.js b/claude-code-source/node_modules/@inquirer/core/node_modules/strip-ansi/index.js deleted file mode 100644 index 9a593dfc..00000000 --- a/claude-code-source/node_modules/@inquirer/core/node_modules/strip-ansi/index.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; -const ansiRegex = require('ansi-regex'); - -module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; diff --git a/claude-code-source/node_modules/@inquirer/core/node_modules/strip-ansi/node_modules/ansi-regex/index.js b/claude-code-source/node_modules/@inquirer/core/node_modules/strip-ansi/node_modules/ansi-regex/index.js deleted file mode 100644 index 616ff837..00000000 --- a/claude-code-source/node_modules/@inquirer/core/node_modules/strip-ansi/node_modules/ansi-regex/index.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -module.exports = ({onlyFirst = false} = {}) => { - const pattern = [ - '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', - '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' - ].join('|'); - - return new RegExp(pattern, onlyFirst ? undefined : 'g'); -}; diff --git a/claude-code-source/node_modules/@inquirer/core/node_modules/wrap-ansi/index.js b/claude-code-source/node_modules/@inquirer/core/node_modules/wrap-ansi/index.js deleted file mode 100644 index a6e54431..00000000 --- a/claude-code-source/node_modules/@inquirer/core/node_modules/wrap-ansi/index.js +++ /dev/null @@ -1,186 +0,0 @@ -'use strict'; -const stringWidth = require('string-width'); -const stripAnsi = require('strip-ansi'); -const ansiStyles = require('ansi-styles'); - -const ESCAPES = new Set([ - '\u001B', - '\u009B' -]); - -const END_CODE = 39; - -const wrapAnsi = code => `${ESCAPES.values().next().value}[${code}m`; - -// Calculate the length of words split on ' ', ignoring -// the extra characters added by ansi escape codes -const wordLengths = string => string.split(' ').map(character => stringWidth(character)); - -// Wrap a long word across multiple rows -// Ansi escape codes do not count towards length -const wrapWord = (rows, word, columns) => { - const characters = [...word]; - - let isInsideEscape = false; - let visible = stringWidth(stripAnsi(rows[rows.length - 1])); - - for (const [index, character] of characters.entries()) { - const characterLength = stringWidth(character); - - if (visible + characterLength <= columns) { - rows[rows.length - 1] += character; - } else { - rows.push(character); - visible = 0; - } - - if (ESCAPES.has(character)) { - isInsideEscape = true; - } else if (isInsideEscape && character === 'm') { - isInsideEscape = false; - continue; - } - - if (isInsideEscape) { - continue; - } - - visible += characterLength; - - if (visible === columns && index < characters.length - 1) { - rows.push(''); - visible = 0; - } - } - - // It's possible that the last row we copy over is only - // ansi escape characters, handle this edge-case - if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { - rows[rows.length - 2] += rows.pop(); - } -}; - -// Trims spaces from a string ignoring invisible sequences -const stringVisibleTrimSpacesRight = str => { - const words = str.split(' '); - let last = words.length; - - while (last > 0) { - if (stringWidth(words[last - 1]) > 0) { - break; - } - - last--; - } - - if (last === words.length) { - return str; - } - - return words.slice(0, last).join(' ') + words.slice(last).join(''); -}; - -// The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode -// -// 'hard' will never allow a string to take up more than columns characters -// -// 'soft' allows long words to expand past the column length -const exec = (string, columns, options = {}) => { - if (options.trim !== false && string.trim() === '') { - return ''; - } - - let pre = ''; - let ret = ''; - let escapeCode; - - const lengths = wordLengths(string); - let rows = ['']; - - for (const [index, word] of string.split(' ').entries()) { - if (options.trim !== false) { - rows[rows.length - 1] = rows[rows.length - 1].trimLeft(); - } - - let rowLength = stringWidth(rows[rows.length - 1]); - - if (index !== 0) { - if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { - // If we start with a new word but the current row length equals the length of the columns, add a new row - rows.push(''); - rowLength = 0; - } - - if (rowLength > 0 || options.trim === false) { - rows[rows.length - 1] += ' '; - rowLength++; - } - } - - // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns' - if (options.hard && lengths[index] > columns) { - const remainingColumns = (columns - rowLength); - const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); - const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); - if (breaksStartingNextLine < breaksStartingThisLine) { - rows.push(''); - } - - wrapWord(rows, word, columns); - continue; - } - - if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { - if (options.wordWrap === false && rowLength < columns) { - wrapWord(rows, word, columns); - continue; - } - - rows.push(''); - } - - if (rowLength + lengths[index] > columns && options.wordWrap === false) { - wrapWord(rows, word, columns); - continue; - } - - rows[rows.length - 1] += word; - } - - if (options.trim !== false) { - rows = rows.map(stringVisibleTrimSpacesRight); - } - - pre = rows.join('\n'); - - for (const [index, character] of [...pre].entries()) { - ret += character; - - if (ESCAPES.has(character)) { - const code = parseFloat(/\d[^m]*/.exec(pre.slice(index, index + 4))); - escapeCode = code === END_CODE ? null : code; - } - - const code = ansiStyles.codes.get(Number(escapeCode)); - - if (escapeCode && code) { - if (pre[index + 1] === '\n') { - ret += wrapAnsi(code); - } else if (character === '\n') { - ret += wrapAnsi(escapeCode); - } - } - } - - return ret; -}; - -// For each newline, invoke the method separately -module.exports = (string, columns, options) => { - return String(string) - .normalize() - .replace(/\r\n/g, '\n') - .split('\n') - .map(line => exec(line, columns, options)) - .join('\n'); -}; diff --git a/claude-code-source/node_modules/@inquirer/core/node_modules/wrap-ansi/node_modules/ansi-styles/index.js b/claude-code-source/node_modules/@inquirer/core/node_modules/wrap-ansi/node_modules/ansi-styles/index.js deleted file mode 100644 index 5d82581a..00000000 --- a/claude-code-source/node_modules/@inquirer/core/node_modules/wrap-ansi/node_modules/ansi-styles/index.js +++ /dev/null @@ -1,163 +0,0 @@ -'use strict'; - -const wrapAnsi16 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${code + offset}m`; -}; - -const wrapAnsi256 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${38 + offset};5;${code}m`; -}; - -const wrapAnsi16m = (fn, offset) => (...args) => { - const rgb = fn(...args); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; -}; - -const ansi2ansi = n => n; -const rgb2rgb = (r, g, b) => [r, g, b]; - -const setLazyProperty = (object, property, get) => { - Object.defineProperty(object, property, { - get: () => { - const value = get(); - - Object.defineProperty(object, property, { - value, - enumerable: true, - configurable: true - }); - - return value; - }, - enumerable: true, - configurable: true - }); -}; - -/** @type {typeof import('color-convert')} */ -let colorConvert; -const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { - if (colorConvert === undefined) { - colorConvert = require('color-convert'); - } - - const offset = isBackground ? 10 : 0; - const styles = {}; - - for (const [sourceSpace, suite] of Object.entries(colorConvert)) { - const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; - if (sourceSpace === targetSpace) { - styles[name] = wrap(identity, offset); - } else if (typeof suite === 'object') { - styles[name] = wrap(suite[targetSpace], offset); - } - } - - return styles; -}; - -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - - // Bright color - blackBright: [90, 39], - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; - - // Alias bright black as gray (and grey) - styles.color.gray = styles.color.blackBright; - styles.bgColor.bgGray = styles.bgColor.bgBlackBright; - styles.color.grey = styles.color.blackBright; - styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; - - for (const [groupName, group] of Object.entries(styles)) { - for (const [styleName, style] of Object.entries(group)) { - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; - - group[styleName] = styles[styleName]; - - codes.set(style[0], style[1]); - } - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - } - - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; - - setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); - setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); - - return styles; -} - -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); diff --git a/claude-code-source/node_modules/@inquirer/figures/dist/esm/index.js b/claude-code-source/node_modules/@inquirer/figures/dist/esm/index.js deleted file mode 100644 index d43b15e6..00000000 --- a/claude-code-source/node_modules/@inquirer/figures/dist/esm/index.js +++ /dev/null @@ -1,309 +0,0 @@ -// process.env dot-notation access prints: -// Property 'TERM' comes from an index signature, so it must be accessed with ['TERM'].ts(4111) -/* eslint dot-notation: ["off"] */ -import process from 'node:process'; -// Ported from is-unicode-supported -function isUnicodeSupported() { - if (process.platform !== 'win32') { - return process.env['TERM'] !== 'linux'; // Linux console (kernel) - } - return (Boolean(process.env['WT_SESSION']) || // Windows Terminal - Boolean(process.env['TERMINUS_SUBLIME']) || // Terminus (<0.2.27) - process.env['ConEmuTask'] === '{cmd::Cmder}' || // ConEmu and cmder - process.env['TERM_PROGRAM'] === 'Terminus-Sublime' || - process.env['TERM_PROGRAM'] === 'vscode' || - process.env['TERM'] === 'xterm-256color' || - process.env['TERM'] === 'alacritty' || - process.env['TERMINAL_EMULATOR'] === 'JetBrains-JediTerm'); -} -// Ported from figures -const common = { - circleQuestionMark: '(?)', - questionMarkPrefix: '(?)', - square: '█', - squareDarkShade: '▓', - squareMediumShade: '▒', - squareLightShade: '░', - squareTop: '▀', - squareBottom: '▄', - squareLeft: '▌', - squareRight: '▐', - squareCenter: '■', - bullet: '●', - dot: '․', - ellipsis: '…', - pointerSmall: '›', - triangleUp: '▲', - triangleUpSmall: '▴', - triangleDown: '▼', - triangleDownSmall: '▾', - triangleLeftSmall: '◂', - triangleRightSmall: '▸', - home: '⌂', - heart: '♥', - musicNote: '♪', - musicNoteBeamed: '♫', - arrowUp: '↑', - arrowDown: '↓', - arrowLeft: '←', - arrowRight: '→', - arrowLeftRight: '↔', - arrowUpDown: '↕', - almostEqual: '≈', - notEqual: '≠', - lessOrEqual: '≤', - greaterOrEqual: '≥', - identical: '≡', - infinity: '∞', - subscriptZero: '₀', - subscriptOne: '₁', - subscriptTwo: '₂', - subscriptThree: '₃', - subscriptFour: '₄', - subscriptFive: '₅', - subscriptSix: '₆', - subscriptSeven: '₇', - subscriptEight: '₈', - subscriptNine: '₉', - oneHalf: '½', - oneThird: '⅓', - oneQuarter: '¼', - oneFifth: '⅕', - oneSixth: '⅙', - oneEighth: '⅛', - twoThirds: '⅔', - twoFifths: '⅖', - threeQuarters: '¾', - threeFifths: '⅗', - threeEighths: '⅜', - fourFifths: '⅘', - fiveSixths: '⅚', - fiveEighths: '⅝', - sevenEighths: '⅞', - line: '─', - lineBold: '━', - lineDouble: '═', - lineDashed0: '┄', - lineDashed1: '┅', - lineDashed2: '┈', - lineDashed3: '┉', - lineDashed4: '╌', - lineDashed5: '╍', - lineDashed6: '╴', - lineDashed7: '╶', - lineDashed8: '╸', - lineDashed9: '╺', - lineDashed10: '╼', - lineDashed11: '╾', - lineDashed12: '−', - lineDashed13: '–', - lineDashed14: '‐', - lineDashed15: '⁃', - lineVertical: '│', - lineVerticalBold: '┃', - lineVerticalDouble: '║', - lineVerticalDashed0: '┆', - lineVerticalDashed1: '┇', - lineVerticalDashed2: '┊', - lineVerticalDashed3: '┋', - lineVerticalDashed4: '╎', - lineVerticalDashed5: '╏', - lineVerticalDashed6: '╵', - lineVerticalDashed7: '╷', - lineVerticalDashed8: '╹', - lineVerticalDashed9: '╻', - lineVerticalDashed10: '╽', - lineVerticalDashed11: '╿', - lineDownLeft: '┐', - lineDownLeftArc: '╮', - lineDownBoldLeftBold: '┓', - lineDownBoldLeft: '┒', - lineDownLeftBold: '┑', - lineDownDoubleLeftDouble: '╗', - lineDownDoubleLeft: '╖', - lineDownLeftDouble: '╕', - lineDownRight: '┌', - lineDownRightArc: '╭', - lineDownBoldRightBold: '┏', - lineDownBoldRight: '┎', - lineDownRightBold: '┍', - lineDownDoubleRightDouble: '╔', - lineDownDoubleRight: '╓', - lineDownRightDouble: '╒', - lineUpLeft: '┘', - lineUpLeftArc: '╯', - lineUpBoldLeftBold: '┛', - lineUpBoldLeft: '┚', - lineUpLeftBold: '┙', - lineUpDoubleLeftDouble: '╝', - lineUpDoubleLeft: '╜', - lineUpLeftDouble: '╛', - lineUpRight: '└', - lineUpRightArc: '╰', - lineUpBoldRightBold: '┗', - lineUpBoldRight: '┖', - lineUpRightBold: '┕', - lineUpDoubleRightDouble: '╚', - lineUpDoubleRight: '╙', - lineUpRightDouble: '╘', - lineUpDownLeft: '┤', - lineUpBoldDownBoldLeftBold: '┫', - lineUpBoldDownBoldLeft: '┨', - lineUpDownLeftBold: '┥', - lineUpBoldDownLeftBold: '┩', - lineUpDownBoldLeftBold: '┪', - lineUpDownBoldLeft: '┧', - lineUpBoldDownLeft: '┦', - lineUpDoubleDownDoubleLeftDouble: '╣', - lineUpDoubleDownDoubleLeft: '╢', - lineUpDownLeftDouble: '╡', - lineUpDownRight: '├', - lineUpBoldDownBoldRightBold: '┣', - lineUpBoldDownBoldRight: '┠', - lineUpDownRightBold: '┝', - lineUpBoldDownRightBold: '┡', - lineUpDownBoldRightBold: '┢', - lineUpDownBoldRight: '┟', - lineUpBoldDownRight: '┞', - lineUpDoubleDownDoubleRightDouble: '╠', - lineUpDoubleDownDoubleRight: '╟', - lineUpDownRightDouble: '╞', - lineDownLeftRight: '┬', - lineDownBoldLeftBoldRightBold: '┳', - lineDownLeftBoldRightBold: '┯', - lineDownBoldLeftRight: '┰', - lineDownBoldLeftBoldRight: '┱', - lineDownBoldLeftRightBold: '┲', - lineDownLeftRightBold: '┮', - lineDownLeftBoldRight: '┭', - lineDownDoubleLeftDoubleRightDouble: '╦', - lineDownDoubleLeftRight: '╥', - lineDownLeftDoubleRightDouble: '╤', - lineUpLeftRight: '┴', - lineUpBoldLeftBoldRightBold: '┻', - lineUpLeftBoldRightBold: '┷', - lineUpBoldLeftRight: '┸', - lineUpBoldLeftBoldRight: '┹', - lineUpBoldLeftRightBold: '┺', - lineUpLeftRightBold: '┶', - lineUpLeftBoldRight: '┵', - lineUpDoubleLeftDoubleRightDouble: '╩', - lineUpDoubleLeftRight: '╨', - lineUpLeftDoubleRightDouble: '╧', - lineUpDownLeftRight: '┼', - lineUpBoldDownBoldLeftBoldRightBold: '╋', - lineUpDownBoldLeftBoldRightBold: '╈', - lineUpBoldDownLeftBoldRightBold: '╇', - lineUpBoldDownBoldLeftRightBold: '╊', - lineUpBoldDownBoldLeftBoldRight: '╉', - lineUpBoldDownLeftRight: '╀', - lineUpDownBoldLeftRight: '╁', - lineUpDownLeftBoldRight: '┽', - lineUpDownLeftRightBold: '┾', - lineUpBoldDownBoldLeftRight: '╂', - lineUpDownLeftBoldRightBold: '┿', - lineUpBoldDownLeftBoldRight: '╃', - lineUpBoldDownLeftRightBold: '╄', - lineUpDownBoldLeftBoldRight: '╅', - lineUpDownBoldLeftRightBold: '╆', - lineUpDoubleDownDoubleLeftDoubleRightDouble: '╬', - lineUpDoubleDownDoubleLeftRight: '╫', - lineUpDownLeftDoubleRightDouble: '╪', - lineCross: '╳', - lineBackslash: '╲', - lineSlash: '╱', -}; -const specialMainSymbols = { - tick: '✔', - info: 'ℹ', - warning: '⚠', - cross: '✘', - squareSmall: '◻', - squareSmallFilled: '◼', - circle: '◯', - circleFilled: '◉', - circleDotted: '◌', - circleDouble: '◎', - circleCircle: 'ⓞ', - circleCross: 'ⓧ', - circlePipe: 'Ⓘ', - radioOn: '◉', - radioOff: '◯', - checkboxOn: '☒', - checkboxOff: '☐', - checkboxCircleOn: 'ⓧ', - checkboxCircleOff: 'Ⓘ', - pointer: '❯', - triangleUpOutline: '△', - triangleLeft: '◀', - triangleRight: '▶', - lozenge: '◆', - lozengeOutline: '◇', - hamburger: '☰', - smiley: '㋡', - mustache: '෴', - star: '★', - play: '▶', - nodejs: '⬢', - oneSeventh: '⅐', - oneNinth: '⅑', - oneTenth: '⅒', -}; -const specialFallbackSymbols = { - tick: '√', - info: 'i', - warning: '‼', - cross: '×', - squareSmall: '□', - squareSmallFilled: '■', - circle: '( )', - circleFilled: '(*)', - circleDotted: '( )', - circleDouble: '( )', - circleCircle: '(○)', - circleCross: '(×)', - circlePipe: '(│)', - radioOn: '(*)', - radioOff: '( )', - checkboxOn: '[×]', - checkboxOff: '[ ]', - checkboxCircleOn: '(×)', - checkboxCircleOff: '( )', - pointer: '>', - triangleUpOutline: '∆', - triangleLeft: '◄', - triangleRight: '►', - lozenge: '♦', - lozengeOutline: '◊', - hamburger: '≡', - smiley: '☺', - mustache: '┌─┐', - star: '✶', - play: '►', - nodejs: '♦', - oneSeventh: '1/7', - oneNinth: '1/9', - oneTenth: '1/10', -}; -export const mainSymbols = { ...common, ...specialMainSymbols }; -export const fallbackSymbols = { - ...common, - ...specialFallbackSymbols, -}; -const shouldUseMain = isUnicodeSupported(); -const figures = shouldUseMain ? mainSymbols : fallbackSymbols; -export default figures; -const replacements = Object.entries(specialMainSymbols); -// On terminals which do not support Unicode symbols, substitute them to other symbols -export const replaceSymbols = (string, { useFallback = !shouldUseMain } = {}) => { - if (useFallback) { - for (const [key, mainSymbol] of replacements) { - const fallbackSymbol = fallbackSymbols[key]; - if (!fallbackSymbol) { - throw new Error(`Unable to find fallback for ${key}`); - } - string = string.replaceAll(mainSymbol, fallbackSymbol); - } - } - return string; -}; diff --git a/claude-code-source/node_modules/@inquirer/input/dist/esm/index.mjs b/claude-code-source/node_modules/@inquirer/input/dist/esm/index.mjs deleted file mode 100644 index 48430ace..00000000 --- a/claude-code-source/node_modules/@inquirer/input/dist/esm/index.mjs +++ /dev/null @@ -1,68 +0,0 @@ -import { createPrompt, useState, useKeypress, usePrefix, isEnterKey, isBackspaceKey, makeTheme, } from '@inquirer/core'; -export default createPrompt((config, done) => { - const { required, validate = () => true } = config; - const theme = makeTheme(config.theme); - const [status, setStatus] = useState('idle'); - const [defaultValue = '', setDefaultValue] = useState(config.default); - const [errorMsg, setError] = useState(); - const [value, setValue] = useState(''); - const prefix = usePrefix({ status, theme }); - useKeypress(async (key, rl) => { - // Ignore keypress while our prompt is doing other processing. - if (status !== 'idle') { - return; - } - if (isEnterKey(key)) { - const answer = value || defaultValue; - setStatus('loading'); - const isValid = required && !answer ? 'You must provide a value' : await validate(answer); - if (isValid === true) { - setValue(answer); - setStatus('done'); - done(answer); - } - else { - // Reset the readline line value to the previous value. On line event, the value - // get cleared, forcing the user to re-enter the value instead of fixing it. - rl.write(value); - setError(isValid || 'You must provide a valid value'); - setStatus('idle'); - } - } - else if (isBackspaceKey(key) && !value) { - setDefaultValue(undefined); - } - else if (key.name === 'tab' && !value) { - setDefaultValue(undefined); - rl.clearLine(0); // Remove the tab character. - rl.write(defaultValue); - setValue(defaultValue); - } - else { - setValue(rl.line); - setError(undefined); - } - }); - const message = theme.style.message(config.message, status); - let formattedValue = value; - if (typeof config.transformer === 'function') { - formattedValue = config.transformer(value, { isFinal: status === 'done' }); - } - else if (status === 'done') { - formattedValue = theme.style.answer(value); - } - let defaultStr; - if (defaultValue && status !== 'done' && !value) { - defaultStr = theme.style.defaultAnswer(defaultValue); - } - let error = ''; - if (errorMsg) { - error = theme.style.error(errorMsg); - } - return [ - [prefix, message, defaultStr, formattedValue] - .filter((v) => v !== undefined) - .join(' '), - error, - ]; -}); diff --git a/claude-code-source/node_modules/@inquirer/prompts/dist/esm/index.mjs b/claude-code-source/node_modules/@inquirer/prompts/dist/esm/index.mjs deleted file mode 100644 index 19263757..00000000 --- a/claude-code-source/node_modules/@inquirer/prompts/dist/esm/index.mjs +++ /dev/null @@ -1,10 +0,0 @@ -export { default as checkbox, Separator } from '@inquirer/checkbox'; -export { default as editor } from '@inquirer/editor'; -export { default as confirm } from '@inquirer/confirm'; -export { default as input } from '@inquirer/input'; -export { default as number } from '@inquirer/number'; -export { default as expand } from '@inquirer/expand'; -export { default as rawlist } from '@inquirer/rawlist'; -export { default as password } from '@inquirer/password'; -export { default as search } from '@inquirer/search'; -export { default as select } from '@inquirer/select'; diff --git a/claude-code-source/node_modules/@inquirer/select/dist/esm/index.mjs b/claude-code-source/node_modules/@inquirer/select/dist/esm/index.mjs deleted file mode 100644 index 8b9cb6da..00000000 --- a/claude-code-source/node_modules/@inquirer/select/dist/esm/index.mjs +++ /dev/null @@ -1,150 +0,0 @@ -import { createPrompt, useState, useKeypress, usePrefix, usePagination, useRef, useMemo, useEffect, isBackspaceKey, isEnterKey, isUpKey, isDownKey, isNumberKey, Separator, ValidationError, makeTheme, } from '@inquirer/core'; -import colors from 'yoctocolors-cjs'; -import figures from '@inquirer/figures'; -import ansiEscapes from 'ansi-escapes'; -const selectTheme = { - icon: { cursor: figures.pointer }, - style: { - disabled: (text) => colors.dim(`- ${text}`), - description: (text) => colors.cyan(text), - }, - helpMode: 'auto', -}; -function isSelectable(item) { - return !Separator.isSeparator(item) && !item.disabled; -} -function normalizeChoices(choices) { - return choices.map((choice) => { - if (Separator.isSeparator(choice)) - return choice; - if (typeof choice === 'string') { - return { - value: choice, - name: choice, - short: choice, - disabled: false, - }; - } - const name = choice.name ?? String(choice.value); - return { - value: choice.value, - name, - description: choice.description, - short: choice.short ?? name, - disabled: choice.disabled ?? false, - }; - }); -} -export default createPrompt((config, done) => { - const { loop = true, pageSize = 7 } = config; - const firstRender = useRef(true); - const theme = makeTheme(selectTheme, config.theme); - const [status, setStatus] = useState('idle'); - const prefix = usePrefix({ status, theme }); - const searchTimeoutRef = useRef(); - const items = useMemo(() => normalizeChoices(config.choices), [config.choices]); - const bounds = useMemo(() => { - const first = items.findIndex(isSelectable); - const last = items.findLastIndex(isSelectable); - if (first < 0) { - throw new ValidationError('[select prompt] No selectable choices. All choices are disabled.'); - } - return { first, last }; - }, [items]); - const defaultItemIndex = useMemo(() => { - if (!('default' in config)) - return -1; - return items.findIndex((item) => isSelectable(item) && item.value === config.default); - }, [config.default, items]); - const [active, setActive] = useState(defaultItemIndex === -1 ? bounds.first : defaultItemIndex); - // Safe to assume the cursor position always point to a Choice. - const selectedChoice = items[active]; - useKeypress((key, rl) => { - clearTimeout(searchTimeoutRef.current); - if (isEnterKey(key)) { - setStatus('done'); - done(selectedChoice.value); - } - else if (isUpKey(key) || isDownKey(key)) { - rl.clearLine(0); - if (loop || - (isUpKey(key) && active !== bounds.first) || - (isDownKey(key) && active !== bounds.last)) { - const offset = isUpKey(key) ? -1 : 1; - let next = active; - do { - next = (next + offset + items.length) % items.length; - } while (!isSelectable(items[next])); - setActive(next); - } - } - else if (isNumberKey(key)) { - rl.clearLine(0); - const position = Number(key.name) - 1; - const item = items[position]; - if (item != null && isSelectable(item)) { - setActive(position); - } - } - else if (isBackspaceKey(key)) { - rl.clearLine(0); - } - else { - // Default to search - const searchTerm = rl.line.toLowerCase(); - const matchIndex = items.findIndex((item) => { - if (Separator.isSeparator(item) || !isSelectable(item)) - return false; - return item.name.toLowerCase().startsWith(searchTerm); - }); - if (matchIndex >= 0) { - setActive(matchIndex); - } - searchTimeoutRef.current = setTimeout(() => { - rl.clearLine(0); - }, 700); - } - }); - useEffect(() => () => { - clearTimeout(searchTimeoutRef.current); - }, []); - const message = theme.style.message(config.message, status); - let helpTipTop = ''; - let helpTipBottom = ''; - if (theme.helpMode === 'always' || - (theme.helpMode === 'auto' && firstRender.current)) { - firstRender.current = false; - if (items.length > pageSize) { - helpTipBottom = `\n${theme.style.help('(Use arrow keys to reveal more choices)')}`; - } - else { - helpTipTop = theme.style.help('(Use arrow keys)'); - } - } - const page = usePagination({ - items, - active, - renderItem({ item, isActive }) { - if (Separator.isSeparator(item)) { - return ` ${item.separator}`; - } - if (item.disabled) { - const disabledLabel = typeof item.disabled === 'string' ? item.disabled : '(disabled)'; - return theme.style.disabled(`${item.name} ${disabledLabel}`); - } - const color = isActive ? theme.style.highlight : (x) => x; - const cursor = isActive ? theme.icon.cursor : ` `; - return color(`${cursor} ${item.name}`); - }, - pageSize, - loop, - }); - if (status === 'done') { - return `${prefix} ${message} ${theme.style.answer(selectedChoice.short)}`; - } - const choiceDescription = selectedChoice.description - ? `\n${theme.style.description(selectedChoice.description)}` - : ``; - return `${[prefix, message, helpTipTop].filter(Boolean).join(' ')}\n${page}${helpTipBottom}${choiceDescription}${ansiEscapes.cursorHide}`; -}); -export { Separator } from '@inquirer/core'; diff --git a/claude-code-source/node_modules/@inquirer/select/node_modules/ansi-escapes/index.js b/claude-code-source/node_modules/@inquirer/select/node_modules/ansi-escapes/index.js deleted file mode 100644 index 28333185..00000000 --- a/claude-code-source/node_modules/@inquirer/select/node_modules/ansi-escapes/index.js +++ /dev/null @@ -1,157 +0,0 @@ -'use strict'; -const ansiEscapes = module.exports; -// TODO: remove this in the next major version -module.exports.default = ansiEscapes; - -const ESC = '\u001B['; -const OSC = '\u001B]'; -const BEL = '\u0007'; -const SEP = ';'; -const isTerminalApp = process.env.TERM_PROGRAM === 'Apple_Terminal'; - -ansiEscapes.cursorTo = (x, y) => { - if (typeof x !== 'number') { - throw new TypeError('The `x` argument is required'); - } - - if (typeof y !== 'number') { - return ESC + (x + 1) + 'G'; - } - - return ESC + (y + 1) + ';' + (x + 1) + 'H'; -}; - -ansiEscapes.cursorMove = (x, y) => { - if (typeof x !== 'number') { - throw new TypeError('The `x` argument is required'); - } - - let ret = ''; - - if (x < 0) { - ret += ESC + (-x) + 'D'; - } else if (x > 0) { - ret += ESC + x + 'C'; - } - - if (y < 0) { - ret += ESC + (-y) + 'A'; - } else if (y > 0) { - ret += ESC + y + 'B'; - } - - return ret; -}; - -ansiEscapes.cursorUp = (count = 1) => ESC + count + 'A'; -ansiEscapes.cursorDown = (count = 1) => ESC + count + 'B'; -ansiEscapes.cursorForward = (count = 1) => ESC + count + 'C'; -ansiEscapes.cursorBackward = (count = 1) => ESC + count + 'D'; - -ansiEscapes.cursorLeft = ESC + 'G'; -ansiEscapes.cursorSavePosition = isTerminalApp ? '\u001B7' : ESC + 's'; -ansiEscapes.cursorRestorePosition = isTerminalApp ? '\u001B8' : ESC + 'u'; -ansiEscapes.cursorGetPosition = ESC + '6n'; -ansiEscapes.cursorNextLine = ESC + 'E'; -ansiEscapes.cursorPrevLine = ESC + 'F'; -ansiEscapes.cursorHide = ESC + '?25l'; -ansiEscapes.cursorShow = ESC + '?25h'; - -ansiEscapes.eraseLines = count => { - let clear = ''; - - for (let i = 0; i < count; i++) { - clear += ansiEscapes.eraseLine + (i < count - 1 ? ansiEscapes.cursorUp() : ''); - } - - if (count) { - clear += ansiEscapes.cursorLeft; - } - - return clear; -}; - -ansiEscapes.eraseEndLine = ESC + 'K'; -ansiEscapes.eraseStartLine = ESC + '1K'; -ansiEscapes.eraseLine = ESC + '2K'; -ansiEscapes.eraseDown = ESC + 'J'; -ansiEscapes.eraseUp = ESC + '1J'; -ansiEscapes.eraseScreen = ESC + '2J'; -ansiEscapes.scrollUp = ESC + 'S'; -ansiEscapes.scrollDown = ESC + 'T'; - -ansiEscapes.clearScreen = '\u001Bc'; - -ansiEscapes.clearTerminal = process.platform === 'win32' ? - `${ansiEscapes.eraseScreen}${ESC}0f` : - // 1. Erases the screen (Only done in case `2` is not supported) - // 2. Erases the whole screen including scrollback buffer - // 3. Moves cursor to the top-left position - // More info: https://www.real-world-systems.com/docs/ANSIcode.html - `${ansiEscapes.eraseScreen}${ESC}3J${ESC}H`; - -ansiEscapes.beep = BEL; - -ansiEscapes.link = (text, url) => { - return [ - OSC, - '8', - SEP, - SEP, - url, - BEL, - text, - OSC, - '8', - SEP, - SEP, - BEL - ].join(''); -}; - -ansiEscapes.image = (buffer, options = {}) => { - let ret = `${OSC}1337;File=inline=1`; - - if (options.width) { - ret += `;width=${options.width}`; - } - - if (options.height) { - ret += `;height=${options.height}`; - } - - if (options.preserveAspectRatio === false) { - ret += ';preserveAspectRatio=0'; - } - - return ret + ':' + buffer.toString('base64') + BEL; -}; - -ansiEscapes.iTerm = { - setCwd: (cwd = process.cwd()) => `${OSC}50;CurrentDir=${cwd}${BEL}`, - - annotation: (message, options = {}) => { - let ret = `${OSC}1337;`; - - const hasX = typeof options.x !== 'undefined'; - const hasY = typeof options.y !== 'undefined'; - if ((hasX || hasY) && !(hasX && hasY && typeof options.length !== 'undefined')) { - throw new Error('`x`, `y` and `length` must be defined when `x` or `y` is defined'); - } - - message = message.replace(/\|/g, ''); - - ret += options.isHidden ? 'AddHiddenAnnotation=' : 'AddAnnotation='; - - if (options.length > 0) { - ret += - (hasX ? - [message, options.length, options.x, options.y] : - [options.length, message]).join('|'); - } else { - ret += message; - } - - return ret + BEL; - } -}; diff --git a/claude-code-source/node_modules/@js-sdsl/ordered-map/dist/cjs/index.js b/claude-code-source/node_modules/@js-sdsl/ordered-map/dist/cjs/index.js deleted file mode 100644 index 575a7fa2..00000000 --- a/claude-code-source/node_modules/@js-sdsl/ordered-map/dist/cjs/index.js +++ /dev/null @@ -1,795 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "t", { - value: true -}); - -class TreeNode { - constructor(t, e, s = 1) { - this.i = undefined; - this.h = undefined; - this.o = undefined; - this.u = t; - this.l = e; - this.p = s; - } - I() { - let t = this; - const e = t.o.o === t; - if (e && t.p === 1) { - t = t.h; - } else if (t.i) { - t = t.i; - while (t.h) { - t = t.h; - } - } else { - if (e) { - return t.o; - } - let s = t.o; - while (s.i === t) { - t = s; - s = t.o; - } - t = s; - } - return t; - } - B() { - let t = this; - if (t.h) { - t = t.h; - while (t.i) { - t = t.i; - } - return t; - } else { - let e = t.o; - while (e.h === t) { - t = e; - e = t.o; - } - if (t.h !== e) { - return e; - } else return t; - } - } - _() { - const t = this.o; - const e = this.h; - const s = e.i; - if (t.o === this) t.o = e; else if (t.i === this) t.i = e; else t.h = e; - e.o = t; - e.i = this; - this.o = e; - this.h = s; - if (s) s.o = this; - return e; - } - g() { - const t = this.o; - const e = this.i; - const s = e.h; - if (t.o === this) t.o = e; else if (t.i === this) t.i = e; else t.h = e; - e.o = t; - e.h = this; - this.o = e; - this.i = s; - if (s) s.o = this; - return e; - } -} - -class TreeNodeEnableIndex extends TreeNode { - constructor() { - super(...arguments); - this.M = 1; - } - _() { - const t = super._(); - this.O(); - t.O(); - return t; - } - g() { - const t = super.g(); - this.O(); - t.O(); - return t; - } - O() { - this.M = 1; - if (this.i) { - this.M += this.i.M; - } - if (this.h) { - this.M += this.h.M; - } - } -} - -class ContainerIterator { - constructor(t = 0) { - this.iteratorType = t; - } - equals(t) { - return this.T === t.T; - } -} - -class Base { - constructor() { - this.m = 0; - } - get length() { - return this.m; - } - size() { - return this.m; - } - empty() { - return this.m === 0; - } -} - -class Container extends Base {} - -function throwIteratorAccessError() { - throw new RangeError("Iterator access denied!"); -} - -class TreeContainer extends Container { - constructor(t = function(t, e) { - if (t < e) return -1; - if (t > e) return 1; - return 0; - }, e = false) { - super(); - this.v = undefined; - this.A = t; - this.enableIndex = e; - this.N = e ? TreeNodeEnableIndex : TreeNode; - this.C = new this.N; - } - R(t, e) { - let s = this.C; - while (t) { - const i = this.A(t.u, e); - if (i < 0) { - t = t.h; - } else if (i > 0) { - s = t; - t = t.i; - } else return t; - } - return s; - } - K(t, e) { - let s = this.C; - while (t) { - const i = this.A(t.u, e); - if (i <= 0) { - t = t.h; - } else { - s = t; - t = t.i; - } - } - return s; - } - L(t, e) { - let s = this.C; - while (t) { - const i = this.A(t.u, e); - if (i < 0) { - s = t; - t = t.h; - } else if (i > 0) { - t = t.i; - } else return t; - } - return s; - } - k(t, e) { - let s = this.C; - while (t) { - const i = this.A(t.u, e); - if (i < 0) { - s = t; - t = t.h; - } else { - t = t.i; - } - } - return s; - } - P(t) { - while (true) { - const e = t.o; - if (e === this.C) return; - if (t.p === 1) { - t.p = 0; - return; - } - if (t === e.i) { - const s = e.h; - if (s.p === 1) { - s.p = 0; - e.p = 1; - if (e === this.v) { - this.v = e._(); - } else e._(); - } else { - if (s.h && s.h.p === 1) { - s.p = e.p; - e.p = 0; - s.h.p = 0; - if (e === this.v) { - this.v = e._(); - } else e._(); - return; - } else if (s.i && s.i.p === 1) { - s.p = 1; - s.i.p = 0; - s.g(); - } else { - s.p = 1; - t = e; - } - } - } else { - const s = e.i; - if (s.p === 1) { - s.p = 0; - e.p = 1; - if (e === this.v) { - this.v = e.g(); - } else e.g(); - } else { - if (s.i && s.i.p === 1) { - s.p = e.p; - e.p = 0; - s.i.p = 0; - if (e === this.v) { - this.v = e.g(); - } else e.g(); - return; - } else if (s.h && s.h.p === 1) { - s.p = 1; - s.h.p = 0; - s._(); - } else { - s.p = 1; - t = e; - } - } - } - } - } - S(t) { - if (this.m === 1) { - this.clear(); - return; - } - let e = t; - while (e.i || e.h) { - if (e.h) { - e = e.h; - while (e.i) e = e.i; - } else { - e = e.i; - } - const s = t.u; - t.u = e.u; - e.u = s; - const i = t.l; - t.l = e.l; - e.l = i; - t = e; - } - if (this.C.i === e) { - this.C.i = e.o; - } else if (this.C.h === e) { - this.C.h = e.o; - } - this.P(e); - let s = e.o; - if (e === s.i) { - s.i = undefined; - } else s.h = undefined; - this.m -= 1; - this.v.p = 0; - if (this.enableIndex) { - while (s !== this.C) { - s.M -= 1; - s = s.o; - } - } - } - U(t) { - const e = typeof t === "number" ? t : undefined; - const s = typeof t === "function" ? t : undefined; - const i = typeof t === "undefined" ? [] : undefined; - let r = 0; - let n = this.v; - const h = []; - while (h.length || n) { - if (n) { - h.push(n); - n = n.i; - } else { - n = h.pop(); - if (r === e) return n; - i && i.push(n); - s && s(n, r, this); - r += 1; - n = n.h; - } - } - return i; - } - j(t) { - while (true) { - const e = t.o; - if (e.p === 0) return; - const s = e.o; - if (e === s.i) { - const i = s.h; - if (i && i.p === 1) { - i.p = e.p = 0; - if (s === this.v) return; - s.p = 1; - t = s; - continue; - } else if (t === e.h) { - t.p = 0; - if (t.i) { - t.i.o = e; - } - if (t.h) { - t.h.o = s; - } - e.h = t.i; - s.i = t.h; - t.i = e; - t.h = s; - if (s === this.v) { - this.v = t; - this.C.o = t; - } else { - const e = s.o; - if (e.i === s) { - e.i = t; - } else e.h = t; - } - t.o = s.o; - e.o = t; - s.o = t; - s.p = 1; - } else { - e.p = 0; - if (s === this.v) { - this.v = s.g(); - } else s.g(); - s.p = 1; - return; - } - } else { - const i = s.i; - if (i && i.p === 1) { - i.p = e.p = 0; - if (s === this.v) return; - s.p = 1; - t = s; - continue; - } else if (t === e.i) { - t.p = 0; - if (t.i) { - t.i.o = s; - } - if (t.h) { - t.h.o = e; - } - s.h = t.i; - e.i = t.h; - t.i = s; - t.h = e; - if (s === this.v) { - this.v = t; - this.C.o = t; - } else { - const e = s.o; - if (e.i === s) { - e.i = t; - } else e.h = t; - } - t.o = s.o; - e.o = t; - s.o = t; - s.p = 1; - } else { - e.p = 0; - if (s === this.v) { - this.v = s._(); - } else s._(); - s.p = 1; - return; - } - } - if (this.enableIndex) { - e.O(); - s.O(); - t.O(); - } - return; - } - } - q(t, e, s) { - if (this.v === undefined) { - this.m += 1; - this.v = new this.N(t, e, 0); - this.v.o = this.C; - this.C.o = this.C.i = this.C.h = this.v; - return this.m; - } - let i; - const r = this.C.i; - const n = this.A(r.u, t); - if (n === 0) { - r.l = e; - return this.m; - } else if (n > 0) { - r.i = new this.N(t, e); - r.i.o = r; - i = r.i; - this.C.i = i; - } else { - const r = this.C.h; - const n = this.A(r.u, t); - if (n === 0) { - r.l = e; - return this.m; - } else if (n < 0) { - r.h = new this.N(t, e); - r.h.o = r; - i = r.h; - this.C.h = i; - } else { - if (s !== undefined) { - const r = s.T; - if (r !== this.C) { - const s = this.A(r.u, t); - if (s === 0) { - r.l = e; - return this.m; - } else if (s > 0) { - const s = r.I(); - const n = this.A(s.u, t); - if (n === 0) { - s.l = e; - return this.m; - } else if (n < 0) { - i = new this.N(t, e); - if (s.h === undefined) { - s.h = i; - i.o = s; - } else { - r.i = i; - i.o = r; - } - } - } - } - } - if (i === undefined) { - i = this.v; - while (true) { - const s = this.A(i.u, t); - if (s > 0) { - if (i.i === undefined) { - i.i = new this.N(t, e); - i.i.o = i; - i = i.i; - break; - } - i = i.i; - } else if (s < 0) { - if (i.h === undefined) { - i.h = new this.N(t, e); - i.h.o = i; - i = i.h; - break; - } - i = i.h; - } else { - i.l = e; - return this.m; - } - } - } - } - } - if (this.enableIndex) { - let t = i.o; - while (t !== this.C) { - t.M += 1; - t = t.o; - } - } - this.j(i); - this.m += 1; - return this.m; - } - H(t, e) { - while (t) { - const s = this.A(t.u, e); - if (s < 0) { - t = t.h; - } else if (s > 0) { - t = t.i; - } else return t; - } - return t || this.C; - } - clear() { - this.m = 0; - this.v = undefined; - this.C.o = undefined; - this.C.i = this.C.h = undefined; - } - updateKeyByIterator(t, e) { - const s = t.T; - if (s === this.C) { - throwIteratorAccessError(); - } - if (this.m === 1) { - s.u = e; - return true; - } - const i = s.B().u; - if (s === this.C.i) { - if (this.A(i, e) > 0) { - s.u = e; - return true; - } - return false; - } - const r = s.I().u; - if (s === this.C.h) { - if (this.A(r, e) < 0) { - s.u = e; - return true; - } - return false; - } - if (this.A(r, e) >= 0 || this.A(i, e) <= 0) return false; - s.u = e; - return true; - } - eraseElementByPos(t) { - if (t < 0 || t > this.m - 1) { - throw new RangeError; - } - const e = this.U(t); - this.S(e); - return this.m; - } - eraseElementByKey(t) { - if (this.m === 0) return false; - const e = this.H(this.v, t); - if (e === this.C) return false; - this.S(e); - return true; - } - eraseElementByIterator(t) { - const e = t.T; - if (e === this.C) { - throwIteratorAccessError(); - } - const s = e.h === undefined; - const i = t.iteratorType === 0; - if (i) { - if (s) t.next(); - } else { - if (!s || e.i === undefined) t.next(); - } - this.S(e); - return t; - } - getHeight() { - if (this.m === 0) return 0; - function traversal(t) { - if (!t) return 0; - return Math.max(traversal(t.i), traversal(t.h)) + 1; - } - return traversal(this.v); - } -} - -class TreeIterator extends ContainerIterator { - constructor(t, e, s) { - super(s); - this.T = t; - this.C = e; - if (this.iteratorType === 0) { - this.pre = function() { - if (this.T === this.C.i) { - throwIteratorAccessError(); - } - this.T = this.T.I(); - return this; - }; - this.next = function() { - if (this.T === this.C) { - throwIteratorAccessError(); - } - this.T = this.T.B(); - return this; - }; - } else { - this.pre = function() { - if (this.T === this.C.h) { - throwIteratorAccessError(); - } - this.T = this.T.B(); - return this; - }; - this.next = function() { - if (this.T === this.C) { - throwIteratorAccessError(); - } - this.T = this.T.I(); - return this; - }; - } - } - get index() { - let t = this.T; - const e = this.C.o; - if (t === this.C) { - if (e) { - return e.M - 1; - } - return 0; - } - let s = 0; - if (t.i) { - s += t.i.M; - } - while (t !== e) { - const e = t.o; - if (t === e.h) { - s += 1; - if (e.i) { - s += e.i.M; - } - } - t = e; - } - return s; - } - isAccessible() { - return this.T !== this.C; - } -} - -class OrderedMapIterator extends TreeIterator { - constructor(t, e, s, i) { - super(t, e, i); - this.container = s; - } - get pointer() { - if (this.T === this.C) { - throwIteratorAccessError(); - } - const t = this; - return new Proxy([], { - get(e, s) { - if (s === "0") return t.T.u; else if (s === "1") return t.T.l; - e[0] = t.T.u; - e[1] = t.T.l; - return e[s]; - }, - set(e, s, i) { - if (s !== "1") { - throw new TypeError("prop must be 1"); - } - t.T.l = i; - return true; - } - }); - } - copy() { - return new OrderedMapIterator(this.T, this.C, this.container, this.iteratorType); - } -} - -class OrderedMap extends TreeContainer { - constructor(t = [], e, s) { - super(e, s); - const i = this; - t.forEach((function(t) { - i.setElement(t[0], t[1]); - })); - } - begin() { - return new OrderedMapIterator(this.C.i || this.C, this.C, this); - } - end() { - return new OrderedMapIterator(this.C, this.C, this); - } - rBegin() { - return new OrderedMapIterator(this.C.h || this.C, this.C, this, 1); - } - rEnd() { - return new OrderedMapIterator(this.C, this.C, this, 1); - } - front() { - if (this.m === 0) return; - const t = this.C.i; - return [ t.u, t.l ]; - } - back() { - if (this.m === 0) return; - const t = this.C.h; - return [ t.u, t.l ]; - } - lowerBound(t) { - const e = this.R(this.v, t); - return new OrderedMapIterator(e, this.C, this); - } - upperBound(t) { - const e = this.K(this.v, t); - return new OrderedMapIterator(e, this.C, this); - } - reverseLowerBound(t) { - const e = this.L(this.v, t); - return new OrderedMapIterator(e, this.C, this); - } - reverseUpperBound(t) { - const e = this.k(this.v, t); - return new OrderedMapIterator(e, this.C, this); - } - forEach(t) { - this.U((function(e, s, i) { - t([ e.u, e.l ], s, i); - })); - } - setElement(t, e, s) { - return this.q(t, e, s); - } - getElementByPos(t) { - if (t < 0 || t > this.m - 1) { - throw new RangeError; - } - const e = this.U(t); - return [ e.u, e.l ]; - } - find(t) { - const e = this.H(this.v, t); - return new OrderedMapIterator(e, this.C, this); - } - getElementByKey(t) { - const e = this.H(this.v, t); - return e.l; - } - union(t) { - const e = this; - t.forEach((function(t) { - e.setElement(t[0], t[1]); - })); - return this.m; - } - * [Symbol.iterator]() { - const t = this.m; - const e = this.U(); - for (let s = 0; s < t; ++s) { - const t = e[s]; - yield [ t.u, t.l ]; - } - } -} - -exports.OrderedMap = OrderedMap; -//# sourceMappingURL=index.js.map diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/CSSStyleDeclaration.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/CSSStyleDeclaration.js deleted file mode 100644 index f4ddf656..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/CSSStyleDeclaration.js +++ /dev/null @@ -1,234 +0,0 @@ -"use strict"; - -const { parse } = require('./style_parser'); - -module.exports = function (elt) { - const style = new CSSStyleDeclaration(elt) - const handler = { - get: function(target, property) { - return property in target ? target[property] : target.getPropertyValue(dasherizeProperty(property)); - }, - has: function(target, key) { - return true; - }, - set: function(target, property, value) { - if (property in target) { - target[property] = value; - } else { - target.setProperty(dasherizeProperty(property), value ?? undefined); - } - - return true; - } - }; - - return new Proxy(style, handler); -}; - -function dasherizeProperty(property) { - return property.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); -} - - -function CSSStyleDeclaration(elt) { - this._element = elt; -} - -const IMPORTANT_BANG = '!important'; - -// Utility function for parsing style declarations -// Pass in a string like "margin-left: 5px; border-style: solid" -// and this function returns an object like -// {"margin-left":"5px", "border-style":"solid"} -function parseStyles(value) { - const result = { - property: {}, - priority: {}, - } - - if (!value) { - return result; - } - - const styleValues = parse(value); - if (styleValues.length < 2) { - return result; - } - - for (let i = 0; i < styleValues.length; i += 2) { - const name = styleValues[i]; - let value = styleValues[i+1]; - - if (value.endsWith(IMPORTANT_BANG)) { - result.priority[name] = 'important'; - value = value.slice(0, -IMPORTANT_BANG.length).trim(); - } - - result.property[name] = value; - } - - return result; -} - -var NO_CHANGE = {}; // Private marker object - -CSSStyleDeclaration.prototype = Object.create(Object.prototype, { - - // Return the parsed form of the element's style attribute. - // If the element's style attribute has never been parsed - // or if it has changed since the last parse, then reparse it - // Note that the styles don't get parsed until they're actually needed - _parsed: { get: function() { - if (!this._parsedStyles || this.cssText !== this._lastParsedText) { - var text = this.cssText; - this._parsedStyles = parseStyles(text); - this._lastParsedText = text; - delete this._names; - } - return this._parsedStyles; - }}, - - // Call this method any time the parsed representation of the - // style changes. It converts the style properties to a string and - // sets cssText and the element's style attribute - _serialize: { value: function() { - var styles = this._parsed; - var s = ""; - - for(var name in styles.property) { - if (s) s += " "; - s += name + ": " + styles.property[name]; - if (styles.priority[name]) { - s += " !" + styles.priority[name]; - } - s += ";"; - } - - this.cssText = s; // also sets the style attribute - this._lastParsedText = s; // so we don't reparse - delete this._names; - }}, - - cssText: { - get: function() { - // XXX: this is a CSSStyleDeclaration for an element. - // A different impl might be necessary for a set of styles - // associated returned by getComputedStyle(), e.g. - return this._element.getAttribute("style"); - }, - set: function(value) { - // XXX: I should parse and serialize the value to - // normalize it and remove errors. FF and chrome do that. - this._element.setAttribute("style", value); - } - }, - - length: { get: function() { - if (!this._names) - this._names = Object.getOwnPropertyNames(this._parsed.property); - return this._names.length; - }}, - - item: { value: function(n) { - if (!this._names) - this._names = Object.getOwnPropertyNames(this._parsed.property); - return this._names[n]; - }}, - - getPropertyValue: { value: function(property) { - property = property.toLowerCase(); - return this._parsed.property[property] || ""; - }}, - - getPropertyPriority: { value: function(property) { - property = property.toLowerCase(); - return this._parsed.priority[property] || ""; - }}, - - setProperty: { value: function(property, value, priority) { - property = property.toLowerCase(); - if (value === null || value === undefined) { - value = ""; - } - if (priority === null || priority === undefined) { - priority = ""; - } - - // String coercion - if (value !== NO_CHANGE) { - value = "" + value; - } - - value = value.trim(); - if (value === "") { - this.removeProperty(property); - return; - } - - if (priority !== "" && priority !== NO_CHANGE && - !/^important$/i.test(priority)) { - return; - } - - var styles = this._parsed; - if (value === NO_CHANGE) { - if (!styles.property[property]) { - return; // Not a valid property name. - } - if (priority !== "") { - styles.priority[property] = "important"; - } else { - delete styles.priority[property]; - } - } else { - // We don't just accept the property value. Instead - // we parse it to ensure that it is something valid. - // If it contains a semicolon it is invalid - if (value.indexOf(";") !== -1) return; - - var newprops = parseStyles(property + ":" + value); - if (Object.getOwnPropertyNames(newprops.property).length === 0) { - return; // no valid property found - } - if (Object.getOwnPropertyNames(newprops.priority).length !== 0) { - return; // if the value included '!important' it wasn't valid. - } - - // XXX handle shorthand properties - - for (var p in newprops.property) { - styles.property[p] = newprops.property[p]; - if (priority === NO_CHANGE) { - continue; - } else if (priority !== "") { - styles.priority[p] = "important"; - } else if (styles.priority[p]) { - delete styles.priority[p]; - } - } - } - - // Serialize and update cssText and element.style! - this._serialize(); - }}, - - setPropertyValue: { value: function(property, value) { - return this.setProperty(property, value, NO_CHANGE); - }}, - - setPropertyPriority: { value: function(property, priority) { - return this.setProperty(property, NO_CHANGE, priority); - }}, - - removeProperty: { value: function(property) { - property = property.toLowerCase(); - var styles = this._parsed; - if (property in styles.property) { - delete styles.property[property]; - delete styles.priority[property]; - - // Serialize and update cssText and element.style! - this._serialize(); - } - }}, -}); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/CharacterData.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/CharacterData.js deleted file mode 100644 index 5718b55c..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/CharacterData.js +++ /dev/null @@ -1,120 +0,0 @@ -/* jshint bitwise: false */ -"use strict"; -module.exports = CharacterData; - -var Leaf = require('./Leaf'); -var utils = require('./utils'); -var ChildNode = require('./ChildNode'); -var NonDocumentTypeChildNode = require('./NonDocumentTypeChildNode'); - -function CharacterData() { - Leaf.call(this); -} - -CharacterData.prototype = Object.create(Leaf.prototype, { - // DOMString substringData(unsigned long offset, - // unsigned long count); - // The substringData(offset, count) method must run these steps: - // - // If offset is greater than the context object's - // length, throw an INDEX_SIZE_ERR exception and - // terminate these steps. - // - // If offset+count is greater than the context - // object's length, return a DOMString whose value is - // the UTF-16 code units from the offsetth UTF-16 code - // unit to the end of data. - // - // Return a DOMString whose value is the UTF-16 code - // units from the offsetth UTF-16 code unit to the - // offset+countth UTF-16 code unit in data. - substringData: { value: function substringData(offset, count) { - if (arguments.length < 2) { throw new TypeError("Not enough arguments"); } - // Convert arguments to WebIDL "unsigned long" - offset = offset >>> 0; - count = count >>> 0; - if (offset > this.data.length || offset < 0 || count < 0) { - utils.IndexSizeError(); - } - return this.data.substring(offset, offset+count); - }}, - - // void appendData(DOMString data); - // The appendData(data) method must append data to the context - // object's data. - appendData: { value: function appendData(data) { - if (arguments.length < 1) { throw new TypeError("Not enough arguments"); } - this.data += String(data); - }}, - - // void insertData(unsigned long offset, DOMString data); - // The insertData(offset, data) method must run these steps: - // - // If offset is greater than the context object's - // length, throw an INDEX_SIZE_ERR exception and - // terminate these steps. - // - // Insert data into the context object's data after - // offset UTF-16 code units. - // - insertData: { value: function insertData(offset, data) { - return this.replaceData(offset, 0, data); - }}, - - - // void deleteData(unsigned long offset, unsigned long count); - // The deleteData(offset, count) method must run these steps: - // - // If offset is greater than the context object's - // length, throw an INDEX_SIZE_ERR exception and - // terminate these steps. - // - // If offset+count is greater than the context - // object's length var count be length-offset. - // - // Starting from offset UTF-16 code units remove count - // UTF-16 code units from the context object's data. - deleteData: { value: function deleteData(offset, count) { - return this.replaceData(offset, count, ''); - }}, - - - // void replaceData(unsigned long offset, unsigned long count, - // DOMString data); - // - // The replaceData(offset, count, data) method must act as - // if the deleteData() method is invoked with offset and - // count as arguments followed by the insertData() method - // with offset and data as arguments and re-throw any - // exceptions these methods might have thrown. - replaceData: { value: function replaceData(offset, count, data) { - var curtext = this.data, len = curtext.length; - // Convert arguments to correct WebIDL type - offset = offset >>> 0; - count = count >>> 0; - data = String(data); - - if (offset > len || offset < 0) utils.IndexSizeError(); - - if (offset+count > len) - count = len - offset; - - var prefix = curtext.substring(0, offset), - suffix = curtext.substring(offset+count); - - this.data = prefix + data + suffix; - }}, - - // Utility method that Node.isEqualNode() calls to test Text and - // Comment nodes for equality. It is okay to put it here, since - // Node will have already verified that nodeType is equal - isEqual: { value: function isEqual(n) { - return this._data === n._data; - }}, - - length: { get: function() { return this.data.length; }} - -}); - -Object.defineProperties(CharacterData.prototype, ChildNode); -Object.defineProperties(CharacterData.prototype, NonDocumentTypeChildNode); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/ChildNode.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/ChildNode.js deleted file mode 100644 index f55d95f8..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/ChildNode.js +++ /dev/null @@ -1,119 +0,0 @@ -"use strict"; - -var Node = require('./Node'); -var LinkedList = require('./LinkedList'); - -var createDocumentFragmentFromArguments = function(document, args) { - var docFrag = document.createDocumentFragment(); - - for (var i=0; i 0; - } - return this._firstChild !== null; - }}, - - childNodes: { get: function() { - this._ensureChildNodes(); - return this._childNodes; - }}, - - firstChild: { get: function() { - if (this._childNodes) { - return this._childNodes.length === 0 ? null : this._childNodes[0]; - } - return this._firstChild; - }}, - - lastChild: { get: function() { - var kids = this._childNodes, first; - if (kids) { - return kids.length === 0 ? null: kids[kids.length-1]; - } - first = this._firstChild; - if (first === null) { return null; } - return first._previousSibling; // circular linked list - }}, - - _ensureChildNodes: { value: function() { - if (this._childNodes) { return; } - var first = this._firstChild, - kid = first, - childNodes = this._childNodes = new NodeList(); - if (first) do { - childNodes.push(kid); - kid = kid._nextSibling; - } while (kid !== first); // circular linked list - this._firstChild = null; // free memory - }}, - - // Remove all of this node's children. This is a minor - // optimization that only calls modify() once. - removeChildren: { value: function removeChildren() { - var root = this.rooted ? this.ownerDocument : null, - next = this.firstChild, - kid; - while (next !== null) { - kid = next; - next = kid.nextSibling; - - if (root) root.mutateRemove(kid); - kid.parentNode = null; - } - if (this._childNodes) { - this._childNodes.length = 0; - } else { - this._firstChild = null; - } - this.modify(); // Update last modified type once only - }}, - -}); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/CustomEvent.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/CustomEvent.js deleted file mode 100644 index aaaf1371..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/CustomEvent.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; -module.exports = CustomEvent; - -var Event = require('./Event'); - -function CustomEvent(type, dictionary) { - // Just use the superclass constructor to initialize - Event.call(this, type, dictionary); -} -CustomEvent.prototype = Object.create(Event.prototype, { - constructor: { value: CustomEvent } -}); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/DOMException.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/DOMException.js deleted file mode 100644 index ab87b287..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/DOMException.js +++ /dev/null @@ -1,134 +0,0 @@ -"use strict"; -module.exports = DOMException; - -var INDEX_SIZE_ERR = 1; -var HIERARCHY_REQUEST_ERR = 3; -var WRONG_DOCUMENT_ERR = 4; -var INVALID_CHARACTER_ERR = 5; -var NO_MODIFICATION_ALLOWED_ERR = 7; -var NOT_FOUND_ERR = 8; -var NOT_SUPPORTED_ERR = 9; -var INVALID_STATE_ERR = 11; -var SYNTAX_ERR = 12; -var INVALID_MODIFICATION_ERR = 13; -var NAMESPACE_ERR = 14; -var INVALID_ACCESS_ERR = 15; -var TYPE_MISMATCH_ERR = 17; -var SECURITY_ERR = 18; -var NETWORK_ERR = 19; -var ABORT_ERR = 20; -var URL_MISMATCH_ERR = 21; -var QUOTA_EXCEEDED_ERR = 22; -var TIMEOUT_ERR = 23; -var INVALID_NODE_TYPE_ERR = 24; -var DATA_CLONE_ERR = 25; - -// Code to name -var names = [ - null, // No error with code 0 - 'INDEX_SIZE_ERR', - null, // historical - 'HIERARCHY_REQUEST_ERR', - 'WRONG_DOCUMENT_ERR', - 'INVALID_CHARACTER_ERR', - null, // historical - 'NO_MODIFICATION_ALLOWED_ERR', - 'NOT_FOUND_ERR', - 'NOT_SUPPORTED_ERR', - 'INUSE_ATTRIBUTE_ERR', // historical - 'INVALID_STATE_ERR', - 'SYNTAX_ERR', - 'INVALID_MODIFICATION_ERR', - 'NAMESPACE_ERR', - 'INVALID_ACCESS_ERR', - null, // historical - 'TYPE_MISMATCH_ERR', - 'SECURITY_ERR', - 'NETWORK_ERR', - 'ABORT_ERR', - 'URL_MISMATCH_ERR', - 'QUOTA_EXCEEDED_ERR', - 'TIMEOUT_ERR', - 'INVALID_NODE_TYPE_ERR', - 'DATA_CLONE_ERR', -]; - -// Code to message -// These strings are from the 13 May 2011 Editor's Draft of DOM Core. -// http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html -// Copyright © 2011 W3C® (MIT, ERCIM, Keio), All Rights Reserved. -// Used under the terms of the W3C Document License: -// http://www.w3.org/Consortium/Legal/2002/copyright-documents-20021231 -var messages = [ - null, // No error with code 0 - 'INDEX_SIZE_ERR (1): the index is not in the allowed range', - null, - 'HIERARCHY_REQUEST_ERR (3): the operation would yield an incorrect nodes model', - 'WRONG_DOCUMENT_ERR (4): the object is in the wrong Document, a call to importNode is required', - 'INVALID_CHARACTER_ERR (5): the string contains invalid characters', - null, - 'NO_MODIFICATION_ALLOWED_ERR (7): the object can not be modified', - 'NOT_FOUND_ERR (8): the object can not be found here', - 'NOT_SUPPORTED_ERR (9): this operation is not supported', - 'INUSE_ATTRIBUTE_ERR (10): setAttributeNode called on owned Attribute', - 'INVALID_STATE_ERR (11): the object is in an invalid state', - 'SYNTAX_ERR (12): the string did not match the expected pattern', - 'INVALID_MODIFICATION_ERR (13): the object can not be modified in this way', - 'NAMESPACE_ERR (14): the operation is not allowed by Namespaces in XML', - 'INVALID_ACCESS_ERR (15): the object does not support the operation or argument', - null, - 'TYPE_MISMATCH_ERR (17): the type of the object does not match the expected type', - 'SECURITY_ERR (18): the operation is insecure', - 'NETWORK_ERR (19): a network error occurred', - 'ABORT_ERR (20): the user aborted an operation', - 'URL_MISMATCH_ERR (21): the given URL does not match another URL', - 'QUOTA_EXCEEDED_ERR (22): the quota has been exceeded', - 'TIMEOUT_ERR (23): a timeout occurred', - 'INVALID_NODE_TYPE_ERR (24): the supplied node is invalid or has an invalid ancestor for this operation', - 'DATA_CLONE_ERR (25): the object can not be cloned.' -]; - -// Name to code -var constants = { - INDEX_SIZE_ERR: INDEX_SIZE_ERR, - DOMSTRING_SIZE_ERR: 2, // historical - HIERARCHY_REQUEST_ERR: HIERARCHY_REQUEST_ERR, - WRONG_DOCUMENT_ERR: WRONG_DOCUMENT_ERR, - INVALID_CHARACTER_ERR: INVALID_CHARACTER_ERR, - NO_DATA_ALLOWED_ERR: 6, // historical - NO_MODIFICATION_ALLOWED_ERR: NO_MODIFICATION_ALLOWED_ERR, - NOT_FOUND_ERR: NOT_FOUND_ERR, - NOT_SUPPORTED_ERR: NOT_SUPPORTED_ERR, - INUSE_ATTRIBUTE_ERR: 10, // historical - INVALID_STATE_ERR: INVALID_STATE_ERR, - SYNTAX_ERR: SYNTAX_ERR, - INVALID_MODIFICATION_ERR: INVALID_MODIFICATION_ERR, - NAMESPACE_ERR: NAMESPACE_ERR, - INVALID_ACCESS_ERR: INVALID_ACCESS_ERR, - VALIDATION_ERR: 16, // historical - TYPE_MISMATCH_ERR: TYPE_MISMATCH_ERR, - SECURITY_ERR: SECURITY_ERR, - NETWORK_ERR: NETWORK_ERR, - ABORT_ERR: ABORT_ERR, - URL_MISMATCH_ERR: URL_MISMATCH_ERR, - QUOTA_EXCEEDED_ERR: QUOTA_EXCEEDED_ERR, - TIMEOUT_ERR: TIMEOUT_ERR, - INVALID_NODE_TYPE_ERR: INVALID_NODE_TYPE_ERR, - DATA_CLONE_ERR: DATA_CLONE_ERR -}; - -function DOMException(code) { - Error.call(this); - Error.captureStackTrace(this, this.constructor); - this.code = code; - this.message = messages[code]; - this.name = names[code]; -} -DOMException.prototype.__proto__ = Error.prototype; - -// Initialize the constants on DOMException and DOMException.prototype -for(var c in constants) { - var v = { value: constants[c] }; - Object.defineProperty(DOMException, c, v); - Object.defineProperty(DOMException.prototype, c, v); -} diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/DOMImplementation.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/DOMImplementation.js deleted file mode 100644 index 03f2d3a0..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/DOMImplementation.js +++ /dev/null @@ -1,94 +0,0 @@ -"use strict"; -module.exports = DOMImplementation; - -var Document = require('./Document'); -var DocumentType = require('./DocumentType'); -var HTMLParser = require('./HTMLParser'); -var utils = require('./utils'); -var xml = require('./xmlnames'); - -// Each document must have its own instance of the domimplementation object -function DOMImplementation(contextObject) { - this.contextObject = contextObject; -} - - -// Feature/version pairs that DOMImplementation.hasFeature() returns -// true for. It returns false for anything else. -var supportedFeatures = { - 'xml': { '': true, '1.0': true, '2.0': true }, // DOM Core - 'core': { '': true, '2.0': true }, // DOM Core - 'html': { '': true, '1.0': true, '2.0': true} , // HTML - 'xhtml': { '': true, '1.0': true, '2.0': true} , // HTML -}; - -DOMImplementation.prototype = { - hasFeature: function hasFeature(feature, version) { - var f = supportedFeatures[(feature || '').toLowerCase()]; - return (f && f[version || '']) || false; - }, - - createDocumentType: function createDocumentType(qualifiedName, publicId, systemId) { - if (!xml.isValidQName(qualifiedName)) utils.InvalidCharacterError(); - - return new DocumentType(this.contextObject, qualifiedName, publicId, systemId); - }, - - createDocument: function createDocument(namespace, qualifiedName, doctype) { - // - // Note that the current DOMCore spec makes it impossible to - // create an HTML document with this function, even if the - // namespace and doctype are propertly set. See this thread: - // http://lists.w3.org/Archives/Public/www-dom/2011AprJun/0132.html - // - var d = new Document(false, null); - var e; - - if (qualifiedName) - e = d.createElementNS(namespace, qualifiedName); - else - e = null; - - if (doctype) { - d.appendChild(doctype); - } - - if (e) d.appendChild(e); - if (namespace === utils.NAMESPACE.HTML) { - d._contentType = 'application/xhtml+xml'; - } else if (namespace === utils.NAMESPACE.SVG) { - d._contentType = 'image/svg+xml'; - } else { - d._contentType = 'application/xml'; - } - - return d; - }, - - createHTMLDocument: function createHTMLDocument(titleText) { - var d = new Document(true, null); - d.appendChild(new DocumentType(d, 'html')); - var html = d.createElement('html'); - d.appendChild(html); - var head = d.createElement('head'); - html.appendChild(head); - if (titleText !== undefined) { - var title = d.createElement('title'); - head.appendChild(title); - title.appendChild(d.createTextNode(titleText)); - } - html.appendChild(d.createElement('body')); - d.modclock = 1; // Start tracking modifications - return d; - }, - - mozSetOutputMutationHandler: function(doc, handler) { - doc.mutationHandler = handler; - }, - - mozGetInputMutationHandler: function(doc) { - utils.nyi(); - }, - - mozHTMLParser: HTMLParser, -}; diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/DOMTokenList.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/DOMTokenList.js deleted file mode 100644 index c2580fd6..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/DOMTokenList.js +++ /dev/null @@ -1,186 +0,0 @@ -"use strict"; -// DOMTokenList implementation based on https://github.com/Raynos/DOM-shim -var utils = require('./utils'); - -module.exports = DOMTokenList; - -function DOMTokenList(getter, setter) { - this._getString = getter; - this._setString = setter; - this._length = 0; - this._lastStringValue = ''; - this._update(); -} - -Object.defineProperties(DOMTokenList.prototype, { - length: { get: function() { return this._length; } }, - item: { value: function(index) { - var list = getList(this); - if (index < 0 || index >= list.length) { - return null; - } - return list[index]; - }}, - - contains: { value: function(token) { - token = String(token); // no error checking for contains() - var list = getList(this); - return list.indexOf(token) > -1; - }}, - - add: { value: function() { - var list = getList(this); - for (var i = 0, len = arguments.length; i < len; i++) { - var token = handleErrors(arguments[i]); - if (list.indexOf(token) < 0) { - list.push(token); - } - } - // Note: as per spec, if handleErrors() throws any errors, we never - // make it here and none of the changes take effect. - // Also per spec: we run the "update steps" even if no change was - // made (ie, if the token already existed) - this._update(list); - }}, - - remove: { value: function() { - var list = getList(this); - for (var i = 0, len = arguments.length; i < len; i++) { - var token = handleErrors(arguments[i]); - var index = list.indexOf(token); - if (index > -1) { - list.splice(index, 1); - } - } - // Note: as per spec, if handleErrors() throws any errors, we never - // make it here and none of the changes take effect. - // Also per spec: we run the "update steps" even if no change was - // made (ie, if the token wasn't previously present) - this._update(list); - }}, - - toggle: { value: function toggle(token, force) { - token = handleErrors(token); - if (this.contains(token)) { - if (force === undefined || force === false) { - this.remove(token); - return false; - } - return true; - } else { - if (force === undefined || force === true) { - this.add(token); - return true; - } - return false; - } - }}, - - replace: { value: function replace(token, newToken) { - // weird corner case of spec: if `token` contains whitespace, but - // `newToken` is the empty string, we must throw SyntaxError not - // InvalidCharacterError (sigh) - if (String(newToken)==='') { utils.SyntaxError(); } - token = handleErrors(token); - newToken = handleErrors(newToken); - var list = getList(this); - var idx = list.indexOf(token); - if (idx < 0) { - // Note that, per spec, we do not run the update steps on this path. - return false; - } - var idx2 = list.indexOf(newToken); - if (idx2 < 0) { - list[idx] = newToken; - } else { - // "replace the first instance of either `token` or `newToken` with - // `newToken` and remove all other instances" - if (idx < idx2) { - list[idx] = newToken; - list.splice(idx2, 1); - } else { - // idx2 is already `newToken` - list.splice(idx, 1); - } - } - this._update(list); - return true; - }}, - - toString: { value: function() { - return this._getString(); - }}, - - value: { - get: function() { - return this._getString(); - }, - set: function(v) { - this._setString(v); - this._update(); - } - }, - - // Called when the setter is called from outside this interface. - _update: { value: function(list) { - if (list) { - fixIndex(this, list); - this._setString(list.join(" ").trim()); - } else { - fixIndex(this, getList(this)); - } - this._lastStringValue = this._getString(); - } }, -}); - -function fixIndex(clist, list) { - var oldLength = clist._length; - var i; - clist._length = list.length; - for (i = 0; i < list.length; i++) { - clist[i] = list[i]; - } - // Clear/free old entries. - for (; i < oldLength; i++) { - clist[i] = undefined; - } -} - -function handleErrors(token) { - token = String(token); - if (token === "") { - utils.SyntaxError(); - } - if (/[ \t\r\n\f]/.test(token)) { - utils.InvalidCharacterError(); - } - return token; -} - -function toArray(clist) { - var length = clist._length; - var arr = Array(length); - for (var i = 0; i < length; i++) { - arr[i] = clist[i]; - } - return arr; -} - -function getList(clist) { - var strProp = clist._getString(); - if (strProp === clist._lastStringValue) { - return toArray(clist); - } - var str = strProp.replace(/(^[ \t\r\n\f]+)|([ \t\r\n\f]+$)/g, ''); - if (str === "") { - return []; - } else { - var seen = Object.create(null); - return str.split(/[ \t\r\n\f]+/g).filter(function(n) { - var key = '$' + n; - if (seen[key]) { return false; } - seen[key] = true; - return true; - }); - } -} diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/Document.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/Document.js deleted file mode 100644 index bcd50ea1..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/Document.js +++ /dev/null @@ -1,884 +0,0 @@ -"use strict"; -module.exports = Document; - -var Node = require('./Node'); -var NodeList = require('./NodeList'); -var ContainerNode = require('./ContainerNode'); -var Element = require('./Element'); -var Text = require('./Text'); -var Comment = require('./Comment'); -var Event = require('./Event'); -var DocumentFragment = require('./DocumentFragment'); -var ProcessingInstruction = require('./ProcessingInstruction'); -var DOMImplementation = require('./DOMImplementation'); -var TreeWalker = require('./TreeWalker'); -var NodeIterator = require('./NodeIterator'); -var NodeFilter = require('./NodeFilter'); -var URL = require('./URL'); -var select = require('./select'); -var events = require('./events'); -var xml = require('./xmlnames'); -var html = require('./htmlelts'); -var svg = require('./svg'); -var utils = require('./utils'); -var MUTATE = require('./MutationConstants'); -var NAMESPACE = utils.NAMESPACE; -var isApiWritable = require("./config").isApiWritable; - -function Document(isHTML, address) { - ContainerNode.call(this); - this.nodeType = Node.DOCUMENT_NODE; - this.isHTML = isHTML; - this._address = address || 'about:blank'; - this.readyState = 'loading'; - this.implementation = new DOMImplementation(this); - - // DOMCore says that documents are always associated with themselves - this.ownerDocument = null; // ... but W3C tests expect null - this._contentType = isHTML ? 'text/html' : 'application/xml'; - - // These will be initialized by our custom versions of - // appendChild and insertBefore that override the inherited - // Node methods. - // XXX: override those methods! - this.doctype = null; - this.documentElement = null; - - // "Associated inert template document" - this._templateDocCache = null; - // List of active NodeIterators, see NodeIterator#_preremove() - this._nodeIterators = null; - - // Documents are always rooted, by definition - this._nid = 1; - this._nextnid = 2; // For numbering children of the document - this._nodes = [null, this]; // nid to node map - - // This maintains the mapping from element ids to element nodes. - // We may need to update this mapping every time a node is rooted - // or uprooted, and any time an attribute is added, removed or changed - // on a rooted element. - this.byId = Object.create(null); - - // This property holds a monotonically increasing value akin to - // a timestamp used to record the last modification time of nodes - // and their subtrees. See the lastModTime attribute and modify() - // method of the Node class. And see FilteredElementList for an example - // of the use of lastModTime - this.modclock = 0; -} - -// Map from lowercase event category names (used as arguments to -// createEvent()) to the property name in the impl object of the -// event constructor. -var supportedEvents = { - event: 'Event', - customevent: 'CustomEvent', - uievent: 'UIEvent', - mouseevent: 'MouseEvent' -}; - -// Certain arguments to document.createEvent() must be treated specially -var replacementEvent = { - events: 'event', - htmlevents: 'event', - mouseevents: 'mouseevent', - mutationevents: 'mutationevent', - uievents: 'uievent' -}; - -var mirrorAttr = function(f, name, defaultValue) { - return { - get: function() { - var o = f.call(this); - if (o) { return o[name]; } - return defaultValue; - }, - set: function(value) { - var o = f.call(this); - if (o) { o[name] = value; } - }, - }; -}; - -/** @spec https://dom.spec.whatwg.org/#validate-and-extract */ -function validateAndExtract(namespace, qualifiedName) { - var prefix, localName, pos; - if (namespace==='') { namespace = null; } - // See https://github.com/whatwg/dom/issues/671 - // and https://github.com/whatwg/dom/issues/319 - if (!xml.isValidQName(qualifiedName)) { - utils.InvalidCharacterError(); - } - prefix = null; - localName = qualifiedName; - - pos = qualifiedName.indexOf(':'); - if (pos >= 0) { - prefix = qualifiedName.substring(0, pos); - localName = qualifiedName.substring(pos+1); - } - if (prefix !== null && namespace === null) { - utils.NamespaceError(); - } - if (prefix === 'xml' && namespace !== NAMESPACE.XML) { - utils.NamespaceError(); - } - if ((prefix === 'xmlns' || qualifiedName === 'xmlns') && - namespace !== NAMESPACE.XMLNS) { - utils.NamespaceError(); - } - if (namespace === NAMESPACE.XMLNS && !(prefix==='xmlns' || qualifiedName==='xmlns')) { - utils.NamespaceError(); - } - return { namespace: namespace, prefix: prefix, localName: localName }; -} - -Document.prototype = Object.create(ContainerNode.prototype, { - // This method allows dom.js to communicate with a renderer - // that displays the document in some way - // XXX: I should probably move this to the window object - _setMutationHandler: { value: function(handler) { - this.mutationHandler = handler; - }}, - - // This method allows dom.js to receive event notifications - // from the renderer. - // XXX: I should probably move this to the window object - _dispatchRendererEvent: { value: function(targetNid, type, details) { - var target = this._nodes[targetNid]; - if (!target) return; - target._dispatchEvent(new Event(type, details), true); - }}, - - nodeName: { value: '#document'}, - nodeValue: { - get: function() { - return null; - }, - set: function() {} - }, - - // XXX: DOMCore may remove documentURI, so it is NYI for now - documentURI: { get: function() { return this._address; }, set: utils.nyi }, - compatMode: { get: function() { - // The _quirks property is set by the HTML parser - return this._quirks ? 'BackCompat' : 'CSS1Compat'; - }}, - - createTextNode: { value: function(data) { - return new Text(this, String(data)); - }}, - createComment: { value: function(data) { - return new Comment(this, data); - }}, - createDocumentFragment: { value: function() { - return new DocumentFragment(this); - }}, - createProcessingInstruction: { value: function(target, data) { - if (!xml.isValidName(target) || data.indexOf('?>') !== -1) - utils.InvalidCharacterError(); - return new ProcessingInstruction(this, target, data); - }}, - - createAttribute: { value: function(localName) { - localName = String(localName); - if (!xml.isValidName(localName)) utils.InvalidCharacterError(); - if (this.isHTML) { - localName = utils.toASCIILowerCase(localName); - } - return new Element._Attr(null, localName, null, null, ''); - }}, - createAttributeNS: { value: function(namespace, qualifiedName) { - // Convert parameter types according to WebIDL - namespace = - (namespace === null || namespace === undefined || namespace === '') ? null : - String(namespace); - qualifiedName = String(qualifiedName); - var ve = validateAndExtract(namespace, qualifiedName); - return new Element._Attr(null, ve.localName, ve.prefix, ve.namespace, ''); - }}, - - createElement: { value: function(localName) { - localName = String(localName); - if (!xml.isValidName(localName)) utils.InvalidCharacterError(); - // Per spec, namespace should be HTML namespace if "context object is - // an HTML document or context object's content type is - // "application/xhtml+xml", and null otherwise. - if (this.isHTML) { - if (/[A-Z]/.test(localName)) - localName = utils.toASCIILowerCase(localName); - return html.createElement(this, localName, null); - } else if (this.contentType === 'application/xhtml+xml') { - return html.createElement(this, localName, null); - } else { - return new Element(this, localName, null, null); - } - }, writable: isApiWritable }, - - createElementNS: { value: function(namespace, qualifiedName) { - // Convert parameter types according to WebIDL - namespace = - (namespace === null || namespace === undefined || namespace === '') ? null : - String(namespace); - qualifiedName = String(qualifiedName); - var ve = validateAndExtract(namespace, qualifiedName); - return this._createElementNS(ve.localName, ve.namespace, ve.prefix); - }, writable: isApiWritable }, - - // This is used directly by HTML parser, which allows it to create - // elements with localNames containing ':' and non-default namespaces - _createElementNS: { value: function(localName, namespace, prefix) { - if (namespace === NAMESPACE.HTML) { - return html.createElement(this, localName, prefix); - } - else if (namespace === NAMESPACE.SVG) { - return svg.createElement(this, localName, prefix); - } - - return new Element(this, localName, namespace, prefix); - }}, - - createEvent: { value: function createEvent(interfaceName) { - interfaceName = interfaceName.toLowerCase(); - var name = replacementEvent[interfaceName] || interfaceName; - var constructor = events[supportedEvents[name]]; - - if (constructor) { - var e = new constructor(); - e._initialized = false; - return e; - } - else { - utils.NotSupportedError(); - } - }}, - - // See: http://www.w3.org/TR/dom/#dom-document-createtreewalker - createTreeWalker: {value: function (root, whatToShow, filter) { - if (!root) { throw new TypeError("root argument is required"); } - if (!(root instanceof Node)) { throw new TypeError("root not a node"); } - whatToShow = whatToShow === undefined ? NodeFilter.SHOW_ALL : (+whatToShow); - filter = filter === undefined ? null : filter; - - return new TreeWalker(root, whatToShow, filter); - }}, - - // See: http://www.w3.org/TR/dom/#dom-document-createnodeiterator - createNodeIterator: {value: function (root, whatToShow, filter) { - if (!root) { throw new TypeError("root argument is required"); } - if (!(root instanceof Node)) { throw new TypeError("root not a node"); } - whatToShow = whatToShow === undefined ? NodeFilter.SHOW_ALL : (+whatToShow); - filter = filter === undefined ? null : filter; - - return new NodeIterator(root, whatToShow, filter); - }}, - - _attachNodeIterator: { value: function(ni) { - // XXX ideally this should be a weak reference from Document to NodeIterator - if (!this._nodeIterators) { this._nodeIterators = []; } - this._nodeIterators.push(ni); - }}, - - _detachNodeIterator: { value: function(ni) { - // ni should always be in list of node iterators - var idx = this._nodeIterators.indexOf(ni); - this._nodeIterators.splice(idx, 1); - }}, - - _preremoveNodeIterators: { value: function(toBeRemoved) { - if (this._nodeIterators) { - this._nodeIterators.forEach(function(ni) { ni._preremove(toBeRemoved); }); - } - }}, - - // Maintain the documentElement and - // doctype properties of the document. Each of the following - // methods chains to the Node implementation of the method - // to do the actual inserting, removal or replacement. - - _updateDocTypeElement: { value: function _updateDocTypeElement() { - this.doctype = this.documentElement = null; - for (var kid = this.firstChild; kid !== null; kid = kid.nextSibling) { - if (kid.nodeType === Node.DOCUMENT_TYPE_NODE) - this.doctype = kid; - else if (kid.nodeType === Node.ELEMENT_NODE) - this.documentElement = kid; - } - }}, - - insertBefore: { value: function insertBefore(child, refChild) { - Node.prototype.insertBefore.call(this, child, refChild); - this._updateDocTypeElement(); - return child; - }}, - - replaceChild: { value: function replaceChild(node, child) { - Node.prototype.replaceChild.call(this, node, child); - this._updateDocTypeElement(); - return child; - }}, - - removeChild: { value: function removeChild(child) { - Node.prototype.removeChild.call(this, child); - this._updateDocTypeElement(); - return child; - }}, - - getElementById: { value: function(id) { - var n = this.byId[id]; - if (!n) return null; - if (n instanceof MultiId) { // there was more than one element with this id - return n.getFirst(); - } - return n; - }}, - - _hasMultipleElementsWithId: { value: function(id) { - // Used internally by querySelectorAll optimization - return (this.byId[id] instanceof MultiId); - }}, - - // Just copy this method from the Element prototype - getElementsByName: { value: Element.prototype.getElementsByName }, - getElementsByTagName: { value: Element.prototype.getElementsByTagName }, - getElementsByTagNameNS: { value: Element.prototype.getElementsByTagNameNS }, - getElementsByClassName: { value: Element.prototype.getElementsByClassName }, - - adoptNode: { value: function adoptNode(node) { - if (node.nodeType === Node.DOCUMENT_NODE) utils.NotSupportedError(); - if (node.nodeType === Node.ATTRIBUTE_NODE) { return node; } - - if (node.parentNode) node.parentNode.removeChild(node); - - if (node.ownerDocument !== this) - recursivelySetOwner(node, this); - - return node; - }}, - - importNode: { value: function importNode(node, deep) { - return this.adoptNode(node.cloneNode(deep)); - }, writable: isApiWritable }, - - // The following attributes and methods are from the HTML spec - origin: { get: function origin() { return null; } }, - characterSet: { get: function characterSet() { return "UTF-8"; } }, - contentType: { get: function contentType() { return this._contentType; } }, - URL: { get: function URL() { return this._address; } }, - domain: { get: utils.nyi, set: utils.nyi }, - referrer: { get: utils.nyi }, - cookie: { get: utils.nyi, set: utils.nyi }, - lastModified: { get: utils.nyi }, - location: { - get: function() { - return this.defaultView ? this.defaultView.location : null; // gh #75 - }, - set: utils.nyi - }, - _titleElement: { - get: function() { - // The title element of a document is the first title element in the - // document in tree order, if there is one, or null otherwise. - return this.getElementsByTagName('title').item(0) || null; - } - }, - title: { - get: function() { - var elt = this._titleElement; - // The child text content of the title element, or '' if null. - var value = elt ? elt.textContent : ''; - // Strip and collapse whitespace in value - return value.replace(/[ \t\n\r\f]+/g, ' ').replace(/(^ )|( $)/g, ''); - }, - set: function(value) { - var elt = this._titleElement; - var head = this.head; - if (!elt && !head) { return; /* according to spec */ } - if (!elt) { - elt = this.createElement('title'); - head.appendChild(elt); - } - elt.textContent = value; - } - }, - dir: mirrorAttr(function() { - var htmlElement = this.documentElement; - if (htmlElement && htmlElement.tagName === 'HTML') { return htmlElement; } - }, 'dir', ''), - fgColor: mirrorAttr(function() { return this.body; }, 'text', ''), - linkColor: mirrorAttr(function() { return this.body; }, 'link', ''), - vlinkColor: mirrorAttr(function() { return this.body; }, 'vLink', ''), - alinkColor: mirrorAttr(function() { return this.body; }, 'aLink', ''), - bgColor: mirrorAttr(function() { return this.body; }, 'bgColor', ''), - - // Historical aliases of Document#characterSet - charset: { get: function() { return this.characterSet; } }, - inputEncoding: { get: function() { return this.characterSet; } }, - - scrollingElement: { - get: function() { - return this._quirks ? this.body : this.documentElement; - } - }, - - // Return the first child of the document element. - // XXX For now, setting this attribute is not implemented. - body: { - get: function() { - return namedHTMLChild(this.documentElement, 'body'); - }, - set: utils.nyi - }, - // Return the first child of the document element. - head: { get: function() { - return namedHTMLChild(this.documentElement, 'head'); - }}, - images: { get: utils.nyi }, - embeds: { get: utils.nyi }, - plugins: { get: utils.nyi }, - links: { get: utils.nyi }, - forms: { get: utils.nyi }, - scripts: { get: utils.nyi }, - applets: { get: function() { return []; } }, - activeElement: { get: function() { return null; } }, - innerHTML: { - get: function() { return this.serialize(); }, - set: utils.nyi - }, - outerHTML: { - get: function() { return this.serialize(); }, - set: utils.nyi - }, - - write: { value: function(args) { - if (!this.isHTML) utils.InvalidStateError(); - - // XXX: still have to implement the ignore part - if (!this._parser /* && this._ignore_destructive_writes > 0 */ ) - return; - - if (!this._parser) { - // XXX call document.open, etc. - } - - var s = arguments.join(''); - - // If the Document object's reload override flag is set, then - // append the string consisting of the concatenation of all the - // arguments to the method to the Document's reload override - // buffer. - // XXX: don't know what this is about. Still have to do it - - // If there is no pending parsing-blocking script, have the - // tokenizer process the characters that were inserted, one at a - // time, processing resulting tokens as they are emitted, and - // stopping when the tokenizer reaches the insertion point or when - // the processing of the tokenizer is aborted by the tree - // construction stage (this can happen if a script end tag token is - // emitted by the tokenizer). - - // XXX: still have to do the above. Sounds as if we don't - // always call parse() here. If we're blocked, then we just - // insert the text into the stream but don't parse it reentrantly... - - // Invoke the parser reentrantly - this._parser.parse(s); - }}, - - writeln: { value: function writeln(args) { - this.write(Array.prototype.join.call(arguments, '') + '\n'); - }}, - - open: { value: function() { - this.documentElement = null; - }}, - - close: { value: function() { - this.readyState = 'interactive'; - this._dispatchEvent(new Event('readystatechange'), true); - this._dispatchEvent(new Event('DOMContentLoaded'), true); - this.readyState = 'complete'; - this._dispatchEvent(new Event('readystatechange'), true); - if (this.defaultView) { - this.defaultView._dispatchEvent(new Event('load'), true); - } - }}, - - // Utility methods - clone: { value: function clone() { - var d = new Document(this.isHTML, this._address); - d._quirks = this._quirks; - d._contentType = this._contentType; - return d; - }}, - - // We need to adopt the nodes if we do a deep clone - cloneNode: { value: function cloneNode(deep) { - var clone = Node.prototype.cloneNode.call(this, false); - if (deep) { - for (var kid = this.firstChild; kid !== null; kid = kid.nextSibling) { - clone._appendChild(clone.importNode(kid, true)); - } - } - clone._updateDocTypeElement(); - return clone; - }}, - - isEqual: { value: function isEqual(n) { - // Any two documents are shallowly equal. - // Node.isEqualNode will also test the children - return true; - }}, - - // Implementation-specific function. Called when a text, comment, - // or pi value changes. - mutateValue: { value: function(node) { - if (this.mutationHandler) { - this.mutationHandler({ - type: MUTATE.VALUE, - target: node, - data: node.data - }); - } - }}, - - // Invoked when an attribute's value changes. Attr holds the new - // value. oldval is the old value. Attribute mutations can also - // involve changes to the prefix (and therefore the qualified name) - mutateAttr: { value: function(attr, oldval) { - // Manage id->element mapping for getElementsById() - // XXX: this special case id handling should not go here, - // but in the attribute declaration for the id attribute - /* - if (attr.localName === 'id' && attr.namespaceURI === null) { - if (oldval) delId(oldval, attr.ownerElement); - addId(attr.value, attr.ownerElement); - } - */ - if (this.mutationHandler) { - this.mutationHandler({ - type: MUTATE.ATTR, - target: attr.ownerElement, - attr: attr - }); - } - }}, - - // Used by removeAttribute and removeAttributeNS for attributes. - mutateRemoveAttr: { value: function(attr) { -/* -* This is now handled in Attributes.js - // Manage id to element mapping - if (attr.localName === 'id' && attr.namespaceURI === null) { - this.delId(attr.value, attr.ownerElement); - } -*/ - if (this.mutationHandler) { - this.mutationHandler({ - type: MUTATE.REMOVE_ATTR, - target: attr.ownerElement, - attr: attr - }); - } - }}, - - // Called by Node.removeChild, etc. to remove a rooted element from - // the tree. Only needs to generate a single mutation event when a - // node is removed, but must recursively mark all descendants as not - // rooted. - mutateRemove: { value: function(node) { - // Send a single mutation event - if (this.mutationHandler) { - this.mutationHandler({ - type: MUTATE.REMOVE, - target: node.parentNode, - node: node - }); - } - - // Mark this and all descendants as not rooted - recursivelyUproot(node); - }}, - - // Called when a new element becomes rooted. It must recursively - // generate mutation events for each of the children, and mark them all - // as rooted. - mutateInsert: { value: function(node) { - // Mark node and its descendants as rooted - recursivelyRoot(node); - - // Send a single mutation event - if (this.mutationHandler) { - this.mutationHandler({ - type: MUTATE.INSERT, - target: node.parentNode, - node: node - }); - } - }}, - - // Called when a rooted element is moved within the document - mutateMove: { value: function(node) { - if (this.mutationHandler) { - this.mutationHandler({ - type: MUTATE.MOVE, - target: node - }); - } - }}, - - - // Add a mapping from id to n for n.ownerDocument - addId: { value: function addId(id, n) { - var val = this.byId[id]; - if (!val) { - this.byId[id] = n; - } - else { - // TODO: Add a way to opt-out console warnings - //console.warn('Duplicate element id ' + id); - if (!(val instanceof MultiId)) { - val = new MultiId(val); - this.byId[id] = val; - } - val.add(n); - } - }}, - - // Delete the mapping from id to n for n.ownerDocument - delId: { value: function delId(id, n) { - var val = this.byId[id]; - utils.assert(val); - - if (val instanceof MultiId) { - val.del(n); - if (val.length === 1) { // convert back to a single node - this.byId[id] = val.downgrade(); - } - } - else { - this.byId[id] = undefined; - } - }}, - - _resolve: { value: function(href) { - //XXX: Cache the URL - return new URL(this._documentBaseURL).resolve(href); - }}, - - _documentBaseURL: { get: function() { - // XXX: This is not implemented correctly yet - var url = this._address; - if (url === 'about:blank') url = '/'; - - var base = this.querySelector('base[href]'); - if (base) { - return new URL(url).resolve(base.getAttribute('href')); - } - return url; - - // The document base URL of a Document object is the - // absolute URL obtained by running these substeps: - - // Let fallback base url be the document's address. - - // If fallback base url is about:blank, and the - // Document's browsing context has a creator browsing - // context, then let fallback base url be the document - // base URL of the creator Document instead. - - // If the Document is an iframe srcdoc document, then - // let fallback base url be the document base URL of - // the Document's browsing context's browsing context - // container's Document instead. - - // If there is no base element that has an href - // attribute, then the document base URL is fallback - // base url; abort these steps. Otherwise, let url be - // the value of the href attribute of the first such - // element. - - // Resolve url relative to fallback base url (thus, - // the base href attribute isn't affected by xml:base - // attributes). - - // The document base URL is the result of the previous - // step if it was successful; otherwise it is fallback - // base url. - }}, - - _templateDoc: { get: function() { - if (!this._templateDocCache) { - // "associated inert template document" - var newDoc = new Document(this.isHTML, this._address); - this._templateDocCache = newDoc._templateDocCache = newDoc; - } - return this._templateDocCache; - }}, - - querySelector: { value: function(selector) { - return select(selector, this)[0]; - }}, - - querySelectorAll: { value: function(selector) { - var nodes = select(selector, this); - return nodes.item ? nodes : new NodeList(nodes); - }} - -}); - - -var eventHandlerTypes = [ - 'abort', 'canplay', 'canplaythrough', 'change', 'click', 'contextmenu', - 'cuechange', 'dblclick', 'drag', 'dragend', 'dragenter', 'dragleave', - 'dragover', 'dragstart', 'drop', 'durationchange', 'emptied', 'ended', - 'input', 'invalid', 'keydown', 'keypress', 'keyup', 'loadeddata', - 'loadedmetadata', 'loadstart', 'mousedown', 'mousemove', 'mouseout', - 'mouseover', 'mouseup', 'mousewheel', 'pause', 'play', 'playing', - 'progress', 'ratechange', 'readystatechange', 'reset', 'seeked', - 'seeking', 'select', 'show', 'stalled', 'submit', 'suspend', - 'timeupdate', 'volumechange', 'waiting', - - 'blur', 'error', 'focus', 'load', 'scroll' -]; - -// Add event handler idl attribute getters and setters to Document -eventHandlerTypes.forEach(function(type) { - // Define the event handler registration IDL attribute for this type - Object.defineProperty(Document.prototype, 'on' + type, { - get: function() { - return this._getEventHandler(type); - }, - set: function(v) { - this._setEventHandler(type, v); - } - }); -}); - -function namedHTMLChild(parent, name) { - if (parent && parent.isHTML) { - for (var kid = parent.firstChild; kid !== null; kid = kid.nextSibling) { - if (kid.nodeType === Node.ELEMENT_NODE && - kid.localName === name && - kid.namespaceURI === NAMESPACE.HTML) { - return kid; - } - } - } - return null; -} - -function root(n) { - n._nid = n.ownerDocument._nextnid++; - n.ownerDocument._nodes[n._nid] = n; - // Manage id to element mapping - if (n.nodeType === Node.ELEMENT_NODE) { - var id = n.getAttribute('id'); - if (id) n.ownerDocument.addId(id, n); - - // Script elements need to know when they're inserted - // into the document - if (n._roothook) n._roothook(); - } -} - -function uproot(n) { - // Manage id to element mapping - if (n.nodeType === Node.ELEMENT_NODE) { - var id = n.getAttribute('id'); - if (id) n.ownerDocument.delId(id, n); - } - n.ownerDocument._nodes[n._nid] = undefined; - n._nid = undefined; -} - -function recursivelyRoot(node) { - root(node); - // XXX: - // accessing childNodes on a leaf node creates a new array the - // first time, so be careful to write this loop so that it - // doesn't do that. node is polymorphic, so maybe this is hard to - // optimize? Try switching on nodeType? -/* - if (node.hasChildNodes()) { - var kids = node.childNodes; - for(var i = 0, n = kids.length; i < n; i++) - recursivelyRoot(kids[i]); - } -*/ - if (node.nodeType === Node.ELEMENT_NODE) { - for (var kid = node.firstChild; kid !== null; kid = kid.nextSibling) - recursivelyRoot(kid); - } -} - -function recursivelyUproot(node) { - uproot(node); - for (var kid = node.firstChild; kid !== null; kid = kid.nextSibling) - recursivelyUproot(kid); -} - -function recursivelySetOwner(node, owner) { - node.ownerDocument = owner; - node._lastModTime = undefined; // mod times are document-based - if (Object.prototype.hasOwnProperty.call(node, '_tagName')) { - node._tagName = undefined; // Element subclasses might need to change case - } - for (var kid = node.firstChild; kid !== null; kid = kid.nextSibling) - recursivelySetOwner(kid, owner); -} - -// A class for storing multiple nodes with the same ID -function MultiId(node) { - this.nodes = Object.create(null); - this.nodes[node._nid] = node; - this.length = 1; - this.firstNode = undefined; -} - -// Add a node to the list, with O(1) time -MultiId.prototype.add = function(node) { - if (!this.nodes[node._nid]) { - this.nodes[node._nid] = node; - this.length++; - this.firstNode = undefined; - } -}; - -// Remove a node from the list, with O(1) time -MultiId.prototype.del = function(node) { - if (this.nodes[node._nid]) { - delete this.nodes[node._nid]; - this.length--; - this.firstNode = undefined; - } -}; - -// Get the first node from the list, in the document order -// Takes O(N) time in the size of the list, with a cache that is invalidated -// when the list is modified. -MultiId.prototype.getFirst = function() { - /* jshint bitwise: false */ - if (!this.firstNode) { - var nid; - for (nid in this.nodes) { - if (this.firstNode === undefined || - this.firstNode.compareDocumentPosition(this.nodes[nid]) & Node.DOCUMENT_POSITION_PRECEDING) { - this.firstNode = this.nodes[nid]; - } - } - } - return this.firstNode; -}; - -// If there is only one node left, return it. Otherwise return "this". -MultiId.prototype.downgrade = function() { - if (this.length === 1) { - var nid; - for (nid in this.nodes) { - return this.nodes[nid]; - } - } - return this; -}; diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/DocumentFragment.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/DocumentFragment.js deleted file mode 100644 index e2605faf..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/DocumentFragment.js +++ /dev/null @@ -1,71 +0,0 @@ -"use strict"; -module.exports = DocumentFragment; - -var Node = require('./Node'); -var NodeList = require('./NodeList'); -var ContainerNode = require('./ContainerNode'); -var Element = require('./Element'); -var select = require('./select'); -var utils = require('./utils'); - -function DocumentFragment(doc) { - ContainerNode.call(this); - this.nodeType = Node.DOCUMENT_FRAGMENT_NODE; - this.ownerDocument = doc; -} - -DocumentFragment.prototype = Object.create(ContainerNode.prototype, { - nodeName: { value: '#document-fragment' }, - nodeValue: { - get: function() { - return null; - }, - set: function() {} - }, - // Copy the text content getter/setter from Element - textContent: Object.getOwnPropertyDescriptor(Element.prototype, 'textContent'), - - // Copy the text content getter/setter from Element - innerText: Object.getOwnPropertyDescriptor(Element.prototype, 'innerText'), - - querySelector: { value: function(selector) { - // implement in terms of querySelectorAll - var nodes = this.querySelectorAll(selector); - return nodes.length ? nodes[0] : null; - }}, - querySelectorAll: { value: function(selector) { - // create a context - var context = Object.create(this); - // add some methods to the context for zest implementation, without - // adding them to the public DocumentFragment API - context.isHTML = true; // in HTML namespace (case-insensitive match) - context.getElementsByTagName = Element.prototype.getElementsByTagName; - context.nextElement = - Object.getOwnPropertyDescriptor(Element.prototype, 'firstElementChild'). - get; - // invoke zest - var nodes = select(selector, context); - return nodes.item ? nodes : new NodeList(nodes); - }}, - - // Utility methods - clone: { value: function clone() { - return new DocumentFragment(this.ownerDocument); - }}, - isEqual: { value: function isEqual(n) { - // Any two document fragments are shallowly equal. - // Node.isEqualNode() will test their children for equality - return true; - }}, - - // Non-standard, but useful (github issue #73) - innerHTML: { - get: function() { return this.serialize(); }, - set: utils.nyi - }, - outerHTML: { - get: function() { return this.serialize(); }, - set: utils.nyi - }, - -}); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/DocumentType.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/DocumentType.js deleted file mode 100644 index 680ea138..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/DocumentType.js +++ /dev/null @@ -1,36 +0,0 @@ -"use strict"; -module.exports = DocumentType; - -var Node = require('./Node'); -var Leaf = require('./Leaf'); -var ChildNode = require('./ChildNode'); - -function DocumentType(ownerDocument, name, publicId, systemId) { - Leaf.call(this); - this.nodeType = Node.DOCUMENT_TYPE_NODE; - this.ownerDocument = ownerDocument || null; - this.name = name; - this.publicId = publicId || ""; - this.systemId = systemId || ""; -} - -DocumentType.prototype = Object.create(Leaf.prototype, { - nodeName: { get: function() { return this.name; }}, - nodeValue: { - get: function() { return null; }, - set: function() {} - }, - - // Utility methods - clone: { value: function clone() { - return new DocumentType(this.ownerDocument, this.name, this.publicId, this.systemId); - }}, - - isEqual: { value: function isEqual(n) { - return this.name === n.name && - this.publicId === n.publicId && - this.systemId === n.systemId; - }} -}); - -Object.defineProperties(DocumentType.prototype, ChildNode); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/Element.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/Element.js deleted file mode 100644 index dc8cbc67..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/Element.js +++ /dev/null @@ -1,1228 +0,0 @@ -"use strict"; -module.exports = Element; - -var xml = require('./xmlnames'); -var utils = require('./utils'); -var NAMESPACE = utils.NAMESPACE; -var attributes = require('./attributes'); -var Node = require('./Node'); -var NodeList = require('./NodeList'); -var NodeUtils = require('./NodeUtils'); -var FilteredElementList = require('./FilteredElementList'); -var DOMException = require('./DOMException'); -var DOMTokenList = require('./DOMTokenList'); -var select = require('./select'); -var ContainerNode = require('./ContainerNode'); -var ChildNode = require('./ChildNode'); -var NonDocumentTypeChildNode = require('./NonDocumentTypeChildNode'); -var NamedNodeMap = require('./NamedNodeMap'); - -var uppercaseCache = Object.create(null); - -function Element(doc, localName, namespaceURI, prefix) { - ContainerNode.call(this); - this.nodeType = Node.ELEMENT_NODE; - this.ownerDocument = doc; - this.localName = localName; - this.namespaceURI = namespaceURI; - this.prefix = prefix; - this._tagName = undefined; - - // These properties maintain the set of attributes - this._attrsByQName = Object.create(null); // The qname->Attr map - this._attrsByLName = Object.create(null); // The ns|lname->Attr map - this._attrKeys = []; // attr index -> ns|lname -} - -function recursiveGetText(node, a) { - if (node.nodeType === Node.TEXT_NODE) { - a.push(node._data); - } - else { - for(var i = 0, n = node.childNodes.length; i < n; i++) - recursiveGetText(node.childNodes[i], a); - } -} - -Element.prototype = Object.create(ContainerNode.prototype, { - isHTML: { get: function isHTML() { - return this.namespaceURI === NAMESPACE.HTML && this.ownerDocument.isHTML; - }}, - tagName: { get: function tagName() { - if (this._tagName === undefined) { - var tn; - if (this.prefix === null) { - tn = this.localName; - } else { - tn = this.prefix + ':' + this.localName; - } - if (this.isHTML) { - var up = uppercaseCache[tn]; - if (!up) { - // Converting to uppercase can be slow, so cache the conversion. - uppercaseCache[tn] = up = utils.toASCIIUpperCase(tn); - } - tn = up; - } - this._tagName = tn; - } - return this._tagName; - }}, - nodeName: { get: function() { return this.tagName; }}, - nodeValue: { - get: function() { - return null; - }, - set: function() {} - }, - textContent: { - get: function() { - var strings = []; - recursiveGetText(this, strings); - return strings.join(''); - }, - set: function(newtext) { - this.removeChildren(); - if (newtext !== null && newtext !== undefined && newtext !== '') { - this._appendChild(this.ownerDocument.createTextNode(newtext)); - } - } - }, - innerText: { - get: function() { - var strings = []; - recursiveGetText(this, strings); - // Strip and collapse whitespace - // This doesn't 100% match the browser behavior, - // but should cover most of the cases. This is also similar to - // how Angular's renderer used to work: the `textContent` and `innerText` - // were almost equivalent from the renderer perspective. - // See: https://developer.mozilla.org/en-US/docs/Web/API/Node/textContent#differences_from_innertext - return strings.join('').replace(/[ \t\n\f\r]+/g, ' ').trim(); - }, - set: function(newtext) { - this.removeChildren(); - if (newtext !== null && newtext !== undefined && newtext !== '') { - this._appendChild(this.ownerDocument.createTextNode(newtext)); - } - } - }, - innerHTML: { - get: function() { - return this.serialize(); - }, - set: utils.nyi - }, - outerHTML: { - get: function() { - // "the attribute must return the result of running the HTML fragment - // serialization algorithm on a fictional node whose only child is - // the context object" - // - // The serialization logic is intentionally implemented in a separate - // `NodeUtils` helper instead of the more obvious choice of a private - // `_serializeOne()` method on the `Node.prototype` in order to avoid - // the megamorphic `this._serializeOne` property access, which reduces - // performance unnecessarily. If you need specialized behavior for a - // certain subclass, you'll need to implement that in `NodeUtils`. - // See https://github.com/fgnass/domino/pull/142 for more information. - return NodeUtils.serializeOne(this, { nodeType: 0 }); - }, - set: function(v) { - var document = this.ownerDocument; - var parent = this.parentNode; - if (parent === null) { return; } - if (parent.nodeType === Node.DOCUMENT_NODE) { - utils.NoModificationAllowedError(); - } - if (parent.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { - parent = parent.ownerDocument.createElement("body"); - } - var parser = document.implementation.mozHTMLParser( - document._address, - parent - ); - parser.parse(v===null?'':String(v), true); - this.replaceWith(parser._asDocumentFragment()); - }, - }, - - _insertAdjacent: { value: function _insertAdjacent(position, node) { - var first = false; - switch(position) { - case 'beforebegin': - first = true; - /* falls through */ - case 'afterend': - var parent = this.parentNode; - if (parent === null) { return null; } - return parent.insertBefore(node, first ? this : this.nextSibling); - case 'afterbegin': - first = true; - /* falls through */ - case 'beforeend': - return this.insertBefore(node, first ? this.firstChild : null); - default: - return utils.SyntaxError(); - } - }}, - - insertAdjacentElement: { value: function insertAdjacentElement(position, element) { - if (element.nodeType !== Node.ELEMENT_NODE) { - throw new TypeError('not an element'); - } - position = utils.toASCIILowerCase(String(position)); - return this._insertAdjacent(position, element); - }}, - - insertAdjacentText: { value: function insertAdjacentText(position, data) { - var textNode = this.ownerDocument.createTextNode(data); - position = utils.toASCIILowerCase(String(position)); - this._insertAdjacent(position, textNode); - // "This method returns nothing because it existed before we had a chance - // to design it." - }}, - - insertAdjacentHTML: { value: function insertAdjacentHTML(position, text) { - position = utils.toASCIILowerCase(String(position)); - text = String(text); - var context; - switch(position) { - case 'beforebegin': - case 'afterend': - context = this.parentNode; - if (context === null || context.nodeType === Node.DOCUMENT_NODE) { - utils.NoModificationAllowedError(); - } - break; - case 'afterbegin': - case 'beforeend': - context = this; - break; - default: - utils.SyntaxError(); - } - if ( (!(context instanceof Element)) || ( - context.ownerDocument.isHTML && - context.localName === 'html' && - context.namespaceURI === NAMESPACE.HTML - ) ) { - context = context.ownerDocument.createElementNS(NAMESPACE.HTML, 'body'); - } - var parser = this.ownerDocument.implementation.mozHTMLParser( - this.ownerDocument._address, context - ); - parser.parse(text, true); - this._insertAdjacent(position, parser._asDocumentFragment()); - }}, - - children: { get: function() { - if (!this._children) { - this._children = new ChildrenCollection(this); - } - return this._children; - }}, - - attributes: { get: function() { - if (!this._attributes) { - this._attributes = new AttributesArray(this); - } - return this._attributes; - }}, - - - firstElementChild: { get: function() { - for (var kid = this.firstChild; kid !== null; kid = kid.nextSibling) { - if (kid.nodeType === Node.ELEMENT_NODE) return kid; - } - return null; - }}, - - lastElementChild: { get: function() { - for (var kid = this.lastChild; kid !== null; kid = kid.previousSibling) { - if (kid.nodeType === Node.ELEMENT_NODE) return kid; - } - return null; - }}, - - childElementCount: { get: function() { - return this.children.length; - }}, - - - // Return the next element, in source order, after this one or - // null if there are no more. If root element is specified, - // then don't traverse beyond its subtree. - // - // This is not a DOM method, but is convenient for - // lazy traversals of the tree. - nextElement: { value: function(root) { - if (!root) root = this.ownerDocument.documentElement; - var next = this.firstElementChild; - if (!next) { - // don't use sibling if we're at root - if (this===root) return null; - next = this.nextElementSibling; - } - if (next) return next; - - // If we can't go down or across, then we have to go up - // and across to the parent sibling or another ancestor's - // sibling. Be careful, though: if we reach the root - // element, or if we reach the documentElement, then - // the traversal ends. - for(var parent = this.parentElement; - parent && parent !== root; - parent = parent.parentElement) { - - next = parent.nextElementSibling; - if (next) return next; - } - - return null; - }}, - - // XXX: - // Tests are currently failing for this function. - // Awaiting resolution of: - // http://lists.w3.org/Archives/Public/www-dom/2011JulSep/0016.html - getElementsByTagName: { value: function getElementsByTagName(lname) { - var filter; - if (!lname) return new NodeList(); - if (lname === '*') - filter = function() { return true; }; - else if (this.isHTML) - filter = htmlLocalNameElementFilter(lname); - else - filter = localNameElementFilter(lname); - - return new FilteredElementList(this, filter); - }}, - - getElementsByTagNameNS: { value: function getElementsByTagNameNS(ns, lname){ - var filter; - if (ns === '*' && lname === '*') - filter = function() { return true; }; - else if (ns === '*') - filter = localNameElementFilter(lname); - else if (lname === '*') - filter = namespaceElementFilter(ns); - else - filter = namespaceLocalNameElementFilter(ns, lname); - - return new FilteredElementList(this, filter); - }}, - - getElementsByClassName: { value: function getElementsByClassName(names){ - names = String(names).trim(); - if (names === '') { - var result = new NodeList(); // Empty node list - return result; - } - names = names.split(/[ \t\r\n\f]+/); // Split on ASCII whitespace - return new FilteredElementList(this, classNamesElementFilter(names)); - }}, - - getElementsByName: { value: function getElementsByName(name) { - return new FilteredElementList(this, elementNameFilter(String(name))); - }}, - - // Utility methods used by the public API methods above - clone: { value: function clone() { - var e; - - // XXX: - // Modify this to use the constructor directly or - // avoid error checking in some other way. In case we try - // to clone an invalid node that the parser inserted. - // - if (this.namespaceURI !== NAMESPACE.HTML || this.prefix || !this.ownerDocument.isHTML) { - e = this.ownerDocument.createElementNS( - this.namespaceURI, (this.prefix !== null) ? - (this.prefix + ':' + this.localName) : this.localName - ); - } else { - e = this.ownerDocument.createElement(this.localName); - } - - for(var i = 0, n = this._attrKeys.length; i < n; i++) { - var lname = this._attrKeys[i]; - var a = this._attrsByLName[lname]; - var b = a.cloneNode(); - b._setOwnerElement(e); - e._attrsByLName[lname] = b; - e._addQName(b); - } - e._attrKeys = this._attrKeys.concat(); - - return e; - }}, - - isEqual: { value: function isEqual(that) { - if (this.localName !== that.localName || - this.namespaceURI !== that.namespaceURI || - this.prefix !== that.prefix || - this._numattrs !== that._numattrs) - return false; - - // Compare the sets of attributes, ignoring order - // and ignoring attribute prefixes. - for(var i = 0, n = this._numattrs; i < n; i++) { - var a = this._attr(i); - if (!that.hasAttributeNS(a.namespaceURI, a.localName)) - return false; - if (that.getAttributeNS(a.namespaceURI,a.localName) !== a.value) - return false; - } - - return true; - }}, - - // This is the 'locate a namespace prefix' algorithm from the - // DOM specification. It is used by Node.lookupPrefix() - // (Be sure to compare DOM3 and DOM4 versions of spec.) - _lookupNamespacePrefix: { value: function _lookupNamespacePrefix(ns, originalElement) { - if ( - this.namespaceURI && - this.namespaceURI === ns && - this.prefix !== null && - originalElement.lookupNamespaceURI(this.prefix) === ns - ) { - return this.prefix; - } - - for(var i = 0, n = this._numattrs; i < n; i++) { - var a = this._attr(i); - if ( - a.prefix === 'xmlns' && - a.value === ns && - originalElement.lookupNamespaceURI(a.localName) === ns - ) { - return a.localName; - } - } - - var parent = this.parentElement; - return parent ? parent._lookupNamespacePrefix(ns, originalElement) : null; - }}, - - // This is the 'locate a namespace' algorithm for Element nodes - // from the DOM Core spec. It is used by Node#lookupNamespaceURI() - lookupNamespaceURI: { value: function lookupNamespaceURI(prefix) { - if (prefix === '' || prefix === undefined) { prefix = null; } - if (this.namespaceURI !== null && this.prefix === prefix) - return this.namespaceURI; - - for(var i = 0, n = this._numattrs; i < n; i++) { - var a = this._attr(i); - if (a.namespaceURI === NAMESPACE.XMLNS) { - if ( - (a.prefix === 'xmlns' && a.localName === prefix) || - (prefix === null && a.prefix === null && a.localName === 'xmlns') - ) { - return a.value || null; - } - } - } - - var parent = this.parentElement; - return parent ? parent.lookupNamespaceURI(prefix) : null; - }}, - - // - // Attribute handling methods and utilities - // - - /* - * Attributes in the DOM are tricky: - * - * - there are the 8 basic get/set/has/removeAttribute{NS} methods - * - * - but many HTML attributes are also 'reflected' through IDL - * attributes which means that they can be queried and set through - * regular properties of the element. There is just one attribute - * value, but two ways to get and set it. - * - * - Different HTML element types have different sets of reflected - attributes. - * - * - attributes can also be queried and set through the .attributes - * property of an element. This property behaves like an array of - * Attr objects. The value property of each Attr is writeable, so - * this is a third way to read and write attributes. - * - * - for efficiency, we really want to store attributes in some kind - * of name->attr map. But the attributes[] array is an array, not a - * map, which is kind of unnatural. - * - * - When using namespaces and prefixes, and mixing the NS methods - * with the non-NS methods, it is apparently actually possible for - * an attributes[] array to have more than one attribute with the - * same qualified name. And certain methods must operate on only - * the first attribute with such a name. So for these methods, an - * inefficient array-like data structure would be easier to - * implement. - * - * - The attributes[] array is live, not a snapshot, so changes to the - * attributes must be immediately visible through existing arrays. - * - * - When attributes are queried and set through IDL properties - * (instead of the get/setAttributes() method or the attributes[] - * array) they may be subject to type conversions, URL - * normalization, etc., so some extra processing is required in that - * case. - * - * - But access through IDL properties is probably the most common - * case, so we'd like that to be as fast as possible. - * - * - We can't just store attribute values in their parsed idl form, - * because setAttribute() has to return whatever string is passed to - * getAttribute even if it is not a legal, parseable value. So - * attribute values must be stored in unparsed string form. - * - * - We need to be able to send change notifications or mutation - * events of some sort to the renderer whenever an attribute value - * changes, regardless of the way in which it changes. - * - * - Some attributes, such as id and class affect other parts of the - * DOM API, like getElementById and getElementsByClassName and so - * for efficiency, we need to specially track changes to these - * special attributes. - * - * - Some attributes like class have different names (className) when - * reflected. - * - * - Attributes whose names begin with the string 'data-' are treated - specially. - * - * - Reflected attributes that have a boolean type in IDL have special - * behavior: setting them to false (in IDL) is the same as removing - * them with removeAttribute() - * - * - numeric attributes (like HTMLElement.tabIndex) can have default - * values that must be returned by the idl getter even if the - * content attribute does not exist. (The default tabIndex value - * actually varies based on the type of the element, so that is a - * tricky one). - * - * See - * http://www.whatwg.org/specs/web-apps/current-work/multipage/urls.html#reflect - * for rules on how attributes are reflected. - * - */ - - getAttribute: { value: function getAttribute(qname) { - var attr = this.getAttributeNode(qname); - return attr ? attr.value : null; - }}, - - getAttributeNS: { value: function getAttributeNS(ns, lname) { - var attr = this.getAttributeNodeNS(ns, lname); - return attr ? attr.value : null; - }}, - - getAttributeNode: { value: function getAttributeNode(qname) { - qname = String(qname); - if (/[A-Z]/.test(qname) && this.isHTML) - qname = utils.toASCIILowerCase(qname); - var attr = this._attrsByQName[qname]; - if (!attr) return null; - - if (Array.isArray(attr)) // If there is more than one - attr = attr[0]; // use the first - - return attr; - }}, - - getAttributeNodeNS: { value: function getAttributeNodeNS(ns, lname) { - ns = (ns === undefined || ns === null) ? '' : String(ns); - lname = String(lname); - var attr = this._attrsByLName[ns + '|' + lname]; - return attr ? attr : null; - }}, - - hasAttribute: { value: function hasAttribute(qname) { - qname = String(qname); - if (/[A-Z]/.test(qname) && this.isHTML) - qname = utils.toASCIILowerCase(qname); - return this._attrsByQName[qname] !== undefined; - }}, - - hasAttributeNS: { value: function hasAttributeNS(ns, lname) { - ns = (ns === undefined || ns === null) ? '' : String(ns); - lname = String(lname); - var key = ns + '|' + lname; - return this._attrsByLName[key] !== undefined; - }}, - - hasAttributes: { value: function hasAttributes() { - return this._numattrs > 0; - }}, - - toggleAttribute: { value: function toggleAttribute(qname, force) { - qname = String(qname); - if (!xml.isValidName(qname)) utils.InvalidCharacterError(); - if (/[A-Z]/.test(qname) && this.isHTML) - qname = utils.toASCIILowerCase(qname); - var a = this._attrsByQName[qname]; - if (a === undefined) { - if (force === undefined || force === true) { - this._setAttribute(qname, ''); - return true; - } - return false; - } else { - if (force === undefined || force === false) { - this.removeAttribute(qname); - return false; - } - return true; - } - }}, - - // Set the attribute without error checking. The parser uses this. - _setAttribute: { value: function _setAttribute(qname, value) { - // XXX: the spec says that this next search should be done - // on the local name, but I think that is an error. - // email pending on www-dom about it. - var attr = this._attrsByQName[qname]; - var isnew; - if (!attr) { - attr = this._newattr(qname); - isnew = true; - } - else { - if (Array.isArray(attr)) attr = attr[0]; - } - - // Now set the attribute value on the new or existing Attr object. - // The Attr.value setter method handles mutation events, etc. - attr.value = value; - if (this._attributes) this._attributes[qname] = attr; - if (isnew && this._newattrhook) this._newattrhook(qname, value); - }}, - - // Check for errors, and then set the attribute - setAttribute: { value: function setAttribute(qname, value) { - qname = String(qname); - if (!xml.isValidName(qname)) utils.InvalidCharacterError(); - if (/[A-Z]/.test(qname) && this.isHTML) - qname = utils.toASCIILowerCase(qname); - this._setAttribute(qname, String(value)); - }}, - - - // The version with no error checking used by the parser - _setAttributeNS: { value: function _setAttributeNS(ns, qname, value) { - var pos = qname.indexOf(':'), prefix, lname; - if (pos < 0) { - prefix = null; - lname = qname; - } - else { - prefix = qname.substring(0, pos); - lname = qname.substring(pos+1); - } - - if (ns === '' || ns === undefined) ns = null; - var key = (ns === null ? '' : ns) + '|' + lname; - - var attr = this._attrsByLName[key]; - var isnew; - if (!attr) { - attr = new Attr(this, lname, prefix, ns); - isnew = true; - this._attrsByLName[key] = attr; - if (this._attributes) { - this._attributes[this._attrKeys.length] = attr; - } - this._attrKeys.push(key); - - // We also have to make the attr searchable by qname. - // But we have to be careful because there may already - // be an attr with this qname. - this._addQName(attr); - } - else if (false /* changed in DOM 4 */) { - // Calling setAttributeNS() can change the prefix of an - // existing attribute in DOM 2/3. - if (attr.prefix !== prefix) { - // Unbind the old qname - this._removeQName(attr); - // Update the prefix - attr.prefix = prefix; - // Bind the new qname - this._addQName(attr); - } - - } - attr.value = value; // Automatically sends mutation event - if (isnew && this._newattrhook) this._newattrhook(qname, value); - }}, - - // Do error checking then call _setAttributeNS - setAttributeNS: { value: function setAttributeNS(ns, qname, value) { - // Convert parameter types according to WebIDL - ns = (ns === null || ns === undefined || ns === '') ? null : String(ns); - qname = String(qname); - if (!xml.isValidQName(qname)) utils.InvalidCharacterError(); - - var pos = qname.indexOf(':'); - var prefix = (pos < 0) ? null : qname.substring(0, pos); - - if ((prefix !== null && ns === null) || - (prefix === 'xml' && ns !== NAMESPACE.XML) || - ((qname === 'xmlns' || prefix === 'xmlns') && - (ns !== NAMESPACE.XMLNS)) || - (ns === NAMESPACE.XMLNS && - !(qname === 'xmlns' || prefix === 'xmlns'))) - utils.NamespaceError(); - - this._setAttributeNS(ns, qname, String(value)); - }}, - - setAttributeNode: { value: function setAttributeNode(attr) { - if (attr.ownerElement !== null && attr.ownerElement !== this) { - throw new DOMException(DOMException.INUSE_ATTRIBUTE_ERR); - } - var result = null; - var oldAttrs = this._attrsByQName[attr.name]; - if (oldAttrs) { - if (!Array.isArray(oldAttrs)) { oldAttrs = [ oldAttrs ]; } - if (oldAttrs.some(function(a) { return a===attr; })) { - return attr; - } else if (attr.ownerElement !== null) { - throw new DOMException(DOMException.INUSE_ATTRIBUTE_ERR); - } - oldAttrs.forEach(function(a) { this.removeAttributeNode(a); }, this); - result = oldAttrs[0]; - } - this.setAttributeNodeNS(attr); - return result; - }}, - - setAttributeNodeNS: { value: function setAttributeNodeNS(attr) { - if (attr.ownerElement !== null) { - throw new DOMException(DOMException.INUSE_ATTRIBUTE_ERR); - } - var ns = attr.namespaceURI; - var key = (ns === null ? '' : ns) + '|' + attr.localName; - var oldAttr = this._attrsByLName[key]; - if (oldAttr) { this.removeAttributeNode(oldAttr); } - attr._setOwnerElement(this); - this._attrsByLName[key] = attr; - if (this._attributes) { - this._attributes[this._attrKeys.length] = attr; - } - this._attrKeys.push(key); - this._addQName(attr); - if (this._newattrhook) this._newattrhook(attr.name, attr.value); - return oldAttr || null; - }}, - - removeAttribute: { value: function removeAttribute(qname) { - qname = String(qname); - if (/[A-Z]/.test(qname) && this.isHTML) - qname = utils.toASCIILowerCase(qname); - - var attr = this._attrsByQName[qname]; - if (!attr) return; - - // If there is more than one match for this qname - // so don't delete the qname mapping, just remove the first - // element from it. - if (Array.isArray(attr)) { - if (attr.length > 2) { - attr = attr.shift(); // remove it from the array - } - else { - this._attrsByQName[qname] = attr[1]; - attr = attr[0]; - } - } - else { - // only a single match, so remove the qname mapping - this._attrsByQName[qname] = undefined; - } - - var ns = attr.namespaceURI; - // Now attr is the removed attribute. Figure out its - // ns+lname key and remove it from the other mapping as well. - var key = (ns === null ? '' : ns) + '|' + attr.localName; - this._attrsByLName[key] = undefined; - - var i = this._attrKeys.indexOf(key); - if (this._attributes) { - Array.prototype.splice.call(this._attributes, i, 1); - this._attributes[qname] = undefined; - } - this._attrKeys.splice(i, 1); - - // Onchange handler for the attribute - var onchange = attr.onchange; - attr._setOwnerElement(null); - if (onchange) { - onchange.call(attr, this, attr.localName, attr.value, null); - } - // Mutation event - if (this.rooted) this.ownerDocument.mutateRemoveAttr(attr); - }}, - - removeAttributeNS: { value: function removeAttributeNS(ns, lname) { - ns = (ns === undefined || ns === null) ? '' : String(ns); - lname = String(lname); - var key = ns + '|' + lname; - var attr = this._attrsByLName[key]; - if (!attr) return; - - this._attrsByLName[key] = undefined; - - var i = this._attrKeys.indexOf(key); - if (this._attributes) { - Array.prototype.splice.call(this._attributes, i, 1); - } - this._attrKeys.splice(i, 1); - - // Now find the same Attr object in the qname mapping and remove it - // But be careful because there may be more than one match. - this._removeQName(attr); - - // Onchange handler for the attribute - var onchange = attr.onchange; - attr._setOwnerElement(null); - if (onchange) { - onchange.call(attr, this, attr.localName, attr.value, null); - } - // Mutation event - if (this.rooted) this.ownerDocument.mutateRemoveAttr(attr); - }}, - - removeAttributeNode: { value: function removeAttributeNode(attr) { - var ns = attr.namespaceURI; - var key = (ns === null ? '' : ns) + '|' + attr.localName; - if (this._attrsByLName[key] !== attr) { - utils.NotFoundError(); - } - this.removeAttributeNS(ns, attr.localName); - return attr; - }}, - - getAttributeNames: { value: function getAttributeNames() { - var elt = this; - return this._attrKeys.map(function(key) { - return elt._attrsByLName[key].name; - }); - }}, - - // This 'raw' version of getAttribute is used by the getter functions - // of reflected attributes. It skips some error checking and - // namespace steps - _getattr: { value: function _getattr(qname) { - // Assume that qname is already lowercased, so don't do it here. - // Also don't check whether attr is an array: a qname with no - // prefix will never have two matching Attr objects (because - // setAttributeNS doesn't allow a non-null namespace with a - // null prefix. - var attr = this._attrsByQName[qname]; - return attr ? attr.value : null; - }}, - - // The raw version of setAttribute for reflected idl attributes. - _setattr: { value: function _setattr(qname, value) { - var attr = this._attrsByQName[qname]; - var isnew; - if (!attr) { - attr = this._newattr(qname); - isnew = true; - } - attr.value = String(value); - if (this._attributes) this._attributes[qname] = attr; - if (isnew && this._newattrhook) this._newattrhook(qname, value); - }}, - - // Create a new Attr object, insert it, and return it. - // Used by setAttribute() and by set() - _newattr: { value: function _newattr(qname) { - var attr = new Attr(this, qname, null, null); - var key = '|' + qname; - this._attrsByQName[qname] = attr; - this._attrsByLName[key] = attr; - if (this._attributes) { - this._attributes[this._attrKeys.length] = attr; - } - this._attrKeys.push(key); - return attr; - }}, - - // Add a qname->Attr mapping to the _attrsByQName object, taking into - // account that there may be more than one attr object with the - // same qname - _addQName: { value: function(attr) { - var qname = attr.name; - var existing = this._attrsByQName[qname]; - if (!existing) { - this._attrsByQName[qname] = attr; - } - else if (Array.isArray(existing)) { - existing.push(attr); - } - else { - this._attrsByQName[qname] = [existing, attr]; - } - if (this._attributes) this._attributes[qname] = attr; - }}, - - // Remove a qname->Attr mapping to the _attrsByQName object, taking into - // account that there may be more than one attr object with the - // same qname - _removeQName: { value: function(attr) { - var qname = attr.name; - var target = this._attrsByQName[qname]; - - if (Array.isArray(target)) { - var idx = target.indexOf(attr); - utils.assert(idx !== -1); // It must be here somewhere - if (target.length === 2) { - this._attrsByQName[qname] = target[1-idx]; - if (this._attributes) { - this._attributes[qname] = this._attrsByQName[qname]; - } - } else { - target.splice(idx, 1); - if (this._attributes && this._attributes[qname] === attr) { - this._attributes[qname] = target[0]; - } - } - } - else { - utils.assert(target === attr); // If only one, it must match - this._attrsByQName[qname] = undefined; - if (this._attributes) { - this._attributes[qname] = undefined; - } - } - }}, - - // Return the number of attributes - _numattrs: { get: function() { return this._attrKeys.length; }}, - // Return the nth Attr object - _attr: { value: function(n) { - return this._attrsByLName[this._attrKeys[n]]; - }}, - - // Define getters and setters for an 'id' property that reflects - // the content attribute 'id'. - id: attributes.property({name: 'id'}), - - // Define getters and setters for a 'className' property that reflects - // the content attribute 'class'. - className: attributes.property({name: 'class'}), - - classList: { get: function() { - var self = this; - if (this._classList) { - return this._classList; - } - var dtlist = new DOMTokenList( - function() { - return self.className || ""; - }, - function(v) { - self.className = v; - } - ); - this._classList = dtlist; - return dtlist; - }, set: function(v) { this.className = v; }}, - - matches: { value: function(selector) { - return select.matches(this, selector); - }}, - - closest: { value: function(selector) { - var el = this; - do { - if (el.matches && el.matches(selector)) { return el; } - el = el.parentElement || el.parentNode; - } while (el !== null && el.nodeType === Node.ELEMENT_NODE); - return null; - }}, - - querySelector: { value: function(selector) { - return select(selector, this)[0]; - }}, - - querySelectorAll: { value: function(selector) { - var nodes = select(selector, this); - return nodes.item ? nodes : new NodeList(nodes); - }} - -}); - -Object.defineProperties(Element.prototype, ChildNode); -Object.defineProperties(Element.prototype, NonDocumentTypeChildNode); - -// Register special handling for the id attribute -attributes.registerChangeHandler(Element, 'id', - function(element, lname, oldval, newval) { - if (element.rooted) { - if (oldval) { - element.ownerDocument.delId(oldval, element); - } - if (newval) { - element.ownerDocument.addId(newval, element); - } - } - } -); -attributes.registerChangeHandler(Element, 'class', - function(element, lname, oldval, newval) { - if (element._classList) { element._classList._update(); } - } -); - -// The Attr class represents a single attribute. The values in -// _attrsByQName and _attrsByLName are instances of this class. -function Attr(elt, lname, prefix, namespace, value) { - // localName and namespace are constant for any attr object. - // But value may change. And so can prefix, and so, therefore can name. - this.localName = lname; - this.prefix = (prefix===null || prefix==='') ? null : ('' + prefix); - this.namespaceURI = (namespace===null || namespace==='') ? null : ('' + namespace); - this.data = value; - // Set ownerElement last to ensure it is hooked up to onchange handler - this._setOwnerElement(elt); -} - -// In DOM 3 Attr was supposed to extend Node; in DOM 4 that was abandoned. -Attr.prototype = Object.create(Object.prototype, { - ownerElement: { - get: function() { return this._ownerElement; }, - }, - _setOwnerElement: { value: function _setOwnerElement(elt) { - this._ownerElement = elt; - if (this.prefix === null && this.namespaceURI === null && elt) { - this.onchange = elt._attributeChangeHandlers[this.localName]; - } else { - this.onchange = null; - } - }}, - - name: { get: function() { - return this.prefix ? this.prefix + ':' + this.localName : this.localName; - }}, - - specified: { get: function() { - // Deprecated - return true; - }}, - - value: { - get: function() { - return this.data; - }, - set: function(value) { - var oldval = this.data; - value = (value === undefined) ? '' : value + ''; - if (value === oldval) return; - - this.data = value; - - // Run the onchange hook for the attribute - // if there is one. - if (this.ownerElement) { - if (this.onchange) - this.onchange(this.ownerElement,this.localName, oldval, value); - - // Generate a mutation event if the element is rooted - if (this.ownerElement.rooted) - this.ownerElement.ownerDocument.mutateAttr(this, oldval); - } - }, - }, - - cloneNode: { value: function cloneNode(deep) { - // Both this method and Document#createAttribute*() create unowned Attrs - return new Attr( - null, this.localName, this.prefix, this.namespaceURI, this.data - ); - }}, - - // Legacy aliases (see gh#70 and https://dom.spec.whatwg.org/#interface-attr) - nodeType: { get: function() { return Node.ATTRIBUTE_NODE; } }, - nodeName: { get: function() { return this.name; } }, - nodeValue: { - get: function() { return this.value; }, - set: function(v) { this.value = v; }, - }, - textContent: { - get: function() { return this.value; }, - set: function(v) { - if (v === null || v === undefined) { v = ''; } - this.value = v; - }, - }, - innerText: { - get: function() { return this.value; }, - set: function(v) { - if (v === null || v === undefined) { v = ''; } - this.value = v; - }, - }, -}); -// Sneakily export this class for use by Document.createAttribute() -Element._Attr = Attr; - -// The attributes property of an Element will be an instance of this class. -// This class is really just a dummy, though. It only defines a length -// property and an item() method. The AttrArrayProxy that -// defines the public API just uses the Element object itself. -function AttributesArray(elt) { - NamedNodeMap.call(this, elt); - for (var name in elt._attrsByQName) { - this[name] = elt._attrsByQName[name]; - } - for (var i = 0; i < elt._attrKeys.length; i++) { - this[i] = elt._attrsByLName[elt._attrKeys[i]]; - } -} -AttributesArray.prototype = Object.create(NamedNodeMap.prototype, { - length: { get: function() { - return this.element._attrKeys.length; - }, set: function() { /* ignore */ } }, - item: { value: function(n) { - /* jshint bitwise: false */ - n = n >>> 0; - if (n >= this.length) { return null; } - return this.element._attrsByLName[this.element._attrKeys[n]]; - /* jshint bitwise: true */ - } }, -}); - -// We can't make direct array access work (without Proxies, node >=6) -// but we can make `Array.from(node.attributes)` and for-of loops work. -if (globalThis.Symbol?.iterator) { - AttributesArray.prototype[globalThis.Symbol.iterator] = function() { - var i=0, n=this.length, self=this; - return { - next: function() { - if (ielement map. - // It is not part of the HTMLCollection API, but we need it in - // src/HTMLCollectionProxy - namedItems: { get: function() { - this.updateCache(); - return this.childrenByName; - } }, - - updateCache: { value: function updateCache() { - var namedElts = /^(a|applet|area|embed|form|frame|frameset|iframe|img|object)$/; - if (this.lastModTime !== this.element.lastModTime) { - this.lastModTime = this.element.lastModTime; - - var n = this.childrenByNumber && this.childrenByNumber.length || 0; - for(var i = 0; i < n; i++) { - this[i] = undefined; - } - - this.childrenByNumber = []; - this.childrenByName = Object.create(null); - - for (var c = this.element.firstChild; c !== null; c = c.nextSibling) { - if (c.nodeType === Node.ELEMENT_NODE) { - - this[this.childrenByNumber.length] = c; - this.childrenByNumber.push(c); - - // XXX Are there any requirements about the namespace - // of the id property? - var id = c.getAttribute('id'); - - // If there is an id that is not already in use... - if (id && !this.childrenByName[id]) - this.childrenByName[id] = c; - - // For certain HTML elements we check the name attribute - var name = c.getAttribute('name'); - if (name && - this.element.namespaceURI === NAMESPACE.HTML && - namedElts.test(this.element.localName) && - !this.childrenByName[name]) - this.childrenByName[id] = c; - } - } - } - } }, -}); - -// These functions return predicates for filtering elements. -// They're used by the Document and Element classes for methods like -// getElementsByTagName and getElementsByClassName - -function localNameElementFilter(lname) { - return function(e) { return e.localName === lname; }; -} - -function htmlLocalNameElementFilter(lname) { - var lclname = utils.toASCIILowerCase(lname); - if (lclname === lname) - return localNameElementFilter(lname); - - return function(e) { - return e.isHTML ? e.localName === lclname : e.localName === lname; - }; -} - -function namespaceElementFilter(ns) { - return function(e) { return e.namespaceURI === ns; }; -} - -function namespaceLocalNameElementFilter(ns, lname) { - return function(e) { - return e.namespaceURI === ns && e.localName === lname; - }; -} - -function classNamesElementFilter(names) { - return function(e) { - return names.every(function(n) { return e.classList.contains(n); }); - }; -} - -function elementNameFilter(name) { - return function(e) { - // All the *HTML elements* in the document with the given name attribute - if (e.namespaceURI !== NAMESPACE.HTML) { return false; } - return e.getAttribute('name') === name; - }; -} diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/Event.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/Event.js deleted file mode 100644 index a1272c4f..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/Event.js +++ /dev/null @@ -1,66 +0,0 @@ -"use strict"; -module.exports = Event; - -Event.CAPTURING_PHASE = 1; -Event.AT_TARGET = 2; -Event.BUBBLING_PHASE = 3; - -function Event(type, dictionary) { - // Initialize basic event properties - this.type = ''; - this.target = null; - this.currentTarget = null; - this.eventPhase = Event.AT_TARGET; - this.bubbles = false; - this.cancelable = false; - this.isTrusted = false; - this.defaultPrevented = false; - this.timeStamp = Date.now(); - - // Initialize internal flags - // XXX: Would it be better to inherit these defaults from the prototype? - this._propagationStopped = false; - this._immediatePropagationStopped = false; - this._initialized = true; - this._dispatching = false; - - // Now initialize based on the constructor arguments (if any) - if (type) this.type = type; - if (dictionary) { - for(var p in dictionary) { - this[p] = dictionary[p]; - } - } -} - -Event.prototype = Object.create(Object.prototype, { - constructor: { value: Event }, - stopPropagation: { value: function stopPropagation() { - this._propagationStopped = true; - }}, - - stopImmediatePropagation: { value: function stopImmediatePropagation() { - this._propagationStopped = true; - this._immediatePropagationStopped = true; - }}, - - preventDefault: { value: function preventDefault() { - if (this.cancelable) this.defaultPrevented = true; - }}, - - initEvent: { value: function initEvent(type, bubbles, cancelable) { - this._initialized = true; - if (this._dispatching) return; - - this._propagationStopped = false; - this._immediatePropagationStopped = false; - this.defaultPrevented = false; - this.isTrusted = false; - - this.target = null; - this.type = type; - this.bubbles = bubbles; - this.cancelable = cancelable; - }}, - -}); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/EventTarget.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/EventTarget.js deleted file mode 100644 index 03a9919a..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/EventTarget.js +++ /dev/null @@ -1,298 +0,0 @@ -"use strict"; -var Event = require('./Event'); -var MouseEvent = require('./MouseEvent'); -var utils = require('./utils'); - -module.exports = EventTarget; - -function EventTarget() {} - -EventTarget.prototype = { - // XXX - // See WebIDL §4.8 for details on object event handlers - // and how they should behave. We actually have to accept - // any object to addEventListener... Can't type check it. - // on registration. - - // XXX: - // Capturing event listeners are sort of rare. I think I can optimize - // them so that dispatchEvent can skip the capturing phase (or much of - // it). Each time a capturing listener is added, increment a flag on - // the target node and each of its ancestors. Decrement when removed. - // And update the counter when nodes are added and removed from the - // tree as well. Then, in dispatch event, the capturing phase can - // abort if it sees any node with a zero count. - addEventListener: function addEventListener(type, listener, capture) { - if (!listener) return; - if (capture === undefined) capture = false; - if (!this._listeners) this._listeners = Object.create(null); - if (!this._listeners[type]) this._listeners[type] = []; - var list = this._listeners[type]; - - // If this listener has already been registered, just return - for(var i = 0, n = list.length; i < n; i++) { - var l = list[i]; - if (l.listener === listener && l.capture === capture) - return; - } - - // Add an object to the list of listeners - var obj = { listener: listener, capture: capture }; - if (typeof listener === 'function') obj.f = listener; - list.push(obj); - }, - - removeEventListener: function removeEventListener(type, - listener, - capture) { - if (capture === undefined) capture = false; - if (this._listeners) { - var list = this._listeners[type]; - if (list) { - // Find the listener in the list and remove it - for(var i = 0, n = list.length; i < n; i++) { - var l = list[i]; - if (l.listener === listener && l.capture === capture) { - if (list.length === 1) { - this._listeners[type] = undefined; - } - else { - list.splice(i, 1); - } - return; - } - } - } - } - }, - - // This is the public API for dispatching untrusted public events. - // See _dispatchEvent for the implementation - dispatchEvent: function dispatchEvent(event) { - // Dispatch an untrusted event - return this._dispatchEvent(event, false); - }, - - // - // See DOMCore §4.4 - // XXX: I'll probably need another version of this method for - // internal use, one that does not set isTrusted to false. - // XXX: see Document._dispatchEvent: perhaps that and this could - // call a common internal function with different settings of - // a trusted boolean argument - // - // XXX: - // The spec has changed in how to deal with handlers registered - // on idl or content attributes rather than with addEventListener. - // Used to say that they always ran first. That's how webkit does it - // Spec now says that they run in a position determined by - // when they were first set. FF does it that way. See: - // http://www.whatwg.org/specs/web-apps/current-work/multipage/webappapis.html#event-handlers - // - _dispatchEvent: function _dispatchEvent(event, trusted) { - if (typeof trusted !== 'boolean') trusted = false; - function invoke(target, event) { - var type = event.type, phase = event.eventPhase; - event.currentTarget = target; - - // If there was an individual handler defined, invoke it first - // XXX: see comment above: this shouldn't always be first. - if (phase !== Event.CAPTURING_PHASE && - target._handlers && target._handlers[type]) - { - var handler = target._handlers[type]; - var rv; - if (typeof handler === 'function') { - rv=handler.call(event.currentTarget, event); - } - else { - var f = handler.handleEvent; - if (typeof f !== 'function') - throw new TypeError('handleEvent property of ' + - 'event handler object is' + - 'not a function.'); - rv=f.call(handler, event); - } - - switch(event.type) { - case 'mouseover': - if (rv === true) // Historical baggage - event.preventDefault(); - break; - case 'beforeunload': - // XXX: eventually we need a special case here - /* falls through */ - default: - if (rv === false) - event.preventDefault(); - break; - } - } - - // Now invoke list list of listeners for this target and type - var list = target._listeners && target._listeners[type]; - if (!list) return; - list = list.slice(); - for(var i = 0, n = list.length; i < n; i++) { - if (event._immediatePropagationStopped) return; - var l = list[i]; - if ((phase === Event.CAPTURING_PHASE && !l.capture) || - (phase === Event.BUBBLING_PHASE && l.capture)) - continue; - if (l.f) { - l.f.call(event.currentTarget, event); - } - else { - var fn = l.listener.handleEvent; - if (typeof fn !== 'function') - throw new TypeError('handleEvent property of event listener object is not a function.'); - fn.call(l.listener, event); - } - } - } - - if (!event._initialized || event._dispatching) utils.InvalidStateError(); - event.isTrusted = trusted; - - // Begin dispatching the event now - event._dispatching = true; - event.target = this; - - // Build the list of targets for the capturing and bubbling phases - // XXX: we'll eventually have to add Window to this list. - var ancestors = []; - for(var n = this.parentNode; n; n = n.parentNode) - ancestors.push(n); - - // Capturing phase - event.eventPhase = Event.CAPTURING_PHASE; - for(var i = ancestors.length-1; i >= 0; i--) { - invoke(ancestors[i], event); - if (event._propagationStopped) break; - } - - // At target phase - if (!event._propagationStopped) { - event.eventPhase = Event.AT_TARGET; - invoke(this, event); - } - - // Bubbling phase - if (event.bubbles && !event._propagationStopped) { - event.eventPhase = Event.BUBBLING_PHASE; - for(var ii = 0, nn = ancestors.length; ii < nn; ii++) { - invoke(ancestors[ii], event); - if (event._propagationStopped) break; - } - } - - event._dispatching = false; - event.eventPhase = Event.AT_TARGET; - event.currentTarget = null; - - // Deal with mouse events and figure out when - // a click has happened - if (trusted && !event.defaultPrevented && event instanceof MouseEvent) { - switch(event.type) { - case 'mousedown': - this._armed = { - x: event.clientX, - y: event.clientY, - t: event.timeStamp - }; - break; - case 'mouseout': - case 'mouseover': - this._armed = null; - break; - case 'mouseup': - if (this._isClick(event)) this._doClick(event); - this._armed = null; - break; - } - } - - - - return !event.defaultPrevented; - }, - - // Determine whether a click occurred - // XXX We don't support double clicks for now - _isClick: function(event) { - return (this._armed !== null && - event.type === 'mouseup' && - event.isTrusted && - event.button === 0 && - event.timeStamp - this._armed.t < 1000 && - Math.abs(event.clientX - this._armed.x) < 10 && - Math.abs(event.clientY - this._armed.Y) < 10); - }, - - // Clicks are handled like this: - // http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#interactive-content-0 - // - // Note that this method is similar to the HTMLElement.click() method - // The event argument must be the trusted mouseup event - _doClick: function(event) { - if (this._click_in_progress) return; - this._click_in_progress = true; - - // Find the nearest enclosing element that is activatable - // An element is activatable if it has a - // _post_click_activation_steps hook - var activated = this; - while(activated && !activated._post_click_activation_steps) - activated = activated.parentNode; - - if (activated && activated._pre_click_activation_steps) { - activated._pre_click_activation_steps(); - } - - var click = this.ownerDocument.createEvent('MouseEvent'); - click.initMouseEvent('click', true, true, - this.ownerDocument.defaultView, 1, - event.screenX, event.screenY, - event.clientX, event.clientY, - event.ctrlKey, event.altKey, - event.shiftKey, event.metaKey, - event.button, null); - - var result = this._dispatchEvent(click, true); - - if (activated) { - if (result) { - // This is where hyperlinks get followed, for example. - if (activated._post_click_activation_steps) - activated._post_click_activation_steps(click); - } - else { - if (activated._cancelled_activation_steps) - activated._cancelled_activation_steps(); - } - } - }, - - // - // An event handler is like an event listener, but it registered - // by setting an IDL or content attribute like onload or onclick. - // There can only be one of these at a time for any event type. - // This is an internal method for the attribute accessors and - // content attribute handlers that need to register events handlers. - // The type argument is the same as in addEventListener(). - // The handler argument is the same as listeners in addEventListener: - // it can be a function or an object. Pass null to remove any existing - // handler. Handlers are always invoked before any listeners of - // the same type. They are not invoked during the capturing phase - // of event dispatch. - // - _setEventHandler: function _setEventHandler(type, handler) { - if (!this._handlers) this._handlers = Object.create(null); - this._handlers[type] = handler; - }, - - _getEventHandler: function _getEventHandler(type) { - return (this._handlers && this._handlers[type]) || null; - } - -}; diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/FilteredElementList.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/FilteredElementList.js deleted file mode 100644 index 72e912de..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/FilteredElementList.js +++ /dev/null @@ -1,92 +0,0 @@ -"use strict"; -module.exports = FilteredElementList; - -var Node = require('./Node'); - -// -// This file defines node list implementation that lazily traverses -// the document tree (or a subtree rooted at any element) and includes -// only those elements for which a specified filter function returns true. -// It is used to implement the -// {Document,Element}.getElementsBy{TagName,ClassName}{,NS} methods. -// -// XXX this should inherit from NodeList - -function FilteredElementList(root, filter) { - this.root = root; - this.filter = filter; - this.lastModTime = root.lastModTime; - this.done = false; - this.cache = []; - this.traverse(); -} - -FilteredElementList.prototype = Object.create(Object.prototype, { - length: { get: function() { - this.checkcache(); - if (!this.done) this.traverse(); - return this.cache.length; - } }, - - item: { value: function(n) { - this.checkcache(); - if (!this.done && n >= this.cache.length) { - // This can lead to O(N^2) behavior if we stop when we get to n - // and the caller is iterating through the items in order; so - // be sure to do the full traverse here. - this.traverse(/*n*/); - } - return this.cache[n]; - } }, - - checkcache: { value: function() { - if (this.lastModTime !== this.root.lastModTime) { - // subtree has changed, so invalidate cache - for (var i = this.cache.length-1; i>=0; i--) { - this[i] = undefined; - } - this.cache.length = 0; - this.done = false; - this.lastModTime = this.root.lastModTime; - } - } }, - - // If n is specified, then traverse the tree until we've found the nth - // item (or until we've found all items). If n is not specified, - // traverse until we've found all items. - traverse: { value: function(n) { - // increment n so we can compare to length, and so it is never falsy - if (n !== undefined) n++; - - var elt; - while ((elt = this.next()) !== null) { - this[this.cache.length] = elt; //XXX Use proxy instead - this.cache.push(elt); - if (n && this.cache.length === n) return; - } - - // no next element, so we've found everything - this.done = true; - } }, - - // Return the next element under root that matches filter - next: { value: function() { - var start = (this.cache.length === 0) ? this.root // Start at the root or at - : this.cache[this.cache.length-1]; // the last element we found - - var elt; - if (start.nodeType === Node.DOCUMENT_NODE) - elt = start.documentElement; - else - elt = start.nextElement(this.root); - - while(elt) { - if (this.filter(elt)) { - return elt; - } - - elt = elt.nextElement(this.root); - } - return null; - } }, -}); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/HTMLParser.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/HTMLParser.js deleted file mode 100644 index 45d8fc17..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/HTMLParser.js +++ /dev/null @@ -1,7254 +0,0 @@ -"use strict"; -module.exports = HTMLParser; - -var Document = require('./Document'); -var DocumentType = require('./DocumentType'); -var Node = require('./Node'); -var NAMESPACE = require('./utils').NAMESPACE; -var html = require('./htmlelts'); -var impl = html.elements; - -var pushAll = Function.prototype.apply.bind(Array.prototype.push); - -/* - * This file contains an implementation of the HTML parsing algorithm. - * The algorithm and the implementation are complex because HTML - * explicitly defines how the parser should behave for all possible - * valid and invalid inputs. - * - * Usage: - * - * The file defines a single HTMLParser() function, which dom.js exposes - * publicly as document.implementation.mozHTMLParser(). This is a - * factory function, not a constructor. - * - * When you call document.implementation.mozHTMLParser(), it returns - * an object that has parse() and document() methods. To parse HTML text, - * pass the text (in one or more chunks) to the parse() method. When - * you've passed all the text (on the last chunk, or afterward) pass - * true as the second argument to parse() to tell the parser that there - * is no more coming. Call document() to get the document object that - * the parser is parsing into. You can call this at any time, before - * or after calling parse(). - * - * The first argument to mozHTMLParser is the absolute URL of the document. - * - * The second argument is optional and is for internal use only. Pass an - * element as the fragmentContext to do innerHTML parsing for the - * element. To do innerHTML parsing on a document, pass null. Otherwise, - * omit the 2nd argument. See HTMLElement.innerHTML for an example. Note - * that if you pass a context element, the end() method will return an - * unwrapped document instead of a wrapped one. - * - * Implementation details: - * - * This is a long file of almost 7000 lines. It is structured as one - * big function nested within another big function. The outer - * function defines a bunch of constant data, utility functions - * that use that data, and a couple of classes used by the parser. - * The outer function also defines and returns the - * inner function. This inner function is the HTMLParser factory - * function that implements the parser and holds all the parser state - * as local variables. The HTMLParser function is quite big because - * it defines many nested functions that use those local variables. - * - * There are three tightly coupled parser stages: a scanner, a - * tokenizer and a tree builder. In a (possibly misguided) attempt at - * efficiency, the stages are not implemented as separate classes: - * everything shares state and is (mostly) implemented in imperative - * (rather than OO) style. - * - * The stages of the parser work like this: When the client code calls - * the parser's parse() method, the specified string is passed to - * scanChars(). The scanner loops through that string and passes characters - * (sometimes one at a time, sometimes in chunks) to the tokenizer stage. - * The tokenizer groups the characters into tokens: tags, endtags, runs - * of text, comments, doctype declarations, and the end-of-file (EOF) - * token. These tokens are then passed to the tree building stage via - * the insertToken() function. The tree building stage builds up the - * document tree. - * - * The tokenizer stage is a finite state machine. Each state is - * implemented as a function with a name that ends in "_state". The - * initial state is data_state(). The current tokenizer state is stored - * in the variable 'tokenizer'. Most state functions expect a single - * integer argument which represents a single UTF-16 codepoint. Some - * states want more characters and set a lookahead property on - * themselves. The scanChars() function in the scanner checks for this - * lookahead property. If it doesn't exist, then scanChars() just passes - * the next input character to the current tokenizer state function. - * Otherwise, scanChars() looks ahead (a given # of characters, or for a - * matching string, or for a matching regexp) and passes a string of - * characters to the current tokenizer state function. - * - * As a shortcut, certain states of the tokenizer use regular expressions - * to look ahead in the scanner's input buffer for runs of text, simple - * tags and attributes. For well-formed input, these shortcuts skip a - * lot of state transitions and speed things up a bit. - * - * When a tokenizer state function has consumed a complete token, it - * emits that token, by calling insertToken(), or by calling a utility - * function that itself calls insertToken(). These tokens are passed to - * the tree building stage, which is also a state machine. Like the - * tokenizer, the tree building states are implemented as functions, and - * these functions have names that end with _mode (because the HTML spec - * refers to them as insertion modes). The current insertion mode is held - * by the 'parser' variable. Each insertion mode function takes up to 4 - * arguments. The first is a token type, represented by the constants - * TAG, ENDTAG, TEXT, COMMENT, DOCTYPE and EOF. The second argument is - * the value of the token: the text or comment data, or tagname or - * doctype. For tags, the 3rd argument is an array of attributes. For - * DOCTYPES it is the optional public id. For tags, the 4th argument is - * true if the tag is self-closing. For doctypes, the 4th argument is the - * optional system id. - * - * Search for "***" to find the major sub-divisions in the code. - */ - - -/*** - * Data prolog. Lots of constants declared here, including some - * very large objects. They're used throughout the code that follows - */ -// Token types for the tree builder. -var EOF = -1; -var TEXT = 1; -var TAG = 2; -var ENDTAG = 3; -var COMMENT = 4; -var DOCTYPE = 5; - -// A re-usable empty array -var NOATTRS = []; - -// These DTD public ids put the browser in quirks mode -var quirkyPublicIds = /^HTML$|^-\/\/W3O\/\/DTD W3 HTML Strict 3\.0\/\/EN\/\/$|^-\/W3C\/DTD HTML 4\.0 Transitional\/EN$|^\+\/\/Silmaril\/\/dtd html Pro v0r11 19970101\/\/|^-\/\/AdvaSoft Ltd\/\/DTD HTML 3\.0 asWedit \+ extensions\/\/|^-\/\/AS\/\/DTD HTML 3\.0 asWedit \+ extensions\/\/|^-\/\/IETF\/\/DTD HTML 2\.0 Level 1\/\/|^-\/\/IETF\/\/DTD HTML 2\.0 Level 2\/\/|^-\/\/IETF\/\/DTD HTML 2\.0 Strict Level 1\/\/|^-\/\/IETF\/\/DTD HTML 2\.0 Strict Level 2\/\/|^-\/\/IETF\/\/DTD HTML 2\.0 Strict\/\/|^-\/\/IETF\/\/DTD HTML 2\.0\/\/|^-\/\/IETF\/\/DTD HTML 2\.1E\/\/|^-\/\/IETF\/\/DTD HTML 3\.0\/\/|^-\/\/IETF\/\/DTD HTML 3\.2 Final\/\/|^-\/\/IETF\/\/DTD HTML 3\.2\/\/|^-\/\/IETF\/\/DTD HTML 3\/\/|^-\/\/IETF\/\/DTD HTML Level 0\/\/|^-\/\/IETF\/\/DTD HTML Level 1\/\/|^-\/\/IETF\/\/DTD HTML Level 2\/\/|^-\/\/IETF\/\/DTD HTML Level 3\/\/|^-\/\/IETF\/\/DTD HTML Strict Level 0\/\/|^-\/\/IETF\/\/DTD HTML Strict Level 1\/\/|^-\/\/IETF\/\/DTD HTML Strict Level 2\/\/|^-\/\/IETF\/\/DTD HTML Strict Level 3\/\/|^-\/\/IETF\/\/DTD HTML Strict\/\/|^-\/\/IETF\/\/DTD HTML\/\/|^-\/\/Metrius\/\/DTD Metrius Presentational\/\/|^-\/\/Microsoft\/\/DTD Internet Explorer 2\.0 HTML Strict\/\/|^-\/\/Microsoft\/\/DTD Internet Explorer 2\.0 HTML\/\/|^-\/\/Microsoft\/\/DTD Internet Explorer 2\.0 Tables\/\/|^-\/\/Microsoft\/\/DTD Internet Explorer 3\.0 HTML Strict\/\/|^-\/\/Microsoft\/\/DTD Internet Explorer 3\.0 HTML\/\/|^-\/\/Microsoft\/\/DTD Internet Explorer 3\.0 Tables\/\/|^-\/\/Netscape Comm\. Corp\.\/\/DTD HTML\/\/|^-\/\/Netscape Comm\. Corp\.\/\/DTD Strict HTML\/\/|^-\/\/O'Reilly and Associates\/\/DTD HTML 2\.0\/\/|^-\/\/O'Reilly and Associates\/\/DTD HTML Extended 1\.0\/\/|^-\/\/O'Reilly and Associates\/\/DTD HTML Extended Relaxed 1\.0\/\/|^-\/\/SoftQuad Software\/\/DTD HoTMetaL PRO 6\.0::19990601::extensions to HTML 4\.0\/\/|^-\/\/SoftQuad\/\/DTD HoTMetaL PRO 4\.0::19971010::extensions to HTML 4\.0\/\/|^-\/\/Spyglass\/\/DTD HTML 2\.0 Extended\/\/|^-\/\/SQ\/\/DTD HTML 2\.0 HoTMetaL \+ extensions\/\/|^-\/\/Sun Microsystems Corp\.\/\/DTD HotJava HTML\/\/|^-\/\/Sun Microsystems Corp\.\/\/DTD HotJava Strict HTML\/\/|^-\/\/W3C\/\/DTD HTML 3 1995-03-24\/\/|^-\/\/W3C\/\/DTD HTML 3\.2 Draft\/\/|^-\/\/W3C\/\/DTD HTML 3\.2 Final\/\/|^-\/\/W3C\/\/DTD HTML 3\.2\/\/|^-\/\/W3C\/\/DTD HTML 3\.2S Draft\/\/|^-\/\/W3C\/\/DTD HTML 4\.0 Frameset\/\/|^-\/\/W3C\/\/DTD HTML 4\.0 Transitional\/\/|^-\/\/W3C\/\/DTD HTML Experimental 19960712\/\/|^-\/\/W3C\/\/DTD HTML Experimental 970421\/\/|^-\/\/W3C\/\/DTD W3 HTML\/\/|^-\/\/W3O\/\/DTD W3 HTML 3\.0\/\/|^-\/\/WebTechs\/\/DTD Mozilla HTML 2\.0\/\/|^-\/\/WebTechs\/\/DTD Mozilla HTML\/\//i; - -var quirkySystemId = "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd"; - -var conditionallyQuirkyPublicIds = /^-\/\/W3C\/\/DTD HTML 4\.01 Frameset\/\/|^-\/\/W3C\/\/DTD HTML 4\.01 Transitional\/\//i; - -// These DTD public ids put the browser in limited quirks mode -var limitedQuirkyPublicIds = /^-\/\/W3C\/\/DTD XHTML 1\.0 Frameset\/\/|^-\/\/W3C\/\/DTD XHTML 1\.0 Transitional\/\//i; - - -// Element sets below. See the isA() function for a way to test -// whether an element is a member of a set -var specialSet = Object.create(null); -specialSet[NAMESPACE.HTML] = { - __proto__: null, - "address":true, "applet":true, "area":true, "article":true, - "aside":true, "base":true, "basefont":true, "bgsound":true, - "blockquote":true, "body":true, "br":true, "button":true, - "caption":true, "center":true, "col":true, "colgroup":true, - "dd":true, "details":true, "dir":true, - "div":true, "dl":true, "dt":true, "embed":true, - "fieldset":true, "figcaption":true, "figure":true, "footer":true, - "form":true, "frame":true, "frameset":true, "h1":true, - "h2":true, "h3":true, "h4":true, "h5":true, - "h6":true, "head":true, "header":true, "hgroup":true, - "hr":true, "html":true, "iframe":true, "img":true, - "input":true, "li":true, "link":true, - "listing":true, "main":true, "marquee":true, "menu":true, "meta":true, - "nav":true, "noembed":true, "noframes":true, "noscript":true, - "object":true, "ol":true, "p":true, "param":true, - "plaintext":true, "pre":true, "script":true, "section":true, - "select":true, "source":true, "style":true, "summary":true, "table":true, - "tbody":true, "td":true, "template":true, "textarea":true, "tfoot":true, - "th":true, "thead":true, "title":true, "tr":true, "track":true, - // Note that "xmp" was removed from the "special" set in the latest - // spec, apparently by accident; see - // https://github.com/whatwg/html/pull/1919 - "ul":true, "wbr":true, "xmp":true -}; -specialSet[NAMESPACE.SVG] = { - __proto__: null, - "foreignObject": true, "desc": true, "title": true -}; -specialSet[NAMESPACE.MATHML] = { - __proto__: null, - "mi":true, "mo":true, "mn":true, "ms":true, - "mtext":true, "annotation-xml":true -}; - -// The set of address, div, and p HTML tags -var addressdivpSet = Object.create(null); -addressdivpSet[NAMESPACE.HTML] = { - __proto__: null, - "address":true, "div":true, "p":true -}; - -var dddtSet = Object.create(null); -dddtSet[NAMESPACE.HTML] = { - __proto__: null, - "dd":true, "dt":true -}; - -var tablesectionrowSet = Object.create(null); -tablesectionrowSet[NAMESPACE.HTML] = { - __proto__: null, - "table":true, "thead":true, "tbody":true, "tfoot":true, "tr":true -}; - -var impliedEndTagsSet = Object.create(null); -impliedEndTagsSet[NAMESPACE.HTML] = { - __proto__: null, - "dd": true, "dt": true, "li": true, "menuitem": true, "optgroup": true, - "option": true, "p": true, "rb": true, "rp": true, "rt": true, "rtc": true -}; - -var thoroughImpliedEndTagsSet = Object.create(null); -thoroughImpliedEndTagsSet[NAMESPACE.HTML] = { - __proto__: null, - "caption": true, "colgroup": true, "dd": true, "dt": true, "li": true, - "optgroup": true, "option": true, "p": true, "rb": true, "rp": true, - "rt": true, "rtc": true, "tbody": true, "td": true, "tfoot": true, - "th": true, "thead": true, "tr": true -}; - -var tableContextSet = Object.create(null); -tableContextSet[NAMESPACE.HTML] = { - __proto__: null, - "table": true, "template": true, "html": true -}; - -var tableBodyContextSet = Object.create(null); -tableBodyContextSet[NAMESPACE.HTML] = { - __proto__: null, - "tbody": true, "tfoot": true, "thead": true, "template": true, "html": true -}; - -var tableRowContextSet = Object.create(null); -tableRowContextSet[NAMESPACE.HTML] = { - __proto__: null, - "tr": true, "template": true, "html": true -}; - -// See http://www.w3.org/TR/html5/forms.html#form-associated-element -var formassociatedSet = Object.create(null); -formassociatedSet[NAMESPACE.HTML] = { - __proto__: null, - "button": true, "fieldset": true, "input": true, "keygen": true, - "object": true, "output": true, "select": true, "textarea": true, - "img": true -}; - -var inScopeSet = Object.create(null); -inScopeSet[NAMESPACE.HTML]= { - __proto__: null, - "applet":true, "caption":true, "html":true, "table":true, - "td":true, "th":true, "marquee":true, "object":true, - "template":true -}; -inScopeSet[NAMESPACE.MATHML] = { - __proto__: null, - "mi":true, "mo":true, "mn":true, "ms":true, - "mtext":true, "annotation-xml":true -}; -inScopeSet[NAMESPACE.SVG] = { - __proto__: null, - "foreignObject":true, "desc":true, "title":true -}; - -var inListItemScopeSet = Object.create(inScopeSet); -inListItemScopeSet[NAMESPACE.HTML] = - Object.create(inScopeSet[NAMESPACE.HTML]); -inListItemScopeSet[NAMESPACE.HTML].ol = true; -inListItemScopeSet[NAMESPACE.HTML].ul = true; - -var inButtonScopeSet = Object.create(inScopeSet); -inButtonScopeSet[NAMESPACE.HTML] = - Object.create(inScopeSet[NAMESPACE.HTML]); -inButtonScopeSet[NAMESPACE.HTML].button = true; - -var inTableScopeSet = Object.create(null); -inTableScopeSet[NAMESPACE.HTML] = { - __proto__: null, - "html":true, "table":true, "template":true -}; - -// The set of elements for select scope is the everything *except* these -var invertedSelectScopeSet = Object.create(null); -invertedSelectScopeSet[NAMESPACE.HTML] = { - __proto__: null, - "optgroup":true, "option":true -}; - -var mathmlTextIntegrationPointSet = Object.create(null); -mathmlTextIntegrationPointSet[NAMESPACE.MATHML] = { - __proto__: null, - mi: true, - mo: true, - mn: true, - ms: true, - mtext: true -}; - -var htmlIntegrationPointSet = Object.create(null); -htmlIntegrationPointSet[NAMESPACE.SVG] = { - __proto__: null, - foreignObject: true, - desc: true, - title: true -}; - -var foreignAttributes = { - __proto__: null, - "xlink:actuate": NAMESPACE.XLINK, "xlink:arcrole": NAMESPACE.XLINK, - "xlink:href": NAMESPACE.XLINK, "xlink:role": NAMESPACE.XLINK, - "xlink:show": NAMESPACE.XLINK, "xlink:title": NAMESPACE.XLINK, - "xlink:type": NAMESPACE.XLINK, "xml:base": NAMESPACE.XML, - "xml:lang": NAMESPACE.XML, "xml:space": NAMESPACE.XML, - "xmlns": NAMESPACE.XMLNS, "xmlns:xlink": NAMESPACE.XMLNS -}; - - -// Lowercase to mixed case mapping for SVG attributes and tagnames -var svgAttrAdjustments = { - __proto__: null, - attributename: "attributeName", attributetype: "attributeType", - basefrequency: "baseFrequency", baseprofile: "baseProfile", - calcmode: "calcMode", clippathunits: "clipPathUnits", - diffuseconstant: "diffuseConstant", - edgemode: "edgeMode", - filterunits: "filterUnits", - glyphref: "glyphRef", gradienttransform: "gradientTransform", - gradientunits: "gradientUnits", kernelmatrix: "kernelMatrix", - kernelunitlength: "kernelUnitLength", keypoints: "keyPoints", - keysplines: "keySplines", keytimes: "keyTimes", - lengthadjust: "lengthAdjust", limitingconeangle: "limitingConeAngle", - markerheight: "markerHeight", markerunits: "markerUnits", - markerwidth: "markerWidth", maskcontentunits: "maskContentUnits", - maskunits: "maskUnits", numoctaves: "numOctaves", - pathlength: "pathLength", patterncontentunits: "patternContentUnits", - patterntransform: "patternTransform", patternunits: "patternUnits", - pointsatx: "pointsAtX", pointsaty: "pointsAtY", - pointsatz: "pointsAtZ", preservealpha: "preserveAlpha", - preserveaspectratio: "preserveAspectRatio", - primitiveunits: "primitiveUnits", refx: "refX", - refy: "refY", repeatcount: "repeatCount", - repeatdur: "repeatDur", requiredextensions: "requiredExtensions", - requiredfeatures: "requiredFeatures", - specularconstant: "specularConstant", - specularexponent: "specularExponent", spreadmethod: "spreadMethod", - startoffset: "startOffset", stddeviation: "stdDeviation", - stitchtiles: "stitchTiles", surfacescale: "surfaceScale", - systemlanguage: "systemLanguage", tablevalues: "tableValues", - targetx: "targetX", targety: "targetY", - textlength: "textLength", viewbox: "viewBox", - viewtarget: "viewTarget", xchannelselector: "xChannelSelector", - ychannelselector: "yChannelSelector", zoomandpan: "zoomAndPan" -}; - -var svgTagNameAdjustments = { - __proto__: null, - altglyph: "altGlyph", altglyphdef: "altGlyphDef", - altglyphitem: "altGlyphItem", animatecolor: "animateColor", - animatemotion: "animateMotion", animatetransform: "animateTransform", - clippath: "clipPath", feblend: "feBlend", - fecolormatrix: "feColorMatrix", - fecomponenttransfer: "feComponentTransfer", fecomposite: "feComposite", - feconvolvematrix: "feConvolveMatrix", - fediffuselighting: "feDiffuseLighting", - fedisplacementmap: "feDisplacementMap", - fedistantlight: "feDistantLight", feflood: "feFlood", - fefunca: "feFuncA", fefuncb: "feFuncB", - fefuncg: "feFuncG", fefuncr: "feFuncR", - fegaussianblur: "feGaussianBlur", feimage: "feImage", - femerge: "feMerge", femergenode: "feMergeNode", - femorphology: "feMorphology", feoffset: "feOffset", - fepointlight: "fePointLight", fespecularlighting: "feSpecularLighting", - fespotlight: "feSpotLight", fetile: "feTile", - feturbulence: "feTurbulence", foreignobject: "foreignObject", - glyphref: "glyphRef", lineargradient: "linearGradient", - radialgradient: "radialGradient", textpath: "textPath" -}; - - -// Data for parsing numeric and named character references -// These next 3 objects are direct translations of tables -// in the HTML spec into JavaScript object format -var numericCharRefReplacements = { - __proto__: null, - 0x00:0xFFFD, 0x80:0x20AC, 0x82:0x201A, 0x83:0x0192, 0x84:0x201E, - 0x85:0x2026, 0x86:0x2020, 0x87:0x2021, 0x88:0x02C6, 0x89:0x2030, - 0x8A:0x0160, 0x8B:0x2039, 0x8C:0x0152, 0x8E:0x017D, 0x91:0x2018, - 0x92:0x2019, 0x93:0x201C, 0x94:0x201D, 0x95:0x2022, 0x96:0x2013, - 0x97:0x2014, 0x98:0x02DC, 0x99:0x2122, 0x9A:0x0161, 0x9B:0x203A, - 0x9C:0x0153, 0x9E:0x017E, 0x9F:0x0178 -}; - -/* - * This table is generated with test/tools/update-entities.js - */ -var namedCharRefs = { - __proto__: null, - "AElig":0xc6, "AElig;":0xc6, - "AMP":0x26, "AMP;":0x26, - "Aacute":0xc1, "Aacute;":0xc1, - "Abreve;":0x102, "Acirc":0xc2, - "Acirc;":0xc2, "Acy;":0x410, - "Afr;":[0xd835,0xdd04], "Agrave":0xc0, - "Agrave;":0xc0, "Alpha;":0x391, - "Amacr;":0x100, "And;":0x2a53, - "Aogon;":0x104, "Aopf;":[0xd835,0xdd38], - "ApplyFunction;":0x2061, "Aring":0xc5, - "Aring;":0xc5, "Ascr;":[0xd835,0xdc9c], - "Assign;":0x2254, "Atilde":0xc3, - "Atilde;":0xc3, "Auml":0xc4, - "Auml;":0xc4, "Backslash;":0x2216, - "Barv;":0x2ae7, "Barwed;":0x2306, - "Bcy;":0x411, "Because;":0x2235, - "Bernoullis;":0x212c, "Beta;":0x392, - "Bfr;":[0xd835,0xdd05], "Bopf;":[0xd835,0xdd39], - "Breve;":0x2d8, "Bscr;":0x212c, - "Bumpeq;":0x224e, "CHcy;":0x427, - "COPY":0xa9, "COPY;":0xa9, - "Cacute;":0x106, "Cap;":0x22d2, - "CapitalDifferentialD;":0x2145, "Cayleys;":0x212d, - "Ccaron;":0x10c, "Ccedil":0xc7, - "Ccedil;":0xc7, "Ccirc;":0x108, - "Cconint;":0x2230, "Cdot;":0x10a, - "Cedilla;":0xb8, "CenterDot;":0xb7, - "Cfr;":0x212d, "Chi;":0x3a7, - "CircleDot;":0x2299, "CircleMinus;":0x2296, - "CirclePlus;":0x2295, "CircleTimes;":0x2297, - "ClockwiseContourIntegral;":0x2232, "CloseCurlyDoubleQuote;":0x201d, - "CloseCurlyQuote;":0x2019, "Colon;":0x2237, - "Colone;":0x2a74, "Congruent;":0x2261, - "Conint;":0x222f, "ContourIntegral;":0x222e, - "Copf;":0x2102, "Coproduct;":0x2210, - "CounterClockwiseContourIntegral;":0x2233, "Cross;":0x2a2f, - "Cscr;":[0xd835,0xdc9e], "Cup;":0x22d3, - "CupCap;":0x224d, "DD;":0x2145, - "DDotrahd;":0x2911, "DJcy;":0x402, - "DScy;":0x405, "DZcy;":0x40f, - "Dagger;":0x2021, "Darr;":0x21a1, - "Dashv;":0x2ae4, "Dcaron;":0x10e, - "Dcy;":0x414, "Del;":0x2207, - "Delta;":0x394, "Dfr;":[0xd835,0xdd07], - "DiacriticalAcute;":0xb4, "DiacriticalDot;":0x2d9, - "DiacriticalDoubleAcute;":0x2dd, "DiacriticalGrave;":0x60, - "DiacriticalTilde;":0x2dc, "Diamond;":0x22c4, - "DifferentialD;":0x2146, "Dopf;":[0xd835,0xdd3b], - "Dot;":0xa8, "DotDot;":0x20dc, - "DotEqual;":0x2250, "DoubleContourIntegral;":0x222f, - "DoubleDot;":0xa8, "DoubleDownArrow;":0x21d3, - "DoubleLeftArrow;":0x21d0, "DoubleLeftRightArrow;":0x21d4, - "DoubleLeftTee;":0x2ae4, "DoubleLongLeftArrow;":0x27f8, - "DoubleLongLeftRightArrow;":0x27fa, "DoubleLongRightArrow;":0x27f9, - "DoubleRightArrow;":0x21d2, "DoubleRightTee;":0x22a8, - "DoubleUpArrow;":0x21d1, "DoubleUpDownArrow;":0x21d5, - "DoubleVerticalBar;":0x2225, "DownArrow;":0x2193, - "DownArrowBar;":0x2913, "DownArrowUpArrow;":0x21f5, - "DownBreve;":0x311, "DownLeftRightVector;":0x2950, - "DownLeftTeeVector;":0x295e, "DownLeftVector;":0x21bd, - "DownLeftVectorBar;":0x2956, "DownRightTeeVector;":0x295f, - "DownRightVector;":0x21c1, "DownRightVectorBar;":0x2957, - "DownTee;":0x22a4, "DownTeeArrow;":0x21a7, - "Downarrow;":0x21d3, "Dscr;":[0xd835,0xdc9f], - "Dstrok;":0x110, "ENG;":0x14a, - "ETH":0xd0, "ETH;":0xd0, - "Eacute":0xc9, "Eacute;":0xc9, - "Ecaron;":0x11a, "Ecirc":0xca, - "Ecirc;":0xca, "Ecy;":0x42d, - "Edot;":0x116, "Efr;":[0xd835,0xdd08], - "Egrave":0xc8, "Egrave;":0xc8, - "Element;":0x2208, "Emacr;":0x112, - "EmptySmallSquare;":0x25fb, "EmptyVerySmallSquare;":0x25ab, - "Eogon;":0x118, "Eopf;":[0xd835,0xdd3c], - "Epsilon;":0x395, "Equal;":0x2a75, - "EqualTilde;":0x2242, "Equilibrium;":0x21cc, - "Escr;":0x2130, "Esim;":0x2a73, - "Eta;":0x397, "Euml":0xcb, - "Euml;":0xcb, "Exists;":0x2203, - "ExponentialE;":0x2147, "Fcy;":0x424, - "Ffr;":[0xd835,0xdd09], "FilledSmallSquare;":0x25fc, - "FilledVerySmallSquare;":0x25aa, "Fopf;":[0xd835,0xdd3d], - "ForAll;":0x2200, "Fouriertrf;":0x2131, - "Fscr;":0x2131, "GJcy;":0x403, - "GT":0x3e, "GT;":0x3e, - "Gamma;":0x393, "Gammad;":0x3dc, - "Gbreve;":0x11e, "Gcedil;":0x122, - "Gcirc;":0x11c, "Gcy;":0x413, - "Gdot;":0x120, "Gfr;":[0xd835,0xdd0a], - "Gg;":0x22d9, "Gopf;":[0xd835,0xdd3e], - "GreaterEqual;":0x2265, "GreaterEqualLess;":0x22db, - "GreaterFullEqual;":0x2267, "GreaterGreater;":0x2aa2, - "GreaterLess;":0x2277, "GreaterSlantEqual;":0x2a7e, - "GreaterTilde;":0x2273, "Gscr;":[0xd835,0xdca2], - "Gt;":0x226b, "HARDcy;":0x42a, - "Hacek;":0x2c7, "Hat;":0x5e, - "Hcirc;":0x124, "Hfr;":0x210c, - "HilbertSpace;":0x210b, "Hopf;":0x210d, - "HorizontalLine;":0x2500, "Hscr;":0x210b, - "Hstrok;":0x126, "HumpDownHump;":0x224e, - "HumpEqual;":0x224f, "IEcy;":0x415, - "IJlig;":0x132, "IOcy;":0x401, - "Iacute":0xcd, "Iacute;":0xcd, - "Icirc":0xce, "Icirc;":0xce, - "Icy;":0x418, "Idot;":0x130, - "Ifr;":0x2111, "Igrave":0xcc, - "Igrave;":0xcc, "Im;":0x2111, - "Imacr;":0x12a, "ImaginaryI;":0x2148, - "Implies;":0x21d2, "Int;":0x222c, - "Integral;":0x222b, "Intersection;":0x22c2, - "InvisibleComma;":0x2063, "InvisibleTimes;":0x2062, - "Iogon;":0x12e, "Iopf;":[0xd835,0xdd40], - "Iota;":0x399, "Iscr;":0x2110, - "Itilde;":0x128, "Iukcy;":0x406, - "Iuml":0xcf, "Iuml;":0xcf, - "Jcirc;":0x134, "Jcy;":0x419, - "Jfr;":[0xd835,0xdd0d], "Jopf;":[0xd835,0xdd41], - "Jscr;":[0xd835,0xdca5], "Jsercy;":0x408, - "Jukcy;":0x404, "KHcy;":0x425, - "KJcy;":0x40c, "Kappa;":0x39a, - "Kcedil;":0x136, "Kcy;":0x41a, - "Kfr;":[0xd835,0xdd0e], "Kopf;":[0xd835,0xdd42], - "Kscr;":[0xd835,0xdca6], "LJcy;":0x409, - "LT":0x3c, "LT;":0x3c, - "Lacute;":0x139, "Lambda;":0x39b, - "Lang;":0x27ea, "Laplacetrf;":0x2112, - "Larr;":0x219e, "Lcaron;":0x13d, - "Lcedil;":0x13b, "Lcy;":0x41b, - "LeftAngleBracket;":0x27e8, "LeftArrow;":0x2190, - "LeftArrowBar;":0x21e4, "LeftArrowRightArrow;":0x21c6, - "LeftCeiling;":0x2308, "LeftDoubleBracket;":0x27e6, - "LeftDownTeeVector;":0x2961, "LeftDownVector;":0x21c3, - "LeftDownVectorBar;":0x2959, "LeftFloor;":0x230a, - "LeftRightArrow;":0x2194, "LeftRightVector;":0x294e, - "LeftTee;":0x22a3, "LeftTeeArrow;":0x21a4, - "LeftTeeVector;":0x295a, "LeftTriangle;":0x22b2, - "LeftTriangleBar;":0x29cf, "LeftTriangleEqual;":0x22b4, - "LeftUpDownVector;":0x2951, "LeftUpTeeVector;":0x2960, - "LeftUpVector;":0x21bf, "LeftUpVectorBar;":0x2958, - "LeftVector;":0x21bc, "LeftVectorBar;":0x2952, - "Leftarrow;":0x21d0, "Leftrightarrow;":0x21d4, - "LessEqualGreater;":0x22da, "LessFullEqual;":0x2266, - "LessGreater;":0x2276, "LessLess;":0x2aa1, - "LessSlantEqual;":0x2a7d, "LessTilde;":0x2272, - "Lfr;":[0xd835,0xdd0f], "Ll;":0x22d8, - "Lleftarrow;":0x21da, "Lmidot;":0x13f, - "LongLeftArrow;":0x27f5, "LongLeftRightArrow;":0x27f7, - "LongRightArrow;":0x27f6, "Longleftarrow;":0x27f8, - "Longleftrightarrow;":0x27fa, "Longrightarrow;":0x27f9, - "Lopf;":[0xd835,0xdd43], "LowerLeftArrow;":0x2199, - "LowerRightArrow;":0x2198, "Lscr;":0x2112, - "Lsh;":0x21b0, "Lstrok;":0x141, - "Lt;":0x226a, "Map;":0x2905, - "Mcy;":0x41c, "MediumSpace;":0x205f, - "Mellintrf;":0x2133, "Mfr;":[0xd835,0xdd10], - "MinusPlus;":0x2213, "Mopf;":[0xd835,0xdd44], - "Mscr;":0x2133, "Mu;":0x39c, - "NJcy;":0x40a, "Nacute;":0x143, - "Ncaron;":0x147, "Ncedil;":0x145, - "Ncy;":0x41d, "NegativeMediumSpace;":0x200b, - "NegativeThickSpace;":0x200b, "NegativeThinSpace;":0x200b, - "NegativeVeryThinSpace;":0x200b, "NestedGreaterGreater;":0x226b, - "NestedLessLess;":0x226a, "NewLine;":0xa, - "Nfr;":[0xd835,0xdd11], "NoBreak;":0x2060, - "NonBreakingSpace;":0xa0, "Nopf;":0x2115, - "Not;":0x2aec, "NotCongruent;":0x2262, - "NotCupCap;":0x226d, "NotDoubleVerticalBar;":0x2226, - "NotElement;":0x2209, "NotEqual;":0x2260, - "NotEqualTilde;":[0x2242,0x338], "NotExists;":0x2204, - "NotGreater;":0x226f, "NotGreaterEqual;":0x2271, - "NotGreaterFullEqual;":[0x2267,0x338], "NotGreaterGreater;":[0x226b,0x338], - "NotGreaterLess;":0x2279, "NotGreaterSlantEqual;":[0x2a7e,0x338], - "NotGreaterTilde;":0x2275, "NotHumpDownHump;":[0x224e,0x338], - "NotHumpEqual;":[0x224f,0x338], "NotLeftTriangle;":0x22ea, - "NotLeftTriangleBar;":[0x29cf,0x338], "NotLeftTriangleEqual;":0x22ec, - "NotLess;":0x226e, "NotLessEqual;":0x2270, - "NotLessGreater;":0x2278, "NotLessLess;":[0x226a,0x338], - "NotLessSlantEqual;":[0x2a7d,0x338], "NotLessTilde;":0x2274, - "NotNestedGreaterGreater;":[0x2aa2,0x338], "NotNestedLessLess;":[0x2aa1,0x338], - "NotPrecedes;":0x2280, "NotPrecedesEqual;":[0x2aaf,0x338], - "NotPrecedesSlantEqual;":0x22e0, "NotReverseElement;":0x220c, - "NotRightTriangle;":0x22eb, "NotRightTriangleBar;":[0x29d0,0x338], - "NotRightTriangleEqual;":0x22ed, "NotSquareSubset;":[0x228f,0x338], - "NotSquareSubsetEqual;":0x22e2, "NotSquareSuperset;":[0x2290,0x338], - "NotSquareSupersetEqual;":0x22e3, "NotSubset;":[0x2282,0x20d2], - "NotSubsetEqual;":0x2288, "NotSucceeds;":0x2281, - "NotSucceedsEqual;":[0x2ab0,0x338], "NotSucceedsSlantEqual;":0x22e1, - "NotSucceedsTilde;":[0x227f,0x338], "NotSuperset;":[0x2283,0x20d2], - "NotSupersetEqual;":0x2289, "NotTilde;":0x2241, - "NotTildeEqual;":0x2244, "NotTildeFullEqual;":0x2247, - "NotTildeTilde;":0x2249, "NotVerticalBar;":0x2224, - "Nscr;":[0xd835,0xdca9], "Ntilde":0xd1, - "Ntilde;":0xd1, "Nu;":0x39d, - "OElig;":0x152, "Oacute":0xd3, - "Oacute;":0xd3, "Ocirc":0xd4, - "Ocirc;":0xd4, "Ocy;":0x41e, - "Odblac;":0x150, "Ofr;":[0xd835,0xdd12], - "Ograve":0xd2, "Ograve;":0xd2, - "Omacr;":0x14c, "Omega;":0x3a9, - "Omicron;":0x39f, "Oopf;":[0xd835,0xdd46], - "OpenCurlyDoubleQuote;":0x201c, "OpenCurlyQuote;":0x2018, - "Or;":0x2a54, "Oscr;":[0xd835,0xdcaa], - "Oslash":0xd8, "Oslash;":0xd8, - "Otilde":0xd5, "Otilde;":0xd5, - "Otimes;":0x2a37, "Ouml":0xd6, - "Ouml;":0xd6, "OverBar;":0x203e, - "OverBrace;":0x23de, "OverBracket;":0x23b4, - "OverParenthesis;":0x23dc, "PartialD;":0x2202, - "Pcy;":0x41f, "Pfr;":[0xd835,0xdd13], - "Phi;":0x3a6, "Pi;":0x3a0, - "PlusMinus;":0xb1, "Poincareplane;":0x210c, - "Popf;":0x2119, "Pr;":0x2abb, - "Precedes;":0x227a, "PrecedesEqual;":0x2aaf, - "PrecedesSlantEqual;":0x227c, "PrecedesTilde;":0x227e, - "Prime;":0x2033, "Product;":0x220f, - "Proportion;":0x2237, "Proportional;":0x221d, - "Pscr;":[0xd835,0xdcab], "Psi;":0x3a8, - "QUOT":0x22, "QUOT;":0x22, - "Qfr;":[0xd835,0xdd14], "Qopf;":0x211a, - "Qscr;":[0xd835,0xdcac], "RBarr;":0x2910, - "REG":0xae, "REG;":0xae, - "Racute;":0x154, "Rang;":0x27eb, - "Rarr;":0x21a0, "Rarrtl;":0x2916, - "Rcaron;":0x158, "Rcedil;":0x156, - "Rcy;":0x420, "Re;":0x211c, - "ReverseElement;":0x220b, "ReverseEquilibrium;":0x21cb, - "ReverseUpEquilibrium;":0x296f, "Rfr;":0x211c, - "Rho;":0x3a1, "RightAngleBracket;":0x27e9, - "RightArrow;":0x2192, "RightArrowBar;":0x21e5, - "RightArrowLeftArrow;":0x21c4, "RightCeiling;":0x2309, - "RightDoubleBracket;":0x27e7, "RightDownTeeVector;":0x295d, - "RightDownVector;":0x21c2, "RightDownVectorBar;":0x2955, - "RightFloor;":0x230b, "RightTee;":0x22a2, - "RightTeeArrow;":0x21a6, "RightTeeVector;":0x295b, - "RightTriangle;":0x22b3, "RightTriangleBar;":0x29d0, - "RightTriangleEqual;":0x22b5, "RightUpDownVector;":0x294f, - "RightUpTeeVector;":0x295c, "RightUpVector;":0x21be, - "RightUpVectorBar;":0x2954, "RightVector;":0x21c0, - "RightVectorBar;":0x2953, "Rightarrow;":0x21d2, - "Ropf;":0x211d, "RoundImplies;":0x2970, - "Rrightarrow;":0x21db, "Rscr;":0x211b, - "Rsh;":0x21b1, "RuleDelayed;":0x29f4, - "SHCHcy;":0x429, "SHcy;":0x428, - "SOFTcy;":0x42c, "Sacute;":0x15a, - "Sc;":0x2abc, "Scaron;":0x160, - "Scedil;":0x15e, "Scirc;":0x15c, - "Scy;":0x421, "Sfr;":[0xd835,0xdd16], - "ShortDownArrow;":0x2193, "ShortLeftArrow;":0x2190, - "ShortRightArrow;":0x2192, "ShortUpArrow;":0x2191, - "Sigma;":0x3a3, "SmallCircle;":0x2218, - "Sopf;":[0xd835,0xdd4a], "Sqrt;":0x221a, - "Square;":0x25a1, "SquareIntersection;":0x2293, - "SquareSubset;":0x228f, "SquareSubsetEqual;":0x2291, - "SquareSuperset;":0x2290, "SquareSupersetEqual;":0x2292, - "SquareUnion;":0x2294, "Sscr;":[0xd835,0xdcae], - "Star;":0x22c6, "Sub;":0x22d0, - "Subset;":0x22d0, "SubsetEqual;":0x2286, - "Succeeds;":0x227b, "SucceedsEqual;":0x2ab0, - "SucceedsSlantEqual;":0x227d, "SucceedsTilde;":0x227f, - "SuchThat;":0x220b, "Sum;":0x2211, - "Sup;":0x22d1, "Superset;":0x2283, - "SupersetEqual;":0x2287, "Supset;":0x22d1, - "THORN":0xde, "THORN;":0xde, - "TRADE;":0x2122, "TSHcy;":0x40b, - "TScy;":0x426, "Tab;":0x9, - "Tau;":0x3a4, "Tcaron;":0x164, - "Tcedil;":0x162, "Tcy;":0x422, - "Tfr;":[0xd835,0xdd17], "Therefore;":0x2234, - "Theta;":0x398, "ThickSpace;":[0x205f,0x200a], - "ThinSpace;":0x2009, "Tilde;":0x223c, - "TildeEqual;":0x2243, "TildeFullEqual;":0x2245, - "TildeTilde;":0x2248, "Topf;":[0xd835,0xdd4b], - "TripleDot;":0x20db, "Tscr;":[0xd835,0xdcaf], - "Tstrok;":0x166, "Uacute":0xda, - "Uacute;":0xda, "Uarr;":0x219f, - "Uarrocir;":0x2949, "Ubrcy;":0x40e, - "Ubreve;":0x16c, "Ucirc":0xdb, - "Ucirc;":0xdb, "Ucy;":0x423, - "Udblac;":0x170, "Ufr;":[0xd835,0xdd18], - "Ugrave":0xd9, "Ugrave;":0xd9, - "Umacr;":0x16a, "UnderBar;":0x5f, - "UnderBrace;":0x23df, "UnderBracket;":0x23b5, - "UnderParenthesis;":0x23dd, "Union;":0x22c3, - "UnionPlus;":0x228e, "Uogon;":0x172, - "Uopf;":[0xd835,0xdd4c], "UpArrow;":0x2191, - "UpArrowBar;":0x2912, "UpArrowDownArrow;":0x21c5, - "UpDownArrow;":0x2195, "UpEquilibrium;":0x296e, - "UpTee;":0x22a5, "UpTeeArrow;":0x21a5, - "Uparrow;":0x21d1, "Updownarrow;":0x21d5, - "UpperLeftArrow;":0x2196, "UpperRightArrow;":0x2197, - "Upsi;":0x3d2, "Upsilon;":0x3a5, - "Uring;":0x16e, "Uscr;":[0xd835,0xdcb0], - "Utilde;":0x168, "Uuml":0xdc, - "Uuml;":0xdc, "VDash;":0x22ab, - "Vbar;":0x2aeb, "Vcy;":0x412, - "Vdash;":0x22a9, "Vdashl;":0x2ae6, - "Vee;":0x22c1, "Verbar;":0x2016, - "Vert;":0x2016, "VerticalBar;":0x2223, - "VerticalLine;":0x7c, "VerticalSeparator;":0x2758, - "VerticalTilde;":0x2240, "VeryThinSpace;":0x200a, - "Vfr;":[0xd835,0xdd19], "Vopf;":[0xd835,0xdd4d], - "Vscr;":[0xd835,0xdcb1], "Vvdash;":0x22aa, - "Wcirc;":0x174, "Wedge;":0x22c0, - "Wfr;":[0xd835,0xdd1a], "Wopf;":[0xd835,0xdd4e], - "Wscr;":[0xd835,0xdcb2], "Xfr;":[0xd835,0xdd1b], - "Xi;":0x39e, "Xopf;":[0xd835,0xdd4f], - "Xscr;":[0xd835,0xdcb3], "YAcy;":0x42f, - "YIcy;":0x407, "YUcy;":0x42e, - "Yacute":0xdd, "Yacute;":0xdd, - "Ycirc;":0x176, "Ycy;":0x42b, - "Yfr;":[0xd835,0xdd1c], "Yopf;":[0xd835,0xdd50], - "Yscr;":[0xd835,0xdcb4], "Yuml;":0x178, - "ZHcy;":0x416, "Zacute;":0x179, - "Zcaron;":0x17d, "Zcy;":0x417, - "Zdot;":0x17b, "ZeroWidthSpace;":0x200b, - "Zeta;":0x396, "Zfr;":0x2128, - "Zopf;":0x2124, "Zscr;":[0xd835,0xdcb5], - "aacute":0xe1, "aacute;":0xe1, - "abreve;":0x103, "ac;":0x223e, - "acE;":[0x223e,0x333], "acd;":0x223f, - "acirc":0xe2, "acirc;":0xe2, - "acute":0xb4, "acute;":0xb4, - "acy;":0x430, "aelig":0xe6, - "aelig;":0xe6, "af;":0x2061, - "afr;":[0xd835,0xdd1e], "agrave":0xe0, - "agrave;":0xe0, "alefsym;":0x2135, - "aleph;":0x2135, "alpha;":0x3b1, - "amacr;":0x101, "amalg;":0x2a3f, - "amp":0x26, "amp;":0x26, - "and;":0x2227, "andand;":0x2a55, - "andd;":0x2a5c, "andslope;":0x2a58, - "andv;":0x2a5a, "ang;":0x2220, - "ange;":0x29a4, "angle;":0x2220, - "angmsd;":0x2221, "angmsdaa;":0x29a8, - "angmsdab;":0x29a9, "angmsdac;":0x29aa, - "angmsdad;":0x29ab, "angmsdae;":0x29ac, - "angmsdaf;":0x29ad, "angmsdag;":0x29ae, - "angmsdah;":0x29af, "angrt;":0x221f, - "angrtvb;":0x22be, "angrtvbd;":0x299d, - "angsph;":0x2222, "angst;":0xc5, - "angzarr;":0x237c, "aogon;":0x105, - "aopf;":[0xd835,0xdd52], "ap;":0x2248, - "apE;":0x2a70, "apacir;":0x2a6f, - "ape;":0x224a, "apid;":0x224b, - "apos;":0x27, "approx;":0x2248, - "approxeq;":0x224a, "aring":0xe5, - "aring;":0xe5, "ascr;":[0xd835,0xdcb6], - "ast;":0x2a, "asymp;":0x2248, - "asympeq;":0x224d, "atilde":0xe3, - "atilde;":0xe3, "auml":0xe4, - "auml;":0xe4, "awconint;":0x2233, - "awint;":0x2a11, "bNot;":0x2aed, - "backcong;":0x224c, "backepsilon;":0x3f6, - "backprime;":0x2035, "backsim;":0x223d, - "backsimeq;":0x22cd, "barvee;":0x22bd, - "barwed;":0x2305, "barwedge;":0x2305, - "bbrk;":0x23b5, "bbrktbrk;":0x23b6, - "bcong;":0x224c, "bcy;":0x431, - "bdquo;":0x201e, "becaus;":0x2235, - "because;":0x2235, "bemptyv;":0x29b0, - "bepsi;":0x3f6, "bernou;":0x212c, - "beta;":0x3b2, "beth;":0x2136, - "between;":0x226c, "bfr;":[0xd835,0xdd1f], - "bigcap;":0x22c2, "bigcirc;":0x25ef, - "bigcup;":0x22c3, "bigodot;":0x2a00, - "bigoplus;":0x2a01, "bigotimes;":0x2a02, - "bigsqcup;":0x2a06, "bigstar;":0x2605, - "bigtriangledown;":0x25bd, "bigtriangleup;":0x25b3, - "biguplus;":0x2a04, "bigvee;":0x22c1, - "bigwedge;":0x22c0, "bkarow;":0x290d, - "blacklozenge;":0x29eb, "blacksquare;":0x25aa, - "blacktriangle;":0x25b4, "blacktriangledown;":0x25be, - "blacktriangleleft;":0x25c2, "blacktriangleright;":0x25b8, - "blank;":0x2423, "blk12;":0x2592, - "blk14;":0x2591, "blk34;":0x2593, - "block;":0x2588, "bne;":[0x3d,0x20e5], - "bnequiv;":[0x2261,0x20e5], "bnot;":0x2310, - "bopf;":[0xd835,0xdd53], "bot;":0x22a5, - "bottom;":0x22a5, "bowtie;":0x22c8, - "boxDL;":0x2557, "boxDR;":0x2554, - "boxDl;":0x2556, "boxDr;":0x2553, - "boxH;":0x2550, "boxHD;":0x2566, - "boxHU;":0x2569, "boxHd;":0x2564, - "boxHu;":0x2567, "boxUL;":0x255d, - "boxUR;":0x255a, "boxUl;":0x255c, - "boxUr;":0x2559, "boxV;":0x2551, - "boxVH;":0x256c, "boxVL;":0x2563, - "boxVR;":0x2560, "boxVh;":0x256b, - "boxVl;":0x2562, "boxVr;":0x255f, - "boxbox;":0x29c9, "boxdL;":0x2555, - "boxdR;":0x2552, "boxdl;":0x2510, - "boxdr;":0x250c, "boxh;":0x2500, - "boxhD;":0x2565, "boxhU;":0x2568, - "boxhd;":0x252c, "boxhu;":0x2534, - "boxminus;":0x229f, "boxplus;":0x229e, - "boxtimes;":0x22a0, "boxuL;":0x255b, - "boxuR;":0x2558, "boxul;":0x2518, - "boxur;":0x2514, "boxv;":0x2502, - "boxvH;":0x256a, "boxvL;":0x2561, - "boxvR;":0x255e, "boxvh;":0x253c, - "boxvl;":0x2524, "boxvr;":0x251c, - "bprime;":0x2035, "breve;":0x2d8, - "brvbar":0xa6, "brvbar;":0xa6, - "bscr;":[0xd835,0xdcb7], "bsemi;":0x204f, - "bsim;":0x223d, "bsime;":0x22cd, - "bsol;":0x5c, "bsolb;":0x29c5, - "bsolhsub;":0x27c8, "bull;":0x2022, - "bullet;":0x2022, "bump;":0x224e, - "bumpE;":0x2aae, "bumpe;":0x224f, - "bumpeq;":0x224f, "cacute;":0x107, - "cap;":0x2229, "capand;":0x2a44, - "capbrcup;":0x2a49, "capcap;":0x2a4b, - "capcup;":0x2a47, "capdot;":0x2a40, - "caps;":[0x2229,0xfe00], "caret;":0x2041, - "caron;":0x2c7, "ccaps;":0x2a4d, - "ccaron;":0x10d, "ccedil":0xe7, - "ccedil;":0xe7, "ccirc;":0x109, - "ccups;":0x2a4c, "ccupssm;":0x2a50, - "cdot;":0x10b, "cedil":0xb8, - "cedil;":0xb8, "cemptyv;":0x29b2, - "cent":0xa2, "cent;":0xa2, - "centerdot;":0xb7, "cfr;":[0xd835,0xdd20], - "chcy;":0x447, "check;":0x2713, - "checkmark;":0x2713, "chi;":0x3c7, - "cir;":0x25cb, "cirE;":0x29c3, - "circ;":0x2c6, "circeq;":0x2257, - "circlearrowleft;":0x21ba, "circlearrowright;":0x21bb, - "circledR;":0xae, "circledS;":0x24c8, - "circledast;":0x229b, "circledcirc;":0x229a, - "circleddash;":0x229d, "cire;":0x2257, - "cirfnint;":0x2a10, "cirmid;":0x2aef, - "cirscir;":0x29c2, "clubs;":0x2663, - "clubsuit;":0x2663, "colon;":0x3a, - "colone;":0x2254, "coloneq;":0x2254, - "comma;":0x2c, "commat;":0x40, - "comp;":0x2201, "compfn;":0x2218, - "complement;":0x2201, "complexes;":0x2102, - "cong;":0x2245, "congdot;":0x2a6d, - "conint;":0x222e, "copf;":[0xd835,0xdd54], - "coprod;":0x2210, "copy":0xa9, - "copy;":0xa9, "copysr;":0x2117, - "crarr;":0x21b5, "cross;":0x2717, - "cscr;":[0xd835,0xdcb8], "csub;":0x2acf, - "csube;":0x2ad1, "csup;":0x2ad0, - "csupe;":0x2ad2, "ctdot;":0x22ef, - "cudarrl;":0x2938, "cudarrr;":0x2935, - "cuepr;":0x22de, "cuesc;":0x22df, - "cularr;":0x21b6, "cularrp;":0x293d, - "cup;":0x222a, "cupbrcap;":0x2a48, - "cupcap;":0x2a46, "cupcup;":0x2a4a, - "cupdot;":0x228d, "cupor;":0x2a45, - "cups;":[0x222a,0xfe00], "curarr;":0x21b7, - "curarrm;":0x293c, "curlyeqprec;":0x22de, - "curlyeqsucc;":0x22df, "curlyvee;":0x22ce, - "curlywedge;":0x22cf, "curren":0xa4, - "curren;":0xa4, "curvearrowleft;":0x21b6, - "curvearrowright;":0x21b7, "cuvee;":0x22ce, - "cuwed;":0x22cf, "cwconint;":0x2232, - "cwint;":0x2231, "cylcty;":0x232d, - "dArr;":0x21d3, "dHar;":0x2965, - "dagger;":0x2020, "daleth;":0x2138, - "darr;":0x2193, "dash;":0x2010, - "dashv;":0x22a3, "dbkarow;":0x290f, - "dblac;":0x2dd, "dcaron;":0x10f, - "dcy;":0x434, "dd;":0x2146, - "ddagger;":0x2021, "ddarr;":0x21ca, - "ddotseq;":0x2a77, "deg":0xb0, - "deg;":0xb0, "delta;":0x3b4, - "demptyv;":0x29b1, "dfisht;":0x297f, - "dfr;":[0xd835,0xdd21], "dharl;":0x21c3, - "dharr;":0x21c2, "diam;":0x22c4, - "diamond;":0x22c4, "diamondsuit;":0x2666, - "diams;":0x2666, "die;":0xa8, - "digamma;":0x3dd, "disin;":0x22f2, - "div;":0xf7, "divide":0xf7, - "divide;":0xf7, "divideontimes;":0x22c7, - "divonx;":0x22c7, "djcy;":0x452, - "dlcorn;":0x231e, "dlcrop;":0x230d, - "dollar;":0x24, "dopf;":[0xd835,0xdd55], - "dot;":0x2d9, "doteq;":0x2250, - "doteqdot;":0x2251, "dotminus;":0x2238, - "dotplus;":0x2214, "dotsquare;":0x22a1, - "doublebarwedge;":0x2306, "downarrow;":0x2193, - "downdownarrows;":0x21ca, "downharpoonleft;":0x21c3, - "downharpoonright;":0x21c2, "drbkarow;":0x2910, - "drcorn;":0x231f, "drcrop;":0x230c, - "dscr;":[0xd835,0xdcb9], "dscy;":0x455, - "dsol;":0x29f6, "dstrok;":0x111, - "dtdot;":0x22f1, "dtri;":0x25bf, - "dtrif;":0x25be, "duarr;":0x21f5, - "duhar;":0x296f, "dwangle;":0x29a6, - "dzcy;":0x45f, "dzigrarr;":0x27ff, - "eDDot;":0x2a77, "eDot;":0x2251, - "eacute":0xe9, "eacute;":0xe9, - "easter;":0x2a6e, "ecaron;":0x11b, - "ecir;":0x2256, "ecirc":0xea, - "ecirc;":0xea, "ecolon;":0x2255, - "ecy;":0x44d, "edot;":0x117, - "ee;":0x2147, "efDot;":0x2252, - "efr;":[0xd835,0xdd22], "eg;":0x2a9a, - "egrave":0xe8, "egrave;":0xe8, - "egs;":0x2a96, "egsdot;":0x2a98, - "el;":0x2a99, "elinters;":0x23e7, - "ell;":0x2113, "els;":0x2a95, - "elsdot;":0x2a97, "emacr;":0x113, - "empty;":0x2205, "emptyset;":0x2205, - "emptyv;":0x2205, "emsp13;":0x2004, - "emsp14;":0x2005, "emsp;":0x2003, - "eng;":0x14b, "ensp;":0x2002, - "eogon;":0x119, "eopf;":[0xd835,0xdd56], - "epar;":0x22d5, "eparsl;":0x29e3, - "eplus;":0x2a71, "epsi;":0x3b5, - "epsilon;":0x3b5, "epsiv;":0x3f5, - "eqcirc;":0x2256, "eqcolon;":0x2255, - "eqsim;":0x2242, "eqslantgtr;":0x2a96, - "eqslantless;":0x2a95, "equals;":0x3d, - "equest;":0x225f, "equiv;":0x2261, - "equivDD;":0x2a78, "eqvparsl;":0x29e5, - "erDot;":0x2253, "erarr;":0x2971, - "escr;":0x212f, "esdot;":0x2250, - "esim;":0x2242, "eta;":0x3b7, - "eth":0xf0, "eth;":0xf0, - "euml":0xeb, "euml;":0xeb, - "euro;":0x20ac, "excl;":0x21, - "exist;":0x2203, "expectation;":0x2130, - "exponentiale;":0x2147, "fallingdotseq;":0x2252, - "fcy;":0x444, "female;":0x2640, - "ffilig;":0xfb03, "fflig;":0xfb00, - "ffllig;":0xfb04, "ffr;":[0xd835,0xdd23], - "filig;":0xfb01, "fjlig;":[0x66,0x6a], - "flat;":0x266d, "fllig;":0xfb02, - "fltns;":0x25b1, "fnof;":0x192, - "fopf;":[0xd835,0xdd57], "forall;":0x2200, - "fork;":0x22d4, "forkv;":0x2ad9, - "fpartint;":0x2a0d, "frac12":0xbd, - "frac12;":0xbd, "frac13;":0x2153, - "frac14":0xbc, "frac14;":0xbc, - "frac15;":0x2155, "frac16;":0x2159, - "frac18;":0x215b, "frac23;":0x2154, - "frac25;":0x2156, "frac34":0xbe, - "frac34;":0xbe, "frac35;":0x2157, - "frac38;":0x215c, "frac45;":0x2158, - "frac56;":0x215a, "frac58;":0x215d, - "frac78;":0x215e, "frasl;":0x2044, - "frown;":0x2322, "fscr;":[0xd835,0xdcbb], - "gE;":0x2267, "gEl;":0x2a8c, - "gacute;":0x1f5, "gamma;":0x3b3, - "gammad;":0x3dd, "gap;":0x2a86, - "gbreve;":0x11f, "gcirc;":0x11d, - "gcy;":0x433, "gdot;":0x121, - "ge;":0x2265, "gel;":0x22db, - "geq;":0x2265, "geqq;":0x2267, - "geqslant;":0x2a7e, "ges;":0x2a7e, - "gescc;":0x2aa9, "gesdot;":0x2a80, - "gesdoto;":0x2a82, "gesdotol;":0x2a84, - "gesl;":[0x22db,0xfe00], "gesles;":0x2a94, - "gfr;":[0xd835,0xdd24], "gg;":0x226b, - "ggg;":0x22d9, "gimel;":0x2137, - "gjcy;":0x453, "gl;":0x2277, - "glE;":0x2a92, "gla;":0x2aa5, - "glj;":0x2aa4, "gnE;":0x2269, - "gnap;":0x2a8a, "gnapprox;":0x2a8a, - "gne;":0x2a88, "gneq;":0x2a88, - "gneqq;":0x2269, "gnsim;":0x22e7, - "gopf;":[0xd835,0xdd58], "grave;":0x60, - "gscr;":0x210a, "gsim;":0x2273, - "gsime;":0x2a8e, "gsiml;":0x2a90, - "gt":0x3e, "gt;":0x3e, - "gtcc;":0x2aa7, "gtcir;":0x2a7a, - "gtdot;":0x22d7, "gtlPar;":0x2995, - "gtquest;":0x2a7c, "gtrapprox;":0x2a86, - "gtrarr;":0x2978, "gtrdot;":0x22d7, - "gtreqless;":0x22db, "gtreqqless;":0x2a8c, - "gtrless;":0x2277, "gtrsim;":0x2273, - "gvertneqq;":[0x2269,0xfe00], "gvnE;":[0x2269,0xfe00], - "hArr;":0x21d4, "hairsp;":0x200a, - "half;":0xbd, "hamilt;":0x210b, - "hardcy;":0x44a, "harr;":0x2194, - "harrcir;":0x2948, "harrw;":0x21ad, - "hbar;":0x210f, "hcirc;":0x125, - "hearts;":0x2665, "heartsuit;":0x2665, - "hellip;":0x2026, "hercon;":0x22b9, - "hfr;":[0xd835,0xdd25], "hksearow;":0x2925, - "hkswarow;":0x2926, "hoarr;":0x21ff, - "homtht;":0x223b, "hookleftarrow;":0x21a9, - "hookrightarrow;":0x21aa, "hopf;":[0xd835,0xdd59], - "horbar;":0x2015, "hscr;":[0xd835,0xdcbd], - "hslash;":0x210f, "hstrok;":0x127, - "hybull;":0x2043, "hyphen;":0x2010, - "iacute":0xed, "iacute;":0xed, - "ic;":0x2063, "icirc":0xee, - "icirc;":0xee, "icy;":0x438, - "iecy;":0x435, "iexcl":0xa1, - "iexcl;":0xa1, "iff;":0x21d4, - "ifr;":[0xd835,0xdd26], "igrave":0xec, - "igrave;":0xec, "ii;":0x2148, - "iiiint;":0x2a0c, "iiint;":0x222d, - "iinfin;":0x29dc, "iiota;":0x2129, - "ijlig;":0x133, "imacr;":0x12b, - "image;":0x2111, "imagline;":0x2110, - "imagpart;":0x2111, "imath;":0x131, - "imof;":0x22b7, "imped;":0x1b5, - "in;":0x2208, "incare;":0x2105, - "infin;":0x221e, "infintie;":0x29dd, - "inodot;":0x131, "int;":0x222b, - "intcal;":0x22ba, "integers;":0x2124, - "intercal;":0x22ba, "intlarhk;":0x2a17, - "intprod;":0x2a3c, "iocy;":0x451, - "iogon;":0x12f, "iopf;":[0xd835,0xdd5a], - "iota;":0x3b9, "iprod;":0x2a3c, - "iquest":0xbf, "iquest;":0xbf, - "iscr;":[0xd835,0xdcbe], "isin;":0x2208, - "isinE;":0x22f9, "isindot;":0x22f5, - "isins;":0x22f4, "isinsv;":0x22f3, - "isinv;":0x2208, "it;":0x2062, - "itilde;":0x129, "iukcy;":0x456, - "iuml":0xef, "iuml;":0xef, - "jcirc;":0x135, "jcy;":0x439, - "jfr;":[0xd835,0xdd27], "jmath;":0x237, - "jopf;":[0xd835,0xdd5b], "jscr;":[0xd835,0xdcbf], - "jsercy;":0x458, "jukcy;":0x454, - "kappa;":0x3ba, "kappav;":0x3f0, - "kcedil;":0x137, "kcy;":0x43a, - "kfr;":[0xd835,0xdd28], "kgreen;":0x138, - "khcy;":0x445, "kjcy;":0x45c, - "kopf;":[0xd835,0xdd5c], "kscr;":[0xd835,0xdcc0], - "lAarr;":0x21da, "lArr;":0x21d0, - "lAtail;":0x291b, "lBarr;":0x290e, - "lE;":0x2266, "lEg;":0x2a8b, - "lHar;":0x2962, "lacute;":0x13a, - "laemptyv;":0x29b4, "lagran;":0x2112, - "lambda;":0x3bb, "lang;":0x27e8, - "langd;":0x2991, "langle;":0x27e8, - "lap;":0x2a85, "laquo":0xab, - "laquo;":0xab, "larr;":0x2190, - "larrb;":0x21e4, "larrbfs;":0x291f, - "larrfs;":0x291d, "larrhk;":0x21a9, - "larrlp;":0x21ab, "larrpl;":0x2939, - "larrsim;":0x2973, "larrtl;":0x21a2, - "lat;":0x2aab, "latail;":0x2919, - "late;":0x2aad, "lates;":[0x2aad,0xfe00], - "lbarr;":0x290c, "lbbrk;":0x2772, - "lbrace;":0x7b, "lbrack;":0x5b, - "lbrke;":0x298b, "lbrksld;":0x298f, - "lbrkslu;":0x298d, "lcaron;":0x13e, - "lcedil;":0x13c, "lceil;":0x2308, - "lcub;":0x7b, "lcy;":0x43b, - "ldca;":0x2936, "ldquo;":0x201c, - "ldquor;":0x201e, "ldrdhar;":0x2967, - "ldrushar;":0x294b, "ldsh;":0x21b2, - "le;":0x2264, "leftarrow;":0x2190, - "leftarrowtail;":0x21a2, "leftharpoondown;":0x21bd, - "leftharpoonup;":0x21bc, "leftleftarrows;":0x21c7, - "leftrightarrow;":0x2194, "leftrightarrows;":0x21c6, - "leftrightharpoons;":0x21cb, "leftrightsquigarrow;":0x21ad, - "leftthreetimes;":0x22cb, "leg;":0x22da, - "leq;":0x2264, "leqq;":0x2266, - "leqslant;":0x2a7d, "les;":0x2a7d, - "lescc;":0x2aa8, "lesdot;":0x2a7f, - "lesdoto;":0x2a81, "lesdotor;":0x2a83, - "lesg;":[0x22da,0xfe00], "lesges;":0x2a93, - "lessapprox;":0x2a85, "lessdot;":0x22d6, - "lesseqgtr;":0x22da, "lesseqqgtr;":0x2a8b, - "lessgtr;":0x2276, "lesssim;":0x2272, - "lfisht;":0x297c, "lfloor;":0x230a, - "lfr;":[0xd835,0xdd29], "lg;":0x2276, - "lgE;":0x2a91, "lhard;":0x21bd, - "lharu;":0x21bc, "lharul;":0x296a, - "lhblk;":0x2584, "ljcy;":0x459, - "ll;":0x226a, "llarr;":0x21c7, - "llcorner;":0x231e, "llhard;":0x296b, - "lltri;":0x25fa, "lmidot;":0x140, - "lmoust;":0x23b0, "lmoustache;":0x23b0, - "lnE;":0x2268, "lnap;":0x2a89, - "lnapprox;":0x2a89, "lne;":0x2a87, - "lneq;":0x2a87, "lneqq;":0x2268, - "lnsim;":0x22e6, "loang;":0x27ec, - "loarr;":0x21fd, "lobrk;":0x27e6, - "longleftarrow;":0x27f5, "longleftrightarrow;":0x27f7, - "longmapsto;":0x27fc, "longrightarrow;":0x27f6, - "looparrowleft;":0x21ab, "looparrowright;":0x21ac, - "lopar;":0x2985, "lopf;":[0xd835,0xdd5d], - "loplus;":0x2a2d, "lotimes;":0x2a34, - "lowast;":0x2217, "lowbar;":0x5f, - "loz;":0x25ca, "lozenge;":0x25ca, - "lozf;":0x29eb, "lpar;":0x28, - "lparlt;":0x2993, "lrarr;":0x21c6, - "lrcorner;":0x231f, "lrhar;":0x21cb, - "lrhard;":0x296d, "lrm;":0x200e, - "lrtri;":0x22bf, "lsaquo;":0x2039, - "lscr;":[0xd835,0xdcc1], "lsh;":0x21b0, - "lsim;":0x2272, "lsime;":0x2a8d, - "lsimg;":0x2a8f, "lsqb;":0x5b, - "lsquo;":0x2018, "lsquor;":0x201a, - "lstrok;":0x142, "lt":0x3c, - "lt;":0x3c, "ltcc;":0x2aa6, - "ltcir;":0x2a79, "ltdot;":0x22d6, - "lthree;":0x22cb, "ltimes;":0x22c9, - "ltlarr;":0x2976, "ltquest;":0x2a7b, - "ltrPar;":0x2996, "ltri;":0x25c3, - "ltrie;":0x22b4, "ltrif;":0x25c2, - "lurdshar;":0x294a, "luruhar;":0x2966, - "lvertneqq;":[0x2268,0xfe00], "lvnE;":[0x2268,0xfe00], - "mDDot;":0x223a, "macr":0xaf, - "macr;":0xaf, "male;":0x2642, - "malt;":0x2720, "maltese;":0x2720, - "map;":0x21a6, "mapsto;":0x21a6, - "mapstodown;":0x21a7, "mapstoleft;":0x21a4, - "mapstoup;":0x21a5, "marker;":0x25ae, - "mcomma;":0x2a29, "mcy;":0x43c, - "mdash;":0x2014, "measuredangle;":0x2221, - "mfr;":[0xd835,0xdd2a], "mho;":0x2127, - "micro":0xb5, "micro;":0xb5, - "mid;":0x2223, "midast;":0x2a, - "midcir;":0x2af0, "middot":0xb7, - "middot;":0xb7, "minus;":0x2212, - "minusb;":0x229f, "minusd;":0x2238, - "minusdu;":0x2a2a, "mlcp;":0x2adb, - "mldr;":0x2026, "mnplus;":0x2213, - "models;":0x22a7, "mopf;":[0xd835,0xdd5e], - "mp;":0x2213, "mscr;":[0xd835,0xdcc2], - "mstpos;":0x223e, "mu;":0x3bc, - "multimap;":0x22b8, "mumap;":0x22b8, - "nGg;":[0x22d9,0x338], "nGt;":[0x226b,0x20d2], - "nGtv;":[0x226b,0x338], "nLeftarrow;":0x21cd, - "nLeftrightarrow;":0x21ce, "nLl;":[0x22d8,0x338], - "nLt;":[0x226a,0x20d2], "nLtv;":[0x226a,0x338], - "nRightarrow;":0x21cf, "nVDash;":0x22af, - "nVdash;":0x22ae, "nabla;":0x2207, - "nacute;":0x144, "nang;":[0x2220,0x20d2], - "nap;":0x2249, "napE;":[0x2a70,0x338], - "napid;":[0x224b,0x338], "napos;":0x149, - "napprox;":0x2249, "natur;":0x266e, - "natural;":0x266e, "naturals;":0x2115, - "nbsp":0xa0, "nbsp;":0xa0, - "nbump;":[0x224e,0x338], "nbumpe;":[0x224f,0x338], - "ncap;":0x2a43, "ncaron;":0x148, - "ncedil;":0x146, "ncong;":0x2247, - "ncongdot;":[0x2a6d,0x338], "ncup;":0x2a42, - "ncy;":0x43d, "ndash;":0x2013, - "ne;":0x2260, "neArr;":0x21d7, - "nearhk;":0x2924, "nearr;":0x2197, - "nearrow;":0x2197, "nedot;":[0x2250,0x338], - "nequiv;":0x2262, "nesear;":0x2928, - "nesim;":[0x2242,0x338], "nexist;":0x2204, - "nexists;":0x2204, "nfr;":[0xd835,0xdd2b], - "ngE;":[0x2267,0x338], "nge;":0x2271, - "ngeq;":0x2271, "ngeqq;":[0x2267,0x338], - "ngeqslant;":[0x2a7e,0x338], "nges;":[0x2a7e,0x338], - "ngsim;":0x2275, "ngt;":0x226f, - "ngtr;":0x226f, "nhArr;":0x21ce, - "nharr;":0x21ae, "nhpar;":0x2af2, - "ni;":0x220b, "nis;":0x22fc, - "nisd;":0x22fa, "niv;":0x220b, - "njcy;":0x45a, "nlArr;":0x21cd, - "nlE;":[0x2266,0x338], "nlarr;":0x219a, - "nldr;":0x2025, "nle;":0x2270, - "nleftarrow;":0x219a, "nleftrightarrow;":0x21ae, - "nleq;":0x2270, "nleqq;":[0x2266,0x338], - "nleqslant;":[0x2a7d,0x338], "nles;":[0x2a7d,0x338], - "nless;":0x226e, "nlsim;":0x2274, - "nlt;":0x226e, "nltri;":0x22ea, - "nltrie;":0x22ec, "nmid;":0x2224, - "nopf;":[0xd835,0xdd5f], "not":0xac, - "not;":0xac, "notin;":0x2209, - "notinE;":[0x22f9,0x338], "notindot;":[0x22f5,0x338], - "notinva;":0x2209, "notinvb;":0x22f7, - "notinvc;":0x22f6, "notni;":0x220c, - "notniva;":0x220c, "notnivb;":0x22fe, - "notnivc;":0x22fd, "npar;":0x2226, - "nparallel;":0x2226, "nparsl;":[0x2afd,0x20e5], - "npart;":[0x2202,0x338], "npolint;":0x2a14, - "npr;":0x2280, "nprcue;":0x22e0, - "npre;":[0x2aaf,0x338], "nprec;":0x2280, - "npreceq;":[0x2aaf,0x338], "nrArr;":0x21cf, - "nrarr;":0x219b, "nrarrc;":[0x2933,0x338], - "nrarrw;":[0x219d,0x338], "nrightarrow;":0x219b, - "nrtri;":0x22eb, "nrtrie;":0x22ed, - "nsc;":0x2281, "nsccue;":0x22e1, - "nsce;":[0x2ab0,0x338], "nscr;":[0xd835,0xdcc3], - "nshortmid;":0x2224, "nshortparallel;":0x2226, - "nsim;":0x2241, "nsime;":0x2244, - "nsimeq;":0x2244, "nsmid;":0x2224, - "nspar;":0x2226, "nsqsube;":0x22e2, - "nsqsupe;":0x22e3, "nsub;":0x2284, - "nsubE;":[0x2ac5,0x338], "nsube;":0x2288, - "nsubset;":[0x2282,0x20d2], "nsubseteq;":0x2288, - "nsubseteqq;":[0x2ac5,0x338], "nsucc;":0x2281, - "nsucceq;":[0x2ab0,0x338], "nsup;":0x2285, - "nsupE;":[0x2ac6,0x338], "nsupe;":0x2289, - "nsupset;":[0x2283,0x20d2], "nsupseteq;":0x2289, - "nsupseteqq;":[0x2ac6,0x338], "ntgl;":0x2279, - "ntilde":0xf1, "ntilde;":0xf1, - "ntlg;":0x2278, "ntriangleleft;":0x22ea, - "ntrianglelefteq;":0x22ec, "ntriangleright;":0x22eb, - "ntrianglerighteq;":0x22ed, "nu;":0x3bd, - "num;":0x23, "numero;":0x2116, - "numsp;":0x2007, "nvDash;":0x22ad, - "nvHarr;":0x2904, "nvap;":[0x224d,0x20d2], - "nvdash;":0x22ac, "nvge;":[0x2265,0x20d2], - "nvgt;":[0x3e,0x20d2], "nvinfin;":0x29de, - "nvlArr;":0x2902, "nvle;":[0x2264,0x20d2], - "nvlt;":[0x3c,0x20d2], "nvltrie;":[0x22b4,0x20d2], - "nvrArr;":0x2903, "nvrtrie;":[0x22b5,0x20d2], - "nvsim;":[0x223c,0x20d2], "nwArr;":0x21d6, - "nwarhk;":0x2923, "nwarr;":0x2196, - "nwarrow;":0x2196, "nwnear;":0x2927, - "oS;":0x24c8, "oacute":0xf3, - "oacute;":0xf3, "oast;":0x229b, - "ocir;":0x229a, "ocirc":0xf4, - "ocirc;":0xf4, "ocy;":0x43e, - "odash;":0x229d, "odblac;":0x151, - "odiv;":0x2a38, "odot;":0x2299, - "odsold;":0x29bc, "oelig;":0x153, - "ofcir;":0x29bf, "ofr;":[0xd835,0xdd2c], - "ogon;":0x2db, "ograve":0xf2, - "ograve;":0xf2, "ogt;":0x29c1, - "ohbar;":0x29b5, "ohm;":0x3a9, - "oint;":0x222e, "olarr;":0x21ba, - "olcir;":0x29be, "olcross;":0x29bb, - "oline;":0x203e, "olt;":0x29c0, - "omacr;":0x14d, "omega;":0x3c9, - "omicron;":0x3bf, "omid;":0x29b6, - "ominus;":0x2296, "oopf;":[0xd835,0xdd60], - "opar;":0x29b7, "operp;":0x29b9, - "oplus;":0x2295, "or;":0x2228, - "orarr;":0x21bb, "ord;":0x2a5d, - "order;":0x2134, "orderof;":0x2134, - "ordf":0xaa, "ordf;":0xaa, - "ordm":0xba, "ordm;":0xba, - "origof;":0x22b6, "oror;":0x2a56, - "orslope;":0x2a57, "orv;":0x2a5b, - "oscr;":0x2134, "oslash":0xf8, - "oslash;":0xf8, "osol;":0x2298, - "otilde":0xf5, "otilde;":0xf5, - "otimes;":0x2297, "otimesas;":0x2a36, - "ouml":0xf6, "ouml;":0xf6, - "ovbar;":0x233d, "par;":0x2225, - "para":0xb6, "para;":0xb6, - "parallel;":0x2225, "parsim;":0x2af3, - "parsl;":0x2afd, "part;":0x2202, - "pcy;":0x43f, "percnt;":0x25, - "period;":0x2e, "permil;":0x2030, - "perp;":0x22a5, "pertenk;":0x2031, - "pfr;":[0xd835,0xdd2d], "phi;":0x3c6, - "phiv;":0x3d5, "phmmat;":0x2133, - "phone;":0x260e, "pi;":0x3c0, - "pitchfork;":0x22d4, "piv;":0x3d6, - "planck;":0x210f, "planckh;":0x210e, - "plankv;":0x210f, "plus;":0x2b, - "plusacir;":0x2a23, "plusb;":0x229e, - "pluscir;":0x2a22, "plusdo;":0x2214, - "plusdu;":0x2a25, "pluse;":0x2a72, - "plusmn":0xb1, "plusmn;":0xb1, - "plussim;":0x2a26, "plustwo;":0x2a27, - "pm;":0xb1, "pointint;":0x2a15, - "popf;":[0xd835,0xdd61], "pound":0xa3, - "pound;":0xa3, "pr;":0x227a, - "prE;":0x2ab3, "prap;":0x2ab7, - "prcue;":0x227c, "pre;":0x2aaf, - "prec;":0x227a, "precapprox;":0x2ab7, - "preccurlyeq;":0x227c, "preceq;":0x2aaf, - "precnapprox;":0x2ab9, "precneqq;":0x2ab5, - "precnsim;":0x22e8, "precsim;":0x227e, - "prime;":0x2032, "primes;":0x2119, - "prnE;":0x2ab5, "prnap;":0x2ab9, - "prnsim;":0x22e8, "prod;":0x220f, - "profalar;":0x232e, "profline;":0x2312, - "profsurf;":0x2313, "prop;":0x221d, - "propto;":0x221d, "prsim;":0x227e, - "prurel;":0x22b0, "pscr;":[0xd835,0xdcc5], - "psi;":0x3c8, "puncsp;":0x2008, - "qfr;":[0xd835,0xdd2e], "qint;":0x2a0c, - "qopf;":[0xd835,0xdd62], "qprime;":0x2057, - "qscr;":[0xd835,0xdcc6], "quaternions;":0x210d, - "quatint;":0x2a16, "quest;":0x3f, - "questeq;":0x225f, "quot":0x22, - "quot;":0x22, "rAarr;":0x21db, - "rArr;":0x21d2, "rAtail;":0x291c, - "rBarr;":0x290f, "rHar;":0x2964, - "race;":[0x223d,0x331], "racute;":0x155, - "radic;":0x221a, "raemptyv;":0x29b3, - "rang;":0x27e9, "rangd;":0x2992, - "range;":0x29a5, "rangle;":0x27e9, - "raquo":0xbb, "raquo;":0xbb, - "rarr;":0x2192, "rarrap;":0x2975, - "rarrb;":0x21e5, "rarrbfs;":0x2920, - "rarrc;":0x2933, "rarrfs;":0x291e, - "rarrhk;":0x21aa, "rarrlp;":0x21ac, - "rarrpl;":0x2945, "rarrsim;":0x2974, - "rarrtl;":0x21a3, "rarrw;":0x219d, - "ratail;":0x291a, "ratio;":0x2236, - "rationals;":0x211a, "rbarr;":0x290d, - "rbbrk;":0x2773, "rbrace;":0x7d, - "rbrack;":0x5d, "rbrke;":0x298c, - "rbrksld;":0x298e, "rbrkslu;":0x2990, - "rcaron;":0x159, "rcedil;":0x157, - "rceil;":0x2309, "rcub;":0x7d, - "rcy;":0x440, "rdca;":0x2937, - "rdldhar;":0x2969, "rdquo;":0x201d, - "rdquor;":0x201d, "rdsh;":0x21b3, - "real;":0x211c, "realine;":0x211b, - "realpart;":0x211c, "reals;":0x211d, - "rect;":0x25ad, "reg":0xae, - "reg;":0xae, "rfisht;":0x297d, - "rfloor;":0x230b, "rfr;":[0xd835,0xdd2f], - "rhard;":0x21c1, "rharu;":0x21c0, - "rharul;":0x296c, "rho;":0x3c1, - "rhov;":0x3f1, "rightarrow;":0x2192, - "rightarrowtail;":0x21a3, "rightharpoondown;":0x21c1, - "rightharpoonup;":0x21c0, "rightleftarrows;":0x21c4, - "rightleftharpoons;":0x21cc, "rightrightarrows;":0x21c9, - "rightsquigarrow;":0x219d, "rightthreetimes;":0x22cc, - "ring;":0x2da, "risingdotseq;":0x2253, - "rlarr;":0x21c4, "rlhar;":0x21cc, - "rlm;":0x200f, "rmoust;":0x23b1, - "rmoustache;":0x23b1, "rnmid;":0x2aee, - "roang;":0x27ed, "roarr;":0x21fe, - "robrk;":0x27e7, "ropar;":0x2986, - "ropf;":[0xd835,0xdd63], "roplus;":0x2a2e, - "rotimes;":0x2a35, "rpar;":0x29, - "rpargt;":0x2994, "rppolint;":0x2a12, - "rrarr;":0x21c9, "rsaquo;":0x203a, - "rscr;":[0xd835,0xdcc7], "rsh;":0x21b1, - "rsqb;":0x5d, "rsquo;":0x2019, - "rsquor;":0x2019, "rthree;":0x22cc, - "rtimes;":0x22ca, "rtri;":0x25b9, - "rtrie;":0x22b5, "rtrif;":0x25b8, - "rtriltri;":0x29ce, "ruluhar;":0x2968, - "rx;":0x211e, "sacute;":0x15b, - "sbquo;":0x201a, "sc;":0x227b, - "scE;":0x2ab4, "scap;":0x2ab8, - "scaron;":0x161, "sccue;":0x227d, - "sce;":0x2ab0, "scedil;":0x15f, - "scirc;":0x15d, "scnE;":0x2ab6, - "scnap;":0x2aba, "scnsim;":0x22e9, - "scpolint;":0x2a13, "scsim;":0x227f, - "scy;":0x441, "sdot;":0x22c5, - "sdotb;":0x22a1, "sdote;":0x2a66, - "seArr;":0x21d8, "searhk;":0x2925, - "searr;":0x2198, "searrow;":0x2198, - "sect":0xa7, "sect;":0xa7, - "semi;":0x3b, "seswar;":0x2929, - "setminus;":0x2216, "setmn;":0x2216, - "sext;":0x2736, "sfr;":[0xd835,0xdd30], - "sfrown;":0x2322, "sharp;":0x266f, - "shchcy;":0x449, "shcy;":0x448, - "shortmid;":0x2223, "shortparallel;":0x2225, - "shy":0xad, "shy;":0xad, - "sigma;":0x3c3, "sigmaf;":0x3c2, - "sigmav;":0x3c2, "sim;":0x223c, - "simdot;":0x2a6a, "sime;":0x2243, - "simeq;":0x2243, "simg;":0x2a9e, - "simgE;":0x2aa0, "siml;":0x2a9d, - "simlE;":0x2a9f, "simne;":0x2246, - "simplus;":0x2a24, "simrarr;":0x2972, - "slarr;":0x2190, "smallsetminus;":0x2216, - "smashp;":0x2a33, "smeparsl;":0x29e4, - "smid;":0x2223, "smile;":0x2323, - "smt;":0x2aaa, "smte;":0x2aac, - "smtes;":[0x2aac,0xfe00], "softcy;":0x44c, - "sol;":0x2f, "solb;":0x29c4, - "solbar;":0x233f, "sopf;":[0xd835,0xdd64], - "spades;":0x2660, "spadesuit;":0x2660, - "spar;":0x2225, "sqcap;":0x2293, - "sqcaps;":[0x2293,0xfe00], "sqcup;":0x2294, - "sqcups;":[0x2294,0xfe00], "sqsub;":0x228f, - "sqsube;":0x2291, "sqsubset;":0x228f, - "sqsubseteq;":0x2291, "sqsup;":0x2290, - "sqsupe;":0x2292, "sqsupset;":0x2290, - "sqsupseteq;":0x2292, "squ;":0x25a1, - "square;":0x25a1, "squarf;":0x25aa, - "squf;":0x25aa, "srarr;":0x2192, - "sscr;":[0xd835,0xdcc8], "ssetmn;":0x2216, - "ssmile;":0x2323, "sstarf;":0x22c6, - "star;":0x2606, "starf;":0x2605, - "straightepsilon;":0x3f5, "straightphi;":0x3d5, - "strns;":0xaf, "sub;":0x2282, - "subE;":0x2ac5, "subdot;":0x2abd, - "sube;":0x2286, "subedot;":0x2ac3, - "submult;":0x2ac1, "subnE;":0x2acb, - "subne;":0x228a, "subplus;":0x2abf, - "subrarr;":0x2979, "subset;":0x2282, - "subseteq;":0x2286, "subseteqq;":0x2ac5, - "subsetneq;":0x228a, "subsetneqq;":0x2acb, - "subsim;":0x2ac7, "subsub;":0x2ad5, - "subsup;":0x2ad3, "succ;":0x227b, - "succapprox;":0x2ab8, "succcurlyeq;":0x227d, - "succeq;":0x2ab0, "succnapprox;":0x2aba, - "succneqq;":0x2ab6, "succnsim;":0x22e9, - "succsim;":0x227f, "sum;":0x2211, - "sung;":0x266a, "sup1":0xb9, - "sup1;":0xb9, "sup2":0xb2, - "sup2;":0xb2, "sup3":0xb3, - "sup3;":0xb3, "sup;":0x2283, - "supE;":0x2ac6, "supdot;":0x2abe, - "supdsub;":0x2ad8, "supe;":0x2287, - "supedot;":0x2ac4, "suphsol;":0x27c9, - "suphsub;":0x2ad7, "suplarr;":0x297b, - "supmult;":0x2ac2, "supnE;":0x2acc, - "supne;":0x228b, "supplus;":0x2ac0, - "supset;":0x2283, "supseteq;":0x2287, - "supseteqq;":0x2ac6, "supsetneq;":0x228b, - "supsetneqq;":0x2acc, "supsim;":0x2ac8, - "supsub;":0x2ad4, "supsup;":0x2ad6, - "swArr;":0x21d9, "swarhk;":0x2926, - "swarr;":0x2199, "swarrow;":0x2199, - "swnwar;":0x292a, "szlig":0xdf, - "szlig;":0xdf, "target;":0x2316, - "tau;":0x3c4, "tbrk;":0x23b4, - "tcaron;":0x165, "tcedil;":0x163, - "tcy;":0x442, "tdot;":0x20db, - "telrec;":0x2315, "tfr;":[0xd835,0xdd31], - "there4;":0x2234, "therefore;":0x2234, - "theta;":0x3b8, "thetasym;":0x3d1, - "thetav;":0x3d1, "thickapprox;":0x2248, - "thicksim;":0x223c, "thinsp;":0x2009, - "thkap;":0x2248, "thksim;":0x223c, - "thorn":0xfe, "thorn;":0xfe, - "tilde;":0x2dc, "times":0xd7, - "times;":0xd7, "timesb;":0x22a0, - "timesbar;":0x2a31, "timesd;":0x2a30, - "tint;":0x222d, "toea;":0x2928, - "top;":0x22a4, "topbot;":0x2336, - "topcir;":0x2af1, "topf;":[0xd835,0xdd65], - "topfork;":0x2ada, "tosa;":0x2929, - "tprime;":0x2034, "trade;":0x2122, - "triangle;":0x25b5, "triangledown;":0x25bf, - "triangleleft;":0x25c3, "trianglelefteq;":0x22b4, - "triangleq;":0x225c, "triangleright;":0x25b9, - "trianglerighteq;":0x22b5, "tridot;":0x25ec, - "trie;":0x225c, "triminus;":0x2a3a, - "triplus;":0x2a39, "trisb;":0x29cd, - "tritime;":0x2a3b, "trpezium;":0x23e2, - "tscr;":[0xd835,0xdcc9], "tscy;":0x446, - "tshcy;":0x45b, "tstrok;":0x167, - "twixt;":0x226c, "twoheadleftarrow;":0x219e, - "twoheadrightarrow;":0x21a0, "uArr;":0x21d1, - "uHar;":0x2963, "uacute":0xfa, - "uacute;":0xfa, "uarr;":0x2191, - "ubrcy;":0x45e, "ubreve;":0x16d, - "ucirc":0xfb, "ucirc;":0xfb, - "ucy;":0x443, "udarr;":0x21c5, - "udblac;":0x171, "udhar;":0x296e, - "ufisht;":0x297e, "ufr;":[0xd835,0xdd32], - "ugrave":0xf9, "ugrave;":0xf9, - "uharl;":0x21bf, "uharr;":0x21be, - "uhblk;":0x2580, "ulcorn;":0x231c, - "ulcorner;":0x231c, "ulcrop;":0x230f, - "ultri;":0x25f8, "umacr;":0x16b, - "uml":0xa8, "uml;":0xa8, - "uogon;":0x173, "uopf;":[0xd835,0xdd66], - "uparrow;":0x2191, "updownarrow;":0x2195, - "upharpoonleft;":0x21bf, "upharpoonright;":0x21be, - "uplus;":0x228e, "upsi;":0x3c5, - "upsih;":0x3d2, "upsilon;":0x3c5, - "upuparrows;":0x21c8, "urcorn;":0x231d, - "urcorner;":0x231d, "urcrop;":0x230e, - "uring;":0x16f, "urtri;":0x25f9, - "uscr;":[0xd835,0xdcca], "utdot;":0x22f0, - "utilde;":0x169, "utri;":0x25b5, - "utrif;":0x25b4, "uuarr;":0x21c8, - "uuml":0xfc, "uuml;":0xfc, - "uwangle;":0x29a7, "vArr;":0x21d5, - "vBar;":0x2ae8, "vBarv;":0x2ae9, - "vDash;":0x22a8, "vangrt;":0x299c, - "varepsilon;":0x3f5, "varkappa;":0x3f0, - "varnothing;":0x2205, "varphi;":0x3d5, - "varpi;":0x3d6, "varpropto;":0x221d, - "varr;":0x2195, "varrho;":0x3f1, - "varsigma;":0x3c2, "varsubsetneq;":[0x228a,0xfe00], - "varsubsetneqq;":[0x2acb,0xfe00], "varsupsetneq;":[0x228b,0xfe00], - "varsupsetneqq;":[0x2acc,0xfe00], "vartheta;":0x3d1, - "vartriangleleft;":0x22b2, "vartriangleright;":0x22b3, - "vcy;":0x432, "vdash;":0x22a2, - "vee;":0x2228, "veebar;":0x22bb, - "veeeq;":0x225a, "vellip;":0x22ee, - "verbar;":0x7c, "vert;":0x7c, - "vfr;":[0xd835,0xdd33], "vltri;":0x22b2, - "vnsub;":[0x2282,0x20d2], "vnsup;":[0x2283,0x20d2], - "vopf;":[0xd835,0xdd67], "vprop;":0x221d, - "vrtri;":0x22b3, "vscr;":[0xd835,0xdccb], - "vsubnE;":[0x2acb,0xfe00], "vsubne;":[0x228a,0xfe00], - "vsupnE;":[0x2acc,0xfe00], "vsupne;":[0x228b,0xfe00], - "vzigzag;":0x299a, "wcirc;":0x175, - "wedbar;":0x2a5f, "wedge;":0x2227, - "wedgeq;":0x2259, "weierp;":0x2118, - "wfr;":[0xd835,0xdd34], "wopf;":[0xd835,0xdd68], - "wp;":0x2118, "wr;":0x2240, - "wreath;":0x2240, "wscr;":[0xd835,0xdccc], - "xcap;":0x22c2, "xcirc;":0x25ef, - "xcup;":0x22c3, "xdtri;":0x25bd, - "xfr;":[0xd835,0xdd35], "xhArr;":0x27fa, - "xharr;":0x27f7, "xi;":0x3be, - "xlArr;":0x27f8, "xlarr;":0x27f5, - "xmap;":0x27fc, "xnis;":0x22fb, - "xodot;":0x2a00, "xopf;":[0xd835,0xdd69], - "xoplus;":0x2a01, "xotime;":0x2a02, - "xrArr;":0x27f9, "xrarr;":0x27f6, - "xscr;":[0xd835,0xdccd], "xsqcup;":0x2a06, - "xuplus;":0x2a04, "xutri;":0x25b3, - "xvee;":0x22c1, "xwedge;":0x22c0, - "yacute":0xfd, "yacute;":0xfd, - "yacy;":0x44f, "ycirc;":0x177, - "ycy;":0x44b, "yen":0xa5, - "yen;":0xa5, "yfr;":[0xd835,0xdd36], - "yicy;":0x457, "yopf;":[0xd835,0xdd6a], - "yscr;":[0xd835,0xdcce], "yucy;":0x44e, - "yuml":0xff, "yuml;":0xff, - "zacute;":0x17a, "zcaron;":0x17e, - "zcy;":0x437, "zdot;":0x17c, - "zeetrf;":0x2128, "zeta;":0x3b6, - "zfr;":[0xd835,0xdd37], "zhcy;":0x436, - "zigrarr;":0x21dd, "zopf;":[0xd835,0xdd6b], - "zscr;":[0xd835,0xdccf], "zwj;":0x200d, - "zwnj;":0x200c, -}; -/* - * This regexp is generated with test/tools/update-entities.js - * It will always match at least one character -- but note that there - * are no entities whose names are a single character long. - */ -var NAMEDCHARREF = /(A(?:Elig;?|MP;?|acute;?|breve;|c(?:irc;?|y;)|fr;|grave;?|lpha;|macr;|nd;|o(?:gon;|pf;)|pplyFunction;|ring;?|s(?:cr;|sign;)|tilde;?|uml;?)|B(?:a(?:ckslash;|r(?:v;|wed;))|cy;|e(?:cause;|rnoullis;|ta;)|fr;|opf;|reve;|scr;|umpeq;)|C(?:Hcy;|OPY;?|a(?:cute;|p(?:;|italDifferentialD;)|yleys;)|c(?:aron;|edil;?|irc;|onint;)|dot;|e(?:dilla;|nterDot;)|fr;|hi;|ircle(?:Dot;|Minus;|Plus;|Times;)|lo(?:ckwiseContourIntegral;|seCurly(?:DoubleQuote;|Quote;))|o(?:lon(?:;|e;)|n(?:gruent;|int;|tourIntegral;)|p(?:f;|roduct;)|unterClockwiseContourIntegral;)|ross;|scr;|up(?:;|Cap;))|D(?:D(?:;|otrahd;)|Jcy;|Scy;|Zcy;|a(?:gger;|rr;|shv;)|c(?:aron;|y;)|el(?:;|ta;)|fr;|i(?:a(?:critical(?:Acute;|Do(?:t;|ubleAcute;)|Grave;|Tilde;)|mond;)|fferentialD;)|o(?:pf;|t(?:;|Dot;|Equal;)|uble(?:ContourIntegral;|Do(?:t;|wnArrow;)|L(?:eft(?:Arrow;|RightArrow;|Tee;)|ong(?:Left(?:Arrow;|RightArrow;)|RightArrow;))|Right(?:Arrow;|Tee;)|Up(?:Arrow;|DownArrow;)|VerticalBar;)|wn(?:Arrow(?:;|Bar;|UpArrow;)|Breve;|Left(?:RightVector;|TeeVector;|Vector(?:;|Bar;))|Right(?:TeeVector;|Vector(?:;|Bar;))|Tee(?:;|Arrow;)|arrow;))|s(?:cr;|trok;))|E(?:NG;|TH;?|acute;?|c(?:aron;|irc;?|y;)|dot;|fr;|grave;?|lement;|m(?:acr;|pty(?:SmallSquare;|VerySmallSquare;))|o(?:gon;|pf;)|psilon;|qu(?:al(?:;|Tilde;)|ilibrium;)|s(?:cr;|im;)|ta;|uml;?|x(?:ists;|ponentialE;))|F(?:cy;|fr;|illed(?:SmallSquare;|VerySmallSquare;)|o(?:pf;|rAll;|uriertrf;)|scr;)|G(?:Jcy;|T;?|amma(?:;|d;)|breve;|c(?:edil;|irc;|y;)|dot;|fr;|g;|opf;|reater(?:Equal(?:;|Less;)|FullEqual;|Greater;|Less;|SlantEqual;|Tilde;)|scr;|t;)|H(?:ARDcy;|a(?:cek;|t;)|circ;|fr;|ilbertSpace;|o(?:pf;|rizontalLine;)|s(?:cr;|trok;)|ump(?:DownHump;|Equal;))|I(?:Ecy;|Jlig;|Ocy;|acute;?|c(?:irc;?|y;)|dot;|fr;|grave;?|m(?:;|a(?:cr;|ginaryI;)|plies;)|n(?:t(?:;|e(?:gral;|rsection;))|visible(?:Comma;|Times;))|o(?:gon;|pf;|ta;)|scr;|tilde;|u(?:kcy;|ml;?))|J(?:c(?:irc;|y;)|fr;|opf;|s(?:cr;|ercy;)|ukcy;)|K(?:Hcy;|Jcy;|appa;|c(?:edil;|y;)|fr;|opf;|scr;)|L(?:Jcy;|T;?|a(?:cute;|mbda;|ng;|placetrf;|rr;)|c(?:aron;|edil;|y;)|e(?:ft(?:A(?:ngleBracket;|rrow(?:;|Bar;|RightArrow;))|Ceiling;|Do(?:ubleBracket;|wn(?:TeeVector;|Vector(?:;|Bar;)))|Floor;|Right(?:Arrow;|Vector;)|T(?:ee(?:;|Arrow;|Vector;)|riangle(?:;|Bar;|Equal;))|Up(?:DownVector;|TeeVector;|Vector(?:;|Bar;))|Vector(?:;|Bar;)|arrow;|rightarrow;)|ss(?:EqualGreater;|FullEqual;|Greater;|Less;|SlantEqual;|Tilde;))|fr;|l(?:;|eftarrow;)|midot;|o(?:ng(?:Left(?:Arrow;|RightArrow;)|RightArrow;|left(?:arrow;|rightarrow;)|rightarrow;)|pf;|wer(?:LeftArrow;|RightArrow;))|s(?:cr;|h;|trok;)|t;)|M(?:ap;|cy;|e(?:diumSpace;|llintrf;)|fr;|inusPlus;|opf;|scr;|u;)|N(?:Jcy;|acute;|c(?:aron;|edil;|y;)|e(?:gative(?:MediumSpace;|Thi(?:ckSpace;|nSpace;)|VeryThinSpace;)|sted(?:GreaterGreater;|LessLess;)|wLine;)|fr;|o(?:Break;|nBreakingSpace;|pf;|t(?:;|C(?:ongruent;|upCap;)|DoubleVerticalBar;|E(?:lement;|qual(?:;|Tilde;)|xists;)|Greater(?:;|Equal;|FullEqual;|Greater;|Less;|SlantEqual;|Tilde;)|Hump(?:DownHump;|Equal;)|Le(?:ftTriangle(?:;|Bar;|Equal;)|ss(?:;|Equal;|Greater;|Less;|SlantEqual;|Tilde;))|Nested(?:GreaterGreater;|LessLess;)|Precedes(?:;|Equal;|SlantEqual;)|R(?:everseElement;|ightTriangle(?:;|Bar;|Equal;))|S(?:quareSu(?:bset(?:;|Equal;)|perset(?:;|Equal;))|u(?:bset(?:;|Equal;)|cceeds(?:;|Equal;|SlantEqual;|Tilde;)|perset(?:;|Equal;)))|Tilde(?:;|Equal;|FullEqual;|Tilde;)|VerticalBar;))|scr;|tilde;?|u;)|O(?:Elig;|acute;?|c(?:irc;?|y;)|dblac;|fr;|grave;?|m(?:acr;|ega;|icron;)|opf;|penCurly(?:DoubleQuote;|Quote;)|r;|s(?:cr;|lash;?)|ti(?:lde;?|mes;)|uml;?|ver(?:B(?:ar;|rac(?:e;|ket;))|Parenthesis;))|P(?:artialD;|cy;|fr;|hi;|i;|lusMinus;|o(?:incareplane;|pf;)|r(?:;|ecedes(?:;|Equal;|SlantEqual;|Tilde;)|ime;|o(?:duct;|portion(?:;|al;)))|s(?:cr;|i;))|Q(?:UOT;?|fr;|opf;|scr;)|R(?:Barr;|EG;?|a(?:cute;|ng;|rr(?:;|tl;))|c(?:aron;|edil;|y;)|e(?:;|verse(?:E(?:lement;|quilibrium;)|UpEquilibrium;))|fr;|ho;|ight(?:A(?:ngleBracket;|rrow(?:;|Bar;|LeftArrow;))|Ceiling;|Do(?:ubleBracket;|wn(?:TeeVector;|Vector(?:;|Bar;)))|Floor;|T(?:ee(?:;|Arrow;|Vector;)|riangle(?:;|Bar;|Equal;))|Up(?:DownVector;|TeeVector;|Vector(?:;|Bar;))|Vector(?:;|Bar;)|arrow;)|o(?:pf;|undImplies;)|rightarrow;|s(?:cr;|h;)|uleDelayed;)|S(?:H(?:CHcy;|cy;)|OFTcy;|acute;|c(?:;|aron;|edil;|irc;|y;)|fr;|hort(?:DownArrow;|LeftArrow;|RightArrow;|UpArrow;)|igma;|mallCircle;|opf;|q(?:rt;|uare(?:;|Intersection;|Su(?:bset(?:;|Equal;)|perset(?:;|Equal;))|Union;))|scr;|tar;|u(?:b(?:;|set(?:;|Equal;))|c(?:ceeds(?:;|Equal;|SlantEqual;|Tilde;)|hThat;)|m;|p(?:;|erset(?:;|Equal;)|set;)))|T(?:HORN;?|RADE;|S(?:Hcy;|cy;)|a(?:b;|u;)|c(?:aron;|edil;|y;)|fr;|h(?:e(?:refore;|ta;)|i(?:ckSpace;|nSpace;))|ilde(?:;|Equal;|FullEqual;|Tilde;)|opf;|ripleDot;|s(?:cr;|trok;))|U(?:a(?:cute;?|rr(?:;|ocir;))|br(?:cy;|eve;)|c(?:irc;?|y;)|dblac;|fr;|grave;?|macr;|n(?:der(?:B(?:ar;|rac(?:e;|ket;))|Parenthesis;)|ion(?:;|Plus;))|o(?:gon;|pf;)|p(?:Arrow(?:;|Bar;|DownArrow;)|DownArrow;|Equilibrium;|Tee(?:;|Arrow;)|arrow;|downarrow;|per(?:LeftArrow;|RightArrow;)|si(?:;|lon;))|ring;|scr;|tilde;|uml;?)|V(?:Dash;|bar;|cy;|dash(?:;|l;)|e(?:e;|r(?:bar;|t(?:;|ical(?:Bar;|Line;|Separator;|Tilde;))|yThinSpace;))|fr;|opf;|scr;|vdash;)|W(?:circ;|edge;|fr;|opf;|scr;)|X(?:fr;|i;|opf;|scr;)|Y(?:Acy;|Icy;|Ucy;|acute;?|c(?:irc;|y;)|fr;|opf;|scr;|uml;)|Z(?:Hcy;|acute;|c(?:aron;|y;)|dot;|e(?:roWidthSpace;|ta;)|fr;|opf;|scr;)|a(?:acute;?|breve;|c(?:;|E;|d;|irc;?|ute;?|y;)|elig;?|f(?:;|r;)|grave;?|l(?:e(?:fsym;|ph;)|pha;)|m(?:a(?:cr;|lg;)|p;?)|n(?:d(?:;|and;|d;|slope;|v;)|g(?:;|e;|le;|msd(?:;|a(?:a;|b;|c;|d;|e;|f;|g;|h;))|rt(?:;|vb(?:;|d;))|s(?:ph;|t;)|zarr;))|o(?:gon;|pf;)|p(?:;|E;|acir;|e;|id;|os;|prox(?:;|eq;))|ring;?|s(?:cr;|t;|ymp(?:;|eq;))|tilde;?|uml;?|w(?:conint;|int;))|b(?:Not;|a(?:ck(?:cong;|epsilon;|prime;|sim(?:;|eq;))|r(?:vee;|wed(?:;|ge;)))|brk(?:;|tbrk;)|c(?:ong;|y;)|dquo;|e(?:caus(?:;|e;)|mptyv;|psi;|rnou;|t(?:a;|h;|ween;))|fr;|ig(?:c(?:ap;|irc;|up;)|o(?:dot;|plus;|times;)|s(?:qcup;|tar;)|triangle(?:down;|up;)|uplus;|vee;|wedge;)|karow;|l(?:a(?:ck(?:lozenge;|square;|triangle(?:;|down;|left;|right;))|nk;)|k(?:1(?:2;|4;)|34;)|ock;)|n(?:e(?:;|quiv;)|ot;)|o(?:pf;|t(?:;|tom;)|wtie;|x(?:D(?:L;|R;|l;|r;)|H(?:;|D;|U;|d;|u;)|U(?:L;|R;|l;|r;)|V(?:;|H;|L;|R;|h;|l;|r;)|box;|d(?:L;|R;|l;|r;)|h(?:;|D;|U;|d;|u;)|minus;|plus;|times;|u(?:L;|R;|l;|r;)|v(?:;|H;|L;|R;|h;|l;|r;)))|prime;|r(?:eve;|vbar;?)|s(?:cr;|emi;|im(?:;|e;)|ol(?:;|b;|hsub;))|u(?:ll(?:;|et;)|mp(?:;|E;|e(?:;|q;))))|c(?:a(?:cute;|p(?:;|and;|brcup;|c(?:ap;|up;)|dot;|s;)|r(?:et;|on;))|c(?:a(?:ps;|ron;)|edil;?|irc;|ups(?:;|sm;))|dot;|e(?:dil;?|mptyv;|nt(?:;|erdot;|))|fr;|h(?:cy;|eck(?:;|mark;)|i;)|ir(?:;|E;|c(?:;|eq;|le(?:arrow(?:left;|right;)|d(?:R;|S;|ast;|circ;|dash;)))|e;|fnint;|mid;|scir;)|lubs(?:;|uit;)|o(?:lon(?:;|e(?:;|q;))|m(?:ma(?:;|t;)|p(?:;|fn;|le(?:ment;|xes;)))|n(?:g(?:;|dot;)|int;)|p(?:f;|rod;|y(?:;|sr;|)))|r(?:arr;|oss;)|s(?:cr;|u(?:b(?:;|e;)|p(?:;|e;)))|tdot;|u(?:darr(?:l;|r;)|e(?:pr;|sc;)|larr(?:;|p;)|p(?:;|brcap;|c(?:ap;|up;)|dot;|or;|s;)|r(?:arr(?:;|m;)|ly(?:eq(?:prec;|succ;)|vee;|wedge;)|ren;?|vearrow(?:left;|right;))|vee;|wed;)|w(?:conint;|int;)|ylcty;)|d(?:Arr;|Har;|a(?:gger;|leth;|rr;|sh(?:;|v;))|b(?:karow;|lac;)|c(?:aron;|y;)|d(?:;|a(?:gger;|rr;)|otseq;)|e(?:g;?|lta;|mptyv;)|f(?:isht;|r;)|har(?:l;|r;)|i(?:am(?:;|ond(?:;|suit;)|s;)|e;|gamma;|sin;|v(?:;|ide(?:;|ontimes;|)|onx;))|jcy;|lc(?:orn;|rop;)|o(?:llar;|pf;|t(?:;|eq(?:;|dot;)|minus;|plus;|square;)|ublebarwedge;|wn(?:arrow;|downarrows;|harpoon(?:left;|right;)))|r(?:bkarow;|c(?:orn;|rop;))|s(?:c(?:r;|y;)|ol;|trok;)|t(?:dot;|ri(?:;|f;))|u(?:arr;|har;)|wangle;|z(?:cy;|igrarr;))|e(?:D(?:Dot;|ot;)|a(?:cute;?|ster;)|c(?:aron;|ir(?:;|c;?)|olon;|y;)|dot;|e;|f(?:Dot;|r;)|g(?:;|rave;?|s(?:;|dot;))|l(?:;|inters;|l;|s(?:;|dot;))|m(?:acr;|pty(?:;|set;|v;)|sp(?:1(?:3;|4;)|;))|n(?:g;|sp;)|o(?:gon;|pf;)|p(?:ar(?:;|sl;)|lus;|si(?:;|lon;|v;))|q(?:c(?:irc;|olon;)|s(?:im;|lant(?:gtr;|less;))|u(?:als;|est;|iv(?:;|DD;))|vparsl;)|r(?:Dot;|arr;)|s(?:cr;|dot;|im;)|t(?:a;|h;?)|u(?:ml;?|ro;)|x(?:cl;|ist;|p(?:ectation;|onentiale;)))|f(?:allingdotseq;|cy;|emale;|f(?:ilig;|l(?:ig;|lig;)|r;)|ilig;|jlig;|l(?:at;|lig;|tns;)|nof;|o(?:pf;|r(?:all;|k(?:;|v;)))|partint;|r(?:a(?:c(?:1(?:2;?|3;|4;?|5;|6;|8;)|2(?:3;|5;)|3(?:4;?|5;|8;)|45;|5(?:6;|8;)|78;)|sl;)|own;)|scr;)|g(?:E(?:;|l;)|a(?:cute;|mma(?:;|d;)|p;)|breve;|c(?:irc;|y;)|dot;|e(?:;|l;|q(?:;|q;|slant;)|s(?:;|cc;|dot(?:;|o(?:;|l;))|l(?:;|es;)))|fr;|g(?:;|g;)|imel;|jcy;|l(?:;|E;|a;|j;)|n(?:E;|ap(?:;|prox;)|e(?:;|q(?:;|q;))|sim;)|opf;|rave;|s(?:cr;|im(?:;|e;|l;))|t(?:;|c(?:c;|ir;)|dot;|lPar;|quest;|r(?:a(?:pprox;|rr;)|dot;|eq(?:less;|qless;)|less;|sim;)|)|v(?:ertneqq;|nE;))|h(?:Arr;|a(?:irsp;|lf;|milt;|r(?:dcy;|r(?:;|cir;|w;)))|bar;|circ;|e(?:arts(?:;|uit;)|llip;|rcon;)|fr;|ks(?:earow;|warow;)|o(?:arr;|mtht;|ok(?:leftarrow;|rightarrow;)|pf;|rbar;)|s(?:cr;|lash;|trok;)|y(?:bull;|phen;))|i(?:acute;?|c(?:;|irc;?|y;)|e(?:cy;|xcl;?)|f(?:f;|r;)|grave;?|i(?:;|i(?:int;|nt;)|nfin;|ota;)|jlig;|m(?:a(?:cr;|g(?:e;|line;|part;)|th;)|of;|ped;)|n(?:;|care;|fin(?:;|tie;)|odot;|t(?:;|cal;|e(?:gers;|rcal;)|larhk;|prod;))|o(?:cy;|gon;|pf;|ta;)|prod;|quest;?|s(?:cr;|in(?:;|E;|dot;|s(?:;|v;)|v;))|t(?:;|ilde;)|u(?:kcy;|ml;?))|j(?:c(?:irc;|y;)|fr;|math;|opf;|s(?:cr;|ercy;)|ukcy;)|k(?:appa(?:;|v;)|c(?:edil;|y;)|fr;|green;|hcy;|jcy;|opf;|scr;)|l(?:A(?:arr;|rr;|tail;)|Barr;|E(?:;|g;)|Har;|a(?:cute;|emptyv;|gran;|mbda;|ng(?:;|d;|le;)|p;|quo;?|rr(?:;|b(?:;|fs;)|fs;|hk;|lp;|pl;|sim;|tl;)|t(?:;|ail;|e(?:;|s;)))|b(?:arr;|brk;|r(?:ac(?:e;|k;)|k(?:e;|sl(?:d;|u;))))|c(?:aron;|e(?:dil;|il;)|ub;|y;)|d(?:ca;|quo(?:;|r;)|r(?:dhar;|ushar;)|sh;)|e(?:;|ft(?:arrow(?:;|tail;)|harpoon(?:down;|up;)|leftarrows;|right(?:arrow(?:;|s;)|harpoons;|squigarrow;)|threetimes;)|g;|q(?:;|q;|slant;)|s(?:;|cc;|dot(?:;|o(?:;|r;))|g(?:;|es;)|s(?:approx;|dot;|eq(?:gtr;|qgtr;)|gtr;|sim;)))|f(?:isht;|loor;|r;)|g(?:;|E;)|h(?:ar(?:d;|u(?:;|l;))|blk;)|jcy;|l(?:;|arr;|corner;|hard;|tri;)|m(?:idot;|oust(?:;|ache;))|n(?:E;|ap(?:;|prox;)|e(?:;|q(?:;|q;))|sim;)|o(?:a(?:ng;|rr;)|brk;|ng(?:left(?:arrow;|rightarrow;)|mapsto;|rightarrow;)|oparrow(?:left;|right;)|p(?:ar;|f;|lus;)|times;|w(?:ast;|bar;)|z(?:;|enge;|f;))|par(?:;|lt;)|r(?:arr;|corner;|har(?:;|d;)|m;|tri;)|s(?:aquo;|cr;|h;|im(?:;|e;|g;)|q(?:b;|uo(?:;|r;))|trok;)|t(?:;|c(?:c;|ir;)|dot;|hree;|imes;|larr;|quest;|r(?:Par;|i(?:;|e;|f;))|)|ur(?:dshar;|uhar;)|v(?:ertneqq;|nE;))|m(?:DDot;|a(?:cr;?|l(?:e;|t(?:;|ese;))|p(?:;|sto(?:;|down;|left;|up;))|rker;)|c(?:omma;|y;)|dash;|easuredangle;|fr;|ho;|i(?:cro;?|d(?:;|ast;|cir;|dot;?)|nus(?:;|b;|d(?:;|u;)))|l(?:cp;|dr;)|nplus;|o(?:dels;|pf;)|p;|s(?:cr;|tpos;)|u(?:;|ltimap;|map;))|n(?:G(?:g;|t(?:;|v;))|L(?:eft(?:arrow;|rightarrow;)|l;|t(?:;|v;))|Rightarrow;|V(?:Dash;|dash;)|a(?:bla;|cute;|ng;|p(?:;|E;|id;|os;|prox;)|tur(?:;|al(?:;|s;)))|b(?:sp;?|ump(?:;|e;))|c(?:a(?:p;|ron;)|edil;|ong(?:;|dot;)|up;|y;)|dash;|e(?:;|Arr;|ar(?:hk;|r(?:;|ow;))|dot;|quiv;|s(?:ear;|im;)|xist(?:;|s;))|fr;|g(?:E;|e(?:;|q(?:;|q;|slant;)|s;)|sim;|t(?:;|r;))|h(?:Arr;|arr;|par;)|i(?:;|s(?:;|d;)|v;)|jcy;|l(?:Arr;|E;|arr;|dr;|e(?:;|ft(?:arrow;|rightarrow;)|q(?:;|q;|slant;)|s(?:;|s;))|sim;|t(?:;|ri(?:;|e;)))|mid;|o(?:pf;|t(?:;|in(?:;|E;|dot;|v(?:a;|b;|c;))|ni(?:;|v(?:a;|b;|c;))|))|p(?:ar(?:;|allel;|sl;|t;)|olint;|r(?:;|cue;|e(?:;|c(?:;|eq;))))|r(?:Arr;|arr(?:;|c;|w;)|ightarrow;|tri(?:;|e;))|s(?:c(?:;|cue;|e;|r;)|hort(?:mid;|parallel;)|im(?:;|e(?:;|q;))|mid;|par;|qsu(?:be;|pe;)|u(?:b(?:;|E;|e;|set(?:;|eq(?:;|q;)))|cc(?:;|eq;)|p(?:;|E;|e;|set(?:;|eq(?:;|q;)))))|t(?:gl;|ilde;?|lg;|riangle(?:left(?:;|eq;)|right(?:;|eq;)))|u(?:;|m(?:;|ero;|sp;))|v(?:Dash;|Harr;|ap;|dash;|g(?:e;|t;)|infin;|l(?:Arr;|e;|t(?:;|rie;))|r(?:Arr;|trie;)|sim;)|w(?:Arr;|ar(?:hk;|r(?:;|ow;))|near;))|o(?:S;|a(?:cute;?|st;)|c(?:ir(?:;|c;?)|y;)|d(?:ash;|blac;|iv;|ot;|sold;)|elig;|f(?:cir;|r;)|g(?:on;|rave;?|t;)|h(?:bar;|m;)|int;|l(?:arr;|c(?:ir;|ross;)|ine;|t;)|m(?:acr;|ega;|i(?:cron;|d;|nus;))|opf;|p(?:ar;|erp;|lus;)|r(?:;|arr;|d(?:;|er(?:;|of;)|f;?|m;?)|igof;|or;|slope;|v;)|s(?:cr;|lash;?|ol;)|ti(?:lde;?|mes(?:;|as;))|uml;?|vbar;)|p(?:ar(?:;|a(?:;|llel;|)|s(?:im;|l;)|t;)|cy;|er(?:cnt;|iod;|mil;|p;|tenk;)|fr;|h(?:i(?:;|v;)|mmat;|one;)|i(?:;|tchfork;|v;)|l(?:an(?:ck(?:;|h;)|kv;)|us(?:;|acir;|b;|cir;|d(?:o;|u;)|e;|mn;?|sim;|two;))|m;|o(?:intint;|pf;|und;?)|r(?:;|E;|ap;|cue;|e(?:;|c(?:;|approx;|curlyeq;|eq;|n(?:approx;|eqq;|sim;)|sim;))|ime(?:;|s;)|n(?:E;|ap;|sim;)|o(?:d;|f(?:alar;|line;|surf;)|p(?:;|to;))|sim;|urel;)|s(?:cr;|i;)|uncsp;)|q(?:fr;|int;|opf;|prime;|scr;|u(?:at(?:ernions;|int;)|est(?:;|eq;)|ot;?))|r(?:A(?:arr;|rr;|tail;)|Barr;|Har;|a(?:c(?:e;|ute;)|dic;|emptyv;|ng(?:;|d;|e;|le;)|quo;?|rr(?:;|ap;|b(?:;|fs;)|c;|fs;|hk;|lp;|pl;|sim;|tl;|w;)|t(?:ail;|io(?:;|nals;)))|b(?:arr;|brk;|r(?:ac(?:e;|k;)|k(?:e;|sl(?:d;|u;))))|c(?:aron;|e(?:dil;|il;)|ub;|y;)|d(?:ca;|ldhar;|quo(?:;|r;)|sh;)|e(?:al(?:;|ine;|part;|s;)|ct;|g;?)|f(?:isht;|loor;|r;)|h(?:ar(?:d;|u(?:;|l;))|o(?:;|v;))|i(?:ght(?:arrow(?:;|tail;)|harpoon(?:down;|up;)|left(?:arrows;|harpoons;)|rightarrows;|squigarrow;|threetimes;)|ng;|singdotseq;)|l(?:arr;|har;|m;)|moust(?:;|ache;)|nmid;|o(?:a(?:ng;|rr;)|brk;|p(?:ar;|f;|lus;)|times;)|p(?:ar(?:;|gt;)|polint;)|rarr;|s(?:aquo;|cr;|h;|q(?:b;|uo(?:;|r;)))|t(?:hree;|imes;|ri(?:;|e;|f;|ltri;))|uluhar;|x;)|s(?:acute;|bquo;|c(?:;|E;|a(?:p;|ron;)|cue;|e(?:;|dil;)|irc;|n(?:E;|ap;|sim;)|polint;|sim;|y;)|dot(?:;|b;|e;)|e(?:Arr;|ar(?:hk;|r(?:;|ow;))|ct;?|mi;|swar;|tm(?:inus;|n;)|xt;)|fr(?:;|own;)|h(?:arp;|c(?:hcy;|y;)|ort(?:mid;|parallel;)|y;?)|i(?:gma(?:;|f;|v;)|m(?:;|dot;|e(?:;|q;)|g(?:;|E;)|l(?:;|E;)|ne;|plus;|rarr;))|larr;|m(?:a(?:llsetminus;|shp;)|eparsl;|i(?:d;|le;)|t(?:;|e(?:;|s;)))|o(?:ftcy;|l(?:;|b(?:;|ar;))|pf;)|pa(?:des(?:;|uit;)|r;)|q(?:c(?:ap(?:;|s;)|up(?:;|s;))|su(?:b(?:;|e;|set(?:;|eq;))|p(?:;|e;|set(?:;|eq;)))|u(?:;|ar(?:e;|f;)|f;))|rarr;|s(?:cr;|etmn;|mile;|tarf;)|t(?:ar(?:;|f;)|r(?:aight(?:epsilon;|phi;)|ns;))|u(?:b(?:;|E;|dot;|e(?:;|dot;)|mult;|n(?:E;|e;)|plus;|rarr;|s(?:et(?:;|eq(?:;|q;)|neq(?:;|q;))|im;|u(?:b;|p;)))|cc(?:;|approx;|curlyeq;|eq;|n(?:approx;|eqq;|sim;)|sim;)|m;|ng;|p(?:1;?|2;?|3;?|;|E;|d(?:ot;|sub;)|e(?:;|dot;)|hs(?:ol;|ub;)|larr;|mult;|n(?:E;|e;)|plus;|s(?:et(?:;|eq(?:;|q;)|neq(?:;|q;))|im;|u(?:b;|p;))))|w(?:Arr;|ar(?:hk;|r(?:;|ow;))|nwar;)|zlig;?)|t(?:a(?:rget;|u;)|brk;|c(?:aron;|edil;|y;)|dot;|elrec;|fr;|h(?:e(?:re(?:4;|fore;)|ta(?:;|sym;|v;))|i(?:ck(?:approx;|sim;)|nsp;)|k(?:ap;|sim;)|orn;?)|i(?:lde;|mes(?:;|b(?:;|ar;)|d;|)|nt;)|o(?:ea;|p(?:;|bot;|cir;|f(?:;|ork;))|sa;)|prime;|r(?:ade;|i(?:angle(?:;|down;|left(?:;|eq;)|q;|right(?:;|eq;))|dot;|e;|minus;|plus;|sb;|time;)|pezium;)|s(?:c(?:r;|y;)|hcy;|trok;)|w(?:ixt;|ohead(?:leftarrow;|rightarrow;)))|u(?:Arr;|Har;|a(?:cute;?|rr;)|br(?:cy;|eve;)|c(?:irc;?|y;)|d(?:arr;|blac;|har;)|f(?:isht;|r;)|grave;?|h(?:ar(?:l;|r;)|blk;)|l(?:c(?:orn(?:;|er;)|rop;)|tri;)|m(?:acr;|l;?)|o(?:gon;|pf;)|p(?:arrow;|downarrow;|harpoon(?:left;|right;)|lus;|si(?:;|h;|lon;)|uparrows;)|r(?:c(?:orn(?:;|er;)|rop;)|ing;|tri;)|scr;|t(?:dot;|ilde;|ri(?:;|f;))|u(?:arr;|ml;?)|wangle;)|v(?:Arr;|Bar(?:;|v;)|Dash;|a(?:ngrt;|r(?:epsilon;|kappa;|nothing;|p(?:hi;|i;|ropto;)|r(?:;|ho;)|s(?:igma;|u(?:bsetneq(?:;|q;)|psetneq(?:;|q;)))|t(?:heta;|riangle(?:left;|right;))))|cy;|dash;|e(?:e(?:;|bar;|eq;)|llip;|r(?:bar;|t;))|fr;|ltri;|nsu(?:b;|p;)|opf;|prop;|rtri;|s(?:cr;|u(?:bn(?:E;|e;)|pn(?:E;|e;)))|zigzag;)|w(?:circ;|e(?:d(?:bar;|ge(?:;|q;))|ierp;)|fr;|opf;|p;|r(?:;|eath;)|scr;)|x(?:c(?:ap;|irc;|up;)|dtri;|fr;|h(?:Arr;|arr;)|i;|l(?:Arr;|arr;)|map;|nis;|o(?:dot;|p(?:f;|lus;)|time;)|r(?:Arr;|arr;)|s(?:cr;|qcup;)|u(?:plus;|tri;)|vee;|wedge;)|y(?:ac(?:ute;?|y;)|c(?:irc;|y;)|en;?|fr;|icy;|opf;|scr;|u(?:cy;|ml;?))|z(?:acute;|c(?:aron;|y;)|dot;|e(?:etrf;|ta;)|fr;|hcy;|igrarr;|opf;|scr;|w(?:j;|nj;)))|[\s\S]/g; - -var NAMEDCHARREF_MAXLEN = 32; - -// Regular expression constants used by the tokenizer and parser - -// Note that \r is included in all of these regexps because it will need -// to be converted to LF by the scanChars() function. -var DBLQUOTEATTRVAL = /[^\r"&\u0000]+/g; -var SINGLEQUOTEATTRVAL = /[^\r'&\u0000]+/g; -var UNQUOTEDATTRVAL = /[^\r\t\n\f &>\u0000]+/g; -var TAGNAME = /[^\r\t\n\f \/>A-Z\u0000]+/g; -var ATTRNAME = /[^\r\t\n\f \/=>A-Z\u0000]+/g; - -var CDATATEXT = /[^\]\r\u0000\uffff]*/g; -var DATATEXT = /[^&<\r\u0000\uffff]*/g; -var RAWTEXT = /[^<\r\u0000\uffff]*/g; -var PLAINTEXT = /[^\r\u0000\uffff]*/g; -// Since we don't have the 'sticky tag', add '|.' to the end of SIMPLETAG -// and SIMPLEATTR so that we are guaranteed to always match. This prevents -// us from scanning past the lastIndex set. (Note that the desired matches -// are always greater than 1 char long, so longest-match will ensure that . -// is not matched unless the desired match fails.) -var SIMPLETAG = /(?:(\/)?([a-z]+)>)|[\s\S]/g; -var SIMPLEATTR = /(?:([-a-z]+)[ \t\n\f]*=[ \t\n\f]*('[^'&\r\u0000]*'|"[^"&\r\u0000]*"|[^\t\n\r\f "&'\u0000>][^&> \t\n\r\f\u0000]*[ \t\n\f]))|[\s\S]/g; - -var NONWS = /[^\x09\x0A\x0C\x0D\x20]/; -var ALLNONWS = /[^\x09\x0A\x0C\x0D\x20]/g; // like above, with g flag -var NONWSNONNUL = /[^\x00\x09\x0A\x0C\x0D\x20]/; // don't allow NUL either -var LEADINGWS = /^[\x09\x0A\x0C\x0D\x20]+/; -var NULCHARS = /\x00/g; - -/*** - * These are utility functions that don't use any of the parser's - * internal state. - */ -function buf2str(buf) { - var CHUNKSIZE=16384; - if (buf.length < CHUNKSIZE) { - return String.fromCharCode.apply(String, buf); - } - // special case for large strings, to avoid busting the stack. - var result = ''; - for (var i = 0; i < buf.length; i += CHUNKSIZE) { - result += String.fromCharCode.apply(String, buf.slice(i, i+CHUNKSIZE)); - } - return result; -} - -function str2buf(s) { - var result = []; - for (var i=0; i 0; i--) { - var e = this.elements[i]; - if (isA(e, tag)) break; - } - this.elements.length = i; - this.top = this.elements[i-1]; -}; - -// Pop elements off the stack up to and including the first -// element that is an instance of the specified type -HTMLParser.ElementStack.prototype.popElementType = function(type) { - for(var i = this.elements.length-1; i > 0; i--) { - if (this.elements[i] instanceof type) break; - } - this.elements.length = i; - this.top = this.elements[i-1]; -}; - -// Pop elements off the stack up to and including the element e. -// Note that this is very different from removeElement() -// This requires that e is on the stack. -HTMLParser.ElementStack.prototype.popElement = function(e) { - for(var i = this.elements.length-1; i > 0; i--) { - if (this.elements[i] === e) break; - } - this.elements.length = i; - this.top = this.elements[i-1]; -}; - -// Remove a specific element from the stack. -// Do nothing if the element is not on the stack -HTMLParser.ElementStack.prototype.removeElement = function(e) { - if (this.top === e) this.pop(); - else { - var idx = this.elements.lastIndexOf(e); - if (idx !== -1) - this.elements.splice(idx, 1); - } -}; - -HTMLParser.ElementStack.prototype.clearToContext = function(set) { - // Note that we don't loop to 0. Never pop the elt off. - for(var i = this.elements.length-1; i > 0; i--) { - if (isA(this.elements[i], set)) break; - } - this.elements.length = i+1; - this.top = this.elements[i]; -}; - -HTMLParser.ElementStack.prototype.contains = function(tag) { - return this.inSpecificScope(tag, Object.create(null)); -}; - -HTMLParser.ElementStack.prototype.inSpecificScope = function(tag, set) { - for(var i = this.elements.length-1; i >= 0; i--) { - var elt = this.elements[i]; - if (isA(elt, tag)) return true; - if (isA(elt, set)) return false; - } - return false; -}; - -// Like the above, but for a specific element, not a tagname -HTMLParser.ElementStack.prototype.elementInSpecificScope = function(target, set) { - for(var i = this.elements.length-1; i >= 0; i--) { - var elt = this.elements[i]; - if (elt === target) return true; - if (isA(elt, set)) return false; - } - return false; -}; - -// Like the above, but for an element interface, not a tagname -HTMLParser.ElementStack.prototype.elementTypeInSpecificScope = function(target, set) { - for(var i = this.elements.length-1; i >= 0; i--) { - var elt = this.elements[i]; - if (elt instanceof target) return true; - if (isA(elt, set)) return false; - } - return false; -}; - -HTMLParser.ElementStack.prototype.inScope = function(tag) { - return this.inSpecificScope(tag, inScopeSet); -}; - -HTMLParser.ElementStack.prototype.elementInScope = function(e) { - return this.elementInSpecificScope(e, inScopeSet); -}; - -HTMLParser.ElementStack.prototype.elementTypeInScope = function(type) { - return this.elementTypeInSpecificScope(type, inScopeSet); -}; - -HTMLParser.ElementStack.prototype.inButtonScope = function(tag) { - return this.inSpecificScope(tag, inButtonScopeSet); -}; - -HTMLParser.ElementStack.prototype.inListItemScope = function(tag) { - return this.inSpecificScope(tag, inListItemScopeSet); -}; - -HTMLParser.ElementStack.prototype.inTableScope = function(tag) { - return this.inSpecificScope(tag, inTableScopeSet); -}; - -HTMLParser.ElementStack.prototype.inSelectScope = function(tag) { - // Can't implement this one with inSpecificScope, since it involves - // a set defined by inverting another set. So implement manually. - for(var i = this.elements.length-1; i >= 0; i--) { - var elt = this.elements[i]; - if (elt.namespaceURI !== NAMESPACE.HTML) return false; - var localname = elt.localName; - if (localname === tag) return true; - if (localname !== "optgroup" && localname !== "option") - return false; - } - return false; -}; - -HTMLParser.ElementStack.prototype.generateImpliedEndTags = function(butnot, thorough) { - var endTagSet = thorough ? thoroughImpliedEndTagsSet : impliedEndTagsSet; - for(var i = this.elements.length-1; i >= 0; i--) { - var e = this.elements[i]; - if (butnot && isA(e, butnot)) break; - if (!isA(this.elements[i], endTagSet)) break; - } - - this.elements.length = i+1; - this.top = this.elements[i]; -}; - -/*** - * The ActiveFormattingElements class - */ -HTMLParser.ActiveFormattingElements = function AFE() { - this.list = []; // elements - this.attrs = []; // attribute tokens for cloning -}; - -HTMLParser.ActiveFormattingElements.prototype.MARKER = { localName: "|" }; - -/* -// For debugging -HTMLParser.ActiveFormattingElements.prototype.toString = function() { - return "AFE: " + - this.list.map(function(e) { return e.localName; }).join("-"); -} -*/ - -HTMLParser.ActiveFormattingElements.prototype.insertMarker = function() { - this.list.push(this.MARKER); - this.attrs.push(this.MARKER); -}; - -HTMLParser.ActiveFormattingElements.prototype.push = function(elt, attrs) { - // Scan backwards: if there are already 3 copies of this element - // before we encounter a marker, then drop the last one - var count = 0; - for(var i = this.list.length-1; i >= 0; i--) { - if (this.list[i] === this.MARKER) break; - // equal() is defined below - if (equal(elt, this.list[i], this.attrs[i])) { - count++; - if (count === 3) { - this.list.splice(i, 1); - this.attrs.splice(i, 1); - break; - } - } - } - - - // Now push the element onto the list - this.list.push(elt); - - // Copy the attributes and push those on, too - var attrcopy = []; - for(var ii = 0; ii < attrs.length; ii++) { - attrcopy[ii] = attrs[ii]; - } - - this.attrs.push(attrcopy); - - // This function defines equality of two elements for the purposes - // of the AFE list. Note that it compares the new elements - // attributes to the saved array of attributes associated with - // the old element because a script could have changed the - // old element's set of attributes - function equal(newelt, oldelt, oldattrs) { - if (newelt.localName !== oldelt.localName) return false; - if (newelt._numattrs !== oldattrs.length) return false; - for(var i = 0, n = oldattrs.length; i < n; i++) { - var oldname = oldattrs[i][0]; - var oldval = oldattrs[i][1]; - if (!newelt.hasAttribute(oldname)) return false; - if (newelt.getAttribute(oldname) !== oldval) return false; - } - return true; - } -}; - -HTMLParser.ActiveFormattingElements.prototype.clearToMarker = function() { - for(var i = this.list.length-1; i >= 0; i--) { - if (this.list[i] === this.MARKER) break; - } - if (i < 0) i = 0; - this.list.length = i; - this.attrs.length = i; -}; - -// Find and return the last element with the specified tag between the -// end of the list and the last marker on the list. -// Used when parsing in_body_mode() -HTMLParser.ActiveFormattingElements.prototype.findElementByTag = function(tag) { - for(var i = this.list.length-1; i >= 0; i--) { - var elt = this.list[i]; - if (elt === this.MARKER) break; - if (elt.localName === tag) return elt; - } - return null; -}; - -HTMLParser.ActiveFormattingElements.prototype.indexOf = function(e) { - return this.list.lastIndexOf(e); -}; - -// Find the element e in the list and remove it -// Used when parsing in_body() -HTMLParser.ActiveFormattingElements.prototype.remove = function(e) { - var idx = this.list.lastIndexOf(e); - if (idx !== -1) { - this.list.splice(idx, 1); - this.attrs.splice(idx, 1); - } -}; - -// Find element a in the list and replace it with element b -// XXX: Do I need to handle attributes here? -HTMLParser.ActiveFormattingElements.prototype.replace = function(a, b, attrs) { - var idx = this.list.lastIndexOf(a); - if (idx !== -1) { - this.list[idx] = b; - this.attrs[idx] = attrs; - } -}; - -// Find a in the list and insert b after it -// This is only used for insert a bookmark object, so the -// attrs array doesn't really matter -HTMLParser.ActiveFormattingElements.prototype.insertAfter = function(a,b) { - var idx = this.list.lastIndexOf(a); - if (idx !== -1) { - this.list.splice(idx, 0, b); - this.attrs.splice(idx, 0, b); - } -}; - - - - -/*** - * This is the parser factory function. It is the return value of - * the outer closure that it is defined within. Most of the parser - * implementation details are inside this function. - */ -function HTMLParser(address, fragmentContext, options) { - /*** - * These are the parser's state variables - */ - // Scanner state - var chars = null; - var numchars = 0; // Length of chars - var nextchar = 0; // Index of next char - var input_complete = false; // Becomes true when end() called. - var scanner_skip_newline = false; // If previous char was CR - var reentrant_invocations = 0; - var saved_scanner_state = []; - var leftovers = ""; - var first_batch = true; - var paused = 0; // Becomes non-zero while loading scripts - - - // Tokenizer state - var tokenizer = data_state; // Current tokenizer state - var return_state; - var character_reference_code; - var tagnamebuf = ""; - var lasttagname = ""; // holds the target end tag for text states - var tempbuf = []; - var attrnamebuf = ""; - var attrvaluebuf = ""; - var commentbuf = []; - var doctypenamebuf = []; - var doctypepublicbuf = []; - var doctypesystembuf = []; - var attributes = []; - var is_end_tag = false; - - // Tree builder state - var parser = initial_mode; // Current insertion mode - var originalInsertionMode = null; // A saved insertion mode - var templateInsertionModes = []; // Stack of template insertion modes. - var stack = new HTMLParser.ElementStack(); // Stack of open elements - var afe = new HTMLParser.ActiveFormattingElements(); // mis-nested tags - var fragment = (fragmentContext!==undefined); // For innerHTML, etc. - var head_element_pointer = null; - var form_element_pointer = null; - var scripting_enabled = true; - if (fragmentContext) { - scripting_enabled = fragmentContext.ownerDocument._scripting_enabled; - } - if (options && options.scripting_enabled === false) - scripting_enabled = false; - var frameset_ok = true; - var force_quirks = false; - var pending_table_text; - var text_integration_mode; // XXX a spec bug workaround? - - // A single run of characters, buffered up to be sent to - // the parser as a single string. - var textrun = []; - var textIncludesNUL = false; - var ignore_linefeed = false; - - /*** - * This is the parser object that will be the return value of this - * factory function, which is some 5000 lines below. - * Note that the variable "parser" is the current state of the - * parser's state machine. This variable "htmlparser" is the - * return value and defines the public API of the parser - */ - var htmlparser = { - document: function() { - return doc; - }, - - // Convenience function for internal use. Can only be called once, - // as it removes the nodes from `doc` to add them to fragment. - _asDocumentFragment: function() { - var frag = doc.createDocumentFragment(); - var root = doc.firstChild; - while(root.hasChildNodes()) { - frag.appendChild(root.firstChild); - } - return frag; - }, - - // Internal function used from HTMLScriptElement to pause the - // parser while a script is being loaded from the network - pause: function() { - // print("pausing parser"); - paused++; - }, - - // Called when a script finishes loading - resume: function() { - // print("resuming parser"); - paused--; - // XXX: added this to force a resumption. - // Is this the right thing to do? - this.parse(""); - }, - - // Parse the HTML text s. - // The second argument should be true if there is no more - // text to be parsed, and should be false or omitted otherwise. - // The second argument must not be set for recursive invocations - // from document.write() - parse: function(s, end, shouldPauseFunc) { - var moreToDo; - - // If we're paused, remember the text to parse, but - // don't parse it now. - // (Don't invoke shouldPauseFunc because we haven't handled 'end' yet.) - if (paused > 0) { - leftovers += s; - return true; // more to do - } - - - if (reentrant_invocations === 0) { - // A normal, top-level invocation - if (leftovers) { - s = leftovers + s; - leftovers = ""; - } - - // Add a special marker character to the end of - // the buffer. If the scanner is at the end of - // the buffer and input_complete is set, then this - // character will transform into an EOF token. - // Having an actual character that represents EOF - // in the character buffer makes lookahead regexp - // matching work more easily, and this is - // important for character references. - if (end) { - s += "\uFFFF"; - input_complete = true; // Makes scanChars() send EOF - } - - chars = s; - numchars = s.length; - nextchar = 0; - - if (first_batch) { - // We skip a leading Byte Order Mark (\uFEFF) - // on first batch of text we're given - first_batch = false; - if (chars.charCodeAt(0) === 0xFEFF) nextchar = 1; - } - - reentrant_invocations++; - moreToDo = scanChars(shouldPauseFunc); - leftovers = chars.substring(nextchar, numchars); - reentrant_invocations--; - } - else { - // This is the re-entrant case, which we have to - // handle a little differently. - reentrant_invocations++; - - // Save current scanner state - saved_scanner_state.push(chars, numchars, nextchar); - - // Set new scanner state - chars = s; - numchars = s.length; - nextchar = 0; - - // Now scan as many of these new chars as we can - scanChars(); - moreToDo = false; - - leftovers = chars.substring(nextchar, numchars); - - // restore old scanner state - nextchar = saved_scanner_state.pop(); - numchars = saved_scanner_state.pop(); - chars = saved_scanner_state.pop(); - - // If there were leftover chars from this invocation - // insert them into the pending invocation's buffer - // and trim already processed chars at the same time - if (leftovers) { - chars = leftovers + chars.substring(nextchar); - numchars = chars.length; - nextchar = 0; - leftovers = ""; - } - - // Decrement the counter - reentrant_invocations--; - } - return moreToDo; - } - }; - - - // This is the document we'll be building up - var doc = new Document(true, address); - - // The document needs to know about the parser, for document.write(). - // This _parser property will be deleted when we're done parsing. - doc._parser = htmlparser; - - // XXX I think that any document we use this parser on should support - // scripts. But I may need to configure that through a parser parameter - // Only documents with windows ("browsing contexts" to be precise) - // allow scripting. - doc._scripting_enabled = scripting_enabled; - - - /*** - * The actual code of the HTMLParser() factory function begins here. - */ - - if (fragmentContext) { // for innerHTML parsing - if (fragmentContext.ownerDocument._quirks) - doc._quirks = true; - if (fragmentContext.ownerDocument._limitedQuirks) - doc._limitedQuirks = true; - - // Set the initial tokenizer state - if (fragmentContext.namespaceURI === NAMESPACE.HTML) { - switch(fragmentContext.localName) { - case "title": - case "textarea": - tokenizer = rcdata_state; - break; - case "style": - case "xmp": - case "iframe": - case "noembed": - case "noframes": - case "script": - case "plaintext": - tokenizer = plaintext_state; - break; - } - } - - var root = doc.createElement("html"); - doc._appendChild(root); - stack.push(root); - if (fragmentContext instanceof impl.HTMLTemplateElement) { - templateInsertionModes.push(in_template_mode); - } - resetInsertionMode(); - - for(var e = fragmentContext; e !== null; e = e.parentElement) { - if (e instanceof impl.HTMLFormElement) { - form_element_pointer = e; - break; - } - } - } - - /*** - * Scanner functions - */ - // Loop through the characters in chars, and pass them one at a time - // to the tokenizer FSM. Return when no more characters can be processed - // (This may leave 1 or more characters in the buffer: like a CR - // waiting to see if the next char is LF, or for states that require - // lookahead...) - function scanChars(shouldPauseFunc) { - var codepoint, s, pattern, eof; - - while(nextchar < numchars) { - - // If we just tokenized a tag, then the paused flag - // may have been set to tell us to stop tokenizing while - // the script is loading - if (paused > 0 || (shouldPauseFunc && shouldPauseFunc())) { - return true; - } - - - switch(typeof tokenizer.lookahead) { - case 'undefined': - codepoint = chars.charCodeAt(nextchar++); - if (scanner_skip_newline) { - scanner_skip_newline = false; - if (codepoint === 0x000A) { - nextchar++; - continue; - } - } - switch(codepoint) { - case 0x000D: - // CR always turns into LF, but if the next character - // is LF, then that second LF is skipped. - if (nextchar < numchars) { - if (chars.charCodeAt(nextchar) === 0x000A) - nextchar++; - } - else { - // We don't know the next char right now, so we - // can't check if it is a LF. So set a flag - scanner_skip_newline = true; - } - - // In either case, emit a LF - tokenizer(0x000A); - - break; - case 0xFFFF: - if (input_complete && nextchar === numchars) { - tokenizer(EOF); // codepoint will be 0xFFFF here - break; - } - /* falls through */ - default: - tokenizer(codepoint); - break; - } - break; - - case 'number': - codepoint = chars.charCodeAt(nextchar); - - // The only tokenizer states that require fixed lookahead - // only consume alphanum characters, so we don't have - // to worry about CR and LF in this case - - // tokenizer wants n chars of lookahead - var n = tokenizer.lookahead; - var needsString = true; - if (n < 0) { - needsString = false; - n = -n; - } - - if (n < numchars - nextchar) { - // If we can look ahead that far - s = needsString ? chars.substring(nextchar, nextchar+n) : null; - eof = false; - } - else { // if we don't have that many characters - if (input_complete) { // If no more are coming - // Just return what we have - s = needsString ? chars.substring(nextchar, numchars) : null; - eof = true; - if (codepoint === 0xFFFF && nextchar === numchars-1) - codepoint = EOF; - } - else { - // Return now and wait for more chars later - return true; - } - } - tokenizer(codepoint, s, eof); - break; - case 'string': - codepoint = chars.charCodeAt(nextchar); - - // tokenizer wants characters up to a matching string - pattern = tokenizer.lookahead; - var pos = chars.indexOf(pattern, nextchar); - if (pos !== -1) { - s = chars.substring(nextchar, pos + pattern.length); - eof = false; - } - else { // No match - // If more characters coming, wait for them - if (!input_complete) return true; - - // Otherwise, we've got to return what we've got - s = chars.substring(nextchar, numchars); - if (codepoint === 0xFFFF && nextchar === numchars-1) - codepoint = EOF; - eof = true; - } - - // The tokenizer states that require this kind of - // lookahead have to be careful to handle CR characters - // correctly - tokenizer(codepoint, s, eof); - break; - } - } - return false; // no more characters to scan! - } - - - /*** - * Tokenizer utility functions - */ - function addAttribute(name,value) { - // Make sure there isn't already an attribute with this name - // If there is, ignore this one. - for(var i = 0; i < attributes.length; i++) { - if (attributes[i][0] === name) return; - } - - if (value !== undefined) { - attributes.push([name, value]); - } - else { - attributes.push([name]); - } - } - - // Shortcut for simple attributes - function handleSimpleAttribute() { - SIMPLEATTR.lastIndex = nextchar-1; - var matched = SIMPLEATTR.exec(chars); - if (!matched) throw new Error("should never happen"); - var name = matched[1]; - if (!name) return false; - var value = matched[2]; - var len = value.length; - switch(value[0]) { - case '"': - case "'": - value = value.substring(1, len-1); - nextchar += (matched[0].length-1); - tokenizer = after_attribute_value_quoted_state; - break; - default: - tokenizer = before_attribute_name_state; - nextchar += (matched[0].length-1); - value = value.substring(0, len-1); - break; - } - - // Make sure there isn't already an attribute with this name - // If there is, ignore this one. - for(var i = 0; i < attributes.length; i++) { - if (attributes[i][0] === name) return true; - } - - attributes.push([name, value]); - return true; - } - - function beginTagName() { - is_end_tag = false; - tagnamebuf = ""; - attributes.length = 0; - } - function beginEndTagName() { - is_end_tag = true; - tagnamebuf = ""; - attributes.length = 0; - } - - function beginTempBuf() { tempbuf.length = 0; } - function beginAttrName() { attrnamebuf = ""; } - function beginAttrValue() { attrvaluebuf = ""; } - function beginComment() { commentbuf.length = 0; } - function beginDoctype() { - doctypenamebuf.length = 0; - doctypepublicbuf = null; - doctypesystembuf = null; - } - function beginDoctypePublicId() { doctypepublicbuf = []; } - function beginDoctypeSystemId() { doctypesystembuf = []; } - function forcequirks() { force_quirks = true; } - function cdataAllowed() { - return stack.top && - stack.top.namespaceURI !== "http://www.w3.org/1999/xhtml"; - } - - // Return true if the codepoints in the specified buffer match the - // characters of lasttagname - function appropriateEndTag(buf) { - return lasttagname === buf; - } - - function flushText() { - if (textrun.length > 0) { - var s = buf2str(textrun); - textrun.length = 0; - - if (ignore_linefeed) { - ignore_linefeed = false; - if (s[0] === "\n") s = s.substring(1); - if (s.length === 0) return; - } - - insertToken(TEXT, s); - textIncludesNUL = false; - } - ignore_linefeed = false; - } - - // Consume chars matched by the pattern and return them as a string. Starts - // matching at the current position, so users should drop the current char - // otherwise. - function getMatchingChars(pattern) { - pattern.lastIndex = nextchar - 1; - var match = pattern.exec(chars); - if (match && match.index === nextchar - 1) { - match = match[0]; - nextchar += match.length - 1; - /* Careful! Make sure we haven't matched the EOF character! */ - if (input_complete && nextchar === numchars) { - // Oops, backup one. - match = match.slice(0, -1); - nextchar--; - } - return match; - } else { - throw new Error("should never happen"); - } - } - - // emit a string of chars that match a regexp - // Returns false if no chars matched. - function emitCharsWhile(pattern) { - pattern.lastIndex = nextchar-1; - var match = pattern.exec(chars)[0]; - if (!match) return false; - emitCharString(match); - nextchar += match.length - 1; - return true; - } - - // This is used by CDATA sections - function emitCharString(s) { - if (textrun.length > 0) flushText(); - - if (ignore_linefeed) { - ignore_linefeed = false; - if (s[0] === "\n") s = s.substring(1); - if (s.length === 0) return; - } - - insertToken(TEXT, s); - } - - function emitTag() { - if (is_end_tag) insertToken(ENDTAG, tagnamebuf); - else { - // Remember the last open tag we emitted - var tagname = tagnamebuf; - tagnamebuf = ""; - lasttagname = tagname; - insertToken(TAG, tagname, attributes); - } - } - - - // A shortcut: look ahead and if this is a open or close tag - // in lowercase with no spaces and no attributes, just emit it now. - function emitSimpleTag() { - if (nextchar === numchars) { return false; /* not even 1 char left */ } - SIMPLETAG.lastIndex = nextchar; - var matched = SIMPLETAG.exec(chars); - if (!matched) throw new Error("should never happen"); - var tagname = matched[2]; - if (!tagname) return false; - var endtag = matched[1]; - if (endtag) { - nextchar += (tagname.length+2); - insertToken(ENDTAG, tagname); - } - else { - nextchar += (tagname.length+1); - lasttagname = tagname; - insertToken(TAG, tagname, NOATTRS); - } - return true; - } - - function emitSelfClosingTag() { - if (is_end_tag) insertToken(ENDTAG, tagnamebuf, null, true); - else { - insertToken(TAG, tagnamebuf, attributes, true); - } - } - - function emitDoctype() { - insertToken(DOCTYPE, - buf2str(doctypenamebuf), - doctypepublicbuf ? buf2str(doctypepublicbuf) : undefined, - doctypesystembuf ? buf2str(doctypesystembuf) : undefined); - } - - function emitEOF() { - flushText(); - parser(EOF); // EOF never goes to insertForeignContent() - doc.modclock = 1; // Start tracking modifications - } - - // Insert a token, either using the current parser insertion mode - // (for HTML stuff) or using the insertForeignToken() method. - var insertToken = htmlparser.insertToken = function insertToken(t, value, arg3, arg4) { - flushText(); - var current = stack.top; - - if (!current || current.namespaceURI === NAMESPACE.HTML) { - // This is the common case - parser(t, value, arg3, arg4); - } - else { - // Otherwise we may need to insert this token as foreign content - if (t !== TAG && t !== TEXT) { - insertForeignToken(t, value, arg3, arg4); - } - else { - // But in some cases we treat it as regular content - if ((isMathmlTextIntegrationPoint(current) && - (t === TEXT || - (t === TAG && - value !== "mglyph" && value !== "malignmark"))) || - (t === TAG && - value === "svg" && - current.namespaceURI === NAMESPACE.MATHML && - current.localName === "annotation-xml") || - isHTMLIntegrationPoint(current)) { - - // XXX: the text_integration_mode stuff is an - // attempted bug workaround of mine - text_integration_mode = true; - parser(t, value, arg3, arg4); - text_integration_mode = false; - } - // Otherwise it is foreign content - else { - insertForeignToken(t, value, arg3, arg4); - } - } - } - }; - - - /*** - * Tree building utility functions - */ - function insertComment(data) { - var parent = stack.top; - if (foster_parent_mode && isA(parent, tablesectionrowSet)) { - fosterParent(function(doc) { return doc.createComment(data); }); - } else { - // "If the adjusted insertion location is inside a template element, - // let it instead be inside the template element's template contents" - if (parent instanceof impl.HTMLTemplateElement) { - parent = parent.content; - } - parent._appendChild(parent.ownerDocument.createComment(data)); - } - } - - function insertText(s) { - var parent = stack.top; - if (foster_parent_mode && isA(parent, tablesectionrowSet)) { - fosterParent(function(doc) { return doc.createTextNode(s); }); - } else { - // "If the adjusted insertion location is inside a template element, - // let it instead be inside the template element's template contents" - if (parent instanceof impl.HTMLTemplateElement) { - parent = parent.content; - } - // "If there is a Text node immediately before the adjusted insertion - // location, then append data to that Text node's data." - var lastChild = parent.lastChild; - if (lastChild && lastChild.nodeType === Node.TEXT_NODE) { - lastChild.appendData(s); - } else { - parent._appendChild(parent.ownerDocument.createTextNode(s)); - } - } - } - - function createHTMLElt(doc, name, attrs) { - // Create the element this way, rather than with - // doc.createElement because createElement() does error - // checking on the element name that we need to avoid here. - var elt = html.createElement(doc, name, null); - - if (attrs) { - for(var i = 0, n = attrs.length; i < n; i++) { - // Use the _ version to avoid testing the validity - // of the attribute name - elt._setAttribute(attrs[i][0], attrs[i][1]); - } - } - // XXX - // If the element is a resettable form element, - // run its reset algorithm now - // XXX - // handle case where form-element-pointer is not null - return elt; - } - - // The in_table insertion mode turns on this flag, and that makes - // insertHTMLElement use the foster parenting algorithm for elements - // tags inside a table - var foster_parent_mode = false; - - function insertHTMLElement(name, attrs) { - var elt = insertElement(function(doc) { - return createHTMLElt(doc, name, attrs); - }); - - // XXX - // If this is a form element, set its form attribute property here - if (isA(elt, formassociatedSet)) { - elt._form = form_element_pointer; - } - - return elt; - } - - // Insert the element into the open element or foster parent it - function insertElement(eltFunc) { - var elt; - if (foster_parent_mode && isA(stack.top, tablesectionrowSet)) { - elt = fosterParent(eltFunc); - } - else if (stack.top instanceof impl.HTMLTemplateElement) { - // "If the adjusted insertion location is inside a template element, - // let it instead be inside the template element's template contents" - elt = eltFunc(stack.top.content.ownerDocument); - stack.top.content._appendChild(elt); - } else { - elt = eltFunc(stack.top.ownerDocument); - stack.top._appendChild(elt); - } - - stack.push(elt); - return elt; - } - - function insertForeignElement(name, attrs, ns) { - return insertElement(function(doc) { - // We need to prevent createElementNS from trying to parse `name` as a - // `qname`, so use an internal Document#_createElementNS() interface. - var elt = doc._createElementNS(name, ns, null); - if (attrs) { - for(var i = 0, n = attrs.length; i < n; i++) { - var attr = attrs[i]; - if (attr.length === 2) - elt._setAttribute(attr[0], attr[1]); - else { - elt._setAttributeNS(attr[2], attr[0], attr[1]); - } - } - } - return elt; - }); - } - - function lastElementOfType(type) { - for(var i = stack.elements.length-1; i >= 0; i--) { - if (stack.elements[i] instanceof type) { - return i; - } - } - return -1; - } - - function fosterParent(eltFunc) { - var parent, before, lastTable = -1, lastTemplate = -1, elt; - - lastTable = lastElementOfType(impl.HTMLTableElement); - lastTemplate = lastElementOfType(impl.HTMLTemplateElement); - - if (lastTemplate >= 0 && (lastTable < 0 || lastTemplate > lastTable)) { - parent = stack.elements[lastTemplate]; - } else if (lastTable >= 0) { - parent = stack.elements[lastTable].parentNode; - if (parent) { - before = stack.elements[lastTable]; - } else { - parent = stack.elements[lastTable - 1]; - } - } - if (!parent) parent = stack.elements[0]; // the `html` element. - - // "If the adjusted insertion location is inside a template element, - // let it instead be inside the template element's template contents" - if (parent instanceof impl.HTMLTemplateElement) { - parent = parent.content; - } - // Create element in the appropriate document. - elt = eltFunc(parent.ownerDocument); - - if (elt.nodeType === Node.TEXT_NODE) { - var prev; - if (before) prev = before.previousSibling; - else prev = parent.lastChild; - if (prev && prev.nodeType === Node.TEXT_NODE) { - prev.appendData(elt.data); - return elt; - } - } - if (before) - parent.insertBefore(elt, before); - else - parent._appendChild(elt); - return elt; - } - - - function resetInsertionMode() { - var last = false; - for(var i = stack.elements.length-1; i >= 0; i--) { - var node = stack.elements[i]; - if (i === 0) { - last = true; - if (fragment) { - node = fragmentContext; - } - } - if (node.namespaceURI === NAMESPACE.HTML) { - var tag = node.localName; - switch(tag) { - case "select": - for(var j = i; j > 0; ) { - var ancestor = stack.elements[--j]; - if (ancestor instanceof impl.HTMLTemplateElement) { - break; - } else if (ancestor instanceof impl.HTMLTableElement) { - parser = in_select_in_table_mode; - return; - } - } - parser = in_select_mode; - return; - case "tr": - parser = in_row_mode; - return; - case "tbody": - case "tfoot": - case "thead": - parser = in_table_body_mode; - return; - case "caption": - parser = in_caption_mode; - return; - case "colgroup": - parser = in_column_group_mode; - return; - case "table": - parser = in_table_mode; - return; - case "template": - parser = templateInsertionModes[templateInsertionModes.length-1]; - return; - case "body": - parser = in_body_mode; - return; - case "frameset": - parser = in_frameset_mode; - return; - case "html": - if (head_element_pointer === null) { - parser = before_head_mode; - } else { - parser = after_head_mode; - } - return; - default: - if (!last) { - if (tag === "head") { - parser = in_head_mode; - return; - } - if (tag === "td" || tag === "th") { - parser = in_cell_mode; - return; - } - } - } - } - if (last) { - parser = in_body_mode; - return; - } - } - } - - - function parseRawText(name, attrs) { - insertHTMLElement(name, attrs); - tokenizer = rawtext_state; - originalInsertionMode = parser; - parser = text_mode; - } - - function parseRCDATA(name, attrs) { - insertHTMLElement(name, attrs); - tokenizer = rcdata_state; - originalInsertionMode = parser; - parser = text_mode; - } - - // Make a copy of element i on the list of active formatting - // elements, using its original attributes, not current - // attributes (which may have been modified by a script) - function afeclone(doc, i) { - return { - elt: createHTMLElt(doc, afe.list[i].localName, afe.attrs[i]), - attrs: afe.attrs[i], - }; - } - - - function afereconstruct() { - if (afe.list.length === 0) return; - var entry = afe.list[afe.list.length-1]; - // If the last is a marker , do nothing - if (entry === afe.MARKER) return; - // Or if it is an open element, do nothing - if (stack.elements.lastIndexOf(entry) !== -1) return; - - // Loop backward through the list until we find a marker or an - // open element, and then move forward one from there. - for(var i = afe.list.length-2; i >= 0; i--) { - entry = afe.list[i]; - if (entry === afe.MARKER) break; - if (stack.elements.lastIndexOf(entry) !== -1) break; - } - - // Now loop forward, starting from the element after the current - // one, recreating formatting elements and pushing them back onto - // the list of open elements - for(i = i+1; i < afe.list.length; i++) { - var newelt = insertElement(function(doc) { return afeclone(doc, i).elt; }); - afe.list[i] = newelt; - } - } - - // Used by the adoptionAgency() function - var BOOKMARK = {localName:"BM"}; - - function adoptionAgency(tag) { - // If the current node is an HTML element whose tag name is subject, - // and the current node is not in the list of active formatting - // elements, then pop the current node off the stack of open - // elements and abort these steps. - if (isA(stack.top, tag) && afe.indexOf(stack.top) === -1) { - stack.pop(); - return true; // no more handling required - } - - // Let outer loop counter be zero. - var outer = 0; - - // Outer loop: If outer loop counter is greater than or - // equal to eight, then abort these steps. - while(outer < 8) { - // Increment outer loop counter by one. - outer++; - - // Let the formatting element be the last element in the list - // of active formatting elements that: is between the end of - // the list and the last scope marker in the list, if any, or - // the start of the list otherwise, and has the same tag name - // as the token. - var fmtelt = afe.findElementByTag(tag); - - // If there is no such node, then abort these steps and instead - // act as described in the "any other end tag" entry below. - if (!fmtelt) { - return false; // false means handle by the default case - } - - // Otherwise, if there is such a node, but that node is not in - // the stack of open elements, then this is a parse error; - // remove the element from the list, and abort these steps. - var index = stack.elements.lastIndexOf(fmtelt); - if (index === -1) { - afe.remove(fmtelt); - return true; // true means no more handling required - } - - // Otherwise, if there is such a node, and that node is also in - // the stack of open elements, but the element is not in scope, - // then this is a parse error; ignore the token, and abort - // these steps. - if (!stack.elementInScope(fmtelt)) { - return true; - } - - // Let the furthest block be the topmost node in the stack of - // open elements that is lower in the stack than the formatting - // element, and is an element in the special category. There - // might not be one. - var furthestblock = null, furthestblockindex; - for(var i = index+1; i < stack.elements.length; i++) { - if (isA(stack.elements[i], specialSet)) { - furthestblock = stack.elements[i]; - furthestblockindex = i; - break; - } - } - - // If there is no furthest block, then the UA must skip the - // subsequent steps and instead just pop all the nodes from the - // bottom of the stack of open elements, from the current node - // up to and including the formatting element, and remove the - // formatting element from the list of active formatting - // elements. - if (!furthestblock) { - stack.popElement(fmtelt); - afe.remove(fmtelt); - return true; - } - else { - // Let the common ancestor be the element immediately above - // the formatting element in the stack of open elements. - var ancestor = stack.elements[index-1]; - - // Let a bookmark note the position of the formatting - // element in the list of active formatting elements - // relative to the elements on either side of it in the - // list. - afe.insertAfter(fmtelt, BOOKMARK); - - // Let node and last node be the furthest block. - var node = furthestblock; - var lastnode = furthestblock; - var nodeindex = furthestblockindex; - var nodeafeindex; - - // Let inner loop counter be zero. - var inner = 0; - - while (true) { - - // Increment inner loop counter by one. - inner++; - - // Let node be the element immediately above node in - // the stack of open elements, or if node is no longer - // in the stack of open elements (e.g. because it got - // removed by this algorithm), the element that was - // immediately above node in the stack of open elements - // before node was removed. - node = stack.elements[--nodeindex]; - - // If node is the formatting element, then go - // to the next step in the overall algorithm. - if (node === fmtelt) break; - - // If the inner loop counter is greater than three and node - // is in the list of active formatting elements, then remove - // node from the list of active formatting elements. - nodeafeindex = afe.indexOf(node); - if (inner > 3 && nodeafeindex !== -1) { - afe.remove(node); - nodeafeindex = -1; - } - - // If node is not in the list of active formatting - // elements, then remove node from the stack of open - // elements and then go back to the step labeled inner - // loop. - if (nodeafeindex === -1) { - stack.removeElement(node); - continue; - } - - // Create an element for the token for which the - // element node was created with common ancestor as - // the intended parent, replace the entry for node - // in the list of active formatting elements with an - // entry for the new element, replace the entry for - // node in the stack of open elements with an entry for - // the new element, and let node be the new element. - var newelt = afeclone(ancestor.ownerDocument, nodeafeindex); - afe.replace(node, newelt.elt, newelt.attrs); - stack.elements[nodeindex] = newelt.elt; - node = newelt.elt; - - // If last node is the furthest block, then move the - // aforementioned bookmark to be immediately after the - // new node in the list of active formatting elements. - if (lastnode === furthestblock) { - afe.remove(BOOKMARK); - afe.insertAfter(newelt.elt, BOOKMARK); - } - - // Insert last node into node, first removing it from - // its previous parent node if any. - node._appendChild(lastnode); - - // Let last node be node. - lastnode = node; - } - - // If the common ancestor node is a table, tbody, tfoot, - // thead, or tr element, then, foster parent whatever last - // node ended up being in the previous step, first removing - // it from its previous parent node if any. - if (foster_parent_mode && isA(ancestor, tablesectionrowSet)) { - fosterParent(function() { return lastnode; }); - } - // Otherwise, append whatever last node ended up being in - // the previous step to the common ancestor node, first - // removing it from its previous parent node if any. - else if (ancestor instanceof impl.HTMLTemplateElement) { - ancestor.content._appendChild(lastnode); - } else { - ancestor._appendChild(lastnode); - } - - // Create an element for the token for which the - // formatting element was created, with furthest block - // as the intended parent. - var newelt2 = afeclone(furthestblock.ownerDocument, afe.indexOf(fmtelt)); - - // Take all of the child nodes of the furthest block and - // append them to the element created in the last step. - while(furthestblock.hasChildNodes()) { - newelt2.elt._appendChild(furthestblock.firstChild); - } - - // Append that new element to the furthest block. - furthestblock._appendChild(newelt2.elt); - - // Remove the formatting element from the list of active - // formatting elements, and insert the new element into the - // list of active formatting elements at the position of - // the aforementioned bookmark. - afe.remove(fmtelt); - afe.replace(BOOKMARK, newelt2.elt, newelt2.attrs); - - // Remove the formatting element from the stack of open - // elements, and insert the new element into the stack of - // open elements immediately below the position of the - // furthest block in that stack. - stack.removeElement(fmtelt); - var pos = stack.elements.lastIndexOf(furthestblock); - stack.elements.splice(pos+1, 0, newelt2.elt); - } - } - - return true; - } - - // We do this when we get /script in in_text_mode - function handleScriptEnd() { - // XXX: - // This is just a stub implementation right now and doesn't run scripts. - // Getting this method right involves the event loop, URL resolution - // script fetching etc. For now I just want to be able to parse - // documents and test the parser. - - //var script = stack.top; - stack.pop(); - parser = originalInsertionMode; - //script._prepare(); - return; - - // XXX: here is what this method is supposed to do - - // Provide a stable state. - - // Let script be the current node (which will be a script - // element). - - // Pop the current node off the stack of open elements. - - // Switch the insertion mode to the original insertion mode. - - // Let the old insertion point have the same value as the current - // insertion point. Let the insertion point be just before the - // next input character. - - // Increment the parser's script nesting level by one. - - // Prepare the script. This might cause some script to execute, - // which might cause new characters to be inserted into the - // tokenizer, and might cause the tokenizer to output more tokens, - // resulting in a reentrant invocation of the parser. - - // Decrement the parser's script nesting level by one. If the - // parser's script nesting level is zero, then set the parser - // pause flag to false. - - // Let the insertion point have the value of the old insertion - // point. (In other words, restore the insertion point to its - // previous value. This value might be the "undefined" value.) - - // At this stage, if there is a pending parsing-blocking script, - // then: - - // If the script nesting level is not zero: - - // Set the parser pause flag to true, and abort the processing - // of any nested invocations of the tokenizer, yielding - // control back to the caller. (Tokenization will resume when - // the caller returns to the "outer" tree construction stage.) - - // The tree construction stage of this particular parser is - // being called reentrantly, say from a call to - // document.write(). - - // Otherwise: - - // Run these steps: - - // Let the script be the pending parsing-blocking - // script. There is no longer a pending - // parsing-blocking script. - - // Block the tokenizer for this instance of the HTML - // parser, such that the event loop will not run tasks - // that invoke the tokenizer. - - // If the parser's Document has a style sheet that is - // blocking scripts or the script's "ready to be - // parser-executed" flag is not set: spin the event - // loop until the parser's Document has no style sheet - // that is blocking scripts and the script's "ready to - // be parser-executed" flag is set. - - // Unblock the tokenizer for this instance of the HTML - // parser, such that tasks that invoke the tokenizer - // can again be run. - - // Let the insertion point be just before the next - // input character. - - // Increment the parser's script nesting level by one - // (it should be zero before this step, so this sets - // it to one). - - // Execute the script. - - // Decrement the parser's script nesting level by - // one. If the parser's script nesting level is zero - // (which it always should be at this point), then set - // the parser pause flag to false. - - // Let the insertion point be undefined again. - - // If there is once again a pending parsing-blocking - // script, then repeat these steps from step 1. - - - } - - function stopParsing() { - // XXX This is just a temporary implementation to get the parser working. - // A full implementation involves scripts and events and the event loop. - - // Remove the link from document to parser. - // This is instead of "set the insertion point to undefined". - // It means that document.write() can't write into the doc anymore. - delete doc._parser; - - stack.elements.length = 0; // pop everything off - - // If there is a window object associated with the document - // then trigger an load event on it - if (doc.defaultView) { - doc.defaultView.dispatchEvent(new impl.Event("load",{})); - } - - } - - /**** - * Tokenizer states - */ - - /** - * This file was partially mechanically generated from - * http://www.whatwg.org/specs/web-apps/current-work/multipage/tokenization.html - * - * After mechanical conversion, it was further converted from - * prose to JS by hand, but the intent is that it is a very - * faithful rendering of the HTML tokenization spec in - * JavaScript. - * - * It is not a goal of this tokenizer to detect or report - * parse errors. - * - * XXX The tokenizer is supposed to work with straight UTF32 - * codepoints. But I don't think it has any dependencies on - * any character outside of the BMP so I think it is safe to - * pass it UTF16 characters. I don't think it will ever change - * state in the middle of a surrogate pair. - */ - - /* - * Each state is represented by a function. For most states, the - * scanner simply passes the next character (as an integer - * codepoint) to the current state function and automatically - * consumes the character. If the state function can't process - * the character it can call pushback() to push it back to the - * scanner. - * - * Some states require lookahead, though. If a state function has - * a lookahead property, then it is invoked differently. In this - * case, the scanner invokes the function with 3 arguments: 1) the - * next codepoint 2) a string of lookahead text 3) a boolean that - * is true if the lookahead goes all the way to the EOF. (XXX - * actually maybe this third is not necessary... the lookahead - * could just include \uFFFF?) - * - * If the lookahead property of a state function is an integer, it - * specifies the number of characters required. If it is a string, - * then the scanner will scan for that string and return all - * characters up to and including that sequence, or up to EOF. If - * the lookahead property is a regexp, then the scanner will match - * the regexp at the current point and return the matching string. - * - * States that require lookahead are responsible for explicitly - * consuming the characters they process. They do this by - * incrementing nextchar by the number of processed characters. - */ - function reconsume(c, new_state) { - tokenizer = new_state; - nextchar--; // pushback - } - - function data_state(c) { - switch(c) { - case 0x0026: // AMPERSAND - return_state = data_state; - tokenizer = character_reference_state; - break; - case 0x003C: // LESS-THAN SIGN - if (emitSimpleTag()) // Shortcut for

,

, etc. - break; - tokenizer = tag_open_state; - break; - case 0x0000: // NULL - // Usually null characters emitted by the tokenizer will be - // ignored by the tree builder, but sometimes they'll be - // converted to \uFFFD. I don't want to have the search every - // string emitted to replace NULs, so I'll set a flag - // if I've emitted a NUL. - textrun.push(c); - textIncludesNUL = true; - break; - case -1: // EOF - emitEOF(); - break; - default: - // Instead of just pushing a single character and then - // coming back to the very same place, lookahead and - // emit everything we can at once. - /*jshint -W030 */ - emitCharsWhile(DATATEXT) || textrun.push(c); - break; - } - } - - function rcdata_state(c) { - // Save the open tag so we can find a matching close tag - switch(c) { - case 0x0026: // AMPERSAND - return_state = rcdata_state; - tokenizer = character_reference_state; - break; - case 0x003C: // LESS-THAN SIGN - tokenizer = rcdata_less_than_sign_state; - break; - case 0x0000: // NULL - textrun.push(0xFFFD); // REPLACEMENT CHARACTER - textIncludesNUL = true; - break; - case -1: // EOF - emitEOF(); - break; - default: - textrun.push(c); - break; - } - } - - function rawtext_state(c) { - switch(c) { - case 0x003C: // LESS-THAN SIGN - tokenizer = rawtext_less_than_sign_state; - break; - case 0x0000: // NULL - textrun.push(0xFFFD); // REPLACEMENT CHARACTER - break; - case -1: // EOF - emitEOF(); - break; - default: - /*jshint -W030 */ - emitCharsWhile(RAWTEXT) || textrun.push(c); - break; - } - } - - function script_data_state(c) { - switch(c) { - case 0x003C: // LESS-THAN SIGN - tokenizer = script_data_less_than_sign_state; - break; - case 0x0000: // NULL - textrun.push(0xFFFD); // REPLACEMENT CHARACTER - break; - case -1: // EOF - emitEOF(); - break; - default: - /*jshint -W030 */ - emitCharsWhile(RAWTEXT) || textrun.push(c); - break; - } - } - - function plaintext_state(c) { - switch(c) { - case 0x0000: // NULL - textrun.push(0xFFFD); // REPLACEMENT CHARACTER - break; - case -1: // EOF - emitEOF(); - break; - default: - /*jshint -W030 */ - emitCharsWhile(PLAINTEXT) || textrun.push(c); - break; - } - } - - function tag_open_state(c) { - switch(c) { - case 0x0021: // EXCLAMATION MARK - tokenizer = markup_declaration_open_state; - break; - case 0x002F: // SOLIDUS - tokenizer = end_tag_open_state; - break; - case 0x0041: // [A-Z] - case 0x0042:case 0x0043:case 0x0044:case 0x0045:case 0x0046: - case 0x0047:case 0x0048:case 0x0049:case 0x004A:case 0x004B: - case 0x004C:case 0x004D:case 0x004E:case 0x004F:case 0x0050: - case 0x0051:case 0x0052:case 0x0053:case 0x0054:case 0x0055: - case 0x0056:case 0x0057:case 0x0058:case 0x0059:case 0x005A: - case 0x0061: // [a-z] - case 0x0062:case 0x0063:case 0x0064:case 0x0065:case 0x0066: - case 0x0067:case 0x0068:case 0x0069:case 0x006A:case 0x006B: - case 0x006C:case 0x006D:case 0x006E:case 0x006F:case 0x0070: - case 0x0071:case 0x0072:case 0x0073:case 0x0074:case 0x0075: - case 0x0076:case 0x0077:case 0x0078:case 0x0079:case 0x007A: - beginTagName(); - reconsume(c, tag_name_state); - break; - case 0x003F: // QUESTION MARK - reconsume(c, bogus_comment_state); - break; - default: - textrun.push(0x003C); // LESS-THAN SIGN - reconsume(c, data_state); - break; - } - } - - function end_tag_open_state(c) { - switch(c) { - case 0x0041: // [A-Z] - case 0x0042:case 0x0043:case 0x0044:case 0x0045:case 0x0046: - case 0x0047:case 0x0048:case 0x0049:case 0x004A:case 0x004B: - case 0x004C:case 0x004D:case 0x004E:case 0x004F:case 0x0050: - case 0x0051:case 0x0052:case 0x0053:case 0x0054:case 0x0055: - case 0x0056:case 0x0057:case 0x0058:case 0x0059:case 0x005A: - case 0x0061: // [a-z] - case 0x0062:case 0x0063:case 0x0064:case 0x0065:case 0x0066: - case 0x0067:case 0x0068:case 0x0069:case 0x006A:case 0x006B: - case 0x006C:case 0x006D:case 0x006E:case 0x006F:case 0x0070: - case 0x0071:case 0x0072:case 0x0073:case 0x0074:case 0x0075: - case 0x0076:case 0x0077:case 0x0078:case 0x0079:case 0x007A: - beginEndTagName(); - reconsume(c, tag_name_state); - break; - case 0x003E: // GREATER-THAN SIGN - tokenizer = data_state; - break; - case -1: // EOF - textrun.push(0x003C); // LESS-THAN SIGN - textrun.push(0x002F); // SOLIDUS - emitEOF(); - break; - default: - reconsume(c, bogus_comment_state); - break; - } - } - - function tag_name_state(c) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - tokenizer = before_attribute_name_state; - break; - case 0x002F: // SOLIDUS - tokenizer = self_closing_start_tag_state; - break; - case 0x003E: // GREATER-THAN SIGN - tokenizer = data_state; - emitTag(); - break; - case 0x0041: // [A-Z] - case 0x0042:case 0x0043:case 0x0044:case 0x0045:case 0x0046: - case 0x0047:case 0x0048:case 0x0049:case 0x004A:case 0x004B: - case 0x004C:case 0x004D:case 0x004E:case 0x004F:case 0x0050: - case 0x0051:case 0x0052:case 0x0053:case 0x0054:case 0x0055: - case 0x0056:case 0x0057:case 0x0058:case 0x0059:case 0x005A: - tagnamebuf += String.fromCharCode(c + 0x0020); - break; - case 0x0000: // NULL - tagnamebuf += String.fromCharCode(0xFFFD /* REPLACEMENT CHARACTER */); - break; - case -1: // EOF - emitEOF(); - break; - default: - tagnamebuf += getMatchingChars(TAGNAME); - break; - } - } - - function rcdata_less_than_sign_state(c) { - /* identical to the RAWTEXT less-than sign state, except s/RAWTEXT/RCDATA/g */ - if (c === 0x002F) { // SOLIDUS - beginTempBuf(); - tokenizer = rcdata_end_tag_open_state; - } - else { - textrun.push(0x003C); // LESS-THAN SIGN - reconsume(c, rcdata_state); - } - } - - function rcdata_end_tag_open_state(c) { - /* identical to the RAWTEXT (and Script data) end tag open state, except s/RAWTEXT/RCDATA/g */ - switch(c) { - case 0x0041: // [A-Z] - case 0x0042:case 0x0043:case 0x0044:case 0x0045:case 0x0046: - case 0x0047:case 0x0048:case 0x0049:case 0x004A:case 0x004B: - case 0x004C:case 0x004D:case 0x004E:case 0x004F:case 0x0050: - case 0x0051:case 0x0052:case 0x0053:case 0x0054:case 0x0055: - case 0x0056:case 0x0057:case 0x0058:case 0x0059:case 0x005A: - case 0x0061: // [a-z] - case 0x0062:case 0x0063:case 0x0064:case 0x0065:case 0x0066: - case 0x0067:case 0x0068:case 0x0069:case 0x006A:case 0x006B: - case 0x006C:case 0x006D:case 0x006E:case 0x006F:case 0x0070: - case 0x0071:case 0x0072:case 0x0073:case 0x0074:case 0x0075: - case 0x0076:case 0x0077:case 0x0078:case 0x0079:case 0x007A: - beginEndTagName(); - reconsume(c, rcdata_end_tag_name_state); - break; - default: - textrun.push(0x003C); // LESS-THAN SIGN - textrun.push(0x002F); // SOLIDUS - reconsume(c, rcdata_state); - break; - } - } - - function rcdata_end_tag_name_state(c) { - /* identical to the RAWTEXT (and Script data) end tag name state, except s/RAWTEXT/RCDATA/g */ - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - if (appropriateEndTag(tagnamebuf)) { - tokenizer = before_attribute_name_state; - return; - } - break; - case 0x002F: // SOLIDUS - if (appropriateEndTag(tagnamebuf)) { - tokenizer = self_closing_start_tag_state; - return; - } - break; - case 0x003E: // GREATER-THAN SIGN - if (appropriateEndTag(tagnamebuf)) { - tokenizer = data_state; - emitTag(); - return; - } - break; - case 0x0041: // [A-Z] - case 0x0042:case 0x0043:case 0x0044:case 0x0045:case 0x0046: - case 0x0047:case 0x0048:case 0x0049:case 0x004A:case 0x004B: - case 0x004C:case 0x004D:case 0x004E:case 0x004F:case 0x0050: - case 0x0051:case 0x0052:case 0x0053:case 0x0054:case 0x0055: - case 0x0056:case 0x0057:case 0x0058:case 0x0059:case 0x005A: - - tagnamebuf += String.fromCharCode(c + 0x0020); - tempbuf.push(c); - return; - case 0x0061: // [a-z] - case 0x0062:case 0x0063:case 0x0064:case 0x0065:case 0x0066: - case 0x0067:case 0x0068:case 0x0069:case 0x006A:case 0x006B: - case 0x006C:case 0x006D:case 0x006E:case 0x006F:case 0x0070: - case 0x0071:case 0x0072:case 0x0073:case 0x0074:case 0x0075: - case 0x0076:case 0x0077:case 0x0078:case 0x0079:case 0x007A: - - tagnamebuf += String.fromCharCode(c); - tempbuf.push(c); - return; - default: - break; - } - - // If we don't return in one of the cases above, then this was not - // an appropriately matching close tag, so back out by emitting all - // the characters as text - textrun.push(0x003C); // LESS-THAN SIGN - textrun.push(0x002F); // SOLIDUS - pushAll(textrun, tempbuf); - reconsume(c, rcdata_state); - } - - function rawtext_less_than_sign_state(c) { - /* identical to the RCDATA less-than sign state, except s/RCDATA/RAWTEXT/g - */ - if (c === 0x002F) { // SOLIDUS - beginTempBuf(); - tokenizer = rawtext_end_tag_open_state; - } - else { - textrun.push(0x003C); // LESS-THAN SIGN - reconsume(c, rawtext_state); - } - } - - function rawtext_end_tag_open_state(c) { - /* identical to the RCDATA (and Script data) end tag open state, except s/RCDATA/RAWTEXT/g */ - switch(c) { - case 0x0041: // [A-Z] - case 0x0042:case 0x0043:case 0x0044:case 0x0045:case 0x0046: - case 0x0047:case 0x0048:case 0x0049:case 0x004A:case 0x004B: - case 0x004C:case 0x004D:case 0x004E:case 0x004F:case 0x0050: - case 0x0051:case 0x0052:case 0x0053:case 0x0054:case 0x0055: - case 0x0056:case 0x0057:case 0x0058:case 0x0059:case 0x005A: - case 0x0061: // [a-z] - case 0x0062:case 0x0063:case 0x0064:case 0x0065:case 0x0066: - case 0x0067:case 0x0068:case 0x0069:case 0x006A:case 0x006B: - case 0x006C:case 0x006D:case 0x006E:case 0x006F:case 0x0070: - case 0x0071:case 0x0072:case 0x0073:case 0x0074:case 0x0075: - case 0x0076:case 0x0077:case 0x0078:case 0x0079:case 0x007A: - beginEndTagName(); - reconsume(c, rawtext_end_tag_name_state); - break; - default: - textrun.push(0x003C); // LESS-THAN SIGN - textrun.push(0x002F); // SOLIDUS - reconsume(c, rawtext_state); - break; - } - } - - function rawtext_end_tag_name_state(c) { - /* identical to the RCDATA (and Script data) end tag name state, except s/RCDATA/RAWTEXT/g */ - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - if (appropriateEndTag(tagnamebuf)) { - tokenizer = before_attribute_name_state; - return; - } - break; - case 0x002F: // SOLIDUS - if (appropriateEndTag(tagnamebuf)) { - tokenizer = self_closing_start_tag_state; - return; - } - break; - case 0x003E: // GREATER-THAN SIGN - if (appropriateEndTag(tagnamebuf)) { - tokenizer = data_state; - emitTag(); - return; - } - break; - case 0x0041: // [A-Z] - case 0x0042:case 0x0043:case 0x0044:case 0x0045:case 0x0046: - case 0x0047:case 0x0048:case 0x0049:case 0x004A:case 0x004B: - case 0x004C:case 0x004D:case 0x004E:case 0x004F:case 0x0050: - case 0x0051:case 0x0052:case 0x0053:case 0x0054:case 0x0055: - case 0x0056:case 0x0057:case 0x0058:case 0x0059:case 0x005A: - tagnamebuf += String.fromCharCode(c + 0x0020); - tempbuf.push(c); - return; - case 0x0061: // [a-z] - case 0x0062:case 0x0063:case 0x0064:case 0x0065:case 0x0066: - case 0x0067:case 0x0068:case 0x0069:case 0x006A:case 0x006B: - case 0x006C:case 0x006D:case 0x006E:case 0x006F:case 0x0070: - case 0x0071:case 0x0072:case 0x0073:case 0x0074:case 0x0075: - case 0x0076:case 0x0077:case 0x0078:case 0x0079:case 0x007A: - tagnamebuf += String.fromCharCode(c); - tempbuf.push(c); - return; - default: - break; - } - - // If we don't return in one of the cases above, then this was not - // an appropriately matching close tag, so back out by emitting all - // the characters as text - textrun.push(0x003C); // LESS-THAN SIGN - textrun.push(0x002F); // SOLIDUS - pushAll(textrun,tempbuf); - reconsume(c, rawtext_state); - } - - function script_data_less_than_sign_state(c) { - switch(c) { - case 0x002F: // SOLIDUS - beginTempBuf(); - tokenizer = script_data_end_tag_open_state; - break; - case 0x0021: // EXCLAMATION MARK - tokenizer = script_data_escape_start_state; - textrun.push(0x003C); // LESS-THAN SIGN - textrun.push(0x0021); // EXCLAMATION MARK - break; - default: - textrun.push(0x003C); // LESS-THAN SIGN - reconsume(c, script_data_state); - break; - } - } - - function script_data_end_tag_open_state(c) { - /* identical to the RCDATA (and RAWTEXT) end tag open state, except s/RCDATA/Script data/g */ - switch(c) { - case 0x0041: // [A-Z] - case 0x0042:case 0x0043:case 0x0044:case 0x0045:case 0x0046: - case 0x0047:case 0x0048:case 0x0049:case 0x004A:case 0x004B: - case 0x004C:case 0x004D:case 0x004E:case 0x004F:case 0x0050: - case 0x0051:case 0x0052:case 0x0053:case 0x0054:case 0x0055: - case 0x0056:case 0x0057:case 0x0058:case 0x0059:case 0x005A: - case 0x0061: // [a-z] - case 0x0062:case 0x0063:case 0x0064:case 0x0065:case 0x0066: - case 0x0067:case 0x0068:case 0x0069:case 0x006A:case 0x006B: - case 0x006C:case 0x006D:case 0x006E:case 0x006F:case 0x0070: - case 0x0071:case 0x0072:case 0x0073:case 0x0074:case 0x0075: - case 0x0076:case 0x0077:case 0x0078:case 0x0079:case 0x007A: - beginEndTagName(); - reconsume(c, script_data_end_tag_name_state); - break; - default: - textrun.push(0x003C); // LESS-THAN SIGN - textrun.push(0x002F); // SOLIDUS - reconsume(c, script_data_state); - break; - } - } - - function script_data_end_tag_name_state(c) { - /* identical to the RCDATA (and RAWTEXT) end tag name state, except s/RCDATA/Script data/g */ - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - if (appropriateEndTag(tagnamebuf)) { - tokenizer = before_attribute_name_state; - return; - } - break; - case 0x002F: // SOLIDUS - if (appropriateEndTag(tagnamebuf)) { - tokenizer = self_closing_start_tag_state; - return; - } - break; - case 0x003E: // GREATER-THAN SIGN - if (appropriateEndTag(tagnamebuf)) { - tokenizer = data_state; - emitTag(); - return; - } - break; - case 0x0041: // [A-Z] - case 0x0042:case 0x0043:case 0x0044:case 0x0045:case 0x0046: - case 0x0047:case 0x0048:case 0x0049:case 0x004A:case 0x004B: - case 0x004C:case 0x004D:case 0x004E:case 0x004F:case 0x0050: - case 0x0051:case 0x0052:case 0x0053:case 0x0054:case 0x0055: - case 0x0056:case 0x0057:case 0x0058:case 0x0059:case 0x005A: - - tagnamebuf += String.fromCharCode(c + 0x0020); - tempbuf.push(c); - return; - case 0x0061: // [a-z] - case 0x0062:case 0x0063:case 0x0064:case 0x0065:case 0x0066: - case 0x0067:case 0x0068:case 0x0069:case 0x006A:case 0x006B: - case 0x006C:case 0x006D:case 0x006E:case 0x006F:case 0x0070: - case 0x0071:case 0x0072:case 0x0073:case 0x0074:case 0x0075: - case 0x0076:case 0x0077:case 0x0078:case 0x0079:case 0x007A: - - tagnamebuf += String.fromCharCode(c); - tempbuf.push(c); - return; - default: - break; - } - - // If we don't return in one of the cases above, then this was not - // an appropriately matching close tag, so back out by emitting all - // the characters as text - textrun.push(0x003C); // LESS-THAN SIGN - textrun.push(0x002F); // SOLIDUS - pushAll(textrun,tempbuf); - reconsume(c, script_data_state); - } - - function script_data_escape_start_state(c) { - if (c === 0x002D) { // HYPHEN-MINUS - tokenizer = script_data_escape_start_dash_state; - textrun.push(0x002D); // HYPHEN-MINUS - } - else { - reconsume(c, script_data_state); - } - } - - function script_data_escape_start_dash_state(c) { - if (c === 0x002D) { // HYPHEN-MINUS - tokenizer = script_data_escaped_dash_dash_state; - textrun.push(0x002D); // HYPHEN-MINUS - } - else { - reconsume(c, script_data_state); - } - } - - function script_data_escaped_state(c) { - switch(c) { - case 0x002D: // HYPHEN-MINUS - tokenizer = script_data_escaped_dash_state; - textrun.push(0x002D); // HYPHEN-MINUS - break; - case 0x003C: // LESS-THAN SIGN - tokenizer = script_data_escaped_less_than_sign_state; - break; - case 0x0000: // NULL - textrun.push(0xFFFD); // REPLACEMENT CHARACTER - break; - case -1: // EOF - emitEOF(); - break; - default: - textrun.push(c); - break; - } - } - - function script_data_escaped_dash_state(c) { - switch(c) { - case 0x002D: // HYPHEN-MINUS - tokenizer = script_data_escaped_dash_dash_state; - textrun.push(0x002D); // HYPHEN-MINUS - break; - case 0x003C: // LESS-THAN SIGN - tokenizer = script_data_escaped_less_than_sign_state; - break; - case 0x0000: // NULL - tokenizer = script_data_escaped_state; - textrun.push(0xFFFD); // REPLACEMENT CHARACTER - break; - case -1: // EOF - emitEOF(); - break; - default: - tokenizer = script_data_escaped_state; - textrun.push(c); - break; - } - } - - function script_data_escaped_dash_dash_state(c) { - switch(c) { - case 0x002D: // HYPHEN-MINUS - textrun.push(0x002D); // HYPHEN-MINUS - break; - case 0x003C: // LESS-THAN SIGN - tokenizer = script_data_escaped_less_than_sign_state; - break; - case 0x003E: // GREATER-THAN SIGN - tokenizer = script_data_state; - textrun.push(0x003E); // GREATER-THAN SIGN - break; - case 0x0000: // NULL - tokenizer = script_data_escaped_state; - textrun.push(0xFFFD); // REPLACEMENT CHARACTER - break; - case -1: // EOF - emitEOF(); - break; - default: - tokenizer = script_data_escaped_state; - textrun.push(c); - break; - } - } - - function script_data_escaped_less_than_sign_state(c) { - switch(c) { - case 0x002F: // SOLIDUS - beginTempBuf(); - tokenizer = script_data_escaped_end_tag_open_state; - break; - case 0x0041: // [A-Z] - case 0x0042:case 0x0043:case 0x0044:case 0x0045:case 0x0046: - case 0x0047:case 0x0048:case 0x0049:case 0x004A:case 0x004B: - case 0x004C:case 0x004D:case 0x004E:case 0x004F:case 0x0050: - case 0x0051:case 0x0052:case 0x0053:case 0x0054:case 0x0055: - case 0x0056:case 0x0057:case 0x0058:case 0x0059:case 0x005A: - case 0x0061: // [a-z] - case 0x0062:case 0x0063:case 0x0064:case 0x0065:case 0x0066: - case 0x0067:case 0x0068:case 0x0069:case 0x006A:case 0x006B: - case 0x006C:case 0x006D:case 0x006E:case 0x006F:case 0x0070: - case 0x0071:case 0x0072:case 0x0073:case 0x0074:case 0x0075: - case 0x0076:case 0x0077:case 0x0078:case 0x0079:case 0x007A: - beginTempBuf(); - textrun.push(0x003C); // LESS-THAN SIGN - reconsume(c, script_data_double_escape_start_state); - break; - default: - textrun.push(0x003C); // LESS-THAN SIGN - reconsume(c, script_data_escaped_state); - break; - } - } - - function script_data_escaped_end_tag_open_state(c) { - switch(c) { - case 0x0041: // [A-Z] - case 0x0042:case 0x0043:case 0x0044:case 0x0045:case 0x0046: - case 0x0047:case 0x0048:case 0x0049:case 0x004A:case 0x004B: - case 0x004C:case 0x004D:case 0x004E:case 0x004F:case 0x0050: - case 0x0051:case 0x0052:case 0x0053:case 0x0054:case 0x0055: - case 0x0056:case 0x0057:case 0x0058:case 0x0059:case 0x005A: - case 0x0061: // [a-z] - case 0x0062:case 0x0063:case 0x0064:case 0x0065:case 0x0066: - case 0x0067:case 0x0068:case 0x0069:case 0x006A:case 0x006B: - case 0x006C:case 0x006D:case 0x006E:case 0x006F:case 0x0070: - case 0x0071:case 0x0072:case 0x0073:case 0x0074:case 0x0075: - case 0x0076:case 0x0077:case 0x0078:case 0x0079:case 0x007A: - beginEndTagName(); - reconsume(c, script_data_escaped_end_tag_name_state); - break; - default: - textrun.push(0x003C); // LESS-THAN SIGN - textrun.push(0x002F); // SOLIDUS - reconsume(c, script_data_escaped_state); - break; - } - } - - function script_data_escaped_end_tag_name_state(c) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - if (appropriateEndTag(tagnamebuf)) { - tokenizer = before_attribute_name_state; - return; - } - break; - case 0x002F: // SOLIDUS - if (appropriateEndTag(tagnamebuf)) { - tokenizer = self_closing_start_tag_state; - return; - } - break; - case 0x003E: // GREATER-THAN SIGN - if (appropriateEndTag(tagnamebuf)) { - tokenizer = data_state; - emitTag(); - return; - } - break; - case 0x0041: // [A-Z] - case 0x0042:case 0x0043:case 0x0044:case 0x0045:case 0x0046: - case 0x0047:case 0x0048:case 0x0049:case 0x004A:case 0x004B: - case 0x004C:case 0x004D:case 0x004E:case 0x004F:case 0x0050: - case 0x0051:case 0x0052:case 0x0053:case 0x0054:case 0x0055: - case 0x0056:case 0x0057:case 0x0058:case 0x0059:case 0x005A: - tagnamebuf += String.fromCharCode(c + 0x0020); - tempbuf.push(c); - return; - case 0x0061: // [a-z] - case 0x0062:case 0x0063:case 0x0064:case 0x0065:case 0x0066: - case 0x0067:case 0x0068:case 0x0069:case 0x006A:case 0x006B: - case 0x006C:case 0x006D:case 0x006E:case 0x006F:case 0x0070: - case 0x0071:case 0x0072:case 0x0073:case 0x0074:case 0x0075: - case 0x0076:case 0x0077:case 0x0078:case 0x0079:case 0x007A: - tagnamebuf += String.fromCharCode(c); - tempbuf.push(c); - return; - default: - break; - } - - // We get here in the default case, and if the closing tagname - // is not an appropriate tagname. - textrun.push(0x003C); // LESS-THAN SIGN - textrun.push(0x002F); // SOLIDUS - pushAll(textrun,tempbuf); - reconsume(c, script_data_escaped_state); - } - - function script_data_double_escape_start_state(c) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - case 0x002F: // SOLIDUS - case 0x003E: // GREATER-THAN SIGN - if (buf2str(tempbuf) === "script") { - tokenizer = script_data_double_escaped_state; - } - else { - tokenizer = script_data_escaped_state; - } - textrun.push(c); - break; - case 0x0041: // [A-Z] - case 0x0042:case 0x0043:case 0x0044:case 0x0045:case 0x0046: - case 0x0047:case 0x0048:case 0x0049:case 0x004A:case 0x004B: - case 0x004C:case 0x004D:case 0x004E:case 0x004F:case 0x0050: - case 0x0051:case 0x0052:case 0x0053:case 0x0054:case 0x0055: - case 0x0056:case 0x0057:case 0x0058:case 0x0059:case 0x005A: - tempbuf.push(c + 0x0020); - textrun.push(c); - break; - case 0x0061: // [a-z] - case 0x0062:case 0x0063:case 0x0064:case 0x0065:case 0x0066: - case 0x0067:case 0x0068:case 0x0069:case 0x006A:case 0x006B: - case 0x006C:case 0x006D:case 0x006E:case 0x006F:case 0x0070: - case 0x0071:case 0x0072:case 0x0073:case 0x0074:case 0x0075: - case 0x0076:case 0x0077:case 0x0078:case 0x0079:case 0x007A: - tempbuf.push(c); - textrun.push(c); - break; - default: - reconsume(c, script_data_escaped_state); - break; - } - } - - function script_data_double_escaped_state(c) { - switch(c) { - case 0x002D: // HYPHEN-MINUS - tokenizer = script_data_double_escaped_dash_state; - textrun.push(0x002D); // HYPHEN-MINUS - break; - case 0x003C: // LESS-THAN SIGN - tokenizer = script_data_double_escaped_less_than_sign_state; - textrun.push(0x003C); // LESS-THAN SIGN - break; - case 0x0000: // NULL - textrun.push(0xFFFD); // REPLACEMENT CHARACTER - break; - case -1: // EOF - emitEOF(); - break; - default: - textrun.push(c); - break; - } - } - - function script_data_double_escaped_dash_state(c) { - switch(c) { - case 0x002D: // HYPHEN-MINUS - tokenizer = script_data_double_escaped_dash_dash_state; - textrun.push(0x002D); // HYPHEN-MINUS - break; - case 0x003C: // LESS-THAN SIGN - tokenizer = script_data_double_escaped_less_than_sign_state; - textrun.push(0x003C); // LESS-THAN SIGN - break; - case 0x0000: // NULL - tokenizer = script_data_double_escaped_state; - textrun.push(0xFFFD); // REPLACEMENT CHARACTER - break; - case -1: // EOF - emitEOF(); - break; - default: - tokenizer = script_data_double_escaped_state; - textrun.push(c); - break; - } - } - - function script_data_double_escaped_dash_dash_state(c) { - switch(c) { - case 0x002D: // HYPHEN-MINUS - textrun.push(0x002D); // HYPHEN-MINUS - break; - case 0x003C: // LESS-THAN SIGN - tokenizer = script_data_double_escaped_less_than_sign_state; - textrun.push(0x003C); // LESS-THAN SIGN - break; - case 0x003E: // GREATER-THAN SIGN - tokenizer = script_data_state; - textrun.push(0x003E); // GREATER-THAN SIGN - break; - case 0x0000: // NULL - tokenizer = script_data_double_escaped_state; - textrun.push(0xFFFD); // REPLACEMENT CHARACTER - break; - case -1: // EOF - emitEOF(); - break; - default: - tokenizer = script_data_double_escaped_state; - textrun.push(c); - break; - } - } - - function script_data_double_escaped_less_than_sign_state(c) { - if (c === 0x002F) { // SOLIDUS - beginTempBuf(); - tokenizer = script_data_double_escape_end_state; - textrun.push(0x002F); // SOLIDUS - } - else { - reconsume(c, script_data_double_escaped_state); - } - } - - function script_data_double_escape_end_state(c) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - case 0x002F: // SOLIDUS - case 0x003E: // GREATER-THAN SIGN - if (buf2str(tempbuf) === "script") { - tokenizer = script_data_escaped_state; - } - else { - tokenizer = script_data_double_escaped_state; - } - textrun.push(c); - break; - case 0x0041: // [A-Z] - case 0x0042:case 0x0043:case 0x0044:case 0x0045:case 0x0046: - case 0x0047:case 0x0048:case 0x0049:case 0x004A:case 0x004B: - case 0x004C:case 0x004D:case 0x004E:case 0x004F:case 0x0050: - case 0x0051:case 0x0052:case 0x0053:case 0x0054:case 0x0055: - case 0x0056:case 0x0057:case 0x0058:case 0x0059:case 0x005A: - tempbuf.push(c + 0x0020); - textrun.push(c); - break; - case 0x0061: // [a-z] - case 0x0062:case 0x0063:case 0x0064:case 0x0065:case 0x0066: - case 0x0067:case 0x0068:case 0x0069:case 0x006A:case 0x006B: - case 0x006C:case 0x006D:case 0x006E:case 0x006F:case 0x0070: - case 0x0071:case 0x0072:case 0x0073:case 0x0074:case 0x0075: - case 0x0076:case 0x0077:case 0x0078:case 0x0079:case 0x007A: - tempbuf.push(c); - textrun.push(c); - break; - default: - reconsume(c, script_data_double_escaped_state); - break; - } - } - - function before_attribute_name_state(c) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - /* Ignore the character. */ - break; - // For SOLIDUS, GREATER-THAN SIGN, and EOF, spec says "reconsume in - // the after attribute name state", but in our implementation that - // state always has an active attribute in attrnamebuf. Just clone - // the rules here, without the addAttribute business. - case 0x002F: // SOLIDUS - tokenizer = self_closing_start_tag_state; - break; - case 0x003E: // GREATER-THAN SIGN - tokenizer = data_state; - emitTag(); - break; - case -1: // EOF - emitEOF(); - break; - case 0x003D: // EQUALS SIGN - beginAttrName(); - attrnamebuf += String.fromCharCode(c); - tokenizer = attribute_name_state; - break; - default: - if (handleSimpleAttribute()) break; - beginAttrName(); - reconsume(c, attribute_name_state); - break; - } - } - - // beginAttrName() must have been called before this point - // There is an active attribute in attrnamebuf (but not attrvaluebuf) - function attribute_name_state(c) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - case 0x002F: // SOLIDUS - case 0x003E: // GREATER-THAN SIGN - case -1: // EOF - reconsume(c, after_attribute_name_state); - break; - case 0x003D: // EQUALS SIGN - tokenizer = before_attribute_value_state; - break; - case 0x0041: // [A-Z] - case 0x0042:case 0x0043:case 0x0044:case 0x0045:case 0x0046: - case 0x0047:case 0x0048:case 0x0049:case 0x004A:case 0x004B: - case 0x004C:case 0x004D:case 0x004E:case 0x004F:case 0x0050: - case 0x0051:case 0x0052:case 0x0053:case 0x0054:case 0x0055: - case 0x0056:case 0x0057:case 0x0058:case 0x0059:case 0x005A: - attrnamebuf += String.fromCharCode(c + 0x0020); - break; - case 0x0000: // NULL - attrnamebuf += String.fromCharCode(0xFFFD /* REPLACEMENT CHARACTER */); - break; - case 0x0022: // QUOTATION MARK - case 0x0027: // APOSTROPHE - case 0x003C: // LESS-THAN SIGN - /* falls through */ - default: - attrnamebuf += getMatchingChars(ATTRNAME); - break; - } - } - - // There is an active attribute in attrnamebuf, but not yet in attrvaluebuf. - function after_attribute_name_state(c) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - /* Ignore the character. */ - break; - case 0x002F: // SOLIDUS - // Keep in sync with before_attribute_name_state. - addAttribute(attrnamebuf); - tokenizer = self_closing_start_tag_state; - break; - case 0x003D: // EQUALS SIGN - tokenizer = before_attribute_value_state; - break; - case 0x003E: // GREATER-THAN SIGN - // Keep in sync with before_attribute_name_state. - tokenizer = data_state; - addAttribute(attrnamebuf); - emitTag(); - break; - case -1: // EOF - // Keep in sync with before_attribute_name_state. - addAttribute(attrnamebuf); - emitEOF(); - break; - default: - addAttribute(attrnamebuf); - beginAttrName(); - reconsume(c, attribute_name_state); - break; - } - } - - function before_attribute_value_state(c) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - /* Ignore the character. */ - break; - case 0x0022: // QUOTATION MARK - beginAttrValue(); - tokenizer = attribute_value_double_quoted_state; - break; - case 0x0027: // APOSTROPHE - beginAttrValue(); - tokenizer = attribute_value_single_quoted_state; - break; - case 0x003E: // GREATER-THAN SIGN - /* falls through */ - default: - beginAttrValue(); - reconsume(c, attribute_value_unquoted_state); - break; - } - } - - function attribute_value_double_quoted_state(c) { - switch(c) { - case 0x0022: // QUOTATION MARK - addAttribute(attrnamebuf, attrvaluebuf); - tokenizer = after_attribute_value_quoted_state; - break; - case 0x0026: // AMPERSAND - return_state = attribute_value_double_quoted_state; - tokenizer = character_reference_state; - break; - case 0x0000: // NULL - attrvaluebuf += String.fromCharCode(0xFFFD /* REPLACEMENT CHARACTER */); - break; - case -1: // EOF - emitEOF(); - break; - case 0x000A: // LF - // this could be a converted \r, so don't use getMatchingChars - attrvaluebuf += String.fromCharCode(c); - break; - default: - attrvaluebuf += getMatchingChars(DBLQUOTEATTRVAL); - break; - } - } - - function attribute_value_single_quoted_state(c) { - switch(c) { - case 0x0027: // APOSTROPHE - addAttribute(attrnamebuf, attrvaluebuf); - tokenizer = after_attribute_value_quoted_state; - break; - case 0x0026: // AMPERSAND - return_state = attribute_value_single_quoted_state; - tokenizer = character_reference_state; - break; - case 0x0000: // NULL - attrvaluebuf += String.fromCharCode(0xFFFD /* REPLACEMENT CHARACTER */); - break; - case -1: // EOF - emitEOF(); - break; - case 0x000A: // LF - // this could be a converted \r, so don't use getMatchingChars - attrvaluebuf += String.fromCharCode(c); - break; - default: - attrvaluebuf += getMatchingChars(SINGLEQUOTEATTRVAL); - break; - } - } - - function attribute_value_unquoted_state(c) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - addAttribute(attrnamebuf, attrvaluebuf); - tokenizer = before_attribute_name_state; - break; - case 0x0026: // AMPERSAND - return_state = attribute_value_unquoted_state; - tokenizer = character_reference_state; - break; - case 0x003E: // GREATER-THAN SIGN - addAttribute(attrnamebuf, attrvaluebuf); - tokenizer = data_state; - emitTag(); - break; - case 0x0000: // NULL - attrvaluebuf += String.fromCharCode(0xFFFD /* REPLACEMENT CHARACTER */); - break; - case -1: // EOF - nextchar--; // pushback - tokenizer = data_state; - break; - case 0x0022: // QUOTATION MARK - case 0x0027: // APOSTROPHE - case 0x003C: // LESS-THAN SIGN - case 0x003D: // EQUALS SIGN - case 0x0060: // GRAVE ACCENT - /* falls through */ - default: - attrvaluebuf += getMatchingChars(UNQUOTEDATTRVAL); - break; - } - } - - function after_attribute_value_quoted_state(c) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - tokenizer = before_attribute_name_state; - break; - case 0x002F: // SOLIDUS - tokenizer = self_closing_start_tag_state; - break; - case 0x003E: // GREATER-THAN SIGN - tokenizer = data_state; - emitTag(); - break; - case -1: // EOF - emitEOF(); - break; - default: - reconsume(c, before_attribute_name_state); - break; - } - } - - function self_closing_start_tag_state(c) { - switch(c) { - case 0x003E: // GREATER-THAN SIGN - // Set the self-closing flag of the current tag token. - tokenizer = data_state; - emitSelfClosingTag(true); - break; - case -1: // EOF - emitEOF(); - break; - default: - reconsume(c, before_attribute_name_state); - break; - } - } - - function bogus_comment_state(c, lookahead, eof) { - var len = lookahead.length; - - if (eof) { - nextchar += len-1; // don't consume the eof - } - else { - nextchar += len; - } - - var comment = lookahead.substring(0, len-1); - - comment = comment.replace(/\u0000/g,"\uFFFD"); - comment = comment.replace(/\u000D\u000A/g,"\u000A"); - comment = comment.replace(/\u000D/g,"\u000A"); - - insertToken(COMMENT, comment); - tokenizer = data_state; - } - bogus_comment_state.lookahead = ">"; - - function markup_declaration_open_state(c, lookahead, eof) { - if (lookahead[0] === "-" && lookahead[1] === "-") { - nextchar += 2; - beginComment(); - tokenizer = comment_start_state; - return; - } - - if (lookahead.toUpperCase() === "DOCTYPE") { - nextchar += 7; - tokenizer = doctype_state; - } - else if (lookahead === "[CDATA[" && cdataAllowed()) { - nextchar += 7; - tokenizer = cdata_section_state; - } - else { - tokenizer = bogus_comment_state; - } - } - markup_declaration_open_state.lookahead = 7; - - function comment_start_state(c) { - beginComment(); - switch(c) { - case 0x002D: // HYPHEN-MINUS - tokenizer = comment_start_dash_state; - break; - case 0x003E: // GREATER-THAN SIGN - tokenizer = data_state; - insertToken(COMMENT, buf2str(commentbuf)); - break; /* see comment in comment end state */ - default: - reconsume(c, comment_state); - break; - } - } - - function comment_start_dash_state(c) { - switch(c) { - case 0x002D: // HYPHEN-MINUS - tokenizer = comment_end_state; - break; - case 0x003E: // GREATER-THAN SIGN - tokenizer = data_state; - insertToken(COMMENT, buf2str(commentbuf)); - break; - case -1: // EOF - insertToken(COMMENT, buf2str(commentbuf)); - emitEOF(); - break; /* see comment in comment end state */ - default: - commentbuf.push(0x002D /* HYPHEN-MINUS */); - reconsume(c, comment_state); - break; - } - } - - function comment_state(c) { - switch(c) { - case 0x003C: // LESS-THAN SIGN - commentbuf.push(c); - tokenizer = comment_less_than_sign_state; - break; - case 0x002D: // HYPHEN-MINUS - tokenizer = comment_end_dash_state; - break; - case 0x0000: // NULL - commentbuf.push(0xFFFD /* REPLACEMENT CHARACTER */); - break; - case -1: // EOF - insertToken(COMMENT, buf2str(commentbuf)); - emitEOF(); - break; /* see comment in comment end state */ - default: - commentbuf.push(c); - break; - } - } - - function comment_less_than_sign_state(c) { - switch(c) { - case 0x0021: // EXCLAMATION MARK - commentbuf.push(c); - tokenizer = comment_less_than_sign_bang_state; - break; - case 0x003C: // LESS-THAN SIGN - commentbuf.push(c); - break; - default: - reconsume(c, comment_state); - break; - } - } - - function comment_less_than_sign_bang_state(c) { - switch(c) { - case 0x002D: // HYPHEN-MINUS - tokenizer = comment_less_than_sign_bang_dash_state; - break; - default: - reconsume(c, comment_state); - break; - } - } - - function comment_less_than_sign_bang_dash_state(c) { - switch(c) { - case 0x002D: // HYPHEN-MINUS - tokenizer = comment_less_than_sign_bang_dash_dash_state; - break; - default: - reconsume(c, comment_end_dash_state); - break; - } - } - - function comment_less_than_sign_bang_dash_dash_state(c) { - switch(c) { - case 0x003E: // GREATER-THAN SIGN - case -1: // EOF - reconsume(c, comment_end_state); - break; - default: - // parse error - reconsume(c, comment_end_state); - break; - } - } - - function comment_end_dash_state(c) { - switch(c) { - case 0x002D: // HYPHEN-MINUS - tokenizer = comment_end_state; - break; - case -1: // EOF - insertToken(COMMENT, buf2str(commentbuf)); - emitEOF(); - break; /* see comment in comment end state */ - default: - commentbuf.push(0x002D /* HYPHEN-MINUS */); - reconsume(c, comment_state); - break; - } - } - - function comment_end_state(c) { - switch(c) { - case 0x003E: // GREATER-THAN SIGN - tokenizer = data_state; - insertToken(COMMENT, buf2str(commentbuf)); - break; - case 0x0021: // EXCLAMATION MARK - tokenizer = comment_end_bang_state; - break; - case 0x002D: // HYPHEN-MINUS - commentbuf.push(0x002D); - break; - case -1: // EOF - insertToken(COMMENT, buf2str(commentbuf)); - emitEOF(); - break; /* For security reasons: otherwise, hostile user could put a script in a comment e.g. in a blog comment and then DOS the server so that the end tag isn't read, and then the commented script tag would be treated as live code */ - default: - commentbuf.push(0x002D); - commentbuf.push(0x002D); - reconsume(c, comment_state); - break; - } - } - - function comment_end_bang_state(c) { - switch(c) { - case 0x002D: // HYPHEN-MINUS - commentbuf.push(0x002D); - commentbuf.push(0x002D); - commentbuf.push(0x0021); - tokenizer = comment_end_dash_state; - break; - case 0x003E: // GREATER-THAN SIGN - tokenizer = data_state; - insertToken(COMMENT, buf2str(commentbuf)); - break; - case -1: // EOF - insertToken(COMMENT, buf2str(commentbuf)); - emitEOF(); - break; /* see comment in comment end state */ - default: - commentbuf.push(0x002D); - commentbuf.push(0x002D); - commentbuf.push(0x0021); - reconsume(c, comment_state); - break; - } - } - - function doctype_state(c) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - tokenizer = before_doctype_name_state; - break; - case -1: // EOF - beginDoctype(); - forcequirks(); - emitDoctype(); - emitEOF(); - break; - default: - reconsume(c, before_doctype_name_state); - break; - } - } - - function before_doctype_name_state(c) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - /* Ignore the character. */ - break; - case 0x0041: // [A-Z] - case 0x0042:case 0x0043:case 0x0044:case 0x0045:case 0x0046: - case 0x0047:case 0x0048:case 0x0049:case 0x004A:case 0x004B: - case 0x004C:case 0x004D:case 0x004E:case 0x004F:case 0x0050: - case 0x0051:case 0x0052:case 0x0053:case 0x0054:case 0x0055: - case 0x0056:case 0x0057:case 0x0058:case 0x0059:case 0x005A: - beginDoctype(); - doctypenamebuf.push(c + 0x0020); - tokenizer = doctype_name_state; - break; - case 0x0000: // NULL - beginDoctype(); - doctypenamebuf.push(0xFFFD); - tokenizer = doctype_name_state; - break; - case 0x003E: // GREATER-THAN SIGN - beginDoctype(); - forcequirks(); - tokenizer = data_state; - emitDoctype(); - break; - case -1: // EOF - beginDoctype(); - forcequirks(); - emitDoctype(); - emitEOF(); - break; - default: - beginDoctype(); - doctypenamebuf.push(c); - tokenizer = doctype_name_state; - break; - } - } - - function doctype_name_state(c) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - tokenizer = after_doctype_name_state; - break; - case 0x003E: // GREATER-THAN SIGN - tokenizer = data_state; - emitDoctype(); - break; - case 0x0041: // [A-Z] - case 0x0042:case 0x0043:case 0x0044:case 0x0045:case 0x0046: - case 0x0047:case 0x0048:case 0x0049:case 0x004A:case 0x004B: - case 0x004C:case 0x004D:case 0x004E:case 0x004F:case 0x0050: - case 0x0051:case 0x0052:case 0x0053:case 0x0054:case 0x0055: - case 0x0056:case 0x0057:case 0x0058:case 0x0059:case 0x005A: - doctypenamebuf.push(c + 0x0020); - break; - case 0x0000: // NULL - doctypenamebuf.push(0xFFFD /* REPLACEMENT CHARACTER */); - break; - case -1: // EOF - forcequirks(); - emitDoctype(); - emitEOF(); - break; - default: - doctypenamebuf.push(c); - break; - } - } - - function after_doctype_name_state(c, lookahead, eof) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - /* Ignore the character. */ - nextchar += 1; - break; - case 0x003E: // GREATER-THAN SIGN - tokenizer = data_state; - nextchar += 1; - emitDoctype(); - break; - case -1: // EOF - forcequirks(); - emitDoctype(); - emitEOF(); - break; - default: - lookahead = lookahead.toUpperCase(); - if (lookahead === "PUBLIC") { - nextchar += 6; - tokenizer = after_doctype_public_keyword_state; - } - else if (lookahead === "SYSTEM") { - nextchar += 6; - tokenizer = after_doctype_system_keyword_state; - } - else { - forcequirks(); - tokenizer = bogus_doctype_state; - } - break; - } - } - after_doctype_name_state.lookahead = 6; - - function after_doctype_public_keyword_state(c) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - tokenizer = before_doctype_public_identifier_state; - break; - case 0x0022: // QUOTATION MARK - beginDoctypePublicId(); - tokenizer = doctype_public_identifier_double_quoted_state; - break; - case 0x0027: // APOSTROPHE - beginDoctypePublicId(); - tokenizer = doctype_public_identifier_single_quoted_state; - break; - case 0x003E: // GREATER-THAN SIGN - forcequirks(); - tokenizer = data_state; - emitDoctype(); - break; - case -1: // EOF - forcequirks(); - emitDoctype(); - emitEOF(); - break; - default: - forcequirks(); - tokenizer = bogus_doctype_state; - break; - } - } - - function before_doctype_public_identifier_state(c) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - /* Ignore the character. */ - break; - case 0x0022: // QUOTATION MARK - beginDoctypePublicId(); - tokenizer = doctype_public_identifier_double_quoted_state; - break; - case 0x0027: // APOSTROPHE - beginDoctypePublicId(); - tokenizer = doctype_public_identifier_single_quoted_state; - break; - case 0x003E: // GREATER-THAN SIGN - forcequirks(); - tokenizer = data_state; - emitDoctype(); - break; - case -1: // EOF - forcequirks(); - emitDoctype(); - emitEOF(); - break; - default: - forcequirks(); - tokenizer = bogus_doctype_state; - break; - } - } - - function doctype_public_identifier_double_quoted_state(c) { - switch(c) { - case 0x0022: // QUOTATION MARK - tokenizer = after_doctype_public_identifier_state; - break; - case 0x0000: // NULL - doctypepublicbuf.push(0xFFFD /* REPLACEMENT CHARACTER */); - break; - case 0x003E: // GREATER-THAN SIGN - forcequirks(); - tokenizer = data_state; - emitDoctype(); - break; - case -1: // EOF - forcequirks(); - emitDoctype(); - emitEOF(); - break; - default: - doctypepublicbuf.push(c); - break; - } - } - - function doctype_public_identifier_single_quoted_state(c) { - switch(c) { - case 0x0027: // APOSTROPHE - tokenizer = after_doctype_public_identifier_state; - break; - case 0x0000: // NULL - doctypepublicbuf.push(0xFFFD /* REPLACEMENT CHARACTER */); - break; - case 0x003E: // GREATER-THAN SIGN - forcequirks(); - tokenizer = data_state; - emitDoctype(); - break; - case -1: // EOF - forcequirks(); - emitDoctype(); - emitEOF(); - break; - default: - doctypepublicbuf.push(c); - break; - } - } - - function after_doctype_public_identifier_state(c) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - tokenizer = between_doctype_public_and_system_identifiers_state; - break; - case 0x003E: // GREATER-THAN SIGN - tokenizer = data_state; - emitDoctype(); - break; - case 0x0022: // QUOTATION MARK - beginDoctypeSystemId(); - tokenizer = doctype_system_identifier_double_quoted_state; - break; - case 0x0027: // APOSTROPHE - beginDoctypeSystemId(); - tokenizer = doctype_system_identifier_single_quoted_state; - break; - case -1: // EOF - forcequirks(); - emitDoctype(); - emitEOF(); - break; - default: - forcequirks(); - tokenizer = bogus_doctype_state; - break; - } - } - - function between_doctype_public_and_system_identifiers_state(c) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE Ignore the character. - break; - case 0x003E: // GREATER-THAN SIGN - tokenizer = data_state; - emitDoctype(); - break; - case 0x0022: // QUOTATION MARK - beginDoctypeSystemId(); - tokenizer = doctype_system_identifier_double_quoted_state; - break; - case 0x0027: // APOSTROPHE - beginDoctypeSystemId(); - tokenizer = doctype_system_identifier_single_quoted_state; - break; - case -1: // EOF - forcequirks(); - emitDoctype(); - emitEOF(); - break; - default: - forcequirks(); - tokenizer = bogus_doctype_state; - break; - } - } - - function after_doctype_system_keyword_state(c) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - tokenizer = before_doctype_system_identifier_state; - break; - case 0x0022: // QUOTATION MARK - beginDoctypeSystemId(); - tokenizer = doctype_system_identifier_double_quoted_state; - break; - case 0x0027: // APOSTROPHE - beginDoctypeSystemId(); - tokenizer = doctype_system_identifier_single_quoted_state; - break; - case 0x003E: // GREATER-THAN SIGN - forcequirks(); - tokenizer = data_state; - emitDoctype(); - break; - case -1: // EOF - forcequirks(); - emitDoctype(); - emitEOF(); - break; - default: - forcequirks(); - tokenizer = bogus_doctype_state; - break; - } - } - - function before_doctype_system_identifier_state(c) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE Ignore the character. - break; - case 0x0022: // QUOTATION MARK - beginDoctypeSystemId(); - tokenizer = doctype_system_identifier_double_quoted_state; - break; - case 0x0027: // APOSTROPHE - beginDoctypeSystemId(); - tokenizer = doctype_system_identifier_single_quoted_state; - break; - case 0x003E: // GREATER-THAN SIGN - forcequirks(); - tokenizer = data_state; - emitDoctype(); - break; - case -1: // EOF - forcequirks(); - emitDoctype(); - emitEOF(); - break; - default: - forcequirks(); - tokenizer = bogus_doctype_state; - break; - } - } - - function doctype_system_identifier_double_quoted_state(c) { - switch(c) { - case 0x0022: // QUOTATION MARK - tokenizer = after_doctype_system_identifier_state; - break; - case 0x0000: // NULL - doctypesystembuf.push(0xFFFD /* REPLACEMENT CHARACTER */); - break; - case 0x003E: // GREATER-THAN SIGN - forcequirks(); - tokenizer = data_state; - emitDoctype(); - break; - case -1: // EOF - forcequirks(); - emitDoctype(); - emitEOF(); - break; - default: - doctypesystembuf.push(c); - break; - } - } - - function doctype_system_identifier_single_quoted_state(c) { - switch(c) { - case 0x0027: // APOSTROPHE - tokenizer = after_doctype_system_identifier_state; - break; - case 0x0000: // NULL - doctypesystembuf.push(0xFFFD /* REPLACEMENT CHARACTER */); - break; - case 0x003E: // GREATER-THAN SIGN - forcequirks(); - tokenizer = data_state; - emitDoctype(); - break; - case -1: // EOF - forcequirks(); - emitDoctype(); - emitEOF(); - break; - default: - doctypesystembuf.push(c); - break; - } - } - - function after_doctype_system_identifier_state(c) { - switch(c) { - case 0x0009: // CHARACTER TABULATION (tab) - case 0x000A: // LINE FEED (LF) - case 0x000C: // FORM FEED (FF) - case 0x0020: // SPACE - /* Ignore the character. */ - break; - case 0x003E: // GREATER-THAN SIGN - tokenizer = data_state; - emitDoctype(); - break; - case -1: // EOF - forcequirks(); - emitDoctype(); - emitEOF(); - break; - default: - tokenizer = bogus_doctype_state; - /* This does *not* set the DOCTYPE token's force-quirks flag. */ - break; - } - } - - function bogus_doctype_state(c) { - switch(c) { - case 0x003E: // GREATER-THAN SIGN - tokenizer = data_state; - emitDoctype(); - break; - case -1: // EOF - emitDoctype(); - emitEOF(); - break; - default: - /* Ignore the character. */ - break; - } - } - - function cdata_section_state(c) { - switch(c) { - case 0x005D: // RIGHT SQUARE BRACKET - tokenizer = cdata_section_bracket_state; - break; - case -1: // EOF - emitEOF(); - break; - case 0x0000: // NULL - textIncludesNUL = true; - /* fall through */ - default: - // Instead of just pushing a single character and then - // coming back to the very same place, lookahead and - // emit everything we can at once. - /*jshint -W030 */ - emitCharsWhile(CDATATEXT) || textrun.push(c); - break; - } - } - - function cdata_section_bracket_state(c) { - switch(c) { - case 0x005D: // RIGHT SQUARE BRACKET - tokenizer = cdata_section_end_state; - break; - default: - textrun.push(0x005D); - reconsume(c, cdata_section_state); - break; - } - } - - function cdata_section_end_state(c) { - switch(c) { - case 0x005D: // RIGHT SQUARE BRACKET - textrun.push(0x005D); - break; - case 0x003E: // GREATER-THAN SIGN - flushText(); - tokenizer = data_state; - break; - default: - textrun.push(0x005D); - textrun.push(0x005D); - reconsume(c, cdata_section_state); - break; - } - } - - function character_reference_state(c) { - beginTempBuf(); - tempbuf.push(0x0026); - switch(c) { - case 0x0009: // TAB - case 0x000A: // LINE FEED - case 0x000C: // FORM FEED - case 0x0020: // SPACE - case 0x003C: // LESS-THAN SIGN - case 0x0026: // AMPERSAND - case -1: // EOF - reconsume(c, character_reference_end_state); - break; - case 0x0023: // NUMBER SIGN - tempbuf.push(c); - tokenizer = numeric_character_reference_state; - break; - default: - reconsume(c, named_character_reference_state); - break; - } - } - - function named_character_reference_state(c) { - NAMEDCHARREF.lastIndex = nextchar; // w/ lookahead no char has been consumed - var matched = NAMEDCHARREF.exec(chars); - if (!matched) throw new Error("should never happen"); - var name = matched[1]; - if (!name) { - // If no match can be made, switch to the character reference end state - tokenizer = character_reference_end_state; - return; - } - - // Consume the matched characters and append them to temporary buffer - nextchar += name.length; - pushAll(tempbuf, str2buf(name)); - - switch(return_state) { - case attribute_value_double_quoted_state: - case attribute_value_single_quoted_state: - case attribute_value_unquoted_state: - // If the character reference was consumed as part of an attribute... - if (name[name.length-1] !== ';') { // ...and the last char is not ; - if (/[=A-Za-z0-9]/.test(chars[nextchar])) { - tokenizer = character_reference_end_state; - return; - } - } - break; - default: - break; - } - - beginTempBuf(); - var rv = namedCharRefs[name]; - if (typeof rv === 'number') { - tempbuf.push(rv); - } else { - pushAll(tempbuf, rv); - } - tokenizer = character_reference_end_state; - } - // We might need to pause tokenization until we have enough characters - // in the buffer for longest possible character reference. - named_character_reference_state.lookahead = -NAMEDCHARREF_MAXLEN; - - function numeric_character_reference_state(c) { - character_reference_code = 0; - switch(c) { - case 0x0078: // x - case 0x0058: // X - tempbuf.push(c); - tokenizer = hexadecimal_character_reference_start_state; - break; - default: - reconsume(c, decimal_character_reference_start_state); - break; - } - } - - function hexadecimal_character_reference_start_state(c) { - switch(c) { - case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: - case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: // [0-9] - case 0x0041: case 0x0042: case 0x0043: case 0x0044: case 0x0045: - case 0x0046: // [A-F] - case 0x0061: case 0x0062: case 0x0063: case 0x0064: case 0x0065: - case 0x0066: // [a-f] - reconsume(c, hexadecimal_character_reference_state); - break; - default: - reconsume(c, character_reference_end_state); - break; - } - } - - function decimal_character_reference_start_state(c) { - switch(c) { - case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: - case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: // [0-9] - reconsume(c, decimal_character_reference_state); - break; - default: - reconsume(c, character_reference_end_state); - break; - } - } - - function hexadecimal_character_reference_state(c) { - switch(c) { - case 0x0041: case 0x0042: case 0x0043: case 0x0044: case 0x0045: - case 0x0046: // [A-F] - character_reference_code *= 16; - character_reference_code += (c - 0x0037); - break; - case 0x0061: case 0x0062: case 0x0063: case 0x0064: case 0x0065: - case 0x0066: // [a-f] - character_reference_code *= 16; - character_reference_code += (c - 0x0057); - break; - case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: - case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: // [0-9] - character_reference_code *= 16; - character_reference_code += (c - 0x0030); - break; - case 0x003B: // SEMICOLON - tokenizer = numeric_character_reference_end_state; - break; - default: - reconsume(c, numeric_character_reference_end_state); - break; - } - } - - function decimal_character_reference_state(c) { - switch(c) { - case 0x0030: case 0x0031: case 0x0032: case 0x0033: case 0x0034: - case 0x0035: case 0x0036: case 0x0037: case 0x0038: case 0x0039: // [0-9] - character_reference_code *= 10; - character_reference_code += (c - 0x0030); - break; - case 0x003B: // SEMICOLON - tokenizer = numeric_character_reference_end_state; - break; - default: - reconsume(c, numeric_character_reference_end_state); - break; - } - } - - function numeric_character_reference_end_state(c) { - if (character_reference_code in numericCharRefReplacements) { - character_reference_code = numericCharRefReplacements[character_reference_code]; - } else if (character_reference_code > 0x10FFFF || (character_reference_code >= 0xD800 && character_reference_code < 0xE000)) { - character_reference_code = 0xFFFD; - } - - beginTempBuf(); - if (character_reference_code <= 0xFFFF) { - tempbuf.push(character_reference_code); - } else { - character_reference_code = character_reference_code - 0x10000; - /* jshint bitwise: false */ - tempbuf.push(0xD800 + (character_reference_code >> 10)); - tempbuf.push(0xDC00 + (character_reference_code & 0x03FF)); - } - reconsume(c, character_reference_end_state); - } - - function character_reference_end_state(c) { - switch(return_state) { - case attribute_value_double_quoted_state: - case attribute_value_single_quoted_state: - case attribute_value_unquoted_state: - // append each character to the current attribute's value - attrvaluebuf += buf2str(tempbuf); - break; - default: - pushAll(textrun, tempbuf); - break; - } - reconsume(c, return_state); - } - - /*** - * The tree builder insertion modes - */ - - // 11.2.5.4.1 The "initial" insertion mode - function initial_mode(t, value, arg3, arg4) { - switch(t) { - case 1: // TEXT - value = value.replace(LEADINGWS, ""); // Ignore spaces - if (value.length === 0) return; // Are we done? - break; // Handle anything non-space text below - case 4: // COMMENT - doc._appendChild(doc.createComment(value)); - return; - case 5: // DOCTYPE - var name = value; - var publicid = arg3; - var systemid = arg4; - // Use the constructor directly instead of - // implementation.createDocumentType because the create - // function throws errors on invalid characters, and - // we don't want the parser to throw them. - doc.appendChild(new DocumentType(doc, name, publicid, systemid)); - - // Note that there is no public API for setting quirks mode We can - // do this here because we have access to implementation details - if (force_quirks || - name.toLowerCase() !== "html" || - quirkyPublicIds.test(publicid) || - (systemid && systemid.toLowerCase() === quirkySystemId) || - (systemid === undefined && - conditionallyQuirkyPublicIds.test(publicid))) - doc._quirks = true; - else if (limitedQuirkyPublicIds.test(publicid) || - (systemid !== undefined && - conditionallyQuirkyPublicIds.test(publicid))) - doc._limitedQuirks = true; - parser = before_html_mode; - return; - } - - // tags or non-whitespace text - doc._quirks = true; - parser = before_html_mode; - parser(t,value,arg3,arg4); - } - - // 11.2.5.4.2 The "before html" insertion mode - function before_html_mode(t,value,arg3,arg4) { - var elt; - switch(t) { - case 1: // TEXT - value = value.replace(LEADINGWS, ""); // Ignore spaces - if (value.length === 0) return; // Are we done? - break; // Handle anything non-space text below - case 5: // DOCTYPE - /* ignore the token */ - return; - case 4: // COMMENT - doc._appendChild(doc.createComment(value)); - return; - case 2: // TAG - if (value === "html") { - elt = createHTMLElt(doc, value, arg3); - stack.push(elt); - doc.appendChild(elt); - // XXX: handle application cache here - parser = before_head_mode; - return; - } - break; - case 3: // ENDTAG - switch(value) { - case "html": - case "head": - case "body": - case "br": - break; // fall through on these - default: - return; // ignore most end tags - } - } - - // Anything that didn't get handled above is handled like this: - elt = createHTMLElt(doc, "html", null); - stack.push(elt); - doc.appendChild(elt); - // XXX: handle application cache here - parser = before_head_mode; - parser(t,value,arg3,arg4); - } - - // 11.2.5.4.3 The "before head" insertion mode - function before_head_mode(t,value,arg3,arg4) { - switch(t) { - case 1: // TEXT - value = value.replace(LEADINGWS, ""); // Ignore spaces - if (value.length === 0) return; // Are we done? - break; // Handle anything non-space text below - case 5: // DOCTYPE - /* ignore the token */ - return; - case 4: // COMMENT - insertComment(value); - return; - case 2: // TAG - switch(value) { - case "html": - in_body_mode(t,value,arg3,arg4); - return; - case "head": - var elt = insertHTMLElement(value, arg3); - head_element_pointer = elt; - parser = in_head_mode; - return; - } - break; - case 3: // ENDTAG - switch(value) { - case "html": - case "head": - case "body": - case "br": - break; - default: - return; // ignore most end tags - } - } - - // If not handled explicitly above - before_head_mode(TAG, "head", null); // create a head tag - parser(t, value, arg3, arg4); // then try again with this token - } - - function in_head_mode(t, value, arg3, arg4) { - switch(t) { - case 1: // TEXT - var ws = value.match(LEADINGWS); - if (ws) { - insertText(ws[0]); - value = value.substring(ws[0].length); - } - if (value.length === 0) return; - break; // Handle non-whitespace below - case 4: // COMMENT - insertComment(value); - return; - case 5: // DOCTYPE - return; - case 2: // TAG - switch(value) { - case "html": - in_body_mode(t, value, arg3, arg4); - return; - case "meta": - // XXX: - // May need to change the encoding based on this tag - /* falls through */ - case "base": - case "basefont": - case "bgsound": - case "link": - insertHTMLElement(value, arg3); - stack.pop(); - return; - case "title": - parseRCDATA(value, arg3); - return; - case "noscript": - if (!scripting_enabled) { - insertHTMLElement(value, arg3); - parser = in_head_noscript_mode; - return; - } - // Otherwise, if scripting is enabled... - /* falls through */ - case "noframes": - case "style": - parseRawText(value,arg3); - return; - case "script": - insertElement(function(doc) { - var elt = createHTMLElt(doc, value, arg3); - elt._parser_inserted = true; - elt._force_async = false; - if (fragment) elt._already_started = true; - flushText(); - return elt; - }); - tokenizer = script_data_state; - originalInsertionMode = parser; - parser = text_mode; - return; - case "template": - insertHTMLElement(value, arg3); - afe.insertMarker(); - frameset_ok = false; - parser = in_template_mode; - templateInsertionModes.push(parser); - return; - case "head": - return; // ignore it - } - break; - case 3: // ENDTAG - switch(value) { - case "head": - stack.pop(); - parser = after_head_mode; - return; - case "body": - case "html": - case "br": - break; // handle these at the bottom of the function - case "template": - if (!stack.contains("template")) { - return; - } - stack.generateImpliedEndTags(null, "thorough"); - stack.popTag("template"); - afe.clearToMarker(); - templateInsertionModes.pop(); - resetInsertionMode(); - return; - default: - // ignore any other end tag - return; - } - break; - } - - // If not handled above - in_head_mode(ENDTAG, "head", null); // synthetic - parser(t, value, arg3, arg4); // Then redo this one - } - - // 13.2.5.4.5 The "in head noscript" insertion mode - function in_head_noscript_mode(t, value, arg3, arg4) { - switch(t) { - case 5: // DOCTYPE - return; - case 4: // COMMENT - in_head_mode(t, value); - return; - case 1: // TEXT - var ws = value.match(LEADINGWS); - if (ws) { - in_head_mode(t, ws[0]); - value = value.substring(ws[0].length); - } - if (value.length === 0) return; // no more text - break; // Handle non-whitespace below - case 2: // TAG - switch(value) { - case "html": - in_body_mode(t, value, arg3, arg4); - return; - case "basefont": - case "bgsound": - case "link": - case "meta": - case "noframes": - case "style": - in_head_mode(t, value, arg3); - return; - case "head": - case "noscript": - return; - } - break; - case 3: // ENDTAG - switch(value) { - case "noscript": - stack.pop(); - parser = in_head_mode; - return; - case "br": - break; // goes to the outer default - default: - return; // ignore other end tags - } - break; - } - - // If not handled above - in_head_noscript_mode(ENDTAG, "noscript", null); - parser(t, value, arg3, arg4); - } - - function after_head_mode(t, value, arg3, arg4) { - switch(t) { - case 1: // TEXT - var ws = value.match(LEADINGWS); - if (ws) { - insertText(ws[0]); - value = value.substring(ws[0].length); - } - if (value.length === 0) return; - break; // Handle non-whitespace below - case 4: // COMMENT - insertComment(value); - return; - case 5: // DOCTYPE - return; - case 2: // TAG - switch(value) { - case "html": - in_body_mode(t, value, arg3, arg4); - return; - case "body": - insertHTMLElement(value, arg3); - frameset_ok = false; - parser = in_body_mode; - return; - case "frameset": - insertHTMLElement(value, arg3); - parser = in_frameset_mode; - return; - case "base": - case "basefont": - case "bgsound": - case "link": - case "meta": - case "noframes": - case "script": - case "style": - case "template": - case "title": - stack.push(head_element_pointer); - in_head_mode(TAG, value, arg3); - stack.removeElement(head_element_pointer); - return; - case "head": - return; - } - break; - case 3: // ENDTAG - switch(value) { - case "template": - return in_head_mode(t, value, arg3, arg4); - case "body": - case "html": - case "br": - break; - default: - return; // ignore any other end tag - } - break; - } - - after_head_mode(TAG, "body", null); - frameset_ok = true; - parser(t, value, arg3, arg4); - } - - // 13.2.5.4.7 The "in body" insertion mode - function in_body_mode(t,value,arg3,arg4) { - var body, i, node, elt; - switch(t) { - case 1: // TEXT - if (textIncludesNUL) { - value = value.replace(NULCHARS, ""); - if (value.length === 0) return; - } - // If any non-space characters - if (frameset_ok && NONWS.test(value)) - frameset_ok = false; - afereconstruct(); - insertText(value); - return; - case 5: // DOCTYPE - return; - case 4: // COMMENT - insertComment(value); - return; - case -1: // EOF - if (templateInsertionModes.length) { - return in_template_mode(t); - } - stopParsing(); - return; - case 2: // TAG - switch(value) { - case "html": - if (stack.contains("template")) { - return; - } - transferAttributes(arg3, stack.elements[0]); - return; - case "base": - case "basefont": - case "bgsound": - case "link": - case "meta": - case "noframes": - case "script": - case "style": - case "template": - case "title": - in_head_mode(TAG, value, arg3); - return; - case "body": - body = stack.elements[1]; - if (!body || !(body instanceof impl.HTMLBodyElement) || - stack.contains("template")) - return; - frameset_ok = false; - transferAttributes(arg3, body); - return; - case "frameset": - if (!frameset_ok) return; - body = stack.elements[1]; - if (!body || !(body instanceof impl.HTMLBodyElement)) - return; - if (body.parentNode) body.parentNode.removeChild(body); - while(!(stack.top instanceof impl.HTMLHtmlElement)) - stack.pop(); - insertHTMLElement(value, arg3); - parser = in_frameset_mode; - return; - - case "address": - case "article": - case "aside": - case "blockquote": - case "center": - case "details": - case "dialog": - case "dir": - case "div": - case "dl": - case "fieldset": - case "figcaption": - case "figure": - case "footer": - case "header": - case "hgroup": - case "main": - case "nav": - case "ol": - case "p": - case "section": - case "summary": - case "ul": - if (stack.inButtonScope("p")) in_body_mode(ENDTAG, "p"); - insertHTMLElement(value, arg3); - return; - - case "menu": - if (stack.inButtonScope("p")) in_body_mode(ENDTAG, "p"); - if (isA(stack.top, 'menuitem')) { - stack.pop(); - } - insertHTMLElement(value, arg3); - return; - - case "h1": - case "h2": - case "h3": - case "h4": - case "h5": - case "h6": - if (stack.inButtonScope("p")) in_body_mode(ENDTAG, "p"); - if (stack.top instanceof impl.HTMLHeadingElement) - stack.pop(); - insertHTMLElement(value, arg3); - return; - - case "pre": - case "listing": - if (stack.inButtonScope("p")) in_body_mode(ENDTAG, "p"); - insertHTMLElement(value, arg3); - ignore_linefeed = true; - frameset_ok = false; - return; - - case "form": - if (form_element_pointer && !stack.contains("template")) return; - if (stack.inButtonScope("p")) in_body_mode(ENDTAG, "p"); - elt = insertHTMLElement(value, arg3); - if (!stack.contains("template")) - form_element_pointer = elt; - return; - - case "li": - frameset_ok = false; - for(i = stack.elements.length-1; i >= 0; i--) { - node = stack.elements[i]; - if (node instanceof impl.HTMLLIElement) { - in_body_mode(ENDTAG, "li"); - break; - } - if (isA(node, specialSet) && !isA(node, addressdivpSet)) - break; - } - if (stack.inButtonScope("p")) in_body_mode(ENDTAG, "p"); - insertHTMLElement(value, arg3); - return; - - case "dd": - case "dt": - frameset_ok = false; - for(i = stack.elements.length-1; i >= 0; i--) { - node = stack.elements[i]; - if (isA(node, dddtSet)) { - in_body_mode(ENDTAG, node.localName); - break; - } - if (isA(node, specialSet) && !isA(node, addressdivpSet)) - break; - } - if (stack.inButtonScope("p")) in_body_mode(ENDTAG, "p"); - insertHTMLElement(value, arg3); - return; - - case "plaintext": - if (stack.inButtonScope("p")) in_body_mode(ENDTAG, "p"); - insertHTMLElement(value, arg3); - tokenizer = plaintext_state; - return; - - case "button": - if (stack.inScope("button")) { - in_body_mode(ENDTAG, "button"); - parser(t, value, arg3, arg4); - } - else { - afereconstruct(); - insertHTMLElement(value, arg3); - frameset_ok = false; - } - return; - - case "a": - var activeElement = afe.findElementByTag("a"); - if (activeElement) { - in_body_mode(ENDTAG, value); - afe.remove(activeElement); - stack.removeElement(activeElement); - } - /* falls through */ - case "b": - case "big": - case "code": - case "em": - case "font": - case "i": - case "s": - case "small": - case "strike": - case "strong": - case "tt": - case "u": - afereconstruct(); - afe.push(insertHTMLElement(value,arg3), arg3); - return; - - case "nobr": - afereconstruct(); - - if (stack.inScope(value)) { - in_body_mode(ENDTAG, value); - afereconstruct(); - } - afe.push(insertHTMLElement(value,arg3), arg3); - return; - - case "applet": - case "marquee": - case "object": - afereconstruct(); - insertHTMLElement(value,arg3); - afe.insertMarker(); - frameset_ok = false; - return; - - case "table": - if (!doc._quirks && stack.inButtonScope("p")) { - in_body_mode(ENDTAG, "p"); - } - insertHTMLElement(value,arg3); - frameset_ok = false; - parser = in_table_mode; - return; - - case "area": - case "br": - case "embed": - case "img": - case "keygen": - case "wbr": - afereconstruct(); - insertHTMLElement(value,arg3); - stack.pop(); - frameset_ok = false; - return; - - case "input": - afereconstruct(); - elt = insertHTMLElement(value,arg3); - stack.pop(); - var type = elt.getAttribute("type"); - if (!type || type.toLowerCase() !== "hidden") - frameset_ok = false; - return; - - case "param": - case "source": - case "track": - insertHTMLElement(value,arg3); - stack.pop(); - return; - - case "hr": - if (stack.inButtonScope("p")) in_body_mode(ENDTAG, "p"); - if (isA(stack.top, 'menuitem')) { - stack.pop(); - } - insertHTMLElement(value,arg3); - stack.pop(); - frameset_ok = false; - return; - - case "image": - in_body_mode(TAG, "img", arg3, arg4); - return; - - case "textarea": - insertHTMLElement(value,arg3); - ignore_linefeed = true; - frameset_ok = false; - tokenizer = rcdata_state; - originalInsertionMode = parser; - parser = text_mode; - return; - - case "xmp": - if (stack.inButtonScope("p")) in_body_mode(ENDTAG, "p"); - afereconstruct(); - frameset_ok = false; - parseRawText(value, arg3); - return; - - case "iframe": - frameset_ok = false; - parseRawText(value, arg3); - return; - - case "noembed": - parseRawText(value,arg3); - return; - - case "select": - afereconstruct(); - insertHTMLElement(value,arg3); - frameset_ok = false; - if (parser === in_table_mode || - parser === in_caption_mode || - parser === in_table_body_mode || - parser === in_row_mode || - parser === in_cell_mode) - parser = in_select_in_table_mode; - else - parser = in_select_mode; - return; - - case "optgroup": - case "option": - if (stack.top instanceof impl.HTMLOptionElement) { - in_body_mode(ENDTAG, "option"); - } - afereconstruct(); - insertHTMLElement(value,arg3); - return; - - case "menuitem": - if (isA(stack.top, 'menuitem')) { - stack.pop(); - } - afereconstruct(); - insertHTMLElement(value, arg3); - return; - - case "rb": - case "rtc": - if (stack.inScope("ruby")) { - stack.generateImpliedEndTags(); - } - insertHTMLElement(value,arg3); - return; - - case "rp": - case "rt": - if (stack.inScope("ruby")) { - stack.generateImpliedEndTags("rtc"); - } - insertHTMLElement(value,arg3); - return; - - case "math": - afereconstruct(); - adjustMathMLAttributes(arg3); - adjustForeignAttributes(arg3); - insertForeignElement(value, arg3, NAMESPACE.MATHML); - if (arg4) // self-closing flag - stack.pop(); - return; - - case "svg": - afereconstruct(); - adjustSVGAttributes(arg3); - adjustForeignAttributes(arg3); - insertForeignElement(value, arg3, NAMESPACE.SVG); - if (arg4) // self-closing flag - stack.pop(); - return; - - case "caption": - case "col": - case "colgroup": - case "frame": - case "head": - case "tbody": - case "td": - case "tfoot": - case "th": - case "thead": - case "tr": - // Ignore table tags if we're not in_table mode - return; - } - - // Handle any other start tag here - // (and also noscript tags when scripting is disabled) - afereconstruct(); - insertHTMLElement(value,arg3); - return; - - case 3: // ENDTAG - switch(value) { - case "template": - in_head_mode(ENDTAG, value, arg3); - return; - case "body": - if (!stack.inScope("body")) return; - parser = after_body_mode; - return; - case "html": - if (!stack.inScope("body")) return; - parser = after_body_mode; - parser(t, value, arg3); - return; - - case "address": - case "article": - case "aside": - case "blockquote": - case "button": - case "center": - case "details": - case "dialog": - case "dir": - case "div": - case "dl": - case "fieldset": - case "figcaption": - case "figure": - case "footer": - case "header": - case "hgroup": - case "listing": - case "main": - case "menu": - case "nav": - case "ol": - case "pre": - case "section": - case "summary": - case "ul": - // Ignore if there is not a matching open tag - if (!stack.inScope(value)) return; - stack.generateImpliedEndTags(); - stack.popTag(value); - return; - - case "form": - if (!stack.contains("template")) { - var openform = form_element_pointer; - form_element_pointer = null; - if (!openform || !stack.elementInScope(openform)) return; - stack.generateImpliedEndTags(); - stack.removeElement(openform); - } else { - if (!stack.inScope("form")) return; - stack.generateImpliedEndTags(); - stack.popTag("form"); - } - return; - - case "p": - if (!stack.inButtonScope(value)) { - in_body_mode(TAG, value, null); - parser(t, value, arg3, arg4); - } - else { - stack.generateImpliedEndTags(value); - stack.popTag(value); - } - return; - - case "li": - if (!stack.inListItemScope(value)) return; - stack.generateImpliedEndTags(value); - stack.popTag(value); - return; - - case "dd": - case "dt": - if (!stack.inScope(value)) return; - stack.generateImpliedEndTags(value); - stack.popTag(value); - return; - - case "h1": - case "h2": - case "h3": - case "h4": - case "h5": - case "h6": - if (!stack.elementTypeInScope(impl.HTMLHeadingElement)) return; - stack.generateImpliedEndTags(); - stack.popElementType(impl.HTMLHeadingElement); - return; - - case "sarcasm": - // Take a deep breath, and then: - break; - - case "a": - case "b": - case "big": - case "code": - case "em": - case "font": - case "i": - case "nobr": - case "s": - case "small": - case "strike": - case "strong": - case "tt": - case "u": - var result = adoptionAgency(value); - if (result) return; // If we did something we're done - break; // Go to the "any other end tag" case - - case "applet": - case "marquee": - case "object": - if (!stack.inScope(value)) return; - stack.generateImpliedEndTags(); - stack.popTag(value); - afe.clearToMarker(); - return; - - case "br": - in_body_mode(TAG, value, null); // Turn
into
- return; - } - - // Any other end tag goes here - for(i = stack.elements.length-1; i >= 0; i--) { - node = stack.elements[i]; - if (isA(node, value)) { - stack.generateImpliedEndTags(value); - stack.popElement(node); - break; - } - else if (isA(node, specialSet)) { - return; - } - } - - return; - } - } - - function text_mode(t, value, arg3, arg4) { - switch(t) { - case 1: // TEXT - insertText(value); - return; - case -1: // EOF - if (stack.top instanceof impl.HTMLScriptElement) - stack.top._already_started = true; - stack.pop(); - parser = originalInsertionMode; - parser(t); - return; - case 3: // ENDTAG - if (value === "script") { - handleScriptEnd(); - } - else { - stack.pop(); - parser = originalInsertionMode; - } - return; - default: - // We should never get any other token types - return; - } - } - - function in_table_mode(t, value, arg3, arg4) { - function getTypeAttr(attrs) { - for(var i = 0, n = attrs.length; i < n; i++) { - if (attrs[i][0] === "type") - return attrs[i][1].toLowerCase(); - } - return null; - } - - switch(t) { - case 1: // TEXT - // XXX the text_integration_mode stuff is - // just a hack I made up - if (text_integration_mode) { - in_body_mode(t, value, arg3, arg4); - return; - } - else if (isA(stack.top, tablesectionrowSet)) { - pending_table_text = []; - originalInsertionMode = parser; - parser = in_table_text_mode; - parser(t, value, arg3, arg4); - return; - } - break; - case 4: // COMMENT - insertComment(value); - return; - case 5: // DOCTYPE - return; - case 2: // TAG - switch(value) { - case "caption": - stack.clearToContext(tableContextSet); - afe.insertMarker(); - insertHTMLElement(value,arg3); - parser = in_caption_mode; - return; - case "colgroup": - stack.clearToContext(tableContextSet); - insertHTMLElement(value,arg3); - parser = in_column_group_mode; - return; - case "col": - in_table_mode(TAG, "colgroup", null); - parser(t, value, arg3, arg4); - return; - case "tbody": - case "tfoot": - case "thead": - stack.clearToContext(tableContextSet); - insertHTMLElement(value,arg3); - parser = in_table_body_mode; - return; - case "td": - case "th": - case "tr": - in_table_mode(TAG, "tbody", null); - parser(t, value, arg3, arg4); - return; - - case "table": - if (!stack.inTableScope(value)) { - return; // Ignore the token - } - in_table_mode(ENDTAG, value); - parser(t, value, arg3, arg4); - return; - - case "style": - case "script": - case "template": - in_head_mode(t, value, arg3, arg4); - return; - - case "input": - var type = getTypeAttr(arg3); - if (type !== "hidden") break; // to the anything else case - insertHTMLElement(value,arg3); - stack.pop(); - return; - - case "form": - if (form_element_pointer || stack.contains("template")) return; - form_element_pointer = insertHTMLElement(value, arg3); - stack.popElement(form_element_pointer); - return; - } - break; - case 3: // ENDTAG - switch(value) { - case "table": - if (!stack.inTableScope(value)) return; - stack.popTag(value); - resetInsertionMode(); - return; - case "body": - case "caption": - case "col": - case "colgroup": - case "html": - case "tbody": - case "td": - case "tfoot": - case "th": - case "thead": - case "tr": - return; - case "template": - in_head_mode(t, value, arg3, arg4); - return; - } - - break; - case -1: // EOF - in_body_mode(t, value, arg3, arg4); - return; - } - - // This is the anything else case - foster_parent_mode = true; - in_body_mode(t, value, arg3, arg4); - foster_parent_mode = false; - } - - function in_table_text_mode(t, value, arg3, arg4) { - if (t === TEXT) { - if (textIncludesNUL) { - value = value.replace(NULCHARS, ""); - if (value.length === 0) return; - } - pending_table_text.push(value); - } - else { - var s = pending_table_text.join(""); - pending_table_text.length = 0; - if (NONWS.test(s)) { // If any non-whitespace characters - // This must be the same code as the "anything else" - // case of the in_table mode above. - foster_parent_mode = true; - in_body_mode(TEXT, s); - foster_parent_mode = false; - } - else { - insertText(s); - } - parser = originalInsertionMode; - parser(t, value, arg3, arg4); - } - } - - - function in_caption_mode(t, value, arg3, arg4) { - function end_caption() { - if (!stack.inTableScope("caption")) return false; - stack.generateImpliedEndTags(); - stack.popTag("caption"); - afe.clearToMarker(); - parser = in_table_mode; - return true; - } - - switch(t) { - case 2: // TAG - switch(value) { - case "caption": - case "col": - case "colgroup": - case "tbody": - case "td": - case "tfoot": - case "th": - case "thead": - case "tr": - if (end_caption()) parser(t, value, arg3, arg4); - return; - } - break; - case 3: // ENDTAG - switch(value) { - case "caption": - end_caption(); - return; - case "table": - if (end_caption()) parser(t, value, arg3, arg4); - return; - case "body": - case "col": - case "colgroup": - case "html": - case "tbody": - case "td": - case "tfoot": - case "th": - case "thead": - case "tr": - return; - } - break; - } - - // The Anything Else case - in_body_mode(t, value, arg3, arg4); - } - - function in_column_group_mode(t, value, arg3, arg4) { - switch(t) { - case 1: // TEXT - var ws = value.match(LEADINGWS); - if (ws) { - insertText(ws[0]); - value = value.substring(ws[0].length); - } - if (value.length === 0) return; - break; // Handle non-whitespace below - - case 4: // COMMENT - insertComment(value); - return; - case 5: // DOCTYPE - return; - case 2: // TAG - switch(value) { - case "html": - in_body_mode(t, value, arg3, arg4); - return; - case "col": - insertHTMLElement(value, arg3); - stack.pop(); - return; - case "template": - in_head_mode(t, value, arg3, arg4); - return; - } - break; - case 3: // ENDTAG - switch(value) { - case "colgroup": - if (!isA(stack.top, 'colgroup')) { - return; // Ignore the token. - } - stack.pop(); - parser = in_table_mode; - return; - case "col": - return; - case "template": - in_head_mode(t, value, arg3, arg4); - return; - } - break; - case -1: // EOF - in_body_mode(t, value, arg3, arg4); - return; - } - - // Anything else - if (!isA(stack.top, 'colgroup')) { - return; // Ignore the token. - } - in_column_group_mode(ENDTAG, "colgroup"); - parser(t, value, arg3, arg4); - } - - function in_table_body_mode(t, value, arg3, arg4) { - function endsect() { - if (!stack.inTableScope("tbody") && - !stack.inTableScope("thead") && - !stack.inTableScope("tfoot")) - return; - stack.clearToContext(tableBodyContextSet); - in_table_body_mode(ENDTAG, stack.top.localName, null); - parser(t, value, arg3, arg4); - } - - switch(t) { - case 2: // TAG - switch(value) { - case "tr": - stack.clearToContext(tableBodyContextSet); - insertHTMLElement(value, arg3); - parser = in_row_mode; - return; - case "th": - case "td": - in_table_body_mode(TAG, "tr", null); - parser(t, value, arg3, arg4); - return; - case "caption": - case "col": - case "colgroup": - case "tbody": - case "tfoot": - case "thead": - endsect(); - return; - } - break; - case 3: // ENDTAG - switch(value) { - case "table": - endsect(); - return; - case "tbody": - case "tfoot": - case "thead": - if (stack.inTableScope(value)) { - stack.clearToContext(tableBodyContextSet); - stack.pop(); - parser = in_table_mode; - } - return; - case "body": - case "caption": - case "col": - case "colgroup": - case "html": - case "td": - case "th": - case "tr": - return; - } - break; - } - - // Anything else: - in_table_mode(t, value, arg3, arg4); - } - - function in_row_mode(t, value, arg3, arg4) { - function endrow() { - if (!stack.inTableScope("tr")) return false; - stack.clearToContext(tableRowContextSet); - stack.pop(); - parser = in_table_body_mode; - return true; - } - - switch(t) { - case 2: // TAG - switch(value) { - case "th": - case "td": - stack.clearToContext(tableRowContextSet); - insertHTMLElement(value, arg3); - parser = in_cell_mode; - afe.insertMarker(); - return; - case "caption": - case "col": - case "colgroup": - case "tbody": - case "tfoot": - case "thead": - case "tr": - if (endrow()) parser(t, value, arg3, arg4); - return; - } - break; - case 3: // ENDTAG - switch(value) { - case "tr": - endrow(); - return; - case "table": - if (endrow()) parser(t, value, arg3, arg4); - return; - case "tbody": - case "tfoot": - case "thead": - if (stack.inTableScope(value)) { - if (endrow()) parser(t, value, arg3, arg4); - } - return; - case "body": - case "caption": - case "col": - case "colgroup": - case "html": - case "td": - case "th": - return; - } - break; - } - - // anything else - in_table_mode(t, value, arg3, arg4); - } - - function in_cell_mode(t, value, arg3, arg4) { - switch(t) { - case 2: // TAG - switch(value) { - case "caption": - case "col": - case "colgroup": - case "tbody": - case "td": - case "tfoot": - case "th": - case "thead": - case "tr": - if (stack.inTableScope("td")) { - in_cell_mode(ENDTAG, "td"); - parser(t, value, arg3, arg4); - } - else if (stack.inTableScope("th")) { - in_cell_mode(ENDTAG, "th"); - parser(t, value, arg3, arg4); - } - return; - } - break; - case 3: // ENDTAG - switch(value) { - case "td": - case "th": - if (!stack.inTableScope(value)) return; - stack.generateImpliedEndTags(); - stack.popTag(value); - afe.clearToMarker(); - parser = in_row_mode; - return; - - case "body": - case "caption": - case "col": - case "colgroup": - case "html": - return; - - case "table": - case "tbody": - case "tfoot": - case "thead": - case "tr": - if (!stack.inTableScope(value)) return; - in_cell_mode(ENDTAG, stack.inTableScope("td") ? "td" : "th"); - parser(t, value, arg3, arg4); - return; - } - break; - } - - // anything else - in_body_mode(t, value, arg3, arg4); - } - - function in_select_mode(t, value, arg3, arg4) { - switch(t) { - case 1: // TEXT - if (textIncludesNUL) { - value = value.replace(NULCHARS, ""); - if (value.length === 0) return; - } - insertText(value); - return; - case 4: // COMMENT - insertComment(value); - return; - case 5: // DOCTYPE - return; - case -1: // EOF - in_body_mode(t, value, arg3, arg4); - return; - case 2: // TAG - switch(value) { - case "html": - in_body_mode(t, value, arg3, arg4); - return; - case "option": - if (stack.top instanceof impl.HTMLOptionElement) - in_select_mode(ENDTAG, value); - insertHTMLElement(value, arg3); - return; - case "optgroup": - if (stack.top instanceof impl.HTMLOptionElement) - in_select_mode(ENDTAG, "option"); - if (stack.top instanceof impl.HTMLOptGroupElement) - in_select_mode(ENDTAG, value); - insertHTMLElement(value, arg3); - return; - case "select": - in_select_mode(ENDTAG, value); // treat it as a close tag - return; - - case "input": - case "keygen": - case "textarea": - if (!stack.inSelectScope("select")) return; - in_select_mode(ENDTAG, "select"); - parser(t, value, arg3, arg4); - return; - - case "script": - case "template": - in_head_mode(t, value, arg3, arg4); - return; - } - break; - case 3: // ENDTAG - switch(value) { - case "optgroup": - if (stack.top instanceof impl.HTMLOptionElement && - stack.elements[stack.elements.length-2] instanceof - impl.HTMLOptGroupElement) { - in_select_mode(ENDTAG, "option"); - } - if (stack.top instanceof impl.HTMLOptGroupElement) - stack.pop(); - - return; - - case "option": - if (stack.top instanceof impl.HTMLOptionElement) - stack.pop(); - return; - - case "select": - if (!stack.inSelectScope(value)) return; - stack.popTag(value); - resetInsertionMode(); - return; - - case "template": - in_head_mode(t, value, arg3, arg4); - return; - } - - break; - } - - // anything else: just ignore the token - } - - function in_select_in_table_mode(t, value, arg3, arg4) { - switch(value) { - case "caption": - case "table": - case "tbody": - case "tfoot": - case "thead": - case "tr": - case "td": - case "th": - switch(t) { - case 2: // TAG - in_select_in_table_mode(ENDTAG, "select"); - parser(t, value, arg3, arg4); - return; - case 3: // ENDTAG - if (stack.inTableScope(value)) { - in_select_in_table_mode(ENDTAG, "select"); - parser(t, value, arg3, arg4); - } - return; - } - } - - // anything else - in_select_mode(t, value, arg3, arg4); - } - - function in_template_mode(t, value, arg3, arg4) { - function switchModeAndReprocess(mode) { - parser = mode; - templateInsertionModes[templateInsertionModes.length-1] = parser; - parser(t, value, arg3, arg4); - } - switch(t) { - case 1: // TEXT - case 4: // COMMENT - case 5: // DOCTYPE - in_body_mode(t, value, arg3, arg4); - return; - case -1: // EOF - if (!stack.contains("template")) { - stopParsing(); - } else { - stack.popTag("template"); - afe.clearToMarker(); - templateInsertionModes.pop(); - resetInsertionMode(); - parser(t, value, arg3, arg4); - } - return; - case 2: // TAG - switch(value) { - case "base": - case "basefont": - case "bgsound": - case "link": - case "meta": - case "noframes": - case "script": - case "style": - case "template": - case "title": - in_head_mode(t, value, arg3, arg4); - return; - case "caption": - case "colgroup": - case "tbody": - case "tfoot": - case "thead": - switchModeAndReprocess(in_table_mode); - return; - case "col": - switchModeAndReprocess(in_column_group_mode); - return; - case "tr": - switchModeAndReprocess(in_table_body_mode); - return; - case "td": - case "th": - switchModeAndReprocess(in_row_mode); - return; - } - switchModeAndReprocess(in_body_mode); - return; - case 3: // ENDTAG - switch(value) { - case "template": - in_head_mode(t, value, arg3, arg4); - return; - default: - return; - } - } - } - - function after_body_mode(t, value, arg3, arg4) { - switch(t) { - case 1: // TEXT - // If any non-space chars, handle below - if (NONWS.test(value)) break; - in_body_mode(t, value); - return; - case 4: // COMMENT - // Append it to the element - stack.elements[0]._appendChild(doc.createComment(value)); - return; - case 5: // DOCTYPE - return; - case -1: // EOF - stopParsing(); - return; - case 2: // TAG - if (value === "html") { - in_body_mode(t, value, arg3, arg4); - return; - } - break; // for any other tags - case 3: // ENDTAG - if (value === "html") { - if (fragment) return; - parser = after_after_body_mode; - return; - } - break; // for any other tags - } - - // anything else - parser = in_body_mode; - parser(t, value, arg3, arg4); - } - - function in_frameset_mode(t, value, arg3, arg4) { - switch(t) { - case 1: // TEXT - // Ignore any non-space characters - value = value.replace(ALLNONWS, ""); - if (value.length > 0) insertText(value); - return; - case 4: // COMMENT - insertComment(value); - return; - case 5: // DOCTYPE - return; - case -1: // EOF - stopParsing(); - return; - case 2: // TAG - switch(value) { - case "html": - in_body_mode(t, value, arg3, arg4); - return; - case "frameset": - insertHTMLElement(value, arg3); - return; - case "frame": - insertHTMLElement(value, arg3); - stack.pop(); - return; - case "noframes": - in_head_mode(t, value, arg3, arg4); - return; - } - break; - case 3: // ENDTAG - if (value === "frameset") { - if (fragment && stack.top instanceof impl.HTMLHtmlElement) - return; - stack.pop(); - if (!fragment && - !(stack.top instanceof impl.HTMLFrameSetElement)) - parser = after_frameset_mode; - return; - } - break; - } - - // ignore anything else - } - - function after_frameset_mode(t, value, arg3, arg4) { - switch(t) { - case 1: // TEXT - // Ignore any non-space characters - value = value.replace(ALLNONWS, ""); - if (value.length > 0) insertText(value); - return; - case 4: // COMMENT - insertComment(value); - return; - case 5: // DOCTYPE - return; - case -1: // EOF - stopParsing(); - return; - case 2: // TAG - switch(value) { - case "html": - in_body_mode(t, value, arg3, arg4); - return; - case "noframes": - in_head_mode(t, value, arg3, arg4); - return; - } - break; - case 3: // ENDTAG - if (value === "html") { - parser = after_after_frameset_mode; - return; - } - break; - } - - // ignore anything else - } - - function after_after_body_mode(t, value, arg3, arg4) { - switch(t) { - case 1: // TEXT - // If any non-space chars, handle below - if (NONWS.test(value)) break; - in_body_mode(t, value, arg3, arg4); - return; - case 4: // COMMENT - doc._appendChild(doc.createComment(value)); - return; - case 5: // DOCTYPE - in_body_mode(t, value, arg3, arg4); - return; - case -1: // EOF - stopParsing(); - return; - case 2: // TAG - if (value === "html") { - in_body_mode(t, value, arg3, arg4); - return; - } - break; - } - - // anything else - parser = in_body_mode; - parser(t, value, arg3, arg4); - } - - function after_after_frameset_mode(t, value, arg3, arg4) { - switch(t) { - case 1: // TEXT - // Ignore any non-space characters - value = value.replace(ALLNONWS, ""); - if (value.length > 0) - in_body_mode(t, value, arg3, arg4); - return; - case 4: // COMMENT - doc._appendChild(doc.createComment(value)); - return; - case 5: // DOCTYPE - in_body_mode(t, value, arg3, arg4); - return; - case -1: // EOF - stopParsing(); - return; - case 2: // TAG - switch(value) { - case "html": - in_body_mode(t, value, arg3, arg4); - return; - case "noframes": - in_head_mode(t, value, arg3, arg4); - return; - } - break; - } - - // ignore anything else - } - - - // 13.2.5.5 The rules for parsing tokens in foreign content - // - // This is like one of the insertion modes above, but is - // invoked somewhat differently when the current token is not HTML. - // See the insertToken() function. - function insertForeignToken(t, value, arg3, arg4) { - // A tag is an HTML font tag if it has a color, font, or size - // attribute. Otherwise we assume it is foreign content - function isHTMLFont(attrs) { - for(var i = 0, n = attrs.length; i < n; i++) { - switch(attrs[i][0]) { - case "color": - case "face": - case "size": - return true; - } - } - return false; - } - - var current; - - switch(t) { - case 1: // TEXT - // If any non-space, non-nul characters - if (frameset_ok && NONWSNONNUL.test(value)) - frameset_ok = false; - if (textIncludesNUL) { - value = value.replace(NULCHARS, "\uFFFD"); - } - insertText(value); - return; - case 4: // COMMENT - insertComment(value); - return; - case 5: // DOCTYPE - // ignore it - return; - case 2: // TAG - switch(value) { - case "font": - if (!isHTMLFont(arg3)) break; - /* falls through */ - case "b": - case "big": - case "blockquote": - case "body": - case "br": - case "center": - case "code": - case "dd": - case "div": - case "dl": - case "dt": - case "em": - case "embed": - case "h1": - case "h2": - case "h3": - case "h4": - case "h5": - case "h6": - case "head": - case "hr": - case "i": - case "img": - case "li": - case "listing": - case "menu": - case "meta": - case "nobr": - case "ol": - case "p": - case "pre": - case "ruby": - case "s": - case "small": - case "span": - case "strong": - case "strike": - case "sub": - case "sup": - case "table": - case "tt": - case "u": - case "ul": - case "var": - if (fragment) { - break; - } - do { - stack.pop(); - current = stack.top; - } while(current.namespaceURI !== NAMESPACE.HTML && - !isMathmlTextIntegrationPoint(current) && - !isHTMLIntegrationPoint(current)); - - insertToken(t, value, arg3, arg4); // reprocess - return; - } - - // Any other start tag case goes here - current = (stack.elements.length===1 && fragment) ? fragmentContext : - stack.top; - if (current.namespaceURI === NAMESPACE.MATHML) { - adjustMathMLAttributes(arg3); - } - else if (current.namespaceURI === NAMESPACE.SVG) { - value = adjustSVGTagName(value); - adjustSVGAttributes(arg3); - } - adjustForeignAttributes(arg3); - - insertForeignElement(value, arg3, current.namespaceURI); - if (arg4) { // the self-closing flag - if (value === 'script' && current.namespaceURI === NAMESPACE.SVG) { - // XXX deal with SVG scripts here - } - stack.pop(); - } - return; - - case 3: // ENDTAG - current = stack.top; - if (value === "script" && - current.namespaceURI === NAMESPACE.SVG && - current.localName === "script") { - - stack.pop(); - - // XXX - // Deal with SVG scripts here - } - else { - // The any other end tag case - var i = stack.elements.length-1; - var node = stack.elements[i]; - for(;;) { - if (node.localName.toLowerCase() === value) { - stack.popElement(node); - break; - } - node = stack.elements[--i]; - // If non-html, keep looping - if (node.namespaceURI !== NAMESPACE.HTML) - continue; - // Otherwise process the end tag as html - parser(t, value, arg3, arg4); - break; - } - } - return; - } - } - - /*** - * Finally, this is the end of the HTMLParser() factory function. - * It returns the htmlparser object with the append() and end() methods. - */ - - // Sneak another method into the htmlparser object to allow us to run - // tokenizer tests. This can be commented out in production code. - // This is a hook for testing the tokenizer. It has to be here - // because the tokenizer details are all hidden away within the closure. - // It should return an array of tokens generated while parsing the - // input string. - htmlparser.testTokenizer = function(input, initialState, lastStartTag, charbychar) { - var tokens = []; - - switch(initialState) { - case "PCDATA state": - tokenizer = data_state; - break; - case "RCDATA state": - tokenizer = rcdata_state; - break; - case "RAWTEXT state": - tokenizer = rawtext_state; - break; - case "PLAINTEXT state": - tokenizer = plaintext_state; - break; - } - - if (lastStartTag) { - lasttagname = lastStartTag; - } - - insertToken = function(t, value, arg3, arg4) { - flushText(); - switch(t) { - case 1: // TEXT - if (tokens.length > 0 && - tokens[tokens.length-1][0] === "Character") { - tokens[tokens.length-1][1] += value; - } - else tokens.push(["Character", value]); - break; - case 4: // COMMENT - tokens.push(["Comment", value]); - break; - case 5: // DOCTYPE - tokens.push(["DOCTYPE", value, - arg3 === undefined ? null : arg3, - arg4 === undefined ? null : arg4, - !force_quirks]); - break; - case 2: // TAG - var attrs = Object.create(null); - for(var i = 0; i < arg3.length; i++) { - // XXX: does attribute order matter? - var a = arg3[i]; - if (a.length === 1) { - attrs[a[0]] = ""; - } - else { - attrs[a[0]] = a[1]; - } - } - var token = ["StartTag", value, attrs]; - if (arg4) token.push(true); - tokens.push(token); - break; - case 3: // ENDTAG - tokens.push(["EndTag", value]); - break; - case -1: // EOF - break; - } - }; - - if (!charbychar) { - this.parse(input, true); - } - else { - for(var i = 0; i < input.length; i++) { - this.parse(input[i]); - } - this.parse("", true); - } - return tokens; - }; - - // Return the parser object from the HTMLParser() factory function - return htmlparser; -} diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/Leaf.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/Leaf.js deleted file mode 100644 index 2b0fd57f..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/Leaf.js +++ /dev/null @@ -1,37 +0,0 @@ -"use strict"; -module.exports = Leaf; - -var Node = require('./Node'); -var NodeList = require('./NodeList'); -var utils = require('./utils'); -var HierarchyRequestError = utils.HierarchyRequestError; -var NotFoundError = utils.NotFoundError; - -// This class defines common functionality for node subtypes that -// can never have children -function Leaf() { - Node.call(this); -} - -Leaf.prototype = Object.create(Node.prototype, { - hasChildNodes: { value: function() { return false; }}, - firstChild: { value: null }, - lastChild: { value: null }, - insertBefore: { value: function(node, child) { - if (!node.nodeType) throw new TypeError('not a node'); - HierarchyRequestError(); - }}, - replaceChild: { value: function(node, child) { - if (!node.nodeType) throw new TypeError('not a node'); - HierarchyRequestError(); - }}, - removeChild: { value: function(node) { - if (!node.nodeType) throw new TypeError('not a node'); - NotFoundError(); - }}, - removeChildren: { value: function() { /* no op */ }}, - childNodes: { get: function() { - if (!this._childNodes) this._childNodes = new NodeList(); - return this._childNodes; - }} -}); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/LinkedList.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/LinkedList.js deleted file mode 100644 index f62885ed..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/LinkedList.js +++ /dev/null @@ -1,44 +0,0 @@ -"use strict"; -var utils = require('./utils'); - -var LinkedList = module.exports = { - // basic validity tests on a circular linked list a - valid: function(a) { - utils.assert(a, "list falsy"); - utils.assert(a._previousSibling, "previous falsy"); - utils.assert(a._nextSibling, "next falsy"); - // xxx check that list is actually circular - return true; - }, - // insert a before b - insertBefore: function(a, b) { - utils.assert(LinkedList.valid(a) && LinkedList.valid(b)); - var a_first = a, a_last = a._previousSibling; - var b_first = b, b_last = b._previousSibling; - a_first._previousSibling = b_last; - a_last._nextSibling = b_first; - b_last._nextSibling = a_first; - b_first._previousSibling = a_last; - utils.assert(LinkedList.valid(a) && LinkedList.valid(b)); - }, - // replace a single node a with a list b (which could be null) - replace: function(a, b) { - utils.assert(LinkedList.valid(a) && (b===null || LinkedList.valid(b))); - if (b!==null) { - LinkedList.insertBefore(b, a); - } - LinkedList.remove(a); - utils.assert(LinkedList.valid(a) && (b===null || LinkedList.valid(b))); - }, - // remove single node a from its list - remove: function(a) { - utils.assert(LinkedList.valid(a)); - var prev = a._previousSibling; - if (prev === a) { return; } - var next = a._nextSibling; - prev._nextSibling = next; - next._previousSibling = prev; - a._previousSibling = a._nextSibling = a; - utils.assert(LinkedList.valid(a)); - } -}; diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/Location.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/Location.js deleted file mode 100644 index ae091515..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/Location.js +++ /dev/null @@ -1,56 +0,0 @@ -"use strict"; -var URL = require('./URL'); -var URLUtils = require('./URLUtils'); - -module.exports = Location; - -function Location(window, href) { - this._window = window; - this._href = href; -} - -Location.prototype = Object.create(URLUtils.prototype, { - constructor: { value: Location }, - - // Special behavior when href is set - href: { - get: function() { return this._href; }, - set: function(v) { this.assign(v); } - }, - - assign: { value: function(url) { - // Resolve the new url against the current one - // XXX: - // This is not actually correct. It should be resolved against - // the URL of the document of the script. For now, though, I only - // support a single window and there is only one base url. - // So this is good enough for now. - var current = new URL(this._href); - var newurl = current.resolve(url); - - // Save the new url - this._href = newurl; - - // Start loading the new document! - // XXX - // This is just something hacked together. - // The real algorithm is: http://www.whatwg.org/specs/web-apps/current-work/multipage/history.html#navigate - }}, - - replace: { value: function(url) { - // XXX - // Since we aren't tracking history yet, replace is the same as assign - this.assign(url); - }}, - - reload: { value: function() { - // XXX: - // Actually, the spec is a lot more complicated than this - this.assign(this.href); - }}, - - toString: { value: function() { - return this.href; - }} - -}); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/MouseEvent.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/MouseEvent.js deleted file mode 100644 index fc3d69f6..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/MouseEvent.js +++ /dev/null @@ -1,52 +0,0 @@ -"use strict"; -var UIEvent = require('./UIEvent'); - -module.exports = MouseEvent; - -function MouseEvent() { - // Just use the superclass constructor to initialize - UIEvent.call(this); - - this.screenX = this.screenY = this.clientX = this.clientY = 0; - this.ctrlKey = this.altKey = this.shiftKey = this.metaKey = false; - this.button = 0; - this.buttons = 1; - this.relatedTarget = null; -} -MouseEvent.prototype = Object.create(UIEvent.prototype, { - constructor: { value: MouseEvent }, - initMouseEvent: { value: function(type, bubbles, cancelable, - view, detail, - screenX, screenY, clientX, clientY, - ctrlKey, altKey, shiftKey, metaKey, - button, relatedTarget) { - - this.initEvent(type, bubbles, cancelable, view, detail); - this.screenX = screenX; - this.screenY = screenY; - this.clientX = clientX; - this.clientY = clientY; - this.ctrlKey = ctrlKey; - this.altKey = altKey; - this.shiftKey = shiftKey; - this.metaKey = metaKey; - this.button = button; - switch(button) { - case 0: this.buttons = 1; break; - case 1: this.buttons = 4; break; - case 2: this.buttons = 2; break; - default: this.buttons = 0; break; - } - this.relatedTarget = relatedTarget; - }}, - - getModifierState: { value: function(key) { - switch(key) { - case "Alt": return this.altKey; - case "Control": return this.ctrlKey; - case "Shift": return this.shiftKey; - case "Meta": return this.metaKey; - default: return false; - } - }} -}); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/MutationConstants.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/MutationConstants.js deleted file mode 100644 index 81ddc3ee..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/MutationConstants.js +++ /dev/null @@ -1,9 +0,0 @@ -"use strict"; -module.exports = { - VALUE: 1, // The value of a Text, Comment or PI node changed - ATTR: 2, // A new attribute was added or an attribute value and/or prefix changed - REMOVE_ATTR: 3, // An attribute was removed - REMOVE: 4, // A node was removed - MOVE: 5, // A node was moved - INSERT: 6 // A node (or a subtree of nodes) was inserted -}; \ No newline at end of file diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/NamedNodeMap.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/NamedNodeMap.js deleted file mode 100644 index 01c48018..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/NamedNodeMap.js +++ /dev/null @@ -1,41 +0,0 @@ -"use strict"; -module.exports = NamedNodeMap; - -var utils = require('./utils'); - -/* This is a hacky implementation of NamedNodeMap, intended primarily to - * satisfy clients (like dompurify and the web-platform-tests) which check - * to ensure that Node#attributes instanceof NamedNodeMap. */ - -function NamedNodeMap(element) { - this.element = element; -} -Object.defineProperties(NamedNodeMap.prototype, { - length: { get: utils.shouldOverride }, - item: { value: utils.shouldOverride }, - - getNamedItem: { value: function getNamedItem(qualifiedName) { - return this.element.getAttributeNode(qualifiedName); - } }, - getNamedItemNS: { value: function getNamedItemNS(namespace, localName) { - return this.element.getAttributeNodeNS(namespace, localName); - } }, - setNamedItem: { value: utils.nyi }, - setNamedItemNS: { value: utils.nyi }, - removeNamedItem: { value: function removeNamedItem(qualifiedName) { - var attr = this.element.getAttributeNode(qualifiedName); - if (attr) { - this.element.removeAttribute(qualifiedName); - return attr; - } - utils.NotFoundError(); - } }, - removeNamedItemNS: { value: function removeNamedItemNS(ns, lname) { - var attr = this.element.getAttributeNodeNS(ns, lname); - if (attr) { - this.element.removeAttributeNS(ns, lname); - return attr; - } - utils.NotFoundError(); - } }, -}); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/NavigatorID.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/NavigatorID.js deleted file mode 100644 index d6f985cb..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/NavigatorID.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; - -// https://html.spec.whatwg.org/multipage/webappapis.html#navigatorid -var NavigatorID = Object.create(null, { - appCodeName: { value: "Mozilla" }, - appName: { value: "Netscape" }, - appVersion: { value: "4.0" }, - platform: { value: "" }, - product: { value: "Gecko" }, - productSub: { value: "20100101" }, - userAgent: { value: "" }, - vendor: { value: "" }, - vendorSub: { value: "" }, - taintEnabled: { value: function() { return false; } } -}); - -module.exports = NavigatorID; diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/Node.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/Node.js deleted file mode 100644 index e8ac690f..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/Node.js +++ /dev/null @@ -1,764 +0,0 @@ -"use strict"; -module.exports = Node; - -var EventTarget = require('./EventTarget'); -var LinkedList = require('./LinkedList'); -var NodeUtils = require('./NodeUtils'); -var utils = require('./utils'); - -// All nodes have a nodeType and an ownerDocument. -// Once inserted, they also have a parentNode. -// This is an abstract class; all nodes in a document are instances -// of a subtype, so all the properties are defined by more specific -// constructors. -function Node() { - EventTarget.call(this); - this.parentNode = null; - this._nextSibling = this._previousSibling = this; - this._index = undefined; -} - -var ELEMENT_NODE = Node.ELEMENT_NODE = 1; -var ATTRIBUTE_NODE = Node.ATTRIBUTE_NODE = 2; -var TEXT_NODE = Node.TEXT_NODE = 3; -var CDATA_SECTION_NODE = Node.CDATA_SECTION_NODE = 4; -var ENTITY_REFERENCE_NODE = Node.ENTITY_REFERENCE_NODE = 5; -var ENTITY_NODE = Node.ENTITY_NODE = 6; -var PROCESSING_INSTRUCTION_NODE = Node.PROCESSING_INSTRUCTION_NODE = 7; -var COMMENT_NODE = Node.COMMENT_NODE = 8; -var DOCUMENT_NODE = Node.DOCUMENT_NODE = 9; -var DOCUMENT_TYPE_NODE = Node.DOCUMENT_TYPE_NODE = 10; -var DOCUMENT_FRAGMENT_NODE = Node.DOCUMENT_FRAGMENT_NODE = 11; -var NOTATION_NODE = Node.NOTATION_NODE = 12; - -var DOCUMENT_POSITION_DISCONNECTED = Node.DOCUMENT_POSITION_DISCONNECTED = 0x01; -var DOCUMENT_POSITION_PRECEDING = Node.DOCUMENT_POSITION_PRECEDING = 0x02; -var DOCUMENT_POSITION_FOLLOWING = Node.DOCUMENT_POSITION_FOLLOWING = 0x04; -var DOCUMENT_POSITION_CONTAINS = Node.DOCUMENT_POSITION_CONTAINS = 0x08; -var DOCUMENT_POSITION_CONTAINED_BY = Node.DOCUMENT_POSITION_CONTAINED_BY = 0x10; -var DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 0x20; - -Node.prototype = Object.create(EventTarget.prototype, { - - // Node that are not inserted into the tree inherit a null parent - - // XXX: the baseURI attribute is defined by dom core, but - // a correct implementation of it requires HTML features, so - // we'll come back to this later. - baseURI: { get: utils.nyi }, - - parentElement: { get: function() { - return (this.parentNode && this.parentNode.nodeType===ELEMENT_NODE) ? this.parentNode : null; - }}, - - hasChildNodes: { value: utils.shouldOverride }, - - firstChild: { get: utils.shouldOverride }, - - lastChild: { get: utils.shouldOverride }, - - isConnected: { - get: function () { - let node = this; - while (node != null) { - if (node.nodeType === Node.DOCUMENT_NODE) { - return true; - } - - node = node.parentNode; - if (node != null && node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { - node = node.host; - } - } - return false; - }, - }, - - previousSibling: { get: function() { - var parent = this.parentNode; - if (!parent) return null; - if (this === parent.firstChild) return null; - return this._previousSibling; - }}, - - nextSibling: { get: function() { - var parent = this.parentNode, next = this._nextSibling; - if (!parent) return null; - if (next === parent.firstChild) return null; - return next; - }}, - - textContent: { - // Should override for DocumentFragment/Element/Attr/Text/PI/Comment - get: function() { return null; }, - set: function(v) { /* do nothing */ }, - }, - - innerText: { - // Should override for DocumentFragment/Element/Attr/Text/PI/Comment - get: function() { return null; }, - set: function(v) { /* do nothing */ }, - }, - - _countChildrenOfType: { value: function(type) { - var sum = 0; - for (var kid = this.firstChild; kid !== null; kid = kid.nextSibling) { - if (kid.nodeType === type) sum++; - } - return sum; - }}, - - _ensureInsertValid: { value: function _ensureInsertValid(node, child, isPreinsert) { - var parent = this, i, kid; - if (!node.nodeType) throw new TypeError('not a node'); - // 1. If parent is not a Document, DocumentFragment, or Element - // node, throw a HierarchyRequestError. - switch (parent.nodeType) { - case DOCUMENT_NODE: - case DOCUMENT_FRAGMENT_NODE: - case ELEMENT_NODE: - break; - default: utils.HierarchyRequestError(); - } - // 2. If node is a host-including inclusive ancestor of parent, - // throw a HierarchyRequestError. - if (node.isAncestor(parent)) utils.HierarchyRequestError(); - // 3. If child is not null and its parent is not parent, then - // throw a NotFoundError. (replaceChild omits the 'child is not null' - // and throws a TypeError here if child is null.) - if (child !== null || !isPreinsert) { - if (child.parentNode !== parent) utils.NotFoundError(); - } - // 4. If node is not a DocumentFragment, DocumentType, Element, - // Text, ProcessingInstruction, or Comment node, throw a - // HierarchyRequestError. - switch (node.nodeType) { - case DOCUMENT_FRAGMENT_NODE: - case DOCUMENT_TYPE_NODE: - case ELEMENT_NODE: - case TEXT_NODE: - case PROCESSING_INSTRUCTION_NODE: - case COMMENT_NODE: - break; - default: utils.HierarchyRequestError(); - } - // 5. If either node is a Text node and parent is a document, or - // node is a doctype and parent is not a document, throw a - // HierarchyRequestError. - // 6. If parent is a document, and any of the statements below, switched - // on node, are true, throw a HierarchyRequestError. - if (parent.nodeType === DOCUMENT_NODE) { - switch (node.nodeType) { - case TEXT_NODE: - utils.HierarchyRequestError(); - break; - case DOCUMENT_FRAGMENT_NODE: - // 6a1. If node has more than one element child or has a Text - // node child. - if (node._countChildrenOfType(TEXT_NODE) > 0) - utils.HierarchyRequestError(); - switch (node._countChildrenOfType(ELEMENT_NODE)) { - case 0: - break; - case 1: - // 6a2. Otherwise, if node has one element child and either - // parent has an element child, child is a doctype, or child - // is not null and a doctype is following child. [preinsert] - // 6a2. Otherwise, if node has one element child and either - // parent has an element child that is not child or a - // doctype is following child. [replaceWith] - if (child !== null /* always true here for replaceWith */) { - if (isPreinsert && child.nodeType === DOCUMENT_TYPE_NODE) - utils.HierarchyRequestError(); - for (kid = child.nextSibling; kid !== null; kid = kid.nextSibling) { - if (kid.nodeType === DOCUMENT_TYPE_NODE) - utils.HierarchyRequestError(); - } - } - i = parent._countChildrenOfType(ELEMENT_NODE); - if (isPreinsert) { - // "parent has an element child" - if (i > 0) - utils.HierarchyRequestError(); - } else { - // "parent has an element child that is not child" - if (i > 1 || (i === 1 && child.nodeType !== ELEMENT_NODE)) - utils.HierarchyRequestError(); - } - break; - default: // 6a1, continued. (more than one Element child) - utils.HierarchyRequestError(); - } - break; - case ELEMENT_NODE: - // 6b. parent has an element child, child is a doctype, or - // child is not null and a doctype is following child. [preinsert] - // 6b. parent has an element child that is not child or a - // doctype is following child. [replaceWith] - if (child !== null /* always true here for replaceWith */) { - if (isPreinsert && child.nodeType === DOCUMENT_TYPE_NODE) - utils.HierarchyRequestError(); - for (kid = child.nextSibling; kid !== null; kid = kid.nextSibling) { - if (kid.nodeType === DOCUMENT_TYPE_NODE) - utils.HierarchyRequestError(); - } - } - i = parent._countChildrenOfType(ELEMENT_NODE); - if (isPreinsert) { - // "parent has an element child" - if (i > 0) - utils.HierarchyRequestError(); - } else { - // "parent has an element child that is not child" - if (i > 1 || (i === 1 && child.nodeType !== ELEMENT_NODE)) - utils.HierarchyRequestError(); - } - break; - case DOCUMENT_TYPE_NODE: - // 6c. parent has a doctype child, child is non-null and an - // element is preceding child, or child is null and parent has - // an element child. [preinsert] - // 6c. parent has a doctype child that is not child, or an - // element is preceding child. [replaceWith] - if (child === null) { - if (parent._countChildrenOfType(ELEMENT_NODE)) - utils.HierarchyRequestError(); - } else { - // child is always non-null for [replaceWith] case - for (kid = parent.firstChild; kid !== null; kid = kid.nextSibling) { - if (kid === child) break; - if (kid.nodeType === ELEMENT_NODE) - utils.HierarchyRequestError(); - } - } - i = parent._countChildrenOfType(DOCUMENT_TYPE_NODE); - if (isPreinsert) { - // "parent has an doctype child" - if (i > 0) - utils.HierarchyRequestError(); - } else { - // "parent has an doctype child that is not child" - if (i > 1 || (i === 1 && child.nodeType !== DOCUMENT_TYPE_NODE)) - utils.HierarchyRequestError(); - } - break; - } - } else { - // 5, continued: (parent is not a document) - if (node.nodeType === DOCUMENT_TYPE_NODE) utils.HierarchyRequestError(); - } - }}, - - insertBefore: { value: function insertBefore(node, child) { - var parent = this; - // 1. Ensure pre-insertion validity - parent._ensureInsertValid(node, child, true); - // 2. Let reference child be child. - var refChild = child; - // 3. If reference child is node, set it to node's next sibling - if (refChild === node) { refChild = node.nextSibling; } - // 4. Adopt node into parent's node document. - parent.doc.adoptNode(node); - // 5. Insert node into parent before reference child. - node._insertOrReplace(parent, refChild, false); - // 6. Return node - return node; - }}, - - - appendChild: { value: function(child) { - // This invokes _appendChild after doing validity checks. - return this.insertBefore(child, null); - }}, - - _appendChild: { value: function(child) { - child._insertOrReplace(this, null, false); - }}, - - removeChild: { value: function removeChild(child) { - var parent = this; - if (!child.nodeType) throw new TypeError('not a node'); - if (child.parentNode !== parent) utils.NotFoundError(); - child.remove(); - return child; - }}, - - // To replace a `child` with `node` within a `parent` (this) - replaceChild: { value: function replaceChild(node, child) { - var parent = this; - // Ensure validity (slight differences from pre-insertion check) - parent._ensureInsertValid(node, child, false); - // Adopt node into parent's node document. - if (node.doc !== parent.doc) { - // XXX adoptNode has side-effect of removing node from its parent - // and generating a mutation event, thus causing the _insertOrReplace - // to generate two deletes and an insert instead of a 'move' - // event. It looks like the new MutationObserver stuff avoids - // this problem, but for now let's only adopt (ie, remove `node` - // from its parent) here if we need to. - parent.doc.adoptNode(node); - } - // Do the replace. - node._insertOrReplace(parent, child, true); - return child; - }}, - - // See: http://ejohn.org/blog/comparing-document-position/ - contains: { value: function contains(node) { - if (node === null) { return false; } - if (this === node) { return true; /* inclusive descendant */ } - /* jshint bitwise: false */ - return (this.compareDocumentPosition(node) & - DOCUMENT_POSITION_CONTAINED_BY) !== 0; - }}, - - compareDocumentPosition: { value: function compareDocumentPosition(that){ - // Basic algorithm for finding the relative position of two nodes. - // Make a list the ancestors of each node, starting with the - // document element and proceeding down to the nodes themselves. - // Then, loop through the lists, looking for the first element - // that differs. The order of those two elements give the - // order of their descendant nodes. Or, if one list is a prefix - // of the other one, then that node contains the other. - - if (this === that) return 0; - - // If they're not owned by the same document or if one is rooted - // and one is not, then they're disconnected. - if (this.doc !== that.doc || - this.rooted !== that.rooted) - return (DOCUMENT_POSITION_DISCONNECTED + - DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC); - - // Get arrays of ancestors for this and that - var these = [], those = []; - for(var n = this; n !== null; n = n.parentNode) these.push(n); - for(n = that; n !== null; n = n.parentNode) those.push(n); - these.reverse(); // So we start with the outermost - those.reverse(); - - if (these[0] !== those[0]) // No common ancestor - return (DOCUMENT_POSITION_DISCONNECTED + - DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC); - - n = Math.min(these.length, those.length); - for(var i = 1; i < n; i++) { - if (these[i] !== those[i]) { - // We found two different ancestors, so compare - // their positions - if (these[i].index < those[i].index) - return DOCUMENT_POSITION_FOLLOWING; - else - return DOCUMENT_POSITION_PRECEDING; - } - } - - // If we get to here, then one of the nodes (the one with the - // shorter list of ancestors) contains the other one. - if (these.length < those.length) - return (DOCUMENT_POSITION_FOLLOWING + - DOCUMENT_POSITION_CONTAINED_BY); - else - return (DOCUMENT_POSITION_PRECEDING + - DOCUMENT_POSITION_CONTAINS); - }}, - - isSameNode: {value : function isSameNode(node) { - return this === node; - }}, - - - // This method implements the generic parts of node equality testing - // and defers to the (non-recursive) type-specific isEqual() method - // defined by subclasses - isEqualNode: { value: function isEqualNode(node) { - if (!node) return false; - if (node.nodeType !== this.nodeType) return false; - - // Check type-specific properties for equality - if (!this.isEqual(node)) return false; - - // Now check children for number and equality - for (var c1 = this.firstChild, c2 = node.firstChild; - c1 && c2; - c1 = c1.nextSibling, c2 = c2.nextSibling) { - if (!c1.isEqualNode(c2)) return false; - } - return c1 === null && c2 === null; - }}, - - // This method delegates shallow cloning to a clone() method - // that each concrete subclass must implement - cloneNode: { value: function(deep) { - // Clone this node - var clone = this.clone(); - - // Handle the recursive case if necessary - if (deep) { - for (var kid = this.firstChild; kid !== null; kid = kid.nextSibling) { - clone._appendChild(kid.cloneNode(true)); - } - } - - return clone; - }}, - - lookupPrefix: { value: function lookupPrefix(ns) { - var e; - if (ns === '' || ns === null || ns === undefined) return null; - switch(this.nodeType) { - case ELEMENT_NODE: - return this._lookupNamespacePrefix(ns, this); - case DOCUMENT_NODE: - e = this.documentElement; - return e ? e.lookupPrefix(ns) : null; - case ENTITY_NODE: - case NOTATION_NODE: - case DOCUMENT_FRAGMENT_NODE: - case DOCUMENT_TYPE_NODE: - return null; - case ATTRIBUTE_NODE: - e = this.ownerElement; - return e ? e.lookupPrefix(ns) : null; - default: - e = this.parentElement; - return e ? e.lookupPrefix(ns) : null; - } - }}, - - - lookupNamespaceURI: {value: function lookupNamespaceURI(prefix) { - if (prefix === '' || prefix === undefined) { prefix = null; } - var e; - switch(this.nodeType) { - case ELEMENT_NODE: - return utils.shouldOverride(); - case DOCUMENT_NODE: - e = this.documentElement; - return e ? e.lookupNamespaceURI(prefix) : null; - case ENTITY_NODE: - case NOTATION_NODE: - case DOCUMENT_TYPE_NODE: - case DOCUMENT_FRAGMENT_NODE: - return null; - case ATTRIBUTE_NODE: - e = this.ownerElement; - return e ? e.lookupNamespaceURI(prefix) : null; - default: - e = this.parentElement; - return e ? e.lookupNamespaceURI(prefix) : null; - } - }}, - - isDefaultNamespace: { value: function isDefaultNamespace(ns) { - if (ns === '' || ns === undefined) { ns = null; } - var defaultNamespace = this.lookupNamespaceURI(null); - return (defaultNamespace === ns); - }}, - - // Utility methods for nodes. Not part of the DOM - - // Return the index of this node in its parent. - // Throw if no parent, or if this node is not a child of its parent - index: { get: function() { - var parent = this.parentNode; - if (this === parent.firstChild) return 0; // fast case - var kids = parent.childNodes; - if (this._index === undefined || kids[this._index] !== this) { - // Ensure that we don't have an O(N^2) blowup if none of the - // kids have defined indices yet and we're traversing via - // nextSibling or previousSibling - for (var i=0; i 2 ? spliceArgs[2] : null); - } else if (len > 2 && n !== null) { - LinkedList.insertBefore(spliceArgs[2], n); - } - if (parent._childNodes) { - spliceArgs[0] = (before === null) ? - parent._childNodes.length : before._index; - parent._childNodes.splice.apply(parent._childNodes, spliceArgs); - for (i=2; i 2) { - parent._firstChild = spliceArgs[2]; - } else if (isReplace) { - parent._firstChild = null; - } - } - // Remove all nodes from the document fragment - if (child._childNodes) { - child._childNodes.length = 0; - } else { - child._firstChild = null; - } - // Call the mutation handlers - // Use spliceArgs since the original array has been destroyed. The - // liveness guarantee requires us to clone the array so that - // references to the childNodes of the DocumentFragment will be empty - // when the insertion handlers are called. - if (parent.rooted) { - parent.modify(); - for (i = 2; i < len; i++) { - parent.doc.mutateInsert(spliceArgs[i]); - } - } - } else { - if (before === child) { return; } - if (bothRooted) { - // Remove the child from its current position in the tree - // without calling remove(), since we don't want to uproot it. - child._remove(); - } else if (child.parentNode) { - child.remove(); - } - - // Insert it as a child of its new parent - child.parentNode = parent; - if (isReplace) { - LinkedList.replace(n, child); - if (parent._childNodes) { - child._index = before_index; - parent._childNodes[before_index] = child; - } else if (parent._firstChild === before) { - parent._firstChild = child; - } - } else { - if (n !== null) { - LinkedList.insertBefore(child, n); - } - if (parent._childNodes) { - child._index = before_index; - parent._childNodes.splice(before_index, 0, child); - } else if (parent._firstChild === before) { - parent._firstChild = child; - } - } - if (bothRooted) { - parent.modify(); - // Generate a move mutation event - parent.doc.mutateMove(child); - } else if (parent.rooted) { - parent.modify(); - parent.doc.mutateInsert(child); - } - } - }}, - - - // Return the lastModTime value for this node. (For use as a - // cache invalidation mechanism. If the node does not already - // have one, initialize it from the owner document's modclock - // property. (Note that modclock does not return the actual - // time; it is simply a counter incremented on each document - // modification) - lastModTime: { get: function() { - if (!this._lastModTime) { - this._lastModTime = this.doc.modclock; - } - return this._lastModTime; - }}, - - // Increment the owner document's modclock and use the new - // value to update the lastModTime value for this node and - // all of its ancestors. Nodes that have never had their - // lastModTime value queried do not need to have a - // lastModTime property set on them since there is no - // previously queried value to ever compare the new value - // against, so only update nodes that already have a - // _lastModTime property. - modify: { value: function() { - if (this.doc.modclock) { // Skip while doc.modclock == 0 - var time = ++this.doc.modclock; - for(var n = this; n; n = n.parentElement) { - if (n._lastModTime) { - n._lastModTime = time; - } - } - } - }}, - - // This attribute is not part of the DOM but is quite helpful. - // It returns the document with which a node is associated. Usually - // this is the ownerDocument. But ownerDocument is null for the - // document object itself, so this is a handy way to get the document - // regardless of the node type - doc: { get: function() { - return this.ownerDocument || this; - }}, - - - // If the node has a nid (node id), then it is rooted in a document - rooted: { get: function() { - return !!this._nid; - }}, - - normalize: { value: function() { - var next; - for (var child=this.firstChild; child !== null; child=next) { - next = child.nextSibling; - - if (child.normalize) { - child.normalize(); - } - - if (child.nodeType !== Node.TEXT_NODE) { - continue; - } - - if (child.nodeValue === "") { - this.removeChild(child); - continue; - } - - var prevChild = child.previousSibling; - if (prevChild === null) { - continue; - } else if (prevChild.nodeType === Node.TEXT_NODE) { - // merge this with previous and remove the child - prevChild.appendData(child.nodeValue); - this.removeChild(child); - } - } - }}, - - // Convert the children of a node to an HTML string. - // This is used by the innerHTML getter - // The serialization spec is at: - // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-end.html#serializing-html-fragments - // - // The serialization logic is intentionally implemented in a separate - // `NodeUtils` helper instead of the more obvious choice of a private - // `_serializeOne()` method on the `Node.prototype` in order to avoid - // the megamorphic `this._serializeOne` property access, which reduces - // performance unnecessarily. If you need specialized behavior for a - // certain subclass, you'll need to implement that in `NodeUtils`. - // See https://github.com/fgnass/domino/pull/142 for more information. - serialize: { value: function() { - if (this._innerHTML) { - return this._innerHTML; - } - var s = ''; - for (var kid = this.firstChild; kid !== null; kid = kid.nextSibling) { - s += NodeUtils.serializeOne(kid, this); - } - return s; - }}, - - // Non-standard, but often useful for debugging. - outerHTML: { - get: function() { - return NodeUtils.serializeOne(this, { nodeType: 0 }); - }, - set: utils.nyi, - }, - - // mirror node type properties in the prototype, so they are present - // in instances of Node (and subclasses) - ELEMENT_NODE: { value: ELEMENT_NODE }, - ATTRIBUTE_NODE: { value: ATTRIBUTE_NODE }, - TEXT_NODE: { value: TEXT_NODE }, - CDATA_SECTION_NODE: { value: CDATA_SECTION_NODE }, - ENTITY_REFERENCE_NODE: { value: ENTITY_REFERENCE_NODE }, - ENTITY_NODE: { value: ENTITY_NODE }, - PROCESSING_INSTRUCTION_NODE: { value: PROCESSING_INSTRUCTION_NODE }, - COMMENT_NODE: { value: COMMENT_NODE }, - DOCUMENT_NODE: { value: DOCUMENT_NODE }, - DOCUMENT_TYPE_NODE: { value: DOCUMENT_TYPE_NODE }, - DOCUMENT_FRAGMENT_NODE: { value: DOCUMENT_FRAGMENT_NODE }, - NOTATION_NODE: { value: NOTATION_NODE }, - - DOCUMENT_POSITION_DISCONNECTED: { value: DOCUMENT_POSITION_DISCONNECTED }, - DOCUMENT_POSITION_PRECEDING: { value: DOCUMENT_POSITION_PRECEDING }, - DOCUMENT_POSITION_FOLLOWING: { value: DOCUMENT_POSITION_FOLLOWING }, - DOCUMENT_POSITION_CONTAINS: { value: DOCUMENT_POSITION_CONTAINS }, - DOCUMENT_POSITION_CONTAINED_BY: { value: DOCUMENT_POSITION_CONTAINED_BY }, - DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC: { value: DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC }, -}); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeFilter.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeFilter.js deleted file mode 100644 index efa51830..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeFilter.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -var NodeFilter = { - // Constants for acceptNode() - FILTER_ACCEPT: 1, - FILTER_REJECT: 2, - FILTER_SKIP: 3, - - // Constants for whatToShow - SHOW_ALL: 0xFFFFFFFF, - SHOW_ELEMENT: 0x1, - SHOW_ATTRIBUTE: 0x2, // historical - SHOW_TEXT: 0x4, - SHOW_CDATA_SECTION: 0x8, // historical - SHOW_ENTITY_REFERENCE: 0x10, // historical - SHOW_ENTITY: 0x20, // historical - SHOW_PROCESSING_INSTRUCTION: 0x40, - SHOW_COMMENT: 0x80, - SHOW_DOCUMENT: 0x100, - SHOW_DOCUMENT_TYPE: 0x200, - SHOW_DOCUMENT_FRAGMENT: 0x400, - SHOW_NOTATION: 0x800 // historical -}; - -module.exports = (NodeFilter.constructor = NodeFilter.prototype = NodeFilter); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeIterator.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeIterator.js deleted file mode 100644 index 8a2d90d3..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeIterator.js +++ /dev/null @@ -1,217 +0,0 @@ -"use strict"; -module.exports = NodeIterator; - -var NodeFilter = require('./NodeFilter'); -var NodeTraversal = require('./NodeTraversal'); -var utils = require('./utils'); - -/* Private methods and helpers */ - -/** - * @based on WebKit's NodeIterator::moveToNext and NodeIterator::moveToPrevious - * https://trac.webkit.org/browser/trunk/Source/WebCore/dom/NodeIterator.cpp?rev=186279#L51 - */ -function move(node, stayWithin, directionIsNext) { - if (directionIsNext) { - return NodeTraversal.next(node, stayWithin); - } else { - if (node === stayWithin) { - return null; - } - return NodeTraversal.previous(node, null); - } -} - -function isInclusiveAncestor(node, possibleChild) { - for ( ; possibleChild; possibleChild = possibleChild.parentNode) { - if (node === possibleChild) { return true; } - } - return false; -} - -/** - * @spec http://www.w3.org/TR/dom/#concept-nodeiterator-traverse - * @method - * @access private - * @param {NodeIterator} ni - * @param {string} direction One of 'next' or 'previous'. - * @return {Node|null} - */ -function traverse(ni, directionIsNext) { - var node, beforeNode; - node = ni._referenceNode; - beforeNode = ni._pointerBeforeReferenceNode; - while (true) { - if (beforeNode === directionIsNext) { - beforeNode = !beforeNode; - } else { - node = move(node, ni._root, directionIsNext); - if (node === null) { - return null; - } - } - var result = ni._internalFilter(node); - if (result === NodeFilter.FILTER_ACCEPT) { - break; - } - } - ni._referenceNode = node; - ni._pointerBeforeReferenceNode = beforeNode; - return node; -} - -/* Public API */ - -/** - * Implemented version: http://www.w3.org/TR/2015/WD-dom-20150618/#nodeiterator - * Latest version: http://www.w3.org/TR/dom/#nodeiterator - * - * @constructor - * @param {Node} root - * @param {number} whatToShow [optional] - * @param {Function|NodeFilter} filter [optional] - * @throws Error - */ -function NodeIterator(root, whatToShow, filter) { - if (!root || !root.nodeType) { - utils.NotSupportedError(); - } - - // Read-only properties - this._root = root; - this._referenceNode = root; - this._pointerBeforeReferenceNode = true; - this._whatToShow = Number(whatToShow) || 0; - this._filter = filter || null; - this._active = false; - // Record active node iterators in the document, in order to perform - // "node iterator pre-removal steps". - root.doc._attachNodeIterator(this); -} - -Object.defineProperties(NodeIterator.prototype, { - root: { get: function root() { - return this._root; - } }, - referenceNode: { get: function referenceNode() { - return this._referenceNode; - } }, - pointerBeforeReferenceNode: { get: function pointerBeforeReferenceNode() { - return this._pointerBeforeReferenceNode; - } }, - whatToShow: { get: function whatToShow() { - return this._whatToShow; - } }, - filter: { get: function filter() { - return this._filter; - } }, - - /** - * @method - * @param {Node} node - * @return {Number} Constant NodeFilter.FILTER_ACCEPT, - * NodeFilter.FILTER_REJECT or NodeFilter.FILTER_SKIP. - */ - _internalFilter: { value: function _internalFilter(node) { - /* jshint bitwise: false */ - var result, filter; - if (this._active) { - utils.InvalidStateError(); - } - - // Maps nodeType to whatToShow - if (!(((1 << (node.nodeType - 1)) & this._whatToShow))) { - return NodeFilter.FILTER_SKIP; - } - - filter = this._filter; - if (filter === null) { - result = NodeFilter.FILTER_ACCEPT; - } else { - this._active = true; - try { - if (typeof filter === 'function') { - result = filter(node); - } else { - result = filter.acceptNode(node); - } - } finally { - this._active = false; - } - } - - // Note that coercing to a number means that - // `true` becomes `1` (which is NodeFilter.FILTER_ACCEPT) - // `false` becomes `0` (neither accept, reject, or skip) - return (+result); - } }, - - /** - * @spec https://dom.spec.whatwg.org/#nodeiterator-pre-removing-steps - * @method - * @return void - */ - _preremove: { value: function _preremove(toBeRemovedNode) { - if (isInclusiveAncestor(toBeRemovedNode, this._root)) { return; } - if (!isInclusiveAncestor(toBeRemovedNode, this._referenceNode)) { return; } - if (this._pointerBeforeReferenceNode) { - var next = toBeRemovedNode; - while (next.lastChild) { - next = next.lastChild; - } - next = NodeTraversal.next(next, this.root); - if (next) { - this._referenceNode = next; - return; - } - this._pointerBeforeReferenceNode = false; - // fall through - } - if (toBeRemovedNode.previousSibling === null) { - this._referenceNode = toBeRemovedNode.parentNode; - } else { - this._referenceNode = toBeRemovedNode.previousSibling; - var lastChild; - for (lastChild = this._referenceNode.lastChild; - lastChild; - lastChild = this._referenceNode.lastChild) { - this._referenceNode = lastChild; - } - } - } }, - - /** - * @spec http://www.w3.org/TR/dom/#dom-nodeiterator-nextnode - * @method - * @return {Node|null} - */ - nextNode: { value: function nextNode() { - return traverse(this, true); - } }, - - /** - * @spec http://www.w3.org/TR/dom/#dom-nodeiterator-previousnode - * @method - * @return {Node|null} - */ - previousNode: { value: function previousNode() { - return traverse(this, false); - } }, - - /** - * @spec http://www.w3.org/TR/dom/#dom-nodeiterator-detach - * @method - * @return void - */ - detach: { value: function detach() { - /* "The detach() method must do nothing. - * Its functionality (disabling a NodeIterator object) was removed, - * but the method itself is preserved for compatibility. - */ - } }, - - /** For compatibility with web-platform-tests. */ - toString: { value: function toString() { - return "[object NodeIterator]"; - } }, -}); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeList.es5.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeList.es5.js deleted file mode 100644 index dede302c..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeList.es5.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; - -// No support for subclassing array, return an actual Array object. -function item(i) { - /* jshint validthis: true */ - return this[i] || null; -} - -function NodeList(a) { - if (!a) a = []; - a.item = item; - return a; -} - -module.exports = NodeList; diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeList.es6.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeList.es6.js deleted file mode 100644 index ee47bfab..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeList.es6.js +++ /dev/null @@ -1,12 +0,0 @@ -/* jshint esversion: 6 */ -"use strict"; - -module.exports = class NodeList extends Array { - constructor(a) { - super((a && a.length) || 0); - if (a) { - for (var idx in a) { this[idx] = a[idx]; } - } - } - item(i) { return this[i] || null; } -}; diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeList.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeList.js deleted file mode 100644 index cff8fae3..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeList.js +++ /dev/null @@ -1,13 +0,0 @@ -"use strict"; - -var NodeList; - -try { - // Attempt to use ES6-style Array subclass if possible. - NodeList = require('./NodeList.es6.js'); -} catch (e) { - // No support for subclassing array, return an actual Array object. - NodeList = require('./NodeList.es5.js'); -} - -module.exports = NodeList; diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeTraversal.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeTraversal.js deleted file mode 100644 index 1d3648dd..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeTraversal.js +++ /dev/null @@ -1,87 +0,0 @@ -"use strict"; -/* exported NodeTraversal */ -var NodeTraversal = module.exports = { - nextSkippingChildren: nextSkippingChildren, - nextAncestorSibling: nextAncestorSibling, - next: next, - previous: previous, - deepLastChild: deepLastChild -}; - -/** - * @based on WebKit's NodeTraversal::nextSkippingChildren - * https://trac.webkit.org/browser/trunk/Source/WebCore/dom/NodeTraversal.h?rev=179143#L109 - */ -function nextSkippingChildren(node, stayWithin) { - if (node === stayWithin) { - return null; - } - if (node.nextSibling !== null) { - return node.nextSibling; - } - return nextAncestorSibling(node, stayWithin); -} - -/** - * @based on WebKit's NodeTraversal::nextAncestorSibling - * https://trac.webkit.org/browser/trunk/Source/WebCore/dom/NodeTraversal.cpp?rev=179143#L93 - */ -function nextAncestorSibling(node, stayWithin) { - for (node = node.parentNode; node !== null; node = node.parentNode) { - if (node === stayWithin) { - return null; - } - if (node.nextSibling !== null) { - return node.nextSibling; - } - } - return null; -} - -/** - * @based on WebKit's NodeTraversal::next - * https://trac.webkit.org/browser/trunk/Source/WebCore/dom/NodeTraversal.h?rev=179143#L99 - */ -function next(node, stayWithin) { - var n; - n = node.firstChild; - if (n !== null) { - return n; - } - if (node === stayWithin) { - return null; - } - n = node.nextSibling; - if (n !== null) { - return n; - } - return nextAncestorSibling(node, stayWithin); -} - -/** - * @based on WebKit's NodeTraversal::deepLastChild - * https://trac.webkit.org/browser/trunk/Source/WebCore/dom/NodeTraversal.cpp?rev=179143#L116 - */ -function deepLastChild(node) { - while (node.lastChild) { - node = node.lastChild; - } - return node; -} - -/** - * @based on WebKit's NodeTraversal::previous - * https://trac.webkit.org/browser/trunk/Source/WebCore/dom/NodeTraversal.h?rev=179143#L121 - */ -function previous(node, stayWithin) { - var p; - p = node.previousSibling; - if (p !== null) { - return deepLastChild(p); - } - p = node.parentNode; - if (p === stayWithin) { - return null; - } - return p; -} diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeUtils.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeUtils.js deleted file mode 100644 index b10e3596..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/NodeUtils.js +++ /dev/null @@ -1,246 +0,0 @@ -"use strict"; -module.exports = { - // NOTE: The `serializeOne()` function used to live on the `Node.prototype` - // as a private method `Node#_serializeOne(child)`, however that requires - // a megamorphic property access `this._serializeOne` just to get to the - // method, and this is being done on lots of different `Node` subclasses, - // which puts a lot of pressure on V8's megamorphic stub cache. So by - // moving the helper off of the `Node.prototype` and into a separate - // function in this helper module, we get a monomorphic property access - // `NodeUtils.serializeOne` to get to the function and reduce pressure - // on the megamorphic stub cache. - // See https://github.com/fgnass/domino/pull/142 for more information. - serializeOne: serializeOne, - - // Export util functions so that we can run extra test for them. - // Note: we prefix function names with `ɵ`, similar to what we do - // with internal functions in Angular packages. - ɵescapeMatchingClosingTag: escapeMatchingClosingTag, - ɵescapeClosingCommentTag: escapeClosingCommentTag, - ɵescapeProcessingInstructionContent: escapeProcessingInstructionContent -}; - -var utils = require('./utils'); -var NAMESPACE = utils.NAMESPACE; - -var hasRawContent = { - STYLE: true, - SCRIPT: true, - XMP: true, - IFRAME: true, - NOEMBED: true, - NOFRAMES: true, - PLAINTEXT: true -}; - -var emptyElements = { - area: true, - base: true, - basefont: true, - bgsound: true, - br: true, - col: true, - embed: true, - frame: true, - hr: true, - img: true, - input: true, - keygen: true, - link: true, - meta: true, - param: true, - source: true, - track: true, - wbr: true -}; - -var extraNewLine = { - /* Removed in https://github.com/whatwg/html/issues/944 - pre: true, - textarea: true, - listing: true - */ -}; - -const ESCAPE_REGEXP = /[&<>\u00A0]/g; -const ESCAPE_ATTR_REGEXP = /[&"<>\u00A0]/g; - -function escape(s) { - if (!ESCAPE_REGEXP.test(s)) { - // nothing to do, fast path - return s; - } - - return s.replace(ESCAPE_REGEXP, (c) => { - switch (c) { - case "&": - return "&"; - case "<": - return "<"; - case ">": - return ">"; - case "\u00A0": - return " "; - } - }); -} - -function escapeAttr(s) { - if (!ESCAPE_ATTR_REGEXP.test(s)) { - // nothing to do, fast path - return s; - } - - return s.replace(ESCAPE_ATTR_REGEXP, (c) => { - switch (c) { - case "<": - return "<"; - case ">": - return ">"; - case "&": - return "&"; - case '"': - return """; - case "\u00A0": - return " "; - } - }); -} - -function attrname(a) { - var ns = a.namespaceURI; - if (!ns) - return a.localName; - if (ns === NAMESPACE.XML) - return 'xml:' + a.localName; - if (ns === NAMESPACE.XLINK) - return 'xlink:' + a.localName; - - if (ns === NAMESPACE.XMLNS) { - if (a.localName === 'xmlns') return 'xmlns'; - else return 'xmlns:' + a.localName; - } - return a.name; -} - -/** - * Escapes matching closing tag in a raw text. - * - * For example, given `)`, - * the parent tag would by "style" and the raw text is - * "". If we come across a matching closing tag - * (in out case ``) - replace `<` with `<` to avoid unexpected - * and unsafe behavior after de-serialization. - */ -function escapeMatchingClosingTag(rawText, parentTag) { - const parentClosingTag = '/; - -/** - * Escapes closing comment tag in a comment content. - * - * For example, given `#comment('-->')`, the content of a comment would be - * updated to `-->` to avoid unexpected and unsafe behavior after - * de-serialization. - */ -function escapeClosingCommentTag(rawContent) { - if (!CLOSING_COMMENT_REGEXP.test(rawContent)) { - return rawContent; // fast path - } - return rawContent.replace(/(--\!?)>/g, '$1>'); -} - -/** - * Escapes processing instruction content by replacing `>` with `>`. - */ -function escapeProcessingInstructionContent(rawContent) { - return rawContent.includes('>') - ? rawContent.replaceAll('>', '>') - : rawContent; -} - -function serializeOne(kid, parent) { - var s = ''; - switch(kid.nodeType) { - case 1: //ELEMENT_NODE - var ns = kid.namespaceURI; - var html = ns === NAMESPACE.HTML; - var tagname = (html || ns === NAMESPACE.SVG || ns === NAMESPACE.MATHML) ? kid.localName : kid.tagName; - - s += '<' + tagname; - - for(var j = 0, k = kid._numattrs; j < k; j++) { - var a = kid._attr(j); - s += ' ' + attrname(a); - if (a.value !== undefined) s += '="' + escapeAttr(a.value) + '"'; - } - s += '>'; - - if (!(html && emptyElements[tagname])) { - var ss = kid.serialize(); - // If an element can have raw content, this content may - // potentially require escaping to avoid XSS. - if (hasRawContent[tagname.toUpperCase()]) { - ss = escapeMatchingClosingTag(ss, tagname); - } - if (html && extraNewLine[tagname] && ss.charAt(0)==='\n') s += '\n'; - // Serialize children and add end tag for all others - s += ss; - s += ''; - } - break; - case 3: //TEXT_NODE - case 4: //CDATA_SECTION_NODE - var parenttag; - if (parent.nodeType === 1 /*ELEMENT_NODE*/ && - parent.namespaceURI === NAMESPACE.HTML) - parenttag = parent.tagName; - else - parenttag = ''; - - if (hasRawContent[parenttag] || - (parenttag==='NOSCRIPT' && parent.ownerDocument._scripting_enabled)) { - s += kid.data; - } else { - s += escape(kid.data); - } - break; - case 8: //COMMENT_NODE - s += ''; - break; - case 7: //PROCESSING_INSTRUCTION_NODE - const content = escapeProcessingInstructionContent(kid.data); - s += ''; - break; - case 10: //DOCUMENT_TYPE_NODE - s += ''; - break; - default: - utils.InvalidStateError(); - } - return s; -} diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/NonDocumentTypeChildNode.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/NonDocumentTypeChildNode.js deleted file mode 100644 index 38ed5d21..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/NonDocumentTypeChildNode.js +++ /dev/null @@ -1,26 +0,0 @@ -"use strict"; -var Node = require('./Node'); - -var NonDocumentTypeChildNode = { - - nextElementSibling: { get: function() { - if (this.parentNode) { - for (var kid = this.nextSibling; kid !== null; kid = kid.nextSibling) { - if (kid.nodeType === Node.ELEMENT_NODE) return kid; - } - } - return null; - }}, - - previousElementSibling: { get: function() { - if (this.parentNode) { - for (var kid = this.previousSibling; kid !== null; kid = kid.previousSibling) { - if (kid.nodeType === Node.ELEMENT_NODE) return kid; - } - } - return null; - }} - -}; - -module.exports = NonDocumentTypeChildNode; diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/ProcessingInstruction.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/ProcessingInstruction.js deleted file mode 100644 index 8056fb6c..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/ProcessingInstruction.js +++ /dev/null @@ -1,44 +0,0 @@ -"use strict"; -module.exports = ProcessingInstruction; - -var Node = require('./Node'); -var CharacterData = require('./CharacterData'); - -function ProcessingInstruction(doc, target, data) { - CharacterData.call(this); - this.nodeType = Node.PROCESSING_INSTRUCTION_NODE; - this.ownerDocument = doc; - this.target = target; - this._data = data; -} - -var nodeValue = { - get: function() { return this._data; }, - set: function(v) { - if (v === null || v === undefined) { v = ''; } else { v = String(v); } - this._data = v; - if (this.rooted) this.ownerDocument.mutateValue(this); - } -}; - -ProcessingInstruction.prototype = Object.create(CharacterData.prototype, { - nodeName: { get: function() { return this.target; }}, - nodeValue: nodeValue, - textContent: nodeValue, - innerText: nodeValue, - data: { - get: nodeValue.get, - set: function(v) { - nodeValue.set.call(this, v===null ? '' : String(v)); - }, - }, - - // Utility methods - clone: { value: function clone() { - return new ProcessingInstruction(this.ownerDocument, this.target, this._data); - }}, - isEqual: { value: function isEqual(n) { - return this.target === n.target && this._data === n._data; - }} - -}); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/Text.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/Text.js deleted file mode 100644 index 8ee099ad..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/Text.js +++ /dev/null @@ -1,75 +0,0 @@ -"use strict"; -module.exports = Text; - -var utils = require('./utils'); -var Node = require('./Node'); -var CharacterData = require('./CharacterData'); - -function Text(doc, data) { - CharacterData.call(this); - this.nodeType = Node.TEXT_NODE; - this.ownerDocument = doc; - this._data = data; - this._index = undefined; -} - -var nodeValue = { - get: function() { return this._data; }, - set: function(v) { - if (v === null || v === undefined) { v = ''; } else { v = String(v); } - if (v === this._data) return; - this._data = v; - if (this.rooted) - this.ownerDocument.mutateValue(this); - if (this.parentNode && - this.parentNode._textchangehook) - this.parentNode._textchangehook(this); - } -}; - -Text.prototype = Object.create(CharacterData.prototype, { - nodeName: { value: "#text" }, - // These three attributes are all the same. - // The data attribute has a [TreatNullAs=EmptyString] but we'll - // implement that at the interface level - nodeValue: nodeValue, - textContent: nodeValue, - innerText: nodeValue, - data: { - get: nodeValue.get, - set: function(v) { - nodeValue.set.call(this, v===null ? '' : String(v)); - }, - }, - - splitText: { value: function splitText(offset) { - if (offset > this._data.length || offset < 0) utils.IndexSizeError(); - - var newdata = this._data.substring(offset), - newnode = this.ownerDocument.createTextNode(newdata); - this.data = this.data.substring(0, offset); - - var parent = this.parentNode; - if (parent !== null) - parent.insertBefore(newnode, this.nextSibling); - - return newnode; - }}, - - wholeText: { get: function wholeText() { - var result = this.textContent; - for (var next = this.nextSibling; next; next = next.nextSibling) { - if (next.nodeType !== Node.TEXT_NODE) { break; } - result += next.textContent; - } - return result; - }}, - // Obsolete, removed from spec. - replaceWholeText: { value: utils.nyi }, - - // Utility methods - clone: { value: function clone() { - return new Text(this.ownerDocument, this._data); - }}, - -}); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/TreeWalker.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/TreeWalker.js deleted file mode 100644 index b23756d1..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/TreeWalker.js +++ /dev/null @@ -1,336 +0,0 @@ -"use strict"; -module.exports = TreeWalker; - -var Node = require('./Node'); -var NodeFilter = require('./NodeFilter'); -var NodeTraversal = require('./NodeTraversal'); -var utils = require('./utils'); - -var mapChild = { - first: 'firstChild', - last: 'lastChild', - next: 'firstChild', - previous: 'lastChild' -}; - -var mapSibling = { - first: 'nextSibling', - last: 'previousSibling', - next: 'nextSibling', - previous: 'previousSibling' -}; - -/* Private methods and helpers */ - -/** - * @spec https://dom.spec.whatwg.org/#concept-traverse-children - * @method - * @access private - * @param {TreeWalker} tw - * @param {string} type One of 'first' or 'last'. - * @return {Node|null} - */ -function traverseChildren(tw, type) { - var child, node, parent, result, sibling; - node = tw._currentNode[mapChild[type]]; - while (node !== null) { - result = tw._internalFilter(node); - if (result === NodeFilter.FILTER_ACCEPT) { - tw._currentNode = node; - return node; - } - if (result === NodeFilter.FILTER_SKIP) { - child = node[mapChild[type]]; - if (child !== null) { - node = child; - continue; - } - } - while (node !== null) { - sibling = node[mapSibling[type]]; - if (sibling !== null) { - node = sibling; - break; - } - parent = node.parentNode; - if (parent === null || parent === tw.root || parent === tw._currentNode) { - return null; - } else { - node = parent; - } - } - } - return null; -} - -/** - * @spec https://dom.spec.whatwg.org/#concept-traverse-siblings - * @method - * @access private - * @param {TreeWalker} tw - * @param {TreeWalker} type One of 'next' or 'previous'. - * @return {Node|nul} - */ -function traverseSiblings(tw, type) { - var node, result, sibling; - node = tw._currentNode; - if (node === tw.root) { - return null; - } - while (true) { - sibling = node[mapSibling[type]]; - while (sibling !== null) { - node = sibling; - result = tw._internalFilter(node); - if (result === NodeFilter.FILTER_ACCEPT) { - tw._currentNode = node; - return node; - } - sibling = node[mapChild[type]]; - if (result === NodeFilter.FILTER_REJECT || sibling === null) { - sibling = node[mapSibling[type]]; - } - } - node = node.parentNode; - if (node === null || node === tw.root) { - return null; - } - if (tw._internalFilter(node) === NodeFilter.FILTER_ACCEPT) { - return null; - } - } -} - - -/* Public API */ - -/** - * Latest version: https://dom.spec.whatwg.org/#treewalker - * - * @constructor - * @param {Node} root - * @param {number} whatToShow [optional] - * @param {Function|NodeFilter} filter [optional] - * @throws Error - */ -function TreeWalker(root, whatToShow, filter) { - if (!root || !root.nodeType) { - utils.NotSupportedError(); - } - - // Read-only properties - this._root = root; - this._whatToShow = Number(whatToShow) || 0; - this._filter = filter || null; - this._active = false; - // Read-write property - this._currentNode = root; -} - -Object.defineProperties(TreeWalker.prototype, { - root: { get: function() { return this._root; } }, - whatToShow: { get: function() { return this._whatToShow; } }, - filter: { get: function() { return this._filter; } }, - - currentNode: { - get: function currentNode() { - return this._currentNode; - }, - set: function setCurrentNode(v) { - if (!(v instanceof Node)) { - throw new TypeError("Not a Node"); // `null` is also not a node - } - this._currentNode = v; - }, - }, - - /** - * @method - * @param {Node} node - * @return {Number} Constant NodeFilter.FILTER_ACCEPT, - * NodeFilter.FILTER_REJECT or NodeFilter.FILTER_SKIP. - */ - _internalFilter: { value: function _internalFilter(node) { - /* jshint bitwise: false */ - var result, filter; - if (this._active) { - utils.InvalidStateError(); - } - - // Maps nodeType to whatToShow - if (!(((1 << (node.nodeType - 1)) & this._whatToShow))) { - return NodeFilter.FILTER_SKIP; - } - - filter = this._filter; - if (filter === null) { - result = NodeFilter.FILTER_ACCEPT; - } else { - this._active = true; - try { - if (typeof filter === 'function') { - result = filter(node); - } else { - result = filter.acceptNode(node); - } - } finally { - this._active = false; - } - } - - // Note that coercing to a number means that - // `true` becomes `1` (which is NodeFilter.FILTER_ACCEPT) - // `false` becomes `0` (neither accept, reject, or skip) - return (+result); - }}, - - /** - * @spec https://dom.spec.whatwg.org/#dom-treewalker-parentnode - * @based on WebKit's TreeWalker::parentNode - * https://trac.webkit.org/browser/webkit/trunk/Source/WebCore/dom/TreeWalker.cpp?rev=220453#L50 - * @method - * @return {Node|null} - */ - parentNode: { value: function parentNode() { - var node = this._currentNode; - while (node !== this.root) { - node = node.parentNode; - if (node === null) { - return null; - } - if (this._internalFilter(node) === NodeFilter.FILTER_ACCEPT) { - this._currentNode = node; - return node; - } - } - return null; - }}, - - /** - * @spec https://dom.spec.whatwg.org/#dom-treewalker-firstchild - * @method - * @return {Node|null} - */ - firstChild: { value: function firstChild() { - return traverseChildren(this, 'first'); - }}, - - /** - * @spec https://dom.spec.whatwg.org/#dom-treewalker-lastchild - * @method - * @return {Node|null} - */ - lastChild: { value: function lastChild() { - return traverseChildren(this, 'last'); - }}, - - /** - * @spec http://www.w3.org/TR/dom/#dom-treewalker-previoussibling - * @method - * @return {Node|null} - */ - previousSibling: { value: function previousSibling() { - return traverseSiblings(this, 'previous'); - }}, - - /** - * @spec http://www.w3.org/TR/dom/#dom-treewalker-nextsibling - * @method - * @return {Node|null} - */ - nextSibling: { value: function nextSibling() { - return traverseSiblings(this, 'next'); - }}, - - /** - * @spec https://dom.spec.whatwg.org/#dom-treewalker-previousnode - * @based on WebKit's TreeWalker::previousNode - * https://trac.webkit.org/browser/webkit/trunk/Source/WebCore/dom/TreeWalker.cpp?rev=220453#L181 - * @method - * @return {Node|null} - */ - previousNode: { value: function previousNode() { - var node, result, previousSibling, lastChild; - node = this._currentNode; - while (node !== this._root) { - for (previousSibling = node.previousSibling; - previousSibling; - previousSibling = node.previousSibling) { - node = previousSibling; - result = this._internalFilter(node); - if (result === NodeFilter.FILTER_REJECT) { - continue; - } - for (lastChild = node.lastChild; - lastChild; - lastChild = node.lastChild) { - node = lastChild; - result = this._internalFilter(node); - if (result === NodeFilter.FILTER_REJECT) { - break; - } - } - if (result === NodeFilter.FILTER_ACCEPT) { - this._currentNode = node; - return node; - } - } - if (node === this.root || node.parentNode === null) { - return null; - } - node = node.parentNode; - if (this._internalFilter(node) === NodeFilter.FILTER_ACCEPT) { - this._currentNode = node; - return node; - } - } - return null; - }}, - - /** - * @spec https://dom.spec.whatwg.org/#dom-treewalker-nextnode - * @based on WebKit's TreeWalker::nextNode - * https://trac.webkit.org/browser/webkit/trunk/Source/WebCore/dom/TreeWalker.cpp?rev=220453#L228 - * @method - * @return {Node|null} - */ - nextNode: { value: function nextNode() { - var node, result, firstChild, nextSibling; - node = this._currentNode; - result = NodeFilter.FILTER_ACCEPT; - - CHILDREN: - while (true) { - for (firstChild = node.firstChild; - firstChild; - firstChild = node.firstChild) { - node = firstChild; - result = this._internalFilter(node); - if (result === NodeFilter.FILTER_ACCEPT) { - this._currentNode = node; - return node; - } else if (result === NodeFilter.FILTER_REJECT) { - break; - } - } - for (nextSibling = NodeTraversal.nextSkippingChildren(node, this.root); - nextSibling; - nextSibling = NodeTraversal.nextSkippingChildren(node, this.root)) { - node = nextSibling; - result = this._internalFilter(node); - if (result === NodeFilter.FILTER_ACCEPT) { - this._currentNode = node; - return node; - } else if (result === NodeFilter.FILTER_SKIP) { - continue CHILDREN; - } - } - return null; - } - }}, - - /** For compatibility with web-platform-tests. */ - toString: { value: function toString() { - return "[object TreeWalker]"; - }}, -}); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/UIEvent.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/UIEvent.js deleted file mode 100644 index f065b9c9..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/UIEvent.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -var Event = require('./Event'); - -module.exports = UIEvent; - -function UIEvent() { - // Just use the superclass constructor to initialize - Event.call(this); - this.view = null; // FF uses the current window - this.detail = 0; -} -UIEvent.prototype = Object.create(Event.prototype, { - constructor: { value: UIEvent }, - initUIEvent: { value: function(type, bubbles, cancelable, view, detail) { - this.initEvent(type, bubbles, cancelable); - this.view = view; - this.detail = detail; - }} -}); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/URL.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/URL.js deleted file mode 100644 index d52be34b..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/URL.js +++ /dev/null @@ -1,194 +0,0 @@ -"use strict"; -module.exports = URL; - -function URL(url) { - if (!url) return Object.create(URL.prototype); - // Can't use String.trim() since it defines whitespace differently than HTML - this.url = url.replace(/^[ \t\n\r\f]+|[ \t\n\r\f]+$/g, ""); - - // See http://tools.ietf.org/html/rfc3986#appendix-B - // and https://url.spec.whatwg.org/#parsing - var match = URL.pattern.exec(this.url); - if (match) { - if (match[2]) this.scheme = match[2]; - if (match[4]) { - // parse username/password - var userinfo = match[4].match(URL.userinfoPattern); - if (userinfo) { - this.username = userinfo[1]; - this.password = userinfo[3]; - match[4] = match[4].substring(userinfo[0].length); - } - if (match[4].match(URL.portPattern)) { - var pos = match[4].lastIndexOf(':'); - this.host = match[4].substring(0, pos); - this.port = match[4].substring(pos+1); - } - else { - this.host = match[4]; - } - } - if (match[5]) this.path = match[5]; - if (match[6]) this.query = match[7]; - if (match[8]) this.fragment = match[9]; - } -} - -URL.pattern = /^(([^:\/?#]+):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/; -URL.userinfoPattern = /^([^@:]*)(:([^@]*))?@/; -URL.portPattern = /:\d+$/; -URL.authorityPattern = /^[^:\/?#]+:\/\//; -URL.hierarchyPattern = /^[^:\/?#]+:\//; - -// Return a percentEncoded version of s. -// S should be a single-character string -// XXX: needs to do utf-8 encoding? -URL.percentEncode = function percentEncode(s) { - var c = s.charCodeAt(0); - if (c < 256) return "%" + c.toString(16); - else throw Error("can't percent-encode codepoints > 255 yet"); -}; - -URL.prototype = { - constructor: URL, - - // XXX: not sure if this is the precise definition of absolute - isAbsolute: function() { return !!this.scheme; }, - isAuthorityBased: function() { - return URL.authorityPattern.test(this.url); - }, - isHierarchical: function() { - return URL.hierarchyPattern.test(this.url); - }, - - toString: function() { - var s = ""; - if (this.scheme !== undefined) s += this.scheme + ":"; - if (this.isAbsolute()) { - s += '//'; - if (this.username || this.password) { - s += this.username || ''; - if (this.password) { - s += ':' + this.password; - } - s += '@'; - } - if (this.host) { - s += this.host; - } - } - if (this.port !== undefined) s += ":" + this.port; - if (this.path !== undefined) s += this.path; - if (this.query !== undefined) s += "?" + this.query; - if (this.fragment !== undefined) s += "#" + this.fragment; - return s; - }, - - // See: http://tools.ietf.org/html/rfc3986#section-5.2 - // and https://url.spec.whatwg.org/#constructors - resolve: function(relative) { - var base = this; // The base url we're resolving against - var r = new URL(relative); // The relative reference url to resolve - var t = new URL(); // The absolute target url we will return - - if (r.scheme !== undefined) { - t.scheme = r.scheme; - t.username = r.username; - t.password = r.password; - t.host = r.host; - t.port = r.port; - t.path = remove_dot_segments(r.path); - t.query = r.query; - } - else { - t.scheme = base.scheme; - if (r.host !== undefined) { - t.username = r.username; - t.password = r.password; - t.host = r.host; - t.port = r.port; - t.path = remove_dot_segments(r.path); - t.query = r.query; - } - else { - t.username = base.username; - t.password = base.password; - t.host = base.host; - t.port = base.port; - if (!r.path) { // undefined or empty - t.path = base.path; - if (r.query !== undefined) - t.query = r.query; - else - t.query = base.query; - } - else { - if (r.path.charAt(0) === "/") { - t.path = remove_dot_segments(r.path); - } - else { - t.path = merge(base.path, r.path); - t.path = remove_dot_segments(t.path); - } - t.query = r.query; - } - } - } - t.fragment = r.fragment; - - return t.toString(); - - - function merge(basepath, refpath) { - if (base.host !== undefined && !base.path) - return "/" + refpath; - - var lastslash = basepath.lastIndexOf("/"); - if (lastslash === -1) - return refpath; - else - return basepath.substring(0, lastslash+1) + refpath; - } - - function remove_dot_segments(path) { - if (!path) return path; // For "" or undefined - - var output = ""; - while(path.length > 0) { - if (path === "." || path === "..") { - path = ""; - break; - } - - var twochars = path.substring(0,2); - var threechars = path.substring(0,3); - var fourchars = path.substring(0,4); - if (threechars === "../") { - path = path.substring(3); - } - else if (twochars === "./") { - path = path.substring(2); - } - else if (threechars === "/./") { - path = "/" + path.substring(3); - } - else if (twochars === "/." && path.length === 2) { - path = "/"; - } - else if (fourchars === "/../" || - (threechars === "/.." && path.length === 3)) { - path = "/" + path.substring(4); - - output = output.replace(/\/?[^\/]*$/, ""); - } - else { - var segment = path.match(/(\/?([^\/]*))/)[0]; - output += segment; - path = path.substring(segment.length); - } - } - - return output; - } - }, -}; diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/URLUtils.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/URLUtils.js deleted file mode 100644 index 14b2ae0f..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/URLUtils.js +++ /dev/null @@ -1,270 +0,0 @@ -"use strict"; -var URL = require('./URL'); - -module.exports = URLUtils; - -// Allow the `x == null` pattern. This is eslint's "null: 'ignore'" option, -// but jshint doesn't support this. -/* jshint eqeqeq: false */ - -// This is an abstract superclass for Location, HTMLAnchorElement and -// other types that have the standard complement of "URL decomposition -// IDL attributes". This is now standardized as URLUtils, see: -// https://url.spec.whatwg.org/#urlutils -// Subclasses must define a getter/setter on href. -// The getter and setter methods parse and rebuild the URL on each -// invocation; there is no attempt to cache the value and be more efficient -function URLUtils() {} -URLUtils.prototype = Object.create(Object.prototype, { - - _url: { get: function() { - // XXX: this should do the "Reinitialize url" steps, and "null" should - // be a valid return value. - return new URL(this.href); - } }, - - protocol: { - get: function() { - var url = this._url; - if (url && url.scheme) return url.scheme + ":"; - else return ":"; - }, - set: function(v) { - var output = this.href; - var url = new URL(output); - if (url.isAbsolute()) { - v = v.replace(/:+$/, ""); - v = v.replace(/[^-+\.a-zA-Z0-9]/g, URL.percentEncode); - if (v.length > 0) { - url.scheme = v; - output = url.toString(); - } - } - this.href = output; - }, - }, - - host: { - get: function() { - var url = this._url; - if (url.isAbsolute() && url.isAuthorityBased()) - return url.host + (url.port ? (":" + url.port) : ""); - else - return ""; - }, - set: function(v) { - var output = this.href; - var url = new URL(output); - if (url.isAbsolute() && url.isAuthorityBased()) { - v = v.replace(/[^-+\._~!$&'()*,;:=a-zA-Z0-9]/g, URL.percentEncode); - if (v.length > 0) { - url.host = v; - delete url.port; - output = url.toString(); - } - } - this.href = output; - }, - }, - - hostname: { - get: function() { - var url = this._url; - if (url.isAbsolute() && url.isAuthorityBased()) - return url.host; - else - return ""; - }, - set: function(v) { - var output = this.href; - var url = new URL(output); - if (url.isAbsolute() && url.isAuthorityBased()) { - v = v.replace(/^\/+/, ""); - v = v.replace(/[^-+\._~!$&'()*,;:=a-zA-Z0-9]/g, URL.percentEncode); - if (v.length > 0) { - url.host = v; - output = url.toString(); - } - } - this.href = output; - }, - }, - - port: { - get: function() { - var url = this._url; - if (url.isAbsolute() && url.isAuthorityBased() && url.port!==undefined) - return url.port; - else - return ""; - }, - set: function(v) { - var output = this.href; - var url = new URL(output); - if (url.isAbsolute() && url.isAuthorityBased()) { - v = '' + v; - v = v.replace(/[^0-9].*$/, ""); - v = v.replace(/^0+/, ""); - if (v.length === 0) v = "0"; - if (parseInt(v, 10) <= 65535) { - url.port = v; - output = url.toString(); - } - } - this.href = output; - }, - }, - - pathname: { - get: function() { - var url = this._url; - if (url.isAbsolute() && url.isHierarchical()) - return url.path; - else - return ""; - }, - set: function(v) { - var output = this.href; - var url = new URL(output); - if (url.isAbsolute() && url.isHierarchical()) { - if (v.charAt(0) !== "/") - v = "/" + v; - v = v.replace(/[^-+\._~!$&'()*,;:=@\/a-zA-Z0-9]/g, URL.percentEncode); - url.path = v; - output = url.toString(); - } - this.href = output; - }, - }, - - search: { - get: function() { - var url = this._url; - if (url.isAbsolute() && url.isHierarchical() && url.query!==undefined) - return "?" + url.query; - else - return ""; - }, - set: function(v) { - var output = this.href; - var url = new URL(output); - if (url.isAbsolute() && url.isHierarchical()) { - if (v.charAt(0) === "?") v = v.substring(1); - v = v.replace(/[^-+\._~!$&'()*,;:=@\/?a-zA-Z0-9]/g, URL.percentEncode); - url.query = v; - output = url.toString(); - } - this.href = output; - }, - }, - - hash: { - get: function() { - var url = this._url; - if (url == null || url.fragment == null || url.fragment === '') { - return ""; - } else { - return "#" + url.fragment; - } - }, - set: function(v) { - var output = this.href; - var url = new URL(output); - - if (v.charAt(0) === "#") v = v.substring(1); - v = v.replace(/[^-+\._~!$&'()*,;:=@\/?a-zA-Z0-9]/g, URL.percentEncode); - url.fragment = v; - output = url.toString(); - - this.href = output; - }, - }, - - username: { - get: function() { - var url = this._url; - return url.username || ''; - }, - set: function(v) { - var output = this.href; - var url = new URL(output); - if (url.isAbsolute()) { - v = v.replace(/[\x00-\x1F\x7F-\uFFFF "#<>?`\/@\\:]/g, URL.percentEncode); - url.username = v; - output = url.toString(); - } - this.href = output; - }, - }, - - password: { - get: function() { - var url = this._url; - return url.password || ''; - }, - set: function(v) { - var output = this.href; - var url = new URL(output); - if (url.isAbsolute()) { - if (v==='') { - url.password = null; - } else { - v = v.replace(/[\x00-\x1F\x7F-\uFFFF "#<>?`\/@\\]/g, URL.percentEncode); - url.password = v; - } - output = url.toString(); - } - this.href = output; - }, - }, - - origin: { get: function() { - var url = this._url; - if (url == null) { return ''; } - var originForPort = function(defaultPort) { - var origin = [url.scheme, url.host, +url.port || defaultPort]; - // XXX should be "unicode serialization" - return origin[0] + '://' + origin[1] + - (origin[2] === defaultPort ? '' : (':' + origin[2])); - }; - switch (url.scheme) { - case 'ftp': - return originForPort(21); - case 'gopher': - return originForPort(70); - case 'http': - case 'ws': - return originForPort(80); - case 'https': - case 'wss': - return originForPort(443); - default: - // this is what chrome does - return url.scheme + '://'; - } - } }, - - /* - searchParams: { - get: function() { - var url = this._url; - // XXX - }, - set: function(v) { - var output = this.href; - var url = new URL(output); - // XXX - this.href = output; - }, - }, - */ -}); - -URLUtils._inherit = function(proto) { - // copy getters/setters from URLUtils to o. - Object.getOwnPropertyNames(URLUtils.prototype).forEach(function(p) { - if (p==='constructor' || p==='href') { return; } - var desc = Object.getOwnPropertyDescriptor(URLUtils.prototype, p); - Object.defineProperty(proto, p, desc); - }); -}; diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/Window.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/Window.js deleted file mode 100644 index 71cf5eb2..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/Window.js +++ /dev/null @@ -1,60 +0,0 @@ -"use strict"; -var DOMImplementation = require('./DOMImplementation'); -var EventTarget = require('./EventTarget'); -var Location = require('./Location'); -var utils = require('./utils'); - -module.exports = Window; - -function Window(document) { - this.document = document || new DOMImplementation(null).createHTMLDocument(""); - this.document._scripting_enabled = true; - this.document.defaultView = this; - this.location = new Location(this, this.document._address || 'about:blank'); -} - -Window.prototype = Object.create(EventTarget.prototype, { - console: { value: console }, - history: { value: { - back: utils.nyi, - forward: utils.nyi, - go: utils.nyi - }}, - navigator: { value: require("./NavigatorID") }, - - // Self-referential properties - window: { get: function() { return this; }}, - self: { get: function() { return this; }}, - frames: { get: function() { return this; }}, - - // Self-referential properties for a top-level window - parent: { get: function() { return this; }}, - top: { get: function() { return this; }}, - - // We don't support any other windows for now - length: { value: 0 }, // no frames - frameElement: { value: null }, // not part of a frame - opener: { value: null }, // not opened by another window - - // The onload event handler. - // XXX: need to support a bunch of other event types, too, - // and have them interoperate with document.body. - - onload: { - get: function() { - return this._getEventHandler("load"); - }, - set: function(v) { - this._setEventHandler("load", v); - } - }, - - // XXX This is a completely broken implementation - getComputedStyle: { value: function getComputedStyle(elt) { - return elt.style; - }} - -}); - -utils.expose(require('./WindowTimers'), Window); -utils.expose(require('./impl'), Window); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/WindowTimers.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/WindowTimers.js deleted file mode 100644 index eaf7e0e9..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/WindowTimers.js +++ /dev/null @@ -1,11 +0,0 @@ -"use strict"; - -// https://html.spec.whatwg.org/multipage/webappapis.html#windowtimers -var WindowTimers = { - setTimeout: setTimeout, - clearTimeout: clearTimeout, - setInterval: setInterval, - clearInterval: clearInterval -}; - -module.exports = WindowTimers; diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/attributes.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/attributes.js deleted file mode 100644 index 68d14704..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/attributes.js +++ /dev/null @@ -1,152 +0,0 @@ -"use strict"; -var utils = require('./utils'); - -exports.property = function(attr) { - if (Array.isArray(attr.type)) { - var valid = Object.create(null); - attr.type.forEach(function(val) { - valid[val.value || val] = val.alias || val; - }); - var missingValueDefault = attr.missing; - if (missingValueDefault===undefined) { missingValueDefault = null; } - var invalidValueDefault = attr.invalid; - if (invalidValueDefault===undefined) { invalidValueDefault = missingValueDefault; } - return { - get: function() { - var v = this._getattr(attr.name); - if (v === null) return missingValueDefault; - - v = valid[v.toLowerCase()]; - if (v !== undefined) return v; - if (invalidValueDefault !== null) return invalidValueDefault; - return v; - }, - set: function(v) { - this._setattr(attr.name, v); - } - }; - } - else if (attr.type === Boolean) { - return { - get: function() { - return this.hasAttribute(attr.name); - }, - set: function(v) { - if (v) { - this._setattr(attr.name, ''); - } - else { - this.removeAttribute(attr.name); - } - } - }; - } - else if (attr.type === Number || - attr.type === "long" || - attr.type === "unsigned long" || - attr.type === "limited unsigned long with fallback") { - return numberPropDesc(attr); - } - else if (!attr.type || attr.type === String) { - return { - get: function() { return this._getattr(attr.name) || ''; }, - set: function(v) { - if (attr.treatNullAsEmptyString && v === null) { v = ''; } - this._setattr(attr.name, v); - } - }; - } - else if (typeof attr.type === 'function') { - return attr.type(attr.name, attr); - } - throw new Error('Invalid attribute definition'); -}; - -// See http://www.whatwg.org/specs/web-apps/current-work/#reflect -// -// defval is the default value. If it is a function, then that function -// will be invoked as a method of the element to obtain the default. -// If no default is specified for a given attribute, then the default -// depends on the type of the attribute, but since this function handles -// 4 integer cases, you must specify the default value in each call -// -// min and max define a valid range for getting the attribute. -// -// setmin defines a minimum value when setting. If the value is less -// than that, then throw INDEX_SIZE_ERR. -// -// Conveniently, JavaScript's parseInt function appears to be -// compatible with HTML's 'rules for parsing integers' -function numberPropDesc(a) { - var def; - if(typeof a.default === 'function') { - def = a.default; - } - else if(typeof a.default === 'number') { - def = function() { return a.default; }; - } - else { - def = function() { utils.assert(false, typeof a.default); }; - } - var unsigned_long = (a.type === 'unsigned long'); - var signed_long = (a.type === 'long'); - var unsigned_fallback = (a.type === 'limited unsigned long with fallback'); - var min = a.min, max = a.max, setmin = a.setmin; - if (min === undefined) { - if (unsigned_long) min = 0; - if (signed_long) min = -0x80000000; - if (unsigned_fallback) min = 1; - } - if (max === undefined) { - if (unsigned_long || signed_long || unsigned_fallback) max = 0x7FFFFFFF; - } - - return { - get: function() { - var v = this._getattr(a.name); - var n = a.float ? parseFloat(v) : parseInt(v, 10); - if (v === null || !isFinite(n) || (min !== undefined && n < min) || (max !== undefined && n > max)) { - return def.call(this); - } - if (unsigned_long || signed_long || unsigned_fallback) { - if (!/^[ \t\n\f\r]*[-+]?[0-9]/.test(v)) { return def.call(this); } - n = n|0; // jshint ignore:line - } - return n; - }, - set: function(v) { - if (!a.float) { v = Math.floor(v); } - if (setmin !== undefined && v < setmin) { - utils.IndexSizeError(a.name + ' set to ' + v); - } - if (unsigned_long) { - v = (v < 0 || v > 0x7FFFFFFF) ? def.call(this) : - (v|0); // jshint ignore:line - } else if (unsigned_fallback) { - v = (v < 1 || v > 0x7FFFFFFF) ? def.call(this) : - (v|0); // jshint ignore:line - } else if (signed_long) { - v = (v < -0x80000000 || v > 0x7FFFFFFF) ? def.call(this) : - (v|0); // jshint ignore:line - } - this._setattr(a.name, String(v)); - } - }; -} - -// This is a utility function for setting up change handler functions -// for attributes like 'id' that require special handling when they change. -exports.registerChangeHandler = function(c, name, handler) { - var p = c.prototype; - - // If p does not already have its own _attributeChangeHandlers - // then create one for it, inheriting from the inherited - // _attributeChangeHandlers. At the top (for the Element class) the - // _attributeChangeHandlers object will be created with a null prototype. - if (!Object.prototype.hasOwnProperty.call(p, '_attributeChangeHandlers')) { - p._attributeChangeHandlers = - Object.create(p._attributeChangeHandlers || null); - } - - p._attributeChangeHandlers[name] = handler; -}; diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/config.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/config.js deleted file mode 100644 index efdc1692..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/config.js +++ /dev/null @@ -1,7 +0,0 @@ -/* - * This file defines Domino behaviour that can be externally configured. - * To change these settings, set the relevant global property *before* - * you call `require("domino")`. - */ - -exports.isApiWritable = !globalThis.__domino_frozen__; diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/defineElement.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/defineElement.js deleted file mode 100644 index 5ba52953..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/defineElement.js +++ /dev/null @@ -1,71 +0,0 @@ -"use strict"; - -var attributes = require('./attributes'); -var isApiWritable = require("./config").isApiWritable; - -module.exports = function(spec, defaultConstructor, tagList, tagNameToImpl) { - var c = spec.ctor; - if (c) { - var props = spec.props || {}; - - if (spec.attributes) { - for (var n in spec.attributes) { - var attr = spec.attributes[n]; - if (typeof attr !== 'object' || Array.isArray(attr)) attr = {type: attr}; - if (!attr.name) attr.name = n.toLowerCase(); - props[n] = attributes.property(attr); - } - } - - props.constructor = { value : c, writable: isApiWritable }; - c.prototype = Object.create((spec.superclass || defaultConstructor).prototype, props); - if (spec.events) { - addEventHandlers(c, spec.events); - } - tagList[spec.name] = c; - } - else { - c = defaultConstructor; - } - - (spec.tags || spec.tag && [spec.tag] || []).forEach(function(tag) { - tagNameToImpl[tag] = c; - }); - - return c; -}; - -function EventHandlerBuilder(body, document, form, element) { - this.body = body; - this.document = document; - this.form = form; - this.element = element; -} - -EventHandlerBuilder.prototype.build = function () { - return () => {}; -}; - -function EventHandlerChangeHandler(elt, name, oldval, newval) { - var doc = elt.ownerDocument || Object.create(null); - var form = elt.form || Object.create(null); - elt[name] = new EventHandlerBuilder(newval, doc, form, elt).build(); -} - -function addEventHandlers(c, eventHandlerTypes) { - var p = c.prototype; - eventHandlerTypes.forEach(function(type) { - // Define the event handler registration IDL attribute for this type - Object.defineProperty(p, "on" + type, { - get: function() { - return this._getEventHandler(type); - }, - set: function(v) { - this._setEventHandler(type, v); - }, - }); - - // Define special behavior for the content attribute as well - attributes.registerChangeHandler(c, "on" + type, EventHandlerChangeHandler); - }); -} diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/events.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/events.js deleted file mode 100644 index 6b20fb5f..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/events.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; -module.exports = { - Event: require('./Event'), - UIEvent: require('./UIEvent'), - MouseEvent: require('./MouseEvent'), - CustomEvent: require('./CustomEvent') -}; diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/htmlelts.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/htmlelts.js deleted file mode 100644 index 68de66d8..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/htmlelts.js +++ /dev/null @@ -1,1499 +0,0 @@ -"use strict"; -var Node = require('./Node'); -var Element = require('./Element'); -var CSSStyleDeclaration = require('./CSSStyleDeclaration'); -var utils = require('./utils'); -var URLUtils = require('./URLUtils'); -var defineElement = require('./defineElement'); - -var htmlElements = exports.elements = {}; -var htmlNameToImpl = Object.create(null); - -exports.createElement = function(doc, localName, prefix) { - var impl = htmlNameToImpl[localName] || HTMLUnknownElement; - return new impl(doc, localName, prefix); -}; - -function define(spec) { - return defineElement(spec, HTMLElement, htmlElements, htmlNameToImpl); -} - -function URL(attr) { - return { - get: function() { - var v = this._getattr(attr); - if (v === null) { return ''; } - var url = this.doc._resolve(v); - return (url === null) ? v : url; - }, - set: function(value) { - this._setattr(attr, value); - } - }; -} - -function CORS(attr) { - return { - get: function() { - var v = this._getattr(attr); - if (v === null) { return null; } - if (v.toLowerCase() === 'use-credentials') { return 'use-credentials'; } - return 'anonymous'; - }, - set: function(value) { - if (value===null || value===undefined) { - this.removeAttribute(attr); - } else { - this._setattr(attr, value); - } - } - }; -} - -const REFERRER = { - type: ["", "no-referrer", "no-referrer-when-downgrade", "same-origin", "origin", "strict-origin", "origin-when-cross-origin", "strict-origin-when-cross-origin", "unsafe-url"], - missing: '', -}; - - -// XXX: the default value for tabIndex should be 0 if the element is -// focusable and -1 if it is not. But the full definition of focusable -// is actually hard to compute, so for now, I'll follow Firefox and -// just base the default value on the type of the element. -var focusableElements = { - "A":true, "LINK":true, "BUTTON":true, "INPUT":true, - "SELECT":true, "TEXTAREA":true, "COMMAND":true -}; - -var HTMLFormElement = function(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - this._form = null; // Prevent later deoptimization -}; - -var HTMLElement = exports.HTMLElement = define({ - superclass: Element, - name: 'HTMLElement', - ctor: function HTMLElement(doc, localName, prefix) { - Element.call(this, doc, localName, utils.NAMESPACE.HTML, prefix); - }, - props: { - dangerouslySetInnerHTML: { - set: function (v) { - this._innerHTML = v; - }, - }, - innerHTML: { - get: function() { - return this.serialize(); - }, - set: function(v) { - var parser = this.ownerDocument.implementation.mozHTMLParser( - this.ownerDocument._address, - this); - parser.parse(v===null ? '' : String(v), true); - - // Remove any existing children of this node - var target = (this instanceof htmlNameToImpl.template) ? - this.content : this; - while(target.hasChildNodes()) - target.removeChild(target.firstChild); - - // Now copy newly parsed children to this node - target.appendChild(parser._asDocumentFragment()); - } - }, - style: { get: function() { - if (!this._style) - this._style = new CSSStyleDeclaration(this); - return this._style; - }, set: function(v) { - if (v===null||v===undefined) { v = ''; } - this._setattr('style', String(v)); - }}, - - // These can't really be implemented server-side in a reasonable way. - blur: { value: function() {}}, - focus: { value: function() {}}, - forceSpellCheck: { value: function() {}}, - - click: { value: function() { - if (this._click_in_progress) return; - this._click_in_progress = true; - try { - if (this._pre_click_activation_steps) - this._pre_click_activation_steps(); - - var event = this.ownerDocument.createEvent("MouseEvent"); - event.initMouseEvent("click", true, true, - this.ownerDocument.defaultView, 1, - 0, 0, 0, 0, - // These 4 should be initialized with - // the actually current keyboard state - // somehow... - false, false, false, false, - 0, null - ); - - // Dispatch this as an untrusted event since it is synthetic - var success = this.dispatchEvent(event); - - if (success) { - if (this._post_click_activation_steps) - this._post_click_activation_steps(event); - } - else { - if (this._cancelled_activation_steps) - this._cancelled_activation_steps(); - } - } - finally { - this._click_in_progress = false; - } - }}, - submit: { value: utils.nyi }, - }, - attributes: { - title: String, - lang: String, - dir: {type: ["ltr", "rtl", "auto"], missing: ''}, - draggable: {type: ["true", "false"], treatNullAsEmptyString: true }, - spellcheck: {type: ["true", "false"], missing: ''}, - enterKeyHint: {type: ["enter", "done", "go", "next", "previous", "search", "send"], missing: ''}, - autoCapitalize: {type: ["off", "on", "none", "sentences", "words", "characters"], missing: '' }, - autoFocus: Boolean, - accessKey: String, - nonce: String, - hidden: Boolean, - translate: {type: ["no", "yes"], missing: '' }, - tabIndex: {type: "long", default: function() { - if (this.tagName in focusableElements || - this.contentEditable) - return 0; - else - return -1; - }} - }, - events: [ - "abort", "canplay", "canplaythrough", "change", "click", "contextmenu", - "cuechange", "dblclick", "drag", "dragend", "dragenter", "dragleave", - "dragover", "dragstart", "drop", "durationchange", "emptied", "ended", - "input", "invalid", "keydown", "keypress", "keyup", "loadeddata", - "loadedmetadata", "loadstart", "mousedown", "mousemove", "mouseout", - "mouseover", "mouseup", "mousewheel", "pause", "play", "playing", - "progress", "ratechange", "readystatechange", "reset", "seeked", - "seeking", "select", "show", "stalled", "submit", "suspend", - "timeupdate", "volumechange", "waiting", - - // These last 5 event types will be overriden by HTMLBodyElement - "blur", "error", "focus", "load", "scroll" - ] -}); - - -// XXX: reflect contextmenu as contextMenu, with element type - - -// style: the spec doesn't call this a reflected attribute. -// may want to handle it manually. - -// contentEditable: enumerated, not clear if it is actually -// reflected or requires custom getter/setter. Not listed as -// "limited to known values". Raises syntax_err on bad setting, -// so I think this is custom. - -// contextmenu: content is element id, idl type is an element -// draggable: boolean, but not a reflected attribute -// dropzone: reflected SettableTokenList, experimental, so don't -// implement it right away. - -// data-* attributes: need special handling in setAttribute? -// Or maybe that isn't necessary. Can I just scan the attribute list -// when building the dataset? Liveness and caching issues? - -// microdata attributes: many are simple reflected attributes, but -// I'm not going to implement this now. - - -var HTMLUnknownElement = define({ - name: 'HTMLUnknownElement', - ctor: function HTMLUnknownElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - } -}); - - -var formAssociatedProps = { - // See http://www.w3.org/TR/html5/association-of-controls-and-forms.html#form-owner - form: { get: function() { - return this._form; - }} -}; - -define({ - tag: 'a', - name: 'HTMLAnchorElement', - ctor: function HTMLAnchorElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - props: { - _post_click_activation_steps: { value: function(e) { - if (this.href) { - // Follow the link - // XXX: this is just a quick hack - // XXX: the HTML spec probably requires more than this - this.ownerDocument.defaultView.location = this.href; - } - }}, - }, - attributes: { - href: URL, - ping: String, - download: String, - target: String, - rel: String, - media: String, - hreflang: String, - type: String, - referrerPolicy: REFERRER, - // Obsolete - coords: String, - charset: String, - name: String, - rev: String, - shape: String, - } -}); -// Latest WhatWG spec says these methods come via HTMLHyperlinkElementUtils -URLUtils._inherit(htmlNameToImpl.a.prototype); - -define({ - tag: 'area', - name: 'HTMLAreaElement', - ctor: function HTMLAreaElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - alt: String, - target: String, - download: String, - rel: String, - media: String, - href: URL, - hreflang: String, - type: String, - shape: String, - coords: String, - ping: String, - // XXX: also reflect relList - referrerPolicy: REFERRER, - // Obsolete - noHref: Boolean, - } -}); -// Latest WhatWG spec says these methods come via HTMLHyperlinkElementUtils -URLUtils._inherit(htmlNameToImpl.area.prototype); - -define({ - tag: 'br', - name: 'HTMLBRElement', - ctor: function HTMLBRElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - // Obsolete - clear: String - }, -}); - -define({ - tag: 'base', - name: 'HTMLBaseElement', - ctor: function HTMLBaseElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - "target": String - } -}); - - -define({ - tag: 'body', - name: 'HTMLBodyElement', - ctor: function HTMLBodyElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - // Certain event handler attributes on a tag actually set - // handlers for the window rather than just that element. Define - // getters and setters for those here. Note that some of these override - // properties on HTMLElement.prototype. - // XXX: If I add support for , these have to go there, too - // XXX - // When the Window object is implemented, these attribute will have - // to work with the same-named attributes on the Window. - events: [ - "afterprint", "beforeprint", "beforeunload", "blur", "error", - "focus","hashchange", "load", "message", "offline", "online", - "pagehide", "pageshow","popstate","resize","scroll","storage","unload", - ], - attributes: { - // Obsolete - text: { type: String, treatNullAsEmptyString: true }, - link: { type: String, treatNullAsEmptyString: true }, - vLink: { type: String, treatNullAsEmptyString: true }, - aLink: { type: String, treatNullAsEmptyString: true }, - bgColor: { type: String, treatNullAsEmptyString: true }, - background: String, - } -}); - -define({ - tag: 'button', - name: 'HTMLButtonElement', - ctor: function HTMLButtonElement(doc, localName, prefix) { - HTMLFormElement.call(this, doc, localName, prefix); - }, - props: formAssociatedProps, - attributes: { - name: String, - value: String, - disabled: Boolean, - autofocus: Boolean, - type: { type:["submit", "reset", "button", "menu"], missing: 'submit' }, - formTarget: String, - formAction: URL, - formNoValidate: Boolean, - formMethod: { type: ["get", "post", "dialog"], invalid: 'get', missing: '' }, - formEnctype: { type: ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"], invalid: "application/x-www-form-urlencoded", missing: '' }, - } -}); - -define({ - tag: 'dl', - name: 'HTMLDListElement', - ctor: function HTMLDListElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - // Obsolete - compact: Boolean, - } -}); - -define({ - tag: 'data', - name: 'HTMLDataElement', - ctor: function HTMLDataElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - value: String, - } -}); - -define({ - tag: 'datalist', - name: 'HTMLDataListElement', - ctor: function HTMLDataListElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - } -}); - -define({ - tag: 'details', - name: 'HTMLDetailsElement', - ctor: function HTMLDetailsElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - "open": Boolean - } -}); - -define({ - tag: 'div', - name: 'HTMLDivElement', - ctor: function HTMLDivElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - // Obsolete - align: String - } -}); - -define({ - tag: 'embed', - name: 'HTMLEmbedElement', - ctor: function HTMLEmbedElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - src: URL, - type: String, - width: String, - height: String, - // Obsolete - align: String, - name: String, - } -}); - -define({ - tag: 'fieldset', - name: 'HTMLFieldSetElement', - ctor: function HTMLFieldSetElement(doc, localName, prefix) { - HTMLFormElement.call(this, doc, localName, prefix); - }, - props: formAssociatedProps, - attributes: { - disabled: Boolean, - name: String - } -}); - -define({ - tag: 'form', - name: 'HTMLFormElement', - ctor: function HTMLFormElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - action: String, - autocomplete: {type:['on', 'off'], missing: 'on'}, - name: String, - acceptCharset: {name: "accept-charset"}, - target: String, - noValidate: Boolean, - method: { type: ["get", "post", "dialog"], invalid: 'get', missing: 'get' }, - // Both enctype and encoding reflect the enctype content attribute - enctype: { type: ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"], invalid: "application/x-www-form-urlencoded", missing: "application/x-www-form-urlencoded" }, - encoding: {name: 'enctype', type: ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"], invalid: "application/x-www-form-urlencoded", missing: "application/x-www-form-urlencoded" }, - } -}); - -define({ - tag: 'hr', - name: 'HTMLHRElement', - ctor: function HTMLHRElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - // Obsolete - align: String, - color: String, - noShade: Boolean, - size: String, - width: String, - }, -}); - -define({ - tag: 'head', - name: 'HTMLHeadElement', - ctor: function HTMLHeadElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - } -}); - -define({ - tags: ['h1','h2','h3','h4','h5','h6'], - name: 'HTMLHeadingElement', - ctor: function HTMLHeadingElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - // Obsolete - align: String, - }, -}); - -define({ - tag: 'html', - name: 'HTMLHtmlElement', - ctor: function HTMLHtmlElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - xmlns: URL, - // Obsolete - version: String - } -}); - -define({ - tag: 'iframe', - name: 'HTMLIFrameElement', - ctor: function HTMLIFrameElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - src: URL, - srcdoc: String, - name: String, - width: String, - height: String, - // XXX: sandbox is a reflected settable token list - seamless: Boolean, - allow: Boolean, - allowFullscreen: Boolean, - allowUserMedia: Boolean, - allowPaymentRequest: Boolean, - referrerPolicy: REFERRER, - loading: { type:['eager','lazy'], treatNullAsEmptyString: true }, - // Obsolete - align: String, - scrolling: String, - frameBorder: String, - longDesc: URL, - marginHeight: { type: String, treatNullAsEmptyString: true }, - marginWidth: { type: String, treatNullAsEmptyString: true }, - } -}); - -define({ - tag: 'img', - name: 'HTMLImageElement', - ctor: function HTMLImageElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - alt: String, - src: URL, - srcset: String, - crossOrigin: CORS, - useMap: String, - isMap: Boolean, - sizes: String, - height: { type: "unsigned long", default: 0 }, - width: { type: "unsigned long", default: 0 }, - referrerPolicy: REFERRER, - loading: { type:['eager','lazy'], missing: '' }, - // Obsolete: - name: String, - lowsrc: URL, - align: String, - hspace: { type: "unsigned long", default: 0 }, - vspace: { type: "unsigned long", default: 0 }, - longDesc: URL, - border: { type: String, treatNullAsEmptyString: true }, - } -}); - -define({ - tag: 'input', - name: 'HTMLInputElement', - ctor: function HTMLInputElement(doc, localName, prefix) { - HTMLFormElement.call(this, doc, localName, prefix); - }, - props: { - form: formAssociatedProps.form, - _post_click_activation_steps: { value: function(e) { - if (this.type === 'checkbox') { - this.checked = !this.checked; - } - else if (this.type === 'radio') { - var group = this.form.getElementsByName(this.name); - for (var i=group.length-1; i >= 0; i--) { - var el = group[i]; - el.checked = (el === this); - } - } - }}, - }, - attributes: { - name: String, - disabled: Boolean, - autofocus: Boolean, - accept: String, - alt: String, - max: String, - min: String, - pattern: String, - placeholder: String, - step: String, - dirName: String, - defaultValue: {name: 'value'}, - multiple: Boolean, - required: Boolean, - readOnly: Boolean, - checked: Boolean, - value: String, - src: URL, - defaultChecked: {name: 'checked', type: Boolean}, - size: {type: 'unsigned long', default: 20, min: 1, setmin: 1}, - width: {type: 'unsigned long', min: 0, setmin: 0, default: 0}, - height: {type: 'unsigned long', min: 0, setmin: 0, default: 0}, - minLength: {type: 'unsigned long', min: 0, setmin: 0, default: -1}, - maxLength: {type: 'unsigned long', min: 0, setmin: 0, default: -1}, - autocomplete: String, // It's complicated - type: { type: - ["text", "hidden", "search", "tel", "url", "email", "password", - "datetime", "date", "month", "week", "time", "datetime-local", - "number", "range", "color", "checkbox", "radio", "file", "submit", - "image", "reset", "button"], - missing: 'text' }, - formTarget: String, - formNoValidate: Boolean, - formMethod: { type: ["get", "post"], invalid: 'get', missing: '' }, - formEnctype: { type: ["application/x-www-form-urlencoded", "multipart/form-data", "text/plain"], invalid: "application/x-www-form-urlencoded", missing: '' }, - inputMode: { type: [ "verbatim", "latin", "latin-name", "latin-prose", "full-width-latin", "kana", "kana-name", "katakana", "numeric", "tel", "email", "url" ], missing: '' }, - // Obsolete - align: String, - useMap: String, - } -}); - -define({ - tag: 'keygen', - name: 'HTMLKeygenElement', - ctor: function HTMLKeygenElement(doc, localName, prefix) { - HTMLFormElement.call(this, doc, localName, prefix); - }, - props: formAssociatedProps, - attributes: { - name: String, - disabled: Boolean, - autofocus: Boolean, - challenge: String, - keytype: { type:["rsa"], missing: '' }, - } -}); - -define({ - tag: 'li', - name: 'HTMLLIElement', - ctor: function HTMLLIElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - value: {type: "long", default: 0}, - // Obsolete - type: String, - } -}); - -define({ - tag: 'label', - name: 'HTMLLabelElement', - ctor: function HTMLLabelElement(doc, localName, prefix) { - HTMLFormElement.call(this, doc, localName, prefix); - }, - props: formAssociatedProps, - attributes: { - htmlFor: {name: 'for', type: String} - } -}); - -define({ - tag: 'legend', - name: 'HTMLLegendElement', - ctor: function HTMLLegendElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - // Obsolete - align: String - }, -}); - -define({ - tag: 'link', - name: 'HTMLLinkElement', - ctor: function HTMLLinkElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - // XXX Reflect DOMSettableTokenList sizes also DOMTokenList relList - href: URL, - rel: String, - media: String, - hreflang: String, - type: String, - crossOrigin: CORS, - nonce: String, - integrity: String, - referrerPolicy: REFERRER, - imageSizes: String, - imageSrcset: String, - // Obsolete - charset: String, - rev: String, - target: String, - } -}); - -define({ - tag: 'map', - name: 'HTMLMapElement', - ctor: function HTMLMapElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - name: String - } -}); - -define({ - tag: 'menu', - name: 'HTMLMenuElement', - ctor: function HTMLMenuElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - // XXX: not quite right, default should be popup if parent element is - // popup. - type: { type: [ 'context', 'popup', 'toolbar' ], missing: 'toolbar' }, - label: String, - // Obsolete - compact: Boolean, - } -}); - -define({ - tag: 'meta', - name: 'HTMLMetaElement', - ctor: function HTMLMetaElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - name: String, - content: String, - httpEquiv: {name: 'http-equiv', type: String}, - // Obsolete - scheme: String, - } -}); - -define({ - tag: 'meter', - name: 'HTMLMeterElement', - ctor: function HTMLMeterElement(doc, localName, prefix) { - HTMLFormElement.call(this, doc, localName, prefix); - }, - props: formAssociatedProps -}); - -define({ - tags: ['ins', 'del'], - name: 'HTMLModElement', - ctor: function HTMLModElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - cite: URL, - dateTime: String - } -}); - -define({ - tag: 'ol', - name: 'HTMLOListElement', - ctor: function HTMLOListElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - props: { - // Utility function (see the start attribute default value). Returns - // the number of
  • children of this element - _numitems: { get: function() { - var items = 0; - this.childNodes.forEach(function(n) { - if (n.nodeType === Node.ELEMENT_NODE && n.tagName === "LI") - items++; - }); - return items; - }} - }, - attributes: { - type: String, - reversed: Boolean, - start: { - type: "long", - default: function() { - // The default value of the start attribute is 1 unless the list is - // reversed. Then it is the # of li children - if (this.reversed) - return this._numitems; - else - return 1; - } - }, - // Obsolete - compact: Boolean, - } -}); - -define({ - tag: 'object', - name: 'HTMLObjectElement', - ctor: function HTMLObjectElement(doc, localName, prefix) { - HTMLFormElement.call(this, doc, localName, prefix); - }, - props: formAssociatedProps, - attributes: { - data: URL, - type: String, - name: String, - useMap: String, - typeMustMatch: Boolean, - width: String, - height: String, - // Obsolete - align: String, - archive: String, - code: String, - declare: Boolean, - hspace: { type: "unsigned long", default: 0 }, - standby: String, - vspace: { type: "unsigned long", default: 0 }, - codeBase: URL, - codeType: String, - border: { type: String, treatNullAsEmptyString: true }, - } -}); - -define({ - tag: 'optgroup', - name: 'HTMLOptGroupElement', - ctor: function HTMLOptGroupElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - disabled: Boolean, - label: String - } -}); - -define({ - tag: 'option', - name: 'HTMLOptionElement', - ctor: function HTMLOptionElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - props: { - form: { get: function() { - var p = this.parentNode; - while (p && p.nodeType === Node.ELEMENT_NODE) { - if (p.localName === 'select') return p.form; - p = p.parentNode; - } - }}, - value: { - get: function() { return this._getattr('value') || this.text; }, - set: function(v) { this._setattr('value', v); }, - }, - text: { - get: function() { - // Strip and collapse whitespace - return this.textContent.replace(/[ \t\n\f\r]+/g, ' ').trim(); - }, - set: function(v) { this.textContent = v; }, - }, - // missing: index - }, - attributes: { - disabled: Boolean, - defaultSelected: {name: 'selected', type: Boolean}, - label: String, - } -}); - -define({ - tag: 'output', - name: 'HTMLOutputElement', - ctor: function HTMLOutputElement(doc, localName, prefix) { - HTMLFormElement.call(this, doc, localName, prefix); - }, - props: formAssociatedProps, - attributes: { - // XXX Reflect for/htmlFor as a settable token list - name: String - } -}); - -define({ - tag: 'p', - name: 'HTMLParagraphElement', - ctor: function HTMLParagraphElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - // Obsolete - align: String - } -}); - -define({ - tag: 'param', - name: 'HTMLParamElement', - ctor: function HTMLParamElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - name: String, - value: String, - // Obsolete - type: String, - valueType: String, - } -}); - -define({ - tags: ['pre',/*legacy elements:*/'listing','xmp'], - name: 'HTMLPreElement', - ctor: function HTMLPreElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - // Obsolete - width: { type: "long", default: 0 }, - } -}); - -define({ - tag: 'progress', - name: 'HTMLProgressElement', - ctor: function HTMLProgressElement(doc, localName, prefix) { - HTMLFormElement.call(this, doc, localName, prefix); - }, - props: formAssociatedProps, - attributes: { - max: {type: Number, float: true, default: 1.0, min: 0} - } -}); - -define({ - tags: ['q', 'blockquote'], - name: 'HTMLQuoteElement', - ctor: function HTMLQuoteElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - cite: URL - } -}); - -define({ - tag: 'script', - name: 'HTMLScriptElement', - ctor: function HTMLScriptElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - props: { - text: { - get: function() { - var s = ""; - for(var i = 0, n = this.childNodes.length; i < n; i++) { - var child = this.childNodes[i]; - if (child.nodeType === Node.TEXT_NODE) - s += child._data; - } - return s; - }, - set: function(value) { - this.removeChildren(); - if (value !== null && value !== "") { - this.appendChild(this.ownerDocument.createTextNode(value)); - } - } - } - }, - attributes: { - src: URL, - type: String, - charset: String, - referrerPolicy: REFERRER, - defer: Boolean, - async: Boolean, - nomodule: Boolean, - crossOrigin: CORS, - nonce: String, - integrity: String, - } -}); - -define({ - tag: 'select', - name: 'HTMLSelectElement', - ctor: function HTMLSelectElement(doc, localName, prefix) { - HTMLFormElement.call(this, doc, localName, prefix); - }, - props: { - form: formAssociatedProps.form, - options: { get: function() { - return this.getElementsByTagName('option'); - }} - }, - attributes: { - autocomplete: String, // It's complicated - name: String, - disabled: Boolean, - autofocus: Boolean, - multiple: Boolean, - required: Boolean, - size: {type: "unsigned long", default: 0} - } -}); - -define({ - tag: 'span', - name: 'HTMLSpanElement', - ctor: function HTMLSpanElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - } -}); - -define({ - tag: 'style', - name: 'HTMLStyleElement', - ctor: function HTMLStyleElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - media: String, - type: String, - scoped: Boolean - } -}); - -define({ - tag: 'caption', - name: 'HTMLTableCaptionElement', - ctor: function HTMLTableCaptionElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - // Obsolete - align: String, - } -}); - - -define({ - name: 'HTMLTableCellElement', - ctor: function HTMLTableCellElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - colSpan: {type: "unsigned long", default: 1}, - rowSpan: {type: "unsigned long", default: 1}, - //XXX Also reflect settable token list headers - scope: { type: ['row','col','rowgroup','colgroup'], missing: '' }, - abbr: String, - // Obsolete - align: String, - axis: String, - height: String, - width: String, - ch: { name: 'char', type: String }, - chOff: { name: 'charoff', type: String }, - noWrap: Boolean, - vAlign: String, - bgColor: { type: String, treatNullAsEmptyString: true }, - } -}); - -define({ - tags: ['col', 'colgroup'], - name: 'HTMLTableColElement', - ctor: function HTMLTableColElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - span: {type: 'limited unsigned long with fallback', default: 1, min: 1}, - // Obsolete - align: String, - ch: { name: 'char', type: String }, - chOff: { name: 'charoff', type: String }, - vAlign: String, - width: String, - } -}); - -define({ - tag: 'table', - name: 'HTMLTableElement', - ctor: function HTMLTableElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - props: { - rows: { get: function() { - return this.getElementsByTagName('tr'); - }} - }, - attributes: { - // Obsolete - align: String, - border: String, - frame: String, - rules: String, - summary: String, - width: String, - bgColor: { type: String, treatNullAsEmptyString: true }, - cellPadding: { type: String, treatNullAsEmptyString: true }, - cellSpacing: { type: String, treatNullAsEmptyString: true }, - } -}); - -define({ - tag: 'template', - name: 'HTMLTemplateElement', - ctor: function HTMLTemplateElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - this._contentFragment = doc._templateDoc.createDocumentFragment(); - }, - props: { - content: { get: function() { return this._contentFragment; } }, - serialize: { value: function() { return this.content.serialize(); } } - } -}); - -define({ - tag: 'tr', - name: 'HTMLTableRowElement', - ctor: function HTMLTableRowElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - props: { - cells: { get: function() { - return this.querySelectorAll('td,th'); - }} - }, - attributes: { - // Obsolete - align: String, - ch: { name: 'char', type: String }, - chOff: { name: 'charoff', type: String }, - vAlign: String, - bgColor: { type: String, treatNullAsEmptyString: true }, - }, -}); - -define({ - tags: ['thead', 'tfoot', 'tbody'], - name: 'HTMLTableSectionElement', - ctor: function HTMLTableSectionElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - props: { - rows: { get: function() { - return this.getElementsByTagName('tr'); - }} - }, - attributes: { - // Obsolete - align: String, - ch: { name: 'char', type: String }, - chOff: { name: 'charoff', type: String }, - vAlign: String, - } -}); - -define({ - tag: 'textarea', - name: 'HTMLTextAreaElement', - ctor: function HTMLTextAreaElement(doc, localName, prefix) { - HTMLFormElement.call(this, doc, localName, prefix); - }, - props: { - form: formAssociatedProps.form, - type: { get: function() { return 'textarea'; } }, - defaultValue: { - get: function() { return this.textContent; }, - set: function(v) { this.textContent = v; }, - }, - value: { - get: function() { return this.defaultValue; /* never dirty */ }, - set: function(v) { - // This isn't completely correct: according to the spec, this - // should "dirty" the API value, and result in - // `this.value !== this.defaultValue`. But for most of what - // folks want to do, this implementation should be fine: - this.defaultValue = v; - }, - }, - textLength: { get: function() { return this.value.length; } }, - }, - attributes: { - autocomplete: String, // It's complicated - name: String, - disabled: Boolean, - autofocus: Boolean, - placeholder: String, - wrap: String, - dirName: String, - required: Boolean, - readOnly: Boolean, - rows: {type: 'limited unsigned long with fallback', default: 2 }, - cols: {type: 'limited unsigned long with fallback', default: 20 }, - maxLength: {type: 'unsigned long', min: 0, setmin: 0, default: -1}, - minLength: {type: 'unsigned long', min: 0, setmin: 0, default: -1}, - inputMode: { type: [ "verbatim", "latin", "latin-name", "latin-prose", "full-width-latin", "kana", "kana-name", "katakana", "numeric", "tel", "email", "url" ], missing: '' }, - } -}); - -define({ - tag: 'time', - name: 'HTMLTimeElement', - ctor: function HTMLTimeElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - dateTime: String, - pubDate: Boolean - } -}); - -define({ - tag: 'title', - name: 'HTMLTitleElement', - ctor: function HTMLTitleElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - props: { - text: { get: function() { - return this.textContent; - }} - } -}); - -define({ - tag: 'ul', - name: 'HTMLUListElement', - ctor: function HTMLUListElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - type: String, - // Obsolete - compact: Boolean, - } -}); - -define({ - name: 'HTMLMediaElement', - ctor: function HTMLMediaElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - src: URL, - crossOrigin: CORS, - preload: { type:["metadata", "none", "auto", {value: "", alias: "auto"}], missing: 'auto' }, - loop: Boolean, - autoplay: Boolean, - mediaGroup: String, - controls: Boolean, - defaultMuted: {name: "muted", type: Boolean} - } -}); - -define({ - name: 'HTMLAudioElement', - tag: 'audio', - superclass: htmlElements.HTMLMediaElement, - ctor: function HTMLAudioElement(doc, localName, prefix) { - htmlElements.HTMLMediaElement.call(this, doc, localName, prefix); - } -}); - -define({ - name: 'HTMLVideoElement', - tag: 'video', - superclass: htmlElements.HTMLMediaElement, - ctor: function HTMLVideoElement(doc, localName, prefix) { - htmlElements.HTMLMediaElement.call(this, doc, localName, prefix); - }, - attributes: { - poster: URL, - width: {type: "unsigned long", min: 0, default: 0 }, - height: {type: "unsigned long", min: 0, default: 0 } - } -}); - -define({ - tag: 'td', - name: 'HTMLTableDataCellElement', - superclass: htmlElements.HTMLTableCellElement, - ctor: function HTMLTableDataCellElement(doc, localName, prefix) { - htmlElements.HTMLTableCellElement.call(this, doc, localName, prefix); - } -}); - -define({ - tag: 'th', - name: 'HTMLTableHeaderCellElement', - superclass: htmlElements.HTMLTableCellElement, - ctor: function HTMLTableHeaderCellElement(doc, localName, prefix) { - htmlElements.HTMLTableCellElement.call(this, doc, localName, prefix); - }, -}); - -define({ - tag: 'frameset', - name: 'HTMLFrameSetElement', - ctor: function HTMLFrameSetElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - } -}); - -define({ - tag: 'frame', - name: 'HTMLFrameElement', - ctor: function HTMLFrameElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - } -}); - -define({ - tag: 'canvas', - name: 'HTMLCanvasElement', - ctor: function HTMLCanvasElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - props: { - getContext: { value: utils.nyi }, - probablySupportsContext: { value: utils.nyi }, - setContext: { value: utils.nyi }, - transferControlToProxy: { value: utils.nyi }, - toDataURL: { value: utils.nyi }, - toBlob: { value: utils.nyi } - }, - attributes: { - width: { type: "unsigned long", default: 300}, - height: { type: "unsigned long", default: 150} - } -}); - -define({ - tag: 'dialog', - name: 'HTMLDialogElement', - ctor: function HTMLDialogElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - props: { - show: { value: utils.nyi }, - showModal: { value: utils.nyi }, - close: { value: utils.nyi } - }, - attributes: { - open: Boolean, - returnValue: String - } -}); - -define({ - tag: 'menuitem', - name: 'HTMLMenuItemElement', - ctor: function HTMLMenuItemElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - props: { - // The menuitem's label - _label: { - get: function() { - var val = this._getattr('label'); - if (val !== null && val !== '') { return val; } - val = this.textContent; - // Strip and collapse whitespace - return val.replace(/[ \t\n\f\r]+/g, ' ').trim(); - } - }, - // The menuitem label IDL attribute - label: { - get: function() { - var val = this._getattr('label'); - if (val !== null) { return val; } - return this._label; - }, - set: function(v) { - this._setattr('label', v); - }, - } - }, - attributes: { - type: { type: ["command","checkbox","radio"], missing: 'command' }, - icon: URL, - disabled: Boolean, - checked: Boolean, - radiogroup: String, - default: Boolean - } -}); - -define({ - tag: 'source', - name: 'HTMLSourceElement', - ctor: function HTMLSourceElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - srcset: String, - sizes: String, - media: String, - src: URL, - type: String, - width: String, - height: String, - } -}); - -define({ - tag: 'track', - name: 'HTMLTrackElement', - ctor: function HTMLTrackElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - src: URL, - srclang: String, - label: String, - default: Boolean, - kind: { type: ["subtitles", "captions", "descriptions", "chapters", "metadata"], missing: 'subtitles', invalid: 'metadata' }, - }, - props: { - NONE: { get: function() { return 0; } }, - LOADING: { get: function() { return 1; } }, - LOADED: { get: function() { return 2; } }, - ERROR: { get: function() { return 3; } }, - readyState: { get: utils.nyi }, - track: { get: utils.nyi } - } -}); - -define({ - // obsolete - tag: 'font', - name: 'HTMLFontElement', - ctor: function HTMLFontElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - color: { type: String, treatNullAsEmptyString: true }, - face: { type: String }, - size: { type: String }, - }, -}); - -define({ - // obsolete - tag: 'dir', - name: 'HTMLDirectoryElement', - ctor: function HTMLDirectoryElement(doc, localName, prefix) { - HTMLElement.call(this, doc, localName, prefix); - }, - attributes: { - compact: Boolean, - }, -}); - -define({ - tags: [ - "abbr", "address", "article", "aside", "b", "bdi", "bdo", "cite", "content", "code", - "dd", "dfn", "dt", "em", "figcaption", "figure", "footer", "header", "hgroup", "i", "kbd", - "main", "mark", "nav", "noscript", "rb", "rp", "rt", "rtc", - "ruby", "s", "samp", "section", "small", "strong", "sub", "summary", "sup", "u", "var", "wbr", - // Legacy elements - "acronym", "basefont", "big", "center", "nobr", "noembed", "noframes", - "plaintext", "strike", "tt" - ] -}); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/impl.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/impl.js deleted file mode 100644 index 732e8215..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/impl.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict"; -var utils = require('./utils'); - -exports = module.exports = { - CSSStyleDeclaration: require('./CSSStyleDeclaration'), - CharacterData: require('./CharacterData'), - Comment: require('./Comment'), - DOMException: require('./DOMException'), - DOMImplementation: require('./DOMImplementation'), - DOMTokenList: require('./DOMTokenList'), - Document: require('./Document'), - DocumentFragment: require('./DocumentFragment'), - DocumentType: require('./DocumentType'), - Element: require('./Element'), - HTMLParser: require('./HTMLParser'), - NamedNodeMap: require('./NamedNodeMap'), - Node: require('./Node'), - NodeList: require('./NodeList'), - NodeFilter: require('./NodeFilter'), - ProcessingInstruction: require('./ProcessingInstruction'), - Text: require('./Text'), - Window: require('./Window') -}; - -utils.merge(exports, require('./events')); -utils.merge(exports, require('./htmlelts').elements); -utils.merge(exports, require('./svg').elements); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/index.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/index.js deleted file mode 100644 index ebca0713..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/index.js +++ /dev/null @@ -1,80 +0,0 @@ -"use strict"; -var DOMImplementation = require('./DOMImplementation'); -var HTMLParser = require('./HTMLParser'); -var Window = require('./Window'); -var impl = require('./impl'); - -exports.createDOMImplementation = function() { - return new DOMImplementation(null); -}; - -exports.createDocument = function(html, force) { - // Previous API couldn't let you pass '' as a document, and that - // yields a slightly different document than createHTMLDocument('') - // does. The new `force` parameter lets you pass '' if you want to. - if (html || force) { - var parser = new HTMLParser(); - parser.parse(html || '', true); - return parser.document(); - } - return new DOMImplementation(null).createHTMLDocument(""); -}; - -exports.createIncrementalHTMLParser = function() { - var parser = new HTMLParser(); - /** API for incremental parser. */ - return { - /** Provide an additional chunk of text to be parsed. */ - write: function(s) { - if (s.length > 0) { - parser.parse(s, false, function() { return true; }); - } - }, - /** - * Signal that we are done providing input text, optionally - * providing one last chunk as a parameter. - */ - end: function(s) { - parser.parse(s || '', true, function() { return true; }); - }, - /** - * Performs a chunk of parsing work, returning at the end of - * the next token as soon as shouldPauseFunc() returns true. - * Returns true iff there is more work to do. - * - * For example: - * ``` - * var incrParser = domino.createIncrementalHTMLParser(); - * incrParser.end('...long html document...'); - * while (true) { - * // Pause every 10ms - * var start = Date.now(); - * var pauseIn10 = function() { return (Date.now() - start) >= 10; }; - * if (!incrParser.process(pauseIn10)) { - * break; - * } - * ...yield to other tasks, do other housekeeping, etc... - * } - * ``` - */ - process: function(shouldPauseFunc) { - return parser.parse('', false, shouldPauseFunc); - }, - /** - * Returns the result of the incremental parse. Valid after - * `this.end()` has been called and `this.process()` has returned - * false. - */ - document: function() { - return parser.document(); - }, - }; -}; - -exports.createWindow = function(html, address) { - var document = exports.createDocument(html); - if (address !== undefined) { document._address = address; } - return new impl.Window(document); -}; - -exports.impl = impl; \ No newline at end of file diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/select.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/select.js deleted file mode 100644 index 4e68e740..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/select.js +++ /dev/null @@ -1,933 +0,0 @@ -"use strict"; -/* jshint eqnull: true */ -/** - * Zest (https://github.com/chjj/zest) - * A css selector engine. - * Copyright (c) 2011-2012, Christopher Jeffrey. (MIT Licensed) - * Domino version based on Zest v0.1.3 with bugfixes applied. - */ - -/** - * Helpers - */ - -var window = Object.create(null, { - location: { get: function() { - throw new Error('window.location is not supported.'); - } } -}); - -var compareDocumentPosition = function(a, b) { - return a.compareDocumentPosition(b); -}; - -var order = function(a, b) { - /* jshint bitwise: false */ - return compareDocumentPosition(a, b) & 2 ? 1 : -1; -}; - -var next = function(el) { - while ((el = el.nextSibling) - && el.nodeType !== 1); - return el; -}; - -var prev = function(el) { - while ((el = el.previousSibling) - && el.nodeType !== 1); - return el; -}; - -var child = function(el) { - /*jshint -W084 */ - if (el = el.firstChild) { - while (el.nodeType !== 1 - && (el = el.nextSibling)); - } - return el; -}; - -var lastChild = function(el) { - /*jshint -W084 */ - if (el = el.lastChild) { - while (el.nodeType !== 1 - && (el = el.previousSibling)); - } - return el; -}; - -var parentIsElement = function(n) { - if (!n.parentNode) { return false; } - var nodeType = n.parentNode.nodeType; - // The root `html` element can be a first- or last-child, too. - return nodeType === 1 || nodeType === 9; -}; - -var unquote = function(str) { - if (!str) return str; - var ch = str[0]; - if (ch === '"' || ch === '\'') { - if (str[str.length-1] === ch) { - str = str.slice(1, -1); - } else { - // bad string. - str = str.slice(1); - } - return str.replace(rules.str_escape, function(s) { - var m = /^\\(?:([0-9A-Fa-f]+)|([\r\n\f]+))/.exec(s); - if (!m) { return s.slice(1); } - if (m[2]) { return ''; /* escaped newlines are ignored in strings. */ } - var cp = parseInt(m[1], 16); - return String.fromCodePoint ? String.fromCodePoint(cp) : - // Not all JavaScript implementations have String.fromCodePoint yet. - String.fromCharCode(cp); - }); - } else if (rules.ident.test(str)) { - return decodeid(str); - } else { - // NUMBER, PERCENTAGE, DIMENSION, etc - return str; - } -}; - -var decodeid = function(str) { - return str.replace(rules.escape, function(s) { - var m = /^\\([0-9A-Fa-f]+)/.exec(s); - if (!m) { return s[1]; } - var cp = parseInt(m[1], 16); - return String.fromCodePoint ? String.fromCodePoint(cp) : - // Not all JavaScript implementations have String.fromCodePoint yet. - String.fromCharCode(cp); - }); -}; - -var indexOf = (function() { - if (Array.prototype.indexOf) { - return Array.prototype.indexOf; - } - return function(obj, item) { - var i = this.length; - while (i--) { - if (this[i] === item) return i; - } - return -1; - }; -})(); - -var makeInside = function(start, end) { - var regex = rules.inside.source - .replace(//g, end); - - return new RegExp(regex); -}; - -var replace = function(regex, name, val) { - regex = regex.source; - regex = regex.replace(name, val.source || val); - return new RegExp(regex); -}; - -var truncateUrl = function(url, num) { - return url - .replace(/^(?:\w+:\/\/|\/+)/, '') - .replace(/(?:\/+|\/*#.*?)$/, '') - .split('/', num) - .join('/'); -}; - -/** - * Handle `nth` Selectors - */ - -var parseNth = function(param_, test) { - var param = param_.replace(/\s+/g, '') - , cap; - - if (param === 'even') { - param = '2n+0'; - } else if (param === 'odd') { - param = '2n+1'; - } else if (param.indexOf('n') === -1) { - param = '0n' + param; - } - - cap = /^([+-])?(\d+)?n([+-])?(\d+)?$/.exec(param); - - return { - group: cap[1] === '-' - ? -(cap[2] || 1) - : +(cap[2] || 1), - offset: cap[4] - ? (cap[3] === '-' ? -cap[4] : +cap[4]) - : 0 - }; -}; - -var nth = function(param_, test, last) { - var param = parseNth(param_) - , group = param.group - , offset = param.offset - , find = !last ? child : lastChild - , advance = !last ? next : prev; - - return function(el) { - if (!parentIsElement(el)) return; - - var rel = find(el.parentNode) - , pos = 0; - - while (rel) { - if (test(rel, el)) pos++; - if (rel === el) { - pos -= offset; - return group && pos - ? (pos % group) === 0 && (pos < 0 === group < 0) - : !pos; - } - rel = advance(rel); - } - }; -}; - -/** - * Simple Selectors - */ - -var selectors = { - '*': (function() { - if (false/*function() { - var el = document.createElement('div'); - el.appendChild(document.createComment('')); - return !!el.getElementsByTagName('*')[0]; - }()*/) { - return function(el) { - if (el.nodeType === 1) return true; - }; - } - return function() { - return true; - }; - })(), - 'type': function(type) { - type = type.toLowerCase(); - return function(el) { - return el.nodeName.toLowerCase() === type; - }; - }, - 'attr': function(key, op, val, i) { - op = operators[op]; - return function(el) { - var attr; - switch (key) { - case 'for': - attr = el.htmlFor; - break; - case 'class': - // className is '' when non-existent - // getAttribute('class') is null - attr = el.className; - if (attr === '' && el.getAttribute('class') == null) { - attr = null; - } - break; - case 'href': - case 'src': - attr = el.getAttribute(key, 2); - break; - case 'title': - // getAttribute('title') can be '' when non-existent sometimes? - attr = el.getAttribute('title') || null; - break; - // careful with attributes with special getter functions - case 'id': - case 'lang': - case 'dir': - case 'accessKey': - case 'hidden': - case 'tabIndex': - case 'style': - if (el.getAttribute) { - attr = el.getAttribute(key); - break; - } - /* falls through */ - default: - if (el.hasAttribute && !el.hasAttribute(key)) { - break; - } - attr = el[key] != null - ? el[key] - : el.getAttribute && el.getAttribute(key); - break; - } - if (attr == null) return; - attr = attr + ''; - if (i) { - attr = attr.toLowerCase(); - val = val.toLowerCase(); - } - return op(attr, val); - }; - }, - ':first-child': function(el) { - return !prev(el) && parentIsElement(el); - }, - ':last-child': function(el) { - return !next(el) && parentIsElement(el); - }, - ':only-child': function(el) { - return !prev(el) && !next(el) && parentIsElement(el); - }, - ':nth-child': function(param, last) { - return nth(param, function() { - return true; - }, last); - }, - ':nth-last-child': function(param) { - return selectors[':nth-child'](param, true); - }, - ':root': function(el) { - return el.ownerDocument.documentElement === el; - }, - ':empty': function(el) { - return !el.firstChild; - }, - ':not': function(sel) { - var test = compileGroup(sel); - return function(el) { - return !test(el); - }; - }, - ':first-of-type': function(el) { - if (!parentIsElement(el)) return; - var type = el.nodeName; - /*jshint -W084 */ - while (el = prev(el)) { - if (el.nodeName === type) return; - } - return true; - }, - ':last-of-type': function(el) { - if (!parentIsElement(el)) return; - var type = el.nodeName; - /*jshint -W084 */ - while (el = next(el)) { - if (el.nodeName === type) return; - } - return true; - }, - ':only-of-type': function(el) { - return selectors[':first-of-type'](el) - && selectors[':last-of-type'](el); - }, - ':nth-of-type': function(param, last) { - return nth(param, function(rel, el) { - return rel.nodeName === el.nodeName; - }, last); - }, - ':nth-last-of-type': function(param) { - return selectors[':nth-of-type'](param, true); - }, - ':checked': function(el) { - return !!(el.checked || el.selected); - }, - ':indeterminate': function(el) { - return !selectors[':checked'](el); - }, - ':enabled': function(el) { - return !el.disabled && el.type !== 'hidden'; - }, - ':disabled': function(el) { - return !!el.disabled; - }, - ':target': function(el) { - return el.id === window.location.hash.substring(1); - }, - ':focus': function(el) { - return el === el.ownerDocument.activeElement; - }, - ':is': function(sel) { - return compileGroup(sel); - }, - // :matches is an older name for :is; see - // https://github.com/w3c/csswg-drafts/issues/3258 - ':matches': function(sel) { - return selectors[':is'](sel); - }, - ':nth-match': function(param, last) { - var args = param.split(/\s*,\s*/) - , arg = args.shift() - , test = compileGroup(args.join(',')); - - return nth(arg, test, last); - }, - ':nth-last-match': function(param) { - return selectors[':nth-match'](param, true); - }, - ':links-here': function(el) { - return el + '' === window.location + ''; - }, - ':lang': function(param) { - return function(el) { - while (el) { - if (el.lang) return el.lang.indexOf(param) === 0; - el = el.parentNode; - } - }; - }, - ':dir': function(param) { - return function(el) { - while (el) { - if (el.dir) return el.dir === param; - el = el.parentNode; - } - }; - }, - ':scope': function(el, con) { - var context = con || el.ownerDocument; - if (context.nodeType === 9) { - return el === context.documentElement; - } - return el === context; - }, - ':any-link': function(el) { - return typeof el.href === 'string'; - }, - ':local-link': function(el) { - if (el.nodeName) { - return el.href && el.host === window.location.host; - } - var param = +el + 1; - return function(el) { - if (!el.href) return; - - var url = window.location + '' - , href = el + ''; - - return truncateUrl(url, param) === truncateUrl(href, param); - }; - }, - ':default': function(el) { - return !!el.defaultSelected; - }, - ':valid': function(el) { - return el.willValidate || (el.validity && el.validity.valid); - }, - ':invalid': function(el) { - return !selectors[':valid'](el); - }, - ':in-range': function(el) { - return el.value > el.min && el.value <= el.max; - }, - ':out-of-range': function(el) { - return !selectors[':in-range'](el); - }, - ':required': function(el) { - return !!el.required; - }, - ':optional': function(el) { - return !el.required; - }, - ':read-only': function(el) { - if (el.readOnly) return true; - - var attr = el.getAttribute('contenteditable') - , prop = el.contentEditable - , name = el.nodeName.toLowerCase(); - - name = name !== 'input' && name !== 'textarea'; - - return (name || el.disabled) && attr == null && prop !== 'true'; - }, - ':read-write': function(el) { - return !selectors[':read-only'](el); - }, - ':hover': function() { - throw new Error(':hover is not supported.'); - }, - ':active': function() { - throw new Error(':active is not supported.'); - }, - ':link': function() { - throw new Error(':link is not supported.'); - }, - ':visited': function() { - throw new Error(':visited is not supported.'); - }, - ':column': function() { - throw new Error(':column is not supported.'); - }, - ':nth-column': function() { - throw new Error(':nth-column is not supported.'); - }, - ':nth-last-column': function() { - throw new Error(':nth-last-column is not supported.'); - }, - ':current': function() { - throw new Error(':current is not supported.'); - }, - ':past': function() { - throw new Error(':past is not supported.'); - }, - ':future': function() { - throw new Error(':future is not supported.'); - }, - // Non-standard, for compatibility purposes. - ':contains': function(param) { - return function(el) { - var text = el.innerText || el.textContent || el.value || ''; - return text.indexOf(param) !== -1; - }; - }, - ':has': function(param) { - return function(el) { - return find(param, el).length > 0; - }; - } - // Potentially add more pseudo selectors for - // compatibility with sizzle and most other - // selector engines (?). -}; - -/** - * Attribute Operators - */ - -var operators = { - '-': function() { - return true; - }, - '=': function(attr, val) { - return attr === val; - }, - '*=': function(attr, val) { - return attr.indexOf(val) !== -1; - }, - '~=': function(attr, val) { - var i - , s - , f - , l; - - for (s = 0; true; s = i + 1) { - i = attr.indexOf(val, s); - if (i === -1) return false; - f = attr[i - 1]; - l = attr[i + val.length]; - if ((!f || f === ' ') && (!l || l === ' ')) return true; - } - }, - '|=': function(attr, val) { - var i = attr.indexOf(val) - , l; - - if (i !== 0) return; - l = attr[i + val.length]; - - return l === '-' || !l; - }, - '^=': function(attr, val) { - return attr.indexOf(val) === 0; - }, - '$=': function(attr, val) { - var i = attr.lastIndexOf(val); - return i !== -1 && i + val.length === attr.length; - }, - // non-standard - '!=': function(attr, val) { - return attr !== val; - } -}; - -/** - * Combinator Logic - */ - -var combinators = { - ' ': function(test) { - return function(el) { - /*jshint -W084 */ - while (el = el.parentNode) { - if (test(el)) return el; - } - }; - }, - '>': function(test) { - return function(el) { - /*jshint -W084 */ - if (el = el.parentNode) { - return test(el) && el; - } - }; - }, - '+': function(test) { - return function(el) { - /*jshint -W084 */ - if (el = prev(el)) { - return test(el) && el; - } - }; - }, - '~': function(test) { - return function(el) { - /*jshint -W084 */ - while (el = prev(el)) { - if (test(el)) return el; - } - }; - }, - 'noop': function(test) { - return function(el) { - return test(el) && el; - }; - }, - 'ref': function(test, name) { - var node; - - function ref(el) { - var doc = el.ownerDocument - , nodes = doc.getElementsByTagName('*') - , i = nodes.length; - - while (i--) { - node = nodes[i]; - if (ref.test(el)) { - node = null; - return true; - } - } - - node = null; - } - - ref.combinator = function(el) { - if (!node || !node.getAttribute) return; - - var attr = node.getAttribute(name) || ''; - if (attr[0] === '#') attr = attr.substring(1); - - if (attr === el.id && test(node)) { - return node; - } - }; - - return ref; - } -}; - -/** - * Grammar - */ - -var rules = { - escape: /\\(?:[^0-9A-Fa-f\r\n]|[0-9A-Fa-f]{1,6}[\r\n\t ]?)/g, - str_escape: /(escape)|\\(\n|\r\n?|\f)/g, - nonascii: /[\u00A0-\uFFFF]/, - cssid: /(?:(?!-?[0-9])(?:escape|nonascii|[-_a-zA-Z0-9])+)/, - qname: /^ *(cssid|\*)/, - simple: /^(?:([.#]cssid)|pseudo|attr)/, - ref: /^ *\/(cssid)\/ */, - combinator: /^(?: +([^ \w*.#\\]) +|( )+|([^ \w*.#\\]))(?! *$)/, - attr: /^\[(cssid)(?:([^\w]?=)(inside))?\]/, - pseudo: /^(:cssid)(?:\((inside)\))?/, - inside: /(?:"(?:\\"|[^"])*"|'(?:\\'|[^'])*'|<[^"'>]*>|\\["'>]|[^"'>])*/, - ident: /^(cssid)$/ -}; - -rules.cssid = replace(rules.cssid, 'nonascii', rules.nonascii); -rules.cssid = replace(rules.cssid, 'escape', rules.escape); -rules.qname = replace(rules.qname, 'cssid', rules.cssid); -rules.simple = replace(rules.simple, 'cssid', rules.cssid); -rules.ref = replace(rules.ref, 'cssid', rules.cssid); -rules.attr = replace(rules.attr, 'cssid', rules.cssid); -rules.pseudo = replace(rules.pseudo, 'cssid', rules.cssid); -rules.inside = replace(rules.inside, '[^"\'>]*', rules.inside); -rules.attr = replace(rules.attr, 'inside', makeInside('\\[', '\\]')); -rules.pseudo = replace(rules.pseudo, 'inside', makeInside('\\(', '\\)')); -rules.simple = replace(rules.simple, 'pseudo', rules.pseudo); -rules.simple = replace(rules.simple, 'attr', rules.attr); -rules.ident = replace(rules.ident, 'cssid', rules.cssid); -rules.str_escape = replace(rules.str_escape, 'escape', rules.escape); - -/** - * Compiling - */ - -var compile = function(sel_) { - var sel = sel_.replace(/^\s+|\s+$/g, '') - , test - , filter = [] - , buff = [] - , subject - , qname - , cap - , op - , ref; - - /*jshint -W084 */ - while (sel) { - if (cap = rules.qname.exec(sel)) { - sel = sel.substring(cap[0].length); - qname = decodeid(cap[1]); - buff.push(tok(qname, true)); - } else if (cap = rules.simple.exec(sel)) { - sel = sel.substring(cap[0].length); - qname = '*'; - buff.push(tok(qname, true)); - buff.push(tok(cap)); - } else { - throw new SyntaxError('Invalid selector.'); - } - - while (cap = rules.simple.exec(sel)) { - sel = sel.substring(cap[0].length); - buff.push(tok(cap)); - } - - if (sel[0] === '!') { - sel = sel.substring(1); - subject = makeSubject(); - subject.qname = qname; - buff.push(subject.simple); - } - - if (cap = rules.ref.exec(sel)) { - sel = sel.substring(cap[0].length); - ref = combinators.ref(makeSimple(buff), decodeid(cap[1])); - filter.push(ref.combinator); - buff = []; - continue; - } - - if (cap = rules.combinator.exec(sel)) { - sel = sel.substring(cap[0].length); - op = cap[1] || cap[2] || cap[3]; - if (op === ',') { - filter.push(combinators.noop(makeSimple(buff))); - break; - } - } else { - op = 'noop'; - } - - if (!combinators[op]) { throw new SyntaxError('Bad combinator.'); } - filter.push(combinators[op](makeSimple(buff))); - buff = []; - } - - test = makeTest(filter); - test.qname = qname; - test.sel = sel; - - if (subject) { - subject.lname = test.qname; - - subject.test = test; - subject.qname = subject.qname; - subject.sel = test.sel; - test = subject; - } - - if (ref) { - ref.test = test; - ref.qname = test.qname; - ref.sel = test.sel; - test = ref; - } - - return test; -}; - -var tok = function(cap, qname) { - // qname - if (qname) { - return cap === '*' - ? selectors['*'] - : selectors.type(cap); - } - - // class/id - if (cap[1]) { - return cap[1][0] === '.' - // XXX unescape here? or in attr? - ? selectors.attr('class', '~=', decodeid(cap[1].substring(1)), false) - : selectors.attr('id', '=', decodeid(cap[1].substring(1)), false); - } - - // pseudo-name - // inside-pseudo - if (cap[2]) { - return cap[3] - ? selectors[decodeid(cap[2])](unquote(cap[3])) - : selectors[decodeid(cap[2])]; - } - - // attr name - // attr op - // attr value - if (cap[4]) { - var value = cap[6]; - var i = /["'\s]\s*I$/i.test(value); - if (i) { - value = value.replace(/\s*I$/i, ''); - } - return selectors.attr(decodeid(cap[4]), cap[5] || '-', unquote(value), i); - } - - throw new SyntaxError('Unknown Selector.'); -}; - -var makeSimple = function(func) { - var l = func.length - , i; - - // Potentially make sure - // `el` is truthy. - if (l < 2) return func[0]; - - return function(el) { - if (!el) return; - for (i = 0; i < l; i++) { - if (!func[i](el)) return; - } - return true; - }; -}; - -var makeTest = function(func) { - if (func.length < 2) { - return function(el) { - return !!func[0](el); - }; - } - return function(el) { - var i = func.length; - while (i--) { - if (!(el = func[i](el))) return; - } - return true; - }; -}; - -var makeSubject = function() { - var target; - - function subject(el) { - var node = el.ownerDocument - , scope = node.getElementsByTagName(subject.lname) - , i = scope.length; - - while (i--) { - if (subject.test(scope[i]) && target === el) { - target = null; - return true; - } - } - - target = null; - } - - subject.simple = function(el) { - target = el; - return true; - }; - - return subject; -}; - -var compileGroup = function(sel) { - var test = compile(sel) - , tests = [ test ]; - - while (test.sel) { - test = compile(test.sel); - tests.push(test); - } - - if (tests.length < 2) return test; - - return function(el) { - var l = tests.length - , i = 0; - - for (; i < l; i++) { - if (tests[i](el)) return true; - } - }; -}; - -/** - * Selection - */ - -var find = function(sel, node) { - var results = [] - , test = compile(sel) - , scope = node.getElementsByTagName(test.qname) - , i = 0 - , el; - - /*jshint -W084 */ - while (el = scope[i++]) { - if (test(el)) results.push(el); - } - - if (test.sel) { - while (test.sel) { - test = compile(test.sel); - scope = node.getElementsByTagName(test.qname); - i = 0; - /*jshint -W084 */ - while (el = scope[i++]) { - if (test(el) && indexOf.call(results, el) === -1) { - results.push(el); - } - } - } - results.sort(order); - } - - return results; -}; - -/** - * Expose - */ - -module.exports = exports = function(sel, context) { - /* when context isn't a DocumentFragment and the selector is simple: */ - var id, r; - if (context.nodeType !== 11 && sel.indexOf(' ') === -1) { - if (sel[0] === '#' && context.rooted && /^#[A-Z_][-A-Z0-9_]*$/i.test(sel)) { - if (context.doc._hasMultipleElementsWithId) { - id = sel.substring(1); - if (!context.doc._hasMultipleElementsWithId(id)) { - r = context.doc.getElementById(id); - return r ? [r] : []; - } - } - } - if (sel[0] === '.' && /^\.\w+$/.test(sel)) { - return context.getElementsByClassName(sel.substring(1)); - } - if (/^\w+$/.test(sel)) { - return context.getElementsByTagName(sel); - } - } - /* do things the hard/slow way */ - return find(sel, context); -}; - -exports.selectors = selectors; -exports.operators = operators; -exports.combinators = combinators; - -exports.matches = function(el, sel) { - var test = { sel: sel }; - do { - test = compile(test.sel); - if (test(el)) { return true; } - } while (test.sel); - return false; -}; diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/style_parser.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/style_parser.js deleted file mode 100644 index 6b893c85..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/style_parser.js +++ /dev/null @@ -1,106 +0,0 @@ -"use strict"; -/** - * @license - * Copyright Google LLC All Rights Reserved. - * - * Use of this source code is governed by an MIT-style license that can be - * found in the LICENSE file at https://angular.io/license - */ - -// The below is a compiled copy of https://github.com/angular/angular/blob/92e41e9cb417223d9888a4c23b4c0e73188f87d0/packages/compiler/src/render3/view/style_parser.ts - -Object.defineProperty(exports, "__esModule", { value: true }); -exports.hyphenate = exports.parse = void 0; -/** - * Parses string representation of a style and converts it into object literal. - * - * @param value string representation of style as used in the `style` attribute in HTML. - * Example: `color: red; height: auto`. - * @returns An array of style property name and value pairs, e.g. `['color', 'red', 'height', - * 'auto']` - */ -function parse(value) { - // we use a string array here instead of a string map - // because a string-map is not guaranteed to retain the - // order of the entries whereas a string array can be - // constructed in a [key, value, key, value] format. - const styles = []; - let i = 0; - let parenDepth = 0; - let quote = 0; /* Char.QuoteNone */ - let valueStart = 0; - let propStart = 0; - let currentProp = null; - while (i < value.length) { - const token = value.charCodeAt(i++); - switch (token) { - case 40 /* Char.OpenParen */: - parenDepth++; - break; - case 41 /* Char.CloseParen */: - parenDepth--; - break; - case 39 /* Char.QuoteSingle */: - // valueStart needs to be there since prop values don't - // have quotes in CSS - if (quote === 0 /* Char.QuoteNone */) { - quote = 39 /* Char.QuoteSingle */; - } else if ( - quote === 39 /* Char.QuoteSingle */ && - value.charCodeAt(i - 1) !== 92 /* Char.BackSlash */ - ) { - quote = 0 /* Char.QuoteNone */; - } - break; - case 34 /* Char.QuoteDouble */: - // same logic as above - if (quote === 0 /* Char.QuoteNone */) { - quote = 34 /* Char.QuoteDouble */; - } else if ( - quote === 34 /* Char.QuoteDouble */ && - value.charCodeAt(i - 1) !== 92 /* Char.BackSlash */ - ) { - quote = 0 /* Char.QuoteNone */; - } - break; - case 58 /* Char.Colon */: - if ( - !currentProp && - parenDepth === 0 && - quote === 0 /* Char.QuoteNone */ - ) { - currentProp = hyphenate(value.substring(propStart, i - 1).trim()); - valueStart = i; - } - break; - case 59 /* Char.Semicolon */: - if ( - currentProp && - valueStart > 0 && - parenDepth === 0 && - quote === 0 /* Char.QuoteNone */ - ) { - const styleVal = value.substring(valueStart, i - 1).trim(); - styles.push(currentProp, styleVal); - propStart = i; - valueStart = 0; - currentProp = null; - } - break; - } - } - if (currentProp && valueStart) { - const styleVal = value.slice(valueStart).trim(); - styles.push(currentProp, styleVal); - } - return styles; -} -exports.parse = parse; -function hyphenate(value) { - return value - .replace(/[a-z][A-Z]/g, (v) => { - return v.charAt(0) + "-" + v.charAt(1); - }) - .toLowerCase(); -} -exports.hyphenate = hyphenate; diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/svg.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/svg.js deleted file mode 100644 index c46e9902..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/svg.js +++ /dev/null @@ -1,59 +0,0 @@ -"use strict"; -var Element = require('./Element'); -var defineElement = require('./defineElement'); -var utils = require('./utils'); -var CSSStyleDeclaration = require('./CSSStyleDeclaration'); - -var svgElements = exports.elements = {}; -var svgNameToImpl = Object.create(null); - -exports.createElement = function(doc, localName, prefix) { - var impl = svgNameToImpl[localName] || SVGElement; - return new impl(doc, localName, prefix); -}; - -function define(spec) { - return defineElement(spec, SVGElement, svgElements, svgNameToImpl); -} - -var SVGElement = define({ - superclass: Element, - name: 'SVGElement', - ctor: function SVGElement(doc, localName, prefix) { - Element.call(this, doc, localName, utils.NAMESPACE.SVG, prefix); - }, - props: { - style: { get: function() { - if (!this._style) - this._style = new CSSStyleDeclaration(this); - return this._style; - }} - } -}); - -define({ - name: 'SVGSVGElement', - ctor: function SVGSVGElement(doc, localName, prefix) { - SVGElement.call(this, doc, localName, prefix); - }, - tag: 'svg', - props: { - createSVGRect: { value: function () { - return exports.createElement(this.ownerDocument, 'rect', null); - } } - } -}); - -define({ - tags: [ - 'a', 'altGlyph', 'altGlyphDef', 'altGlyphItem', 'animate', 'animateColor', 'animateMotion', 'animateTransform', - 'circle', 'clipPath', 'color-profile', 'cursor', 'defs', 'desc', 'ellipse', 'feBlend', 'feColorMatrix', - 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', - 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', - 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence', 'filter', - 'font', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignObject', 'g', - 'glyph', 'glyphRef', 'hkern', 'image', 'line', 'linearGradient', 'marker', 'mask', 'metadata', 'missing-glyph', - 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'script', 'set', 'stop', 'style', - 'switch', 'symbol', 'text', 'textPath', 'title', 'tref', 'tspan', 'use', 'view', 'vkern' - ] -}); diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/utils.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/utils.js deleted file mode 100644 index affaed84..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/utils.js +++ /dev/null @@ -1,85 +0,0 @@ -"use strict"; -var DOMException = require('./DOMException'); -var ERR = DOMException; -var isApiWritable = require("./config").isApiWritable; - -exports.NAMESPACE = { - HTML: 'http://www.w3.org/1999/xhtml', - XML: 'http://www.w3.org/XML/1998/namespace', - XMLNS: 'http://www.w3.org/2000/xmlns/', - MATHML: 'http://www.w3.org/1998/Math/MathML', - SVG: 'http://www.w3.org/2000/svg', - XLINK: 'http://www.w3.org/1999/xlink' -}; - -// -// Shortcut functions for throwing errors of various types. -// -exports.IndexSizeError = function() { throw new DOMException(ERR.INDEX_SIZE_ERR); }; -exports.HierarchyRequestError = function() { throw new DOMException(ERR.HIERARCHY_REQUEST_ERR); }; -exports.WrongDocumentError = function() { throw new DOMException(ERR.WRONG_DOCUMENT_ERR); }; -exports.InvalidCharacterError = function() { throw new DOMException(ERR.INVALID_CHARACTER_ERR); }; -exports.NoModificationAllowedError = function() { throw new DOMException(ERR.NO_MODIFICATION_ALLOWED_ERR); }; -exports.NotFoundError = function() { throw new DOMException(ERR.NOT_FOUND_ERR); }; -exports.NotSupportedError = function() { throw new DOMException(ERR.NOT_SUPPORTED_ERR); }; -exports.InvalidStateError = function() { throw new DOMException(ERR.INVALID_STATE_ERR); }; -exports.SyntaxError = function() { throw new DOMException(ERR.SYNTAX_ERR); }; -exports.InvalidModificationError = function() { throw new DOMException(ERR.INVALID_MODIFICATION_ERR); }; -exports.NamespaceError = function() { throw new DOMException(ERR.NAMESPACE_ERR); }; -exports.InvalidAccessError = function() { throw new DOMException(ERR.INVALID_ACCESS_ERR); }; -exports.TypeMismatchError = function() { throw new DOMException(ERR.TYPE_MISMATCH_ERR); }; -exports.SecurityError = function() { throw new DOMException(ERR.SECURITY_ERR); }; -exports.NetworkError = function() { throw new DOMException(ERR.NETWORK_ERR); }; -exports.AbortError = function() { throw new DOMException(ERR.ABORT_ERR); }; -exports.UrlMismatchError = function() { throw new DOMException(ERR.URL_MISMATCH_ERR); }; -exports.QuotaExceededError = function() { throw new DOMException(ERR.QUOTA_EXCEEDED_ERR); }; -exports.TimeoutError = function() { throw new DOMException(ERR.TIMEOUT_ERR); }; -exports.InvalidNodeTypeError = function() { throw new DOMException(ERR.INVALID_NODE_TYPE_ERR); }; -exports.DataCloneError = function() { throw new DOMException(ERR.DATA_CLONE_ERR); }; - -exports.nyi = function() { - throw new Error("NotYetImplemented"); -}; - -exports.shouldOverride = function() { - throw new Error("Abstract function; should be overriding in subclass."); -}; - -exports.assert = function(expr, msg) { - if (!expr) { - throw new Error("Assertion failed: " + (msg || "") + "\n" + new Error().stack); - } -}; - -exports.expose = function(src, c) { - for (var n in src) { - Object.defineProperty(c.prototype, n, { value: src[n], writable: isApiWritable }); - } -}; - -exports.merge = function(a, b) { - for (var n in b) { - a[n] = b[n]; - } -}; - -// Compare two nodes based on their document order. This function is intended -// to be passed to sort(). Assumes that the array being sorted does not -// contain duplicates. And that all nodes are connected and comparable. -// Clever code by ppk via jeresig. -exports.documentOrder = function(n,m) { - /* jshint bitwise: false */ - return 3 - (n.compareDocumentPosition(m) & 6); -}; - -exports.toASCIILowerCase = function(s) { - return s.replace(/[A-Z]+/g, function(c) { - return c.toLowerCase(); - }); -}; - -exports.toASCIIUpperCase = function(s) { - return s.replace(/[a-z]+/g, function(c) { - return c.toUpperCase(); - }); -}; diff --git a/claude-code-source/node_modules/@mixmark-io/domino/lib/xmlnames.js b/claude-code-source/node_modules/@mixmark-io/domino/lib/xmlnames.js deleted file mode 100644 index e131d81c..00000000 --- a/claude-code-source/node_modules/@mixmark-io/domino/lib/xmlnames.js +++ /dev/null @@ -1,91 +0,0 @@ -"use strict"; -// This grammar is from the XML and XML Namespace specs. It specifies whether -// a string (such as an element or attribute name) is a valid Name or QName. -// -// Name ::= NameStartChar (NameChar)* -// NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | -// [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | -// [#x370-#x37D] | [#x37F-#x1FFF] | -// [#x200C-#x200D] | [#x2070-#x218F] | -// [#x2C00-#x2FEF] | [#x3001-#xD7FF] | -// [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | -// [#x10000-#xEFFFF] -// -// NameChar ::= NameStartChar | "-" | "." | [0-9] | -// #xB7 | [#x0300-#x036F] | [#x203F-#x2040] -// -// QName ::= PrefixedName| UnprefixedName -// PrefixedName ::= Prefix ':' LocalPart -// UnprefixedName ::= LocalPart -// Prefix ::= NCName -// LocalPart ::= NCName -// NCName ::= Name - (Char* ':' Char*) -// # An XML Name, minus the ":" -// - -exports.isValidName = isValidName; -exports.isValidQName = isValidQName; - -// Most names will be ASCII only. Try matching against simple regexps first -var simplename = /^[_:A-Za-z][-.:\w]+$/; -var simpleqname = /^([_A-Za-z][-.\w]+|[_A-Za-z][-.\w]+:[_A-Za-z][-.\w]+)$/; - -// If the regular expressions above fail, try more complex ones that work -// for any identifiers using codepoints from the Unicode BMP -var ncnamestartchars = "_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02ff\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD"; -var ncnamechars = "-._A-Za-z0-9\u00B7\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02ff\u0300-\u037D\u037F-\u1FFF\u200C\u200D\u203f\u2040\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD"; - -var ncname = "[" + ncnamestartchars + "][" + ncnamechars + "]*"; -var namestartchars = ncnamestartchars + ":"; -var namechars = ncnamechars + ":"; -var name = new RegExp("^[" + namestartchars + "]" + "[" + namechars + "]*$"); -var qname = new RegExp("^(" + ncname + "|" + ncname + ":" + ncname + ")$"); - -// XML says that these characters are also legal: -// [#x10000-#xEFFFF]. So if the patterns above fail, and the -// target string includes surrogates, then try the following -// patterns that allow surrogates and then run an extra validation -// step to make sure that the surrogates are in valid pairs and in -// the right range. Note that since the characters \uf0000 to \u1f0000 -// are not allowed, it means that the high surrogate can only go up to -// \uDB7f instead of \uDBFF. -var hassurrogates = /[\uD800-\uDB7F\uDC00-\uDFFF]/; -var surrogatechars = /[\uD800-\uDB7F\uDC00-\uDFFF]/g; -var surrogatepairs = /[\uD800-\uDB7F][\uDC00-\uDFFF]/g; - -// Modify the variables above to allow surrogates -ncnamestartchars += "\uD800-\uDB7F\uDC00-\uDFFF"; -ncnamechars += "\uD800-\uDB7F\uDC00-\uDFFF"; -ncname = "[" + ncnamestartchars + "][" + ncnamechars + "]*"; -namestartchars = ncnamestartchars + ":"; -namechars = ncnamechars + ":"; - -// Build another set of regexps that include surrogates -var surrogatename = new RegExp("^[" + namestartchars + "]" + "[" + namechars + "]*$"); -var surrogateqname = new RegExp("^(" + ncname + "|" + ncname + ":" + ncname + ")$"); - -function isValidName(s) { - if (simplename.test(s)) return true; // Plain ASCII - if (name.test(s)) return true; // Unicode BMP - - // Maybe the tests above failed because s includes surrogate pairs - // Most likely, though, they failed for some more basic syntax problem - if (!hassurrogates.test(s)) return false; - - // Is the string a valid name if we allow surrogates? - if (!surrogatename.test(s)) return false; - - // Finally, are the surrogates all correctly paired up? - var chars = s.match(surrogatechars), pairs = s.match(surrogatepairs); - return pairs !== null && 2*pairs.length === chars.length; -} - -function isValidQName(s) { - if (simpleqname.test(s)) return true; // Plain ASCII - if (qname.test(s)) return true; // Unicode BMP - - if (!hassurrogates.test(s)) return false; - if (!surrogateqname.test(s)) return false; - var chars = s.match(surrogatechars), pairs = s.match(surrogatepairs); - return pairs !== null && 2*pairs.length === chars.length; -} diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js deleted file mode 100644 index 49e11378..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js +++ /dev/null @@ -1,900 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js deleted file mode 100644 index 49b12c6c..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js +++ /dev/null @@ -1,624 +0,0 @@ -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 - * type CustomNotification = z.infer - * type CustomResult = z.infer - * - * // Create typed client - * const client = new Client({ - * 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js deleted file mode 100644 index 58c47415..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js +++ /dev/null @@ -1,206 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js deleted file mode 100644 index e1e4b9c6..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js +++ /dev/null @@ -1,191 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js deleted file mode 100644 index 624172aa..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js +++ /dev/null @@ -1,477 +0,0 @@ -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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js deleted file mode 100644 index 0c1d8af7..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js +++ /dev/null @@ -1,184 +0,0 @@ -/** - * 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js deleted file mode 100644 index 38800311..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js +++ /dev/null @@ -1,64 +0,0 @@ -/** - * 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js deleted file mode 100644 index d4949de6..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js +++ /dev/null @@ -1,16 +0,0 @@ -/** - * 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js deleted file mode 100644 index 059ab7b1..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/server.js +++ /dev/null @@ -1,246 +0,0 @@ -/** - * 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 \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js deleted file mode 100644 index 7106ab98..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js +++ /dev/null @@ -1,180 +0,0 @@ -/** - * Base class for all OAuth errors - */ -export class OAuthError extends Error { - constructor(message, errorUri) { - super(message); - this.errorUri = errorUri; - this.name = this.constructor.name; - } - /** - * Converts the error to a standard OAuth error response object - */ - toResponseObject() { - const response = { - error: this.errorCode, - error_description: this.message - }; - if (this.errorUri) { - response.error_uri = this.errorUri; - } - return response; - } - get errorCode() { - return this.constructor.errorCode; - } -} -/** - * Invalid request error - The request is missing a required parameter, - * includes an invalid parameter value, includes a parameter more than once, - * or is otherwise malformed. - */ -export class InvalidRequestError extends OAuthError { -} -InvalidRequestError.errorCode = 'invalid_request'; -/** - * Invalid client error - Client authentication failed (e.g., unknown client, no client - * authentication included, or unsupported authentication method). - */ -export class InvalidClientError extends OAuthError { -} -InvalidClientError.errorCode = 'invalid_client'; -/** - * Invalid grant error - The provided authorization grant or refresh token is - * invalid, expired, revoked, does not match the redirection URI used in the - * authorization request, or was issued to another client. - */ -export class InvalidGrantError extends OAuthError { -} -InvalidGrantError.errorCode = 'invalid_grant'; -/** - * Unauthorized client error - The authenticated client is not authorized to use - * this authorization grant type. - */ -export class UnauthorizedClientError extends OAuthError { -} -UnauthorizedClientError.errorCode = 'unauthorized_client'; -/** - * Unsupported grant type error - The authorization grant type is not supported - * by the authorization server. - */ -export class UnsupportedGrantTypeError extends OAuthError { -} -UnsupportedGrantTypeError.errorCode = 'unsupported_grant_type'; -/** - * Invalid scope error - The requested scope is invalid, unknown, malformed, or - * exceeds the scope granted by the resource owner. - */ -export class InvalidScopeError extends OAuthError { -} -InvalidScopeError.errorCode = 'invalid_scope'; -/** - * Access denied error - The resource owner or authorization server denied the request. - */ -export class AccessDeniedError extends OAuthError { -} -AccessDeniedError.errorCode = 'access_denied'; -/** - * Server error - The authorization server encountered an unexpected condition - * that prevented it from fulfilling the request. - */ -export class ServerError extends OAuthError { -} -ServerError.errorCode = 'server_error'; -/** - * Temporarily unavailable error - The authorization server is currently unable to - * handle the request due to a temporary overloading or maintenance of the server. - */ -export class TemporarilyUnavailableError extends OAuthError { -} -TemporarilyUnavailableError.errorCode = 'temporarily_unavailable'; -/** - * Unsupported response type error - The authorization server does not support - * obtaining an authorization code using this method. - */ -export class UnsupportedResponseTypeError extends OAuthError { -} -UnsupportedResponseTypeError.errorCode = 'unsupported_response_type'; -/** - * Unsupported token type error - The authorization server does not support - * the requested token type. - */ -export class UnsupportedTokenTypeError extends OAuthError { -} -UnsupportedTokenTypeError.errorCode = 'unsupported_token_type'; -/** - * Invalid token error - The access token provided is expired, revoked, malformed, - * or invalid for other reasons. - */ -export class InvalidTokenError extends OAuthError { -} -InvalidTokenError.errorCode = 'invalid_token'; -/** - * Method not allowed error - The HTTP method used is not allowed for this endpoint. - * (Custom, non-standard error) - */ -export class MethodNotAllowedError extends OAuthError { -} -MethodNotAllowedError.errorCode = 'method_not_allowed'; -/** - * Too many requests error - Rate limit exceeded. - * (Custom, non-standard error based on RFC 6585) - */ -export class TooManyRequestsError extends OAuthError { -} -TooManyRequestsError.errorCode = 'too_many_requests'; -/** - * Invalid client metadata error - The client metadata is invalid. - * (Custom error for dynamic client registration - RFC 7591) - */ -export class InvalidClientMetadataError extends OAuthError { -} -InvalidClientMetadataError.errorCode = 'invalid_client_metadata'; -/** - * Insufficient scope error - The request requires higher privileges than provided by the access token. - */ -export class InsufficientScopeError extends OAuthError { -} -InsufficientScopeError.errorCode = 'insufficient_scope'; -/** - * Invalid target error - The requested resource is invalid, missing, unknown, or malformed. - * (Custom error for resource indicators - RFC 8707) - */ -export class InvalidTargetError extends OAuthError { -} -InvalidTargetError.errorCode = 'invalid_target'; -/** - * A utility class for defining one-off error codes - */ -export class CustomOAuthError extends OAuthError { - constructor(customErrorCode, message, errorUri) { - super(message, errorUri); - this.customErrorCode = customErrorCode; - } - get errorCode() { - return this.customErrorCode; - } -} -/** - * A full list of all OAuthErrors, enabling parsing from error responses - */ -export const OAUTH_ERRORS = { - [InvalidRequestError.errorCode]: InvalidRequestError, - [InvalidClientError.errorCode]: InvalidClientError, - [InvalidGrantError.errorCode]: InvalidGrantError, - [UnauthorizedClientError.errorCode]: UnauthorizedClientError, - [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError, - [InvalidScopeError.errorCode]: InvalidScopeError, - [AccessDeniedError.errorCode]: AccessDeniedError, - [ServerError.errorCode]: ServerError, - [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError, - [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError, - [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError, - [InvalidTokenError.errorCode]: InvalidTokenError, - [MethodNotAllowedError.errorCode]: MethodNotAllowedError, - [TooManyRequestsError.errorCode]: TooManyRequestsError, - [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError, - [InsufficientScopeError.errorCode]: InsufficientScopeError, - [InvalidTargetError.errorCode]: InvalidTargetError -}; -//# sourceMappingURL=errors.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js deleted file mode 100644 index 51d060e5..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/index.js +++ /dev/null @@ -1,440 +0,0 @@ -import { mergeCapabilities, Protocol } from '../shared/protocol.js'; -import { CreateMessageResultSchema, CreateMessageResultWithToolsSchema, ElicitResultSchema, EmptyResultSchema, ErrorCode, InitializedNotificationSchema, InitializeRequestSchema, LATEST_PROTOCOL_VERSION, ListRootsResultSchema, LoggingLevelSchema, McpError, SetLevelRequestSchema, SUPPORTED_PROTOCOL_VERSIONS, CallToolRequestSchema, CallToolResultSchema, CreateTaskResultSchema } from '../types.js'; -import { AjvJsonSchemaValidator } from '../validation/ajv-provider.js'; -import { getObjectShape, isZ4Schema, safeParse } from './zod-compat.js'; -import { ExperimentalServerTasks } from '../experimental/tasks/server.js'; -import { assertToolsCallTaskCapability, assertClientRequestTaskCapability } from '../experimental/tasks/helpers.js'; -/** - * An MCP server on top of a pluggable transport. - * - * This server will automatically respond to the initialization flow as initiated from the client. - * - * 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 - * type CustomNotification = z.infer - * type CustomResult = z.infer - * - * // Create typed server - * const server = new Server({ - * name: "CustomServer", - * version: "1.0.0" - * }) - * ``` - * @deprecated Use `McpServer` instead for the high-level API. Only use `Server` for advanced use cases. - */ -export class Server extends Protocol { - /** - * Initializes this server with the given name and version information. - */ - constructor(_serverInfo, options) { - super(options); - this._serverInfo = _serverInfo; - // Map log levels by session id - this._loggingLevels = new Map(); - // Map LogLevelSchema to severity index - this.LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); - // Is a message with the given level ignored in the log level set for the given session id? - this.isMessageIgnored = (level, sessionId) => { - const currentLevel = this._loggingLevels.get(sessionId); - return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; - }; - this._capabilities = options?.capabilities ?? {}; - this._instructions = options?.instructions; - this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); - this.setRequestHandler(InitializeRequestSchema, request => this._oninitialize(request)); - this.setNotificationHandler(InitializedNotificationSchema, () => this.oninitialized?.()); - if (this._capabilities.logging) { - this.setRequestHandler(SetLevelRequestSchema, async (request, extra) => { - const transportSessionId = extra.sessionId || extra.requestInfo?.headers['mcp-session-id'] || undefined; - const { level } = request.params; - const parseResult = LoggingLevelSchema.safeParse(level); - if (parseResult.success) { - this._loggingLevels.set(transportSessionId, parseResult.data); - } - return {}; - }); - } - } - /** - * Access experimental features. - * - * WARNING: These APIs are experimental and may change without notice. - * - * @experimental - */ - get experimental() { - if (!this._experimental) { - this._experimental = { - tasks: new ExperimentalServerTasks(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 server-side validation for tools/call. - */ - 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 === 'tools/call') { - const wrappedHandler = async (request, extra) => { - const validatedRequest = safeParse(CallToolRequestSchema, request); - if (!validatedRequest.success) { - const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error); - throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call 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 CallToolResultSchema - const validationResult = safeParse(CallToolResultSchema, result); - if (!validationResult.success) { - const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error); - throw new McpError(ErrorCode.InvalidParams, `Invalid tools/call result: ${errorMessage}`); - } - return validationResult.data; - }; - // Install the wrapped handler - return super.setRequestHandler(requestSchema, wrappedHandler); - } - // Other handlers use default behavior - return super.setRequestHandler(requestSchema, handler); - } - assertCapabilityForMethod(method) { - switch (method) { - case 'sampling/createMessage': - if (!this._clientCapabilities?.sampling) { - throw new Error(`Client does not support sampling (required for ${method})`); - } - break; - case 'elicitation/create': - if (!this._clientCapabilities?.elicitation) { - throw new Error(`Client does not support elicitation (required for ${method})`); - } - break; - case 'roots/list': - if (!this._clientCapabilities?.roots) { - throw new Error(`Client does not support listing roots (required for ${method})`); - } - break; - case 'ping': - // No specific capability required for ping - break; - } - } - assertNotificationCapability(method) { - switch (method) { - case 'notifications/message': - if (!this._capabilities.logging) { - throw new Error(`Server does not support logging (required for ${method})`); - } - break; - case 'notifications/resources/updated': - case 'notifications/resources/list_changed': - if (!this._capabilities.resources) { - throw new Error(`Server does not support notifying about resources (required for ${method})`); - } - break; - case 'notifications/tools/list_changed': - if (!this._capabilities.tools) { - throw new Error(`Server does not support notifying of tool list changes (required for ${method})`); - } - break; - case 'notifications/prompts/list_changed': - if (!this._capabilities.prompts) { - throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`); - } - break; - case 'notifications/elicitation/complete': - if (!this._clientCapabilities?.elicitation?.url) { - throw new Error(`Client does not support URL elicitation (required for ${method})`); - } - 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 'completion/complete': - if (!this._capabilities.completions) { - throw new Error(`Server does not support completions (required for ${method})`); - } - break; - case 'logging/setLevel': - if (!this._capabilities.logging) { - throw new Error(`Server does not support logging (required for ${method})`); - } - break; - case 'prompts/get': - case 'prompts/list': - if (!this._capabilities.prompts) { - throw new Error(`Server does not support prompts (required for ${method})`); - } - break; - case 'resources/list': - case 'resources/templates/list': - case 'resources/read': - if (!this._capabilities.resources) { - throw new Error(`Server does not support resources (required for ${method})`); - } - break; - case 'tools/call': - case 'tools/list': - if (!this._capabilities.tools) { - throw new Error(`Server does not support tools (required for ${method})`); - } - break; - case 'tasks/get': - case 'tasks/list': - case 'tasks/result': - case 'tasks/cancel': - if (!this._capabilities.tasks) { - throw new Error(`Server does not support tasks capability (required for ${method})`); - } - break; - case 'ping': - case 'initialize': - // No specific capability required for these methods - break; - } - } - assertTaskCapability(method) { - assertClientRequestTaskCapability(this._clientCapabilities?.tasks?.requests, method, 'Client'); - } - 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; - } - assertToolsCallTaskCapability(this._capabilities.tasks?.requests, method, 'Server'); - } - async _oninitialize(request) { - const requestedVersion = request.params.protocolVersion; - this._clientCapabilities = request.params.capabilities; - this._clientVersion = request.params.clientInfo; - const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION; - return { - protocolVersion, - capabilities: this.getCapabilities(), - serverInfo: this._serverInfo, - ...(this._instructions && { instructions: this._instructions }) - }; - } - /** - * After initialization has completed, this will be populated with the client's reported capabilities. - */ - getClientCapabilities() { - return this._clientCapabilities; - } - /** - * After initialization has completed, this will be populated with information about the client's name and version. - */ - getClientVersion() { - return this._clientVersion; - } - getCapabilities() { - return this._capabilities; - } - async ping() { - return this.request({ method: 'ping' }, EmptyResultSchema); - } - // Implementation - async createMessage(params, options) { - // Capability check - only required when tools/toolChoice are provided - if (params.tools || params.toolChoice) { - if (!this._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) { - 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'); - } - } - } - // Use different schemas based on whether tools are provided - if (params.tools) { - return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultWithToolsSchema, options); - } - return this.request({ method: 'sampling/createMessage', params }, CreateMessageResultSchema, options); - } - /** - * Creates an elicitation request for the given parameters. - * For backwards compatibility, `mode` may be omitted for form requests and will default to `'form'`. - * @param params The parameters for the elicitation request. - * @param options Optional request options. - * @returns The result of the elicitation request. - */ - async elicitInput(params, options) { - const mode = (params.mode ?? 'form'); - switch (mode) { - case 'url': { - if (!this._clientCapabilities?.elicitation?.url) { - throw new Error('Client does not support url elicitation.'); - } - const urlParams = params; - return this.request({ method: 'elicitation/create', params: urlParams }, ElicitResultSchema, options); - } - case 'form': { - if (!this._clientCapabilities?.elicitation?.form) { - throw new Error('Client does not support form elicitation.'); - } - const formParams = params.mode === 'form' ? params : { ...params, mode: 'form' }; - const result = await this.request({ method: 'elicitation/create', params: formParams }, ElicitResultSchema, options); - if (result.action === 'accept' && result.content && formParams.requestedSchema) { - try { - const validator = this._jsonSchemaValidator.getValidator(formParams.requestedSchema); - const validationResult = validator(result.content); - if (!validationResult.valid) { - throw new McpError(ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); - } - } - catch (error) { - if (error instanceof McpError) { - throw error; - } - throw new McpError(ErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); - } - } - return result; - } - } - } - /** - * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` - * notification for the specified elicitation ID. - * - * @param elicitationId The ID of the elicitation to mark as complete. - * @param options Optional notification options. Useful when the completion notification should be related to a prior request. - * @returns A function that emits the completion notification when awaited. - */ - createElicitationCompletionNotifier(elicitationId, options) { - if (!this._clientCapabilities?.elicitation?.url) { - throw new Error('Client does not support URL elicitation (required for notifications/elicitation/complete)'); - } - return () => this.notification({ - method: 'notifications/elicitation/complete', - params: { - elicitationId - } - }, options); - } - async listRoots(params, options) { - return this.request({ method: 'roots/list', params }, ListRootsResultSchema, options); - } - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON RPC message - * @see LoggingMessageNotification - * @param params - * @param sessionId optional for stateless and backward compatibility - */ - async sendLoggingMessage(params, sessionId) { - if (this._capabilities.logging) { - if (!this.isMessageIgnored(params.level, sessionId)) { - return this.notification({ method: 'notifications/message', params }); - } - } - } - async sendResourceUpdated(params) { - return this.notification({ - method: 'notifications/resources/updated', - params - }); - } - async sendResourceListChanged() { - return this.notification({ - method: 'notifications/resources/list_changed' - }); - } - async sendToolListChanged() { - return this.notification({ method: 'notifications/tools/list_changed' }); - } - async sendPromptListChanged() { - return this.notification({ method: 'notifications/prompts/list_changed' }); - } -} -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js deleted file mode 100644 index 727fe70a..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/stdio.js +++ /dev/null @@ -1,75 +0,0 @@ -import process from 'node:process'; -import { ReadBuffer, serializeMessage } from '../shared/stdio.js'; -/** - * Server transport for stdio: this communicates with an MCP client by reading from the current process' stdin and writing to stdout. - * - * This transport is only available in Node.js environments. - */ -export class StdioServerTransport { - constructor(_stdin = process.stdin, _stdout = process.stdout) { - this._stdin = _stdin; - this._stdout = _stdout; - this._readBuffer = new ReadBuffer(); - this._started = false; - // Arrow functions to bind `this` properly, while maintaining function identity. - this._ondata = (chunk) => { - this._readBuffer.append(chunk); - this.processReadBuffer(); - }; - this._onerror = (error) => { - this.onerror?.(error); - }; - } - /** - * Starts listening for messages on stdin. - */ - async start() { - if (this._started) { - throw new Error('StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.'); - } - this._started = true; - this._stdin.on('data', this._ondata); - this._stdin.on('error', this._onerror); - } - processReadBuffer() { - while (true) { - try { - const message = this._readBuffer.readMessage(); - if (message === null) { - break; - } - this.onmessage?.(message); - } - catch (error) { - this.onerror?.(error); - } - } - } - async close() { - // Remove our event listeners first - this._stdin.off('data', this._ondata); - this._stdin.off('error', this._onerror); - // Check if we were the only data listener - const remainingDataListeners = this._stdin.listenerCount('data'); - if (remainingDataListeners === 0) { - // Only pause stdin if we were the only listener - // This prevents interfering with other parts of the application that might be using stdin - this._stdin.pause(); - } - // Clear the buffer and notify closure - this._readBuffer.clear(); - this.onclose?.(); - } - send(message) { - return new Promise(resolve => { - const json = serializeMessage(message); - if (this._stdout.write(json)) { - resolve(); - } - else { - this._stdout.once('drain', resolve); - } - }); - } -} -//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js deleted file mode 100644 index be30a223..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js +++ /dev/null @@ -1,209 +0,0 @@ -// zod-compat.ts -// ---------------------------------------------------- -// Unified types + helpers to accept Zod v3 and v4 (Mini) -// ---------------------------------------------------- -import * as z3rt from 'zod/v3'; -import * as z4mini from 'zod/v4-mini'; -// --- Runtime detection --- -export function isZ4Schema(s) { - // Present on Zod 4 (Classic & Mini) schemas; absent on Zod 3 - const schema = s; - return !!schema._zod; -} -// --- Schema construction --- -export function objectFromShape(shape) { - const values = Object.values(shape); - if (values.length === 0) - return z4mini.object({}); // default to v4 Mini - const allV4 = values.every(isZ4Schema); - const allV3 = values.every(s => !isZ4Schema(s)); - if (allV4) - return z4mini.object(shape); - if (allV3) - return z3rt.object(shape); - throw new Error('Mixed Zod versions detected in object shape.'); -} -// --- Unified parsing --- -export function safeParse(schema, data) { - if (isZ4Schema(schema)) { - // Mini exposes top-level safeParse - const result = z4mini.safeParse(schema, data); - return result; - } - const v3Schema = schema; - const result = v3Schema.safeParse(data); - return result; -} -export async function safeParseAsync(schema, data) { - if (isZ4Schema(schema)) { - // Mini exposes top-level safeParseAsync - const result = await z4mini.safeParseAsync(schema, data); - return result; - } - const v3Schema = schema; - const result = await v3Schema.safeParseAsync(data); - return result; -} -// --- Shape extraction --- -export function getObjectShape(schema) { - if (!schema) - return undefined; - // Zod v3 exposes `.shape`; Zod v4 keeps the shape on `_zod.def.shape` - let rawShape; - if (isZ4Schema(schema)) { - const v4Schema = schema; - rawShape = v4Schema._zod?.def?.shape; - } - else { - const v3Schema = schema; - rawShape = v3Schema.shape; - } - if (!rawShape) - return undefined; - if (typeof rawShape === 'function') { - try { - return rawShape(); - } - catch { - return undefined; - } - } - return rawShape; -} -// --- Schema normalization --- -/** - * Normalizes a schema to an object schema. Handles both: - * - Already-constructed object schemas (v3 or v4) - * - Raw shapes that need to be wrapped into object schemas - */ -export function normalizeObjectSchema(schema) { - if (!schema) - return undefined; - // First check if it's a raw shape (Record) - // Raw shapes don't have _def or _zod properties and aren't schemas themselves - if (typeof schema === 'object') { - // Check if it's actually a ZodRawShapeCompat (not a schema instance) - // by checking if it lacks schema-like internal properties - const asV3 = schema; - const asV4 = schema; - // If it's not a schema instance (no _def or _zod), it might be a raw shape - if (!asV3._def && !asV4._zod) { - // Check if all values are schemas (heuristic to confirm it's a raw shape) - const values = Object.values(schema); - if (values.length > 0 && - values.every(v => typeof v === 'object' && - v !== null && - (v._def !== undefined || - v._zod !== undefined || - typeof v.parse === 'function'))) { - return objectFromShape(schema); - } - } - } - // If we get here, it should be an AnySchema (not a raw shape) - // Check if it's already an object schema - if (isZ4Schema(schema)) { - // Check if it's a v4 object - const v4Schema = schema; - const def = v4Schema._zod?.def; - if (def && (def.type === 'object' || def.shape !== undefined)) { - return schema; - } - } - else { - // Check if it's a v3 object - const v3Schema = schema; - if (v3Schema.shape !== undefined) { - return schema; - } - } - return undefined; -} -// --- Error message extraction --- -/** - * Safely extracts an error message from a parse result error. - * Zod errors can have different structures, so we handle various cases. - */ -export function getParseErrorMessage(error) { - if (error && typeof error === 'object') { - // Try common error structures - if ('message' in error && typeof error.message === 'string') { - return error.message; - } - if ('issues' in error && Array.isArray(error.issues) && error.issues.length > 0) { - const firstIssue = error.issues[0]; - if (firstIssue && typeof firstIssue === 'object' && 'message' in firstIssue) { - return String(firstIssue.message); - } - } - // Fallback: try to stringify the error - try { - return JSON.stringify(error); - } - catch { - return String(error); - } - } - return String(error); -} -// --- Schema metadata access --- -/** - * Gets the description from a schema, if available. - * Works with both Zod v3 and v4. - * - * Both versions expose a `.description` getter that returns the description - * from their respective internal storage (v3: _def, v4: globalRegistry). - */ -export function getSchemaDescription(schema) { - return schema.description; -} -/** - * Checks if a schema is optional. - * Works with both Zod v3 and v4. - */ -export function isSchemaOptional(schema) { - if (isZ4Schema(schema)) { - const v4Schema = schema; - return v4Schema._zod?.def?.type === 'optional'; - } - const v3Schema = schema; - // v3 has isOptional() method - if (typeof schema.isOptional === 'function') { - return schema.isOptional(); - } - return v3Schema._def?.typeName === 'ZodOptional'; -} -/** - * Gets the literal value from a schema, if it's a literal schema. - * Works with both Zod v3 and v4. - * Returns undefined if the schema is not a literal or the value cannot be determined. - */ -export function getLiteralValue(schema) { - if (isZ4Schema(schema)) { - const v4Schema = schema; - const def = v4Schema._zod?.def; - if (def) { - // Try various ways to get the literal value - if (def.value !== undefined) - return def.value; - if (Array.isArray(def.values) && def.values.length > 0) { - return def.values[0]; - } - } - } - const v3Schema = schema; - const def = v3Schema._def; - if (def) { - if (def.value !== undefined) - return def.value; - if (Array.isArray(def.values) && def.values.length > 0) { - return def.values[0]; - } - } - // Fallback: check for direct value property (some Zod versions) - const directValue = schema.value; - if (directValue !== undefined) - return directValue; - return undefined; -} -//# sourceMappingURL=zod-compat.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js deleted file mode 100644 index 62f7fd0e..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js +++ /dev/null @@ -1,51 +0,0 @@ -// zod-json-schema-compat.ts -// ---------------------------------------------------- -// JSON Schema conversion for both Zod v3 and Zod v4 (Mini) -// v3 uses your vendored converter; v4 uses Mini's toJSONSchema -// ---------------------------------------------------- -import * as z4mini from 'zod/v4-mini'; -import { getObjectShape, safeParse, isZ4Schema, getLiteralValue } from './zod-compat.js'; -import { zodToJsonSchema } from 'zod-to-json-schema'; -function mapMiniTarget(t) { - if (!t) - return 'draft-7'; - if (t === 'jsonSchema7' || t === 'draft-7') - return 'draft-7'; - if (t === 'jsonSchema2019-09' || t === 'draft-2020-12') - return 'draft-2020-12'; - return 'draft-7'; // fallback -} -export function toJsonSchemaCompat(schema, opts) { - if (isZ4Schema(schema)) { - // v4 branch — use Mini's built-in toJSONSchema - return z4mini.toJSONSchema(schema, { - target: mapMiniTarget(opts?.target), - io: opts?.pipeStrategy ?? 'input' - }); - } - // v3 branch — use vendored converter - return zodToJsonSchema(schema, { - strictUnions: opts?.strictUnions ?? true, - pipeStrategy: opts?.pipeStrategy ?? 'input' - }); -} -export function getMethodLiteral(schema) { - const shape = getObjectShape(schema); - const methodSchema = shape?.method; - if (!methodSchema) { - throw new Error('Schema is missing a method literal'); - } - const value = getLiteralValue(methodSchema); - if (typeof value !== 'string') { - throw new Error('Schema method literal must be a string'); - } - return value; -} -export function parseWithCompat(schema, data) { - const result = safeParse(schema, data); - if (!result.success) { - throw result.error; - } - return result.data; -} -//# sourceMappingURL=zod-json-schema-compat.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js deleted file mode 100644 index 1883885e..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js +++ /dev/null @@ -1,44 +0,0 @@ -/** - * Utilities for handling OAuth resource URIs. - */ -/** - * Converts a server URL to a resource URL by removing the fragment. - * RFC 8707 section 2 states that resource URIs "MUST NOT include a fragment component". - * Keeps everything else unchanged (scheme, domain, port, path, query). - */ -export function resourceUrlFromServerUrl(url) { - const resourceURL = typeof url === 'string' ? new URL(url) : new URL(url.href); - resourceURL.hash = ''; // Remove fragment - return resourceURL; -} -/** - * Checks if a requested resource URL matches a configured resource URL. - * A requested resource matches if it has the same scheme, domain, port, - * and its path starts with the configured resource's path. - * - * @param requestedResource The resource URL being requested - * @param configuredResource The resource URL that has been configured - * @returns true if the requested resource matches the configured resource, false otherwise - */ -export function checkResourceAllowed({ requestedResource, configuredResource }) { - const requested = typeof requestedResource === 'string' ? new URL(requestedResource) : new URL(requestedResource.href); - const configured = typeof configuredResource === 'string' ? new URL(configuredResource) : new URL(configuredResource.href); - // Compare the origin (scheme, domain, and port) - if (requested.origin !== configured.origin) { - return false; - } - // Handle cases like requested=/foo and configured=/foo/ - if (requested.pathname.length < configured.pathname.length) { - return false; - } - // Check if the requested path starts with the configured path - // Ensure both paths end with / for proper comparison - // This ensures that if we have paths like "/api" and "/api/users", - // we properly detect that "/api/users" is a subpath of "/api" - // By adding a trailing slash if missing, we avoid false positives - // where paths like "/api123" would incorrectly match "/api" - const requestedPath = requested.pathname.endsWith('/') ? requested.pathname : requested.pathname + '/'; - const configuredPath = configured.pathname.endsWith('/') ? configured.pathname : configured.pathname + '/'; - return requestedPath.startsWith(configuredPath); -} -//# sourceMappingURL=auth-utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js deleted file mode 100644 index 04f38eb8..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js +++ /dev/null @@ -1,198 +0,0 @@ -import * as z from 'zod/v4'; -/** - * Reusable URL validation that disallows javascript: scheme - */ -export const SafeUrlSchema = z - .url() - .superRefine((val, ctx) => { - if (!URL.canParse(val)) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - message: 'URL must be parseable', - fatal: true - }); - return z.NEVER; - } -}) - .refine(url => { - const u = new URL(url); - return u.protocol !== 'javascript:' && u.protocol !== 'data:' && u.protocol !== 'vbscript:'; -}, { message: 'URL cannot use javascript:, data:, or vbscript: scheme' }); -/** - * RFC 9728 OAuth Protected Resource Metadata - */ -export const OAuthProtectedResourceMetadataSchema = z.looseObject({ - resource: z.string().url(), - authorization_servers: z.array(SafeUrlSchema).optional(), - jwks_uri: z.string().url().optional(), - scopes_supported: z.array(z.string()).optional(), - bearer_methods_supported: z.array(z.string()).optional(), - resource_signing_alg_values_supported: z.array(z.string()).optional(), - resource_name: z.string().optional(), - resource_documentation: z.string().optional(), - resource_policy_uri: z.string().url().optional(), - resource_tos_uri: z.string().url().optional(), - tls_client_certificate_bound_access_tokens: z.boolean().optional(), - authorization_details_types_supported: z.array(z.string()).optional(), - dpop_signing_alg_values_supported: z.array(z.string()).optional(), - dpop_bound_access_tokens_required: z.boolean().optional() -}); -/** - * RFC 8414 OAuth 2.0 Authorization Server Metadata - */ -export const OAuthMetadataSchema = z.looseObject({ - issuer: z.string(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: z.array(z.string()).optional(), - response_types_supported: z.array(z.string()), - response_modes_supported: z.array(z.string()).optional(), - grant_types_supported: z.array(z.string()).optional(), - token_endpoint_auth_methods_supported: z.array(z.string()).optional(), - token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), - service_documentation: SafeUrlSchema.optional(), - revocation_endpoint: SafeUrlSchema.optional(), - revocation_endpoint_auth_methods_supported: z.array(z.string()).optional(), - revocation_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), - introspection_endpoint: z.string().optional(), - introspection_endpoint_auth_methods_supported: z.array(z.string()).optional(), - introspection_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), - code_challenge_methods_supported: z.array(z.string()).optional(), - client_id_metadata_document_supported: z.boolean().optional() -}); -/** - * OpenID Connect Discovery 1.0 Provider Metadata - * see: https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata - */ -export const OpenIdProviderMetadataSchema = z.looseObject({ - issuer: z.string(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - userinfo_endpoint: SafeUrlSchema.optional(), - jwks_uri: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: z.array(z.string()).optional(), - response_types_supported: z.array(z.string()), - response_modes_supported: z.array(z.string()).optional(), - grant_types_supported: z.array(z.string()).optional(), - acr_values_supported: z.array(z.string()).optional(), - subject_types_supported: z.array(z.string()), - id_token_signing_alg_values_supported: z.array(z.string()), - id_token_encryption_alg_values_supported: z.array(z.string()).optional(), - id_token_encryption_enc_values_supported: z.array(z.string()).optional(), - userinfo_signing_alg_values_supported: z.array(z.string()).optional(), - userinfo_encryption_alg_values_supported: z.array(z.string()).optional(), - userinfo_encryption_enc_values_supported: z.array(z.string()).optional(), - request_object_signing_alg_values_supported: z.array(z.string()).optional(), - request_object_encryption_alg_values_supported: z.array(z.string()).optional(), - request_object_encryption_enc_values_supported: z.array(z.string()).optional(), - token_endpoint_auth_methods_supported: z.array(z.string()).optional(), - token_endpoint_auth_signing_alg_values_supported: z.array(z.string()).optional(), - display_values_supported: z.array(z.string()).optional(), - claim_types_supported: z.array(z.string()).optional(), - claims_supported: z.array(z.string()).optional(), - service_documentation: z.string().optional(), - claims_locales_supported: z.array(z.string()).optional(), - ui_locales_supported: z.array(z.string()).optional(), - claims_parameter_supported: z.boolean().optional(), - request_parameter_supported: z.boolean().optional(), - request_uri_parameter_supported: z.boolean().optional(), - require_request_uri_registration: z.boolean().optional(), - op_policy_uri: SafeUrlSchema.optional(), - op_tos_uri: SafeUrlSchema.optional(), - client_id_metadata_document_supported: z.boolean().optional() -}); -/** - * OpenID Connect Discovery metadata that may include OAuth 2.0 fields - * This schema represents the real-world scenario where OIDC providers - * return a mix of OpenID Connect and OAuth 2.0 metadata fields - */ -export const OpenIdProviderDiscoveryMetadataSchema = z.object({ - ...OpenIdProviderMetadataSchema.shape, - ...OAuthMetadataSchema.pick({ - code_challenge_methods_supported: true - }).shape -}); -/** - * OAuth 2.1 token response - */ -export const OAuthTokensSchema = z - .object({ - access_token: z.string(), - id_token: z.string().optional(), // Optional for OAuth 2.1, but necessary in OpenID Connect - token_type: z.string(), - expires_in: z.coerce.number().optional(), - scope: z.string().optional(), - refresh_token: z.string().optional() -}) - .strip(); -/** - * OAuth 2.1 error response - */ -export const OAuthErrorResponseSchema = z.object({ - error: z.string(), - error_description: z.string().optional(), - error_uri: z.string().optional() -}); -/** - * Optional version of SafeUrlSchema that allows empty string for retrocompatibility on tos_uri and logo_uri - */ -export const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(z.literal('').transform(() => undefined)); -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration metadata - */ -export const OAuthClientMetadataSchema = z - .object({ - redirect_uris: z.array(SafeUrlSchema), - token_endpoint_auth_method: z.string().optional(), - grant_types: z.array(z.string()).optional(), - response_types: z.array(z.string()).optional(), - client_name: z.string().optional(), - client_uri: SafeUrlSchema.optional(), - logo_uri: OptionalSafeUrlSchema, - scope: z.string().optional(), - contacts: z.array(z.string()).optional(), - tos_uri: OptionalSafeUrlSchema, - policy_uri: z.string().optional(), - jwks_uri: SafeUrlSchema.optional(), - jwks: z.any().optional(), - software_id: z.string().optional(), - software_version: z.string().optional(), - software_statement: z.string().optional() -}) - .strip(); -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration client information - */ -export const OAuthClientInformationSchema = z - .object({ - client_id: z.string(), - client_secret: z.string().optional(), - client_id_issued_at: z.number().optional(), - client_secret_expires_at: z.number().optional() -}) - .strip(); -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) - */ -export const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); -/** - * RFC 7591 OAuth 2.0 Dynamic Client Registration error response - */ -export const OAuthClientRegistrationErrorSchema = z - .object({ - error: z.string(), - error_description: z.string().optional() -}) - .strip(); -/** - * RFC 7009 OAuth 2.0 Token Revocation request - */ -export const OAuthTokenRevocationRequestSchema = z - .object({ - token: z.string(), - token_type_hint: z.string().optional() -}) - .strip(); -//# sourceMappingURL=auth.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js deleted file mode 100644 index 5740ba10..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js +++ /dev/null @@ -1,1099 +0,0 @@ -import { safeParse } from '../server/zod-compat.js'; -import { CancelledNotificationSchema, CreateTaskResultSchema, ErrorCode, GetTaskRequestSchema, GetTaskResultSchema, GetTaskPayloadRequestSchema, ListTasksRequestSchema, ListTasksResultSchema, CancelTaskRequestSchema, CancelTaskResultSchema, isJSONRPCErrorResponse, isJSONRPCRequest, isJSONRPCResultResponse, isJSONRPCNotification, McpError, PingRequestSchema, ProgressNotificationSchema, RELATED_TASK_META_KEY, TaskStatusNotificationSchema, isTaskAugmentedRequestParams } from '../types.js'; -import { isTerminal } from '../experimental/tasks/interfaces.js'; -import { getMethodLiteral, parseWithCompat } from '../server/zod-json-schema-compat.js'; -/** - * The default request timeout, in miliseconds. - */ -export const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000; -/** - * Implements MCP protocol framing on top of a pluggable transport, including - * features like request/response linking, notifications, and progress. - */ -export class Protocol { - constructor(_options) { - this._options = _options; - this._requestMessageId = 0; - this._requestHandlers = new Map(); - this._requestHandlerAbortControllers = new Map(); - this._notificationHandlers = new Map(); - this._responseHandlers = new Map(); - this._progressHandlers = new Map(); - this._timeoutInfo = new Map(); - this._pendingDebouncedNotifications = new Set(); - // Maps task IDs to progress tokens to keep handlers alive after CreateTaskResult - this._taskProgressTokens = new Map(); - this._requestResolvers = new Map(); - this.setNotificationHandler(CancelledNotificationSchema, notification => { - this._oncancel(notification); - }); - this.setNotificationHandler(ProgressNotificationSchema, notification => { - this._onprogress(notification); - }); - this.setRequestHandler(PingRequestSchema, - // Automatic pong by default. - _request => ({})); - // Install task handlers if TaskStore is provided - this._taskStore = _options?.taskStore; - this._taskMessageQueue = _options?.taskMessageQueue; - if (this._taskStore) { - this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => { - const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); - if (!task) { - throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found'); - } - // Per spec: tasks/get responses SHALL NOT include related-task metadata - // as the taskId parameter is the source of truth - // @ts-expect-error SendResultT cannot contain GetTaskResult, but we include it in our derived types everywhere else - return { - ...task - }; - }); - this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => { - const handleTaskResult = async () => { - const taskId = request.params.taskId; - // Deliver queued messages - if (this._taskMessageQueue) { - let queuedMessage; - while ((queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId))) { - // Handle response and error messages by routing them to the appropriate resolver - if (queuedMessage.type === 'response' || queuedMessage.type === 'error') { - const message = queuedMessage.message; - const requestId = message.id; - // Lookup resolver in _requestResolvers map - const resolver = this._requestResolvers.get(requestId); - if (resolver) { - // Remove resolver from map after invocation - this._requestResolvers.delete(requestId); - // Invoke resolver with response or error - if (queuedMessage.type === 'response') { - resolver(message); - } - else { - // Convert JSONRPCError to McpError - const errorMessage = message; - const error = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data); - resolver(error); - } - } - else { - // Handle missing resolver gracefully with error logging - const messageType = queuedMessage.type === 'response' ? 'Response' : 'Error'; - this._onerror(new Error(`${messageType} handler missing for request ${requestId}`)); - } - // Continue to next message - continue; - } - // Send the message on the response stream by passing the relatedRequestId - // This tells the transport to write the message to the tasks/result response stream - await this._transport?.send(queuedMessage.message, { relatedRequestId: extra.requestId }); - } - } - // Now check task status - const task = await this._taskStore.getTask(taskId, extra.sessionId); - if (!task) { - throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`); - } - // Block if task is not terminal (we've already delivered all queued messages above) - if (!isTerminal(task.status)) { - // Wait for status change or new messages - await this._waitForTaskUpdate(taskId, extra.signal); - // After waking up, recursively call to deliver any new messages or result - return await handleTaskResult(); - } - // If task is terminal, return the result - if (isTerminal(task.status)) { - const result = await this._taskStore.getTaskResult(taskId, extra.sessionId); - this._clearTaskQueue(taskId); - return { - ...result, - _meta: { - ...result._meta, - [RELATED_TASK_META_KEY]: { - taskId: taskId - } - } - }; - } - return await handleTaskResult(); - }; - return await handleTaskResult(); - }); - this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => { - try { - const { tasks, nextCursor } = await this._taskStore.listTasks(request.params?.cursor, extra.sessionId); - // @ts-expect-error SendResultT cannot contain ListTasksResult, but we include it in our derived types everywhere else - return { - tasks, - nextCursor, - _meta: {} - }; - } - catch (error) { - throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error instanceof Error ? error.message : String(error)}`); - } - }); - this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => { - try { - // Get the current task to check if it's in a terminal state, in case the implementation is not atomic - const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId); - if (!task) { - throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`); - } - // Reject cancellation of terminal tasks - if (isTerminal(task.status)) { - throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`); - } - await this._taskStore.updateTaskStatus(request.params.taskId, 'cancelled', 'Client cancelled task execution.', extra.sessionId); - this._clearTaskQueue(request.params.taskId); - const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId); - if (!cancelledTask) { - // Task was deleted during cancellation (e.g., cleanup happened) - throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`); - } - return { - _meta: {}, - ...cancelledTask - }; - } - catch (error) { - // Re-throw McpError as-is - if (error instanceof McpError) { - throw error; - } - throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error instanceof Error ? error.message : String(error)}`); - } - }); - } - } - async _oncancel(notification) { - if (!notification.params.requestId) { - return; - } - // Handle request cancellation - const controller = this._requestHandlerAbortControllers.get(notification.params.requestId); - controller?.abort(notification.params.reason); - } - _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { - this._timeoutInfo.set(messageId, { - timeoutId: setTimeout(onTimeout, timeout), - startTime: Date.now(), - timeout, - maxTotalTimeout, - resetTimeoutOnProgress, - onTimeout - }); - } - _resetTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (!info) - return false; - const totalElapsed = Date.now() - info.startTime; - if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { - this._timeoutInfo.delete(messageId); - throw McpError.fromError(ErrorCode.RequestTimeout, 'Maximum total timeout exceeded', { - maxTotalTimeout: info.maxTotalTimeout, - totalElapsed - }); - } - clearTimeout(info.timeoutId); - info.timeoutId = setTimeout(info.onTimeout, info.timeout); - return true; - } - _cleanupTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (info) { - clearTimeout(info.timeoutId); - this._timeoutInfo.delete(messageId); - } - } - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward. - */ - async connect(transport) { - if (this._transport) { - throw new Error('Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.'); - } - this._transport = transport; - const _onclose = this.transport?.onclose; - this._transport.onclose = () => { - _onclose?.(); - this._onclose(); - }; - const _onerror = this.transport?.onerror; - this._transport.onerror = (error) => { - _onerror?.(error); - this._onerror(error); - }; - const _onmessage = this._transport?.onmessage; - this._transport.onmessage = (message, extra) => { - _onmessage?.(message, extra); - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { - this._onresponse(message); - } - else if (isJSONRPCRequest(message)) { - this._onrequest(message, extra); - } - else if (isJSONRPCNotification(message)) { - this._onnotification(message); - } - else { - this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`)); - } - }; - await this._transport.start(); - } - _onclose() { - const responseHandlers = this._responseHandlers; - this._responseHandlers = new Map(); - this._progressHandlers.clear(); - this._taskProgressTokens.clear(); - this._pendingDebouncedNotifications.clear(); - // Abort all in-flight request handlers so they stop sending messages - for (const controller of this._requestHandlerAbortControllers.values()) { - controller.abort(); - } - this._requestHandlerAbortControllers.clear(); - const error = McpError.fromError(ErrorCode.ConnectionClosed, 'Connection closed'); - this._transport = undefined; - this.onclose?.(); - for (const handler of responseHandlers.values()) { - handler(error); - } - } - _onerror(error) { - this.onerror?.(error); - } - _onnotification(notification) { - const handler = this._notificationHandlers.get(notification.method) ?? this.fallbackNotificationHandler; - // Ignore notifications not being subscribed to. - if (handler === undefined) { - return; - } - // Starting with Promise.resolve() puts any synchronous errors into the monad as well. - Promise.resolve() - .then(() => handler(notification)) - .catch(error => this._onerror(new Error(`Uncaught error in notification handler: ${error}`))); - } - _onrequest(request, extra) { - const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; - // Capture the current transport at request time to ensure responses go to the correct client - const capturedTransport = this._transport; - // Extract taskId from request metadata if present (needed early for method not found case) - const relatedTaskId = request.params?._meta?.[RELATED_TASK_META_KEY]?.taskId; - if (handler === undefined) { - const errorResponse = { - jsonrpc: '2.0', - id: request.id, - error: { - code: ErrorCode.MethodNotFound, - message: 'Method not found' - } - }; - // Queue or send the error response based on whether this is a task-related request - if (relatedTaskId && this._taskMessageQueue) { - this._enqueueTaskMessage(relatedTaskId, { - type: 'error', - message: errorResponse, - timestamp: Date.now() - }, capturedTransport?.sessionId).catch(error => this._onerror(new Error(`Failed to enqueue error response: ${error}`))); - } - else { - capturedTransport - ?.send(errorResponse) - .catch(error => this._onerror(new Error(`Failed to send an error response: ${error}`))); - } - return; - } - const abortController = new AbortController(); - this._requestHandlerAbortControllers.set(request.id, abortController); - const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : undefined; - const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport?.sessionId) : undefined; - const fullExtra = { - signal: abortController.signal, - sessionId: capturedTransport?.sessionId, - _meta: request.params?._meta, - sendNotification: async (notification) => { - if (abortController.signal.aborted) - return; - // Include related-task metadata if this request is part of a task - const notificationOptions = { relatedRequestId: request.id }; - if (relatedTaskId) { - notificationOptions.relatedTask = { taskId: relatedTaskId }; - } - await this.notification(notification, notificationOptions); - }, - sendRequest: async (r, resultSchema, options) => { - if (abortController.signal.aborted) { - throw new McpError(ErrorCode.ConnectionClosed, 'Request was cancelled'); - } - // Include related-task metadata if this request is part of a task - const requestOptions = { ...options, relatedRequestId: request.id }; - if (relatedTaskId && !requestOptions.relatedTask) { - requestOptions.relatedTask = { taskId: relatedTaskId }; - } - // Set task status to input_required when sending a request within a task context - // Use the taskId from options (explicit) or fall back to relatedTaskId (inherited) - const effectiveTaskId = requestOptions.relatedTask?.taskId ?? relatedTaskId; - if (effectiveTaskId && taskStore) { - await taskStore.updateTaskStatus(effectiveTaskId, 'input_required'); - } - return await this.request(r, resultSchema, requestOptions); - }, - authInfo: extra?.authInfo, - requestId: request.id, - requestInfo: extra?.requestInfo, - taskId: relatedTaskId, - taskStore: taskStore, - taskRequestedTtl: taskCreationParams?.ttl, - closeSSEStream: extra?.closeSSEStream, - closeStandaloneSSEStream: extra?.closeStandaloneSSEStream - }; - // Starting with Promise.resolve() puts any synchronous errors into the monad as well. - Promise.resolve() - .then(() => { - // If this request asked for task creation, check capability first - if (taskCreationParams) { - // Check if the request method supports task creation - this.assertTaskHandlerCapability(request.method); - } - }) - .then(() => handler(request, fullExtra)) - .then(async (result) => { - if (abortController.signal.aborted) { - // Request was cancelled - return; - } - const response = { - result, - jsonrpc: '2.0', - id: request.id - }; - // Queue or send the response based on whether this is a task-related request - if (relatedTaskId && this._taskMessageQueue) { - await this._enqueueTaskMessage(relatedTaskId, { - type: 'response', - message: response, - timestamp: Date.now() - }, capturedTransport?.sessionId); - } - else { - await capturedTransport?.send(response); - } - }, async (error) => { - if (abortController.signal.aborted) { - // Request was cancelled - return; - } - const errorResponse = { - jsonrpc: '2.0', - id: request.id, - error: { - code: Number.isSafeInteger(error['code']) ? error['code'] : ErrorCode.InternalError, - message: error.message ?? 'Internal error', - ...(error['data'] !== undefined && { data: error['data'] }) - } - }; - // Queue or send the error response based on whether this is a task-related request - if (relatedTaskId && this._taskMessageQueue) { - await this._enqueueTaskMessage(relatedTaskId, { - type: 'error', - message: errorResponse, - timestamp: Date.now() - }, capturedTransport?.sessionId); - } - else { - await capturedTransport?.send(errorResponse); - } - }) - .catch(error => this._onerror(new Error(`Failed to send response: ${error}`))) - .finally(() => { - this._requestHandlerAbortControllers.delete(request.id); - }); - } - _onprogress(notification) { - const { progressToken, ...params } = notification.params; - const messageId = Number(progressToken); - const handler = this._progressHandlers.get(messageId); - if (!handler) { - this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); - return; - } - const responseHandler = this._responseHandlers.get(messageId); - const timeoutInfo = this._timeoutInfo.get(messageId); - if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) { - try { - this._resetTimeout(messageId); - } - catch (error) { - // Clean up if maxTotalTimeout was exceeded - this._responseHandlers.delete(messageId); - this._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - responseHandler(error); - return; - } - } - handler(params); - } - _onresponse(response) { - const messageId = Number(response.id); - // Check if this is a response to a queued request - const resolver = this._requestResolvers.get(messageId); - if (resolver) { - this._requestResolvers.delete(messageId); - if (isJSONRPCResultResponse(response)) { - resolver(response); - } - else { - const error = new McpError(response.error.code, response.error.message, response.error.data); - resolver(error); - } - return; - } - const handler = this._responseHandlers.get(messageId); - if (handler === undefined) { - this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); - return; - } - this._responseHandlers.delete(messageId); - this._cleanupTimeout(messageId); - // Keep progress handler alive for CreateTaskResult responses - let isTaskResponse = false; - if (isJSONRPCResultResponse(response) && response.result && typeof response.result === 'object') { - const result = response.result; - if (result.task && typeof result.task === 'object') { - const task = result.task; - if (typeof task.taskId === 'string') { - isTaskResponse = true; - this._taskProgressTokens.set(task.taskId, messageId); - } - } - } - if (!isTaskResponse) { - this._progressHandlers.delete(messageId); - } - if (isJSONRPCResultResponse(response)) { - handler(response); - } - else { - const error = McpError.fromError(response.error.code, response.error.message, response.error.data); - handler(error); - } - } - get transport() { - return this._transport; - } - /** - * Closes the connection. - */ - async close() { - await this._transport?.close(); - } - /** - * Sends a request and returns an AsyncGenerator that yields response messages. - * The generator is guaranteed to end with either a 'result' or 'error' message. - * - * @example - * ```typescript - * const stream = protocol.requestStream(request, resultSchema, options); - * 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; - * } - * } - * ``` - * - * @experimental Use `client.experimental.tasks.requestStream()` to access this method. - */ - async *requestStream(request, resultSchema, options) { - const { task } = options ?? {}; - // For non-task requests, just yield the result - if (!task) { - try { - const result = await this.request(request, resultSchema, options); - yield { type: 'result', result }; - } - catch (error) { - yield { - type: 'error', - error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error)) - }; - } - return; - } - // For task-augmented requests, we need to poll for status - // First, make the request to create the task - let taskId; - try { - // Send the request and get the CreateTaskResult - const createResult = await this.request(request, CreateTaskResultSchema, options); - // Extract taskId from the result - if (createResult.task) { - taskId = createResult.task.taskId; - yield { type: 'taskCreated', task: createResult.task }; - } - else { - throw new McpError(ErrorCode.InternalError, 'Task creation did not return a task'); - } - // Poll for task completion - while (true) { - // Get current task status - const task = await this.getTask({ taskId }, options); - yield { type: 'taskStatus', task }; - // Check if task is terminal - if (isTerminal(task.status)) { - if (task.status === 'completed') { - // Get the final result - const result = await this.getTaskResult({ taskId }, resultSchema, options); - yield { type: 'result', result }; - } - else if (task.status === 'failed') { - yield { - type: 'error', - error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`) - }; - } - else if (task.status === 'cancelled') { - yield { - type: 'error', - error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`) - }; - } - return; - } - // When input_required, call tasks/result to deliver queued messages - // (elicitation, sampling) via SSE and block until terminal - if (task.status === 'input_required') { - const result = await this.getTaskResult({ taskId }, resultSchema, options); - yield { type: 'result', result }; - return; - } - // Wait before polling again - const pollInterval = task.pollInterval ?? this._options?.defaultTaskPollInterval ?? 1000; - await new Promise(resolve => setTimeout(resolve, pollInterval)); - // Check if cancelled - options?.signal?.throwIfAborted(); - } - } - catch (error) { - yield { - type: 'error', - error: error instanceof McpError ? error : new McpError(ErrorCode.InternalError, String(error)) - }; - } - } - /** - * Sends a request and waits for a response. - * - * Do not use this method to emit notifications! Use notification() instead. - */ - request(request, resultSchema, options) { - const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options ?? {}; - // Send the request - return new Promise((resolve, reject) => { - const earlyReject = (error) => { - reject(error); - }; - if (!this._transport) { - earlyReject(new Error('Not connected')); - return; - } - if (this._options?.enforceStrictCapabilities === true) { - try { - this.assertCapabilityForMethod(request.method); - // If task creation is requested, also check task capabilities - if (task) { - this.assertTaskCapability(request.method); - } - } - catch (e) { - earlyReject(e); - return; - } - } - options?.signal?.throwIfAborted(); - const messageId = this._requestMessageId++; - const jsonrpcRequest = { - ...request, - jsonrpc: '2.0', - id: messageId - }; - if (options?.onprogress) { - this._progressHandlers.set(messageId, options.onprogress); - jsonrpcRequest.params = { - ...request.params, - _meta: { - ...(request.params?._meta || {}), - progressToken: messageId - } - }; - } - // Augment with task creation parameters if provided - if (task) { - jsonrpcRequest.params = { - ...jsonrpcRequest.params, - task: task - }; - } - // Augment with related task metadata if relatedTask is provided - if (relatedTask) { - jsonrpcRequest.params = { - ...jsonrpcRequest.params, - _meta: { - ...(jsonrpcRequest.params?._meta || {}), - [RELATED_TASK_META_KEY]: relatedTask - } - }; - } - const cancel = (reason) => { - this._responseHandlers.delete(messageId); - this._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - this._transport - ?.send({ - jsonrpc: '2.0', - method: 'notifications/cancelled', - params: { - requestId: messageId, - reason: String(reason) - } - }, { relatedRequestId, resumptionToken, onresumptiontoken }) - .catch(error => this._onerror(new Error(`Failed to send cancellation: ${error}`))); - // Wrap the reason in an McpError if it isn't already - const error = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason)); - reject(error); - }; - this._responseHandlers.set(messageId, response => { - if (options?.signal?.aborted) { - return; - } - if (response instanceof Error) { - return reject(response); - } - try { - const parseResult = safeParse(resultSchema, response.result); - if (!parseResult.success) { - // Type guard: if success is false, error is guaranteed to exist - reject(parseResult.error); - } - else { - resolve(parseResult.data); - } - } - catch (error) { - reject(error); - } - }); - options?.signal?.addEventListener('abort', () => { - cancel(options?.signal?.reason); - }); - const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; - const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, 'Request timed out', { timeout })); - this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); - // Queue request if related to a task - const relatedTaskId = relatedTask?.taskId; - if (relatedTaskId) { - // Store the response resolver for this request so responses can be routed back - const responseResolver = (response) => { - const handler = this._responseHandlers.get(messageId); - if (handler) { - handler(response); - } - else { - // Log error when resolver is missing, but don't fail - this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`)); - } - }; - this._requestResolvers.set(messageId, responseResolver); - this._enqueueTaskMessage(relatedTaskId, { - type: 'request', - message: jsonrpcRequest, - timestamp: Date.now() - }).catch(error => { - this._cleanupTimeout(messageId); - reject(error); - }); - // Don't send through transport - queued messages are delivered via tasks/result only - // This prevents duplicate delivery for bidirectional transports - } - else { - // No related task - send through transport normally - this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch(error => { - this._cleanupTimeout(messageId); - reject(error); - }); - } - }); - } - /** - * Gets the current status of a task. - * - * @experimental Use `client.experimental.tasks.getTask()` to access this method. - */ - async getTask(params, options) { - // @ts-expect-error SendRequestT cannot directly contain GetTaskRequest, but we ensure all type instantiations contain it anyways - return this.request({ method: 'tasks/get', params }, GetTaskResultSchema, options); - } - /** - * Retrieves the result of a completed task. - * - * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method. - */ - async getTaskResult(params, resultSchema, options) { - // @ts-expect-error SendRequestT cannot directly contain GetTaskPayloadRequest, but we ensure all type instantiations contain it anyways - return this.request({ method: 'tasks/result', params }, resultSchema, options); - } - /** - * Lists tasks, optionally starting from a pagination cursor. - * - * @experimental Use `client.experimental.tasks.listTasks()` to access this method. - */ - async listTasks(params, options) { - // @ts-expect-error SendRequestT cannot directly contain ListTasksRequest, but we ensure all type instantiations contain it anyways - return this.request({ method: 'tasks/list', params }, ListTasksResultSchema, options); - } - /** - * Cancels a specific task. - * - * @experimental Use `client.experimental.tasks.cancelTask()` to access this method. - */ - async cancelTask(params, options) { - // @ts-expect-error SendRequestT cannot directly contain CancelTaskRequest, but we ensure all type instantiations contain it anyways - return this.request({ method: 'tasks/cancel', params }, CancelTaskResultSchema, options); - } - /** - * Emits a notification, which is a one-way message that does not expect a response. - */ - async notification(notification, options) { - if (!this._transport) { - throw new Error('Not connected'); - } - this.assertNotificationCapability(notification.method); - // Queue notification if related to a task - const relatedTaskId = options?.relatedTask?.taskId; - if (relatedTaskId) { - // Build the JSONRPC notification with metadata - const jsonrpcNotification = { - ...notification, - jsonrpc: '2.0', - params: { - ...notification.params, - _meta: { - ...(notification.params?._meta || {}), - [RELATED_TASK_META_KEY]: options.relatedTask - } - } - }; - await this._enqueueTaskMessage(relatedTaskId, { - type: 'notification', - message: jsonrpcNotification, - timestamp: Date.now() - }); - // Don't send through transport - queued messages are delivered via tasks/result only - // This prevents duplicate delivery for bidirectional transports - return; - } - const debouncedMethods = this._options?.debouncedNotificationMethods ?? []; - // A notification can only be debounced if it's in the list AND it's "simple" - // (i.e., has no parameters and no related request ID or related task that could be lost). - const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !options?.relatedRequestId && !options?.relatedTask; - if (canDebounce) { - // If a notification of this type is already scheduled, do nothing. - if (this._pendingDebouncedNotifications.has(notification.method)) { - return; - } - // Mark this notification type as pending. - this._pendingDebouncedNotifications.add(notification.method); - // Schedule the actual send to happen in the next microtask. - // This allows all synchronous calls in the current event loop tick to be coalesced. - Promise.resolve().then(() => { - // Un-mark the notification so the next one can be scheduled. - this._pendingDebouncedNotifications.delete(notification.method); - // SAFETY CHECK: If the connection was closed while this was pending, abort. - if (!this._transport) { - return; - } - let jsonrpcNotification = { - ...notification, - jsonrpc: '2.0' - }; - // Augment with related task metadata if relatedTask is provided - if (options?.relatedTask) { - jsonrpcNotification = { - ...jsonrpcNotification, - params: { - ...jsonrpcNotification.params, - _meta: { - ...(jsonrpcNotification.params?._meta || {}), - [RELATED_TASK_META_KEY]: options.relatedTask - } - } - }; - } - // Send the notification, but don't await it here to avoid blocking. - // Handle potential errors with a .catch(). - this._transport?.send(jsonrpcNotification, options).catch(error => this._onerror(error)); - }); - // Return immediately. - return; - } - let jsonrpcNotification = { - ...notification, - jsonrpc: '2.0' - }; - // Augment with related task metadata if relatedTask is provided - if (options?.relatedTask) { - jsonrpcNotification = { - ...jsonrpcNotification, - params: { - ...jsonrpcNotification.params, - _meta: { - ...(jsonrpcNotification.params?._meta || {}), - [RELATED_TASK_META_KEY]: options.relatedTask - } - } - }; - } - await this._transport.send(jsonrpcNotification, options); - } - /** - * Registers a handler to invoke when this protocol object receives a request with the given method. - * - * Note that this will replace any previous request handler for the same method. - */ - setRequestHandler(requestSchema, handler) { - const method = getMethodLiteral(requestSchema); - this.assertRequestHandlerCapability(method); - this._requestHandlers.set(method, (request, extra) => { - const parsed = parseWithCompat(requestSchema, request); - return Promise.resolve(handler(parsed, extra)); - }); - } - /** - * Removes the request handler for the given method. - */ - removeRequestHandler(method) { - this._requestHandlers.delete(method); - } - /** - * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. - */ - assertCanSetRequestHandler(method) { - if (this._requestHandlers.has(method)) { - throw new Error(`A request handler for ${method} already exists, which would be overridden`); - } - } - /** - * Registers a handler to invoke when this protocol object receives a notification with the given method. - * - * Note that this will replace any previous notification handler for the same method. - */ - setNotificationHandler(notificationSchema, handler) { - const method = getMethodLiteral(notificationSchema); - this._notificationHandlers.set(method, notification => { - const parsed = parseWithCompat(notificationSchema, notification); - return Promise.resolve(handler(parsed)); - }); - } - /** - * Removes the notification handler for the given method. - */ - removeNotificationHandler(method) { - this._notificationHandlers.delete(method); - } - /** - * Cleans up the progress handler associated with a task. - * This should be called when a task reaches a terminal status. - */ - _cleanupTaskProgressHandler(taskId) { - const progressToken = this._taskProgressTokens.get(taskId); - if (progressToken !== undefined) { - this._progressHandlers.delete(progressToken); - this._taskProgressTokens.delete(taskId); - } - } - /** - * Enqueues a task-related message for side-channel delivery via tasks/result. - * @param taskId The task ID to associate the message with - * @param message The message to enqueue - * @param sessionId Optional session ID for binding the operation to a specific session - * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow) - * - * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle - * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer - * simply propagates the error. - */ - async _enqueueTaskMessage(taskId, message, sessionId) { - // Task message queues are only used when taskStore is configured - if (!this._taskStore || !this._taskMessageQueue) { - throw new Error('Cannot enqueue task message: taskStore and taskMessageQueue are not configured'); - } - const maxQueueSize = this._options?.maxTaskQueueSize; - await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize); - } - /** - * Clears the message queue for a task and rejects any pending request resolvers. - * @param taskId The task ID whose queue should be cleared - * @param sessionId Optional session ID for binding the operation to a specific session - */ - async _clearTaskQueue(taskId, sessionId) { - if (this._taskMessageQueue) { - // Reject any pending request resolvers - const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId); - for (const message of messages) { - if (message.type === 'request' && isJSONRPCRequest(message.message)) { - // Extract request ID from the message - const requestId = message.message.id; - const resolver = this._requestResolvers.get(requestId); - if (resolver) { - resolver(new McpError(ErrorCode.InternalError, 'Task cancelled or completed')); - this._requestResolvers.delete(requestId); - } - else { - // Log error when resolver is missing during cleanup for better observability - this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`)); - } - } - } - } - } - /** - * Waits for a task update (new messages or status change) with abort signal support. - * Uses polling to check for updates at the task's configured poll interval. - * @param taskId The task ID to wait for - * @param signal Abort signal to cancel the wait - * @returns Promise that resolves when an update occurs or rejects if aborted - */ - async _waitForTaskUpdate(taskId, signal) { - // Get the task's poll interval, falling back to default - let interval = this._options?.defaultTaskPollInterval ?? 1000; - try { - const task = await this._taskStore?.getTask(taskId); - if (task?.pollInterval) { - interval = task.pollInterval; - } - } - catch { - // Use default interval if task lookup fails - } - return new Promise((resolve, reject) => { - if (signal.aborted) { - reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled')); - return; - } - // Wait for the poll interval, then resolve so caller can check for updates - const timeoutId = setTimeout(resolve, interval); - // Clean up timeout and reject if aborted - signal.addEventListener('abort', () => { - clearTimeout(timeoutId); - reject(new McpError(ErrorCode.InvalidRequest, 'Request cancelled')); - }, { once: true }); - }); - } - requestTaskStore(request, sessionId) { - const taskStore = this._taskStore; - if (!taskStore) { - throw new Error('No task store configured'); - } - return { - createTask: async (taskParams) => { - if (!request) { - throw new Error('No request provided'); - } - return await taskStore.createTask(taskParams, request.id, { - method: request.method, - params: request.params - }, sessionId); - }, - getTask: async (taskId) => { - const task = await taskStore.getTask(taskId, sessionId); - if (!task) { - throw new McpError(ErrorCode.InvalidParams, 'Failed to retrieve task: Task not found'); - } - return task; - }, - storeTaskResult: async (taskId, status, result) => { - await taskStore.storeTaskResult(taskId, status, result, sessionId); - // Get updated task state and send notification - const task = await taskStore.getTask(taskId, sessionId); - if (task) { - const notification = TaskStatusNotificationSchema.parse({ - method: 'notifications/tasks/status', - params: task - }); - await this.notification(notification); - if (isTerminal(task.status)) { - this._cleanupTaskProgressHandler(taskId); - // Don't clear queue here - it will be cleared after delivery via tasks/result - } - } - }, - getTaskResult: taskId => { - return taskStore.getTaskResult(taskId, sessionId); - }, - updateTaskStatus: async (taskId, status, statusMessage) => { - // Check if task exists - const task = await taskStore.getTask(taskId, sessionId); - if (!task) { - throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`); - } - // Don't allow transitions from terminal states - if (isTerminal(task.status)) { - throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`); - } - await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId); - // Get updated task state and send notification - const updatedTask = await taskStore.getTask(taskId, sessionId); - if (updatedTask) { - const notification = TaskStatusNotificationSchema.parse({ - method: 'notifications/tasks/status', - params: updatedTask - }); - await this.notification(notification); - if (isTerminal(updatedTask.status)) { - this._cleanupTaskProgressHandler(taskId); - // Don't clear queue here - it will be cleared after delivery via tasks/result - } - } - }, - listTasks: cursor => { - return taskStore.listTasks(cursor, sessionId); - } - }; - } -} -function isPlainObject(value) { - return value !== null && typeof value === 'object' && !Array.isArray(value); -} -export function mergeCapabilities(base, additional) { - const result = { ...base }; - for (const key in additional) { - const k = key; - const addValue = additional[k]; - if (addValue === undefined) - continue; - const baseValue = result[k]; - if (isPlainObject(baseValue) && isPlainObject(addValue)) { - result[k] = { ...baseValue, ...addValue }; - } - else { - result[k] = addValue; - } - } - return result; -} -//# sourceMappingURL=protocol.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js deleted file mode 100644 index 30f299f5..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js +++ /dev/null @@ -1,31 +0,0 @@ -import { JSONRPCMessageSchema } from '../types.js'; -/** - * Buffers a continuous stdio stream into discrete JSON-RPC messages. - */ -export class ReadBuffer { - append(chunk) { - this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; - } - readMessage() { - if (!this._buffer) { - return null; - } - const index = this._buffer.indexOf('\n'); - if (index === -1) { - return null; - } - const line = this._buffer.toString('utf8', 0, index).replace(/\r$/, ''); - this._buffer = this._buffer.subarray(index + 1); - return deserializeMessage(line); - } - clear() { - this._buffer = undefined; - } -} -export function deserializeMessage(line) { - return JSONRPCMessageSchema.parse(JSON.parse(line)); -} -export function serializeMessage(message) { - return JSON.stringify(message) + '\n'; -} -//# sourceMappingURL=stdio.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js deleted file mode 100644 index ce25e23c..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * Normalizes HeadersInit to a plain Record for manipulation. - * Handles Headers objects, arrays of tuples, and plain objects. - */ -export function normalizeHeaders(headers) { - if (!headers) - return {}; - if (headers instanceof Headers) { - return Object.fromEntries(headers.entries()); - } - if (Array.isArray(headers)) { - return Object.fromEntries(headers); - } - return { ...headers }; -} -/** - * Creates a fetch function that includes base RequestInit options. - * This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. - * - * @param baseFetch - The base fetch function to wrap (defaults to global fetch) - * @param baseInit - The base RequestInit to merge with each request - * @returns A wrapped fetch function that merges base options with call-specific options - */ -export function createFetchWithInit(baseFetch = fetch, baseInit) { - if (!baseInit) { - return baseFetch; - } - // Return a wrapped fetch that merges base RequestInit with call-specific init - return async (url, init) => { - const mergedInit = { - ...baseInit, - ...init, - // Headers need special handling - merge instead of replace - headers: init?.headers ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers - }; - return baseFetch(url, mergedInit); - }; -} -//# sourceMappingURL=transport.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js deleted file mode 100644 index 8edb88ec..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js +++ /dev/null @@ -1,2052 +0,0 @@ -import * as z from 'zod/v4'; -export const LATEST_PROTOCOL_VERSION = '2025-11-25'; -export const DEFAULT_NEGOTIATED_PROTOCOL_VERSION = '2025-03-26'; -export const SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, '2025-06-18', '2025-03-26', '2024-11-05', '2024-10-07']; -export const RELATED_TASK_META_KEY = 'io.modelcontextprotocol/related-task'; -/* JSON-RPC types */ -export const JSONRPC_VERSION = '2.0'; -/** - * Assert 'object' type schema. - * - * @internal - */ -const AssertObjectSchema = z.custom((v) => v !== null && (typeof v === 'object' || typeof v === 'function')); -/** - * A progress token, used to associate progress notifications with the original request. - */ -export const ProgressTokenSchema = z.union([z.string(), z.number().int()]); -/** - * An opaque token used to represent a cursor for pagination. - */ -export const CursorSchema = z.string(); -/** - * Task creation parameters, used to ask that the server create a task to represent a request. - */ -export const TaskCreationParamsSchema = z.looseObject({ - /** - * Time in milliseconds to keep task results available after completion. - * If null, the task has unlimited lifetime until manually cleaned up. - */ - ttl: z.union([z.number(), z.null()]).optional(), - /** - * Time in milliseconds to wait between task status requests. - */ - pollInterval: z.number().optional() -}); -export const TaskMetadataSchema = z.object({ - ttl: z.number().optional() -}); -/** - * Metadata for associating messages with a task. - * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. - */ -export const RelatedTaskMetadataSchema = z.object({ - taskId: z.string() -}); -const RequestMetaSchema = z.looseObject({ - /** - * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications. - */ - progressToken: ProgressTokenSchema.optional(), - /** - * If specified, this request is related to the provided task. - */ - [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() -}); -/** - * Common params for any request. - */ -const BaseRequestParamsSchema = z.object({ - /** - * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage. - */ - _meta: RequestMetaSchema.optional() -}); -/** - * Common params for any task-augmented request. - */ -export const TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * If specified, the caller is requesting task-augmented execution for this request. - * The request will return a CreateTaskResult immediately, and the actual result can be - * retrieved later via tasks/result. - * - * Task augmentation is subject to capability negotiation - receivers MUST declare support - * for task augmentation of specific request types in their capabilities. - */ - task: TaskMetadataSchema.optional() -}); -/** - * Checks if a value is a valid TaskAugmentedRequestParams. - * @param value - The value to check. - * - * @returns True if the value is a valid TaskAugmentedRequestParams, false otherwise. - */ -export const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; -export const RequestSchema = z.object({ - method: z.string(), - params: BaseRequestParamsSchema.loose().optional() -}); -const NotificationsParamsSchema = z.object({ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: RequestMetaSchema.optional() -}); -export const NotificationSchema = z.object({ - method: z.string(), - params: NotificationsParamsSchema.loose().optional() -}); -export const ResultSchema = z.looseObject({ - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: RequestMetaSchema.optional() -}); -/** - * A uniquely identifying ID for a request in JSON-RPC. - */ -export const RequestIdSchema = z.union([z.string(), z.number().int()]); -/** - * A request that expects a response. - */ -export const JSONRPCRequestSchema = z - .object({ - jsonrpc: z.literal(JSONRPC_VERSION), - id: RequestIdSchema, - ...RequestSchema.shape -}) - .strict(); -export const isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; -/** - * A notification which does not expect a response. - */ -export const JSONRPCNotificationSchema = z - .object({ - jsonrpc: z.literal(JSONRPC_VERSION), - ...NotificationSchema.shape -}) - .strict(); -export const isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; -/** - * A successful (non-error) response to a request. - */ -export const JSONRPCResultResponseSchema = z - .object({ - jsonrpc: z.literal(JSONRPC_VERSION), - id: RequestIdSchema, - result: ResultSchema -}) - .strict(); -/** - * Checks if a value is a valid JSONRPCResultResponse. - * @param value - The value to check. - * - * @returns True if the value is a valid JSONRPCResultResponse, false otherwise. - */ -export const isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; -/** - * @deprecated Use {@link isJSONRPCResultResponse} instead. - * - * Please note that {@link JSONRPCResponse} is a union of {@link JSONRPCResultResponse} and {@link JSONRPCErrorResponse} as per the updated JSON-RPC specification. (was previously just {@link JSONRPCResultResponse}) - */ -export const isJSONRPCResponse = isJSONRPCResultResponse; -/** - * Error codes defined by the JSON-RPC specification. - */ -export var ErrorCode; -(function (ErrorCode) { - // SDK error codes - ErrorCode[ErrorCode["ConnectionClosed"] = -32000] = "ConnectionClosed"; - ErrorCode[ErrorCode["RequestTimeout"] = -32001] = "RequestTimeout"; - // Standard JSON-RPC error codes - ErrorCode[ErrorCode["ParseError"] = -32700] = "ParseError"; - ErrorCode[ErrorCode["InvalidRequest"] = -32600] = "InvalidRequest"; - ErrorCode[ErrorCode["MethodNotFound"] = -32601] = "MethodNotFound"; - ErrorCode[ErrorCode["InvalidParams"] = -32602] = "InvalidParams"; - ErrorCode[ErrorCode["InternalError"] = -32603] = "InternalError"; - // MCP-specific error codes - ErrorCode[ErrorCode["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; -})(ErrorCode || (ErrorCode = {})); -/** - * A response to a request that indicates an error occurred. - */ -export const JSONRPCErrorResponseSchema = z - .object({ - jsonrpc: z.literal(JSONRPC_VERSION), - id: RequestIdSchema.optional(), - error: z.object({ - /** - * The error type that occurred. - */ - code: z.number().int(), - /** - * A short description of the error. The message SHOULD be limited to a concise single sentence. - */ - message: z.string(), - /** - * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.). - */ - data: z.unknown().optional() - }) -}) - .strict(); -/** - * @deprecated Use {@link JSONRPCErrorResponseSchema} instead. - */ -export const JSONRPCErrorSchema = JSONRPCErrorResponseSchema; -/** - * Checks if a value is a valid JSONRPCErrorResponse. - * @param value - The value to check. - * - * @returns True if the value is a valid JSONRPCErrorResponse, false otherwise. - */ -export const isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; -/** - * @deprecated Use {@link isJSONRPCErrorResponse} instead. - */ -export const isJSONRPCError = isJSONRPCErrorResponse; -export const JSONRPCMessageSchema = z.union([ - JSONRPCRequestSchema, - JSONRPCNotificationSchema, - JSONRPCResultResponseSchema, - JSONRPCErrorResponseSchema -]); -export const JSONRPCResponseSchema = z.union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); -/* Empty result */ -/** - * A response that indicates success but carries no data. - */ -export const EmptyResultSchema = ResultSchema.strict(); -export const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The ID of the request to cancel. - * - * This MUST correspond to the ID of a request previously issued in the same direction. - */ - requestId: RequestIdSchema.optional(), - /** - * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user. - */ - reason: z.string().optional() -}); -/* Cancellation */ -/** - * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. - * - * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. - * - * This notification indicates that the result will be unused, so any associated processing SHOULD cease. - * - * A client MUST NOT attempt to cancel its `initialize` request. - */ -export const CancelledNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/cancelled'), - params: CancelledNotificationParamsSchema -}); -/* Base Metadata */ -/** - * Icon schema for use in tools, prompts, resources, and implementations. - */ -export const IconSchema = z.object({ - /** - * URL or data URI for the icon. - */ - src: z.string(), - /** - * Optional MIME type for the icon. - */ - mimeType: z.string().optional(), - /** - * Optional array of strings that specify sizes at which the icon can be used. - * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG. - * - * If not provided, the client should assume that the icon can be used at any size. - */ - sizes: z.array(z.string()).optional(), - /** - * Optional specifier for the theme this icon is designed for. `light` indicates - * the icon is designed to be used with a light background, and `dark` indicates - * the icon is designed to be used with a dark background. - * - * If not provided, the client should assume the icon can be used with any theme. - */ - theme: z.enum(['light', 'dark']).optional() -}); -/** - * Base schema to add `icons` property. - * - */ -export const IconsSchema = z.object({ - /** - * Optional set of sized icons that the client can display in a user interface. - * - * Clients that support rendering icons MUST support at least the following MIME types: - * - `image/png` - PNG images (safe, universal compatibility) - * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility) - * - * Clients that support rendering icons SHOULD also support: - * - `image/svg+xml` - SVG images (scalable but requires security precautions) - * - `image/webp` - WebP images (modern, efficient format) - */ - icons: z.array(IconSchema).optional() -}); -/** - * Base metadata interface for common properties across resources, tools, prompts, and implementations. - */ -export const BaseMetadataSchema = z.object({ - /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */ - name: z.string(), - /** - * Intended for UI and end-user contexts — optimized to be human-readable and easily understood, - * even by those unfamiliar with domain-specific terminology. - * - * If not provided, the name should be used for display (except for Tool, - * where `annotations.title` should be given precedence over using `name`, - * if present). - */ - title: z.string().optional() -}); -/* Initialization */ -/** - * Describes the name and version of an MCP implementation. - */ -export const ImplementationSchema = BaseMetadataSchema.extend({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - version: z.string(), - /** - * An optional URL of the website for this implementation. - */ - websiteUrl: z.string().optional(), - /** - * An optional human-readable description of what this implementation does. - * - * This can be used by clients or servers to provide context about their purpose - * and capabilities. For example, a server might describe the types of resources - * or tools it provides, while a client might describe its intended use case. - */ - description: z.string().optional() -}); -const FormElicitationCapabilitySchema = z.intersection(z.object({ - applyDefaults: z.boolean().optional() -}), z.record(z.string(), z.unknown())); -const ElicitationCapabilitySchema = z.preprocess(value => { - if (value && typeof value === 'object' && !Array.isArray(value)) { - if (Object.keys(value).length === 0) { - return { form: {} }; - } - } - return value; -}, z.intersection(z.object({ - form: FormElicitationCapabilitySchema.optional(), - url: AssertObjectSchema.optional() -}), z.record(z.string(), z.unknown()).optional())); -/** - * Task capabilities for clients, indicating which request types support task creation. - */ -export const ClientTasksCapabilitySchema = z.looseObject({ - /** - * Present if the client supports listing tasks. - */ - list: AssertObjectSchema.optional(), - /** - * Present if the client supports cancelling tasks. - */ - cancel: AssertObjectSchema.optional(), - /** - * Capabilities for task creation on specific request types. - */ - requests: z - .looseObject({ - /** - * Task support for sampling requests. - */ - sampling: z - .looseObject({ - createMessage: AssertObjectSchema.optional() - }) - .optional(), - /** - * Task support for elicitation requests. - */ - elicitation: z - .looseObject({ - create: AssertObjectSchema.optional() - }) - .optional() - }) - .optional() -}); -/** - * Task capabilities for servers, indicating which request types support task creation. - */ -export const ServerTasksCapabilitySchema = z.looseObject({ - /** - * Present if the server supports listing tasks. - */ - list: AssertObjectSchema.optional(), - /** - * Present if the server supports cancelling tasks. - */ - cancel: AssertObjectSchema.optional(), - /** - * Capabilities for task creation on specific request types. - */ - requests: z - .looseObject({ - /** - * Task support for tool requests. - */ - tools: z - .looseObject({ - call: AssertObjectSchema.optional() - }) - .optional() - }) - .optional() -}); -/** - * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. - */ -export const ClientCapabilitiesSchema = z.object({ - /** - * Experimental, non-standard capabilities that the client supports. - */ - experimental: z.record(z.string(), AssertObjectSchema).optional(), - /** - * Present if the client supports sampling from an LLM. - */ - sampling: z - .object({ - /** - * Present if the client supports context inclusion via includeContext parameter. - * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it). - */ - context: AssertObjectSchema.optional(), - /** - * Present if the client supports tool use via tools and toolChoice parameters. - */ - tools: AssertObjectSchema.optional() - }) - .optional(), - /** - * Present if the client supports eliciting user input. - */ - elicitation: ElicitationCapabilitySchema.optional(), - /** - * Present if the client supports listing roots. - */ - roots: z - .object({ - /** - * Whether the client supports issuing notifications for changes to the roots list. - */ - listChanged: z.boolean().optional() - }) - .optional(), - /** - * Present if the client supports task creation. - */ - tasks: ClientTasksCapabilitySchema.optional() -}); -export const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well. - */ - protocolVersion: z.string(), - capabilities: ClientCapabilitiesSchema, - clientInfo: ImplementationSchema -}); -/** - * This request is sent from the client to the server when it first connects, asking it to begin initialization. - */ -export const InitializeRequestSchema = RequestSchema.extend({ - method: z.literal('initialize'), - params: InitializeRequestParamsSchema -}); -export const isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; -/** - * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. - */ -export const ServerCapabilitiesSchema = z.object({ - /** - * Experimental, non-standard capabilities that the server supports. - */ - experimental: z.record(z.string(), AssertObjectSchema).optional(), - /** - * Present if the server supports sending log messages to the client. - */ - logging: AssertObjectSchema.optional(), - /** - * Present if the server supports sending completions to the client. - */ - completions: AssertObjectSchema.optional(), - /** - * Present if the server offers any prompt templates. - */ - prompts: z - .object({ - /** - * Whether this server supports issuing notifications for changes to the prompt list. - */ - listChanged: z.boolean().optional() - }) - .optional(), - /** - * Present if the server offers any resources to read. - */ - resources: z - .object({ - /** - * Whether this server supports clients subscribing to resource updates. - */ - subscribe: z.boolean().optional(), - /** - * Whether this server supports issuing notifications for changes to the resource list. - */ - listChanged: z.boolean().optional() - }) - .optional(), - /** - * Present if the server offers any tools to call. - */ - tools: z - .object({ - /** - * Whether this server supports issuing notifications for changes to the tool list. - */ - listChanged: z.boolean().optional() - }) - .optional(), - /** - * Present if the server supports task creation. - */ - tasks: ServerTasksCapabilitySchema.optional() -}); -/** - * After receiving an initialize request from the client, the server sends this response. - */ -export const InitializeResultSchema = ResultSchema.extend({ - /** - * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect. - */ - protocolVersion: z.string(), - capabilities: ServerCapabilitiesSchema, - serverInfo: ImplementationSchema, - /** - * Instructions describing how to use the server and its features. - * - * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt. - */ - instructions: z.string().optional() -}); -/** - * This notification is sent from the client to the server after initialization has finished. - */ -export const InitializedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/initialized'), - params: NotificationsParamsSchema.optional() -}); -export const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; -/* Ping */ -/** - * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. - */ -export const PingRequestSchema = RequestSchema.extend({ - method: z.literal('ping'), - params: BaseRequestParamsSchema.optional() -}); -/* Progress notifications */ -export const ProgressSchema = z.object({ - /** - * The progress thus far. This should increase every time progress is made, even if the total is unknown. - */ - progress: z.number(), - /** - * Total number of items to process (or total progress required), if known. - */ - total: z.optional(z.number()), - /** - * An optional message describing the current progress. - */ - message: z.optional(z.string()) -}); -export const ProgressNotificationParamsSchema = z.object({ - ...NotificationsParamsSchema.shape, - ...ProgressSchema.shape, - /** - * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding. - */ - progressToken: ProgressTokenSchema -}); -/** - * An out-of-band notification used to inform the receiver of a progress update for a long-running request. - * - * @category notifications/progress - */ -export const ProgressNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/progress'), - params: ProgressNotificationParamsSchema -}); -export const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * An opaque token representing the current pagination position. - * If provided, the server should return results starting after this cursor. - */ - cursor: CursorSchema.optional() -}); -/* Pagination */ -export const PaginatedRequestSchema = RequestSchema.extend({ - params: PaginatedRequestParamsSchema.optional() -}); -export const PaginatedResultSchema = ResultSchema.extend({ - /** - * An opaque token representing the pagination position after the last returned result. - * If present, there may be more results available. - */ - nextCursor: CursorSchema.optional() -}); -/** - * The status of a task. - * */ -export const TaskStatusSchema = z.enum(['working', 'input_required', 'completed', 'failed', 'cancelled']); -/* Tasks */ -/** - * A pollable state object associated with a request. - */ -export const TaskSchema = z.object({ - taskId: z.string(), - status: TaskStatusSchema, - /** - * Time in milliseconds to keep task results available after completion. - * If null, the task has unlimited lifetime until manually cleaned up. - */ - ttl: z.union([z.number(), z.null()]), - /** - * ISO 8601 timestamp when the task was created. - */ - createdAt: z.string(), - /** - * ISO 8601 timestamp when the task was last updated. - */ - lastUpdatedAt: z.string(), - pollInterval: z.optional(z.number()), - /** - * Optional diagnostic message for failed tasks or other status information. - */ - statusMessage: z.optional(z.string()) -}); -/** - * Result returned when a task is created, containing the task data wrapped in a task field. - */ -export const CreateTaskResultSchema = ResultSchema.extend({ - task: TaskSchema -}); -/** - * Parameters for task status notification. - */ -export const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); -/** - * A notification sent when a task's status changes. - */ -export const TaskStatusNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/tasks/status'), - params: TaskStatusNotificationParamsSchema -}); -/** - * A request to get the state of a specific task. - */ -export const GetTaskRequestSchema = RequestSchema.extend({ - method: z.literal('tasks/get'), - params: BaseRequestParamsSchema.extend({ - taskId: z.string() - }) -}); -/** - * The response to a tasks/get request. - */ -export const GetTaskResultSchema = ResultSchema.merge(TaskSchema); -/** - * A request to get the result of a specific task. - */ -export const GetTaskPayloadRequestSchema = RequestSchema.extend({ - method: z.literal('tasks/result'), - params: BaseRequestParamsSchema.extend({ - taskId: z.string() - }) -}); -/** - * The response to a tasks/result request. - * The structure matches the result type of the original request. - * For example, a tools/call task would return the CallToolResult structure. - * - */ -export const GetTaskPayloadResultSchema = ResultSchema.loose(); -/** - * A request to list tasks. - */ -export const ListTasksRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('tasks/list') -}); -/** - * The response to a tasks/list request. - */ -export const ListTasksResultSchema = PaginatedResultSchema.extend({ - tasks: z.array(TaskSchema) -}); -/** - * A request to cancel a specific task. - */ -export const CancelTaskRequestSchema = RequestSchema.extend({ - method: z.literal('tasks/cancel'), - params: BaseRequestParamsSchema.extend({ - taskId: z.string() - }) -}); -/** - * The response to a tasks/cancel request. - */ -export const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); -/* Resources */ -/** - * The contents of a specific resource or sub-resource. - */ -export const ResourceContentsSchema = z.object({ - /** - * The URI of this resource. - */ - uri: z.string(), - /** - * The MIME type of this resource, if known. - */ - mimeType: z.optional(z.string()), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -export const TextResourceContentsSchema = ResourceContentsSchema.extend({ - /** - * The text of the item. This must only be set if the item can actually be represented as text (not binary data). - */ - text: z.string() -}); -/** - * A Zod schema for validating Base64 strings that is more performant and - * robust for very large inputs than the default regex-based check. It avoids - * stack overflows by using the native `atob` function for validation. - */ -const Base64Schema = z.string().refine(val => { - try { - // atob throws a DOMException if the string contains characters - // that are not part of the Base64 character set. - atob(val); - return true; - } - catch { - return false; - } -}, { message: 'Invalid Base64 string' }); -export const BlobResourceContentsSchema = ResourceContentsSchema.extend({ - /** - * A base64-encoded string representing the binary data of the item. - */ - blob: Base64Schema -}); -/** - * The sender or recipient of messages and data in a conversation. - */ -export const RoleSchema = z.enum(['user', 'assistant']); -/** - * Optional annotations providing clients additional context about a resource. - */ -export const AnnotationsSchema = z.object({ - /** - * Intended audience(s) for the resource. - */ - audience: z.array(RoleSchema).optional(), - /** - * Importance hint for the resource, from 0 (least) to 1 (most). - */ - priority: z.number().min(0).max(1).optional(), - /** - * ISO 8601 timestamp for the most recent modification. - */ - lastModified: z.iso.datetime({ offset: true }).optional() -}); -/** - * A known resource that the server is capable of reading. - */ -export const ResourceSchema = z.object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - /** - * The URI of this resource. - */ - uri: z.string(), - /** - * A description of what this resource represents. - * - * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. - */ - description: z.optional(z.string()), - /** - * The MIME type of this resource, if known. - */ - mimeType: z.optional(z.string()), - /** - * Optional annotations for the client. - */ - annotations: AnnotationsSchema.optional(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.looseObject({})) -}); -/** - * A template description for resources available on the server. - */ -export const ResourceTemplateSchema = z.object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - /** - * A URI template (according to RFC 6570) that can be used to construct resource URIs. - */ - uriTemplate: z.string(), - /** - * A description of what this template is for. - * - * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model. - */ - description: z.optional(z.string()), - /** - * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type. - */ - mimeType: z.optional(z.string()), - /** - * Optional annotations for the client. - */ - annotations: AnnotationsSchema.optional(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.looseObject({})) -}); -/** - * Sent from the client to request a list of resources the server has. - */ -export const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('resources/list') -}); -/** - * The server's response to a resources/list request from the client. - */ -export const ListResourcesResultSchema = PaginatedResultSchema.extend({ - resources: z.array(ResourceSchema) -}); -/** - * Sent from the client to request a list of resource templates the server has. - */ -export const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('resources/templates/list') -}); -/** - * The server's response to a resources/templates/list request from the client. - */ -export const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ - resourceTemplates: z.array(ResourceTemplateSchema) -}); -export const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it. - * - * @format uri - */ - uri: z.string() -}); -/** - * Parameters for a `resources/read` request. - */ -export const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; -/** - * Sent from the client to the server, to read a specific resource URI. - */ -export const ReadResourceRequestSchema = RequestSchema.extend({ - method: z.literal('resources/read'), - params: ReadResourceRequestParamsSchema -}); -/** - * The server's response to a resources/read request from the client. - */ -export const ReadResourceResultSchema = ResultSchema.extend({ - contents: z.array(z.union([TextResourceContentsSchema, BlobResourceContentsSchema])) -}); -/** - * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. - */ -export const ResourceListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/resources/list_changed'), - params: NotificationsParamsSchema.optional() -}); -export const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; -/** - * Sent from the client to request resources/updated notifications from the server whenever a particular resource changes. - */ -export const SubscribeRequestSchema = RequestSchema.extend({ - method: z.literal('resources/subscribe'), - params: SubscribeRequestParamsSchema -}); -export const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; -/** - * Sent from the client to request cancellation of resources/updated notifications from the server. This should follow a previous resources/subscribe request. - */ -export const UnsubscribeRequestSchema = RequestSchema.extend({ - method: z.literal('resources/unsubscribe'), - params: UnsubscribeRequestParamsSchema -}); -/** - * Parameters for a `notifications/resources/updated` notification. - */ -export const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to. - */ - uri: z.string() -}); -/** - * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a resources/subscribe request. - */ -export const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/resources/updated'), - params: ResourceUpdatedNotificationParamsSchema -}); -/* Prompts */ -/** - * Describes an argument that a prompt can accept. - */ -export const PromptArgumentSchema = z.object({ - /** - * The name of the argument. - */ - name: z.string(), - /** - * A human-readable description of the argument. - */ - description: z.optional(z.string()), - /** - * Whether this argument must be provided. - */ - required: z.optional(z.boolean()) -}); -/** - * A prompt or prompt template that the server offers. - */ -export const PromptSchema = z.object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - /** - * An optional description of what this prompt provides - */ - description: z.optional(z.string()), - /** - * A list of arguments to use for templating the prompt. - */ - arguments: z.optional(z.array(PromptArgumentSchema)), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.optional(z.looseObject({})) -}); -/** - * Sent from the client to request a list of prompts and prompt templates the server has. - */ -export const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('prompts/list') -}); -/** - * The server's response to a prompts/list request from the client. - */ -export const ListPromptsResultSchema = PaginatedResultSchema.extend({ - prompts: z.array(PromptSchema) -}); -/** - * Parameters for a `prompts/get` request. - */ -export const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The name of the prompt or prompt template. - */ - name: z.string(), - /** - * Arguments to use for templating the prompt. - */ - arguments: z.record(z.string(), z.string()).optional() -}); -/** - * Used by the client to get a prompt provided by the server. - */ -export const GetPromptRequestSchema = RequestSchema.extend({ - method: z.literal('prompts/get'), - params: GetPromptRequestParamsSchema -}); -/** - * Text provided to or from an LLM. - */ -export const TextContentSchema = z.object({ - type: z.literal('text'), - /** - * The text content of the message. - */ - text: z.string(), - /** - * Optional annotations for the client. - */ - annotations: AnnotationsSchema.optional(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * An image provided to or from an LLM. - */ -export const ImageContentSchema = z.object({ - type: z.literal('image'), - /** - * The base64-encoded image data. - */ - data: Base64Schema, - /** - * The MIME type of the image. Different providers may support different image types. - */ - mimeType: z.string(), - /** - * Optional annotations for the client. - */ - annotations: AnnotationsSchema.optional(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * An Audio provided to or from an LLM. - */ -export const AudioContentSchema = z.object({ - type: z.literal('audio'), - /** - * The base64-encoded audio data. - */ - data: Base64Schema, - /** - * The MIME type of the audio. Different providers may support different audio types. - */ - mimeType: z.string(), - /** - * Optional annotations for the client. - */ - annotations: AnnotationsSchema.optional(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * A tool call request from an assistant (LLM). - * Represents the assistant's request to use a tool. - */ -export const ToolUseContentSchema = z.object({ - type: z.literal('tool_use'), - /** - * The name of the tool to invoke. - * Must match a tool name from the request's tools array. - */ - name: z.string(), - /** - * Unique identifier for this tool call. - * Used to correlate with ToolResultContent in subsequent messages. - */ - id: z.string(), - /** - * Arguments to pass to the tool. - * Must conform to the tool's inputSchema. - */ - input: z.record(z.string(), z.unknown()), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * The contents of a resource, embedded into a prompt or tool call result. - */ -export const EmbeddedResourceSchema = z.object({ - type: z.literal('resource'), - resource: z.union([TextResourceContentsSchema, BlobResourceContentsSchema]), - /** - * Optional annotations for the client. - */ - annotations: AnnotationsSchema.optional(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * A resource that the server is capable of reading, included in a prompt or tool call result. - * - * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. - */ -export const ResourceLinkSchema = ResourceSchema.extend({ - type: z.literal('resource_link') -}); -/** - * A content block that can be used in prompts and tool results. - */ -export const ContentBlockSchema = z.union([ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ResourceLinkSchema, - EmbeddedResourceSchema -]); -/** - * Describes a message returned as part of a prompt. - */ -export const PromptMessageSchema = z.object({ - role: RoleSchema, - content: ContentBlockSchema -}); -/** - * The server's response to a prompts/get request from the client. - */ -export const GetPromptResultSchema = ResultSchema.extend({ - /** - * An optional description for the prompt. - */ - description: z.string().optional(), - messages: z.array(PromptMessageSchema) -}); -/** - * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. - */ -export const PromptListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/prompts/list_changed'), - params: NotificationsParamsSchema.optional() -}); -/* Tools */ -/** - * Additional properties describing a Tool to clients. - * - * NOTE: all properties in ToolAnnotations are **hints**. - * They are not guaranteed to provide a faithful description of - * tool behavior (including descriptive properties like `title`). - * - * Clients should never make tool use decisions based on ToolAnnotations - * received from untrusted servers. - */ -export const ToolAnnotationsSchema = z.object({ - /** - * A human-readable title for the tool. - */ - title: z.string().optional(), - /** - * If true, the tool does not modify its environment. - * - * Default: false - */ - readOnlyHint: z.boolean().optional(), - /** - * If true, the tool may perform destructive updates to its environment. - * If false, the tool performs only additive updates. - * - * (This property is meaningful only when `readOnlyHint == false`) - * - * Default: true - */ - destructiveHint: z.boolean().optional(), - /** - * If true, calling the tool repeatedly with the same arguments - * will have no additional effect on the its environment. - * - * (This property is meaningful only when `readOnlyHint == false`) - * - * Default: false - */ - idempotentHint: z.boolean().optional(), - /** - * If true, this tool may interact with an "open world" of external - * entities. If false, the tool's domain of interaction is closed. - * For example, the world of a web search tool is open, whereas that - * of a memory tool is not. - * - * Default: true - */ - openWorldHint: z.boolean().optional() -}); -/** - * Execution-related properties for a tool. - */ -export const ToolExecutionSchema = z.object({ - /** - * Indicates the tool's preference for task-augmented execution. - * - "required": Clients MUST invoke the tool as a task - * - "optional": Clients MAY invoke the tool as a task or normal request - * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task - * - * If not present, defaults to "forbidden". - */ - taskSupport: z.enum(['required', 'optional', 'forbidden']).optional() -}); -/** - * Definition for a tool the client can call. - */ -export const ToolSchema = z.object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - /** - * A human-readable description of the tool. - */ - description: z.string().optional(), - /** - * A JSON Schema 2020-12 object defining the expected parameters for the tool. - * Must have type: 'object' at the root level per MCP spec. - */ - inputSchema: z - .object({ - type: z.literal('object'), - properties: z.record(z.string(), AssertObjectSchema).optional(), - required: z.array(z.string()).optional() - }) - .catchall(z.unknown()), - /** - * An optional JSON Schema 2020-12 object defining the structure of the tool's output - * returned in the structuredContent field of a CallToolResult. - * Must have type: 'object' at the root level per MCP spec. - */ - outputSchema: z - .object({ - type: z.literal('object'), - properties: z.record(z.string(), AssertObjectSchema).optional(), - required: z.array(z.string()).optional() - }) - .catchall(z.unknown()) - .optional(), - /** - * Optional additional tool information. - */ - annotations: ToolAnnotationsSchema.optional(), - /** - * Execution-related properties for this tool. - */ - execution: ToolExecutionSchema.optional(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * Sent from the client to request a list of tools the server has. - */ -export const ListToolsRequestSchema = PaginatedRequestSchema.extend({ - method: z.literal('tools/list') -}); -/** - * The server's response to a tools/list request from the client. - */ -export const ListToolsResultSchema = PaginatedResultSchema.extend({ - tools: z.array(ToolSchema) -}); -/** - * The server's response to a tool call. - */ -export const CallToolResultSchema = ResultSchema.extend({ - /** - * A list of content objects that represent the result of the tool call. - * - * If the Tool does not define an outputSchema, this field MUST be present in the result. - * For backwards compatibility, this field is always present, but it may be empty. - */ - content: z.array(ContentBlockSchema).default([]), - /** - * An object containing structured tool output. - * - * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema. - */ - structuredContent: z.record(z.string(), z.unknown()).optional(), - /** - * Whether the tool call ended in an error. - * - * If not set, this is assumed to be false (the call was successful). - * - * Any errors that originate from the tool SHOULD be reported inside the result - * object, with `isError` set to true, _not_ as an MCP protocol-level error - * response. Otherwise, the LLM would not be able to see that an error occurred - * and self-correct. - * - * However, any errors in _finding_ the tool, an error indicating that the - * server does not support tool calls, or any other exceptional conditions, - * should be reported as an MCP error response. - */ - isError: z.boolean().optional() -}); -/** - * CallToolResultSchema extended with backwards compatibility to protocol version 2024-10-07. - */ -export const CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({ - toolResult: z.unknown() -})); -/** - * Parameters for a `tools/call` request. - */ -export const CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ - /** - * The name of the tool to call. - */ - name: z.string(), - /** - * Arguments to pass to the tool. - */ - arguments: z.record(z.string(), z.unknown()).optional() -}); -/** - * Used by the client to invoke a tool provided by the server. - */ -export const CallToolRequestSchema = RequestSchema.extend({ - method: z.literal('tools/call'), - params: CallToolRequestParamsSchema -}); -/** - * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. - */ -export const ToolListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/tools/list_changed'), - params: NotificationsParamsSchema.optional() -}); -/** - * Base schema for list changed subscription options (without callback). - * Used internally for Zod validation of autoRefresh and debounceMs. - */ -export const ListChangedOptionsBaseSchema = z.object({ - /** - * If true, the list will be refreshed automatically when a list changed notification is received. - * The callback will be called with the updated list. - * - * If false, the callback will be called with null items, allowing manual refresh. - * - * @default true - */ - autoRefresh: z.boolean().default(true), - /** - * Debounce time in milliseconds for list changed notification processing. - * - * Multiple notifications received within this timeframe will only trigger one refresh. - * Set to 0 to disable debouncing. - * - * @default 300 - */ - debounceMs: z.number().int().nonnegative().default(300) -}); -/* Logging */ -/** - * The severity of a log message. - */ -export const LoggingLevelSchema = z.enum(['debug', 'info', 'notice', 'warning', 'error', 'critical', 'alert', 'emergency']); -/** - * Parameters for a `logging/setLevel` request. - */ -export const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ - /** - * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message. - */ - level: LoggingLevelSchema -}); -/** - * A request from the client to the server, to enable or adjust logging. - */ -export const SetLevelRequestSchema = RequestSchema.extend({ - method: z.literal('logging/setLevel'), - params: SetLevelRequestParamsSchema -}); -/** - * Parameters for a `notifications/message` notification. - */ -export const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The severity of this log message. - */ - level: LoggingLevelSchema, - /** - * An optional name of the logger issuing this message. - */ - logger: z.string().optional(), - /** - * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here. - */ - data: z.unknown() -}); -/** - * Notification of a log message passed from server to client. If no logging/setLevel request has been sent from the client, the server MAY decide which messages to send automatically. - */ -export const LoggingMessageNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/message'), - params: LoggingMessageNotificationParamsSchema -}); -/* Sampling */ -/** - * Hints to use for model selection. - */ -export const ModelHintSchema = z.object({ - /** - * A hint for a model name. - */ - name: z.string().optional() -}); -/** - * The server's preferences for model selection, requested of the client during sampling. - */ -export const ModelPreferencesSchema = z.object({ - /** - * Optional hints to use for model selection. - */ - hints: z.array(ModelHintSchema).optional(), - /** - * How much to prioritize cost when selecting a model. - */ - costPriority: z.number().min(0).max(1).optional(), - /** - * How much to prioritize sampling speed (latency) when selecting a model. - */ - speedPriority: z.number().min(0).max(1).optional(), - /** - * How much to prioritize intelligence and capabilities when selecting a model. - */ - intelligencePriority: z.number().min(0).max(1).optional() -}); -/** - * Controls tool usage behavior in sampling requests. - */ -export const ToolChoiceSchema = z.object({ - /** - * Controls when tools are used: - * - "auto": Model decides whether to use tools (default) - * - "required": Model MUST use at least one tool before completing - * - "none": Model MUST NOT use any tools - */ - mode: z.enum(['auto', 'required', 'none']).optional() -}); -/** - * The result of a tool execution, provided by the user (server). - * Represents the outcome of invoking a tool requested via ToolUseContent. - */ -export const ToolResultContentSchema = z.object({ - type: z.literal('tool_result'), - toolUseId: z.string().describe('The unique identifier for the corresponding tool call.'), - content: z.array(ContentBlockSchema).default([]), - structuredContent: z.object({}).loose().optional(), - isError: z.boolean().optional(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * Basic content types for sampling responses (without tool use). - * Used for backwards-compatible CreateMessageResult when tools are not used. - */ -export const SamplingContentSchema = z.discriminatedUnion('type', [TextContentSchema, ImageContentSchema, AudioContentSchema]); -/** - * Content block types allowed in sampling messages. - * This includes text, image, audio, tool use requests, and tool results. - */ -export const SamplingMessageContentBlockSchema = z.discriminatedUnion('type', [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ToolUseContentSchema, - ToolResultContentSchema -]); -/** - * Describes a message issued to or received from an LLM API. - */ -export const SamplingMessageSchema = z.object({ - role: RoleSchema, - content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * Parameters for a `sampling/createMessage` request. - */ -export const CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({ - messages: z.array(SamplingMessageSchema), - /** - * The server's preferences for which model to select. The client MAY modify or omit this request. - */ - modelPreferences: ModelPreferencesSchema.optional(), - /** - * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt. - */ - systemPrompt: z.string().optional(), - /** - * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt. - * The client MAY ignore this request. - * - * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client - * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases. - */ - includeContext: z.enum(['none', 'thisServer', 'allServers']).optional(), - temperature: z.number().optional(), - /** - * The requested maximum number of tokens to sample (to prevent runaway completions). - * - * The client MAY choose to sample fewer tokens than the requested maximum. - */ - maxTokens: z.number().int(), - stopSequences: z.array(z.string()).optional(), - /** - * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific. - */ - metadata: AssertObjectSchema.optional(), - /** - * Tools that the model may use during generation. - * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. - */ - tools: z.array(ToolSchema).optional(), - /** - * Controls how the model uses tools. - * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared. - * Default is `{ mode: "auto" }`. - */ - toolChoice: ToolChoiceSchema.optional() -}); -/** - * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. - */ -export const CreateMessageRequestSchema = RequestSchema.extend({ - method: z.literal('sampling/createMessage'), - params: CreateMessageRequestParamsSchema -}); -/** - * The client's response to a sampling/create_message request from the server. - * This is the backwards-compatible version that returns single content (no arrays). - * Used when the request does not include tools. - */ -export const CreateMessageResultSchema = ResultSchema.extend({ - /** - * The name of the model that generated the message. - */ - model: z.string(), - /** - * The reason why sampling stopped, if known. - * - * Standard values: - * - "endTurn": Natural end of the assistant's turn - * - "stopSequence": A stop sequence was encountered - * - "maxTokens": Maximum token limit was reached - * - * This field is an open string to allow for provider-specific stop reasons. - */ - stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens']).or(z.string())), - role: RoleSchema, - /** - * Response content. Single content block (text, image, or audio). - */ - content: SamplingContentSchema -}); -/** - * The client's response to a sampling/create_message request when tools were provided. - * This version supports array content for tool use flows. - */ -export const CreateMessageResultWithToolsSchema = ResultSchema.extend({ - /** - * The name of the model that generated the message. - */ - model: z.string(), - /** - * The reason why sampling stopped, if known. - * - * Standard values: - * - "endTurn": Natural end of the assistant's turn - * - "stopSequence": A stop sequence was encountered - * - "maxTokens": Maximum token limit was reached - * - "toolUse": The model wants to use one or more tools - * - * This field is an open string to allow for provider-specific stop reasons. - */ - stopReason: z.optional(z.enum(['endTurn', 'stopSequence', 'maxTokens', 'toolUse']).or(z.string())), - role: RoleSchema, - /** - * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse". - */ - content: z.union([SamplingMessageContentBlockSchema, z.array(SamplingMessageContentBlockSchema)]) -}); -/* Elicitation */ -/** - * Primitive schema definition for boolean fields. - */ -export const BooleanSchemaSchema = z.object({ - type: z.literal('boolean'), - title: z.string().optional(), - description: z.string().optional(), - default: z.boolean().optional() -}); -/** - * Primitive schema definition for string fields. - */ -export const StringSchemaSchema = z.object({ - type: z.literal('string'), - title: z.string().optional(), - description: z.string().optional(), - minLength: z.number().optional(), - maxLength: z.number().optional(), - format: z.enum(['email', 'uri', 'date', 'date-time']).optional(), - default: z.string().optional() -}); -/** - * Primitive schema definition for number fields. - */ -export const NumberSchemaSchema = z.object({ - type: z.enum(['number', 'integer']), - title: z.string().optional(), - description: z.string().optional(), - minimum: z.number().optional(), - maximum: z.number().optional(), - default: z.number().optional() -}); -/** - * Schema for single-selection enumeration without display titles for options. - */ -export const UntitledSingleSelectEnumSchemaSchema = z.object({ - type: z.literal('string'), - title: z.string().optional(), - description: z.string().optional(), - enum: z.array(z.string()), - default: z.string().optional() -}); -/** - * Schema for single-selection enumeration with display titles for each option. - */ -export const TitledSingleSelectEnumSchemaSchema = z.object({ - type: z.literal('string'), - title: z.string().optional(), - description: z.string().optional(), - oneOf: z.array(z.object({ - const: z.string(), - title: z.string() - })), - default: z.string().optional() -}); -/** - * Use TitledSingleSelectEnumSchema instead. - * This interface will be removed in a future version. - */ -export const LegacyTitledEnumSchemaSchema = z.object({ - type: z.literal('string'), - title: z.string().optional(), - description: z.string().optional(), - enum: z.array(z.string()), - enumNames: z.array(z.string()).optional(), - default: z.string().optional() -}); -// Combined single selection enumeration -export const SingleSelectEnumSchemaSchema = z.union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); -/** - * Schema for multiple-selection enumeration without display titles for options. - */ -export const UntitledMultiSelectEnumSchemaSchema = z.object({ - type: z.literal('array'), - title: z.string().optional(), - description: z.string().optional(), - minItems: z.number().optional(), - maxItems: z.number().optional(), - items: z.object({ - type: z.literal('string'), - enum: z.array(z.string()) - }), - default: z.array(z.string()).optional() -}); -/** - * Schema for multiple-selection enumeration with display titles for each option. - */ -export const TitledMultiSelectEnumSchemaSchema = z.object({ - type: z.literal('array'), - title: z.string().optional(), - description: z.string().optional(), - minItems: z.number().optional(), - maxItems: z.number().optional(), - items: z.object({ - anyOf: z.array(z.object({ - const: z.string(), - title: z.string() - })) - }), - default: z.array(z.string()).optional() -}); -/** - * Combined schema for multiple-selection enumeration - */ -export const MultiSelectEnumSchemaSchema = z.union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); -/** - * Primitive schema definition for enum fields. - */ -export const EnumSchemaSchema = z.union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]); -/** - * Union of all primitive schema definitions. - */ -export const PrimitiveSchemaDefinitionSchema = z.union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]); -/** - * Parameters for an `elicitation/create` request for form-based elicitation. - */ -export const ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({ - /** - * The elicitation mode. - * - * Optional for backward compatibility. Clients MUST treat missing mode as "form". - */ - mode: z.literal('form').optional(), - /** - * The message to present to the user describing what information is being requested. - */ - message: z.string(), - /** - * A restricted subset of JSON Schema. - * Only top-level properties are allowed, without nesting. - */ - requestedSchema: z.object({ - type: z.literal('object'), - properties: z.record(z.string(), PrimitiveSchemaDefinitionSchema), - required: z.array(z.string()).optional() - }) -}); -/** - * Parameters for an `elicitation/create` request for URL-based elicitation. - */ -export const ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({ - /** - * The elicitation mode. - */ - mode: z.literal('url'), - /** - * The message to present to the user explaining why the interaction is needed. - */ - message: z.string(), - /** - * The ID of the elicitation, which must be unique within the context of the server. - * The client MUST treat this ID as an opaque value. - */ - elicitationId: z.string(), - /** - * The URL that the user should navigate to. - */ - url: z.string().url() -}); -/** - * The parameters for a request to elicit additional information from the user via the client. - */ -export const ElicitRequestParamsSchema = z.union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); -/** - * A request from the server to elicit user input via the client. - * The client should present the message and form fields to the user (form mode) - * or navigate to a URL (URL mode). - */ -export const ElicitRequestSchema = RequestSchema.extend({ - method: z.literal('elicitation/create'), - params: ElicitRequestParamsSchema -}); -/** - * Parameters for a `notifications/elicitation/complete` notification. - * - * @category notifications/elicitation/complete - */ -export const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ - /** - * The ID of the elicitation that completed. - */ - elicitationId: z.string() -}); -/** - * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. - * - * @category notifications/elicitation/complete - */ -export const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/elicitation/complete'), - params: ElicitationCompleteNotificationParamsSchema -}); -/** - * The client's response to an elicitation/create request from the server. - */ -export const ElicitResultSchema = ResultSchema.extend({ - /** - * The user action in response to the elicitation. - * - "accept": User submitted the form/confirmed the action - * - "decline": User explicitly decline the action - * - "cancel": User dismissed without making an explicit choice - */ - action: z.enum(['accept', 'decline', 'cancel']), - /** - * The submitted form data, only present when action is "accept". - * Contains values matching the requested schema. - * Per MCP spec, content is "typically omitted" for decline/cancel actions. - * We normalize null to undefined for leniency while maintaining type compatibility. - */ - content: z.preprocess(val => (val === null ? undefined : val), z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.array(z.string())])).optional()) -}); -/* Autocomplete */ -/** - * A reference to a resource or resource template definition. - */ -export const ResourceTemplateReferenceSchema = z.object({ - type: z.literal('ref/resource'), - /** - * The URI or URI template of the resource. - */ - uri: z.string() -}); -/** - * @deprecated Use ResourceTemplateReferenceSchema instead - */ -export const ResourceReferenceSchema = ResourceTemplateReferenceSchema; -/** - * Identifies a prompt. - */ -export const PromptReferenceSchema = z.object({ - type: z.literal('ref/prompt'), - /** - * The name of the prompt or prompt template - */ - name: z.string() -}); -/** - * Parameters for a `completion/complete` request. - */ -export const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ - ref: z.union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), - /** - * The argument's information - */ - argument: z.object({ - /** - * The name of the argument - */ - name: z.string(), - /** - * The value of the argument to use for completion matching. - */ - value: z.string() - }), - context: z - .object({ - /** - * Previously-resolved variables in a URI template or prompt. - */ - arguments: z.record(z.string(), z.string()).optional() - }) - .optional() -}); -/** - * A request from the client to the server, to ask for completion options. - */ -export const CompleteRequestSchema = RequestSchema.extend({ - method: z.literal('completion/complete'), - params: CompleteRequestParamsSchema -}); -export function assertCompleteRequestPrompt(request) { - if (request.params.ref.type !== 'ref/prompt') { - throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); - } - void request; -} -export function assertCompleteRequestResourceTemplate(request) { - if (request.params.ref.type !== 'ref/resource') { - throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); - } - void request; -} -/** - * The server's response to a completion/complete request - */ -export const CompleteResultSchema = ResultSchema.extend({ - completion: z.looseObject({ - /** - * An array of completion values. Must not exceed 100 items. - */ - values: z.array(z.string()).max(100), - /** - * The total number of completion options available. This can exceed the number of values actually sent in the response. - */ - total: z.optional(z.number().int()), - /** - * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown. - */ - hasMore: z.optional(z.boolean()) - }) -}); -/* Roots */ -/** - * Represents a root directory or file that the server can operate on. - */ -export const RootSchema = z.object({ - /** - * The URI identifying the root. This *must* start with file:// for now. - */ - uri: z.string().startsWith('file://'), - /** - * An optional name for the root. - */ - name: z.string().optional(), - /** - * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields) - * for notes on _meta usage. - */ - _meta: z.record(z.string(), z.unknown()).optional() -}); -/** - * Sent from the server to request a list of root URIs from the client. - */ -export const ListRootsRequestSchema = RequestSchema.extend({ - method: z.literal('roots/list'), - params: BaseRequestParamsSchema.optional() -}); -/** - * The client's response to a roots/list request from the server. - */ -export const ListRootsResultSchema = ResultSchema.extend({ - roots: z.array(RootSchema) -}); -/** - * A notification from the client to the server, informing it that the list of roots has changed. - */ -export const RootsListChangedNotificationSchema = NotificationSchema.extend({ - method: z.literal('notifications/roots/list_changed'), - params: NotificationsParamsSchema.optional() -}); -/* Client messages */ -export const ClientRequestSchema = z.union([ - PingRequestSchema, - InitializeRequestSchema, - CompleteRequestSchema, - SetLevelRequestSchema, - GetPromptRequestSchema, - ListPromptsRequestSchema, - ListResourcesRequestSchema, - ListResourceTemplatesRequestSchema, - ReadResourceRequestSchema, - SubscribeRequestSchema, - UnsubscribeRequestSchema, - CallToolRequestSchema, - ListToolsRequestSchema, - GetTaskRequestSchema, - GetTaskPayloadRequestSchema, - ListTasksRequestSchema, - CancelTaskRequestSchema -]); -export const ClientNotificationSchema = z.union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - InitializedNotificationSchema, - RootsListChangedNotificationSchema, - TaskStatusNotificationSchema -]); -export const ClientResultSchema = z.union([ - EmptyResultSchema, - CreateMessageResultSchema, - CreateMessageResultWithToolsSchema, - ElicitResultSchema, - ListRootsResultSchema, - GetTaskResultSchema, - ListTasksResultSchema, - CreateTaskResultSchema -]); -/* Server messages */ -export const ServerRequestSchema = z.union([ - PingRequestSchema, - CreateMessageRequestSchema, - ElicitRequestSchema, - ListRootsRequestSchema, - GetTaskRequestSchema, - GetTaskPayloadRequestSchema, - ListTasksRequestSchema, - CancelTaskRequestSchema -]); -export const ServerNotificationSchema = z.union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - LoggingMessageNotificationSchema, - ResourceUpdatedNotificationSchema, - ResourceListChangedNotificationSchema, - ToolListChangedNotificationSchema, - PromptListChangedNotificationSchema, - TaskStatusNotificationSchema, - ElicitationCompleteNotificationSchema -]); -export const ServerResultSchema = z.union([ - EmptyResultSchema, - InitializeResultSchema, - CompleteResultSchema, - GetPromptResultSchema, - ListPromptsResultSchema, - ListResourcesResultSchema, - ListResourceTemplatesResultSchema, - ReadResourceResultSchema, - CallToolResultSchema, - ListToolsResultSchema, - GetTaskResultSchema, - ListTasksResultSchema, - CreateTaskResultSchema -]); -export class McpError extends Error { - constructor(code, message, data) { - super(`MCP error ${code}: ${message}`); - this.code = code; - this.data = data; - this.name = 'McpError'; - } - /** - * Factory method to create the appropriate error type based on the error code and data - */ - static fromError(code, message, data) { - // Check for specific error types - if (code === ErrorCode.UrlElicitationRequired && data) { - const errorData = data; - if (errorData.elicitations) { - return new UrlElicitationRequiredError(errorData.elicitations, message); - } - } - // Default to generic McpError - return new McpError(code, message, data); - } -} -/** - * Specialized error type when a tool requires a URL mode elicitation. - * This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. - */ -export class UrlElicitationRequiredError extends McpError { - constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? 's' : ''} required`) { - super(ErrorCode.UrlElicitationRequired, message, { - elicitations: elicitations - }); - } - get elicitations() { - return this.data?.elicitations ?? []; - } -} -//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js b/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js deleted file mode 100644 index a0ab0674..00000000 --- a/claude-code-source/node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js +++ /dev/null @@ -1,87 +0,0 @@ -/** - * AJV-based JSON Schema validator provider - */ -import Ajv from 'ajv'; -import _addFormats from 'ajv-formats'; -function createDefaultAjvInstance() { - const ajv = new Ajv({ - strict: false, - validateFormats: true, - validateSchema: false, - allErrors: true - }); - const addFormats = _addFormats; - addFormats(ajv); - return ajv; -} -/** - * @example - * ```typescript - * // Use with default AJV instance (recommended) - * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; - * const validator = new AjvJsonSchemaValidator(); - * - * // Use with custom AJV instance - * import { Ajv } from 'ajv'; - * const ajv = new Ajv({ strict: true, allErrors: true }); - * const validator = new AjvJsonSchemaValidator(ajv); - * ``` - */ -export class AjvJsonSchemaValidator { - /** - * Create an AJV validator - * - * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created. - * - * @example - * ```typescript - * // Use default configuration (recommended for most cases) - * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv'; - * const validator = new AjvJsonSchemaValidator(); - * - * // Or provide custom AJV instance for advanced configuration - * import { Ajv } from 'ajv'; - * import addFormats from 'ajv-formats'; - * - * const ajv = new Ajv({ validateFormats: true }); - * addFormats(ajv); - * const validator = new AjvJsonSchemaValidator(ajv); - * ``` - */ - constructor(ajv) { - this._ajv = ajv ?? createDefaultAjvInstance(); - } - /** - * Create a validator for the given JSON Schema - * - * The validator is compiled once and can be reused multiple times. - * If the schema has an $id, it will be cached by AJV automatically. - * - * @param schema - Standard JSON Schema object - * @returns A validator function that validates input data - */ - getValidator(schema) { - // Check if schema has $id and is already compiled/cached - const ajvValidator = '$id' in schema && typeof schema.$id === 'string' - ? (this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema)) - : this._ajv.compile(schema); - return (input) => { - const valid = ajvValidator(input); - if (valid) { - return { - valid: true, - data: input, - errorMessage: undefined - }; - } - else { - return { - valid: false, - data: undefined, - errorMessage: this._ajv.errorsText(ajvValidator.errors) - }; - } - }; - } -} -//# sourceMappingURL=ajv-provider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/NoopLogger.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/NoopLogger.js deleted file mode 100644 index 7e1b2188..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/NoopLogger.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.NOOP_LOGGER = exports.NoopLogger = void 0; -class NoopLogger { - emit(_logRecord) { } -} -exports.NoopLogger = NoopLogger; -exports.NOOP_LOGGER = new NoopLogger(); -//# sourceMappingURL=NoopLogger.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/NoopLoggerProvider.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/NoopLoggerProvider.js deleted file mode 100644 index 1601f1a1..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/NoopLoggerProvider.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.NOOP_LOGGER_PROVIDER = exports.NoopLoggerProvider = void 0; -const NoopLogger_1 = require("./NoopLogger"); -class NoopLoggerProvider { - getLogger(_name, _version, _options) { - return new NoopLogger_1.NoopLogger(); - } -} -exports.NoopLoggerProvider = NoopLoggerProvider; -exports.NOOP_LOGGER_PROVIDER = new NoopLoggerProvider(); -//# sourceMappingURL=NoopLoggerProvider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/ProxyLogger.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/ProxyLogger.js deleted file mode 100644 index a37a9e6f..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/ProxyLogger.js +++ /dev/null @@ -1,52 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ProxyLogger = void 0; -const NoopLogger_1 = require("./NoopLogger"); -class ProxyLogger { - constructor(_provider, name, version, options) { - this._provider = _provider; - this.name = name; - this.version = version; - this.options = options; - } - /** - * Emit a log record. This method should only be used by log appenders. - * - * @param logRecord - */ - emit(logRecord) { - this._getLogger().emit(logRecord); - } - /** - * Try to get a logger from the proxy logger provider. - * If the proxy logger provider has no delegate, return a noop logger. - */ - _getLogger() { - if (this._delegate) { - return this._delegate; - } - const logger = this._provider._getDelegateLogger(this.name, this.version, this.options); - if (!logger) { - return NoopLogger_1.NOOP_LOGGER; - } - this._delegate = logger; - return this._delegate; - } -} -exports.ProxyLogger = ProxyLogger; -//# sourceMappingURL=ProxyLogger.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/ProxyLoggerProvider.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/ProxyLoggerProvider.js deleted file mode 100644 index dd0b2909..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/ProxyLoggerProvider.js +++ /dev/null @@ -1,51 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ProxyLoggerProvider = void 0; -const NoopLoggerProvider_1 = require("./NoopLoggerProvider"); -const ProxyLogger_1 = require("./ProxyLogger"); -class ProxyLoggerProvider { - getLogger(name, version, options) { - var _a; - return ((_a = this._getDelegateLogger(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyLogger_1.ProxyLogger(this, name, version, options)); - } - /** - * Get the delegate logger provider. - * Used by tests only. - * @internal - */ - _getDelegate() { - var _a; - return (_a = this._delegate) !== null && _a !== void 0 ? _a : NoopLoggerProvider_1.NOOP_LOGGER_PROVIDER; - } - /** - * Set the delegate logger provider - * @internal - */ - _setDelegate(delegate) { - this._delegate = delegate; - } - /** - * @internal - */ - _getDelegateLogger(name, version, options) { - var _a; - return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getLogger(name, version, options); - } -} -exports.ProxyLoggerProvider = ProxyLoggerProvider; -//# sourceMappingURL=ProxyLoggerProvider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/api/logs.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/api/logs.js deleted file mode 100644 index 8fd7e224..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/api/logs.js +++ /dev/null @@ -1,64 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.LogsAPI = void 0; -const global_utils_1 = require("../internal/global-utils"); -const NoopLoggerProvider_1 = require("../NoopLoggerProvider"); -const ProxyLoggerProvider_1 = require("../ProxyLoggerProvider"); -class LogsAPI { - constructor() { - this._proxyLoggerProvider = new ProxyLoggerProvider_1.ProxyLoggerProvider(); - } - static getInstance() { - if (!this._instance) { - this._instance = new LogsAPI(); - } - return this._instance; - } - setGlobalLoggerProvider(provider) { - if (global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY]) { - return this.getLoggerProvider(); - } - global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY] = (0, global_utils_1.makeGetter)(global_utils_1.API_BACKWARDS_COMPATIBILITY_VERSION, provider, NoopLoggerProvider_1.NOOP_LOGGER_PROVIDER); - this._proxyLoggerProvider._setDelegate(provider); - return provider; - } - /** - * Returns the global logger provider. - * - * @returns LoggerProvider - */ - getLoggerProvider() { - var _a, _b; - return ((_b = (_a = global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY]) === null || _a === void 0 ? void 0 : _a.call(global_utils_1._global, global_utils_1.API_BACKWARDS_COMPATIBILITY_VERSION)) !== null && _b !== void 0 ? _b : this._proxyLoggerProvider); - } - /** - * Returns a logger from the global logger provider. - * - * @returns Logger - */ - getLogger(name, version, options) { - return this.getLoggerProvider().getLogger(name, version, options); - } - /** Remove the global logger provider */ - disable() { - delete global_utils_1._global[global_utils_1.GLOBAL_LOGS_API_KEY]; - this._proxyLoggerProvider = new ProxyLoggerProvider_1.ProxyLoggerProvider(); - } -} -exports.LogsAPI = LogsAPI; -//# sourceMappingURL=logs.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/index.js deleted file mode 100644 index 9c147a97..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/index.js +++ /dev/null @@ -1,28 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.logs = exports.ProxyLoggerProvider = exports.NoopLogger = exports.NOOP_LOGGER = exports.SeverityNumber = void 0; -var LogRecord_1 = require("./types/LogRecord"); -Object.defineProperty(exports, "SeverityNumber", { enumerable: true, get: function () { return LogRecord_1.SeverityNumber; } }); -var NoopLogger_1 = require("./NoopLogger"); -Object.defineProperty(exports, "NOOP_LOGGER", { enumerable: true, get: function () { return NoopLogger_1.NOOP_LOGGER; } }); -Object.defineProperty(exports, "NoopLogger", { enumerable: true, get: function () { return NoopLogger_1.NoopLogger; } }); -var ProxyLoggerProvider_1 = require("./ProxyLoggerProvider"); -Object.defineProperty(exports, "ProxyLoggerProvider", { enumerable: true, get: function () { return ProxyLoggerProvider_1.ProxyLoggerProvider; } }); -const logs_1 = require("./api/logs"); -exports.logs = logs_1.LogsAPI.getInstance(); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/internal/global-utils.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/internal/global-utils.js deleted file mode 100644 index b1b2fbe7..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/internal/global-utils.js +++ /dev/null @@ -1,42 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.API_BACKWARDS_COMPATIBILITY_VERSION = exports.makeGetter = exports._global = exports.GLOBAL_LOGS_API_KEY = void 0; -const platform_1 = require("../platform"); -exports.GLOBAL_LOGS_API_KEY = Symbol.for('io.opentelemetry.js.api.logs'); -exports._global = platform_1._globalThis; -/** - * Make a function which accepts a version integer and returns the instance of an API if the version - * is compatible, or a fallback version (usually NOOP) if it is not. - * - * @param requiredVersion Backwards compatibility version which is required to return the instance - * @param instance Instance which should be returned if the required version is compatible - * @param fallback Fallback instance, usually NOOP, which will be returned if the required version is not compatible - */ -function makeGetter(requiredVersion, instance, fallback) { - return (version) => version === requiredVersion ? instance : fallback; -} -exports.makeGetter = makeGetter; -/** - * A number which should be incremented each time a backwards incompatible - * change is made to the API. This number is used when an API package - * attempts to access the global API to ensure it is getting a compatible - * version. If the global API is not compatible with the API package - * attempting to get it, a NOOP API implementation will be returned. - */ -exports.API_BACKWARDS_COMPATIBILITY_VERSION = 1; -//# sourceMappingURL=global-utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/index.js deleted file mode 100644 index a7cc3283..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports._globalThis = void 0; -var node_1 = require("./node"); -Object.defineProperty(exports, "_globalThis", { enumerable: true, get: function () { return node_1._globalThis; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/node/globalThis.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/node/globalThis.js deleted file mode 100644 index 9ae59140..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/node/globalThis.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports._globalThis = void 0; -/** only globals that common to node and browsers are allowed */ -// eslint-disable-next-line n/no-unsupported-features/es-builtins -exports._globalThis = typeof globalThis === 'object' ? globalThis : global; -//# sourceMappingURL=globalThis.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/node/index.js deleted file mode 100644 index ffe6d10d..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/platform/node/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports._globalThis = void 0; -var globalThis_1 = require("./globalThis"); -Object.defineProperty(exports, "_globalThis", { enumerable: true, get: function () { return globalThis_1._globalThis; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/types/LogRecord.js b/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/types/LogRecord.js deleted file mode 100644 index 3e9e301a..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api-logs/build/src/types/LogRecord.js +++ /dev/null @@ -1,47 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SeverityNumber = void 0; -var SeverityNumber; -(function (SeverityNumber) { - SeverityNumber[SeverityNumber["UNSPECIFIED"] = 0] = "UNSPECIFIED"; - SeverityNumber[SeverityNumber["TRACE"] = 1] = "TRACE"; - SeverityNumber[SeverityNumber["TRACE2"] = 2] = "TRACE2"; - SeverityNumber[SeverityNumber["TRACE3"] = 3] = "TRACE3"; - SeverityNumber[SeverityNumber["TRACE4"] = 4] = "TRACE4"; - SeverityNumber[SeverityNumber["DEBUG"] = 5] = "DEBUG"; - SeverityNumber[SeverityNumber["DEBUG2"] = 6] = "DEBUG2"; - SeverityNumber[SeverityNumber["DEBUG3"] = 7] = "DEBUG3"; - SeverityNumber[SeverityNumber["DEBUG4"] = 8] = "DEBUG4"; - SeverityNumber[SeverityNumber["INFO"] = 9] = "INFO"; - SeverityNumber[SeverityNumber["INFO2"] = 10] = "INFO2"; - SeverityNumber[SeverityNumber["INFO3"] = 11] = "INFO3"; - SeverityNumber[SeverityNumber["INFO4"] = 12] = "INFO4"; - SeverityNumber[SeverityNumber["WARN"] = 13] = "WARN"; - SeverityNumber[SeverityNumber["WARN2"] = 14] = "WARN2"; - SeverityNumber[SeverityNumber["WARN3"] = 15] = "WARN3"; - SeverityNumber[SeverityNumber["WARN4"] = 16] = "WARN4"; - SeverityNumber[SeverityNumber["ERROR"] = 17] = "ERROR"; - SeverityNumber[SeverityNumber["ERROR2"] = 18] = "ERROR2"; - SeverityNumber[SeverityNumber["ERROR3"] = 19] = "ERROR3"; - SeverityNumber[SeverityNumber["ERROR4"] = 20] = "ERROR4"; - SeverityNumber[SeverityNumber["FATAL"] = 21] = "FATAL"; - SeverityNumber[SeverityNumber["FATAL2"] = 22] = "FATAL2"; - SeverityNumber[SeverityNumber["FATAL3"] = 23] = "FATAL3"; - SeverityNumber[SeverityNumber["FATAL4"] = 24] = "FATAL4"; -})(SeverityNumber = exports.SeverityNumber || (exports.SeverityNumber = {})); -//# sourceMappingURL=LogRecord.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/api/context.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/api/context.js deleted file mode 100644 index 8af551f8..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/api/context.js +++ /dev/null @@ -1,81 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ContextAPI = void 0; -const NoopContextManager_1 = require("../context/NoopContextManager"); -const global_utils_1 = require("../internal/global-utils"); -const diag_1 = require("./diag"); -const API_NAME = 'context'; -const NOOP_CONTEXT_MANAGER = new NoopContextManager_1.NoopContextManager(); -/** - * Singleton object which represents the entry point to the OpenTelemetry Context API - */ -class ContextAPI { - /** Empty private constructor prevents end users from constructing a new instance of the API */ - constructor() { } - /** Get the singleton instance of the Context API */ - static getInstance() { - if (!this._instance) { - this._instance = new ContextAPI(); - } - return this._instance; - } - /** - * Set the current context manager. - * - * @returns true if the context manager was successfully registered, else false - */ - setGlobalContextManager(contextManager) { - return (0, global_utils_1.registerGlobal)(API_NAME, contextManager, diag_1.DiagAPI.instance()); - } - /** - * Get the currently active context - */ - active() { - return this._getContextManager().active(); - } - /** - * Execute a function with an active context - * - * @param context context to be active during function execution - * @param fn function to execute in a context - * @param thisArg optional receiver to be used for calling fn - * @param args optional arguments forwarded to fn - */ - with(context, fn, thisArg, ...args) { - return this._getContextManager().with(context, fn, thisArg, ...args); - } - /** - * Bind a context to a target function or event emitter - * - * @param context context to bind to the event emitter or function. Defaults to the currently active context - * @param target function or event emitter to bind - */ - bind(context, target) { - return this._getContextManager().bind(context, target); - } - _getContextManager() { - return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_CONTEXT_MANAGER; - } - /** Disable and remove the global context manager */ - disable() { - this._getContextManager().disable(); - (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); - } -} -exports.ContextAPI = ContextAPI; -//# sourceMappingURL=context.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/api/diag.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/api/diag.js deleted file mode 100644 index 94569232..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/api/diag.js +++ /dev/null @@ -1,93 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DiagAPI = void 0; -const ComponentLogger_1 = require("../diag/ComponentLogger"); -const logLevelLogger_1 = require("../diag/internal/logLevelLogger"); -const types_1 = require("../diag/types"); -const global_utils_1 = require("../internal/global-utils"); -const API_NAME = 'diag'; -/** - * Singleton object which represents the entry point to the OpenTelemetry internal - * diagnostic API - */ -class DiagAPI { - /** - * Private internal constructor - * @private - */ - constructor() { - function _logProxy(funcName) { - return function (...args) { - const logger = (0, global_utils_1.getGlobal)('diag'); - // shortcut if logger not set - if (!logger) - return; - return logger[funcName](...args); - }; - } - // Using self local variable for minification purposes as 'this' cannot be minified - const self = this; - // DiagAPI specific functions - const setLogger = (logger, optionsOrLogLevel = { logLevel: types_1.DiagLogLevel.INFO }) => { - var _a, _b, _c; - if (logger === self) { - // There isn't much we can do here. - // Logging to the console might break the user application. - // Try to log to self. If a logger was previously registered it will receive the log. - const err = new Error('Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation'); - self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message); - return false; - } - if (typeof optionsOrLogLevel === 'number') { - optionsOrLogLevel = { - logLevel: optionsOrLogLevel, - }; - } - const oldLogger = (0, global_utils_1.getGlobal)('diag'); - const newLogger = (0, logLevelLogger_1.createLogLevelDiagLogger)((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : types_1.DiagLogLevel.INFO, logger); - // There already is an logger registered. We'll let it know before overwriting it. - if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) { - const stack = (_c = new Error().stack) !== null && _c !== void 0 ? _c : ''; - oldLogger.warn(`Current logger will be overwritten from ${stack}`); - newLogger.warn(`Current logger will overwrite one already registered from ${stack}`); - } - return (0, global_utils_1.registerGlobal)('diag', newLogger, self, true); - }; - self.setLogger = setLogger; - self.disable = () => { - (0, global_utils_1.unregisterGlobal)(API_NAME, self); - }; - self.createComponentLogger = (options) => { - return new ComponentLogger_1.DiagComponentLogger(options); - }; - self.verbose = _logProxy('verbose'); - self.debug = _logProxy('debug'); - self.info = _logProxy('info'); - self.warn = _logProxy('warn'); - self.error = _logProxy('error'); - } - /** Get the singleton instance of the DiagAPI API */ - static instance() { - if (!this._instance) { - this._instance = new DiagAPI(); - } - return this._instance; - } -} -exports.DiagAPI = DiagAPI; -//# sourceMappingURL=diag.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/api/metrics.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/api/metrics.js deleted file mode 100644 index 4bbc4331..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/api/metrics.js +++ /dev/null @@ -1,61 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MetricsAPI = void 0; -const NoopMeterProvider_1 = require("../metrics/NoopMeterProvider"); -const global_utils_1 = require("../internal/global-utils"); -const diag_1 = require("./diag"); -const API_NAME = 'metrics'; -/** - * Singleton object which represents the entry point to the OpenTelemetry Metrics API - */ -class MetricsAPI { - /** Empty private constructor prevents end users from constructing a new instance of the API */ - constructor() { } - /** Get the singleton instance of the Metrics API */ - static getInstance() { - if (!this._instance) { - this._instance = new MetricsAPI(); - } - return this._instance; - } - /** - * Set the current global meter provider. - * Returns true if the meter provider was successfully registered, else false. - */ - setGlobalMeterProvider(provider) { - return (0, global_utils_1.registerGlobal)(API_NAME, provider, diag_1.DiagAPI.instance()); - } - /** - * Returns the global meter provider. - */ - getMeterProvider() { - return (0, global_utils_1.getGlobal)(API_NAME) || NoopMeterProvider_1.NOOP_METER_PROVIDER; - } - /** - * Returns a meter from the global meter provider. - */ - getMeter(name, version, options) { - return this.getMeterProvider().getMeter(name, version, options); - } - /** Remove the global meter provider */ - disable() { - (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); - } -} -exports.MetricsAPI = MetricsAPI; -//# sourceMappingURL=metrics.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/api/propagation.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/api/propagation.js deleted file mode 100644 index 7f03df81..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/api/propagation.js +++ /dev/null @@ -1,89 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PropagationAPI = void 0; -const global_utils_1 = require("../internal/global-utils"); -const NoopTextMapPropagator_1 = require("../propagation/NoopTextMapPropagator"); -const TextMapPropagator_1 = require("../propagation/TextMapPropagator"); -const context_helpers_1 = require("../baggage/context-helpers"); -const utils_1 = require("../baggage/utils"); -const diag_1 = require("./diag"); -const API_NAME = 'propagation'; -const NOOP_TEXT_MAP_PROPAGATOR = new NoopTextMapPropagator_1.NoopTextMapPropagator(); -/** - * Singleton object which represents the entry point to the OpenTelemetry Propagation API - */ -class PropagationAPI { - /** Empty private constructor prevents end users from constructing a new instance of the API */ - constructor() { - this.createBaggage = utils_1.createBaggage; - this.getBaggage = context_helpers_1.getBaggage; - this.getActiveBaggage = context_helpers_1.getActiveBaggage; - this.setBaggage = context_helpers_1.setBaggage; - this.deleteBaggage = context_helpers_1.deleteBaggage; - } - /** Get the singleton instance of the Propagator API */ - static getInstance() { - if (!this._instance) { - this._instance = new PropagationAPI(); - } - return this._instance; - } - /** - * Set the current propagator. - * - * @returns true if the propagator was successfully registered, else false - */ - setGlobalPropagator(propagator) { - return (0, global_utils_1.registerGlobal)(API_NAME, propagator, diag_1.DiagAPI.instance()); - } - /** - * Inject context into a carrier to be propagated inter-process - * - * @param context Context carrying tracing data to inject - * @param carrier carrier to inject context into - * @param setter Function used to set values on the carrier - */ - inject(context, carrier, setter = TextMapPropagator_1.defaultTextMapSetter) { - return this._getGlobalPropagator().inject(context, carrier, setter); - } - /** - * Extract context from a carrier - * - * @param context Context which the newly created context will inherit from - * @param carrier Carrier to extract context from - * @param getter Function used to extract keys from a carrier - */ - extract(context, carrier, getter = TextMapPropagator_1.defaultTextMapGetter) { - return this._getGlobalPropagator().extract(context, carrier, getter); - } - /** - * Return a list of all fields which may be used by the propagator. - */ - fields() { - return this._getGlobalPropagator().fields(); - } - /** Remove the global propagator */ - disable() { - (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); - } - _getGlobalPropagator() { - return (0, global_utils_1.getGlobal)(API_NAME) || NOOP_TEXT_MAP_PROPAGATOR; - } -} -exports.PropagationAPI = PropagationAPI; -//# sourceMappingURL=propagation.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/api/trace.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/api/trace.js deleted file mode 100644 index aa7a9da5..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/api/trace.js +++ /dev/null @@ -1,79 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TraceAPI = void 0; -const global_utils_1 = require("../internal/global-utils"); -const ProxyTracerProvider_1 = require("../trace/ProxyTracerProvider"); -const spancontext_utils_1 = require("../trace/spancontext-utils"); -const context_utils_1 = require("../trace/context-utils"); -const diag_1 = require("./diag"); -const API_NAME = 'trace'; -/** - * Singleton object which represents the entry point to the OpenTelemetry Tracing API - */ -class TraceAPI { - /** Empty private constructor prevents end users from constructing a new instance of the API */ - constructor() { - this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); - this.wrapSpanContext = spancontext_utils_1.wrapSpanContext; - this.isSpanContextValid = spancontext_utils_1.isSpanContextValid; - this.deleteSpan = context_utils_1.deleteSpan; - this.getSpan = context_utils_1.getSpan; - this.getActiveSpan = context_utils_1.getActiveSpan; - this.getSpanContext = context_utils_1.getSpanContext; - this.setSpan = context_utils_1.setSpan; - this.setSpanContext = context_utils_1.setSpanContext; - } - /** Get the singleton instance of the Trace API */ - static getInstance() { - if (!this._instance) { - this._instance = new TraceAPI(); - } - return this._instance; - } - /** - * Set the current global tracer. - * - * @returns true if the tracer provider was successfully registered, else false - */ - setGlobalTracerProvider(provider) { - const success = (0, global_utils_1.registerGlobal)(API_NAME, this._proxyTracerProvider, diag_1.DiagAPI.instance()); - if (success) { - this._proxyTracerProvider.setDelegate(provider); - } - return success; - } - /** - * Returns the global tracer provider. - */ - getTracerProvider() { - return (0, global_utils_1.getGlobal)(API_NAME) || this._proxyTracerProvider; - } - /** - * Returns a tracer from the global tracer provider. - */ - getTracer(name, version) { - return this.getTracerProvider().getTracer(name, version); - } - /** Remove the global tracer provider */ - disable() { - (0, global_utils_1.unregisterGlobal)(API_NAME, diag_1.DiagAPI.instance()); - this._proxyTracerProvider = new ProxyTracerProvider_1.ProxyTracerProvider(); - } -} -exports.TraceAPI = TraceAPI; -//# sourceMappingURL=trace.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js deleted file mode 100644 index cc0f00bf..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/context-helpers.js +++ /dev/null @@ -1,63 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.deleteBaggage = exports.setBaggage = exports.getActiveBaggage = exports.getBaggage = void 0; -const context_1 = require("../api/context"); -const context_2 = require("../context/context"); -/** - * Baggage key - */ -const BAGGAGE_KEY = (0, context_2.createContextKey)('OpenTelemetry Baggage Key'); -/** - * Retrieve the current baggage from the given context - * - * @param {Context} Context that manage all context values - * @returns {Baggage} Extracted baggage from the context - */ -function getBaggage(context) { - return context.getValue(BAGGAGE_KEY) || undefined; -} -exports.getBaggage = getBaggage; -/** - * Retrieve the current baggage from the active/current context - * - * @returns {Baggage} Extracted baggage from the context - */ -function getActiveBaggage() { - return getBaggage(context_1.ContextAPI.getInstance().active()); -} -exports.getActiveBaggage = getActiveBaggage; -/** - * Store a baggage in the given context - * - * @param {Context} Context that manage all context values - * @param {Baggage} baggage that will be set in the actual context - */ -function setBaggage(context, baggage) { - return context.setValue(BAGGAGE_KEY, baggage); -} -exports.setBaggage = setBaggage; -/** - * Delete the baggage stored in the given context - * - * @param {Context} Context that manage all context values - */ -function deleteBaggage(context) { - return context.deleteValue(BAGGAGE_KEY); -} -exports.deleteBaggage = deleteBaggage; -//# sourceMappingURL=context-helpers.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js deleted file mode 100644 index 6f04d4a6..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/internal/baggage-impl.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BaggageImpl = void 0; -class BaggageImpl { - constructor(entries) { - this._entries = entries ? new Map(entries) : new Map(); - } - getEntry(key) { - const entry = this._entries.get(key); - if (!entry) { - return undefined; - } - return Object.assign({}, entry); - } - getAllEntries() { - return Array.from(this._entries.entries()).map(([k, v]) => [k, v]); - } - setEntry(key, entry) { - const newBaggage = new BaggageImpl(this._entries); - newBaggage._entries.set(key, entry); - return newBaggage; - } - removeEntry(key) { - const newBaggage = new BaggageImpl(this._entries); - newBaggage._entries.delete(key); - return newBaggage; - } - removeEntries(...keys) { - const newBaggage = new BaggageImpl(this._entries); - for (const key of keys) { - newBaggage._entries.delete(key); - } - return newBaggage; - } - clear() { - return new BaggageImpl(); - } -} -exports.BaggageImpl = BaggageImpl; -//# sourceMappingURL=baggage-impl.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js deleted file mode 100644 index 324c216d..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/internal/symbol.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.baggageEntryMetadataSymbol = void 0; -/** - * Symbol used to make BaggageEntryMetadata an opaque type - */ -exports.baggageEntryMetadataSymbol = Symbol('BaggageEntryMetadata'); -//# sourceMappingURL=symbol.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/utils.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/utils.js deleted file mode 100644 index a0bfbf6c..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/baggage/utils.js +++ /dev/null @@ -1,51 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.baggageEntryMetadataFromString = exports.createBaggage = void 0; -const diag_1 = require("../api/diag"); -const baggage_impl_1 = require("./internal/baggage-impl"); -const symbol_1 = require("./internal/symbol"); -const diag = diag_1.DiagAPI.instance(); -/** - * Create a new Baggage with optional entries - * - * @param entries An array of baggage entries the new baggage should contain - */ -function createBaggage(entries = {}) { - return new baggage_impl_1.BaggageImpl(new Map(Object.entries(entries))); -} -exports.createBaggage = createBaggage; -/** - * Create a serializable BaggageEntryMetadata object from a string. - * - * @param str string metadata. Format is currently not defined by the spec and has no special meaning. - * - */ -function baggageEntryMetadataFromString(str) { - if (typeof str !== 'string') { - diag.error(`Cannot create baggage metadata from unknown type: ${typeof str}`); - str = ''; - } - return { - __TYPE__: symbol_1.baggageEntryMetadataSymbol, - toString() { - return str; - }, - }; -} -exports.baggageEntryMetadataFromString = baggageEntryMetadataFromString; -//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/context-api.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/context-api.js deleted file mode 100644 index b9aeea93..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/context-api.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.context = void 0; -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const context_1 = require("./api/context"); -/** Entrypoint for context API */ -exports.context = context_1.ContextAPI.getInstance(); -//# sourceMappingURL=context-api.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js deleted file mode 100644 index 10c6ae1b..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/context/NoopContextManager.js +++ /dev/null @@ -1,38 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.NoopContextManager = void 0; -const context_1 = require("./context"); -class NoopContextManager { - active() { - return context_1.ROOT_CONTEXT; - } - with(_context, fn, thisArg, ...args) { - return fn.call(thisArg, ...args); - } - bind(_context, target) { - return target; - } - enable() { - return this; - } - disable() { - return this; - } -} -exports.NoopContextManager = NoopContextManager; -//# sourceMappingURL=NoopContextManager.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/context/context.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/context/context.js deleted file mode 100644 index eecc1593..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/context/context.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ROOT_CONTEXT = exports.createContextKey = void 0; -/** Get a key to uniquely identify a context value */ -function createContextKey(description) { - // The specification states that for the same input, multiple calls should - // return different keys. Due to the nature of the JS dependency management - // system, this creates problems where multiple versions of some package - // could hold different keys for the same property. - // - // Therefore, we use Symbol.for which returns the same key for the same input. - return Symbol.for(description); -} -exports.createContextKey = createContextKey; -class BaseContext { - /** - * Construct a new context which inherits values from an optional parent context. - * - * @param parentContext a context from which to inherit values - */ - constructor(parentContext) { - // for minification - const self = this; - self._currentContext = parentContext ? new Map(parentContext) : new Map(); - self.getValue = (key) => self._currentContext.get(key); - self.setValue = (key, value) => { - const context = new BaseContext(self._currentContext); - context._currentContext.set(key, value); - return context; - }; - self.deleteValue = (key) => { - const context = new BaseContext(self._currentContext); - context._currentContext.delete(key); - return context; - }; - } -} -/** The root context is used as the default parent context when there is no active context */ -exports.ROOT_CONTEXT = new BaseContext(); -//# sourceMappingURL=context.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/diag-api.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/diag-api.js deleted file mode 100644 index cbf28db3..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/diag-api.js +++ /dev/null @@ -1,29 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.diag = void 0; -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const diag_1 = require("./api/diag"); -/** - * Entrypoint for Diag API. - * Defines Diagnostic handler used for internal diagnostic logging operations. - * The default provides a Noop DiagLogger implementation which may be changed via the - * diag.setLogger(logger: DiagLogger) function. - */ -exports.diag = diag_1.DiagAPI.instance(); -//# sourceMappingURL=diag-api.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js deleted file mode 100644 index 579b7e68..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/ComponentLogger.js +++ /dev/null @@ -1,59 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DiagComponentLogger = void 0; -const global_utils_1 = require("../internal/global-utils"); -/** - * Component Logger which is meant to be used as part of any component which - * will add automatically additional namespace in front of the log message. - * It will then forward all message to global diag logger - * @example - * const cLogger = diag.createComponentLogger({ namespace: '@opentelemetry/instrumentation-http' }); - * cLogger.debug('test'); - * // @opentelemetry/instrumentation-http test - */ -class DiagComponentLogger { - constructor(props) { - this._namespace = props.namespace || 'DiagComponentLogger'; - } - debug(...args) { - return logProxy('debug', this._namespace, args); - } - error(...args) { - return logProxy('error', this._namespace, args); - } - info(...args) { - return logProxy('info', this._namespace, args); - } - warn(...args) { - return logProxy('warn', this._namespace, args); - } - verbose(...args) { - return logProxy('verbose', this._namespace, args); - } -} -exports.DiagComponentLogger = DiagComponentLogger; -function logProxy(funcName, namespace, args) { - const logger = (0, global_utils_1.getGlobal)('diag'); - // shortcut if logger not set - if (!logger) { - return; - } - args.unshift(namespace); - return logger[funcName](...args); -} -//# sourceMappingURL=ComponentLogger.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js deleted file mode 100644 index 1962275f..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/consoleLogger.js +++ /dev/null @@ -1,57 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DiagConsoleLogger = void 0; -const consoleMap = [ - { n: 'error', c: 'error' }, - { n: 'warn', c: 'warn' }, - { n: 'info', c: 'info' }, - { n: 'debug', c: 'debug' }, - { n: 'verbose', c: 'trace' }, -]; -/** - * A simple Immutable Console based diagnostic logger which will output any messages to the Console. - * If you want to limit the amount of logging to a specific level or lower use the - * {@link createLogLevelDiagLogger} - */ -class DiagConsoleLogger { - constructor() { - function _consoleFunc(funcName) { - return function (...args) { - if (console) { - // Some environments only expose the console when the F12 developer console is open - // eslint-disable-next-line no-console - let theFunc = console[funcName]; - if (typeof theFunc !== 'function') { - // Not all environments support all functions - // eslint-disable-next-line no-console - theFunc = console.log; - } - // One last final check - if (typeof theFunc === 'function') { - return theFunc.apply(console, args); - } - } - }; - } - for (let i = 0; i < consoleMap.length; i++) { - this[consoleMap[i].n] = _consoleFunc(consoleMap[i].c); - } - } -} -exports.DiagConsoleLogger = DiagConsoleLogger; -//# sourceMappingURL=consoleLogger.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js deleted file mode 100644 index ee1702e5..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/internal/logLevelLogger.js +++ /dev/null @@ -1,45 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createLogLevelDiagLogger = void 0; -const types_1 = require("../types"); -function createLogLevelDiagLogger(maxLevel, logger) { - if (maxLevel < types_1.DiagLogLevel.NONE) { - maxLevel = types_1.DiagLogLevel.NONE; - } - else if (maxLevel > types_1.DiagLogLevel.ALL) { - maxLevel = types_1.DiagLogLevel.ALL; - } - // In case the logger is null or undefined - logger = logger || {}; - function _filterFunc(funcName, theLevel) { - const theFunc = logger[funcName]; - if (typeof theFunc === 'function' && maxLevel >= theLevel) { - return theFunc.bind(logger); - } - return function () { }; - } - return { - error: _filterFunc('error', types_1.DiagLogLevel.ERROR), - warn: _filterFunc('warn', types_1.DiagLogLevel.WARN), - info: _filterFunc('info', types_1.DiagLogLevel.INFO), - debug: _filterFunc('debug', types_1.DiagLogLevel.DEBUG), - verbose: _filterFunc('verbose', types_1.DiagLogLevel.VERBOSE), - }; -} -exports.createLogLevelDiagLogger = createLogLevelDiagLogger; -//# sourceMappingURL=logLevelLogger.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/types.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/types.js deleted file mode 100644 index c195e45e..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/diag/types.js +++ /dev/null @@ -1,44 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DiagLogLevel = void 0; -/** - * Defines the available internal logging levels for the diagnostic logger, the numeric values - * of the levels are defined to match the original values from the initial LogLevel to avoid - * compatibility/migration issues for any implementation that assume the numeric ordering. - */ -var DiagLogLevel; -(function (DiagLogLevel) { - /** Diagnostic Logging level setting to disable all logging (except and forced logs) */ - DiagLogLevel[DiagLogLevel["NONE"] = 0] = "NONE"; - /** Identifies an error scenario */ - DiagLogLevel[DiagLogLevel["ERROR"] = 30] = "ERROR"; - /** Identifies a warning scenario */ - DiagLogLevel[DiagLogLevel["WARN"] = 50] = "WARN"; - /** General informational log message */ - DiagLogLevel[DiagLogLevel["INFO"] = 60] = "INFO"; - /** General debug log message */ - DiagLogLevel[DiagLogLevel["DEBUG"] = 70] = "DEBUG"; - /** - * Detailed trace level logging should only be used for development, should only be set - * in a development environment. - */ - DiagLogLevel[DiagLogLevel["VERBOSE"] = 80] = "VERBOSE"; - /** Used to set the logging level to include all logging */ - DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL"; -})(DiagLogLevel = exports.DiagLogLevel || (exports.DiagLogLevel = {})); -//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/index.js deleted file mode 100644 index cb0a8723..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/index.js +++ /dev/null @@ -1,81 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.trace = exports.propagation = exports.metrics = exports.diag = exports.context = exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = exports.isValidSpanId = exports.isValidTraceId = exports.isSpanContextValid = exports.createTraceState = exports.TraceFlags = exports.SpanStatusCode = exports.SpanKind = exports.SamplingDecision = exports.ProxyTracerProvider = exports.ProxyTracer = exports.defaultTextMapSetter = exports.defaultTextMapGetter = exports.ValueType = exports.createNoopMeter = exports.DiagLogLevel = exports.DiagConsoleLogger = exports.ROOT_CONTEXT = exports.createContextKey = exports.baggageEntryMetadataFromString = void 0; -var utils_1 = require("./baggage/utils"); -Object.defineProperty(exports, "baggageEntryMetadataFromString", { enumerable: true, get: function () { return utils_1.baggageEntryMetadataFromString; } }); -// Context APIs -var context_1 = require("./context/context"); -Object.defineProperty(exports, "createContextKey", { enumerable: true, get: function () { return context_1.createContextKey; } }); -Object.defineProperty(exports, "ROOT_CONTEXT", { enumerable: true, get: function () { return context_1.ROOT_CONTEXT; } }); -// Diag APIs -var consoleLogger_1 = require("./diag/consoleLogger"); -Object.defineProperty(exports, "DiagConsoleLogger", { enumerable: true, get: function () { return consoleLogger_1.DiagConsoleLogger; } }); -var types_1 = require("./diag/types"); -Object.defineProperty(exports, "DiagLogLevel", { enumerable: true, get: function () { return types_1.DiagLogLevel; } }); -// Metrics APIs -var NoopMeter_1 = require("./metrics/NoopMeter"); -Object.defineProperty(exports, "createNoopMeter", { enumerable: true, get: function () { return NoopMeter_1.createNoopMeter; } }); -var Metric_1 = require("./metrics/Metric"); -Object.defineProperty(exports, "ValueType", { enumerable: true, get: function () { return Metric_1.ValueType; } }); -// Propagation APIs -var TextMapPropagator_1 = require("./propagation/TextMapPropagator"); -Object.defineProperty(exports, "defaultTextMapGetter", { enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapGetter; } }); -Object.defineProperty(exports, "defaultTextMapSetter", { enumerable: true, get: function () { return TextMapPropagator_1.defaultTextMapSetter; } }); -var ProxyTracer_1 = require("./trace/ProxyTracer"); -Object.defineProperty(exports, "ProxyTracer", { enumerable: true, get: function () { return ProxyTracer_1.ProxyTracer; } }); -var ProxyTracerProvider_1 = require("./trace/ProxyTracerProvider"); -Object.defineProperty(exports, "ProxyTracerProvider", { enumerable: true, get: function () { return ProxyTracerProvider_1.ProxyTracerProvider; } }); -var SamplingResult_1 = require("./trace/SamplingResult"); -Object.defineProperty(exports, "SamplingDecision", { enumerable: true, get: function () { return SamplingResult_1.SamplingDecision; } }); -var span_kind_1 = require("./trace/span_kind"); -Object.defineProperty(exports, "SpanKind", { enumerable: true, get: function () { return span_kind_1.SpanKind; } }); -var status_1 = require("./trace/status"); -Object.defineProperty(exports, "SpanStatusCode", { enumerable: true, get: function () { return status_1.SpanStatusCode; } }); -var trace_flags_1 = require("./trace/trace_flags"); -Object.defineProperty(exports, "TraceFlags", { enumerable: true, get: function () { return trace_flags_1.TraceFlags; } }); -var utils_2 = require("./trace/internal/utils"); -Object.defineProperty(exports, "createTraceState", { enumerable: true, get: function () { return utils_2.createTraceState; } }); -var spancontext_utils_1 = require("./trace/spancontext-utils"); -Object.defineProperty(exports, "isSpanContextValid", { enumerable: true, get: function () { return spancontext_utils_1.isSpanContextValid; } }); -Object.defineProperty(exports, "isValidTraceId", { enumerable: true, get: function () { return spancontext_utils_1.isValidTraceId; } }); -Object.defineProperty(exports, "isValidSpanId", { enumerable: true, get: function () { return spancontext_utils_1.isValidSpanId; } }); -var invalid_span_constants_1 = require("./trace/invalid-span-constants"); -Object.defineProperty(exports, "INVALID_SPANID", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPANID; } }); -Object.defineProperty(exports, "INVALID_TRACEID", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_TRACEID; } }); -Object.defineProperty(exports, "INVALID_SPAN_CONTEXT", { enumerable: true, get: function () { return invalid_span_constants_1.INVALID_SPAN_CONTEXT; } }); -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const context_api_1 = require("./context-api"); -Object.defineProperty(exports, "context", { enumerable: true, get: function () { return context_api_1.context; } }); -const diag_api_1 = require("./diag-api"); -Object.defineProperty(exports, "diag", { enumerable: true, get: function () { return diag_api_1.diag; } }); -const metrics_api_1 = require("./metrics-api"); -Object.defineProperty(exports, "metrics", { enumerable: true, get: function () { return metrics_api_1.metrics; } }); -const propagation_api_1 = require("./propagation-api"); -Object.defineProperty(exports, "propagation", { enumerable: true, get: function () { return propagation_api_1.propagation; } }); -const trace_api_1 = require("./trace-api"); -Object.defineProperty(exports, "trace", { enumerable: true, get: function () { return trace_api_1.trace; } }); -// Default export. -exports.default = { - context: context_api_1.context, - diag: diag_api_1.diag, - metrics: metrics_api_1.metrics, - propagation: propagation_api_1.propagation, - trace: trace_api_1.trace, -}; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/internal/global-utils.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/internal/global-utils.js deleted file mode 100644 index 11a1a441..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/internal/global-utils.js +++ /dev/null @@ -1,64 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.unregisterGlobal = exports.getGlobal = exports.registerGlobal = void 0; -const platform_1 = require("../platform"); -const version_1 = require("../version"); -const semver_1 = require("./semver"); -const major = version_1.VERSION.split('.')[0]; -const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`); -const _global = platform_1._globalThis; -function registerGlobal(type, instance, diag, allowOverride = false) { - var _a; - const api = (_global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { - version: version_1.VERSION, - }); - if (!allowOverride && api[type]) { - // already registered an API of this type - const err = new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`); - diag.error(err.stack || err.message); - return false; - } - if (api.version !== version_1.VERSION) { - // All registered APIs must be of the same version exactly - const err = new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${version_1.VERSION}`); - diag.error(err.stack || err.message); - return false; - } - api[type] = instance; - diag.debug(`@opentelemetry/api: Registered a global for ${type} v${version_1.VERSION}.`); - return true; -} -exports.registerGlobal = registerGlobal; -function getGlobal(type) { - var _a, _b; - const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version; - if (!globalVersion || !(0, semver_1.isCompatible)(globalVersion)) { - return; - } - return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type]; -} -exports.getGlobal = getGlobal; -function unregisterGlobal(type, diag) { - diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${version_1.VERSION}.`); - const api = _global[GLOBAL_OPENTELEMETRY_API_KEY]; - if (api) { - delete api[type]; - } -} -exports.unregisterGlobal = unregisterGlobal; -//# sourceMappingURL=global-utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/internal/semver.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/internal/semver.js deleted file mode 100644 index 7a073b22..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/internal/semver.js +++ /dev/null @@ -1,122 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isCompatible = exports._makeCompatibilityCheck = void 0; -const version_1 = require("../version"); -const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/; -/** - * Create a function to test an API version to see if it is compatible with the provided ownVersion. - * - * The returned function has the following semantics: - * - Exact match is always compatible - * - Major versions must match exactly - * - 1.x package cannot use global 2.x package - * - 2.x package cannot use global 1.x package - * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API - * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects - * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 - * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor - * - Patch and build tag differences are not considered at this time - * - * @param ownVersion version which should be checked against - */ -function _makeCompatibilityCheck(ownVersion) { - const acceptedVersions = new Set([ownVersion]); - const rejectedVersions = new Set(); - const myVersionMatch = ownVersion.match(re); - if (!myVersionMatch) { - // we cannot guarantee compatibility so we always return noop - return () => false; - } - const ownVersionParsed = { - major: +myVersionMatch[1], - minor: +myVersionMatch[2], - patch: +myVersionMatch[3], - prerelease: myVersionMatch[4], - }; - // if ownVersion has a prerelease tag, versions must match exactly - if (ownVersionParsed.prerelease != null) { - return function isExactmatch(globalVersion) { - return globalVersion === ownVersion; - }; - } - function _reject(v) { - rejectedVersions.add(v); - return false; - } - function _accept(v) { - acceptedVersions.add(v); - return true; - } - return function isCompatible(globalVersion) { - if (acceptedVersions.has(globalVersion)) { - return true; - } - if (rejectedVersions.has(globalVersion)) { - return false; - } - const globalVersionMatch = globalVersion.match(re); - if (!globalVersionMatch) { - // cannot parse other version - // we cannot guarantee compatibility so we always noop - return _reject(globalVersion); - } - const globalVersionParsed = { - major: +globalVersionMatch[1], - minor: +globalVersionMatch[2], - patch: +globalVersionMatch[3], - prerelease: globalVersionMatch[4], - }; - // if globalVersion has a prerelease tag, versions must match exactly - if (globalVersionParsed.prerelease != null) { - return _reject(globalVersion); - } - // major versions must match - if (ownVersionParsed.major !== globalVersionParsed.major) { - return _reject(globalVersion); - } - if (ownVersionParsed.major === 0) { - if (ownVersionParsed.minor === globalVersionParsed.minor && - ownVersionParsed.patch <= globalVersionParsed.patch) { - return _accept(globalVersion); - } - return _reject(globalVersion); - } - if (ownVersionParsed.minor <= globalVersionParsed.minor) { - return _accept(globalVersion); - } - return _reject(globalVersion); - }; -} -exports._makeCompatibilityCheck = _makeCompatibilityCheck; -/** - * Test an API version to see if it is compatible with this API. - * - * - Exact match is always compatible - * - Major versions must match exactly - * - 1.x package cannot use global 2.x package - * - 2.x package cannot use global 1.x package - * - The minor version of the API module requesting access to the global API must be less than or equal to the minor version of this API - * - 1.3 package may use 1.4 global because the later global contains all functions 1.3 expects - * - 1.4 package may NOT use 1.3 global because it may try to call functions which don't exist on 1.3 - * - If the major version is 0, the minor version is treated as the major and the patch is treated as the minor - * - Patch and build tag differences are not considered at this time - * - * @param version version of the API requesting an instance of the global API - */ -exports.isCompatible = _makeCompatibilityCheck(version_1.VERSION); -//# sourceMappingURL=semver.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics-api.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics-api.js deleted file mode 100644 index 987f7c25..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics-api.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.metrics = void 0; -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const metrics_1 = require("./api/metrics"); -/** Entrypoint for metrics API */ -exports.metrics = metrics_1.MetricsAPI.getInstance(); -//# sourceMappingURL=metrics-api.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/Metric.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/Metric.js deleted file mode 100644 index 4966c3d5..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/Metric.js +++ /dev/null @@ -1,25 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ValueType = void 0; -/** The Type of value. It describes how the data is reported. */ -var ValueType; -(function (ValueType) { - ValueType[ValueType["INT"] = 0] = "INT"; - ValueType[ValueType["DOUBLE"] = 1] = "DOUBLE"; -})(ValueType = exports.ValueType || (exports.ValueType = {})); -//# sourceMappingURL=Metric.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js deleted file mode 100644 index d40ef036..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/NoopMeter.js +++ /dev/null @@ -1,127 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createNoopMeter = exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = exports.NOOP_OBSERVABLE_GAUGE_METRIC = exports.NOOP_OBSERVABLE_COUNTER_METRIC = exports.NOOP_UP_DOWN_COUNTER_METRIC = exports.NOOP_HISTOGRAM_METRIC = exports.NOOP_GAUGE_METRIC = exports.NOOP_COUNTER_METRIC = exports.NOOP_METER = exports.NoopObservableUpDownCounterMetric = exports.NoopObservableGaugeMetric = exports.NoopObservableCounterMetric = exports.NoopObservableMetric = exports.NoopHistogramMetric = exports.NoopGaugeMetric = exports.NoopUpDownCounterMetric = exports.NoopCounterMetric = exports.NoopMetric = exports.NoopMeter = void 0; -/** - * NoopMeter is a noop implementation of the {@link Meter} interface. It reuses - * constant NoopMetrics for all of its methods. - */ -class NoopMeter { - constructor() { } - /** - * @see {@link Meter.createGauge} - */ - createGauge(_name, _options) { - return exports.NOOP_GAUGE_METRIC; - } - /** - * @see {@link Meter.createHistogram} - */ - createHistogram(_name, _options) { - return exports.NOOP_HISTOGRAM_METRIC; - } - /** - * @see {@link Meter.createCounter} - */ - createCounter(_name, _options) { - return exports.NOOP_COUNTER_METRIC; - } - /** - * @see {@link Meter.createUpDownCounter} - */ - createUpDownCounter(_name, _options) { - return exports.NOOP_UP_DOWN_COUNTER_METRIC; - } - /** - * @see {@link Meter.createObservableGauge} - */ - createObservableGauge(_name, _options) { - return exports.NOOP_OBSERVABLE_GAUGE_METRIC; - } - /** - * @see {@link Meter.createObservableCounter} - */ - createObservableCounter(_name, _options) { - return exports.NOOP_OBSERVABLE_COUNTER_METRIC; - } - /** - * @see {@link Meter.createObservableUpDownCounter} - */ - createObservableUpDownCounter(_name, _options) { - return exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC; - } - /** - * @see {@link Meter.addBatchObservableCallback} - */ - addBatchObservableCallback(_callback, _observables) { } - /** - * @see {@link Meter.removeBatchObservableCallback} - */ - removeBatchObservableCallback(_callback) { } -} -exports.NoopMeter = NoopMeter; -class NoopMetric { -} -exports.NoopMetric = NoopMetric; -class NoopCounterMetric extends NoopMetric { - add(_value, _attributes) { } -} -exports.NoopCounterMetric = NoopCounterMetric; -class NoopUpDownCounterMetric extends NoopMetric { - add(_value, _attributes) { } -} -exports.NoopUpDownCounterMetric = NoopUpDownCounterMetric; -class NoopGaugeMetric extends NoopMetric { - record(_value, _attributes) { } -} -exports.NoopGaugeMetric = NoopGaugeMetric; -class NoopHistogramMetric extends NoopMetric { - record(_value, _attributes) { } -} -exports.NoopHistogramMetric = NoopHistogramMetric; -class NoopObservableMetric { - addCallback(_callback) { } - removeCallback(_callback) { } -} -exports.NoopObservableMetric = NoopObservableMetric; -class NoopObservableCounterMetric extends NoopObservableMetric { -} -exports.NoopObservableCounterMetric = NoopObservableCounterMetric; -class NoopObservableGaugeMetric extends NoopObservableMetric { -} -exports.NoopObservableGaugeMetric = NoopObservableGaugeMetric; -class NoopObservableUpDownCounterMetric extends NoopObservableMetric { -} -exports.NoopObservableUpDownCounterMetric = NoopObservableUpDownCounterMetric; -exports.NOOP_METER = new NoopMeter(); -// Synchronous instruments -exports.NOOP_COUNTER_METRIC = new NoopCounterMetric(); -exports.NOOP_GAUGE_METRIC = new NoopGaugeMetric(); -exports.NOOP_HISTOGRAM_METRIC = new NoopHistogramMetric(); -exports.NOOP_UP_DOWN_COUNTER_METRIC = new NoopUpDownCounterMetric(); -// Asynchronous instruments -exports.NOOP_OBSERVABLE_COUNTER_METRIC = new NoopObservableCounterMetric(); -exports.NOOP_OBSERVABLE_GAUGE_METRIC = new NoopObservableGaugeMetric(); -exports.NOOP_OBSERVABLE_UP_DOWN_COUNTER_METRIC = new NoopObservableUpDownCounterMetric(); -/** - * Create a no-op Meter - */ -function createNoopMeter() { - return exports.NOOP_METER; -} -exports.createNoopMeter = createNoopMeter; -//# sourceMappingURL=NoopMeter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js deleted file mode 100644 index b1c1cc06..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/metrics/NoopMeterProvider.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.NOOP_METER_PROVIDER = exports.NoopMeterProvider = void 0; -const NoopMeter_1 = require("./NoopMeter"); -/** - * An implementation of the {@link MeterProvider} which returns an impotent Meter - * for all calls to `getMeter` - */ -class NoopMeterProvider { - getMeter(_name, _version, _options) { - return NoopMeter_1.NOOP_METER; - } -} -exports.NoopMeterProvider = NoopMeterProvider; -exports.NOOP_METER_PROVIDER = new NoopMeterProvider(); -//# sourceMappingURL=NoopMeterProvider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/platform/index.js deleted file mode 100644 index 33b834db..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/platform/index.js +++ /dev/null @@ -1,29 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -__exportStar(require("./node"), exports); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/platform/node/globalThis.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/platform/node/globalThis.js deleted file mode 100644 index 82c4e394..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/platform/node/globalThis.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports._globalThis = void 0; -/** only globals that common to node and browsers are allowed */ -// eslint-disable-next-line node/no-unsupported-features/es-builtins -exports._globalThis = typeof globalThis === 'object' ? globalThis : global; -//# sourceMappingURL=globalThis.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/platform/node/index.js deleted file mode 100644 index 99fd57c8..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/platform/node/index.js +++ /dev/null @@ -1,29 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -__exportStar(require("./globalThis"), exports); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/propagation-api.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/propagation-api.js deleted file mode 100644 index f014fb4a..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/propagation-api.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.propagation = void 0; -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const propagation_1 = require("./api/propagation"); -/** Entrypoint for propagation API */ -exports.propagation = propagation_1.PropagationAPI.getInstance(); -//# sourceMappingURL=propagation-api.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js deleted file mode 100644 index 3f395829..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/propagation/NoopTextMapPropagator.js +++ /dev/null @@ -1,34 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.NoopTextMapPropagator = void 0; -/** - * No-op implementations of {@link TextMapPropagator}. - */ -class NoopTextMapPropagator { - /** Noop inject function does nothing */ - inject(_context, _carrier) { } - /** Noop extract function does nothing and returns the input context */ - extract(context, _carrier) { - return context; - } - fields() { - return []; - } -} -exports.NoopTextMapPropagator = NoopTextMapPropagator; -//# sourceMappingURL=NoopTextMapPropagator.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js deleted file mode 100644 index 513f33c6..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/propagation/TextMapPropagator.js +++ /dev/null @@ -1,41 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.defaultTextMapSetter = exports.defaultTextMapGetter = void 0; -exports.defaultTextMapGetter = { - get(carrier, key) { - if (carrier == null) { - return undefined; - } - return carrier[key]; - }, - keys(carrier) { - if (carrier == null) { - return []; - } - return Object.keys(carrier); - }, -}; -exports.defaultTextMapSetter = { - set(carrier, key, value) { - if (carrier == null) { - return; - } - carrier[key] = value; - }, -}; -//# sourceMappingURL=TextMapPropagator.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace-api.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace-api.js deleted file mode 100644 index c8bbe93a..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace-api.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.trace = void 0; -// Split module-level variable definition into separate files to allow -// tree-shaking on each api instance. -const trace_1 = require("./api/trace"); -/** Entrypoint for trace API */ -exports.trace = trace_1.TraceAPI.getInstance(); -//# sourceMappingURL=trace-api.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js deleted file mode 100644 index 6d3e6eea..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NonRecordingSpan.js +++ /dev/null @@ -1,69 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.NonRecordingSpan = void 0; -const invalid_span_constants_1 = require("./invalid-span-constants"); -/** - * The NonRecordingSpan is the default {@link Span} that is used when no Span - * implementation is available. All operations are no-op including context - * propagation. - */ -class NonRecordingSpan { - constructor(_spanContext = invalid_span_constants_1.INVALID_SPAN_CONTEXT) { - this._spanContext = _spanContext; - } - // Returns a SpanContext. - spanContext() { - return this._spanContext; - } - // By default does nothing - setAttribute(_key, _value) { - return this; - } - // By default does nothing - setAttributes(_attributes) { - return this; - } - // By default does nothing - addEvent(_name, _attributes) { - return this; - } - addLink(_link) { - return this; - } - addLinks(_links) { - return this; - } - // By default does nothing - setStatus(_status) { - return this; - } - // By default does nothing - updateName(_name) { - return this; - } - // By default does nothing - end(_endTime) { } - // isRecording always returns false for NonRecordingSpan. - isRecording() { - return false; - } - // By default does nothing - recordException(_exception, _time) { } -} -exports.NonRecordingSpan = NonRecordingSpan; -//# sourceMappingURL=NonRecordingSpan.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js deleted file mode 100644 index 0a823aa5..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NoopTracer.js +++ /dev/null @@ -1,75 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.NoopTracer = void 0; -const context_1 = require("../api/context"); -const context_utils_1 = require("../trace/context-utils"); -const NonRecordingSpan_1 = require("./NonRecordingSpan"); -const spancontext_utils_1 = require("./spancontext-utils"); -const contextApi = context_1.ContextAPI.getInstance(); -/** - * No-op implementations of {@link Tracer}. - */ -class NoopTracer { - // startSpan starts a noop span. - startSpan(name, options, context = contextApi.active()) { - const root = Boolean(options === null || options === void 0 ? void 0 : options.root); - if (root) { - return new NonRecordingSpan_1.NonRecordingSpan(); - } - const parentFromContext = context && (0, context_utils_1.getSpanContext)(context); - if (isSpanContext(parentFromContext) && - (0, spancontext_utils_1.isSpanContextValid)(parentFromContext)) { - return new NonRecordingSpan_1.NonRecordingSpan(parentFromContext); - } - else { - return new NonRecordingSpan_1.NonRecordingSpan(); - } - } - startActiveSpan(name, arg2, arg3, arg4) { - let opts; - let ctx; - let fn; - if (arguments.length < 2) { - return; - } - else if (arguments.length === 2) { - fn = arg2; - } - else if (arguments.length === 3) { - opts = arg2; - fn = arg3; - } - else { - opts = arg2; - ctx = arg3; - fn = arg4; - } - const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active(); - const span = this.startSpan(name, opts, parentContext); - const contextWithSpanSet = (0, context_utils_1.setSpan)(parentContext, span); - return contextApi.with(contextWithSpanSet, fn, undefined, span); - } -} -exports.NoopTracer = NoopTracer; -function isSpanContext(spanContext) { - return (typeof spanContext === 'object' && - typeof spanContext['spanId'] === 'string' && - typeof spanContext['traceId'] === 'string' && - typeof spanContext['traceFlags'] === 'number'); -} -//# sourceMappingURL=NoopTracer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js deleted file mode 100644 index c9e08d63..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/NoopTracerProvider.js +++ /dev/null @@ -1,32 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.NoopTracerProvider = void 0; -const NoopTracer_1 = require("./NoopTracer"); -/** - * An implementation of the {@link TracerProvider} which returns an impotent - * Tracer for all calls to `getTracer`. - * - * All operations are no-op. - */ -class NoopTracerProvider { - getTracer(_name, _version, _options) { - return new NoopTracer_1.NoopTracer(); - } -} -exports.NoopTracerProvider = NoopTracerProvider; -//# sourceMappingURL=NoopTracerProvider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js deleted file mode 100644 index 66776801..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/ProxyTracer.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ProxyTracer = void 0; -const NoopTracer_1 = require("./NoopTracer"); -const NOOP_TRACER = new NoopTracer_1.NoopTracer(); -/** - * Proxy tracer provided by the proxy tracer provider - */ -class ProxyTracer { - constructor(_provider, name, version, options) { - this._provider = _provider; - this.name = name; - this.version = version; - this.options = options; - } - startSpan(name, options, context) { - return this._getTracer().startSpan(name, options, context); - } - startActiveSpan(_name, _options, _context, _fn) { - const tracer = this._getTracer(); - return Reflect.apply(tracer.startActiveSpan, tracer, arguments); - } - /** - * Try to get a tracer from the proxy tracer provider. - * If the proxy tracer provider has no delegate, return a noop tracer. - */ - _getTracer() { - if (this._delegate) { - return this._delegate; - } - const tracer = this._provider.getDelegateTracer(this.name, this.version, this.options); - if (!tracer) { - return NOOP_TRACER; - } - this._delegate = tracer; - return this._delegate; - } -} -exports.ProxyTracer = ProxyTracer; -//# sourceMappingURL=ProxyTracer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js deleted file mode 100644 index 75ec910d..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/ProxyTracerProvider.js +++ /dev/null @@ -1,54 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ProxyTracerProvider = void 0; -const ProxyTracer_1 = require("./ProxyTracer"); -const NoopTracerProvider_1 = require("./NoopTracerProvider"); -const NOOP_TRACER_PROVIDER = new NoopTracerProvider_1.NoopTracerProvider(); -/** - * Tracer provider which provides {@link ProxyTracer}s. - * - * Before a delegate is set, tracers provided are NoOp. - * When a delegate is set, traces are provided from the delegate. - * When a delegate is set after tracers have already been provided, - * all tracers already provided will use the provided delegate implementation. - */ -class ProxyTracerProvider { - /** - * Get a {@link ProxyTracer} - */ - getTracer(name, version, options) { - var _a; - return ((_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer_1.ProxyTracer(this, name, version, options)); - } - getDelegate() { - var _a; - return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER; - } - /** - * Set the delegate tracer provider - */ - setDelegate(delegate) { - this._delegate = delegate; - } - getDelegateTracer(name, version, options) { - var _a; - return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options); - } -} -exports.ProxyTracerProvider = ProxyTracerProvider; -//# sourceMappingURL=ProxyTracerProvider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js deleted file mode 100644 index 6df6b3bf..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/SamplingResult.js +++ /dev/null @@ -1,42 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SamplingDecision = void 0; -/** - * @deprecated use the one declared in @opentelemetry/sdk-trace-base instead. - * A sampling decision that determines how a {@link Span} will be recorded - * and collected. - */ -var SamplingDecision; -(function (SamplingDecision) { - /** - * `Span.isRecording() === false`, span will not be recorded and all events - * and attributes will be dropped. - */ - SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD"; - /** - * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} - * MUST NOT be set. - */ - SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD"; - /** - * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} - * MUST be set. - */ - SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; -})(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {})); -//# sourceMappingURL=SamplingResult.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/context-utils.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/context-utils.js deleted file mode 100644 index d7e9c3a3..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/context-utils.js +++ /dev/null @@ -1,82 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getSpanContext = exports.setSpanContext = exports.deleteSpan = exports.setSpan = exports.getActiveSpan = exports.getSpan = void 0; -const context_1 = require("../context/context"); -const NonRecordingSpan_1 = require("./NonRecordingSpan"); -const context_2 = require("../api/context"); -/** - * span key - */ -const SPAN_KEY = (0, context_1.createContextKey)('OpenTelemetry Context Key SPAN'); -/** - * Return the span if one exists - * - * @param context context to get span from - */ -function getSpan(context) { - return context.getValue(SPAN_KEY) || undefined; -} -exports.getSpan = getSpan; -/** - * Gets the span from the current context, if one exists. - */ -function getActiveSpan() { - return getSpan(context_2.ContextAPI.getInstance().active()); -} -exports.getActiveSpan = getActiveSpan; -/** - * Set the span on a context - * - * @param context context to use as parent - * @param span span to set active - */ -function setSpan(context, span) { - return context.setValue(SPAN_KEY, span); -} -exports.setSpan = setSpan; -/** - * Remove current span stored in the context - * - * @param context context to delete span from - */ -function deleteSpan(context) { - return context.deleteValue(SPAN_KEY); -} -exports.deleteSpan = deleteSpan; -/** - * Wrap span context in a NoopSpan and set as span in a new - * context - * - * @param context context to set active span on - * @param spanContext span context to be wrapped - */ -function setSpanContext(context, spanContext) { - return setSpan(context, new NonRecordingSpan_1.NonRecordingSpan(spanContext)); -} -exports.setSpanContext = setSpanContext; -/** - * Get the span context of the span if it exists. - * - * @param context context to get values from - */ -function getSpanContext(context) { - var _a; - return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext(); -} -exports.getSpanContext = getSpanContext; -//# sourceMappingURL=context-utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js deleted file mode 100644 index 93c0289c..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-impl.js +++ /dev/null @@ -1,103 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TraceStateImpl = void 0; -const tracestate_validators_1 = require("./tracestate-validators"); -const MAX_TRACE_STATE_ITEMS = 32; -const MAX_TRACE_STATE_LEN = 512; -const LIST_MEMBERS_SEPARATOR = ','; -const LIST_MEMBER_KEY_VALUE_SPLITTER = '='; -/** - * TraceState must be a class and not a simple object type because of the spec - * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). - * - * Here is the list of allowed mutations: - * - New key-value pair should be added into the beginning of the list - * - The value of any key can be updated. Modified keys MUST be moved to the - * beginning of the list. - */ -class TraceStateImpl { - constructor(rawTraceState) { - this._internalState = new Map(); - if (rawTraceState) - this._parse(rawTraceState); - } - set(key, value) { - // TODO: Benchmark the different approaches(map vs list) and - // use the faster one. - const traceState = this._clone(); - if (traceState._internalState.has(key)) { - traceState._internalState.delete(key); - } - traceState._internalState.set(key, value); - return traceState; - } - unset(key) { - const traceState = this._clone(); - traceState._internalState.delete(key); - return traceState; - } - get(key) { - return this._internalState.get(key); - } - serialize() { - return this._keys() - .reduce((agg, key) => { - agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); - return agg; - }, []) - .join(LIST_MEMBERS_SEPARATOR); - } - _parse(rawTraceState) { - if (rawTraceState.length > MAX_TRACE_STATE_LEN) - return; - this._internalState = rawTraceState - .split(LIST_MEMBERS_SEPARATOR) - .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning - .reduce((agg, part) => { - const listMember = part.trim(); // Optional Whitespace (OWS) handling - const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); - if (i !== -1) { - const key = listMember.slice(0, i); - const value = listMember.slice(i + 1, part.length); - if ((0, tracestate_validators_1.validateKey)(key) && (0, tracestate_validators_1.validateValue)(value)) { - agg.set(key, value); - } - else { - // TODO: Consider to add warning log - } - } - return agg; - }, new Map()); - // Because of the reverse() requirement, trunc must be done after map is created - if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { - this._internalState = new Map(Array.from(this._internalState.entries()) - .reverse() // Use reverse same as original tracestate parse chain - .slice(0, MAX_TRACE_STATE_ITEMS)); - } - } - _keys() { - return Array.from(this._internalState.keys()).reverse(); - } - _clone() { - const traceState = new TraceStateImpl(); - traceState._internalState = new Map(this._internalState); - return traceState; - } -} -exports.TraceStateImpl = TraceStateImpl; -//# sourceMappingURL=tracestate-impl.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.js deleted file mode 100644 index 3e370449..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/tracestate-validators.js +++ /dev/null @@ -1,46 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.validateValue = exports.validateKey = void 0; -const VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]'; -const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; -const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; -const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); -const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; -const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; -/** - * Key is opaque string up to 256 characters printable. It MUST begin with a - * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, - * underscores _, dashes -, asterisks *, and forward slashes /. - * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the - * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. - * see https://www.w3.org/TR/trace-context/#key - */ -function validateKey(key) { - return VALID_KEY_REGEX.test(key); -} -exports.validateKey = validateKey; -/** - * Value is opaque string up to 256 characters printable ASCII RFC0020 - * characters (i.e., the range 0x20 to 0x7E) except comma , and =. - */ -function validateValue(value) { - return (VALID_VALUE_BASE_REGEX.test(value) && - !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)); -} -exports.validateValue = validateValue; -//# sourceMappingURL=tracestate-validators.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/utils.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/utils.js deleted file mode 100644 index 3d954190..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/internal/utils.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createTraceState = void 0; -const tracestate_impl_1 = require("./tracestate-impl"); -function createTraceState(rawTraceState) { - return new tracestate_impl_1.TraceStateImpl(rawTraceState); -} -exports.createTraceState = createTraceState; -//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js deleted file mode 100644 index 77fb79e9..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/invalid-span-constants.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.INVALID_SPAN_CONTEXT = exports.INVALID_TRACEID = exports.INVALID_SPANID = void 0; -const trace_flags_1 = require("./trace_flags"); -exports.INVALID_SPANID = '0000000000000000'; -exports.INVALID_TRACEID = '00000000000000000000000000000000'; -exports.INVALID_SPAN_CONTEXT = { - traceId: exports.INVALID_TRACEID, - spanId: exports.INVALID_SPANID, - traceFlags: trace_flags_1.TraceFlags.NONE, -}; -//# sourceMappingURL=invalid-span-constants.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/span_kind.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/span_kind.js deleted file mode 100644 index 9c06e2c2..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/span_kind.js +++ /dev/null @@ -1,46 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpanKind = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var SpanKind; -(function (SpanKind) { - /** Default value. Indicates that the span is used internally. */ - SpanKind[SpanKind["INTERNAL"] = 0] = "INTERNAL"; - /** - * Indicates that the span covers server-side handling of an RPC or other - * remote request. - */ - SpanKind[SpanKind["SERVER"] = 1] = "SERVER"; - /** - * Indicates that the span covers the client-side wrapper around an RPC or - * other remote request. - */ - SpanKind[SpanKind["CLIENT"] = 2] = "CLIENT"; - /** - * Indicates that the span describes producer sending a message to a - * broker. Unlike client and server, there is no direct critical path latency - * relationship between producer and consumer spans. - */ - SpanKind[SpanKind["PRODUCER"] = 3] = "PRODUCER"; - /** - * Indicates that the span describes consumer receiving a message from a - * broker. Unlike client and server, there is no direct critical path latency - * relationship between producer and consumer spans. - */ - SpanKind[SpanKind["CONSUMER"] = 4] = "CONSUMER"; -})(SpanKind = exports.SpanKind || (exports.SpanKind = {})); -//# sourceMappingURL=span_kind.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js deleted file mode 100644 index dc88f5e6..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/spancontext-utils.js +++ /dev/null @@ -1,49 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.wrapSpanContext = exports.isSpanContextValid = exports.isValidSpanId = exports.isValidTraceId = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const invalid_span_constants_1 = require("./invalid-span-constants"); -const NonRecordingSpan_1 = require("./NonRecordingSpan"); -const VALID_TRACEID_REGEX = /^([0-9a-f]{32})$/i; -const VALID_SPANID_REGEX = /^[0-9a-f]{16}$/i; -function isValidTraceId(traceId) { - return VALID_TRACEID_REGEX.test(traceId) && traceId !== invalid_span_constants_1.INVALID_TRACEID; -} -exports.isValidTraceId = isValidTraceId; -function isValidSpanId(spanId) { - return VALID_SPANID_REGEX.test(spanId) && spanId !== invalid_span_constants_1.INVALID_SPANID; -} -exports.isValidSpanId = isValidSpanId; -/** - * Returns true if this {@link SpanContext} is valid. - * @return true if this {@link SpanContext} is valid. - */ -function isSpanContextValid(spanContext) { - return (isValidTraceId(spanContext.traceId) && isValidSpanId(spanContext.spanId)); -} -exports.isSpanContextValid = isSpanContextValid; -/** - * Wrap the given {@link SpanContext} in a new non-recording {@link Span} - * - * @param spanContext span context to be wrapped - * @returns a new non-recording {@link Span} with the provided context - */ -function wrapSpanContext(spanContext) { - return new NonRecordingSpan_1.NonRecordingSpan(spanContext); -} -exports.wrapSpanContext = wrapSpanContext; -//# sourceMappingURL=spancontext-utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/status.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/status.js deleted file mode 100644 index 50cbdef8..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/status.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpanStatusCode = void 0; -/** - * An enumeration of status codes. - */ -var SpanStatusCode; -(function (SpanStatusCode) { - /** - * The default status. - */ - SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET"; - /** - * The operation has been validated by an Application developer or - * Operator to have completed successfully. - */ - SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK"; - /** - * The operation contains an error. - */ - SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR"; -})(SpanStatusCode = exports.SpanStatusCode || (exports.SpanStatusCode = {})); -//# sourceMappingURL=status.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/trace_flags.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/trace_flags.js deleted file mode 100644 index f8d4dd8a..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/trace/trace_flags.js +++ /dev/null @@ -1,26 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TraceFlags = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var TraceFlags; -(function (TraceFlags) { - /** Represents no flag set. */ - TraceFlags[TraceFlags["NONE"] = 0] = "NONE"; - /** Bit to represent whether trace is sampled in trace flags. */ - TraceFlags[TraceFlags["SAMPLED"] = 1] = "SAMPLED"; -})(TraceFlags = exports.TraceFlags || (exports.TraceFlags = {})); -//# sourceMappingURL=trace_flags.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/api/build/src/version.js b/claude-code-source/node_modules/@opentelemetry/api/build/src/version.js deleted file mode 100644 index 3c717941..00000000 --- a/claude-code-source/node_modules/@opentelemetry/api/build/src/version.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.VERSION = void 0; -// this is autogenerated file, see scripts/version-update.js -exports.VERSION = '1.9.0'; -//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/ExportResult.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/ExportResult.js deleted file mode 100644 index 724d006d..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/ExportResult.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ExportResultCode = void 0; -var ExportResultCode; -(function (ExportResultCode) { - ExportResultCode[ExportResultCode["SUCCESS"] = 0] = "SUCCESS"; - ExportResultCode[ExportResultCode["FAILED"] = 1] = "FAILED"; -})(ExportResultCode = exports.ExportResultCode || (exports.ExportResultCode = {})); -//# sourceMappingURL=ExportResult.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/constants.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/constants.js deleted file mode 100644 index 88dcfcef..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/constants.js +++ /dev/null @@ -1,30 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BAGGAGE_MAX_TOTAL_LENGTH = exports.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = exports.BAGGAGE_MAX_NAME_VALUE_PAIRS = exports.BAGGAGE_HEADER = exports.BAGGAGE_ITEMS_SEPARATOR = exports.BAGGAGE_PROPERTIES_SEPARATOR = exports.BAGGAGE_KEY_PAIR_SEPARATOR = void 0; -exports.BAGGAGE_KEY_PAIR_SEPARATOR = '='; -exports.BAGGAGE_PROPERTIES_SEPARATOR = ';'; -exports.BAGGAGE_ITEMS_SEPARATOR = ','; -// Name of the http header used to propagate the baggage -exports.BAGGAGE_HEADER = 'baggage'; -// Maximum number of name-value pairs allowed by w3c spec -exports.BAGGAGE_MAX_NAME_VALUE_PAIRS = 180; -// Maximum number of bytes per a single name-value pair allowed by w3c spec -exports.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS = 4096; -// Maximum total length of all name-value pairs allowed by w3c spec -exports.BAGGAGE_MAX_TOTAL_LENGTH = 8192; -//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/propagation/W3CBaggagePropagator.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/propagation/W3CBaggagePropagator.js deleted file mode 100644 index d2959501..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/propagation/W3CBaggagePropagator.js +++ /dev/null @@ -1,76 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.W3CBaggagePropagator = void 0; -const api_1 = require("@opentelemetry/api"); -const suppress_tracing_1 = require("../../trace/suppress-tracing"); -const constants_1 = require("../constants"); -const utils_1 = require("../utils"); -/** - * Propagates {@link Baggage} through Context format propagation. - * - * Based on the Baggage specification: - * https://w3c.github.io/baggage/ - */ -class W3CBaggagePropagator { - inject(context, carrier, setter) { - const baggage = api_1.propagation.getBaggage(context); - if (!baggage || (0, suppress_tracing_1.isTracingSuppressed)(context)) - return; - const keyPairs = (0, utils_1.getKeyPairs)(baggage) - .filter((pair) => { - return pair.length <= constants_1.BAGGAGE_MAX_PER_NAME_VALUE_PAIRS; - }) - .slice(0, constants_1.BAGGAGE_MAX_NAME_VALUE_PAIRS); - const headerValue = (0, utils_1.serializeKeyPairs)(keyPairs); - if (headerValue.length > 0) { - setter.set(carrier, constants_1.BAGGAGE_HEADER, headerValue); - } - } - extract(context, carrier, getter) { - const headerValue = getter.get(carrier, constants_1.BAGGAGE_HEADER); - const baggageString = Array.isArray(headerValue) - ? headerValue.join(constants_1.BAGGAGE_ITEMS_SEPARATOR) - : headerValue; - if (!baggageString) - return context; - const baggage = {}; - if (baggageString.length === 0) { - return context; - } - const pairs = baggageString.split(constants_1.BAGGAGE_ITEMS_SEPARATOR); - pairs.forEach(entry => { - const keyPair = (0, utils_1.parsePairKeyValue)(entry); - if (keyPair) { - const baggageEntry = { value: keyPair.value }; - if (keyPair.metadata) { - baggageEntry.metadata = keyPair.metadata; - } - baggage[keyPair.key] = baggageEntry; - } - }); - if (Object.entries(baggage).length === 0) { - return context; - } - return api_1.propagation.setBaggage(context, api_1.propagation.createBaggage(baggage)); - } - fields() { - return [constants_1.BAGGAGE_HEADER]; - } -} -exports.W3CBaggagePropagator = W3CBaggagePropagator; -//# sourceMappingURL=W3CBaggagePropagator.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/utils.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/utils.js deleted file mode 100644 index 3cb9015f..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/baggage/utils.js +++ /dev/null @@ -1,76 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.parseKeyPairsIntoRecord = exports.parsePairKeyValue = exports.getKeyPairs = exports.serializeKeyPairs = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const api_1 = require("@opentelemetry/api"); -const constants_1 = require("./constants"); -function serializeKeyPairs(keyPairs) { - return keyPairs.reduce((hValue, current) => { - const value = `${hValue}${hValue !== '' ? constants_1.BAGGAGE_ITEMS_SEPARATOR : ''}${current}`; - return value.length > constants_1.BAGGAGE_MAX_TOTAL_LENGTH ? hValue : value; - }, ''); -} -exports.serializeKeyPairs = serializeKeyPairs; -function getKeyPairs(baggage) { - return baggage.getAllEntries().map(([key, value]) => { - let entry = `${encodeURIComponent(key)}=${encodeURIComponent(value.value)}`; - // include opaque metadata if provided - // NOTE: we intentionally don't URI-encode the metadata - that responsibility falls on the metadata implementation - if (value.metadata !== undefined) { - entry += constants_1.BAGGAGE_PROPERTIES_SEPARATOR + value.metadata.toString(); - } - return entry; - }); -} -exports.getKeyPairs = getKeyPairs; -function parsePairKeyValue(entry) { - const valueProps = entry.split(constants_1.BAGGAGE_PROPERTIES_SEPARATOR); - if (valueProps.length <= 0) - return; - const keyPairPart = valueProps.shift(); - if (!keyPairPart) - return; - const separatorIndex = keyPairPart.indexOf(constants_1.BAGGAGE_KEY_PAIR_SEPARATOR); - if (separatorIndex <= 0) - return; - const key = decodeURIComponent(keyPairPart.substring(0, separatorIndex).trim()); - const value = decodeURIComponent(keyPairPart.substring(separatorIndex + 1).trim()); - let metadata; - if (valueProps.length > 0) { - metadata = (0, api_1.baggageEntryMetadataFromString)(valueProps.join(constants_1.BAGGAGE_PROPERTIES_SEPARATOR)); - } - return { key, value, metadata }; -} -exports.parsePairKeyValue = parsePairKeyValue; -/** - * Parse a string serialized in the baggage HTTP Format (without metadata): - * https://github.com/w3c/baggage/blob/master/baggage/HTTP_HEADER_FORMAT.md - */ -function parseKeyPairsIntoRecord(value) { - const result = {}; - if (typeof value === 'string' && value.length > 0) { - value.split(constants_1.BAGGAGE_ITEMS_SEPARATOR).forEach(entry => { - const keyPair = parsePairKeyValue(entry); - if (keyPair !== undefined && keyPair.value.length > 0) { - result[keyPair.key] = keyPair.value; - } - }); - } - return result; -} -exports.parseKeyPairsIntoRecord = parseKeyPairsIntoRecord; -//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/common/anchored-clock.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/common/anchored-clock.js deleted file mode 100644 index e4ae16cd..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/common/anchored-clock.js +++ /dev/null @@ -1,61 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AnchoredClock = void 0; -/** - * A utility for returning wall times anchored to a given point in time. Wall time measurements will - * not be taken from the system, but instead are computed by adding a monotonic clock time - * to the anchor point. - * - * This is needed because the system time can change and result in unexpected situations like - * spans ending before they are started. Creating an anchored clock for each local root span - * ensures that span timings and durations are accurate while preventing span times from drifting - * too far from the system clock. - * - * Only creating an anchored clock once per local trace ensures span times are correct relative - * to each other. For example, a child span will never have a start time before its parent even - * if the system clock is corrected during the local trace. - * - * Heavily inspired by the OTel Java anchored clock - * https://github.com/open-telemetry/opentelemetry-java/blob/main/sdk/trace/src/main/java/io/opentelemetry/sdk/trace/AnchoredClock.java - */ -class AnchoredClock { - _monotonicClock; - _epochMillis; - _performanceMillis; - /** - * Create a new AnchoredClock anchored to the current time returned by systemClock. - * - * @param systemClock should be a clock that returns the number of milliseconds since January 1 1970 such as Date - * @param monotonicClock should be a clock that counts milliseconds monotonically such as window.performance or perf_hooks.performance - */ - constructor(systemClock, monotonicClock) { - this._monotonicClock = monotonicClock; - this._epochMillis = systemClock.now(); - this._performanceMillis = monotonicClock.now(); - } - /** - * Returns the current time by adding the number of milliseconds since the - * AnchoredClock was created to the creation epoch time - */ - now() { - const delta = this._monotonicClock.now() - this._performanceMillis; - return this._epochMillis + delta; - } -} -exports.AnchoredClock = AnchoredClock; -//# sourceMappingURL=anchored-clock.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/common/attributes.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/common/attributes.js deleted file mode 100644 index 8f7bbfff..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/common/attributes.js +++ /dev/null @@ -1,93 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isAttributeValue = exports.isAttributeKey = exports.sanitizeAttributes = void 0; -const api_1 = require("@opentelemetry/api"); -function sanitizeAttributes(attributes) { - const out = {}; - if (typeof attributes !== 'object' || attributes == null) { - return out; - } - for (const key in attributes) { - if (!Object.prototype.hasOwnProperty.call(attributes, key)) { - continue; - } - if (!isAttributeKey(key)) { - api_1.diag.warn(`Invalid attribute key: ${key}`); - continue; - } - const val = attributes[key]; - if (!isAttributeValue(val)) { - api_1.diag.warn(`Invalid attribute value set for key: ${key}`); - continue; - } - if (Array.isArray(val)) { - out[key] = val.slice(); - } - else { - out[key] = val; - } - } - return out; -} -exports.sanitizeAttributes = sanitizeAttributes; -function isAttributeKey(key) { - return typeof key === 'string' && key !== ''; -} -exports.isAttributeKey = isAttributeKey; -function isAttributeValue(val) { - if (val == null) { - return true; - } - if (Array.isArray(val)) { - return isHomogeneousAttributeValueArray(val); - } - return isValidPrimitiveAttributeValueType(typeof val); -} -exports.isAttributeValue = isAttributeValue; -function isHomogeneousAttributeValueArray(arr) { - let type; - for (const element of arr) { - // null/undefined elements are allowed - if (element == null) - continue; - const elementType = typeof element; - if (elementType === type) { - continue; - } - if (!type) { - if (isValidPrimitiveAttributeValueType(elementType)) { - type = elementType; - continue; - } - // encountered an invalid primitive - return false; - } - return false; - } - return true; -} -function isValidPrimitiveAttributeValueType(valType) { - switch (valType) { - case 'number': - case 'boolean': - case 'string': - return true; - } - return false; -} -//# sourceMappingURL=attributes.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/common/global-error-handler.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/common/global-error-handler.js deleted file mode 100644 index a5d9b765..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/common/global-error-handler.js +++ /dev/null @@ -1,41 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.globalErrorHandler = exports.setGlobalErrorHandler = void 0; -const logging_error_handler_1 = require("./logging-error-handler"); -/** The global error handler delegate */ -let delegateHandler = (0, logging_error_handler_1.loggingErrorHandler)(); -/** - * Set the global error handler - * @param {ErrorHandler} handler - */ -function setGlobalErrorHandler(handler) { - delegateHandler = handler; -} -exports.setGlobalErrorHandler = setGlobalErrorHandler; -/** - * Return the global error handler - * @param {Exception} ex - */ -function globalErrorHandler(ex) { - try { - delegateHandler(ex); - } - catch { } // eslint-disable-line no-empty -} -exports.globalErrorHandler = globalErrorHandler; -//# sourceMappingURL=global-error-handler.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/common/logging-error-handler.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/common/logging-error-handler.js deleted file mode 100644 index e1ea6e02..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/common/logging-error-handler.js +++ /dev/null @@ -1,63 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.loggingErrorHandler = void 0; -const api_1 = require("@opentelemetry/api"); -/** - * Returns a function that logs an error using the provided logger, or a - * console logger if one was not provided. - */ -function loggingErrorHandler() { - return (ex) => { - api_1.diag.error(stringifyException(ex)); - }; -} -exports.loggingErrorHandler = loggingErrorHandler; -/** - * Converts an exception into a string representation - * @param {Exception} ex - */ -function stringifyException(ex) { - if (typeof ex === 'string') { - return ex; - } - else { - return JSON.stringify(flattenException(ex)); - } -} -/** - * Flattens an exception into key-value pairs by traversing the prototype chain - * and coercing values to strings. Duplicate properties will not be overwritten; - * the first insert wins. - */ -function flattenException(ex) { - const result = {}; - let current = ex; - while (current !== null) { - Object.getOwnPropertyNames(current).forEach(propertyName => { - if (result[propertyName]) - return; - const value = current[propertyName]; - if (value) { - result[propertyName] = String(value); - } - }); - current = Object.getPrototypeOf(current); - } - return result; -} -//# sourceMappingURL=logging-error-handler.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/common/time.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/common/time.js deleted file mode 100644 index 0dfd7502..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/common/time.js +++ /dev/null @@ -1,171 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.addHrTimes = exports.isTimeInput = exports.isTimeInputHrTime = exports.hrTimeToMicroseconds = exports.hrTimeToMilliseconds = exports.hrTimeToNanoseconds = exports.hrTimeToTimeStamp = exports.hrTimeDuration = exports.timeInputToHrTime = exports.hrTime = exports.getTimeOrigin = exports.millisToHrTime = void 0; -const platform_1 = require("../platform"); -const NANOSECOND_DIGITS = 9; -const NANOSECOND_DIGITS_IN_MILLIS = 6; -const MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS); -const SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS); -/** - * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]). - * @param epochMillis - */ -function millisToHrTime(epochMillis) { - const epochSeconds = epochMillis / 1000; - // Decimals only. - const seconds = Math.trunc(epochSeconds); - // Round sub-nanosecond accuracy to nanosecond. - const nanos = Math.round((epochMillis % 1000) * MILLISECONDS_TO_NANOSECONDS); - return [seconds, nanos]; -} -exports.millisToHrTime = millisToHrTime; -function getTimeOrigin() { - let timeOrigin = platform_1.otperformance.timeOrigin; - if (typeof timeOrigin !== 'number') { - const perf = platform_1.otperformance; - timeOrigin = perf.timing && perf.timing.fetchStart; - } - return timeOrigin; -} -exports.getTimeOrigin = getTimeOrigin; -/** - * Returns an hrtime calculated via performance component. - * @param performanceNow - */ -function hrTime(performanceNow) { - const timeOrigin = millisToHrTime(getTimeOrigin()); - const now = millisToHrTime(typeof performanceNow === 'number' ? performanceNow : platform_1.otperformance.now()); - return addHrTimes(timeOrigin, now); -} -exports.hrTime = hrTime; -/** - * - * Converts a TimeInput to an HrTime, defaults to _hrtime(). - * @param time - */ -function timeInputToHrTime(time) { - // process.hrtime - if (isTimeInputHrTime(time)) { - return time; - } - else if (typeof time === 'number') { - // Must be a performance.now() if it's smaller than process start time. - if (time < getTimeOrigin()) { - return hrTime(time); - } - else { - // epoch milliseconds or performance.timeOrigin - return millisToHrTime(time); - } - } - else if (time instanceof Date) { - return millisToHrTime(time.getTime()); - } - else { - throw TypeError('Invalid input type'); - } -} -exports.timeInputToHrTime = timeInputToHrTime; -/** - * Returns a duration of two hrTime. - * @param startTime - * @param endTime - */ -function hrTimeDuration(startTime, endTime) { - let seconds = endTime[0] - startTime[0]; - let nanos = endTime[1] - startTime[1]; - // overflow - if (nanos < 0) { - seconds -= 1; - // negate - nanos += SECOND_TO_NANOSECONDS; - } - return [seconds, nanos]; -} -exports.hrTimeDuration = hrTimeDuration; -/** - * Convert hrTime to timestamp, for example "2019-05-14T17:00:00.000123456Z" - * @param time - */ -function hrTimeToTimeStamp(time) { - const precision = NANOSECOND_DIGITS; - const tmp = `${'0'.repeat(precision)}${time[1]}Z`; - const nanoString = tmp.substring(tmp.length - precision - 1); - const date = new Date(time[0] * 1000).toISOString(); - return date.replace('000Z', nanoString); -} -exports.hrTimeToTimeStamp = hrTimeToTimeStamp; -/** - * Convert hrTime to nanoseconds. - * @param time - */ -function hrTimeToNanoseconds(time) { - return time[0] * SECOND_TO_NANOSECONDS + time[1]; -} -exports.hrTimeToNanoseconds = hrTimeToNanoseconds; -/** - * Convert hrTime to milliseconds. - * @param time - */ -function hrTimeToMilliseconds(time) { - return time[0] * 1e3 + time[1] / 1e6; -} -exports.hrTimeToMilliseconds = hrTimeToMilliseconds; -/** - * Convert hrTime to microseconds. - * @param time - */ -function hrTimeToMicroseconds(time) { - return time[0] * 1e6 + time[1] / 1e3; -} -exports.hrTimeToMicroseconds = hrTimeToMicroseconds; -/** - * check if time is HrTime - * @param value - */ -function isTimeInputHrTime(value) { - return (Array.isArray(value) && - value.length === 2 && - typeof value[0] === 'number' && - typeof value[1] === 'number'); -} -exports.isTimeInputHrTime = isTimeInputHrTime; -/** - * check if input value is a correct types.TimeInput - * @param value - */ -function isTimeInput(value) { - return (isTimeInputHrTime(value) || - typeof value === 'number' || - value instanceof Date); -} -exports.isTimeInput = isTimeInput; -/** - * Given 2 HrTime formatted times, return their sum as an HrTime. - */ -function addHrTimes(time1, time2) { - const out = [time1[0] + time2[0], time1[1] + time2[1]]; - // Nanoseconds - if (out[1] >= SECOND_TO_NANOSECONDS) { - out[1] -= SECOND_TO_NANOSECONDS; - out[0] += 1; - } - return out; -} -exports.addHrTimes = addHrTimes; -//# sourceMappingURL=time.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/common/timer-util.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/common/timer-util.js deleted file mode 100644 index 76043b63..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/common/timer-util.js +++ /dev/null @@ -1,29 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.unrefTimer = void 0; -/** - * @deprecated please copy this code to your implementation instead, this function will be removed in the next major version of this package. - * @param timer - */ -function unrefTimer(timer) { - if (typeof timer !== 'number') { - timer.unref(); - } -} -exports.unrefTimer = unrefTimer; -//# sourceMappingURL=timer-util.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/index.js deleted file mode 100644 index acba8c7a..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/index.js +++ /dev/null @@ -1,92 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.internal = exports.diagLogLevelFromString = exports.BindOnceFuture = exports.urlMatches = exports.isUrlIgnored = exports.callWithTimeout = exports.TimeoutError = exports.merge = exports.TraceState = exports.unsuppressTracing = exports.suppressTracing = exports.isTracingSuppressed = exports.setRPCMetadata = exports.getRPCMetadata = exports.deleteRPCMetadata = exports.RPCType = exports.parseTraceParent = exports.W3CTraceContextPropagator = exports.TRACE_STATE_HEADER = exports.TRACE_PARENT_HEADER = exports.CompositePropagator = exports.otperformance = exports.getStringListFromEnv = exports.getNumberFromEnv = exports.getBooleanFromEnv = exports.getStringFromEnv = exports._globalThis = exports.SDK_INFO = exports.parseKeyPairsIntoRecord = exports.ExportResultCode = exports.unrefTimer = exports.timeInputToHrTime = exports.millisToHrTime = exports.isTimeInputHrTime = exports.isTimeInput = exports.hrTimeToTimeStamp = exports.hrTimeToNanoseconds = exports.hrTimeToMilliseconds = exports.hrTimeToMicroseconds = exports.hrTimeDuration = exports.hrTime = exports.getTimeOrigin = exports.addHrTimes = exports.loggingErrorHandler = exports.setGlobalErrorHandler = exports.globalErrorHandler = exports.sanitizeAttributes = exports.isAttributeValue = exports.AnchoredClock = exports.W3CBaggagePropagator = void 0; -var W3CBaggagePropagator_1 = require("./baggage/propagation/W3CBaggagePropagator"); -Object.defineProperty(exports, "W3CBaggagePropagator", { enumerable: true, get: function () { return W3CBaggagePropagator_1.W3CBaggagePropagator; } }); -var anchored_clock_1 = require("./common/anchored-clock"); -Object.defineProperty(exports, "AnchoredClock", { enumerable: true, get: function () { return anchored_clock_1.AnchoredClock; } }); -var attributes_1 = require("./common/attributes"); -Object.defineProperty(exports, "isAttributeValue", { enumerable: true, get: function () { return attributes_1.isAttributeValue; } }); -Object.defineProperty(exports, "sanitizeAttributes", { enumerable: true, get: function () { return attributes_1.sanitizeAttributes; } }); -var global_error_handler_1 = require("./common/global-error-handler"); -Object.defineProperty(exports, "globalErrorHandler", { enumerable: true, get: function () { return global_error_handler_1.globalErrorHandler; } }); -Object.defineProperty(exports, "setGlobalErrorHandler", { enumerable: true, get: function () { return global_error_handler_1.setGlobalErrorHandler; } }); -var logging_error_handler_1 = require("./common/logging-error-handler"); -Object.defineProperty(exports, "loggingErrorHandler", { enumerable: true, get: function () { return logging_error_handler_1.loggingErrorHandler; } }); -var time_1 = require("./common/time"); -Object.defineProperty(exports, "addHrTimes", { enumerable: true, get: function () { return time_1.addHrTimes; } }); -Object.defineProperty(exports, "getTimeOrigin", { enumerable: true, get: function () { return time_1.getTimeOrigin; } }); -Object.defineProperty(exports, "hrTime", { enumerable: true, get: function () { return time_1.hrTime; } }); -Object.defineProperty(exports, "hrTimeDuration", { enumerable: true, get: function () { return time_1.hrTimeDuration; } }); -Object.defineProperty(exports, "hrTimeToMicroseconds", { enumerable: true, get: function () { return time_1.hrTimeToMicroseconds; } }); -Object.defineProperty(exports, "hrTimeToMilliseconds", { enumerable: true, get: function () { return time_1.hrTimeToMilliseconds; } }); -Object.defineProperty(exports, "hrTimeToNanoseconds", { enumerable: true, get: function () { return time_1.hrTimeToNanoseconds; } }); -Object.defineProperty(exports, "hrTimeToTimeStamp", { enumerable: true, get: function () { return time_1.hrTimeToTimeStamp; } }); -Object.defineProperty(exports, "isTimeInput", { enumerable: true, get: function () { return time_1.isTimeInput; } }); -Object.defineProperty(exports, "isTimeInputHrTime", { enumerable: true, get: function () { return time_1.isTimeInputHrTime; } }); -Object.defineProperty(exports, "millisToHrTime", { enumerable: true, get: function () { return time_1.millisToHrTime; } }); -Object.defineProperty(exports, "timeInputToHrTime", { enumerable: true, get: function () { return time_1.timeInputToHrTime; } }); -var timer_util_1 = require("./common/timer-util"); -Object.defineProperty(exports, "unrefTimer", { enumerable: true, get: function () { return timer_util_1.unrefTimer; } }); -var ExportResult_1 = require("./ExportResult"); -Object.defineProperty(exports, "ExportResultCode", { enumerable: true, get: function () { return ExportResult_1.ExportResultCode; } }); -var utils_1 = require("./baggage/utils"); -Object.defineProperty(exports, "parseKeyPairsIntoRecord", { enumerable: true, get: function () { return utils_1.parseKeyPairsIntoRecord; } }); -var platform_1 = require("./platform"); -Object.defineProperty(exports, "SDK_INFO", { enumerable: true, get: function () { return platform_1.SDK_INFO; } }); -Object.defineProperty(exports, "_globalThis", { enumerable: true, get: function () { return platform_1._globalThis; } }); -Object.defineProperty(exports, "getStringFromEnv", { enumerable: true, get: function () { return platform_1.getStringFromEnv; } }); -Object.defineProperty(exports, "getBooleanFromEnv", { enumerable: true, get: function () { return platform_1.getBooleanFromEnv; } }); -Object.defineProperty(exports, "getNumberFromEnv", { enumerable: true, get: function () { return platform_1.getNumberFromEnv; } }); -Object.defineProperty(exports, "getStringListFromEnv", { enumerable: true, get: function () { return platform_1.getStringListFromEnv; } }); -Object.defineProperty(exports, "otperformance", { enumerable: true, get: function () { return platform_1.otperformance; } }); -var composite_1 = require("./propagation/composite"); -Object.defineProperty(exports, "CompositePropagator", { enumerable: true, get: function () { return composite_1.CompositePropagator; } }); -var W3CTraceContextPropagator_1 = require("./trace/W3CTraceContextPropagator"); -Object.defineProperty(exports, "TRACE_PARENT_HEADER", { enumerable: true, get: function () { return W3CTraceContextPropagator_1.TRACE_PARENT_HEADER; } }); -Object.defineProperty(exports, "TRACE_STATE_HEADER", { enumerable: true, get: function () { return W3CTraceContextPropagator_1.TRACE_STATE_HEADER; } }); -Object.defineProperty(exports, "W3CTraceContextPropagator", { enumerable: true, get: function () { return W3CTraceContextPropagator_1.W3CTraceContextPropagator; } }); -Object.defineProperty(exports, "parseTraceParent", { enumerable: true, get: function () { return W3CTraceContextPropagator_1.parseTraceParent; } }); -var rpc_metadata_1 = require("./trace/rpc-metadata"); -Object.defineProperty(exports, "RPCType", { enumerable: true, get: function () { return rpc_metadata_1.RPCType; } }); -Object.defineProperty(exports, "deleteRPCMetadata", { enumerable: true, get: function () { return rpc_metadata_1.deleteRPCMetadata; } }); -Object.defineProperty(exports, "getRPCMetadata", { enumerable: true, get: function () { return rpc_metadata_1.getRPCMetadata; } }); -Object.defineProperty(exports, "setRPCMetadata", { enumerable: true, get: function () { return rpc_metadata_1.setRPCMetadata; } }); -var suppress_tracing_1 = require("./trace/suppress-tracing"); -Object.defineProperty(exports, "isTracingSuppressed", { enumerable: true, get: function () { return suppress_tracing_1.isTracingSuppressed; } }); -Object.defineProperty(exports, "suppressTracing", { enumerable: true, get: function () { return suppress_tracing_1.suppressTracing; } }); -Object.defineProperty(exports, "unsuppressTracing", { enumerable: true, get: function () { return suppress_tracing_1.unsuppressTracing; } }); -var TraceState_1 = require("./trace/TraceState"); -Object.defineProperty(exports, "TraceState", { enumerable: true, get: function () { return TraceState_1.TraceState; } }); -var merge_1 = require("./utils/merge"); -Object.defineProperty(exports, "merge", { enumerable: true, get: function () { return merge_1.merge; } }); -var timeout_1 = require("./utils/timeout"); -Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function () { return timeout_1.TimeoutError; } }); -Object.defineProperty(exports, "callWithTimeout", { enumerable: true, get: function () { return timeout_1.callWithTimeout; } }); -var url_1 = require("./utils/url"); -Object.defineProperty(exports, "isUrlIgnored", { enumerable: true, get: function () { return url_1.isUrlIgnored; } }); -Object.defineProperty(exports, "urlMatches", { enumerable: true, get: function () { return url_1.urlMatches; } }); -var callback_1 = require("./utils/callback"); -Object.defineProperty(exports, "BindOnceFuture", { enumerable: true, get: function () { return callback_1.BindOnceFuture; } }); -var configuration_1 = require("./utils/configuration"); -Object.defineProperty(exports, "diagLogLevelFromString", { enumerable: true, get: function () { return configuration_1.diagLogLevelFromString; } }); -const exporter_1 = require("./internal/exporter"); -exports.internal = { - _export: exporter_1._export, -}; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/internal/exporter.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/internal/exporter.js deleted file mode 100644 index c5c35110..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/internal/exporter.js +++ /dev/null @@ -1,36 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports._export = void 0; -const api_1 = require("@opentelemetry/api"); -const suppress_tracing_1 = require("../trace/suppress-tracing"); -/** - * @internal - * Shared functionality used by Exporters while exporting data, including suppression of Traces. - */ -function _export(exporter, arg) { - return new Promise(resolve => { - // prevent downstream exporter calls from generating spans - api_1.context.with((0, suppress_tracing_1.suppressTracing)(api_1.context.active()), () => { - exporter.export(arg, (result) => { - resolve(result); - }); - }); - }); -} -exports._export = _export; -//# sourceMappingURL=exporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/internal/validators.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/internal/validators.js deleted file mode 100644 index 820522ca..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/internal/validators.js +++ /dev/null @@ -1,46 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.validateValue = exports.validateKey = void 0; -const VALID_KEY_CHAR_RANGE = '[_0-9a-z-*/]'; -const VALID_KEY = `[a-z]${VALID_KEY_CHAR_RANGE}{0,255}`; -const VALID_VENDOR_KEY = `[a-z0-9]${VALID_KEY_CHAR_RANGE}{0,240}@[a-z]${VALID_KEY_CHAR_RANGE}{0,13}`; -const VALID_KEY_REGEX = new RegExp(`^(?:${VALID_KEY}|${VALID_VENDOR_KEY})$`); -const VALID_VALUE_BASE_REGEX = /^[ -~]{0,255}[!-~]$/; -const INVALID_VALUE_COMMA_EQUAL_REGEX = /,|=/; -/** - * Key is opaque string up to 256 characters printable. It MUST begin with a - * lowercase letter, and can only contain lowercase letters a-z, digits 0-9, - * underscores _, dashes -, asterisks *, and forward slashes /. - * For multi-tenant vendor scenarios, an at sign (@) can be used to prefix the - * vendor name. Vendors SHOULD set the tenant ID at the beginning of the key. - * see https://www.w3.org/TR/trace-context/#key - */ -function validateKey(key) { - return VALID_KEY_REGEX.test(key); -} -exports.validateKey = validateKey; -/** - * Value is opaque string up to 256 characters printable ASCII RFC0020 - * characters (i.e., the range 0x20 to 0x7E) except comma , and =. - */ -function validateValue(value) { - return (VALID_VALUE_BASE_REGEX.test(value) && - !INVALID_VALUE_COMMA_EQUAL_REGEX.test(value)); -} -exports.validateValue = validateValue; -//# sourceMappingURL=validators.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/index.js deleted file mode 100644 index 5e83a058..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/index.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getStringListFromEnv = exports.getNumberFromEnv = exports.getStringFromEnv = exports.getBooleanFromEnv = exports.otperformance = exports._globalThis = exports.SDK_INFO = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var node_1 = require("./node"); -Object.defineProperty(exports, "SDK_INFO", { enumerable: true, get: function () { return node_1.SDK_INFO; } }); -Object.defineProperty(exports, "_globalThis", { enumerable: true, get: function () { return node_1._globalThis; } }); -Object.defineProperty(exports, "otperformance", { enumerable: true, get: function () { return node_1.otperformance; } }); -Object.defineProperty(exports, "getBooleanFromEnv", { enumerable: true, get: function () { return node_1.getBooleanFromEnv; } }); -Object.defineProperty(exports, "getStringFromEnv", { enumerable: true, get: function () { return node_1.getStringFromEnv; } }); -Object.defineProperty(exports, "getNumberFromEnv", { enumerable: true, get: function () { return node_1.getNumberFromEnv; } }); -Object.defineProperty(exports, "getStringListFromEnv", { enumerable: true, get: function () { return node_1.getStringListFromEnv; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/environment.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/environment.js deleted file mode 100644 index d0268b37..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/environment.js +++ /dev/null @@ -1,104 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getStringListFromEnv = exports.getBooleanFromEnv = exports.getStringFromEnv = exports.getNumberFromEnv = void 0; -const api_1 = require("@opentelemetry/api"); -const util_1 = require("util"); -/** - * Retrieves a number from an environment variable. - * - Returns `undefined` if the environment variable is empty, unset, contains only whitespace, or is not a number. - * - Returns a number in all other cases. - * - * @param {string} key - The name of the environment variable to retrieve. - * @returns {number | undefined} - The number value or `undefined`. - */ -function getNumberFromEnv(key) { - const raw = process.env[key]; - if (raw == null || raw.trim() === '') { - return undefined; - } - const value = Number(raw); - if (isNaN(value)) { - api_1.diag.warn(`Unknown value ${(0, util_1.inspect)(raw)} for ${key}, expected a number, using defaults`); - return undefined; - } - return value; -} -exports.getNumberFromEnv = getNumberFromEnv; -/** - * Retrieves a string from an environment variable. - * - Returns `undefined` if the environment variable is empty, unset, or contains only whitespace. - * - * @param {string} key - The name of the environment variable to retrieve. - * @returns {string | undefined} - The string value or `undefined`. - */ -function getStringFromEnv(key) { - const raw = process.env[key]; - if (raw == null || raw.trim() === '') { - return undefined; - } - return raw; -} -exports.getStringFromEnv = getStringFromEnv; -/** - * Retrieves a boolean value from an environment variable. - * - Trims leading and trailing whitespace and ignores casing. - * - Returns `false` if the environment variable is empty, unset, or contains only whitespace. - * - Returns `false` for strings that cannot be mapped to a boolean. - * - * @param {string} key - The name of the environment variable to retrieve. - * @returns {boolean} - The boolean value or `false` if the environment variable is unset empty, unset, or contains only whitespace. - */ -function getBooleanFromEnv(key) { - const raw = process.env[key]?.trim().toLowerCase(); - if (raw == null || raw === '') { - // NOTE: falling back to `false` instead of `undefined` as required by the specification. - // If you have a use-case that requires `undefined`, consider using `getStringFromEnv()` and applying the necessary - // normalizations in the consuming code. - return false; - } - if (raw === 'true') { - return true; - } - else if (raw === 'false') { - return false; - } - else { - api_1.diag.warn(`Unknown value ${(0, util_1.inspect)(raw)} for ${key}, expected 'true' or 'false', falling back to 'false' (default)`); - return false; - } -} -exports.getBooleanFromEnv = getBooleanFromEnv; -/** - * Retrieves a list of strings from an environment variable. - * - Uses ',' as the delimiter. - * - Trims leading and trailing whitespace from each entry. - * - Excludes empty entries. - * - Returns `undefined` if the environment variable is empty or contains only whitespace. - * - Returns an empty array if all entries are empty or whitespace. - * - * @param {string} key - The name of the environment variable to retrieve. - * @returns {string[] | undefined} - The list of strings or `undefined`. - */ -function getStringListFromEnv(key) { - return getStringFromEnv(key) - ?.split(',') - .map(v => v.trim()) - .filter(s => s !== ''); -} -exports.getStringListFromEnv = getStringListFromEnv; -//# sourceMappingURL=environment.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/globalThis.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/globalThis.js deleted file mode 100644 index 9ae59140..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/globalThis.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports._globalThis = void 0; -/** only globals that common to node and browsers are allowed */ -// eslint-disable-next-line n/no-unsupported-features/es-builtins -exports._globalThis = typeof globalThis === 'object' ? globalThis : global; -//# sourceMappingURL=globalThis.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/index.js deleted file mode 100644 index 6934fac6..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/index.js +++ /dev/null @@ -1,30 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SDK_INFO = exports.otperformance = exports._globalThis = exports.getStringListFromEnv = exports.getNumberFromEnv = exports.getBooleanFromEnv = exports.getStringFromEnv = void 0; -var environment_1 = require("./environment"); -Object.defineProperty(exports, "getStringFromEnv", { enumerable: true, get: function () { return environment_1.getStringFromEnv; } }); -Object.defineProperty(exports, "getBooleanFromEnv", { enumerable: true, get: function () { return environment_1.getBooleanFromEnv; } }); -Object.defineProperty(exports, "getNumberFromEnv", { enumerable: true, get: function () { return environment_1.getNumberFromEnv; } }); -Object.defineProperty(exports, "getStringListFromEnv", { enumerable: true, get: function () { return environment_1.getStringListFromEnv; } }); -var globalThis_1 = require("./globalThis"); -Object.defineProperty(exports, "_globalThis", { enumerable: true, get: function () { return globalThis_1._globalThis; } }); -var performance_1 = require("./performance"); -Object.defineProperty(exports, "otperformance", { enumerable: true, get: function () { return performance_1.otperformance; } }); -var sdk_info_1 = require("./sdk-info"); -Object.defineProperty(exports, "SDK_INFO", { enumerable: true, get: function () { return sdk_info_1.SDK_INFO; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/performance.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/performance.js deleted file mode 100644 index ade758b8..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/performance.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.otperformance = void 0; -const perf_hooks_1 = require("perf_hooks"); -exports.otperformance = perf_hooks_1.performance; -//# sourceMappingURL=performance.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/sdk-info.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/sdk-info.js deleted file mode 100644 index 357c2663..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/platform/node/sdk-info.js +++ /dev/null @@ -1,29 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SDK_INFO = void 0; -const version_1 = require("../../version"); -const semantic_conventions_1 = require("@opentelemetry/semantic-conventions"); -const semconv_1 = require("../../semconv"); -/** Constants describing the SDK in use */ -exports.SDK_INFO = { - [semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME]: 'opentelemetry', - [semconv_1.ATTR_PROCESS_RUNTIME_NAME]: 'node', - [semantic_conventions_1.ATTR_TELEMETRY_SDK_LANGUAGE]: semantic_conventions_1.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS, - [semantic_conventions_1.ATTR_TELEMETRY_SDK_VERSION]: version_1.VERSION, -}; -//# sourceMappingURL=sdk-info.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/propagation/composite.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/propagation/composite.js deleted file mode 100644 index c45d7775..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/propagation/composite.js +++ /dev/null @@ -1,81 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CompositePropagator = void 0; -const api_1 = require("@opentelemetry/api"); -/** Combines multiple propagators into a single propagator. */ -class CompositePropagator { - _propagators; - _fields; - /** - * Construct a composite propagator from a list of propagators. - * - * @param [config] Configuration object for composite propagator - */ - constructor(config = {}) { - this._propagators = config.propagators ?? []; - this._fields = Array.from(new Set(this._propagators - // older propagators may not have fields function, null check to be sure - .map(p => (typeof p.fields === 'function' ? p.fields() : [])) - .reduce((x, y) => x.concat(y), []))); - } - /** - * Run each of the configured propagators with the given context and carrier. - * Propagators are run in the order they are configured, so if multiple - * propagators write the same carrier key, the propagator later in the list - * will "win". - * - * @param context Context to inject - * @param carrier Carrier into which context will be injected - */ - inject(context, carrier, setter) { - for (const propagator of this._propagators) { - try { - propagator.inject(context, carrier, setter); - } - catch (err) { - api_1.diag.warn(`Failed to inject with ${propagator.constructor.name}. Err: ${err.message}`); - } - } - } - /** - * Run each of the configured propagators with the given context and carrier. - * Propagators are run in the order they are configured, so if multiple - * propagators write the same context key, the propagator later in the list - * will "win". - * - * @param context Context to add values to - * @param carrier Carrier from which to extract context - */ - extract(context, carrier, getter) { - return this._propagators.reduce((ctx, propagator) => { - try { - return propagator.extract(ctx, carrier, getter); - } - catch (err) { - api_1.diag.warn(`Failed to extract with ${propagator.constructor.name}. Err: ${err.message}`); - } - return ctx; - }, context); - } - fields() { - // return a new array so our fields cannot be modified - return this._fields.slice(); - } -} -exports.CompositePropagator = CompositePropagator; -//# sourceMappingURL=composite.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/semconv.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/semconv.js deleted file mode 100644 index 2cd8ceaf..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/semconv.js +++ /dev/null @@ -1,32 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ATTR_PROCESS_RUNTIME_NAME = void 0; -/* - * This file contains a copy of unstable semantic convention definitions - * used by this package. - * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv - */ -/** - * The name of the runtime of this process. - * - * @example OpenJDK Runtime Environment - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_PROCESS_RUNTIME_NAME = 'process.runtime.name'; -//# sourceMappingURL=semconv.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/TraceState.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/TraceState.js deleted file mode 100644 index 6fdfa5e8..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/TraceState.js +++ /dev/null @@ -1,103 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TraceState = void 0; -const validators_1 = require("../internal/validators"); -const MAX_TRACE_STATE_ITEMS = 32; -const MAX_TRACE_STATE_LEN = 512; -const LIST_MEMBERS_SEPARATOR = ','; -const LIST_MEMBER_KEY_VALUE_SPLITTER = '='; -/** - * TraceState must be a class and not a simple object type because of the spec - * requirement (https://www.w3.org/TR/trace-context/#tracestate-field). - * - * Here is the list of allowed mutations: - * - New key-value pair should be added into the beginning of the list - * - The value of any key can be updated. Modified keys MUST be moved to the - * beginning of the list. - */ -class TraceState { - _internalState = new Map(); - constructor(rawTraceState) { - if (rawTraceState) - this._parse(rawTraceState); - } - set(key, value) { - // TODO: Benchmark the different approaches(map vs list) and - // use the faster one. - const traceState = this._clone(); - if (traceState._internalState.has(key)) { - traceState._internalState.delete(key); - } - traceState._internalState.set(key, value); - return traceState; - } - unset(key) { - const traceState = this._clone(); - traceState._internalState.delete(key); - return traceState; - } - get(key) { - return this._internalState.get(key); - } - serialize() { - return this._keys() - .reduce((agg, key) => { - agg.push(key + LIST_MEMBER_KEY_VALUE_SPLITTER + this.get(key)); - return agg; - }, []) - .join(LIST_MEMBERS_SEPARATOR); - } - _parse(rawTraceState) { - if (rawTraceState.length > MAX_TRACE_STATE_LEN) - return; - this._internalState = rawTraceState - .split(LIST_MEMBERS_SEPARATOR) - .reverse() // Store in reverse so new keys (.set(...)) will be placed at the beginning - .reduce((agg, part) => { - const listMember = part.trim(); // Optional Whitespace (OWS) handling - const i = listMember.indexOf(LIST_MEMBER_KEY_VALUE_SPLITTER); - if (i !== -1) { - const key = listMember.slice(0, i); - const value = listMember.slice(i + 1, part.length); - if ((0, validators_1.validateKey)(key) && (0, validators_1.validateValue)(value)) { - agg.set(key, value); - } - else { - // TODO: Consider to add warning log - } - } - return agg; - }, new Map()); - // Because of the reverse() requirement, trunc must be done after map is created - if (this._internalState.size > MAX_TRACE_STATE_ITEMS) { - this._internalState = new Map(Array.from(this._internalState.entries()) - .reverse() // Use reverse same as original tracestate parse chain - .slice(0, MAX_TRACE_STATE_ITEMS)); - } - } - _keys() { - return Array.from(this._internalState.keys()).reverse(); - } - _clone() { - const traceState = new TraceState(); - traceState._internalState = new Map(this._internalState); - return traceState; - } -} -exports.TraceState = TraceState; -//# sourceMappingURL=TraceState.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/W3CTraceContextPropagator.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/W3CTraceContextPropagator.js deleted file mode 100644 index 86832129..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/W3CTraceContextPropagator.js +++ /dev/null @@ -1,104 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.W3CTraceContextPropagator = exports.parseTraceParent = exports.TRACE_STATE_HEADER = exports.TRACE_PARENT_HEADER = void 0; -const api_1 = require("@opentelemetry/api"); -const suppress_tracing_1 = require("./suppress-tracing"); -const TraceState_1 = require("./TraceState"); -exports.TRACE_PARENT_HEADER = 'traceparent'; -exports.TRACE_STATE_HEADER = 'tracestate'; -const VERSION = '00'; -const VERSION_PART = '(?!ff)[\\da-f]{2}'; -const TRACE_ID_PART = '(?![0]{32})[\\da-f]{32}'; -const PARENT_ID_PART = '(?![0]{16})[\\da-f]{16}'; -const FLAGS_PART = '[\\da-f]{2}'; -const TRACE_PARENT_REGEX = new RegExp(`^\\s?(${VERSION_PART})-(${TRACE_ID_PART})-(${PARENT_ID_PART})-(${FLAGS_PART})(-.*)?\\s?$`); -/** - * Parses information from the [traceparent] span tag and converts it into {@link SpanContext} - * @param traceParent - A meta property that comes from server. - * It should be dynamically generated server side to have the server's request trace Id, - * a parent span Id that was set on the server's request span, - * and the trace flags to indicate the server's sampling decision - * (01 = sampled, 00 = not sampled). - * for example: '{version}-{traceId}-{spanId}-{sampleDecision}' - * For more information see {@link https://www.w3.org/TR/trace-context/} - */ -function parseTraceParent(traceParent) { - const match = TRACE_PARENT_REGEX.exec(traceParent); - if (!match) - return null; - // According to the specification the implementation should be compatible - // with future versions. If there are more parts, we only reject it if it's using version 00 - // See https://www.w3.org/TR/trace-context/#versioning-of-traceparent - if (match[1] === '00' && match[5]) - return null; - return { - traceId: match[2], - spanId: match[3], - traceFlags: parseInt(match[4], 16), - }; -} -exports.parseTraceParent = parseTraceParent; -/** - * Propagates {@link SpanContext} through Trace Context format propagation. - * - * Based on the Trace Context specification: - * https://www.w3.org/TR/trace-context/ - */ -class W3CTraceContextPropagator { - inject(context, carrier, setter) { - const spanContext = api_1.trace.getSpanContext(context); - if (!spanContext || - (0, suppress_tracing_1.isTracingSuppressed)(context) || - !(0, api_1.isSpanContextValid)(spanContext)) - return; - const traceParent = `${VERSION}-${spanContext.traceId}-${spanContext.spanId}-0${Number(spanContext.traceFlags || api_1.TraceFlags.NONE).toString(16)}`; - setter.set(carrier, exports.TRACE_PARENT_HEADER, traceParent); - if (spanContext.traceState) { - setter.set(carrier, exports.TRACE_STATE_HEADER, spanContext.traceState.serialize()); - } - } - extract(context, carrier, getter) { - const traceParentHeader = getter.get(carrier, exports.TRACE_PARENT_HEADER); - if (!traceParentHeader) - return context; - const traceParent = Array.isArray(traceParentHeader) - ? traceParentHeader[0] - : traceParentHeader; - if (typeof traceParent !== 'string') - return context; - const spanContext = parseTraceParent(traceParent); - if (!spanContext) - return context; - spanContext.isRemote = true; - const traceStateHeader = getter.get(carrier, exports.TRACE_STATE_HEADER); - if (traceStateHeader) { - // If more than one `tracestate` header is found, we merge them into a - // single header. - const state = Array.isArray(traceStateHeader) - ? traceStateHeader.join(',') - : traceStateHeader; - spanContext.traceState = new TraceState_1.TraceState(typeof state === 'string' ? state : undefined); - } - return api_1.trace.setSpanContext(context, spanContext); - } - fields() { - return [exports.TRACE_PARENT_HEADER, exports.TRACE_STATE_HEADER]; - } -} -exports.W3CTraceContextPropagator = W3CTraceContextPropagator; -//# sourceMappingURL=W3CTraceContextPropagator.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/rpc-metadata.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/rpc-metadata.js deleted file mode 100644 index 48de80cf..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/rpc-metadata.js +++ /dev/null @@ -1,37 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getRPCMetadata = exports.deleteRPCMetadata = exports.setRPCMetadata = exports.RPCType = void 0; -const api_1 = require("@opentelemetry/api"); -const RPC_METADATA_KEY = (0, api_1.createContextKey)('OpenTelemetry SDK Context Key RPC_METADATA'); -var RPCType; -(function (RPCType) { - RPCType["HTTP"] = "http"; -})(RPCType = exports.RPCType || (exports.RPCType = {})); -function setRPCMetadata(context, meta) { - return context.setValue(RPC_METADATA_KEY, meta); -} -exports.setRPCMetadata = setRPCMetadata; -function deleteRPCMetadata(context) { - return context.deleteValue(RPC_METADATA_KEY); -} -exports.deleteRPCMetadata = deleteRPCMetadata; -function getRPCMetadata(context) { - return context.getValue(RPC_METADATA_KEY); -} -exports.getRPCMetadata = getRPCMetadata; -//# sourceMappingURL=rpc-metadata.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/suppress-tracing.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/suppress-tracing.js deleted file mode 100644 index be8931d3..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/trace/suppress-tracing.js +++ /dev/null @@ -1,33 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isTracingSuppressed = exports.unsuppressTracing = exports.suppressTracing = void 0; -const api_1 = require("@opentelemetry/api"); -const SUPPRESS_TRACING_KEY = (0, api_1.createContextKey)('OpenTelemetry SDK Context Key SUPPRESS_TRACING'); -function suppressTracing(context) { - return context.setValue(SUPPRESS_TRACING_KEY, true); -} -exports.suppressTracing = suppressTracing; -function unsuppressTracing(context) { - return context.deleteValue(SUPPRESS_TRACING_KEY); -} -exports.unsuppressTracing = unsuppressTracing; -function isTracingSuppressed(context) { - return context.getValue(SUPPRESS_TRACING_KEY) === true; -} -exports.isTracingSuppressed = isTracingSuppressed; -//# sourceMappingURL=suppress-tracing.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/callback.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/callback.js deleted file mode 100644 index 82520d9c..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/callback.js +++ /dev/null @@ -1,52 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BindOnceFuture = void 0; -const promise_1 = require("./promise"); -/** - * Bind the callback and only invoke the callback once regardless how many times `BindOnceFuture.call` is invoked. - */ -class BindOnceFuture { - _callback; - _that; - _isCalled = false; - _deferred = new promise_1.Deferred(); - constructor(_callback, _that) { - this._callback = _callback; - this._that = _that; - } - get isCalled() { - return this._isCalled; - } - get promise() { - return this._deferred.promise; - } - call(...args) { - if (!this._isCalled) { - this._isCalled = true; - try { - Promise.resolve(this._callback.call(this._that, ...args)).then(val => this._deferred.resolve(val), err => this._deferred.reject(err)); - } - catch (err) { - this._deferred.reject(err); - } - } - return this._deferred.promise; - } -} -exports.BindOnceFuture = BindOnceFuture; -//# sourceMappingURL=callback.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/configuration.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/configuration.js deleted file mode 100644 index 64ea67e3..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/configuration.js +++ /dev/null @@ -1,46 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.diagLogLevelFromString = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const api_1 = require("@opentelemetry/api"); -const logLevelMap = { - ALL: api_1.DiagLogLevel.ALL, - VERBOSE: api_1.DiagLogLevel.VERBOSE, - DEBUG: api_1.DiagLogLevel.DEBUG, - INFO: api_1.DiagLogLevel.INFO, - WARN: api_1.DiagLogLevel.WARN, - ERROR: api_1.DiagLogLevel.ERROR, - NONE: api_1.DiagLogLevel.NONE, -}; -/** - * Convert a string to a {@link DiagLogLevel}, defaults to {@link DiagLogLevel} if the log level does not exist or undefined if the input is undefined. - * @param value - */ -function diagLogLevelFromString(value) { - if (value == null) { - // don't fall back to default - no value set has different semantics for ús than an incorrect value (do not set vs. fall back to default) - return undefined; - } - const resolvedLogLevel = logLevelMap[value.toUpperCase()]; - if (resolvedLogLevel == null) { - api_1.diag.warn(`Unknown log level "${value}", expected one of ${Object.keys(logLevelMap)}, using default`); - return api_1.DiagLogLevel.INFO; - } - return resolvedLogLevel; -} -exports.diagLogLevelFromString = diagLogLevelFromString; -//# sourceMappingURL=configuration.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/lodash.merge.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/lodash.merge.js deleted file mode 100644 index 9e531958..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/lodash.merge.js +++ /dev/null @@ -1,157 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isPlainObject = void 0; -/* eslint-disable @typescript-eslint/no-explicit-any */ -/** - * based on lodash in order to support esm builds without esModuleInterop. - * lodash is using MIT License. - **/ -const objectTag = '[object Object]'; -const nullTag = '[object Null]'; -const undefinedTag = '[object Undefined]'; -const funcProto = Function.prototype; -const funcToString = funcProto.toString; -const objectCtorString = funcToString.call(Object); -const getPrototypeOf = Object.getPrototypeOf; -const objectProto = Object.prototype; -const hasOwnProperty = objectProto.hasOwnProperty; -const symToStringTag = Symbol ? Symbol.toStringTag : undefined; -const nativeObjectToString = objectProto.toString; -/** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ -function isPlainObject(value) { - if (!isObjectLike(value) || baseGetTag(value) !== objectTag) { - return false; - } - const proto = getPrototypeOf(value); - if (proto === null) { - return true; - } - const Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; - return (typeof Ctor == 'function' && - Ctor instanceof Ctor && - funcToString.call(Ctor) === objectCtorString); -} -exports.isPlainObject = isPlainObject; -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return value != null && typeof value == 'object'; -} -/** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return symToStringTag && symToStringTag in Object(value) - ? getRawTag(value) - : objectToString(value); -} -/** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ -function getRawTag(value) { - const isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; - let unmasked = false; - try { - value[symToStringTag] = undefined; - unmasked = true; - } - catch { - // silence - } - const result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } - else { - delete value[symToStringTag]; - } - } - return result; -} -/** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ -function objectToString(value) { - return nativeObjectToString.call(value); -} -//# sourceMappingURL=lodash.merge.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/merge.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/merge.js deleted file mode 100644 index d821c714..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/merge.js +++ /dev/null @@ -1,162 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.merge = void 0; -/* eslint-disable @typescript-eslint/no-explicit-any */ -const lodash_merge_1 = require("./lodash.merge"); -const MAX_LEVEL = 20; -/** - * Merges objects together - * @param args - objects / values to be merged - */ -function merge(...args) { - let result = args.shift(); - const objects = new WeakMap(); - while (args.length > 0) { - result = mergeTwoObjects(result, args.shift(), 0, objects); - } - return result; -} -exports.merge = merge; -function takeValue(value) { - if (isArray(value)) { - return value.slice(); - } - return value; -} -/** - * Merges two objects - * @param one - first object - * @param two - second object - * @param level - current deep level - * @param objects - objects holder that has been already referenced - to prevent - * cyclic dependency - */ -function mergeTwoObjects(one, two, level = 0, objects) { - let result; - if (level > MAX_LEVEL) { - return undefined; - } - level++; - if (isPrimitive(one) || isPrimitive(two) || isFunction(two)) { - result = takeValue(two); - } - else if (isArray(one)) { - result = one.slice(); - if (isArray(two)) { - for (let i = 0, j = two.length; i < j; i++) { - result.push(takeValue(two[i])); - } - } - else if (isObject(two)) { - const keys = Object.keys(two); - for (let i = 0, j = keys.length; i < j; i++) { - const key = keys[i]; - result[key] = takeValue(two[key]); - } - } - } - else if (isObject(one)) { - if (isObject(two)) { - if (!shouldMerge(one, two)) { - return two; - } - result = Object.assign({}, one); - const keys = Object.keys(two); - for (let i = 0, j = keys.length; i < j; i++) { - const key = keys[i]; - const twoValue = two[key]; - if (isPrimitive(twoValue)) { - if (typeof twoValue === 'undefined') { - delete result[key]; - } - else { - // result[key] = takeValue(twoValue); - result[key] = twoValue; - } - } - else { - const obj1 = result[key]; - const obj2 = twoValue; - if (wasObjectReferenced(one, key, objects) || - wasObjectReferenced(two, key, objects)) { - delete result[key]; - } - else { - if (isObject(obj1) && isObject(obj2)) { - const arr1 = objects.get(obj1) || []; - const arr2 = objects.get(obj2) || []; - arr1.push({ obj: one, key }); - arr2.push({ obj: two, key }); - objects.set(obj1, arr1); - objects.set(obj2, arr2); - } - result[key] = mergeTwoObjects(result[key], twoValue, level, objects); - } - } - } - } - else { - result = two; - } - } - return result; -} -/** - * Function to check if object has been already reference - * @param obj - * @param key - * @param objects - */ -function wasObjectReferenced(obj, key, objects) { - const arr = objects.get(obj[key]) || []; - for (let i = 0, j = arr.length; i < j; i++) { - const info = arr[i]; - if (info.key === key && info.obj === obj) { - return true; - } - } - return false; -} -function isArray(value) { - return Array.isArray(value); -} -function isFunction(value) { - return typeof value === 'function'; -} -function isObject(value) { - return (!isPrimitive(value) && - !isArray(value) && - !isFunction(value) && - typeof value === 'object'); -} -function isPrimitive(value) { - return (typeof value === 'string' || - typeof value === 'number' || - typeof value === 'boolean' || - typeof value === 'undefined' || - value instanceof Date || - value instanceof RegExp || - value === null); -} -function shouldMerge(one, two) { - if (!(0, lodash_merge_1.isPlainObject)(one) || !(0, lodash_merge_1.isPlainObject)(two)) { - return false; - } - return true; -} -//# sourceMappingURL=merge.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/promise.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/promise.js deleted file mode 100644 index e564737a..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/promise.js +++ /dev/null @@ -1,40 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Deferred = void 0; -class Deferred { - _promise; - _resolve; - _reject; - constructor() { - this._promise = new Promise((resolve, reject) => { - this._resolve = resolve; - this._reject = reject; - }); - } - get promise() { - return this._promise; - } - resolve(val) { - this._resolve(val); - } - reject(err) { - this._reject(err); - } -} -exports.Deferred = Deferred; -//# sourceMappingURL=promise.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/timeout.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/timeout.js deleted file mode 100644 index fd45a561..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/timeout.js +++ /dev/null @@ -1,56 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.callWithTimeout = exports.TimeoutError = void 0; -/** - * Error that is thrown on timeouts. - */ -class TimeoutError extends Error { - constructor(message) { - super(message); - // manually adjust prototype to retain `instanceof` functionality when targeting ES5, see: - // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work - Object.setPrototypeOf(this, TimeoutError.prototype); - } -} -exports.TimeoutError = TimeoutError; -/** - * Adds a timeout to a promise and rejects if the specified timeout has elapsed. Also rejects if the specified promise - * rejects, and resolves if the specified promise resolves. - * - *

    NOTE: this operation will continue even after it throws a {@link TimeoutError}. - * - * @param promise promise to use with timeout. - * @param timeout the timeout in milliseconds until the returned promise is rejected. - */ -function callWithTimeout(promise, timeout) { - let timeoutHandle; - const timeoutPromise = new Promise(function timeoutFunction(_resolve, reject) { - timeoutHandle = setTimeout(function timeoutHandler() { - reject(new TimeoutError('Operation timed out.')); - }, timeout); - }); - return Promise.race([promise, timeoutPromise]).then(result => { - clearTimeout(timeoutHandle); - return result; - }, reason => { - clearTimeout(timeoutHandle); - throw reason; - }); -} -exports.callWithTimeout = callWithTimeout; -//# sourceMappingURL=timeout.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/url.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/url.js deleted file mode 100644 index 7bce5b50..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/utils/url.js +++ /dev/null @@ -1,45 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isUrlIgnored = exports.urlMatches = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function urlMatches(url, urlToMatch) { - if (typeof urlToMatch === 'string') { - return url === urlToMatch; - } - else { - return !!url.match(urlToMatch); - } -} -exports.urlMatches = urlMatches; -/** - * Check if {@param url} should be ignored when comparing against {@param ignoredUrls} - * @param url - * @param ignoredUrls - */ -function isUrlIgnored(url, ignoredUrls) { - if (!ignoredUrls) { - return false; - } - for (const ignoreUrl of ignoredUrls) { - if (urlMatches(url, ignoreUrl)) { - return true; - } - } - return false; -} -exports.isUrlIgnored = isUrlIgnored; -//# sourceMappingURL=url.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/core/build/src/version.js b/claude-code-source/node_modules/@opentelemetry/core/build/src/version.js deleted file mode 100644 index deecc74a..00000000 --- a/claude-code-source/node_modules/@opentelemetry/core/build/src/version.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.VERSION = void 0; -// this is autogenerated file, see scripts/version-update.js -exports.VERSION = '2.2.0'; -//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/OTLPLogExporter.js b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/OTLPLogExporter.js deleted file mode 100644 index ee67c2dd..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/OTLPLogExporter.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPLogExporter = void 0; -const otlp_grpc_exporter_base_1 = require("@opentelemetry/otlp-grpc-exporter-base"); -const otlp_transformer_1 = require("@opentelemetry/otlp-transformer"); -const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base"); -/** - * OTLP Logs Exporter for Node - */ -class OTLPLogExporter extends otlp_exporter_base_1.OTLPExporterBase { - constructor(config = {}) { - super((0, otlp_grpc_exporter_base_1.createOtlpGrpcExportDelegate)((0, otlp_grpc_exporter_base_1.convertLegacyOtlpGrpcOptions)(config, 'LOGS'), otlp_transformer_1.ProtobufLogsSerializer, 'LogsExportService', '/opentelemetry.proto.collector.logs.v1.LogsService/Export')); - } -} -exports.OTLPLogExporter = OTLPLogExporter; -//# sourceMappingURL=OTLPLogExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/index.js deleted file mode 100644 index 52d5e649..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-grpc/build/src/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPLogExporter = void 0; -var OTLPLogExporter_1 = require("./OTLPLogExporter"); -Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function () { return OTLPLogExporter_1.OTLPLogExporter; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/index.js deleted file mode 100644 index d074d1d3..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPLogExporter = void 0; -var platform_1 = require("./platform"); -Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function () { return platform_1.OTLPLogExporter; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/index.js deleted file mode 100644 index 0c66169c..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPLogExporter = void 0; -var node_1 = require("./node"); -Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function () { return node_1.OTLPLogExporter; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/OTLPLogExporter.js b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/OTLPLogExporter.js deleted file mode 100644 index 0d5ba863..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/OTLPLogExporter.js +++ /dev/null @@ -1,33 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPLogExporter = void 0; -const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base"); -const otlp_transformer_1 = require("@opentelemetry/otlp-transformer"); -const node_http_1 = require("@opentelemetry/otlp-exporter-base/node-http"); -/** - * Collector Logs Exporter for Node - */ -class OTLPLogExporter extends otlp_exporter_base_1.OTLPExporterBase { - constructor(config = {}) { - super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, 'LOGS', 'v1/logs', { - 'Content-Type': 'application/json', - }), otlp_transformer_1.JsonLogsSerializer)); - } -} -exports.OTLPLogExporter = OTLPLogExporter; -//# sourceMappingURL=OTLPLogExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/index.js deleted file mode 100644 index 52d5e649..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-http/build/src/platform/node/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPLogExporter = void 0; -var OTLPLogExporter_1 = require("./OTLPLogExporter"); -Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function () { return OTLPLogExporter_1.OTLPLogExporter; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/index.js deleted file mode 100644 index f0e2d801..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPLogExporter = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var platform_1 = require("./platform"); -Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function () { return platform_1.OTLPLogExporter; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/index.js deleted file mode 100644 index 9a00e764..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPLogExporter = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var node_1 = require("./node"); -Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function () { return node_1.OTLPLogExporter; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/OTLPLogExporter.js b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/OTLPLogExporter.js deleted file mode 100644 index 8f6facfa..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/OTLPLogExporter.js +++ /dev/null @@ -1,33 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPLogExporter = void 0; -const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base"); -const otlp_transformer_1 = require("@opentelemetry/otlp-transformer"); -const node_http_1 = require("@opentelemetry/otlp-exporter-base/node-http"); -/** - * OTLP Log Protobuf Exporter for Node.js - */ -class OTLPLogExporter extends otlp_exporter_base_1.OTLPExporterBase { - constructor(config = {}) { - super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, 'LOGS', 'v1/logs', { - 'Content-Type': 'application/x-protobuf', - }), otlp_transformer_1.ProtobufLogsSerializer)); - } -} -exports.OTLPLogExporter = OTLPLogExporter; -//# sourceMappingURL=OTLPLogExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/index.js deleted file mode 100644 index 52d5e649..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-logs-otlp-proto/build/src/platform/node/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPLogExporter = void 0; -var OTLPLogExporter_1 = require("./OTLPLogExporter"); -Object.defineProperty(exports, "OTLPLogExporter", { enumerable: true, get: function () { return OTLPLogExporter_1.OTLPLogExporter; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/OTLPMetricExporter.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/OTLPMetricExporter.js deleted file mode 100644 index 7c1862d9..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/OTLPMetricExporter.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPMetricExporter = void 0; -const exporter_metrics_otlp_http_1 = require("@opentelemetry/exporter-metrics-otlp-http"); -const otlp_grpc_exporter_base_1 = require("@opentelemetry/otlp-grpc-exporter-base"); -const otlp_transformer_1 = require("@opentelemetry/otlp-transformer"); -/** - * OTLP-gRPC metric exporter - */ -class OTLPMetricExporter extends exporter_metrics_otlp_http_1.OTLPMetricExporterBase { - constructor(config) { - super((0, otlp_grpc_exporter_base_1.createOtlpGrpcExportDelegate)((0, otlp_grpc_exporter_base_1.convertLegacyOtlpGrpcOptions)(config ?? {}, 'METRICS'), otlp_transformer_1.ProtobufMetricsSerializer, 'MetricsExportService', '/opentelemetry.proto.collector.metrics.v1.MetricsService/Export'), config); - } -} -exports.OTLPMetricExporter = OTLPMetricExporter; -//# sourceMappingURL=OTLPMetricExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/index.js deleted file mode 100644 index 89bafa1f..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-grpc/build/src/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPMetricExporter = void 0; -var OTLPMetricExporter_1 = require("./OTLPMetricExporter"); -Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function () { return OTLPMetricExporter_1.OTLPMetricExporter; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterBase.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterBase.js deleted file mode 100644 index dfd0168e..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterBase.js +++ /dev/null @@ -1,104 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPMetricExporterBase = exports.LowMemoryTemporalitySelector = exports.DeltaTemporalitySelector = exports.CumulativeTemporalitySelector = void 0; -const core_1 = require("@opentelemetry/core"); -const sdk_metrics_1 = require("@opentelemetry/sdk-metrics"); -const OTLPMetricExporterOptions_1 = require("./OTLPMetricExporterOptions"); -const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base"); -const api_1 = require("@opentelemetry/api"); -const CumulativeTemporalitySelector = () => sdk_metrics_1.AggregationTemporality.CUMULATIVE; -exports.CumulativeTemporalitySelector = CumulativeTemporalitySelector; -const DeltaTemporalitySelector = (instrumentType) => { - switch (instrumentType) { - case sdk_metrics_1.InstrumentType.COUNTER: - case sdk_metrics_1.InstrumentType.OBSERVABLE_COUNTER: - case sdk_metrics_1.InstrumentType.GAUGE: - case sdk_metrics_1.InstrumentType.HISTOGRAM: - case sdk_metrics_1.InstrumentType.OBSERVABLE_GAUGE: - return sdk_metrics_1.AggregationTemporality.DELTA; - case sdk_metrics_1.InstrumentType.UP_DOWN_COUNTER: - case sdk_metrics_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER: - return sdk_metrics_1.AggregationTemporality.CUMULATIVE; - } -}; -exports.DeltaTemporalitySelector = DeltaTemporalitySelector; -const LowMemoryTemporalitySelector = (instrumentType) => { - switch (instrumentType) { - case sdk_metrics_1.InstrumentType.COUNTER: - case sdk_metrics_1.InstrumentType.HISTOGRAM: - return sdk_metrics_1.AggregationTemporality.DELTA; - case sdk_metrics_1.InstrumentType.GAUGE: - case sdk_metrics_1.InstrumentType.UP_DOWN_COUNTER: - case sdk_metrics_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER: - case sdk_metrics_1.InstrumentType.OBSERVABLE_COUNTER: - case sdk_metrics_1.InstrumentType.OBSERVABLE_GAUGE: - return sdk_metrics_1.AggregationTemporality.CUMULATIVE; - } -}; -exports.LowMemoryTemporalitySelector = LowMemoryTemporalitySelector; -function chooseTemporalitySelectorFromEnvironment() { - const configuredTemporality = ((0, core_1.getStringFromEnv)('OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE') ?? - 'cumulative').toLowerCase(); - if (configuredTemporality === 'cumulative') { - return exports.CumulativeTemporalitySelector; - } - if (configuredTemporality === 'delta') { - return exports.DeltaTemporalitySelector; - } - if (configuredTemporality === 'lowmemory') { - return exports.LowMemoryTemporalitySelector; - } - api_1.diag.warn(`OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE is set to '${configuredTemporality}', but only 'cumulative' and 'delta' are allowed. Using default ('cumulative') instead.`); - return exports.CumulativeTemporalitySelector; -} -function chooseTemporalitySelector(temporalityPreference) { - // Directly passed preference has priority. - if (temporalityPreference != null) { - if (temporalityPreference === OTLPMetricExporterOptions_1.AggregationTemporalityPreference.DELTA) { - return exports.DeltaTemporalitySelector; - } - else if (temporalityPreference === OTLPMetricExporterOptions_1.AggregationTemporalityPreference.LOWMEMORY) { - return exports.LowMemoryTemporalitySelector; - } - return exports.CumulativeTemporalitySelector; - } - return chooseTemporalitySelectorFromEnvironment(); -} -const DEFAULT_AGGREGATION = Object.freeze({ - type: sdk_metrics_1.AggregationType.DEFAULT, -}); -function chooseAggregationSelector(config) { - return config?.aggregationPreference ?? (() => DEFAULT_AGGREGATION); -} -class OTLPMetricExporterBase extends otlp_exporter_base_1.OTLPExporterBase { - _aggregationTemporalitySelector; - _aggregationSelector; - constructor(delegate, config) { - super(delegate); - this._aggregationSelector = chooseAggregationSelector(config); - this._aggregationTemporalitySelector = chooseTemporalitySelector(config?.temporalityPreference); - } - selectAggregation(instrumentType) { - return this._aggregationSelector(instrumentType); - } - selectAggregationTemporality(instrumentType) { - return this._aggregationTemporalitySelector(instrumentType); - } -} -exports.OTLPMetricExporterBase = OTLPMetricExporterBase; -//# sourceMappingURL=OTLPMetricExporterBase.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterOptions.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterOptions.js deleted file mode 100644 index 239bb04e..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/OTLPMetricExporterOptions.js +++ /dev/null @@ -1,25 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AggregationTemporalityPreference = void 0; -var AggregationTemporalityPreference; -(function (AggregationTemporalityPreference) { - AggregationTemporalityPreference[AggregationTemporalityPreference["DELTA"] = 0] = "DELTA"; - AggregationTemporalityPreference[AggregationTemporalityPreference["CUMULATIVE"] = 1] = "CUMULATIVE"; - AggregationTemporalityPreference[AggregationTemporalityPreference["LOWMEMORY"] = 2] = "LOWMEMORY"; -})(AggregationTemporalityPreference = exports.AggregationTemporalityPreference || (exports.AggregationTemporalityPreference = {})); -//# sourceMappingURL=OTLPMetricExporterOptions.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/index.js deleted file mode 100644 index 82165886..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/index.js +++ /dev/null @@ -1,28 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPMetricExporterBase = exports.LowMemoryTemporalitySelector = exports.DeltaTemporalitySelector = exports.CumulativeTemporalitySelector = exports.AggregationTemporalityPreference = exports.OTLPMetricExporter = void 0; -var platform_1 = require("./platform"); -Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function () { return platform_1.OTLPMetricExporter; } }); -var OTLPMetricExporterOptions_1 = require("./OTLPMetricExporterOptions"); -Object.defineProperty(exports, "AggregationTemporalityPreference", { enumerable: true, get: function () { return OTLPMetricExporterOptions_1.AggregationTemporalityPreference; } }); -var OTLPMetricExporterBase_1 = require("./OTLPMetricExporterBase"); -Object.defineProperty(exports, "CumulativeTemporalitySelector", { enumerable: true, get: function () { return OTLPMetricExporterBase_1.CumulativeTemporalitySelector; } }); -Object.defineProperty(exports, "DeltaTemporalitySelector", { enumerable: true, get: function () { return OTLPMetricExporterBase_1.DeltaTemporalitySelector; } }); -Object.defineProperty(exports, "LowMemoryTemporalitySelector", { enumerable: true, get: function () { return OTLPMetricExporterBase_1.LowMemoryTemporalitySelector; } }); -Object.defineProperty(exports, "OTLPMetricExporterBase", { enumerable: true, get: function () { return OTLPMetricExporterBase_1.OTLPMetricExporterBase; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/index.js deleted file mode 100644 index 5d3b9887..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPMetricExporter = void 0; -var node_1 = require("./node"); -Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function () { return node_1.OTLPMetricExporter; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/OTLPMetricExporter.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/OTLPMetricExporter.js deleted file mode 100644 index 13ea3433..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/OTLPMetricExporter.js +++ /dev/null @@ -1,33 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPMetricExporter = void 0; -const OTLPMetricExporterBase_1 = require("../../OTLPMetricExporterBase"); -const otlp_transformer_1 = require("@opentelemetry/otlp-transformer"); -const node_http_1 = require("@opentelemetry/otlp-exporter-base/node-http"); -/** - * OTLP Metric Exporter for Node.js - */ -class OTLPMetricExporter extends OTLPMetricExporterBase_1.OTLPMetricExporterBase { - constructor(config) { - super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config ?? {}, 'METRICS', 'v1/metrics', { - 'Content-Type': 'application/json', - }), otlp_transformer_1.JsonMetricsSerializer), config); - } -} -exports.OTLPMetricExporter = OTLPMetricExporter; -//# sourceMappingURL=OTLPMetricExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/index.js deleted file mode 100644 index 89bafa1f..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-http/build/src/platform/node/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPMetricExporter = void 0; -var OTLPMetricExporter_1 = require("./OTLPMetricExporter"); -Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function () { return OTLPMetricExporter_1.OTLPMetricExporter; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/index.js deleted file mode 100644 index e1a1b768..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPMetricExporter = void 0; -var platform_1 = require("./platform"); -Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function () { return platform_1.OTLPMetricExporter; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/index.js deleted file mode 100644 index 5d3b9887..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPMetricExporter = void 0; -var node_1 = require("./node"); -Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function () { return node_1.OTLPMetricExporter; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/OTLPMetricExporter.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/OTLPMetricExporter.js deleted file mode 100644 index 15d7b2c0..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/OTLPMetricExporter.js +++ /dev/null @@ -1,30 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPMetricExporter = void 0; -const exporter_metrics_otlp_http_1 = require("@opentelemetry/exporter-metrics-otlp-http"); -const otlp_transformer_1 = require("@opentelemetry/otlp-transformer"); -const node_http_1 = require("@opentelemetry/otlp-exporter-base/node-http"); -class OTLPMetricExporter extends exporter_metrics_otlp_http_1.OTLPMetricExporterBase { - constructor(config) { - super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config ?? {}, 'METRICS', 'v1/metrics', { - 'Content-Type': 'application/x-protobuf', - }), otlp_transformer_1.ProtobufMetricsSerializer), config); - } -} -exports.OTLPMetricExporter = OTLPMetricExporter; -//# sourceMappingURL=OTLPMetricExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/index.js deleted file mode 100644 index 89bafa1f..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-metrics-otlp-proto/build/src/platform/node/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPMetricExporter = void 0; -var OTLPMetricExporter_1 = require("./OTLPMetricExporter"); -Object.defineProperty(exports, "OTLPMetricExporter", { enumerable: true, get: function () { return OTLPMetricExporter_1.OTLPMetricExporter; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusExporter.js b/claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusExporter.js deleted file mode 100644 index 2edf78ac..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusExporter.js +++ /dev/null @@ -1,195 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PrometheusExporter = void 0; -const api_1 = require("@opentelemetry/api"); -const core_1 = require("@opentelemetry/core"); -const sdk_metrics_1 = require("@opentelemetry/sdk-metrics"); -const http_1 = require("http"); -const PrometheusSerializer_1 = require("./PrometheusSerializer"); -/** Node.js v8.x compat */ -const url_1 = require("url"); -class PrometheusExporter extends sdk_metrics_1.MetricReader { - static DEFAULT_OPTIONS = { - host: undefined, - port: 9464, - endpoint: '/metrics', - prefix: '', - appendTimestamp: false, - withResourceConstantLabels: undefined, - withoutTargetInfo: false, - }; - _host; - _port; - _baseUrl; - _endpoint; - _server; - _prefix; - _appendTimestamp; - _serializer; - _startServerPromise; - // This will be required when histogram is implemented. Leaving here so it is not forgotten - // Histogram cannot have a attribute named 'le' - // private static readonly RESERVED_HISTOGRAM_LABEL = 'le'; - /** - * Constructor - * @param config Exporter configuration - * @param callback Callback to be called after a server was started - */ - constructor(config = {}, callback = () => { }) { - super({ - aggregationSelector: _instrumentType => { - return { - type: sdk_metrics_1.AggregationType.DEFAULT, - }; - }, - aggregationTemporalitySelector: _instrumentType => sdk_metrics_1.AggregationTemporality.CUMULATIVE, - metricProducers: config.metricProducers, - }); - this._host = - config.host || - process.env.OTEL_EXPORTER_PROMETHEUS_HOST || - PrometheusExporter.DEFAULT_OPTIONS.host; - this._port = - config.port || - Number(process.env.OTEL_EXPORTER_PROMETHEUS_PORT) || - PrometheusExporter.DEFAULT_OPTIONS.port; - this._prefix = config.prefix || PrometheusExporter.DEFAULT_OPTIONS.prefix; - this._appendTimestamp = - typeof config.appendTimestamp === 'boolean' - ? config.appendTimestamp - : PrometheusExporter.DEFAULT_OPTIONS.appendTimestamp; - const _withResourceConstantLabels = config.withResourceConstantLabels || - PrometheusExporter.DEFAULT_OPTIONS.withResourceConstantLabels; - const _withoutTargetInfo = config.withoutTargetInfo || - PrometheusExporter.DEFAULT_OPTIONS.withoutTargetInfo; - // unref to prevent prometheus exporter from holding the process open on exit - this._server = (0, http_1.createServer)(this._requestHandler).unref(); - this._serializer = new PrometheusSerializer_1.PrometheusSerializer(this._prefix, this._appendTimestamp, _withResourceConstantLabels, _withoutTargetInfo); - this._baseUrl = `http://${this._host}:${this._port}/`; - this._endpoint = (config.endpoint || PrometheusExporter.DEFAULT_OPTIONS.endpoint).replace(/^([^/])/, '/$1'); - if (config.preventServerStart !== true) { - this.startServer().then(callback, err => { - api_1.diag.error(err); - callback(err); - }); - } - else if (callback) { - // Do not invoke callback immediately to avoid zalgo problem. - queueMicrotask(callback); - } - } - async onForceFlush() { - /** do nothing */ - } - /** - * Shuts down the export server and clears the registry - */ - onShutdown() { - return this.stopServer(); - } - /** - * Stops the Prometheus export server - */ - stopServer() { - if (!this._server) { - api_1.diag.debug('Prometheus stopServer() was called but server was never started.'); - return Promise.resolve(); - } - else { - return new Promise(resolve => { - this._server.close(err => { - if (!err) { - api_1.diag.debug('Prometheus exporter was stopped'); - } - else { - if (err.code !== - 'ERR_SERVER_NOT_RUNNING') { - (0, core_1.globalErrorHandler)(err); - } - } - resolve(); - }); - }); - } - } - /** - * Starts the Prometheus export server - */ - startServer() { - this._startServerPromise ??= new Promise((resolve, reject) => { - this._server.once('error', reject); - this._server.listen({ - port: this._port, - host: this._host, - }, () => { - api_1.diag.debug(`Prometheus exporter server started: ${this._host}:${this._port}/${this._endpoint}`); - resolve(); - }); - }); - return this._startServerPromise; - } - /** - * Request handler that responds with the current state of metrics - * @param _request Incoming HTTP request of server instance - * @param response HTTP response object used to response to request - */ - getMetricsRequestHandler(_request, response) { - this._exportMetrics(response); - } - /** - * Request handler used by http library to respond to incoming requests - * for the current state of metrics by the Prometheus backend. - * - * @param request Incoming HTTP request to export server - * @param response HTTP response object used to respond to request - */ - _requestHandler = (request, response) => { - if (request.url != null && - new url_1.URL(request.url, this._baseUrl).pathname === this._endpoint) { - this._exportMetrics(response); - } - else { - this._notFound(response); - } - }; - /** - * Responds to incoming message with current state of all metrics. - */ - _exportMetrics = (response) => { - response.statusCode = 200; - response.setHeader('content-type', 'text/plain'); - this.collect().then(collectionResult => { - const { resourceMetrics, errors } = collectionResult; - if (errors.length) { - api_1.diag.error('PrometheusExporter: metrics collection errors', ...errors); - } - response.end(this._serializer.serialize(resourceMetrics)); - }, err => { - response.end(`# failed to export metrics: ${err}`); - }); - }; - /** - * Responds with 404 status code to all requests that do not match the configured endpoint. - */ - _notFound = (response) => { - response.statusCode = 404; - response.end(); - }; -} -exports.PrometheusExporter = PrometheusExporter; -//# sourceMappingURL=PrometheusExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusSerializer.js b/claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusSerializer.js deleted file mode 100644 index 5cc25164..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/PrometheusSerializer.js +++ /dev/null @@ -1,264 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PrometheusSerializer = void 0; -const api_1 = require("@opentelemetry/api"); -const sdk_metrics_1 = require("@opentelemetry/sdk-metrics"); -const core_1 = require("@opentelemetry/core"); -function escapeString(str) { - return str.replace(/\\/g, '\\\\').replace(/\n/g, '\\n'); -} -/** - * String Attribute values are converted directly to Prometheus attribute values. - * Non-string values are represented as JSON-encoded strings. - * - * `undefined` is converted to an empty string. - */ -function escapeAttributeValue(str = '') { - if (typeof str !== 'string') { - str = JSON.stringify(str); - } - return escapeString(str).replace(/"/g, '\\"'); -} -const invalidCharacterRegex = /[^a-z0-9_]/gi; -const multipleUnderscoreRegex = /_{2,}/g; -/** - * Ensures metric names are valid Prometheus metric names by removing - * characters allowed by OpenTelemetry but disallowed by Prometheus. - * - * https://prometheus.io/docs/concepts/data_model/#metric-names-and-attributes - * - * 1. Names must match `[a-zA-Z_:][a-zA-Z0-9_:]*` - * - * 2. Colons are reserved for user defined recording rules. - * They should not be used by exporters or direct instrumentation. - * - * OpenTelemetry metric names are already validated in the Meter when they are created, - * and they match the format `[a-zA-Z][a-zA-Z0-9_.\-]*` which is very close to a valid - * prometheus metric name, so we only need to strip characters valid in OpenTelemetry - * but not valid in prometheus and replace them with '_'. - * - * @param name name to be sanitized - */ -function sanitizePrometheusMetricName(name) { - // replace all invalid characters with '_' - return name - .replace(invalidCharacterRegex, '_') - .replace(multipleUnderscoreRegex, '_'); -} -/** - * @private - * - * Helper method which assists in enforcing the naming conventions for metric - * names in Prometheus - * @param name the name of the metric - * @param type the kind of metric - * @returns string - */ -function enforcePrometheusNamingConvention(name, data) { - // Prometheus requires that metrics of the Counter kind have "_total" suffix - if (!name.endsWith('_total') && - data.dataPointType === sdk_metrics_1.DataPointType.SUM && - data.isMonotonic) { - name = name + '_total'; - } - return name; -} -function valueString(value) { - if (value === Infinity) { - return '+Inf'; - } - else if (value === -Infinity) { - return '-Inf'; - } - else { - // Handle finite numbers and NaN. - return `${value}`; - } -} -function toPrometheusType(metricData) { - switch (metricData.dataPointType) { - case sdk_metrics_1.DataPointType.SUM: - if (metricData.isMonotonic) { - return 'counter'; - } - return 'gauge'; - case sdk_metrics_1.DataPointType.GAUGE: - return 'gauge'; - case sdk_metrics_1.DataPointType.HISTOGRAM: - return 'histogram'; - default: - return 'untyped'; - } -} -function stringify(metricName, attributes, value, timestamp, additionalAttributes) { - let hasAttribute = false; - let attributesStr = ''; - for (const [key, val] of Object.entries(attributes)) { - const sanitizedAttributeName = sanitizePrometheusMetricName(key); - hasAttribute = true; - attributesStr += `${attributesStr.length > 0 ? ',' : ''}${sanitizedAttributeName}="${escapeAttributeValue(val)}"`; - } - if (additionalAttributes) { - for (const [key, val] of Object.entries(additionalAttributes)) { - const sanitizedAttributeName = sanitizePrometheusMetricName(key); - hasAttribute = true; - attributesStr += `${attributesStr.length > 0 ? ',' : ''}${sanitizedAttributeName}="${escapeAttributeValue(val)}"`; - } - } - if (hasAttribute) { - metricName += `{${attributesStr}}`; - } - return `${metricName} ${valueString(value)}${timestamp !== undefined ? ' ' + String(timestamp) : ''}\n`; -} -const NO_REGISTERED_METRICS = '# no registered metrics'; -class PrometheusSerializer { - _prefix; - _appendTimestamp; - _additionalAttributes; - _withResourceConstantLabels; - _withoutTargetInfo; - constructor(prefix, appendTimestamp = false, withResourceConstantLabels, withoutTargetInfo) { - if (prefix) { - this._prefix = prefix + '_'; - } - this._appendTimestamp = appendTimestamp; - this._withResourceConstantLabels = withResourceConstantLabels; - this._withoutTargetInfo = !!withoutTargetInfo; - } - serialize(resourceMetrics) { - let str = ''; - this._additionalAttributes = this._filterResourceConstantLabels(resourceMetrics.resource.attributes, this._withResourceConstantLabels); - for (const scopeMetrics of resourceMetrics.scopeMetrics) { - str += this._serializeScopeMetrics(scopeMetrics); - } - if (str === '') { - str += NO_REGISTERED_METRICS; - } - return this._serializeResource(resourceMetrics.resource) + str; - } - _filterResourceConstantLabels(attributes, pattern) { - if (pattern) { - const filteredAttributes = {}; - for (const [key, value] of Object.entries(attributes)) { - if (key.match(pattern)) { - filteredAttributes[key] = value; - } - } - return filteredAttributes; - } - return; - } - _serializeScopeMetrics(scopeMetrics) { - let str = ''; - for (const metric of scopeMetrics.metrics) { - str += this._serializeMetricData(metric) + '\n'; - } - return str; - } - _serializeMetricData(metricData) { - let name = sanitizePrometheusMetricName(escapeString(metricData.descriptor.name)); - if (this._prefix) { - name = `${this._prefix}${name}`; - } - const dataPointType = metricData.dataPointType; - name = enforcePrometheusNamingConvention(name, metricData); - const help = `# HELP ${name} ${escapeString(metricData.descriptor.description || 'description missing')}`; - const unit = metricData.descriptor.unit - ? `\n# UNIT ${name} ${escapeString(metricData.descriptor.unit)}` - : ''; - const type = `# TYPE ${name} ${toPrometheusType(metricData)}`; - let results = ''; - switch (dataPointType) { - case sdk_metrics_1.DataPointType.SUM: - case sdk_metrics_1.DataPointType.GAUGE: { - results = metricData.dataPoints - .map(it => this._serializeSingularDataPoint(name, metricData, it)) - .join(''); - break; - } - case sdk_metrics_1.DataPointType.HISTOGRAM: { - results = metricData.dataPoints - .map(it => this._serializeHistogramDataPoint(name, metricData, it)) - .join(''); - break; - } - default: { - api_1.diag.error(`Unrecognizable DataPointType: ${dataPointType} for metric "${name}"`); - } - } - return `${help}${unit}\n${type}\n${results}`.trim(); - } - _serializeSingularDataPoint(name, data, dataPoint) { - let results = ''; - name = enforcePrometheusNamingConvention(name, data); - const { value, attributes } = dataPoint; - const timestamp = (0, core_1.hrTimeToMilliseconds)(dataPoint.endTime); - results += stringify(name, attributes, value, this._appendTimestamp ? timestamp : undefined, this._additionalAttributes); - return results; - } - _serializeHistogramDataPoint(name, data, dataPoint) { - let results = ''; - name = enforcePrometheusNamingConvention(name, data); - const attributes = dataPoint.attributes; - const histogram = dataPoint.value; - const timestamp = (0, core_1.hrTimeToMilliseconds)(dataPoint.endTime); - /** Histogram["bucket"] is not typed with `number` */ - for (const key of ['count', 'sum']) { - const value = histogram[key]; - if (value != null) - results += stringify(name + '_' + key, attributes, value, this._appendTimestamp ? timestamp : undefined, this._additionalAttributes); - } - let cumulativeSum = 0; - const countEntries = histogram.buckets.counts.entries(); - let infiniteBoundaryDefined = false; - for (const [idx, val] of countEntries) { - cumulativeSum += val; - const upperBound = histogram.buckets.boundaries[idx]; - /** HistogramAggregator is producing different boundary output - - * in one case not including infinity values, in other - - * full, e.g. [0, 100] and [0, 100, Infinity] - * we should consider that in export, if Infinity is defined, use it - * as boundary - */ - if (upperBound === undefined && infiniteBoundaryDefined) { - break; - } - if (upperBound === Infinity) { - infiniteBoundaryDefined = true; - } - results += stringify(name + '_bucket', attributes, cumulativeSum, this._appendTimestamp ? timestamp : undefined, Object.assign({}, this._additionalAttributes ?? {}, { - le: upperBound === undefined || upperBound === Infinity - ? '+Inf' - : String(upperBound), - })); - } - return results; - } - _serializeResource(resource) { - if (this._withoutTargetInfo === true) { - return ''; - } - const name = 'target_info'; - const help = `# HELP ${name} Target metadata`; - const type = `# TYPE ${name} gauge`; - const results = stringify(name, resource.attributes, 1).trim(); - return `${help}\n${type}\n${results}\n`; - } -} -exports.PrometheusSerializer = PrometheusSerializer; -//# sourceMappingURL=PrometheusSerializer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/index.js deleted file mode 100644 index 0427e351..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-prometheus/build/src/index.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PrometheusSerializer = exports.PrometheusExporter = void 0; -var PrometheusExporter_1 = require("./PrometheusExporter"); -Object.defineProperty(exports, "PrometheusExporter", { enumerable: true, get: function () { return PrometheusExporter_1.PrometheusExporter; } }); -var PrometheusSerializer_1 = require("./PrometheusSerializer"); -Object.defineProperty(exports, "PrometheusSerializer", { enumerable: true, get: function () { return PrometheusSerializer_1.PrometheusSerializer; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/OTLPTraceExporter.js b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/OTLPTraceExporter.js deleted file mode 100644 index d65398ca..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/OTLPTraceExporter.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPTraceExporter = void 0; -const otlp_grpc_exporter_base_1 = require("@opentelemetry/otlp-grpc-exporter-base"); -const otlp_transformer_1 = require("@opentelemetry/otlp-transformer"); -const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base"); -/** - * OTLP Trace Exporter for Node - */ -class OTLPTraceExporter extends otlp_exporter_base_1.OTLPExporterBase { - constructor(config = {}) { - super((0, otlp_grpc_exporter_base_1.createOtlpGrpcExportDelegate)((0, otlp_grpc_exporter_base_1.convertLegacyOtlpGrpcOptions)(config, 'TRACES'), otlp_transformer_1.ProtobufTraceSerializer, 'TraceExportService', '/opentelemetry.proto.collector.trace.v1.TraceService/Export')); - } -} -exports.OTLPTraceExporter = OTLPTraceExporter; -//# sourceMappingURL=OTLPTraceExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/index.js deleted file mode 100644 index 532d74f2..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-grpc/build/src/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPTraceExporter = void 0; -var OTLPTraceExporter_1 = require("./OTLPTraceExporter"); -Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function () { return OTLPTraceExporter_1.OTLPTraceExporter; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/index.js deleted file mode 100644 index 7fcd8476..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPTraceExporter = void 0; -var platform_1 = require("./platform"); -Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function () { return platform_1.OTLPTraceExporter; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/index.js deleted file mode 100644 index e9701c10..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPTraceExporter = void 0; -var node_1 = require("./node"); -Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function () { return node_1.OTLPTraceExporter; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/OTLPTraceExporter.js b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/OTLPTraceExporter.js deleted file mode 100644 index 2acd49b9..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/OTLPTraceExporter.js +++ /dev/null @@ -1,33 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPTraceExporter = void 0; -const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base"); -const otlp_transformer_1 = require("@opentelemetry/otlp-transformer"); -const node_http_1 = require("@opentelemetry/otlp-exporter-base/node-http"); -/** - * Collector Trace Exporter for Node - */ -class OTLPTraceExporter extends otlp_exporter_base_1.OTLPExporterBase { - constructor(config = {}) { - super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, 'TRACES', 'v1/traces', { - 'Content-Type': 'application/json', - }), otlp_transformer_1.JsonTraceSerializer)); - } -} -exports.OTLPTraceExporter = OTLPTraceExporter; -//# sourceMappingURL=OTLPTraceExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/index.js deleted file mode 100644 index 532d74f2..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-http/build/src/platform/node/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPTraceExporter = void 0; -var OTLPTraceExporter_1 = require("./OTLPTraceExporter"); -Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function () { return OTLPTraceExporter_1.OTLPTraceExporter; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/index.js deleted file mode 100644 index c72a409a..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPTraceExporter = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var platform_1 = require("./platform"); -Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function () { return platform_1.OTLPTraceExporter; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/index.js deleted file mode 100644 index 7d7c7e67..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPTraceExporter = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var node_1 = require("./node"); -Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function () { return node_1.OTLPTraceExporter; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/OTLPTraceExporter.js b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/OTLPTraceExporter.js deleted file mode 100644 index b17e7f90..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/OTLPTraceExporter.js +++ /dev/null @@ -1,33 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPTraceExporter = void 0; -const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base"); -const otlp_transformer_1 = require("@opentelemetry/otlp-transformer"); -const node_http_1 = require("@opentelemetry/otlp-exporter-base/node-http"); -/** - * Collector Trace Exporter for Node with protobuf - */ -class OTLPTraceExporter extends otlp_exporter_base_1.OTLPExporterBase { - constructor(config = {}) { - super((0, node_http_1.createOtlpHttpExportDelegate)((0, node_http_1.convertLegacyHttpOptions)(config, 'TRACES', 'v1/traces', { - 'Content-Type': 'application/x-protobuf', - }), otlp_transformer_1.ProtobufTraceSerializer)); - } -} -exports.OTLPTraceExporter = OTLPTraceExporter; -//# sourceMappingURL=OTLPTraceExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/index.js deleted file mode 100644 index 532d74f2..00000000 --- a/claude-code-source/node_modules/@opentelemetry/exporter-trace-otlp-proto/build/src/platform/node/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPTraceExporter = void 0; -var OTLPTraceExporter_1 = require("./OTLPTraceExporter"); -Object.defineProperty(exports, "OTLPTraceExporter", { enumerable: true, get: function () { return OTLPTraceExporter_1.OTLPTraceExporter; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/OTLPExporterBase.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/OTLPExporterBase.js deleted file mode 100644 index a370aa54..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/OTLPExporterBase.js +++ /dev/null @@ -1,40 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPExporterBase = void 0; -class OTLPExporterBase { - _delegate; - constructor(_delegate) { - this._delegate = _delegate; - } - /** - * Export items. - * @param items - * @param resultCallback - */ - export(items, resultCallback) { - this._delegate.export(items, resultCallback); - } - forceFlush() { - return this._delegate.forceFlush(); - } - shutdown() { - return this._delegate.shutdown(); - } -} -exports.OTLPExporterBase = OTLPExporterBase; -//# sourceMappingURL=OTLPExporterBase.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/bounded-queue-export-promise-handler.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/bounded-queue-export-promise-handler.js deleted file mode 100644 index e234e32b..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/bounded-queue-export-promise-handler.js +++ /dev/null @@ -1,54 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createBoundedQueueExportPromiseHandler = void 0; -class BoundedQueueExportPromiseHandler { - _concurrencyLimit; - _sendingPromises = []; - /** - * @param concurrencyLimit maximum promises allowed in a queue at the same time. - */ - constructor(concurrencyLimit) { - this._concurrencyLimit = concurrencyLimit; - } - pushPromise(promise) { - if (this.hasReachedLimit()) { - throw new Error('Concurrency Limit reached'); - } - this._sendingPromises.push(promise); - const popPromise = () => { - const index = this._sendingPromises.indexOf(promise); - void this._sendingPromises.splice(index, 1); - }; - promise.then(popPromise, popPromise); - } - hasReachedLimit() { - return this._sendingPromises.length >= this._concurrencyLimit; - } - async awaitAll() { - await Promise.all(this._sendingPromises); - } -} -/** - * Promise queue for keeping track of export promises. Finished promises will be auto-dequeued. - * Allows for awaiting all promises in the queue. - */ -function createBoundedQueueExportPromiseHandler(options) { - return new BoundedQueueExportPromiseHandler(options.concurrencyLimit); -} -exports.createBoundedQueueExportPromiseHandler = createBoundedQueueExportPromiseHandler; -//# sourceMappingURL=bounded-queue-export-promise-handler.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/convert-legacy-http-options.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/convert-legacy-http-options.js deleted file mode 100644 index 758fcfb0..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/convert-legacy-http-options.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.convertLegacyHeaders = void 0; -const shared_configuration_1 = require("./shared-configuration"); -function convertLegacyHeaders(config) { - if (typeof config.headers === 'function') { - return config.headers; - } - return (0, shared_configuration_1.wrapStaticHeadersInFunction)(config.headers); -} -exports.convertLegacyHeaders = convertLegacyHeaders; -//# sourceMappingURL=convert-legacy-http-options.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/convert-legacy-node-http-options.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/convert-legacy-node-http-options.js deleted file mode 100644 index 7b50474f..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/convert-legacy-node-http-options.js +++ /dev/null @@ -1,47 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.convertLegacyHttpOptions = void 0; -const api_1 = require("@opentelemetry/api"); -const otlp_node_http_configuration_1 = require("./otlp-node-http-configuration"); -const index_node_http_1 = require("../index-node-http"); -const otlp_node_http_env_configuration_1 = require("./otlp-node-http-env-configuration"); -const convert_legacy_http_options_1 = require("./convert-legacy-http-options"); -function convertLegacyAgentOptions(config) { - if (typeof config.httpAgentOptions === 'function') { - return config.httpAgentOptions; - } - let legacy = config.httpAgentOptions; - if (config.keepAlive != null) { - legacy = { keepAlive: config.keepAlive, ...legacy }; - } - if (legacy != null) { - return (0, index_node_http_1.httpAgentFactoryFromOptions)(legacy); - } - else { - return undefined; - } -} -/** - * @deprecated this will be removed in 2.0 - * @param config - * @param signalIdentifier - * @param signalResourcePath - * @param requiredHeaders - */ -function convertLegacyHttpOptions(config, signalIdentifier, signalResourcePath, requiredHeaders) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (config.metadata) { - api_1.diag.warn('Metadata cannot be set when using http'); - } - return (0, otlp_node_http_configuration_1.mergeOtlpNodeHttpConfigurationWithDefaults)({ - url: config.url, - headers: (0, convert_legacy_http_options_1.convertLegacyHeaders)(config), - concurrencyLimit: config.concurrencyLimit, - timeoutMillis: config.timeoutMillis, - compression: config.compression, - agentFactory: convertLegacyAgentOptions(config), - userAgent: config.userAgent, - }, (0, otlp_node_http_env_configuration_1.getNodeHttpConfigurationFromEnvironment)(signalIdentifier, signalResourcePath), (0, otlp_node_http_configuration_1.getNodeHttpConfigurationDefaults)(requiredHeaders, signalResourcePath)); -} -exports.convertLegacyHttpOptions = convertLegacyHttpOptions; -//# sourceMappingURL=convert-legacy-node-http-options.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/legacy-node-configuration.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/legacy-node-configuration.js deleted file mode 100644 index 863c8cdc..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/legacy-node-configuration.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.CompressionAlgorithm = void 0; -var CompressionAlgorithm; -(function (CompressionAlgorithm) { - CompressionAlgorithm["NONE"] = "none"; - CompressionAlgorithm["GZIP"] = "gzip"; -})(CompressionAlgorithm = exports.CompressionAlgorithm || (exports.CompressionAlgorithm = {})); -//# sourceMappingURL=legacy-node-configuration.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-http-configuration.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-http-configuration.js deleted file mode 100644 index 28a89dac..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-http-configuration.js +++ /dev/null @@ -1,75 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getHttpConfigurationDefaults = exports.mergeOtlpHttpConfigurationWithDefaults = void 0; -const shared_configuration_1 = require("./shared-configuration"); -const util_1 = require("../util"); -function mergeHeaders(userProvidedHeaders, fallbackHeaders, defaultHeaders) { - return async () => { - const requiredHeaders = { - ...(await defaultHeaders()), - }; - const headers = {}; - // add fallback ones first - if (fallbackHeaders != null) { - Object.assign(headers, await fallbackHeaders()); - } - // override with user-provided ones - if (userProvidedHeaders != null) { - Object.assign(headers, (0, util_1.validateAndNormalizeHeaders)(await userProvidedHeaders())); - } - // override required ones. - return Object.assign(headers, requiredHeaders); - }; -} -function validateUserProvidedUrl(url) { - if (url == null) { - return undefined; - } - try { - // NOTE: In non-browser environments, `globalThis.location` will be `undefined`. - const base = globalThis.location?.href; - return new URL(url, base).href; - } - catch { - throw new Error(`Configuration: Could not parse user-provided export URL: '${url}'`); - } -} -/** - * @param userProvidedConfiguration Configuration options provided by the user in code. - * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option. - * @param defaultConfiguration The defaults as defined by the exporter specification - */ -function mergeOtlpHttpConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) { - return { - ...(0, shared_configuration_1.mergeOtlpSharedConfigurationWithDefaults)(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration), - headers: mergeHeaders(userProvidedConfiguration.headers, fallbackConfiguration.headers, defaultConfiguration.headers), - url: validateUserProvidedUrl(userProvidedConfiguration.url) ?? - fallbackConfiguration.url ?? - defaultConfiguration.url, - }; -} -exports.mergeOtlpHttpConfigurationWithDefaults = mergeOtlpHttpConfigurationWithDefaults; -function getHttpConfigurationDefaults(requiredHeaders, signalResourcePath) { - return { - ...(0, shared_configuration_1.getSharedConfigurationDefaults)(), - headers: async () => requiredHeaders, - url: 'http://localhost:4318/' + signalResourcePath, - }; -} -exports.getHttpConfigurationDefaults = getHttpConfigurationDefaults; -//# sourceMappingURL=otlp-http-configuration.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-node-http-configuration.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-node-http-configuration.js deleted file mode 100644 index 2fe2d26f..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-node-http-configuration.js +++ /dev/null @@ -1,56 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getNodeHttpConfigurationDefaults = exports.mergeOtlpNodeHttpConfigurationWithDefaults = exports.httpAgentFactoryFromOptions = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const otlp_http_configuration_1 = require("./otlp-http-configuration"); -function httpAgentFactoryFromOptions(options) { - return async (protocol) => { - const isInsecure = protocol === 'http:'; - const module = isInsecure ? import('http') : import('https'); - const { Agent } = await module; - if (isInsecure) { - // eslint-disable-next-line @typescript-eslint/no-unused-vars -- these props should not be used in agent options - const { ca, cert, key, ...insecureOptions } = options; - return new Agent(insecureOptions); - } - return new Agent(options); - }; -} -exports.httpAgentFactoryFromOptions = httpAgentFactoryFromOptions; -/** - * @param userProvidedConfiguration Configuration options provided by the user in code. - * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option. - * @param defaultConfiguration The defaults as defined by the exporter specification - */ -function mergeOtlpNodeHttpConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) { - return { - ...(0, otlp_http_configuration_1.mergeOtlpHttpConfigurationWithDefaults)(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration), - agentFactory: userProvidedConfiguration.agentFactory ?? - fallbackConfiguration.agentFactory ?? - defaultConfiguration.agentFactory, - userAgent: userProvidedConfiguration.userAgent, - }; -} -exports.mergeOtlpNodeHttpConfigurationWithDefaults = mergeOtlpNodeHttpConfigurationWithDefaults; -function getNodeHttpConfigurationDefaults(requiredHeaders, signalResourcePath) { - return { - ...(0, otlp_http_configuration_1.getHttpConfigurationDefaults)(requiredHeaders, signalResourcePath), - agentFactory: httpAgentFactoryFromOptions({ keepAlive: true }), - }; -} -exports.getNodeHttpConfigurationDefaults = getNodeHttpConfigurationDefaults; -//# sourceMappingURL=otlp-node-http-configuration.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-node-http-env-configuration.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-node-http-env-configuration.js deleted file mode 100644 index 1465531c..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/otlp-node-http-env-configuration.js +++ /dev/null @@ -1,134 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getNodeHttpConfigurationFromEnvironment = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const fs = require("fs"); -const path = require("path"); -const core_1 = require("@opentelemetry/core"); -const api_1 = require("@opentelemetry/api"); -const shared_env_configuration_1 = require("./shared-env-configuration"); -const shared_configuration_1 = require("./shared-configuration"); -const otlp_node_http_configuration_1 = require("./otlp-node-http-configuration"); -function getStaticHeadersFromEnv(signalIdentifier) { - const signalSpecificRawHeaders = (0, core_1.getStringFromEnv)(`OTEL_EXPORTER_OTLP_${signalIdentifier}_HEADERS`); - const nonSignalSpecificRawHeaders = (0, core_1.getStringFromEnv)('OTEL_EXPORTER_OTLP_HEADERS'); - const signalSpecificHeaders = (0, core_1.parseKeyPairsIntoRecord)(signalSpecificRawHeaders); - const nonSignalSpecificHeaders = (0, core_1.parseKeyPairsIntoRecord)(nonSignalSpecificRawHeaders); - if (Object.keys(signalSpecificHeaders).length === 0 && - Object.keys(nonSignalSpecificHeaders).length === 0) { - return undefined; - } - // headers are combined instead of overwritten, with the specific headers taking precedence over - // the non-specific ones. - return Object.assign({}, (0, core_1.parseKeyPairsIntoRecord)(nonSignalSpecificRawHeaders), (0, core_1.parseKeyPairsIntoRecord)(signalSpecificRawHeaders)); -} -function appendRootPathToUrlIfNeeded(url) { - try { - const parsedUrl = new URL(url); - // This will automatically append '/' if there's no root path. - return parsedUrl.toString(); - } - catch { - api_1.diag.warn(`Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`); - return undefined; - } -} -function appendResourcePathToUrl(url, path) { - try { - // just try to parse, if it fails we catch and warn. - new URL(url); - } - catch { - api_1.diag.warn(`Configuration: Could not parse environment-provided export URL: '${url}', falling back to undefined`); - return undefined; - } - if (!url.endsWith('/')) { - url = url + '/'; - } - url += path; - try { - // just try to parse, if it fails we catch and warn. - new URL(url); - } - catch { - api_1.diag.warn(`Configuration: Provided URL appended with '${path}' is not a valid URL, using 'undefined' instead of '${url}'`); - return undefined; - } - return url; -} -function getNonSpecificUrlFromEnv(signalResourcePath) { - const envUrl = (0, core_1.getStringFromEnv)('OTEL_EXPORTER_OTLP_ENDPOINT'); - if (envUrl === undefined) { - return undefined; - } - return appendResourcePathToUrl(envUrl, signalResourcePath); -} -function getSpecificUrlFromEnv(signalIdentifier) { - const envUrl = (0, core_1.getStringFromEnv)(`OTEL_EXPORTER_OTLP_${signalIdentifier}_ENDPOINT`); - if (envUrl === undefined) { - return undefined; - } - return appendRootPathToUrlIfNeeded(envUrl); -} -function readFileFromEnv(signalSpecificEnvVar, nonSignalSpecificEnvVar, warningMessage) { - const signalSpecificPath = (0, core_1.getStringFromEnv)(signalSpecificEnvVar); - const nonSignalSpecificPath = (0, core_1.getStringFromEnv)(nonSignalSpecificEnvVar); - const filePath = signalSpecificPath ?? nonSignalSpecificPath; - if (filePath != null) { - try { - return fs.readFileSync(path.resolve(process.cwd(), filePath)); - } - catch { - api_1.diag.warn(warningMessage); - return undefined; - } - } - else { - return undefined; - } -} -function getClientCertificateFromEnv(signalIdentifier) { - return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_CERTIFICATE`, 'OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE', 'Failed to read client certificate chain file'); -} -function getClientKeyFromEnv(signalIdentifier) { - return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_KEY`, 'OTEL_EXPORTER_OTLP_CLIENT_KEY', 'Failed to read client certificate private key file'); -} -function getRootCertificateFromEnv(signalIdentifier) { - return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CERTIFICATE`, 'OTEL_EXPORTER_OTLP_CERTIFICATE', 'Failed to read root certificate file'); -} -/** - * Reads and returns configuration from the environment - * - * @param signalIdentifier all caps part in environment variables that identifies the signal (e.g.: METRICS, TRACES, LOGS) - * @param signalResourcePath signal resource path to append if necessary (e.g.: v1/metrics, v1/traces, v1/logs) - */ -function getNodeHttpConfigurationFromEnvironment(signalIdentifier, signalResourcePath) { - return { - ...(0, shared_env_configuration_1.getSharedConfigurationFromEnvironment)(signalIdentifier), - url: getSpecificUrlFromEnv(signalIdentifier) ?? - getNonSpecificUrlFromEnv(signalResourcePath), - headers: (0, shared_configuration_1.wrapStaticHeadersInFunction)(getStaticHeadersFromEnv(signalIdentifier)), - agentFactory: (0, otlp_node_http_configuration_1.httpAgentFactoryFromOptions)({ - keepAlive: true, - ca: getRootCertificateFromEnv(signalIdentifier), - cert: getClientCertificateFromEnv(signalIdentifier), - key: getClientKeyFromEnv(signalIdentifier), - }), - }; -} -exports.getNodeHttpConfigurationFromEnvironment = getNodeHttpConfigurationFromEnvironment; -//# sourceMappingURL=otlp-node-http-env-configuration.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/shared-configuration.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/shared-configuration.js deleted file mode 100644 index 02dc8bbd..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/shared-configuration.js +++ /dev/null @@ -1,60 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getSharedConfigurationDefaults = exports.mergeOtlpSharedConfigurationWithDefaults = exports.wrapStaticHeadersInFunction = exports.validateTimeoutMillis = void 0; -function validateTimeoutMillis(timeoutMillis) { - if (Number.isFinite(timeoutMillis) && timeoutMillis > 0) { - return timeoutMillis; - } - throw new Error(`Configuration: timeoutMillis is invalid, expected number greater than 0 (actual: '${timeoutMillis}')`); -} -exports.validateTimeoutMillis = validateTimeoutMillis; -function wrapStaticHeadersInFunction(headers) { - if (headers == null) { - return undefined; - } - return async () => headers; -} -exports.wrapStaticHeadersInFunction = wrapStaticHeadersInFunction; -/** - * @param userProvidedConfiguration Configuration options provided by the user in code. - * @param fallbackConfiguration Fallback to use when the {@link userProvidedConfiguration} does not specify an option. - * @param defaultConfiguration The defaults as defined by the exporter specification - */ -function mergeOtlpSharedConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) { - return { - timeoutMillis: validateTimeoutMillis(userProvidedConfiguration.timeoutMillis ?? - fallbackConfiguration.timeoutMillis ?? - defaultConfiguration.timeoutMillis), - concurrencyLimit: userProvidedConfiguration.concurrencyLimit ?? - fallbackConfiguration.concurrencyLimit ?? - defaultConfiguration.concurrencyLimit, - compression: userProvidedConfiguration.compression ?? - fallbackConfiguration.compression ?? - defaultConfiguration.compression, - }; -} -exports.mergeOtlpSharedConfigurationWithDefaults = mergeOtlpSharedConfigurationWithDefaults; -function getSharedConfigurationDefaults() { - return { - timeoutMillis: 10000, - concurrencyLimit: 30, - compression: 'none', - }; -} -exports.getSharedConfigurationDefaults = getSharedConfigurationDefaults; -//# sourceMappingURL=shared-configuration.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/shared-env-configuration.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/shared-env-configuration.js deleted file mode 100644 index 9a222a18..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/configuration/shared-env-configuration.js +++ /dev/null @@ -1,56 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getSharedConfigurationFromEnvironment = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const core_1 = require("@opentelemetry/core"); -const api_1 = require("@opentelemetry/api"); -function parseAndValidateTimeoutFromEnv(timeoutEnvVar) { - const envTimeout = (0, core_1.getNumberFromEnv)(timeoutEnvVar); - if (envTimeout != null) { - if (Number.isFinite(envTimeout) && envTimeout > 0) { - return envTimeout; - } - api_1.diag.warn(`Configuration: ${timeoutEnvVar} is invalid, expected number greater than 0 (actual: ${envTimeout})`); - } - return undefined; -} -function getTimeoutFromEnv(signalIdentifier) { - const specificTimeout = parseAndValidateTimeoutFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_TIMEOUT`); - const nonSpecificTimeout = parseAndValidateTimeoutFromEnv('OTEL_EXPORTER_OTLP_TIMEOUT'); - return specificTimeout ?? nonSpecificTimeout; -} -function parseAndValidateCompressionFromEnv(compressionEnvVar) { - const compression = (0, core_1.getStringFromEnv)(compressionEnvVar)?.trim(); - if (compression == null || compression === 'none' || compression === 'gzip') { - return compression; - } - api_1.diag.warn(`Configuration: ${compressionEnvVar} is invalid, expected 'none' or 'gzip' (actual: '${compression}')`); - return undefined; -} -function getCompressionFromEnv(signalIdentifier) { - const specificCompression = parseAndValidateCompressionFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_COMPRESSION`); - const nonSpecificCompression = parseAndValidateCompressionFromEnv('OTEL_EXPORTER_OTLP_COMPRESSION'); - return specificCompression ?? nonSpecificCompression; -} -function getSharedConfigurationFromEnvironment(signalIdentifier) { - return { - timeoutMillis: getTimeoutFromEnv(signalIdentifier), - compression: getCompressionFromEnv(signalIdentifier), - }; -} -exports.getSharedConfigurationFromEnvironment = getSharedConfigurationFromEnvironment; -//# sourceMappingURL=shared-env-configuration.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/index-node-http.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/index-node-http.js deleted file mode 100644 index 9aaadc5a..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/index-node-http.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.convertLegacyHttpOptions = exports.getSharedConfigurationFromEnvironment = exports.createOtlpHttpExportDelegate = exports.httpAgentFactoryFromOptions = void 0; -var otlp_node_http_configuration_1 = require("./configuration/otlp-node-http-configuration"); -Object.defineProperty(exports, "httpAgentFactoryFromOptions", { enumerable: true, get: function () { return otlp_node_http_configuration_1.httpAgentFactoryFromOptions; } }); -var otlp_http_export_delegate_1 = require("./otlp-http-export-delegate"); -Object.defineProperty(exports, "createOtlpHttpExportDelegate", { enumerable: true, get: function () { return otlp_http_export_delegate_1.createOtlpHttpExportDelegate; } }); -var shared_env_configuration_1 = require("./configuration/shared-env-configuration"); -Object.defineProperty(exports, "getSharedConfigurationFromEnvironment", { enumerable: true, get: function () { return shared_env_configuration_1.getSharedConfigurationFromEnvironment; } }); -var convert_legacy_node_http_options_1 = require("./configuration/convert-legacy-node-http-options"); -Object.defineProperty(exports, "convertLegacyHttpOptions", { enumerable: true, get: function () { return convert_legacy_node_http_options_1.convertLegacyHttpOptions; } }); -//# sourceMappingURL=index-node-http.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/index.js deleted file mode 100644 index 8d288f58..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/index.js +++ /dev/null @@ -1,30 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createOtlpNetworkExportDelegate = exports.CompressionAlgorithm = exports.getSharedConfigurationDefaults = exports.mergeOtlpSharedConfigurationWithDefaults = exports.OTLPExporterError = exports.OTLPExporterBase = void 0; -var OTLPExporterBase_1 = require("./OTLPExporterBase"); -Object.defineProperty(exports, "OTLPExporterBase", { enumerable: true, get: function () { return OTLPExporterBase_1.OTLPExporterBase; } }); -var types_1 = require("./types"); -Object.defineProperty(exports, "OTLPExporterError", { enumerable: true, get: function () { return types_1.OTLPExporterError; } }); -var shared_configuration_1 = require("./configuration/shared-configuration"); -Object.defineProperty(exports, "mergeOtlpSharedConfigurationWithDefaults", { enumerable: true, get: function () { return shared_configuration_1.mergeOtlpSharedConfigurationWithDefaults; } }); -Object.defineProperty(exports, "getSharedConfigurationDefaults", { enumerable: true, get: function () { return shared_configuration_1.getSharedConfigurationDefaults; } }); -var legacy_node_configuration_1 = require("./configuration/legacy-node-configuration"); -Object.defineProperty(exports, "CompressionAlgorithm", { enumerable: true, get: function () { return legacy_node_configuration_1.CompressionAlgorithm; } }); -var otlp_network_export_delegate_1 = require("./otlp-network-export-delegate"); -Object.defineProperty(exports, "createOtlpNetworkExportDelegate", { enumerable: true, get: function () { return otlp_network_export_delegate_1.createOtlpNetworkExportDelegate; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/is-export-retryable.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/is-export-retryable.js deleted file mode 100644 index 8aa8d626..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/is-export-retryable.js +++ /dev/null @@ -1,40 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.parseRetryAfterToMills = exports.isExportRetryable = void 0; -function isExportRetryable(statusCode) { - const retryCodes = [429, 502, 503, 504]; - return retryCodes.includes(statusCode); -} -exports.isExportRetryable = isExportRetryable; -function parseRetryAfterToMills(retryAfter) { - if (retryAfter == null) { - return undefined; - } - const seconds = Number.parseInt(retryAfter, 10); - if (Number.isInteger(seconds)) { - return seconds > 0 ? seconds * 1000 : -1; - } - // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After#directives - const delay = new Date(retryAfter).getTime() - Date.now(); - if (delay >= 0) { - return delay; - } - return 0; -} -exports.parseRetryAfterToMills = parseRetryAfterToMills; -//# sourceMappingURL=is-export-retryable.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/logging-response-handler.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/logging-response-handler.js deleted file mode 100644 index 28dd66e4..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/logging-response-handler.js +++ /dev/null @@ -1,42 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createLoggingPartialSuccessResponseHandler = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const api_1 = require("@opentelemetry/api"); -function isPartialSuccessResponse(response) { - return Object.prototype.hasOwnProperty.call(response, 'partialSuccess'); -} -/** - * Default response handler that logs a partial success to the console. - */ -function createLoggingPartialSuccessResponseHandler() { - return { - handleResponse(response) { - // Partial success MUST never be an empty object according the specification - // see https://opentelemetry.io/docs/specs/otlp/#partial-success - if (response == null || - !isPartialSuccessResponse(response) || - response.partialSuccess == null || - Object.keys(response.partialSuccess).length === 0) { - return; - } - api_1.diag.warn('Received Partial Success response:', JSON.stringify(response.partialSuccess)); - }, - }; -} -exports.createLoggingPartialSuccessResponseHandler = createLoggingPartialSuccessResponseHandler; -//# sourceMappingURL=logging-response-handler.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-export-delegate.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-export-delegate.js deleted file mode 100644 index 924bc3cf..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-export-delegate.js +++ /dev/null @@ -1,115 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createOtlpExportDelegate = void 0; -const core_1 = require("@opentelemetry/core"); -const types_1 = require("./types"); -const logging_response_handler_1 = require("./logging-response-handler"); -const api_1 = require("@opentelemetry/api"); -class OTLPExportDelegate { - _transport; - _serializer; - _responseHandler; - _promiseQueue; - _timeout; - _diagLogger; - constructor(_transport, _serializer, _responseHandler, _promiseQueue, _timeout) { - this._transport = _transport; - this._serializer = _serializer; - this._responseHandler = _responseHandler; - this._promiseQueue = _promiseQueue; - this._timeout = _timeout; - this._diagLogger = api_1.diag.createComponentLogger({ - namespace: 'OTLPExportDelegate', - }); - } - export(internalRepresentation, resultCallback) { - this._diagLogger.debug('items to be sent', internalRepresentation); - // don't do any work if too many exports are in progress. - if (this._promiseQueue.hasReachedLimit()) { - resultCallback({ - code: core_1.ExportResultCode.FAILED, - error: new Error('Concurrent export limit reached'), - }); - return; - } - const serializedRequest = this._serializer.serializeRequest(internalRepresentation); - if (serializedRequest == null) { - resultCallback({ - code: core_1.ExportResultCode.FAILED, - error: new Error('Nothing to send'), - }); - return; - } - this._promiseQueue.pushPromise(this._transport.send(serializedRequest, this._timeout).then(response => { - if (response.status === 'success') { - if (response.data != null) { - try { - this._responseHandler.handleResponse(this._serializer.deserializeResponse(response.data)); - } - catch (e) { - this._diagLogger.warn('Export succeeded but could not deserialize response - is the response specification compliant?', e, response.data); - } - } - // No matter the response, we can consider the export still successful. - resultCallback({ - code: core_1.ExportResultCode.SUCCESS, - }); - return; - } - else if (response.status === 'failure' && response.error) { - resultCallback({ - code: core_1.ExportResultCode.FAILED, - error: response.error, - }); - return; - } - else if (response.status === 'retryable') { - resultCallback({ - code: core_1.ExportResultCode.FAILED, - error: new types_1.OTLPExporterError('Export failed with retryable status'), - }); - } - else { - resultCallback({ - code: core_1.ExportResultCode.FAILED, - error: new types_1.OTLPExporterError('Export failed with unknown error'), - }); - } - }, reason => resultCallback({ - code: core_1.ExportResultCode.FAILED, - error: reason, - }))); - } - forceFlush() { - return this._promiseQueue.awaitAll(); - } - async shutdown() { - this._diagLogger.debug('shutdown started'); - await this.forceFlush(); - this._transport.shutdown(); - } -} -/** - * Creates a generic delegate for OTLP exports which only contains parts of the OTLP export that are shared across all - * signals. - */ -function createOtlpExportDelegate(components, settings) { - return new OTLPExportDelegate(components.transport, components.serializer, (0, logging_response_handler_1.createLoggingPartialSuccessResponseHandler)(), components.promiseHandler, settings.timeout); -} -exports.createOtlpExportDelegate = createOtlpExportDelegate; -//# sourceMappingURL=otlp-export-delegate.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-http-export-delegate.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-http-export-delegate.js deleted file mode 100644 index 796577ad..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-http-export-delegate.js +++ /dev/null @@ -1,33 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createOtlpHttpExportDelegate = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const otlp_export_delegate_1 = require("./otlp-export-delegate"); -const http_exporter_transport_1 = require("./transport/http-exporter-transport"); -const bounded_queue_export_promise_handler_1 = require("./bounded-queue-export-promise-handler"); -const retrying_transport_1 = require("./retrying-transport"); -function createOtlpHttpExportDelegate(options, serializer) { - return (0, otlp_export_delegate_1.createOtlpExportDelegate)({ - transport: (0, retrying_transport_1.createRetryingTransport)({ - transport: (0, http_exporter_transport_1.createHttpExporterTransport)(options), - }), - serializer: serializer, - promiseHandler: (0, bounded_queue_export_promise_handler_1.createBoundedQueueExportPromiseHandler)(options), - }, { timeout: options.timeoutMillis }); -} -exports.createOtlpHttpExportDelegate = createOtlpHttpExportDelegate; -//# sourceMappingURL=otlp-http-export-delegate.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-network-export-delegate.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-network-export-delegate.js deleted file mode 100644 index 064c7b73..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/otlp-network-export-delegate.js +++ /dev/null @@ -1,29 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createOtlpNetworkExportDelegate = void 0; -const bounded_queue_export_promise_handler_1 = require("./bounded-queue-export-promise-handler"); -const otlp_export_delegate_1 = require("./otlp-export-delegate"); -function createOtlpNetworkExportDelegate(options, serializer, transport) { - return (0, otlp_export_delegate_1.createOtlpExportDelegate)({ - transport: transport, - serializer, - promiseHandler: (0, bounded_queue_export_promise_handler_1.createBoundedQueueExportPromiseHandler)(options), - }, { timeout: options.timeoutMillis }); -} -exports.createOtlpNetworkExportDelegate = createOtlpNetworkExportDelegate; -//# sourceMappingURL=otlp-network-export-delegate.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/retrying-transport.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/retrying-transport.js deleted file mode 100644 index 083013e3..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/retrying-transport.js +++ /dev/null @@ -1,73 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createRetryingTransport = void 0; -const MAX_ATTEMPTS = 5; -const INITIAL_BACKOFF = 1000; -const MAX_BACKOFF = 5000; -const BACKOFF_MULTIPLIER = 1.5; -const JITTER = 0.2; -/** - * Get a pseudo-random jitter that falls in the range of [-JITTER, +JITTER] - */ -function getJitter() { - return Math.random() * (2 * JITTER) - JITTER; -} -class RetryingTransport { - _transport; - constructor(_transport) { - this._transport = _transport; - } - retry(data, timeoutMillis, inMillis) { - return new Promise((resolve, reject) => { - setTimeout(() => { - this._transport.send(data, timeoutMillis).then(resolve, reject); - }, inMillis); - }); - } - async send(data, timeoutMillis) { - const deadline = Date.now() + timeoutMillis; - let result = await this._transport.send(data, timeoutMillis); - let attempts = MAX_ATTEMPTS; - let nextBackoff = INITIAL_BACKOFF; - while (result.status === 'retryable' && attempts > 0) { - attempts--; - // use maximum of computed backoff and 0 to avoid negative timeouts - const backoff = Math.max(Math.min(nextBackoff, MAX_BACKOFF) + getJitter(), 0); - nextBackoff = nextBackoff * BACKOFF_MULTIPLIER; - const retryInMillis = result.retryInMillis ?? backoff; - // return when expected retry time is after the export deadline. - const remainingTimeoutMillis = deadline - Date.now(); - if (retryInMillis > remainingTimeoutMillis) { - return result; - } - result = await this.retry(data, remainingTimeoutMillis, retryInMillis); - } - return result; - } - shutdown() { - return this._transport.shutdown(); - } -} -/** - * Creates an Exporter Transport that retries on 'retryable' response. - */ -function createRetryingTransport(options) { - return new RetryingTransport(options.transport); -} -exports.createRetryingTransport = createRetryingTransport; -//# sourceMappingURL=retrying-transport.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/transport/http-exporter-transport.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/transport/http-exporter-transport.js deleted file mode 100644 index b22cd8c5..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/transport/http-exporter-transport.js +++ /dev/null @@ -1,60 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createHttpExporterTransport = void 0; -const http_transport_utils_1 = require("./http-transport-utils"); -class HttpExporterTransport { - _parameters; - _utils = null; - constructor(_parameters) { - this._parameters = _parameters; - } - async send(data, timeoutMillis) { - const { agent, request } = await this._loadUtils(); - const headers = await this._parameters.headers(); - return new Promise(resolve => { - (0, http_transport_utils_1.sendWithHttp)(request, this._parameters.url, headers, this._parameters.compression, this._parameters.userAgent, agent, data, result => { - resolve(result); - }, timeoutMillis); - }); - } - shutdown() { - // intentionally left empty, nothing to do. - } - async _loadUtils() { - let utils = this._utils; - if (utils === null) { - const protocol = new URL(this._parameters.url).protocol; - const [agent, request] = await Promise.all([ - this._parameters.agentFactory(protocol), - requestFunctionFactory(protocol), - ]); - utils = this._utils = { agent, request }; - } - return utils; - } -} -async function requestFunctionFactory(protocol) { - const module = protocol === 'http:' ? import('http') : import('https'); - const { request } = await module; - return request; -} -function createHttpExporterTransport(parameters) { - return new HttpExporterTransport(parameters); -} -exports.createHttpExporterTransport = createHttpExporterTransport; -//# sourceMappingURL=http-exporter-transport.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/transport/http-transport-utils.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/transport/http-transport-utils.js deleted file mode 100644 index 35ee0703..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/transport/http-transport-utils.js +++ /dev/null @@ -1,99 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.compressAndSend = exports.sendWithHttp = void 0; -const zlib = require("zlib"); -const stream_1 = require("stream"); -const is_export_retryable_1 = require("../is-export-retryable"); -const types_1 = require("../types"); -const version_1 = require("../version"); -const DEFAULT_USER_AGENT = `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`; -/** - * Sends data using http - * @param request - * @param params - * @param agent - * @param data - * @param onDone - * @param timeoutMillis - */ -function sendWithHttp(request, url, headers, compression, userAgent, agent, data, onDone, timeoutMillis) { - const parsedUrl = new URL(url); - if (userAgent) { - headers['User-Agent'] = `${userAgent} ${DEFAULT_USER_AGENT}`; - } - else { - headers['User-Agent'] = DEFAULT_USER_AGENT; - } - const options = { - hostname: parsedUrl.hostname, - port: parsedUrl.port, - path: parsedUrl.pathname, - method: 'POST', - headers, - agent, - }; - const req = request(options, (res) => { - const responseData = []; - res.on('data', chunk => responseData.push(chunk)); - res.on('end', () => { - if (res.statusCode && res.statusCode < 299) { - onDone({ - status: 'success', - data: Buffer.concat(responseData), - }); - } - else if (res.statusCode && (0, is_export_retryable_1.isExportRetryable)(res.statusCode)) { - onDone({ - status: 'retryable', - retryInMillis: (0, is_export_retryable_1.parseRetryAfterToMills)(res.headers['retry-after']), - }); - } - else { - const error = new types_1.OTLPExporterError(res.statusMessage, res.statusCode, Buffer.concat(responseData).toString()); - onDone({ - status: 'failure', - error, - }); - } - }); - }); - req.setTimeout(timeoutMillis, () => { - req.destroy(); - onDone({ - status: 'failure', - error: new Error('Request Timeout'), - }); - }); - req.on('error', (error) => { - onDone({ - status: 'failure', - error, - }); - }); - compressAndSend(req, compression, data, (error) => { - onDone({ - status: 'failure', - error, - }); - }); -} -exports.sendWithHttp = sendWithHttp; -function compressAndSend(req, compression, data, onError) { - let dataStream = readableFromUint8Array(data); - if (compression === 'gzip') { - req.setHeader('Content-Encoding', 'gzip'); - dataStream = dataStream - .on('error', onError) - .pipe(zlib.createGzip()) - .on('error', onError); - } - dataStream.pipe(req).on('error', onError); -} -exports.compressAndSend = compressAndSend; -function readableFromUint8Array(buff) { - const readable = new stream_1.Readable(); - readable.push(buff); - readable.push(null); - return readable; -} -//# sourceMappingURL=http-transport-utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/types.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/types.js deleted file mode 100644 index 3505fcf6..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/types.js +++ /dev/null @@ -1,33 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OTLPExporterError = void 0; -/** - * Interface for handling error - */ -class OTLPExporterError extends Error { - code; - name = 'OTLPExporterError'; - data; - constructor(message, code, data) { - super(message); - this.data = data; - this.code = code; - } -} -exports.OTLPExporterError = OTLPExporterError; -//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/util.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/util.js deleted file mode 100644 index e8a5edab..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/util.js +++ /dev/null @@ -1,37 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.validateAndNormalizeHeaders = void 0; -const api_1 = require("@opentelemetry/api"); -/** - * Parses headers from config leaving only those that have defined values - * @param partialHeaders - */ -function validateAndNormalizeHeaders(partialHeaders) { - const headers = {}; - Object.entries(partialHeaders ?? {}).forEach(([key, value]) => { - if (typeof value !== 'undefined') { - headers[key] = String(value); - } - else { - api_1.diag.warn(`Header "${key}" has invalid value (${value}) and will be ignored`); - } - }); - return headers; -} -exports.validateAndNormalizeHeaders = validateAndNormalizeHeaders; -//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/version.js b/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/version.js deleted file mode 100644 index 19056c5e..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-exporter-base/build/src/version.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.VERSION = void 0; -// this is autogenerated file, see scripts/version-update.js -exports.VERSION = '0.208.0'; -//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/convert-legacy-otlp-grpc-options.js b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/convert-legacy-otlp-grpc-options.js deleted file mode 100644 index 382be6aa..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/convert-legacy-otlp-grpc-options.js +++ /dev/null @@ -1,35 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.convertLegacyOtlpGrpcOptions = void 0; -const api_1 = require("@opentelemetry/api"); -const otlp_grpc_configuration_1 = require("./otlp-grpc-configuration"); -const grpc_exporter_transport_1 = require("../grpc-exporter-transport"); -const otlp_grpc_env_configuration_1 = require("./otlp-grpc-env-configuration"); -/** - * @deprecated - * @param config - * @param signalIdentifier - */ -function convertLegacyOtlpGrpcOptions(config, signalIdentifier) { - if (config.headers) { - api_1.diag.warn('Headers cannot be set when using grpc'); - } - // keep credentials locally in case user updates the reference on the config object - const userProvidedCredentials = config.credentials; - return (0, otlp_grpc_configuration_1.mergeOtlpGrpcConfigurationWithDefaults)({ - url: config.url, - metadata: () => { - // metadata resolution strategy is merge, so we can return empty here, and it will not override the rest of the settings. - return config.metadata ?? (0, grpc_exporter_transport_1.createEmptyMetadata)(); - }, - compression: config.compression, - timeoutMillis: config.timeoutMillis, - concurrencyLimit: config.concurrencyLimit, - credentials: userProvidedCredentials != null - ? () => userProvidedCredentials - : undefined, - userAgent: config.userAgent, - }, (0, otlp_grpc_env_configuration_1.getOtlpGrpcConfigurationFromEnv)(signalIdentifier), (0, otlp_grpc_configuration_1.getOtlpGrpcDefaultConfiguration)()); -} -exports.convertLegacyOtlpGrpcOptions = convertLegacyOtlpGrpcOptions; -//# sourceMappingURL=convert-legacy-otlp-grpc-options.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-configuration.js b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-configuration.js deleted file mode 100644 index 545090cd..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-configuration.js +++ /dev/null @@ -1,89 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getOtlpGrpcDefaultConfiguration = exports.mergeOtlpGrpcConfigurationWithDefaults = exports.validateAndNormalizeUrl = void 0; -const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base"); -const grpc_exporter_transport_1 = require("../grpc-exporter-transport"); -const url_1 = require("url"); -const api_1 = require("@opentelemetry/api"); -function validateAndNormalizeUrl(url) { - url = url.trim(); - const hasProtocol = url.match(/^([\w]{1,8}):\/\//); - if (!hasProtocol) { - url = `https://${url}`; - } - const target = new url_1.URL(url); - if (target.protocol === 'unix:') { - return url; - } - if (target.pathname && target.pathname !== '/') { - api_1.diag.warn('URL path should not be set when using grpc, the path part of the URL will be ignored.'); - } - if (target.protocol !== '' && !target.protocol?.match(/^(http)s?:$/)) { - api_1.diag.warn('URL protocol should be http(s)://. Using http://.'); - } - return target.host; -} -exports.validateAndNormalizeUrl = validateAndNormalizeUrl; -function overrideMetadataEntriesIfNotPresent(metadata, additionalMetadata) { - for (const [key, value] of Object.entries(additionalMetadata.getMap())) { - // only override with env var data if the key has no values. - // not using Metadata.merge() as it will keep both values. - if (metadata.get(key).length < 1) { - metadata.set(key, value); - } - } -} -function mergeOtlpGrpcConfigurationWithDefaults(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration) { - const rawUrl = userProvidedConfiguration.url ?? - fallbackConfiguration.url ?? - defaultConfiguration.url; - return { - ...(0, otlp_exporter_base_1.mergeOtlpSharedConfigurationWithDefaults)(userProvidedConfiguration, fallbackConfiguration, defaultConfiguration), - metadata: () => { - const metadata = defaultConfiguration.metadata(); - overrideMetadataEntriesIfNotPresent(metadata, - // clone to ensure we don't modify what the user gave us in case they hold on to the returned reference - userProvidedConfiguration.metadata?.().clone() ?? (0, grpc_exporter_transport_1.createEmptyMetadata)()); - overrideMetadataEntriesIfNotPresent(metadata, fallbackConfiguration.metadata?.() ?? (0, grpc_exporter_transport_1.createEmptyMetadata)()); - return metadata; - }, - url: validateAndNormalizeUrl(rawUrl), - credentials: userProvidedConfiguration.credentials ?? - fallbackConfiguration.credentials?.(rawUrl) ?? - defaultConfiguration.credentials(rawUrl), - userAgent: userProvidedConfiguration.userAgent, - }; -} -exports.mergeOtlpGrpcConfigurationWithDefaults = mergeOtlpGrpcConfigurationWithDefaults; -function getOtlpGrpcDefaultConfiguration() { - return { - ...(0, otlp_exporter_base_1.getSharedConfigurationDefaults)(), - metadata: () => (0, grpc_exporter_transport_1.createEmptyMetadata)(), - url: 'http://localhost:4317', - credentials: (url) => { - if (url.startsWith('http://')) { - return () => (0, grpc_exporter_transport_1.createInsecureCredentials)(); - } - else { - return () => (0, grpc_exporter_transport_1.createSslCredentials)(); - } - }, - }; -} -exports.getOtlpGrpcDefaultConfiguration = getOtlpGrpcDefaultConfiguration; -//# sourceMappingURL=otlp-grpc-configuration.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-env-configuration.js b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-env-configuration.js deleted file mode 100644 index 292df421..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/configuration/otlp-grpc-env-configuration.js +++ /dev/null @@ -1,159 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getOtlpGrpcConfigurationFromEnv = void 0; -const core_1 = require("@opentelemetry/core"); -const grpc_exporter_transport_1 = require("../grpc-exporter-transport"); -const node_http_1 = require("@opentelemetry/otlp-exporter-base/node-http"); -const fs = require("fs"); -const path = require("path"); -const api_1 = require("@opentelemetry/api"); -function fallbackIfNullishOrBlank(signalSpecific, nonSignalSpecific) { - if (signalSpecific != null && signalSpecific !== '') { - return signalSpecific; - } - if (nonSignalSpecific != null && nonSignalSpecific !== '') { - return nonSignalSpecific; - } - return undefined; -} -function getMetadataFromEnv(signalIdentifier) { - const signalSpecificRawHeaders = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_HEADERS`]?.trim(); - const nonSignalSpecificRawHeaders = process.env['OTEL_EXPORTER_OTLP_HEADERS']?.trim(); - const signalSpecificHeaders = (0, core_1.parseKeyPairsIntoRecord)(signalSpecificRawHeaders); - const nonSignalSpecificHeaders = (0, core_1.parseKeyPairsIntoRecord)(nonSignalSpecificRawHeaders); - if (Object.keys(signalSpecificHeaders).length === 0 && - Object.keys(nonSignalSpecificHeaders).length === 0) { - return undefined; - } - const mergeHeaders = Object.assign({}, nonSignalSpecificHeaders, signalSpecificHeaders); - const metadata = (0, grpc_exporter_transport_1.createEmptyMetadata)(); - // for this to work, metadata MUST be empty - otherwise `Metadata#set()` will merge items. - for (const [key, value] of Object.entries(mergeHeaders)) { - metadata.set(key, value); - } - return metadata; -} -function getMetadataProviderFromEnv(signalIdentifier) { - const metadata = getMetadataFromEnv(signalIdentifier); - if (metadata == null) { - return undefined; - } - return () => metadata; -} -function getUrlFromEnv(signalIdentifier) { - // This does not change the string beyond trimming on purpose. - // Normally a user would just use a host and port for gRPC, but the OTLP Exporter specification requires us to - // use the raw provided endpoint to derive credential settings. Therefore, we only normalize right when - // we merge user-provided, env-provided and defaults together, and we have determined which credentials to use. - // - // Examples: - // - example.test:4317 -> use secure credentials from environment (or provided via code) - // - http://example.test:4317 -> use insecure credentials if nothing else is provided - // - https://example.test:4317 -> use secure credentials from environment (or provided via code) - const specificEndpoint = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_ENDPOINT`]?.trim(); - const nonSpecificEndpoint = process.env[`OTEL_EXPORTER_OTLP_ENDPOINT`]?.trim(); - return fallbackIfNullishOrBlank(specificEndpoint, nonSpecificEndpoint); -} -/** - * Determines whether the env var for insecure credentials is set to {@code true}. - * - * It will allow the following values as {@code true} - * - 'true' - * - 'true ' - * - ' true' - * - 'TrUE' - * - 'TRUE' - * - * It will not allow: - * - 'true false' - * - 'false true' - * - 'true!' - * - 'true,true' - * - '1' - * - ' ' - * - * @param signalIdentifier - */ -function getInsecureSettingFromEnv(signalIdentifier) { - const signalSpecificInsecureValue = process.env[`OTEL_EXPORTER_OTLP_${signalIdentifier}_INSECURE`] - ?.toLowerCase() - .trim(); - const nonSignalSpecificInsecureValue = process.env[`OTEL_EXPORTER_OTLP_INSECURE`] - ?.toLowerCase() - .trim(); - return (fallbackIfNullishOrBlank(signalSpecificInsecureValue, nonSignalSpecificInsecureValue) === 'true'); -} -function readFileFromEnv(signalSpecificEnvVar, nonSignalSpecificEnvVar, warningMessage) { - const signalSpecificPath = process.env[signalSpecificEnvVar]?.trim(); - const nonSignalSpecificPath = process.env[nonSignalSpecificEnvVar]?.trim(); - const filePath = fallbackIfNullishOrBlank(signalSpecificPath, nonSignalSpecificPath); - if (filePath != null) { - try { - return fs.readFileSync(path.resolve(process.cwd(), filePath)); - } - catch { - api_1.diag.warn(warningMessage); - return undefined; - } - } - else { - return undefined; - } -} -function getClientCertificateFromEnv(signalIdentifier) { - return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_CERTIFICATE`, 'OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE', 'Failed to read client certificate chain file'); -} -function getClientKeyFromEnv(signalIdentifier) { - return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CLIENT_KEY`, 'OTEL_EXPORTER_OTLP_CLIENT_KEY', 'Failed to read client certificate private key file'); -} -function getRootCertificateFromEnv(signalIdentifier) { - return readFileFromEnv(`OTEL_EXPORTER_OTLP_${signalIdentifier}_CERTIFICATE`, 'OTEL_EXPORTER_OTLP_CERTIFICATE', 'Failed to read root certificate file'); -} -function getCredentialsFromEnvIgnoreInsecure(signalIdentifier) { - const clientKey = getClientKeyFromEnv(signalIdentifier); - const clientCertificate = getClientCertificateFromEnv(signalIdentifier); - const rootCertificate = getRootCertificateFromEnv(signalIdentifier); - // if the chain is not intact, @grpc/grpc-js will throw. This is fine when a user provides it in code, but env var - // config is not allowed to throw, so we add this safeguard and try to make the best of it here. - const clientChainIntact = clientKey != null && clientCertificate != null; - if (rootCertificate != null && !clientChainIntact) { - api_1.diag.warn('Client key and certificate must both be provided, but one was missing - attempting to create credentials from just the root certificate'); - return (0, grpc_exporter_transport_1.createSslCredentials)(getRootCertificateFromEnv(signalIdentifier)); - } - return (0, grpc_exporter_transport_1.createSslCredentials)(rootCertificate, clientKey, clientCertificate); -} -function getCredentialsFromEnv(signalIdentifier) { - if (getInsecureSettingFromEnv(signalIdentifier)) { - return (0, grpc_exporter_transport_1.createInsecureCredentials)(); - } - return getCredentialsFromEnvIgnoreInsecure(signalIdentifier); -} -function getOtlpGrpcConfigurationFromEnv(signalIdentifier) { - return { - ...(0, node_http_1.getSharedConfigurationFromEnvironment)(signalIdentifier), - metadata: getMetadataProviderFromEnv(signalIdentifier), - url: getUrlFromEnv(signalIdentifier), - credentials: (finalResolvedUrl) => { - // Always assume insecure on http:// and secure on https://, the protocol always takes precedence over the insecure setting. - // note: the spec does not make any exception for - // - "localhost:4317". If the protocol is omitted, credentials are required unless insecure is set - // - "unix://", as it's neither http:// nor https:// and therefore credentials are required unless insecure is set - if (finalResolvedUrl.startsWith('http://')) { - return () => { - return (0, grpc_exporter_transport_1.createInsecureCredentials)(); - }; - } - else if (finalResolvedUrl.startsWith('https://')) { - return () => { - return getCredentialsFromEnvIgnoreInsecure(signalIdentifier); - }; - } - // defer to env settings in this case - return () => { - return getCredentialsFromEnv(signalIdentifier); - }; - }, - }; -} -exports.getOtlpGrpcConfigurationFromEnv = getOtlpGrpcConfigurationFromEnv; -//# sourceMappingURL=otlp-grpc-env-configuration.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/create-service-client-constructor.js b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/create-service-client-constructor.js deleted file mode 100644 index 2327fd88..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/create-service-client-constructor.js +++ /dev/null @@ -1,50 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createServiceClientConstructor = void 0; -const grpc = require("@grpc/grpc-js"); -/** - * Creates a unary service client constructor that, when instantiated, does not serialize/deserialize anything. - * Allows for passing in {@link Buffer} directly, serialization can be handled via protobufjs or custom implementations. - * - * @param path service path - * @param name service name - */ -function createServiceClientConstructor(path, name) { - const serviceDefinition = { - export: { - path: path, - requestStream: false, - responseStream: false, - requestSerialize: (arg) => { - return arg; - }, - requestDeserialize: (arg) => { - return arg; - }, - responseSerialize: (arg) => { - return arg; - }, - responseDeserialize: (arg) => { - return arg; - }, - }, - }; - return grpc.makeGenericClientConstructor(serviceDefinition, name); -} -exports.createServiceClientConstructor = createServiceClientConstructor; -//# sourceMappingURL=create-service-client-constructor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/grpc-exporter-transport.js b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/grpc-exporter-transport.js deleted file mode 100644 index 4bbc8353..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/grpc-exporter-transport.js +++ /dev/null @@ -1,131 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createOtlpGrpcExporterTransport = exports.GrpcExporterTransport = exports.createEmptyMetadata = exports.createSslCredentials = exports.createInsecureCredentials = void 0; -const version_1 = require("./version"); -const DEFAULT_USER_AGENT = `OTel-OTLP-Exporter-JavaScript/${version_1.VERSION}`; -function createUserAgent(userAgent) { - if (userAgent) { - return `${userAgent} ${DEFAULT_USER_AGENT}`; - } - return DEFAULT_USER_AGENT; -} -// values taken from '@grpc/grpc-js` so that we don't need to require/import it. -const GRPC_COMPRESSION_NONE = 0; -const GRPC_COMPRESSION_GZIP = 2; -function toGrpcCompression(compression) { - return compression === 'gzip' ? GRPC_COMPRESSION_GZIP : GRPC_COMPRESSION_NONE; -} -function createInsecureCredentials() { - // Lazy-load so that we don't need to require/import '@grpc/grpc-js' before it can be wrapped by instrumentation. - const { credentials, - // eslint-disable-next-line @typescript-eslint/no-require-imports - } = require('@grpc/grpc-js'); - return credentials.createInsecure(); -} -exports.createInsecureCredentials = createInsecureCredentials; -function createSslCredentials(rootCert, privateKey, certChain) { - // Lazy-load so that we don't need to require/import '@grpc/grpc-js' before it can be wrapped by instrumentation. - const { credentials, - // eslint-disable-next-line @typescript-eslint/no-require-imports - } = require('@grpc/grpc-js'); - return credentials.createSsl(rootCert, privateKey, certChain); -} -exports.createSslCredentials = createSslCredentials; -function createEmptyMetadata() { - // Lazy-load so that we don't need to require/import '@grpc/grpc-js' before it can be wrapped by instrumentation. - const { Metadata, - // eslint-disable-next-line @typescript-eslint/no-require-imports - } = require('@grpc/grpc-js'); - return new Metadata(); -} -exports.createEmptyMetadata = createEmptyMetadata; -class GrpcExporterTransport { - _parameters; - _client; - _metadata; - constructor(_parameters) { - this._parameters = _parameters; - } - shutdown() { - this._client?.close(); - } - send(data, timeoutMillis) { - // We need to make a for gRPC - const buffer = Buffer.from(data); - if (this._client == null) { - // Lazy require to ensure that grpc is not loaded before instrumentations can wrap it - const { createServiceClientConstructor, - // eslint-disable-next-line @typescript-eslint/no-require-imports - } = require('./create-service-client-constructor'); - try { - this._metadata = this._parameters.metadata(); - } - catch (error) { - return Promise.resolve({ - status: 'failure', - error: error, - }); - } - const clientConstructor = createServiceClientConstructor(this._parameters.grpcPath, this._parameters.grpcName); - try { - this._client = new clientConstructor(this._parameters.address, this._parameters.credentials(), { - 'grpc.default_compression_algorithm': toGrpcCompression(this._parameters.compression), - 'grpc.primary_user_agent': createUserAgent(this._parameters.userAgent), - }); - } - catch (error) { - return Promise.resolve({ - status: 'failure', - error: error, - }); - } - } - return new Promise(resolve => { - const deadline = Date.now() + timeoutMillis; - // this should never happen - if (this._metadata == null) { - return resolve({ - error: new Error('metadata was null'), - status: 'failure', - }); - } - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore The gRPC client constructor is created on runtime, so we don't have any types for the resulting client. - this._client.export(buffer, this._metadata, { deadline: deadline }, (err, response) => { - if (err) { - resolve({ - status: 'failure', - error: err, - }); - } - else { - resolve({ - data: response, - status: 'success', - }); - } - }); - }); - } -} -exports.GrpcExporterTransport = GrpcExporterTransport; -function createOtlpGrpcExporterTransport(options) { - return new GrpcExporterTransport(options); -} -exports.createOtlpGrpcExporterTransport = createOtlpGrpcExporterTransport; -//# sourceMappingURL=grpc-exporter-transport.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/index.js deleted file mode 100644 index f82eb1e7..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/index.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createOtlpGrpcExportDelegate = exports.convertLegacyOtlpGrpcOptions = void 0; -var convert_legacy_otlp_grpc_options_1 = require("./configuration/convert-legacy-otlp-grpc-options"); -Object.defineProperty(exports, "convertLegacyOtlpGrpcOptions", { enumerable: true, get: function () { return convert_legacy_otlp_grpc_options_1.convertLegacyOtlpGrpcOptions; } }); -var otlp_grpc_export_delegate_1 = require("./otlp-grpc-export-delegate"); -Object.defineProperty(exports, "createOtlpGrpcExportDelegate", { enumerable: true, get: function () { return otlp_grpc_export_delegate_1.createOtlpGrpcExportDelegate; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/otlp-grpc-export-delegate.js b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/otlp-grpc-export-delegate.js deleted file mode 100644 index 6738005a..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/otlp-grpc-export-delegate.js +++ /dev/null @@ -1,33 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createOtlpGrpcExportDelegate = void 0; -const otlp_exporter_base_1 = require("@opentelemetry/otlp-exporter-base"); -const grpc_exporter_transport_1 = require("./grpc-exporter-transport"); -function createOtlpGrpcExportDelegate(options, serializer, grpcName, grpcPath) { - return (0, otlp_exporter_base_1.createOtlpNetworkExportDelegate)(options, serializer, (0, grpc_exporter_transport_1.createOtlpGrpcExporterTransport)({ - address: options.url, - compression: options.compression, - credentials: options.credentials, - metadata: options.metadata, - userAgent: options.userAgent, - grpcName, - grpcPath, - })); -} -exports.createOtlpGrpcExportDelegate = createOtlpGrpcExportDelegate; -//# sourceMappingURL=otlp-grpc-export-delegate.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/version.js b/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/version.js deleted file mode 100644 index 19056c5e..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-grpc-exporter-base/build/src/version.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.VERSION = void 0; -// this is autogenerated file, see scripts/version-update.js -exports.VERSION = '0.208.0'; -//# sourceMappingURL=version.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/hex-to-binary.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/hex-to-binary.js deleted file mode 100644 index 48c7cb4e..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/hex-to-binary.js +++ /dev/null @@ -1,42 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.hexToBinary = void 0; -function intValue(charCode) { - // 0-9 - if (charCode >= 48 && charCode <= 57) { - return charCode - 48; - } - // a-f - if (charCode >= 97 && charCode <= 102) { - return charCode - 87; - } - // A-F - return charCode - 55; -} -function hexToBinary(hexStr) { - const buf = new Uint8Array(hexStr.length / 2); - let offset = 0; - for (let i = 0; i < hexStr.length; i += 2) { - const hi = intValue(hexStr.charCodeAt(i)); - const lo = intValue(hexStr.charCodeAt(i + 1)); - buf[offset++] = (hi << 4) | lo; - } - return buf; -} -exports.hexToBinary = hexToBinary; -//# sourceMappingURL=hex-to-binary.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/internal.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/internal.js deleted file mode 100644 index 0cdb555b..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/internal.js +++ /dev/null @@ -1,57 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.toAnyValue = exports.toKeyValue = exports.toAttributes = exports.createInstrumentationScope = exports.createResource = void 0; -function createResource(resource) { - const result = { - attributes: toAttributes(resource.attributes), - droppedAttributesCount: 0, - }; - const schemaUrl = resource.schemaUrl; - if (schemaUrl && schemaUrl !== '') - result.schemaUrl = schemaUrl; - return result; -} -exports.createResource = createResource; -function createInstrumentationScope(scope) { - return { - name: scope.name, - version: scope.version, - }; -} -exports.createInstrumentationScope = createInstrumentationScope; -function toAttributes(attributes) { - return Object.keys(attributes).map(key => toKeyValue(key, attributes[key])); -} -exports.toAttributes = toAttributes; -function toKeyValue(key, value) { - return { - key: key, - value: toAnyValue(value), - }; -} -exports.toKeyValue = toKeyValue; -function toAnyValue(value) { - const t = typeof value; - if (t === 'string') - return { stringValue: value }; - if (t === 'number') { - if (!Number.isInteger(value)) - return { doubleValue: value }; - return { intValue: value }; - } - if (t === 'boolean') - return { boolValue: value }; - if (value instanceof Uint8Array) - return { bytesValue: value }; - if (Array.isArray(value)) - return { arrayValue: { values: value.map(toAnyValue) } }; - if (t === 'object' && value != null) - return { - kvlistValue: { - values: Object.entries(value).map(([k, v]) => toKeyValue(k, v)), - }, - }; - return {}; -} -exports.toAnyValue = toAnyValue; -//# sourceMappingURL=internal.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/utils.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/utils.js deleted file mode 100644 index b612ddba..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/common/utils.js +++ /dev/null @@ -1,69 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getOtlpEncoder = exports.encodeAsString = exports.encodeAsLongBits = exports.toLongBits = exports.hrTimeToNanos = void 0; -const core_1 = require("@opentelemetry/core"); -const hex_to_binary_1 = require("./hex-to-binary"); -function hrTimeToNanos(hrTime) { - const NANOSECONDS = BigInt(1000000000); - return (BigInt(Math.trunc(hrTime[0])) * NANOSECONDS + BigInt(Math.trunc(hrTime[1]))); -} -exports.hrTimeToNanos = hrTimeToNanos; -function toLongBits(value) { - const low = Number(BigInt.asUintN(32, value)); - const high = Number(BigInt.asUintN(32, value >> BigInt(32))); - return { low, high }; -} -exports.toLongBits = toLongBits; -function encodeAsLongBits(hrTime) { - const nanos = hrTimeToNanos(hrTime); - return toLongBits(nanos); -} -exports.encodeAsLongBits = encodeAsLongBits; -function encodeAsString(hrTime) { - const nanos = hrTimeToNanos(hrTime); - return nanos.toString(); -} -exports.encodeAsString = encodeAsString; -const encodeTimestamp = typeof BigInt !== 'undefined' ? encodeAsString : core_1.hrTimeToNanoseconds; -function identity(value) { - return value; -} -function optionalHexToBinary(str) { - if (str === undefined) - return undefined; - return (0, hex_to_binary_1.hexToBinary)(str); -} -const DEFAULT_ENCODER = { - encodeHrTime: encodeAsLongBits, - encodeSpanContext: hex_to_binary_1.hexToBinary, - encodeOptionalSpanContext: optionalHexToBinary, -}; -function getOtlpEncoder(options) { - if (options === undefined) { - return DEFAULT_ENCODER; - } - const useLongBits = options.useLongBits ?? true; - const useHex = options.useHex ?? false; - return { - encodeHrTime: useLongBits ? encodeAsLongBits : encodeTimestamp, - encodeSpanContext: useHex ? identity : hex_to_binary_1.hexToBinary, - encodeOptionalSpanContext: useHex ? identity : optionalHexToBinary, - }; -} -exports.getOtlpEncoder = getOtlpEncoder; -//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/generated/root.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/generated/root.js deleted file mode 100644 index 659530f3..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/generated/root.js +++ /dev/null @@ -1,13299 +0,0 @@ -/*eslint-disable block-scoped-var, id-length, no-control-regex, no-magic-numbers, no-prototype-builtins, no-redeclare, no-shadow, no-var, sort-vars*/ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var $protobuf = require("protobufjs/minimal"); -// Common aliases -var $Reader = $protobuf.Reader, $Writer = $protobuf.Writer, $util = $protobuf.util; -// Exported root namespace -var $root = $protobuf.roots["default"] || ($protobuf.roots["default"] = {}); -$root.opentelemetry = (function () { - /** - * Namespace opentelemetry. - * @exports opentelemetry - * @namespace - */ - var opentelemetry = {}; - opentelemetry.proto = (function () { - /** - * Namespace proto. - * @memberof opentelemetry - * @namespace - */ - var proto = {}; - proto.common = (function () { - /** - * Namespace common. - * @memberof opentelemetry.proto - * @namespace - */ - var common = {}; - common.v1 = (function () { - /** - * Namespace v1. - * @memberof opentelemetry.proto.common - * @namespace - */ - var v1 = {}; - v1.AnyValue = (function () { - /** - * Properties of an AnyValue. - * @memberof opentelemetry.proto.common.v1 - * @interface IAnyValue - * @property {string|null} [stringValue] AnyValue stringValue - * @property {boolean|null} [boolValue] AnyValue boolValue - * @property {number|Long|null} [intValue] AnyValue intValue - * @property {number|null} [doubleValue] AnyValue doubleValue - * @property {opentelemetry.proto.common.v1.IArrayValue|null} [arrayValue] AnyValue arrayValue - * @property {opentelemetry.proto.common.v1.IKeyValueList|null} [kvlistValue] AnyValue kvlistValue - * @property {Uint8Array|null} [bytesValue] AnyValue bytesValue - */ - /** - * Constructs a new AnyValue. - * @memberof opentelemetry.proto.common.v1 - * @classdesc Represents an AnyValue. - * @implements IAnyValue - * @constructor - * @param {opentelemetry.proto.common.v1.IAnyValue=} [properties] Properties to set - */ - function AnyValue(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * AnyValue stringValue. - * @member {string|null|undefined} stringValue - * @memberof opentelemetry.proto.common.v1.AnyValue - * @instance - */ - AnyValue.prototype.stringValue = null; - /** - * AnyValue boolValue. - * @member {boolean|null|undefined} boolValue - * @memberof opentelemetry.proto.common.v1.AnyValue - * @instance - */ - AnyValue.prototype.boolValue = null; - /** - * AnyValue intValue. - * @member {number|Long|null|undefined} intValue - * @memberof opentelemetry.proto.common.v1.AnyValue - * @instance - */ - AnyValue.prototype.intValue = null; - /** - * AnyValue doubleValue. - * @member {number|null|undefined} doubleValue - * @memberof opentelemetry.proto.common.v1.AnyValue - * @instance - */ - AnyValue.prototype.doubleValue = null; - /** - * AnyValue arrayValue. - * @member {opentelemetry.proto.common.v1.IArrayValue|null|undefined} arrayValue - * @memberof opentelemetry.proto.common.v1.AnyValue - * @instance - */ - AnyValue.prototype.arrayValue = null; - /** - * AnyValue kvlistValue. - * @member {opentelemetry.proto.common.v1.IKeyValueList|null|undefined} kvlistValue - * @memberof opentelemetry.proto.common.v1.AnyValue - * @instance - */ - AnyValue.prototype.kvlistValue = null; - /** - * AnyValue bytesValue. - * @member {Uint8Array|null|undefined} bytesValue - * @memberof opentelemetry.proto.common.v1.AnyValue - * @instance - */ - AnyValue.prototype.bytesValue = null; - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - /** - * AnyValue value. - * @member {"stringValue"|"boolValue"|"intValue"|"doubleValue"|"arrayValue"|"kvlistValue"|"bytesValue"|undefined} value - * @memberof opentelemetry.proto.common.v1.AnyValue - * @instance - */ - Object.defineProperty(AnyValue.prototype, "value", { - get: $util.oneOfGetter($oneOfFields = ["stringValue", "boolValue", "intValue", "doubleValue", "arrayValue", "kvlistValue", "bytesValue"]), - set: $util.oneOfSetter($oneOfFields) - }); - /** - * Creates a new AnyValue instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.common.v1.AnyValue - * @static - * @param {opentelemetry.proto.common.v1.IAnyValue=} [properties] Properties to set - * @returns {opentelemetry.proto.common.v1.AnyValue} AnyValue instance - */ - AnyValue.create = function create(properties) { - return new AnyValue(properties); - }; - /** - * Encodes the specified AnyValue message. Does not implicitly {@link opentelemetry.proto.common.v1.AnyValue.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.common.v1.AnyValue - * @static - * @param {opentelemetry.proto.common.v1.IAnyValue} message AnyValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - AnyValue.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.stringValue != null && Object.hasOwnProperty.call(message, "stringValue")) - writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.stringValue); - if (message.boolValue != null && Object.hasOwnProperty.call(message, "boolValue")) - writer.uint32(/* id 2, wireType 0 =*/ 16).bool(message.boolValue); - if (message.intValue != null && Object.hasOwnProperty.call(message, "intValue")) - writer.uint32(/* id 3, wireType 0 =*/ 24).int64(message.intValue); - if (message.doubleValue != null && Object.hasOwnProperty.call(message, "doubleValue")) - writer.uint32(/* id 4, wireType 1 =*/ 33).double(message.doubleValue); - if (message.arrayValue != null && Object.hasOwnProperty.call(message, "arrayValue")) - $root.opentelemetry.proto.common.v1.ArrayValue.encode(message.arrayValue, writer.uint32(/* id 5, wireType 2 =*/ 42).fork()).ldelim(); - if (message.kvlistValue != null && Object.hasOwnProperty.call(message, "kvlistValue")) - $root.opentelemetry.proto.common.v1.KeyValueList.encode(message.kvlistValue, writer.uint32(/* id 6, wireType 2 =*/ 50).fork()).ldelim(); - if (message.bytesValue != null && Object.hasOwnProperty.call(message, "bytesValue")) - writer.uint32(/* id 7, wireType 2 =*/ 58).bytes(message.bytesValue); - return writer; - }; - /** - * Encodes the specified AnyValue message, length delimited. Does not implicitly {@link opentelemetry.proto.common.v1.AnyValue.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.common.v1.AnyValue - * @static - * @param {opentelemetry.proto.common.v1.IAnyValue} message AnyValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - AnyValue.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes an AnyValue message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.common.v1.AnyValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.common.v1.AnyValue} AnyValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - AnyValue.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.AnyValue(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.stringValue = reader.string(); - break; - } - case 2: { - message.boolValue = reader.bool(); - break; - } - case 3: { - message.intValue = reader.int64(); - break; - } - case 4: { - message.doubleValue = reader.double(); - break; - } - case 5: { - message.arrayValue = $root.opentelemetry.proto.common.v1.ArrayValue.decode(reader, reader.uint32()); - break; - } - case 6: { - message.kvlistValue = $root.opentelemetry.proto.common.v1.KeyValueList.decode(reader, reader.uint32()); - break; - } - case 7: { - message.bytesValue = reader.bytes(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes an AnyValue message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.common.v1.AnyValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.common.v1.AnyValue} AnyValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - AnyValue.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies an AnyValue message. - * @function verify - * @memberof opentelemetry.proto.common.v1.AnyValue - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - AnyValue.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.stringValue != null && message.hasOwnProperty("stringValue")) { - properties.value = 1; - if (!$util.isString(message.stringValue)) - return "stringValue: string expected"; - } - if (message.boolValue != null && message.hasOwnProperty("boolValue")) { - if (properties.value === 1) - return "value: multiple values"; - properties.value = 1; - if (typeof message.boolValue !== "boolean") - return "boolValue: boolean expected"; - } - if (message.intValue != null && message.hasOwnProperty("intValue")) { - if (properties.value === 1) - return "value: multiple values"; - properties.value = 1; - if (!$util.isInteger(message.intValue) && !(message.intValue && $util.isInteger(message.intValue.low) && $util.isInteger(message.intValue.high))) - return "intValue: integer|Long expected"; - } - if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) { - if (properties.value === 1) - return "value: multiple values"; - properties.value = 1; - if (typeof message.doubleValue !== "number") - return "doubleValue: number expected"; - } - if (message.arrayValue != null && message.hasOwnProperty("arrayValue")) { - if (properties.value === 1) - return "value: multiple values"; - properties.value = 1; - { - var error = $root.opentelemetry.proto.common.v1.ArrayValue.verify(message.arrayValue); - if (error) - return "arrayValue." + error; - } - } - if (message.kvlistValue != null && message.hasOwnProperty("kvlistValue")) { - if (properties.value === 1) - return "value: multiple values"; - properties.value = 1; - { - var error = $root.opentelemetry.proto.common.v1.KeyValueList.verify(message.kvlistValue); - if (error) - return "kvlistValue." + error; - } - } - if (message.bytesValue != null && message.hasOwnProperty("bytesValue")) { - if (properties.value === 1) - return "value: multiple values"; - properties.value = 1; - if (!(message.bytesValue && typeof message.bytesValue.length === "number" || $util.isString(message.bytesValue))) - return "bytesValue: buffer expected"; - } - return null; - }; - /** - * Creates an AnyValue message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.common.v1.AnyValue - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.common.v1.AnyValue} AnyValue - */ - AnyValue.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.common.v1.AnyValue) - return object; - var message = new $root.opentelemetry.proto.common.v1.AnyValue(); - if (object.stringValue != null) - message.stringValue = String(object.stringValue); - if (object.boolValue != null) - message.boolValue = Boolean(object.boolValue); - if (object.intValue != null) - if ($util.Long) - (message.intValue = $util.Long.fromValue(object.intValue)).unsigned = false; - else if (typeof object.intValue === "string") - message.intValue = parseInt(object.intValue, 10); - else if (typeof object.intValue === "number") - message.intValue = object.intValue; - else if (typeof object.intValue === "object") - message.intValue = new $util.LongBits(object.intValue.low >>> 0, object.intValue.high >>> 0).toNumber(); - if (object.doubleValue != null) - message.doubleValue = Number(object.doubleValue); - if (object.arrayValue != null) { - if (typeof object.arrayValue !== "object") - throw TypeError(".opentelemetry.proto.common.v1.AnyValue.arrayValue: object expected"); - message.arrayValue = $root.opentelemetry.proto.common.v1.ArrayValue.fromObject(object.arrayValue); - } - if (object.kvlistValue != null) { - if (typeof object.kvlistValue !== "object") - throw TypeError(".opentelemetry.proto.common.v1.AnyValue.kvlistValue: object expected"); - message.kvlistValue = $root.opentelemetry.proto.common.v1.KeyValueList.fromObject(object.kvlistValue); - } - if (object.bytesValue != null) - if (typeof object.bytesValue === "string") - $util.base64.decode(object.bytesValue, message.bytesValue = $util.newBuffer($util.base64.length(object.bytesValue)), 0); - else if (object.bytesValue.length >= 0) - message.bytesValue = object.bytesValue; - return message; - }; - /** - * Creates a plain object from an AnyValue message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.common.v1.AnyValue - * @static - * @param {opentelemetry.proto.common.v1.AnyValue} message AnyValue - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - AnyValue.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (message.stringValue != null && message.hasOwnProperty("stringValue")) { - object.stringValue = message.stringValue; - if (options.oneofs) - object.value = "stringValue"; - } - if (message.boolValue != null && message.hasOwnProperty("boolValue")) { - object.boolValue = message.boolValue; - if (options.oneofs) - object.value = "boolValue"; - } - if (message.intValue != null && message.hasOwnProperty("intValue")) { - if (typeof message.intValue === "number") - object.intValue = options.longs === String ? String(message.intValue) : message.intValue; - else - object.intValue = options.longs === String ? $util.Long.prototype.toString.call(message.intValue) : options.longs === Number ? new $util.LongBits(message.intValue.low >>> 0, message.intValue.high >>> 0).toNumber() : message.intValue; - if (options.oneofs) - object.value = "intValue"; - } - if (message.doubleValue != null && message.hasOwnProperty("doubleValue")) { - object.doubleValue = options.json && !isFinite(message.doubleValue) ? String(message.doubleValue) : message.doubleValue; - if (options.oneofs) - object.value = "doubleValue"; - } - if (message.arrayValue != null && message.hasOwnProperty("arrayValue")) { - object.arrayValue = $root.opentelemetry.proto.common.v1.ArrayValue.toObject(message.arrayValue, options); - if (options.oneofs) - object.value = "arrayValue"; - } - if (message.kvlistValue != null && message.hasOwnProperty("kvlistValue")) { - object.kvlistValue = $root.opentelemetry.proto.common.v1.KeyValueList.toObject(message.kvlistValue, options); - if (options.oneofs) - object.value = "kvlistValue"; - } - if (message.bytesValue != null && message.hasOwnProperty("bytesValue")) { - object.bytesValue = options.bytes === String ? $util.base64.encode(message.bytesValue, 0, message.bytesValue.length) : options.bytes === Array ? Array.prototype.slice.call(message.bytesValue) : message.bytesValue; - if (options.oneofs) - object.value = "bytesValue"; - } - return object; - }; - /** - * Converts this AnyValue to JSON. - * @function toJSON - * @memberof opentelemetry.proto.common.v1.AnyValue - * @instance - * @returns {Object.} JSON object - */ - AnyValue.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for AnyValue - * @function getTypeUrl - * @memberof opentelemetry.proto.common.v1.AnyValue - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - AnyValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.common.v1.AnyValue"; - }; - return AnyValue; - })(); - v1.ArrayValue = (function () { - /** - * Properties of an ArrayValue. - * @memberof opentelemetry.proto.common.v1 - * @interface IArrayValue - * @property {Array.|null} [values] ArrayValue values - */ - /** - * Constructs a new ArrayValue. - * @memberof opentelemetry.proto.common.v1 - * @classdesc Represents an ArrayValue. - * @implements IArrayValue - * @constructor - * @param {opentelemetry.proto.common.v1.IArrayValue=} [properties] Properties to set - */ - function ArrayValue(properties) { - this.values = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * ArrayValue values. - * @member {Array.} values - * @memberof opentelemetry.proto.common.v1.ArrayValue - * @instance - */ - ArrayValue.prototype.values = $util.emptyArray; - /** - * Creates a new ArrayValue instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.common.v1.ArrayValue - * @static - * @param {opentelemetry.proto.common.v1.IArrayValue=} [properties] Properties to set - * @returns {opentelemetry.proto.common.v1.ArrayValue} ArrayValue instance - */ - ArrayValue.create = function create(properties) { - return new ArrayValue(properties); - }; - /** - * Encodes the specified ArrayValue message. Does not implicitly {@link opentelemetry.proto.common.v1.ArrayValue.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.common.v1.ArrayValue - * @static - * @param {opentelemetry.proto.common.v1.IArrayValue} message ArrayValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ArrayValue.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.values != null && message.values.length) - for (var i = 0; i < message.values.length; ++i) - $root.opentelemetry.proto.common.v1.AnyValue.encode(message.values[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - return writer; - }; - /** - * Encodes the specified ArrayValue message, length delimited. Does not implicitly {@link opentelemetry.proto.common.v1.ArrayValue.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.common.v1.ArrayValue - * @static - * @param {opentelemetry.proto.common.v1.IArrayValue} message ArrayValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ArrayValue.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes an ArrayValue message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.common.v1.ArrayValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.common.v1.ArrayValue} ArrayValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ArrayValue.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.ArrayValue(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - if (!(message.values && message.values.length)) - message.values = []; - message.values.push($root.opentelemetry.proto.common.v1.AnyValue.decode(reader, reader.uint32())); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes an ArrayValue message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.common.v1.ArrayValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.common.v1.ArrayValue} ArrayValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ArrayValue.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies an ArrayValue message. - * @function verify - * @memberof opentelemetry.proto.common.v1.ArrayValue - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ArrayValue.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.values != null && message.hasOwnProperty("values")) { - if (!Array.isArray(message.values)) - return "values: array expected"; - for (var i = 0; i < message.values.length; ++i) { - var error = $root.opentelemetry.proto.common.v1.AnyValue.verify(message.values[i]); - if (error) - return "values." + error; - } - } - return null; - }; - /** - * Creates an ArrayValue message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.common.v1.ArrayValue - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.common.v1.ArrayValue} ArrayValue - */ - ArrayValue.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.common.v1.ArrayValue) - return object; - var message = new $root.opentelemetry.proto.common.v1.ArrayValue(); - if (object.values) { - if (!Array.isArray(object.values)) - throw TypeError(".opentelemetry.proto.common.v1.ArrayValue.values: array expected"); - message.values = []; - for (var i = 0; i < object.values.length; ++i) { - if (typeof object.values[i] !== "object") - throw TypeError(".opentelemetry.proto.common.v1.ArrayValue.values: object expected"); - message.values[i] = $root.opentelemetry.proto.common.v1.AnyValue.fromObject(object.values[i]); - } - } - return message; - }; - /** - * Creates a plain object from an ArrayValue message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.common.v1.ArrayValue - * @static - * @param {opentelemetry.proto.common.v1.ArrayValue} message ArrayValue - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ArrayValue.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.values = []; - if (message.values && message.values.length) { - object.values = []; - for (var j = 0; j < message.values.length; ++j) - object.values[j] = $root.opentelemetry.proto.common.v1.AnyValue.toObject(message.values[j], options); - } - return object; - }; - /** - * Converts this ArrayValue to JSON. - * @function toJSON - * @memberof opentelemetry.proto.common.v1.ArrayValue - * @instance - * @returns {Object.} JSON object - */ - ArrayValue.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for ArrayValue - * @function getTypeUrl - * @memberof opentelemetry.proto.common.v1.ArrayValue - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ArrayValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.common.v1.ArrayValue"; - }; - return ArrayValue; - })(); - v1.KeyValueList = (function () { - /** - * Properties of a KeyValueList. - * @memberof opentelemetry.proto.common.v1 - * @interface IKeyValueList - * @property {Array.|null} [values] KeyValueList values - */ - /** - * Constructs a new KeyValueList. - * @memberof opentelemetry.proto.common.v1 - * @classdesc Represents a KeyValueList. - * @implements IKeyValueList - * @constructor - * @param {opentelemetry.proto.common.v1.IKeyValueList=} [properties] Properties to set - */ - function KeyValueList(properties) { - this.values = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * KeyValueList values. - * @member {Array.} values - * @memberof opentelemetry.proto.common.v1.KeyValueList - * @instance - */ - KeyValueList.prototype.values = $util.emptyArray; - /** - * Creates a new KeyValueList instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.common.v1.KeyValueList - * @static - * @param {opentelemetry.proto.common.v1.IKeyValueList=} [properties] Properties to set - * @returns {opentelemetry.proto.common.v1.KeyValueList} KeyValueList instance - */ - KeyValueList.create = function create(properties) { - return new KeyValueList(properties); - }; - /** - * Encodes the specified KeyValueList message. Does not implicitly {@link opentelemetry.proto.common.v1.KeyValueList.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.common.v1.KeyValueList - * @static - * @param {opentelemetry.proto.common.v1.IKeyValueList} message KeyValueList message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - KeyValueList.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.values != null && message.values.length) - for (var i = 0; i < message.values.length; ++i) - $root.opentelemetry.proto.common.v1.KeyValue.encode(message.values[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - return writer; - }; - /** - * Encodes the specified KeyValueList message, length delimited. Does not implicitly {@link opentelemetry.proto.common.v1.KeyValueList.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.common.v1.KeyValueList - * @static - * @param {opentelemetry.proto.common.v1.IKeyValueList} message KeyValueList message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - KeyValueList.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a KeyValueList message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.common.v1.KeyValueList - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.common.v1.KeyValueList} KeyValueList - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - KeyValueList.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.KeyValueList(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - if (!(message.values && message.values.length)) - message.values = []; - message.values.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a KeyValueList message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.common.v1.KeyValueList - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.common.v1.KeyValueList} KeyValueList - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - KeyValueList.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a KeyValueList message. - * @function verify - * @memberof opentelemetry.proto.common.v1.KeyValueList - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - KeyValueList.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.values != null && message.hasOwnProperty("values")) { - if (!Array.isArray(message.values)) - return "values: array expected"; - for (var i = 0; i < message.values.length; ++i) { - var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.values[i]); - if (error) - return "values." + error; - } - } - return null; - }; - /** - * Creates a KeyValueList message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.common.v1.KeyValueList - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.common.v1.KeyValueList} KeyValueList - */ - KeyValueList.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.common.v1.KeyValueList) - return object; - var message = new $root.opentelemetry.proto.common.v1.KeyValueList(); - if (object.values) { - if (!Array.isArray(object.values)) - throw TypeError(".opentelemetry.proto.common.v1.KeyValueList.values: array expected"); - message.values = []; - for (var i = 0; i < object.values.length; ++i) { - if (typeof object.values[i] !== "object") - throw TypeError(".opentelemetry.proto.common.v1.KeyValueList.values: object expected"); - message.values[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.values[i]); - } - } - return message; - }; - /** - * Creates a plain object from a KeyValueList message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.common.v1.KeyValueList - * @static - * @param {opentelemetry.proto.common.v1.KeyValueList} message KeyValueList - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - KeyValueList.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.values = []; - if (message.values && message.values.length) { - object.values = []; - for (var j = 0; j < message.values.length; ++j) - object.values[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.values[j], options); - } - return object; - }; - /** - * Converts this KeyValueList to JSON. - * @function toJSON - * @memberof opentelemetry.proto.common.v1.KeyValueList - * @instance - * @returns {Object.} JSON object - */ - KeyValueList.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for KeyValueList - * @function getTypeUrl - * @memberof opentelemetry.proto.common.v1.KeyValueList - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - KeyValueList.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.common.v1.KeyValueList"; - }; - return KeyValueList; - })(); - v1.KeyValue = (function () { - /** - * Properties of a KeyValue. - * @memberof opentelemetry.proto.common.v1 - * @interface IKeyValue - * @property {string|null} [key] KeyValue key - * @property {opentelemetry.proto.common.v1.IAnyValue|null} [value] KeyValue value - */ - /** - * Constructs a new KeyValue. - * @memberof opentelemetry.proto.common.v1 - * @classdesc Represents a KeyValue. - * @implements IKeyValue - * @constructor - * @param {opentelemetry.proto.common.v1.IKeyValue=} [properties] Properties to set - */ - function KeyValue(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * KeyValue key. - * @member {string|null|undefined} key - * @memberof opentelemetry.proto.common.v1.KeyValue - * @instance - */ - KeyValue.prototype.key = null; - /** - * KeyValue value. - * @member {opentelemetry.proto.common.v1.IAnyValue|null|undefined} value - * @memberof opentelemetry.proto.common.v1.KeyValue - * @instance - */ - KeyValue.prototype.value = null; - /** - * Creates a new KeyValue instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.common.v1.KeyValue - * @static - * @param {opentelemetry.proto.common.v1.IKeyValue=} [properties] Properties to set - * @returns {opentelemetry.proto.common.v1.KeyValue} KeyValue instance - */ - KeyValue.create = function create(properties) { - return new KeyValue(properties); - }; - /** - * Encodes the specified KeyValue message. Does not implicitly {@link opentelemetry.proto.common.v1.KeyValue.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.common.v1.KeyValue - * @static - * @param {opentelemetry.proto.common.v1.IKeyValue} message KeyValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - KeyValue.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.key != null && Object.hasOwnProperty.call(message, "key")) - writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.key); - if (message.value != null && Object.hasOwnProperty.call(message, "value")) - $root.opentelemetry.proto.common.v1.AnyValue.encode(message.value, writer.uint32(/* id 2, wireType 2 =*/ 18).fork()).ldelim(); - return writer; - }; - /** - * Encodes the specified KeyValue message, length delimited. Does not implicitly {@link opentelemetry.proto.common.v1.KeyValue.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.common.v1.KeyValue - * @static - * @param {opentelemetry.proto.common.v1.IKeyValue} message KeyValue message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - KeyValue.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a KeyValue message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.common.v1.KeyValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.common.v1.KeyValue} KeyValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - KeyValue.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.KeyValue(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.key = reader.string(); - break; - } - case 2: { - message.value = $root.opentelemetry.proto.common.v1.AnyValue.decode(reader, reader.uint32()); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a KeyValue message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.common.v1.KeyValue - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.common.v1.KeyValue} KeyValue - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - KeyValue.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a KeyValue message. - * @function verify - * @memberof opentelemetry.proto.common.v1.KeyValue - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - KeyValue.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.key != null && message.hasOwnProperty("key")) - if (!$util.isString(message.key)) - return "key: string expected"; - if (message.value != null && message.hasOwnProperty("value")) { - var error = $root.opentelemetry.proto.common.v1.AnyValue.verify(message.value); - if (error) - return "value." + error; - } - return null; - }; - /** - * Creates a KeyValue message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.common.v1.KeyValue - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.common.v1.KeyValue} KeyValue - */ - KeyValue.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.common.v1.KeyValue) - return object; - var message = new $root.opentelemetry.proto.common.v1.KeyValue(); - if (object.key != null) - message.key = String(object.key); - if (object.value != null) { - if (typeof object.value !== "object") - throw TypeError(".opentelemetry.proto.common.v1.KeyValue.value: object expected"); - message.value = $root.opentelemetry.proto.common.v1.AnyValue.fromObject(object.value); - } - return message; - }; - /** - * Creates a plain object from a KeyValue message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.common.v1.KeyValue - * @static - * @param {opentelemetry.proto.common.v1.KeyValue} message KeyValue - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - KeyValue.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.key = ""; - object.value = null; - } - if (message.key != null && message.hasOwnProperty("key")) - object.key = message.key; - if (message.value != null && message.hasOwnProperty("value")) - object.value = $root.opentelemetry.proto.common.v1.AnyValue.toObject(message.value, options); - return object; - }; - /** - * Converts this KeyValue to JSON. - * @function toJSON - * @memberof opentelemetry.proto.common.v1.KeyValue - * @instance - * @returns {Object.} JSON object - */ - KeyValue.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for KeyValue - * @function getTypeUrl - * @memberof opentelemetry.proto.common.v1.KeyValue - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - KeyValue.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.common.v1.KeyValue"; - }; - return KeyValue; - })(); - v1.InstrumentationScope = (function () { - /** - * Properties of an InstrumentationScope. - * @memberof opentelemetry.proto.common.v1 - * @interface IInstrumentationScope - * @property {string|null} [name] InstrumentationScope name - * @property {string|null} [version] InstrumentationScope version - * @property {Array.|null} [attributes] InstrumentationScope attributes - * @property {number|null} [droppedAttributesCount] InstrumentationScope droppedAttributesCount - */ - /** - * Constructs a new InstrumentationScope. - * @memberof opentelemetry.proto.common.v1 - * @classdesc Represents an InstrumentationScope. - * @implements IInstrumentationScope - * @constructor - * @param {opentelemetry.proto.common.v1.IInstrumentationScope=} [properties] Properties to set - */ - function InstrumentationScope(properties) { - this.attributes = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * InstrumentationScope name. - * @member {string|null|undefined} name - * @memberof opentelemetry.proto.common.v1.InstrumentationScope - * @instance - */ - InstrumentationScope.prototype.name = null; - /** - * InstrumentationScope version. - * @member {string|null|undefined} version - * @memberof opentelemetry.proto.common.v1.InstrumentationScope - * @instance - */ - InstrumentationScope.prototype.version = null; - /** - * InstrumentationScope attributes. - * @member {Array.} attributes - * @memberof opentelemetry.proto.common.v1.InstrumentationScope - * @instance - */ - InstrumentationScope.prototype.attributes = $util.emptyArray; - /** - * InstrumentationScope droppedAttributesCount. - * @member {number|null|undefined} droppedAttributesCount - * @memberof opentelemetry.proto.common.v1.InstrumentationScope - * @instance - */ - InstrumentationScope.prototype.droppedAttributesCount = null; - /** - * Creates a new InstrumentationScope instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.common.v1.InstrumentationScope - * @static - * @param {opentelemetry.proto.common.v1.IInstrumentationScope=} [properties] Properties to set - * @returns {opentelemetry.proto.common.v1.InstrumentationScope} InstrumentationScope instance - */ - InstrumentationScope.create = function create(properties) { - return new InstrumentationScope(properties); - }; - /** - * Encodes the specified InstrumentationScope message. Does not implicitly {@link opentelemetry.proto.common.v1.InstrumentationScope.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.common.v1.InstrumentationScope - * @static - * @param {opentelemetry.proto.common.v1.IInstrumentationScope} message InstrumentationScope message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - InstrumentationScope.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.name != null && Object.hasOwnProperty.call(message, "name")) - writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.name); - if (message.version != null && Object.hasOwnProperty.call(message, "version")) - writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.version); - if (message.attributes != null && message.attributes.length) - for (var i = 0; i < message.attributes.length; ++i) - $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(/* id 3, wireType 2 =*/ 26).fork()).ldelim(); - if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount")) - writer.uint32(/* id 4, wireType 0 =*/ 32).uint32(message.droppedAttributesCount); - return writer; - }; - /** - * Encodes the specified InstrumentationScope message, length delimited. Does not implicitly {@link opentelemetry.proto.common.v1.InstrumentationScope.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.common.v1.InstrumentationScope - * @static - * @param {opentelemetry.proto.common.v1.IInstrumentationScope} message InstrumentationScope message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - InstrumentationScope.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes an InstrumentationScope message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.common.v1.InstrumentationScope - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.common.v1.InstrumentationScope} InstrumentationScope - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - InstrumentationScope.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.InstrumentationScope(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.name = reader.string(); - break; - } - case 2: { - message.version = reader.string(); - break; - } - case 3: { - if (!(message.attributes && message.attributes.length)) - message.attributes = []; - message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); - break; - } - case 4: { - message.droppedAttributesCount = reader.uint32(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes an InstrumentationScope message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.common.v1.InstrumentationScope - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.common.v1.InstrumentationScope} InstrumentationScope - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - InstrumentationScope.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies an InstrumentationScope message. - * @function verify - * @memberof opentelemetry.proto.common.v1.InstrumentationScope - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - InstrumentationScope.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isString(message.name)) - return "name: string expected"; - if (message.version != null && message.hasOwnProperty("version")) - if (!$util.isString(message.version)) - return "version: string expected"; - if (message.attributes != null && message.hasOwnProperty("attributes")) { - if (!Array.isArray(message.attributes)) - return "attributes: array expected"; - for (var i = 0; i < message.attributes.length; ++i) { - var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]); - if (error) - return "attributes." + error; - } - } - if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) - if (!$util.isInteger(message.droppedAttributesCount)) - return "droppedAttributesCount: integer expected"; - return null; - }; - /** - * Creates an InstrumentationScope message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.common.v1.InstrumentationScope - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.common.v1.InstrumentationScope} InstrumentationScope - */ - InstrumentationScope.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.common.v1.InstrumentationScope) - return object; - var message = new $root.opentelemetry.proto.common.v1.InstrumentationScope(); - if (object.name != null) - message.name = String(object.name); - if (object.version != null) - message.version = String(object.version); - if (object.attributes) { - if (!Array.isArray(object.attributes)) - throw TypeError(".opentelemetry.proto.common.v1.InstrumentationScope.attributes: array expected"); - message.attributes = []; - for (var i = 0; i < object.attributes.length; ++i) { - if (typeof object.attributes[i] !== "object") - throw TypeError(".opentelemetry.proto.common.v1.InstrumentationScope.attributes: object expected"); - message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]); - } - } - if (object.droppedAttributesCount != null) - message.droppedAttributesCount = object.droppedAttributesCount >>> 0; - return message; - }; - /** - * Creates a plain object from an InstrumentationScope message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.common.v1.InstrumentationScope - * @static - * @param {opentelemetry.proto.common.v1.InstrumentationScope} message InstrumentationScope - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - InstrumentationScope.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.attributes = []; - if (options.defaults) { - object.name = ""; - object.version = ""; - object.droppedAttributesCount = 0; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.version != null && message.hasOwnProperty("version")) - object.version = message.version; - if (message.attributes && message.attributes.length) { - object.attributes = []; - for (var j = 0; j < message.attributes.length; ++j) - object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options); - } - if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) - object.droppedAttributesCount = message.droppedAttributesCount; - return object; - }; - /** - * Converts this InstrumentationScope to JSON. - * @function toJSON - * @memberof opentelemetry.proto.common.v1.InstrumentationScope - * @instance - * @returns {Object.} JSON object - */ - InstrumentationScope.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for InstrumentationScope - * @function getTypeUrl - * @memberof opentelemetry.proto.common.v1.InstrumentationScope - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - InstrumentationScope.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.common.v1.InstrumentationScope"; - }; - return InstrumentationScope; - })(); - v1.EntityRef = (function () { - /** - * Properties of an EntityRef. - * @memberof opentelemetry.proto.common.v1 - * @interface IEntityRef - * @property {string|null} [schemaUrl] EntityRef schemaUrl - * @property {string|null} [type] EntityRef type - * @property {Array.|null} [idKeys] EntityRef idKeys - * @property {Array.|null} [descriptionKeys] EntityRef descriptionKeys - */ - /** - * Constructs a new EntityRef. - * @memberof opentelemetry.proto.common.v1 - * @classdesc Represents an EntityRef. - * @implements IEntityRef - * @constructor - * @param {opentelemetry.proto.common.v1.IEntityRef=} [properties] Properties to set - */ - function EntityRef(properties) { - this.idKeys = []; - this.descriptionKeys = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * EntityRef schemaUrl. - * @member {string|null|undefined} schemaUrl - * @memberof opentelemetry.proto.common.v1.EntityRef - * @instance - */ - EntityRef.prototype.schemaUrl = null; - /** - * EntityRef type. - * @member {string|null|undefined} type - * @memberof opentelemetry.proto.common.v1.EntityRef - * @instance - */ - EntityRef.prototype.type = null; - /** - * EntityRef idKeys. - * @member {Array.} idKeys - * @memberof opentelemetry.proto.common.v1.EntityRef - * @instance - */ - EntityRef.prototype.idKeys = $util.emptyArray; - /** - * EntityRef descriptionKeys. - * @member {Array.} descriptionKeys - * @memberof opentelemetry.proto.common.v1.EntityRef - * @instance - */ - EntityRef.prototype.descriptionKeys = $util.emptyArray; - /** - * Creates a new EntityRef instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.common.v1.EntityRef - * @static - * @param {opentelemetry.proto.common.v1.IEntityRef=} [properties] Properties to set - * @returns {opentelemetry.proto.common.v1.EntityRef} EntityRef instance - */ - EntityRef.create = function create(properties) { - return new EntityRef(properties); - }; - /** - * Encodes the specified EntityRef message. Does not implicitly {@link opentelemetry.proto.common.v1.EntityRef.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.common.v1.EntityRef - * @static - * @param {opentelemetry.proto.common.v1.IEntityRef} message EntityRef message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - EntityRef.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl")) - writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.schemaUrl); - if (message.type != null && Object.hasOwnProperty.call(message, "type")) - writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.type); - if (message.idKeys != null && message.idKeys.length) - for (var i = 0; i < message.idKeys.length; ++i) - writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.idKeys[i]); - if (message.descriptionKeys != null && message.descriptionKeys.length) - for (var i = 0; i < message.descriptionKeys.length; ++i) - writer.uint32(/* id 4, wireType 2 =*/ 34).string(message.descriptionKeys[i]); - return writer; - }; - /** - * Encodes the specified EntityRef message, length delimited. Does not implicitly {@link opentelemetry.proto.common.v1.EntityRef.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.common.v1.EntityRef - * @static - * @param {opentelemetry.proto.common.v1.IEntityRef} message EntityRef message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - EntityRef.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes an EntityRef message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.common.v1.EntityRef - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.common.v1.EntityRef} EntityRef - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - EntityRef.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.common.v1.EntityRef(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.schemaUrl = reader.string(); - break; - } - case 2: { - message.type = reader.string(); - break; - } - case 3: { - if (!(message.idKeys && message.idKeys.length)) - message.idKeys = []; - message.idKeys.push(reader.string()); - break; - } - case 4: { - if (!(message.descriptionKeys && message.descriptionKeys.length)) - message.descriptionKeys = []; - message.descriptionKeys.push(reader.string()); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes an EntityRef message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.common.v1.EntityRef - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.common.v1.EntityRef} EntityRef - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - EntityRef.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies an EntityRef message. - * @function verify - * @memberof opentelemetry.proto.common.v1.EntityRef - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - EntityRef.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) - if (!$util.isString(message.schemaUrl)) - return "schemaUrl: string expected"; - if (message.type != null && message.hasOwnProperty("type")) - if (!$util.isString(message.type)) - return "type: string expected"; - if (message.idKeys != null && message.hasOwnProperty("idKeys")) { - if (!Array.isArray(message.idKeys)) - return "idKeys: array expected"; - for (var i = 0; i < message.idKeys.length; ++i) - if (!$util.isString(message.idKeys[i])) - return "idKeys: string[] expected"; - } - if (message.descriptionKeys != null && message.hasOwnProperty("descriptionKeys")) { - if (!Array.isArray(message.descriptionKeys)) - return "descriptionKeys: array expected"; - for (var i = 0; i < message.descriptionKeys.length; ++i) - if (!$util.isString(message.descriptionKeys[i])) - return "descriptionKeys: string[] expected"; - } - return null; - }; - /** - * Creates an EntityRef message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.common.v1.EntityRef - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.common.v1.EntityRef} EntityRef - */ - EntityRef.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.common.v1.EntityRef) - return object; - var message = new $root.opentelemetry.proto.common.v1.EntityRef(); - if (object.schemaUrl != null) - message.schemaUrl = String(object.schemaUrl); - if (object.type != null) - message.type = String(object.type); - if (object.idKeys) { - if (!Array.isArray(object.idKeys)) - throw TypeError(".opentelemetry.proto.common.v1.EntityRef.idKeys: array expected"); - message.idKeys = []; - for (var i = 0; i < object.idKeys.length; ++i) - message.idKeys[i] = String(object.idKeys[i]); - } - if (object.descriptionKeys) { - if (!Array.isArray(object.descriptionKeys)) - throw TypeError(".opentelemetry.proto.common.v1.EntityRef.descriptionKeys: array expected"); - message.descriptionKeys = []; - for (var i = 0; i < object.descriptionKeys.length; ++i) - message.descriptionKeys[i] = String(object.descriptionKeys[i]); - } - return message; - }; - /** - * Creates a plain object from an EntityRef message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.common.v1.EntityRef - * @static - * @param {opentelemetry.proto.common.v1.EntityRef} message EntityRef - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - EntityRef.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) { - object.idKeys = []; - object.descriptionKeys = []; - } - if (options.defaults) { - object.schemaUrl = ""; - object.type = ""; - } - if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) - object.schemaUrl = message.schemaUrl; - if (message.type != null && message.hasOwnProperty("type")) - object.type = message.type; - if (message.idKeys && message.idKeys.length) { - object.idKeys = []; - for (var j = 0; j < message.idKeys.length; ++j) - object.idKeys[j] = message.idKeys[j]; - } - if (message.descriptionKeys && message.descriptionKeys.length) { - object.descriptionKeys = []; - for (var j = 0; j < message.descriptionKeys.length; ++j) - object.descriptionKeys[j] = message.descriptionKeys[j]; - } - return object; - }; - /** - * Converts this EntityRef to JSON. - * @function toJSON - * @memberof opentelemetry.proto.common.v1.EntityRef - * @instance - * @returns {Object.} JSON object - */ - EntityRef.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for EntityRef - * @function getTypeUrl - * @memberof opentelemetry.proto.common.v1.EntityRef - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - EntityRef.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.common.v1.EntityRef"; - }; - return EntityRef; - })(); - return v1; - })(); - return common; - })(); - proto.resource = (function () { - /** - * Namespace resource. - * @memberof opentelemetry.proto - * @namespace - */ - var resource = {}; - resource.v1 = (function () { - /** - * Namespace v1. - * @memberof opentelemetry.proto.resource - * @namespace - */ - var v1 = {}; - v1.Resource = (function () { - /** - * Properties of a Resource. - * @memberof opentelemetry.proto.resource.v1 - * @interface IResource - * @property {Array.|null} [attributes] Resource attributes - * @property {number|null} [droppedAttributesCount] Resource droppedAttributesCount - * @property {Array.|null} [entityRefs] Resource entityRefs - */ - /** - * Constructs a new Resource. - * @memberof opentelemetry.proto.resource.v1 - * @classdesc Represents a Resource. - * @implements IResource - * @constructor - * @param {opentelemetry.proto.resource.v1.IResource=} [properties] Properties to set - */ - function Resource(properties) { - this.attributes = []; - this.entityRefs = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * Resource attributes. - * @member {Array.} attributes - * @memberof opentelemetry.proto.resource.v1.Resource - * @instance - */ - Resource.prototype.attributes = $util.emptyArray; - /** - * Resource droppedAttributesCount. - * @member {number|null|undefined} droppedAttributesCount - * @memberof opentelemetry.proto.resource.v1.Resource - * @instance - */ - Resource.prototype.droppedAttributesCount = null; - /** - * Resource entityRefs. - * @member {Array.} entityRefs - * @memberof opentelemetry.proto.resource.v1.Resource - * @instance - */ - Resource.prototype.entityRefs = $util.emptyArray; - /** - * Creates a new Resource instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.resource.v1.Resource - * @static - * @param {opentelemetry.proto.resource.v1.IResource=} [properties] Properties to set - * @returns {opentelemetry.proto.resource.v1.Resource} Resource instance - */ - Resource.create = function create(properties) { - return new Resource(properties); - }; - /** - * Encodes the specified Resource message. Does not implicitly {@link opentelemetry.proto.resource.v1.Resource.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.resource.v1.Resource - * @static - * @param {opentelemetry.proto.resource.v1.IResource} message Resource message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Resource.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.attributes != null && message.attributes.length) - for (var i = 0; i < message.attributes.length; ++i) - $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount")) - writer.uint32(/* id 2, wireType 0 =*/ 16).uint32(message.droppedAttributesCount); - if (message.entityRefs != null && message.entityRefs.length) - for (var i = 0; i < message.entityRefs.length; ++i) - $root.opentelemetry.proto.common.v1.EntityRef.encode(message.entityRefs[i], writer.uint32(/* id 3, wireType 2 =*/ 26).fork()).ldelim(); - return writer; - }; - /** - * Encodes the specified Resource message, length delimited. Does not implicitly {@link opentelemetry.proto.resource.v1.Resource.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.resource.v1.Resource - * @static - * @param {opentelemetry.proto.resource.v1.IResource} message Resource message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Resource.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a Resource message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.resource.v1.Resource - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.resource.v1.Resource} Resource - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Resource.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.resource.v1.Resource(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - if (!(message.attributes && message.attributes.length)) - message.attributes = []; - message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); - break; - } - case 2: { - message.droppedAttributesCount = reader.uint32(); - break; - } - case 3: { - if (!(message.entityRefs && message.entityRefs.length)) - message.entityRefs = []; - message.entityRefs.push($root.opentelemetry.proto.common.v1.EntityRef.decode(reader, reader.uint32())); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a Resource message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.resource.v1.Resource - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.resource.v1.Resource} Resource - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Resource.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a Resource message. - * @function verify - * @memberof opentelemetry.proto.resource.v1.Resource - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Resource.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.attributes != null && message.hasOwnProperty("attributes")) { - if (!Array.isArray(message.attributes)) - return "attributes: array expected"; - for (var i = 0; i < message.attributes.length; ++i) { - var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]); - if (error) - return "attributes." + error; - } - } - if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) - if (!$util.isInteger(message.droppedAttributesCount)) - return "droppedAttributesCount: integer expected"; - if (message.entityRefs != null && message.hasOwnProperty("entityRefs")) { - if (!Array.isArray(message.entityRefs)) - return "entityRefs: array expected"; - for (var i = 0; i < message.entityRefs.length; ++i) { - var error = $root.opentelemetry.proto.common.v1.EntityRef.verify(message.entityRefs[i]); - if (error) - return "entityRefs." + error; - } - } - return null; - }; - /** - * Creates a Resource message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.resource.v1.Resource - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.resource.v1.Resource} Resource - */ - Resource.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.resource.v1.Resource) - return object; - var message = new $root.opentelemetry.proto.resource.v1.Resource(); - if (object.attributes) { - if (!Array.isArray(object.attributes)) - throw TypeError(".opentelemetry.proto.resource.v1.Resource.attributes: array expected"); - message.attributes = []; - for (var i = 0; i < object.attributes.length; ++i) { - if (typeof object.attributes[i] !== "object") - throw TypeError(".opentelemetry.proto.resource.v1.Resource.attributes: object expected"); - message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]); - } - } - if (object.droppedAttributesCount != null) - message.droppedAttributesCount = object.droppedAttributesCount >>> 0; - if (object.entityRefs) { - if (!Array.isArray(object.entityRefs)) - throw TypeError(".opentelemetry.proto.resource.v1.Resource.entityRefs: array expected"); - message.entityRefs = []; - for (var i = 0; i < object.entityRefs.length; ++i) { - if (typeof object.entityRefs[i] !== "object") - throw TypeError(".opentelemetry.proto.resource.v1.Resource.entityRefs: object expected"); - message.entityRefs[i] = $root.opentelemetry.proto.common.v1.EntityRef.fromObject(object.entityRefs[i]); - } - } - return message; - }; - /** - * Creates a plain object from a Resource message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.resource.v1.Resource - * @static - * @param {opentelemetry.proto.resource.v1.Resource} message Resource - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Resource.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) { - object.attributes = []; - object.entityRefs = []; - } - if (options.defaults) - object.droppedAttributesCount = 0; - if (message.attributes && message.attributes.length) { - object.attributes = []; - for (var j = 0; j < message.attributes.length; ++j) - object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options); - } - if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) - object.droppedAttributesCount = message.droppedAttributesCount; - if (message.entityRefs && message.entityRefs.length) { - object.entityRefs = []; - for (var j = 0; j < message.entityRefs.length; ++j) - object.entityRefs[j] = $root.opentelemetry.proto.common.v1.EntityRef.toObject(message.entityRefs[j], options); - } - return object; - }; - /** - * Converts this Resource to JSON. - * @function toJSON - * @memberof opentelemetry.proto.resource.v1.Resource - * @instance - * @returns {Object.} JSON object - */ - Resource.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for Resource - * @function getTypeUrl - * @memberof opentelemetry.proto.resource.v1.Resource - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Resource.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.resource.v1.Resource"; - }; - return Resource; - })(); - return v1; - })(); - return resource; - })(); - proto.trace = (function () { - /** - * Namespace trace. - * @memberof opentelemetry.proto - * @namespace - */ - var trace = {}; - trace.v1 = (function () { - /** - * Namespace v1. - * @memberof opentelemetry.proto.trace - * @namespace - */ - var v1 = {}; - v1.TracesData = (function () { - /** - * Properties of a TracesData. - * @memberof opentelemetry.proto.trace.v1 - * @interface ITracesData - * @property {Array.|null} [resourceSpans] TracesData resourceSpans - */ - /** - * Constructs a new TracesData. - * @memberof opentelemetry.proto.trace.v1 - * @classdesc Represents a TracesData. - * @implements ITracesData - * @constructor - * @param {opentelemetry.proto.trace.v1.ITracesData=} [properties] Properties to set - */ - function TracesData(properties) { - this.resourceSpans = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * TracesData resourceSpans. - * @member {Array.} resourceSpans - * @memberof opentelemetry.proto.trace.v1.TracesData - * @instance - */ - TracesData.prototype.resourceSpans = $util.emptyArray; - /** - * Creates a new TracesData instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.trace.v1.TracesData - * @static - * @param {opentelemetry.proto.trace.v1.ITracesData=} [properties] Properties to set - * @returns {opentelemetry.proto.trace.v1.TracesData} TracesData instance - */ - TracesData.create = function create(properties) { - return new TracesData(properties); - }; - /** - * Encodes the specified TracesData message. Does not implicitly {@link opentelemetry.proto.trace.v1.TracesData.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.trace.v1.TracesData - * @static - * @param {opentelemetry.proto.trace.v1.ITracesData} message TracesData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - TracesData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.resourceSpans != null && message.resourceSpans.length) - for (var i = 0; i < message.resourceSpans.length; ++i) - $root.opentelemetry.proto.trace.v1.ResourceSpans.encode(message.resourceSpans[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - return writer; - }; - /** - * Encodes the specified TracesData message, length delimited. Does not implicitly {@link opentelemetry.proto.trace.v1.TracesData.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.trace.v1.TracesData - * @static - * @param {opentelemetry.proto.trace.v1.ITracesData} message TracesData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - TracesData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a TracesData message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.trace.v1.TracesData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.trace.v1.TracesData} TracesData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - TracesData.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.TracesData(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - if (!(message.resourceSpans && message.resourceSpans.length)) - message.resourceSpans = []; - message.resourceSpans.push($root.opentelemetry.proto.trace.v1.ResourceSpans.decode(reader, reader.uint32())); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a TracesData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.trace.v1.TracesData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.trace.v1.TracesData} TracesData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - TracesData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a TracesData message. - * @function verify - * @memberof opentelemetry.proto.trace.v1.TracesData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - TracesData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.resourceSpans != null && message.hasOwnProperty("resourceSpans")) { - if (!Array.isArray(message.resourceSpans)) - return "resourceSpans: array expected"; - for (var i = 0; i < message.resourceSpans.length; ++i) { - var error = $root.opentelemetry.proto.trace.v1.ResourceSpans.verify(message.resourceSpans[i]); - if (error) - return "resourceSpans." + error; - } - } - return null; - }; - /** - * Creates a TracesData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.trace.v1.TracesData - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.trace.v1.TracesData} TracesData - */ - TracesData.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.trace.v1.TracesData) - return object; - var message = new $root.opentelemetry.proto.trace.v1.TracesData(); - if (object.resourceSpans) { - if (!Array.isArray(object.resourceSpans)) - throw TypeError(".opentelemetry.proto.trace.v1.TracesData.resourceSpans: array expected"); - message.resourceSpans = []; - for (var i = 0; i < object.resourceSpans.length; ++i) { - if (typeof object.resourceSpans[i] !== "object") - throw TypeError(".opentelemetry.proto.trace.v1.TracesData.resourceSpans: object expected"); - message.resourceSpans[i] = $root.opentelemetry.proto.trace.v1.ResourceSpans.fromObject(object.resourceSpans[i]); - } - } - return message; - }; - /** - * Creates a plain object from a TracesData message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.trace.v1.TracesData - * @static - * @param {opentelemetry.proto.trace.v1.TracesData} message TracesData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - TracesData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.resourceSpans = []; - if (message.resourceSpans && message.resourceSpans.length) { - object.resourceSpans = []; - for (var j = 0; j < message.resourceSpans.length; ++j) - object.resourceSpans[j] = $root.opentelemetry.proto.trace.v1.ResourceSpans.toObject(message.resourceSpans[j], options); - } - return object; - }; - /** - * Converts this TracesData to JSON. - * @function toJSON - * @memberof opentelemetry.proto.trace.v1.TracesData - * @instance - * @returns {Object.} JSON object - */ - TracesData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for TracesData - * @function getTypeUrl - * @memberof opentelemetry.proto.trace.v1.TracesData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - TracesData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.trace.v1.TracesData"; - }; - return TracesData; - })(); - v1.ResourceSpans = (function () { - /** - * Properties of a ResourceSpans. - * @memberof opentelemetry.proto.trace.v1 - * @interface IResourceSpans - * @property {opentelemetry.proto.resource.v1.IResource|null} [resource] ResourceSpans resource - * @property {Array.|null} [scopeSpans] ResourceSpans scopeSpans - * @property {string|null} [schemaUrl] ResourceSpans schemaUrl - */ - /** - * Constructs a new ResourceSpans. - * @memberof opentelemetry.proto.trace.v1 - * @classdesc Represents a ResourceSpans. - * @implements IResourceSpans - * @constructor - * @param {opentelemetry.proto.trace.v1.IResourceSpans=} [properties] Properties to set - */ - function ResourceSpans(properties) { - this.scopeSpans = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * ResourceSpans resource. - * @member {opentelemetry.proto.resource.v1.IResource|null|undefined} resource - * @memberof opentelemetry.proto.trace.v1.ResourceSpans - * @instance - */ - ResourceSpans.prototype.resource = null; - /** - * ResourceSpans scopeSpans. - * @member {Array.} scopeSpans - * @memberof opentelemetry.proto.trace.v1.ResourceSpans - * @instance - */ - ResourceSpans.prototype.scopeSpans = $util.emptyArray; - /** - * ResourceSpans schemaUrl. - * @member {string|null|undefined} schemaUrl - * @memberof opentelemetry.proto.trace.v1.ResourceSpans - * @instance - */ - ResourceSpans.prototype.schemaUrl = null; - /** - * Creates a new ResourceSpans instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.trace.v1.ResourceSpans - * @static - * @param {opentelemetry.proto.trace.v1.IResourceSpans=} [properties] Properties to set - * @returns {opentelemetry.proto.trace.v1.ResourceSpans} ResourceSpans instance - */ - ResourceSpans.create = function create(properties) { - return new ResourceSpans(properties); - }; - /** - * Encodes the specified ResourceSpans message. Does not implicitly {@link opentelemetry.proto.trace.v1.ResourceSpans.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.trace.v1.ResourceSpans - * @static - * @param {opentelemetry.proto.trace.v1.IResourceSpans} message ResourceSpans message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ResourceSpans.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) - $root.opentelemetry.proto.resource.v1.Resource.encode(message.resource, writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - if (message.scopeSpans != null && message.scopeSpans.length) - for (var i = 0; i < message.scopeSpans.length; ++i) - $root.opentelemetry.proto.trace.v1.ScopeSpans.encode(message.scopeSpans[i], writer.uint32(/* id 2, wireType 2 =*/ 18).fork()).ldelim(); - if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl")) - writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.schemaUrl); - return writer; - }; - /** - * Encodes the specified ResourceSpans message, length delimited. Does not implicitly {@link opentelemetry.proto.trace.v1.ResourceSpans.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.trace.v1.ResourceSpans - * @static - * @param {opentelemetry.proto.trace.v1.IResourceSpans} message ResourceSpans message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ResourceSpans.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a ResourceSpans message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.trace.v1.ResourceSpans - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.trace.v1.ResourceSpans} ResourceSpans - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ResourceSpans.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.ResourceSpans(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.resource = $root.opentelemetry.proto.resource.v1.Resource.decode(reader, reader.uint32()); - break; - } - case 2: { - if (!(message.scopeSpans && message.scopeSpans.length)) - message.scopeSpans = []; - message.scopeSpans.push($root.opentelemetry.proto.trace.v1.ScopeSpans.decode(reader, reader.uint32())); - break; - } - case 3: { - message.schemaUrl = reader.string(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a ResourceSpans message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.trace.v1.ResourceSpans - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.trace.v1.ResourceSpans} ResourceSpans - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ResourceSpans.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a ResourceSpans message. - * @function verify - * @memberof opentelemetry.proto.trace.v1.ResourceSpans - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ResourceSpans.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.resource != null && message.hasOwnProperty("resource")) { - var error = $root.opentelemetry.proto.resource.v1.Resource.verify(message.resource); - if (error) - return "resource." + error; - } - if (message.scopeSpans != null && message.hasOwnProperty("scopeSpans")) { - if (!Array.isArray(message.scopeSpans)) - return "scopeSpans: array expected"; - for (var i = 0; i < message.scopeSpans.length; ++i) { - var error = $root.opentelemetry.proto.trace.v1.ScopeSpans.verify(message.scopeSpans[i]); - if (error) - return "scopeSpans." + error; - } - } - if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) - if (!$util.isString(message.schemaUrl)) - return "schemaUrl: string expected"; - return null; - }; - /** - * Creates a ResourceSpans message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.trace.v1.ResourceSpans - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.trace.v1.ResourceSpans} ResourceSpans - */ - ResourceSpans.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.trace.v1.ResourceSpans) - return object; - var message = new $root.opentelemetry.proto.trace.v1.ResourceSpans(); - if (object.resource != null) { - if (typeof object.resource !== "object") - throw TypeError(".opentelemetry.proto.trace.v1.ResourceSpans.resource: object expected"); - message.resource = $root.opentelemetry.proto.resource.v1.Resource.fromObject(object.resource); - } - if (object.scopeSpans) { - if (!Array.isArray(object.scopeSpans)) - throw TypeError(".opentelemetry.proto.trace.v1.ResourceSpans.scopeSpans: array expected"); - message.scopeSpans = []; - for (var i = 0; i < object.scopeSpans.length; ++i) { - if (typeof object.scopeSpans[i] !== "object") - throw TypeError(".opentelemetry.proto.trace.v1.ResourceSpans.scopeSpans: object expected"); - message.scopeSpans[i] = $root.opentelemetry.proto.trace.v1.ScopeSpans.fromObject(object.scopeSpans[i]); - } - } - if (object.schemaUrl != null) - message.schemaUrl = String(object.schemaUrl); - return message; - }; - /** - * Creates a plain object from a ResourceSpans message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.trace.v1.ResourceSpans - * @static - * @param {opentelemetry.proto.trace.v1.ResourceSpans} message ResourceSpans - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ResourceSpans.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.scopeSpans = []; - if (options.defaults) { - object.resource = null; - object.schemaUrl = ""; - } - if (message.resource != null && message.hasOwnProperty("resource")) - object.resource = $root.opentelemetry.proto.resource.v1.Resource.toObject(message.resource, options); - if (message.scopeSpans && message.scopeSpans.length) { - object.scopeSpans = []; - for (var j = 0; j < message.scopeSpans.length; ++j) - object.scopeSpans[j] = $root.opentelemetry.proto.trace.v1.ScopeSpans.toObject(message.scopeSpans[j], options); - } - if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) - object.schemaUrl = message.schemaUrl; - return object; - }; - /** - * Converts this ResourceSpans to JSON. - * @function toJSON - * @memberof opentelemetry.proto.trace.v1.ResourceSpans - * @instance - * @returns {Object.} JSON object - */ - ResourceSpans.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for ResourceSpans - * @function getTypeUrl - * @memberof opentelemetry.proto.trace.v1.ResourceSpans - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ResourceSpans.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.trace.v1.ResourceSpans"; - }; - return ResourceSpans; - })(); - v1.ScopeSpans = (function () { - /** - * Properties of a ScopeSpans. - * @memberof opentelemetry.proto.trace.v1 - * @interface IScopeSpans - * @property {opentelemetry.proto.common.v1.IInstrumentationScope|null} [scope] ScopeSpans scope - * @property {Array.|null} [spans] ScopeSpans spans - * @property {string|null} [schemaUrl] ScopeSpans schemaUrl - */ - /** - * Constructs a new ScopeSpans. - * @memberof opentelemetry.proto.trace.v1 - * @classdesc Represents a ScopeSpans. - * @implements IScopeSpans - * @constructor - * @param {opentelemetry.proto.trace.v1.IScopeSpans=} [properties] Properties to set - */ - function ScopeSpans(properties) { - this.spans = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * ScopeSpans scope. - * @member {opentelemetry.proto.common.v1.IInstrumentationScope|null|undefined} scope - * @memberof opentelemetry.proto.trace.v1.ScopeSpans - * @instance - */ - ScopeSpans.prototype.scope = null; - /** - * ScopeSpans spans. - * @member {Array.} spans - * @memberof opentelemetry.proto.trace.v1.ScopeSpans - * @instance - */ - ScopeSpans.prototype.spans = $util.emptyArray; - /** - * ScopeSpans schemaUrl. - * @member {string|null|undefined} schemaUrl - * @memberof opentelemetry.proto.trace.v1.ScopeSpans - * @instance - */ - ScopeSpans.prototype.schemaUrl = null; - /** - * Creates a new ScopeSpans instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.trace.v1.ScopeSpans - * @static - * @param {opentelemetry.proto.trace.v1.IScopeSpans=} [properties] Properties to set - * @returns {opentelemetry.proto.trace.v1.ScopeSpans} ScopeSpans instance - */ - ScopeSpans.create = function create(properties) { - return new ScopeSpans(properties); - }; - /** - * Encodes the specified ScopeSpans message. Does not implicitly {@link opentelemetry.proto.trace.v1.ScopeSpans.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.trace.v1.ScopeSpans - * @static - * @param {opentelemetry.proto.trace.v1.IScopeSpans} message ScopeSpans message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ScopeSpans.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.scope != null && Object.hasOwnProperty.call(message, "scope")) - $root.opentelemetry.proto.common.v1.InstrumentationScope.encode(message.scope, writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - if (message.spans != null && message.spans.length) - for (var i = 0; i < message.spans.length; ++i) - $root.opentelemetry.proto.trace.v1.Span.encode(message.spans[i], writer.uint32(/* id 2, wireType 2 =*/ 18).fork()).ldelim(); - if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl")) - writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.schemaUrl); - return writer; - }; - /** - * Encodes the specified ScopeSpans message, length delimited. Does not implicitly {@link opentelemetry.proto.trace.v1.ScopeSpans.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.trace.v1.ScopeSpans - * @static - * @param {opentelemetry.proto.trace.v1.IScopeSpans} message ScopeSpans message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ScopeSpans.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a ScopeSpans message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.trace.v1.ScopeSpans - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.trace.v1.ScopeSpans} ScopeSpans - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ScopeSpans.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.ScopeSpans(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.decode(reader, reader.uint32()); - break; - } - case 2: { - if (!(message.spans && message.spans.length)) - message.spans = []; - message.spans.push($root.opentelemetry.proto.trace.v1.Span.decode(reader, reader.uint32())); - break; - } - case 3: { - message.schemaUrl = reader.string(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a ScopeSpans message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.trace.v1.ScopeSpans - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.trace.v1.ScopeSpans} ScopeSpans - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ScopeSpans.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a ScopeSpans message. - * @function verify - * @memberof opentelemetry.proto.trace.v1.ScopeSpans - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ScopeSpans.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.scope != null && message.hasOwnProperty("scope")) { - var error = $root.opentelemetry.proto.common.v1.InstrumentationScope.verify(message.scope); - if (error) - return "scope." + error; - } - if (message.spans != null && message.hasOwnProperty("spans")) { - if (!Array.isArray(message.spans)) - return "spans: array expected"; - for (var i = 0; i < message.spans.length; ++i) { - var error = $root.opentelemetry.proto.trace.v1.Span.verify(message.spans[i]); - if (error) - return "spans." + error; - } - } - if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) - if (!$util.isString(message.schemaUrl)) - return "schemaUrl: string expected"; - return null; - }; - /** - * Creates a ScopeSpans message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.trace.v1.ScopeSpans - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.trace.v1.ScopeSpans} ScopeSpans - */ - ScopeSpans.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.trace.v1.ScopeSpans) - return object; - var message = new $root.opentelemetry.proto.trace.v1.ScopeSpans(); - if (object.scope != null) { - if (typeof object.scope !== "object") - throw TypeError(".opentelemetry.proto.trace.v1.ScopeSpans.scope: object expected"); - message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(object.scope); - } - if (object.spans) { - if (!Array.isArray(object.spans)) - throw TypeError(".opentelemetry.proto.trace.v1.ScopeSpans.spans: array expected"); - message.spans = []; - for (var i = 0; i < object.spans.length; ++i) { - if (typeof object.spans[i] !== "object") - throw TypeError(".opentelemetry.proto.trace.v1.ScopeSpans.spans: object expected"); - message.spans[i] = $root.opentelemetry.proto.trace.v1.Span.fromObject(object.spans[i]); - } - } - if (object.schemaUrl != null) - message.schemaUrl = String(object.schemaUrl); - return message; - }; - /** - * Creates a plain object from a ScopeSpans message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.trace.v1.ScopeSpans - * @static - * @param {opentelemetry.proto.trace.v1.ScopeSpans} message ScopeSpans - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ScopeSpans.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.spans = []; - if (options.defaults) { - object.scope = null; - object.schemaUrl = ""; - } - if (message.scope != null && message.hasOwnProperty("scope")) - object.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.toObject(message.scope, options); - if (message.spans && message.spans.length) { - object.spans = []; - for (var j = 0; j < message.spans.length; ++j) - object.spans[j] = $root.opentelemetry.proto.trace.v1.Span.toObject(message.spans[j], options); - } - if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) - object.schemaUrl = message.schemaUrl; - return object; - }; - /** - * Converts this ScopeSpans to JSON. - * @function toJSON - * @memberof opentelemetry.proto.trace.v1.ScopeSpans - * @instance - * @returns {Object.} JSON object - */ - ScopeSpans.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for ScopeSpans - * @function getTypeUrl - * @memberof opentelemetry.proto.trace.v1.ScopeSpans - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ScopeSpans.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.trace.v1.ScopeSpans"; - }; - return ScopeSpans; - })(); - v1.Span = (function () { - /** - * Properties of a Span. - * @memberof opentelemetry.proto.trace.v1 - * @interface ISpan - * @property {Uint8Array|null} [traceId] Span traceId - * @property {Uint8Array|null} [spanId] Span spanId - * @property {string|null} [traceState] Span traceState - * @property {Uint8Array|null} [parentSpanId] Span parentSpanId - * @property {number|null} [flags] Span flags - * @property {string|null} [name] Span name - * @property {opentelemetry.proto.trace.v1.Span.SpanKind|null} [kind] Span kind - * @property {number|Long|null} [startTimeUnixNano] Span startTimeUnixNano - * @property {number|Long|null} [endTimeUnixNano] Span endTimeUnixNano - * @property {Array.|null} [attributes] Span attributes - * @property {number|null} [droppedAttributesCount] Span droppedAttributesCount - * @property {Array.|null} [events] Span events - * @property {number|null} [droppedEventsCount] Span droppedEventsCount - * @property {Array.|null} [links] Span links - * @property {number|null} [droppedLinksCount] Span droppedLinksCount - * @property {opentelemetry.proto.trace.v1.IStatus|null} [status] Span status - */ - /** - * Constructs a new Span. - * @memberof opentelemetry.proto.trace.v1 - * @classdesc Represents a Span. - * @implements ISpan - * @constructor - * @param {opentelemetry.proto.trace.v1.ISpan=} [properties] Properties to set - */ - function Span(properties) { - this.attributes = []; - this.events = []; - this.links = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * Span traceId. - * @member {Uint8Array|null|undefined} traceId - * @memberof opentelemetry.proto.trace.v1.Span - * @instance - */ - Span.prototype.traceId = null; - /** - * Span spanId. - * @member {Uint8Array|null|undefined} spanId - * @memberof opentelemetry.proto.trace.v1.Span - * @instance - */ - Span.prototype.spanId = null; - /** - * Span traceState. - * @member {string|null|undefined} traceState - * @memberof opentelemetry.proto.trace.v1.Span - * @instance - */ - Span.prototype.traceState = null; - /** - * Span parentSpanId. - * @member {Uint8Array|null|undefined} parentSpanId - * @memberof opentelemetry.proto.trace.v1.Span - * @instance - */ - Span.prototype.parentSpanId = null; - /** - * Span flags. - * @member {number|null|undefined} flags - * @memberof opentelemetry.proto.trace.v1.Span - * @instance - */ - Span.prototype.flags = null; - /** - * Span name. - * @member {string|null|undefined} name - * @memberof opentelemetry.proto.trace.v1.Span - * @instance - */ - Span.prototype.name = null; - /** - * Span kind. - * @member {opentelemetry.proto.trace.v1.Span.SpanKind|null|undefined} kind - * @memberof opentelemetry.proto.trace.v1.Span - * @instance - */ - Span.prototype.kind = null; - /** - * Span startTimeUnixNano. - * @member {number|Long|null|undefined} startTimeUnixNano - * @memberof opentelemetry.proto.trace.v1.Span - * @instance - */ - Span.prototype.startTimeUnixNano = null; - /** - * Span endTimeUnixNano. - * @member {number|Long|null|undefined} endTimeUnixNano - * @memberof opentelemetry.proto.trace.v1.Span - * @instance - */ - Span.prototype.endTimeUnixNano = null; - /** - * Span attributes. - * @member {Array.} attributes - * @memberof opentelemetry.proto.trace.v1.Span - * @instance - */ - Span.prototype.attributes = $util.emptyArray; - /** - * Span droppedAttributesCount. - * @member {number|null|undefined} droppedAttributesCount - * @memberof opentelemetry.proto.trace.v1.Span - * @instance - */ - Span.prototype.droppedAttributesCount = null; - /** - * Span events. - * @member {Array.} events - * @memberof opentelemetry.proto.trace.v1.Span - * @instance - */ - Span.prototype.events = $util.emptyArray; - /** - * Span droppedEventsCount. - * @member {number|null|undefined} droppedEventsCount - * @memberof opentelemetry.proto.trace.v1.Span - * @instance - */ - Span.prototype.droppedEventsCount = null; - /** - * Span links. - * @member {Array.} links - * @memberof opentelemetry.proto.trace.v1.Span - * @instance - */ - Span.prototype.links = $util.emptyArray; - /** - * Span droppedLinksCount. - * @member {number|null|undefined} droppedLinksCount - * @memberof opentelemetry.proto.trace.v1.Span - * @instance - */ - Span.prototype.droppedLinksCount = null; - /** - * Span status. - * @member {opentelemetry.proto.trace.v1.IStatus|null|undefined} status - * @memberof opentelemetry.proto.trace.v1.Span - * @instance - */ - Span.prototype.status = null; - /** - * Creates a new Span instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.trace.v1.Span - * @static - * @param {opentelemetry.proto.trace.v1.ISpan=} [properties] Properties to set - * @returns {opentelemetry.proto.trace.v1.Span} Span instance - */ - Span.create = function create(properties) { - return new Span(properties); - }; - /** - * Encodes the specified Span message. Does not implicitly {@link opentelemetry.proto.trace.v1.Span.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.trace.v1.Span - * @static - * @param {opentelemetry.proto.trace.v1.ISpan} message Span message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Span.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.traceId != null && Object.hasOwnProperty.call(message, "traceId")) - writer.uint32(/* id 1, wireType 2 =*/ 10).bytes(message.traceId); - if (message.spanId != null && Object.hasOwnProperty.call(message, "spanId")) - writer.uint32(/* id 2, wireType 2 =*/ 18).bytes(message.spanId); - if (message.traceState != null && Object.hasOwnProperty.call(message, "traceState")) - writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.traceState); - if (message.parentSpanId != null && Object.hasOwnProperty.call(message, "parentSpanId")) - writer.uint32(/* id 4, wireType 2 =*/ 34).bytes(message.parentSpanId); - if (message.name != null && Object.hasOwnProperty.call(message, "name")) - writer.uint32(/* id 5, wireType 2 =*/ 42).string(message.name); - if (message.kind != null && Object.hasOwnProperty.call(message, "kind")) - writer.uint32(/* id 6, wireType 0 =*/ 48).int32(message.kind); - if (message.startTimeUnixNano != null && Object.hasOwnProperty.call(message, "startTimeUnixNano")) - writer.uint32(/* id 7, wireType 1 =*/ 57).fixed64(message.startTimeUnixNano); - if (message.endTimeUnixNano != null && Object.hasOwnProperty.call(message, "endTimeUnixNano")) - writer.uint32(/* id 8, wireType 1 =*/ 65).fixed64(message.endTimeUnixNano); - if (message.attributes != null && message.attributes.length) - for (var i = 0; i < message.attributes.length; ++i) - $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(/* id 9, wireType 2 =*/ 74).fork()).ldelim(); - if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount")) - writer.uint32(/* id 10, wireType 0 =*/ 80).uint32(message.droppedAttributesCount); - if (message.events != null && message.events.length) - for (var i = 0; i < message.events.length; ++i) - $root.opentelemetry.proto.trace.v1.Span.Event.encode(message.events[i], writer.uint32(/* id 11, wireType 2 =*/ 90).fork()).ldelim(); - if (message.droppedEventsCount != null && Object.hasOwnProperty.call(message, "droppedEventsCount")) - writer.uint32(/* id 12, wireType 0 =*/ 96).uint32(message.droppedEventsCount); - if (message.links != null && message.links.length) - for (var i = 0; i < message.links.length; ++i) - $root.opentelemetry.proto.trace.v1.Span.Link.encode(message.links[i], writer.uint32(/* id 13, wireType 2 =*/ 106).fork()).ldelim(); - if (message.droppedLinksCount != null && Object.hasOwnProperty.call(message, "droppedLinksCount")) - writer.uint32(/* id 14, wireType 0 =*/ 112).uint32(message.droppedLinksCount); - if (message.status != null && Object.hasOwnProperty.call(message, "status")) - $root.opentelemetry.proto.trace.v1.Status.encode(message.status, writer.uint32(/* id 15, wireType 2 =*/ 122).fork()).ldelim(); - if (message.flags != null && Object.hasOwnProperty.call(message, "flags")) - writer.uint32(/* id 16, wireType 5 =*/ 133).fixed32(message.flags); - return writer; - }; - /** - * Encodes the specified Span message, length delimited. Does not implicitly {@link opentelemetry.proto.trace.v1.Span.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.trace.v1.Span - * @static - * @param {opentelemetry.proto.trace.v1.ISpan} message Span message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Span.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a Span message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.trace.v1.Span - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.trace.v1.Span} Span - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Span.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.Span(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.traceId = reader.bytes(); - break; - } - case 2: { - message.spanId = reader.bytes(); - break; - } - case 3: { - message.traceState = reader.string(); - break; - } - case 4: { - message.parentSpanId = reader.bytes(); - break; - } - case 16: { - message.flags = reader.fixed32(); - break; - } - case 5: { - message.name = reader.string(); - break; - } - case 6: { - message.kind = reader.int32(); - break; - } - case 7: { - message.startTimeUnixNano = reader.fixed64(); - break; - } - case 8: { - message.endTimeUnixNano = reader.fixed64(); - break; - } - case 9: { - if (!(message.attributes && message.attributes.length)) - message.attributes = []; - message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); - break; - } - case 10: { - message.droppedAttributesCount = reader.uint32(); - break; - } - case 11: { - if (!(message.events && message.events.length)) - message.events = []; - message.events.push($root.opentelemetry.proto.trace.v1.Span.Event.decode(reader, reader.uint32())); - break; - } - case 12: { - message.droppedEventsCount = reader.uint32(); - break; - } - case 13: { - if (!(message.links && message.links.length)) - message.links = []; - message.links.push($root.opentelemetry.proto.trace.v1.Span.Link.decode(reader, reader.uint32())); - break; - } - case 14: { - message.droppedLinksCount = reader.uint32(); - break; - } - case 15: { - message.status = $root.opentelemetry.proto.trace.v1.Status.decode(reader, reader.uint32()); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a Span message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.trace.v1.Span - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.trace.v1.Span} Span - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Span.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a Span message. - * @function verify - * @memberof opentelemetry.proto.trace.v1.Span - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Span.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.traceId != null && message.hasOwnProperty("traceId")) - if (!(message.traceId && typeof message.traceId.length === "number" || $util.isString(message.traceId))) - return "traceId: buffer expected"; - if (message.spanId != null && message.hasOwnProperty("spanId")) - if (!(message.spanId && typeof message.spanId.length === "number" || $util.isString(message.spanId))) - return "spanId: buffer expected"; - if (message.traceState != null && message.hasOwnProperty("traceState")) - if (!$util.isString(message.traceState)) - return "traceState: string expected"; - if (message.parentSpanId != null && message.hasOwnProperty("parentSpanId")) - if (!(message.parentSpanId && typeof message.parentSpanId.length === "number" || $util.isString(message.parentSpanId))) - return "parentSpanId: buffer expected"; - if (message.flags != null && message.hasOwnProperty("flags")) - if (!$util.isInteger(message.flags)) - return "flags: integer expected"; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isString(message.name)) - return "name: string expected"; - if (message.kind != null && message.hasOwnProperty("kind")) - switch (message.kind) { - default: - return "kind: enum value expected"; - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - break; - } - if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) - if (!$util.isInteger(message.startTimeUnixNano) && !(message.startTimeUnixNano && $util.isInteger(message.startTimeUnixNano.low) && $util.isInteger(message.startTimeUnixNano.high))) - return "startTimeUnixNano: integer|Long expected"; - if (message.endTimeUnixNano != null && message.hasOwnProperty("endTimeUnixNano")) - if (!$util.isInteger(message.endTimeUnixNano) && !(message.endTimeUnixNano && $util.isInteger(message.endTimeUnixNano.low) && $util.isInteger(message.endTimeUnixNano.high))) - return "endTimeUnixNano: integer|Long expected"; - if (message.attributes != null && message.hasOwnProperty("attributes")) { - if (!Array.isArray(message.attributes)) - return "attributes: array expected"; - for (var i = 0; i < message.attributes.length; ++i) { - var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]); - if (error) - return "attributes." + error; - } - } - if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) - if (!$util.isInteger(message.droppedAttributesCount)) - return "droppedAttributesCount: integer expected"; - if (message.events != null && message.hasOwnProperty("events")) { - if (!Array.isArray(message.events)) - return "events: array expected"; - for (var i = 0; i < message.events.length; ++i) { - var error = $root.opentelemetry.proto.trace.v1.Span.Event.verify(message.events[i]); - if (error) - return "events." + error; - } - } - if (message.droppedEventsCount != null && message.hasOwnProperty("droppedEventsCount")) - if (!$util.isInteger(message.droppedEventsCount)) - return "droppedEventsCount: integer expected"; - if (message.links != null && message.hasOwnProperty("links")) { - if (!Array.isArray(message.links)) - return "links: array expected"; - for (var i = 0; i < message.links.length; ++i) { - var error = $root.opentelemetry.proto.trace.v1.Span.Link.verify(message.links[i]); - if (error) - return "links." + error; - } - } - if (message.droppedLinksCount != null && message.hasOwnProperty("droppedLinksCount")) - if (!$util.isInteger(message.droppedLinksCount)) - return "droppedLinksCount: integer expected"; - if (message.status != null && message.hasOwnProperty("status")) { - var error = $root.opentelemetry.proto.trace.v1.Status.verify(message.status); - if (error) - return "status." + error; - } - return null; - }; - /** - * Creates a Span message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.trace.v1.Span - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.trace.v1.Span} Span - */ - Span.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.trace.v1.Span) - return object; - var message = new $root.opentelemetry.proto.trace.v1.Span(); - if (object.traceId != null) - if (typeof object.traceId === "string") - $util.base64.decode(object.traceId, message.traceId = $util.newBuffer($util.base64.length(object.traceId)), 0); - else if (object.traceId.length >= 0) - message.traceId = object.traceId; - if (object.spanId != null) - if (typeof object.spanId === "string") - $util.base64.decode(object.spanId, message.spanId = $util.newBuffer($util.base64.length(object.spanId)), 0); - else if (object.spanId.length >= 0) - message.spanId = object.spanId; - if (object.traceState != null) - message.traceState = String(object.traceState); - if (object.parentSpanId != null) - if (typeof object.parentSpanId === "string") - $util.base64.decode(object.parentSpanId, message.parentSpanId = $util.newBuffer($util.base64.length(object.parentSpanId)), 0); - else if (object.parentSpanId.length >= 0) - message.parentSpanId = object.parentSpanId; - if (object.flags != null) - message.flags = object.flags >>> 0; - if (object.name != null) - message.name = String(object.name); - switch (object.kind) { - default: - if (typeof object.kind === "number") { - message.kind = object.kind; - break; - } - break; - case "SPAN_KIND_UNSPECIFIED": - case 0: - message.kind = 0; - break; - case "SPAN_KIND_INTERNAL": - case 1: - message.kind = 1; - break; - case "SPAN_KIND_SERVER": - case 2: - message.kind = 2; - break; - case "SPAN_KIND_CLIENT": - case 3: - message.kind = 3; - break; - case "SPAN_KIND_PRODUCER": - case 4: - message.kind = 4; - break; - case "SPAN_KIND_CONSUMER": - case 5: - message.kind = 5; - break; - } - if (object.startTimeUnixNano != null) - if ($util.Long) - (message.startTimeUnixNano = $util.Long.fromValue(object.startTimeUnixNano)).unsigned = false; - else if (typeof object.startTimeUnixNano === "string") - message.startTimeUnixNano = parseInt(object.startTimeUnixNano, 10); - else if (typeof object.startTimeUnixNano === "number") - message.startTimeUnixNano = object.startTimeUnixNano; - else if (typeof object.startTimeUnixNano === "object") - message.startTimeUnixNano = new $util.LongBits(object.startTimeUnixNano.low >>> 0, object.startTimeUnixNano.high >>> 0).toNumber(); - if (object.endTimeUnixNano != null) - if ($util.Long) - (message.endTimeUnixNano = $util.Long.fromValue(object.endTimeUnixNano)).unsigned = false; - else if (typeof object.endTimeUnixNano === "string") - message.endTimeUnixNano = parseInt(object.endTimeUnixNano, 10); - else if (typeof object.endTimeUnixNano === "number") - message.endTimeUnixNano = object.endTimeUnixNano; - else if (typeof object.endTimeUnixNano === "object") - message.endTimeUnixNano = new $util.LongBits(object.endTimeUnixNano.low >>> 0, object.endTimeUnixNano.high >>> 0).toNumber(); - if (object.attributes) { - if (!Array.isArray(object.attributes)) - throw TypeError(".opentelemetry.proto.trace.v1.Span.attributes: array expected"); - message.attributes = []; - for (var i = 0; i < object.attributes.length; ++i) { - if (typeof object.attributes[i] !== "object") - throw TypeError(".opentelemetry.proto.trace.v1.Span.attributes: object expected"); - message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]); - } - } - if (object.droppedAttributesCount != null) - message.droppedAttributesCount = object.droppedAttributesCount >>> 0; - if (object.events) { - if (!Array.isArray(object.events)) - throw TypeError(".opentelemetry.proto.trace.v1.Span.events: array expected"); - message.events = []; - for (var i = 0; i < object.events.length; ++i) { - if (typeof object.events[i] !== "object") - throw TypeError(".opentelemetry.proto.trace.v1.Span.events: object expected"); - message.events[i] = $root.opentelemetry.proto.trace.v1.Span.Event.fromObject(object.events[i]); - } - } - if (object.droppedEventsCount != null) - message.droppedEventsCount = object.droppedEventsCount >>> 0; - if (object.links) { - if (!Array.isArray(object.links)) - throw TypeError(".opentelemetry.proto.trace.v1.Span.links: array expected"); - message.links = []; - for (var i = 0; i < object.links.length; ++i) { - if (typeof object.links[i] !== "object") - throw TypeError(".opentelemetry.proto.trace.v1.Span.links: object expected"); - message.links[i] = $root.opentelemetry.proto.trace.v1.Span.Link.fromObject(object.links[i]); - } - } - if (object.droppedLinksCount != null) - message.droppedLinksCount = object.droppedLinksCount >>> 0; - if (object.status != null) { - if (typeof object.status !== "object") - throw TypeError(".opentelemetry.proto.trace.v1.Span.status: object expected"); - message.status = $root.opentelemetry.proto.trace.v1.Status.fromObject(object.status); - } - return message; - }; - /** - * Creates a plain object from a Span message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.trace.v1.Span - * @static - * @param {opentelemetry.proto.trace.v1.Span} message Span - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Span.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) { - object.attributes = []; - object.events = []; - object.links = []; - } - if (options.defaults) { - if (options.bytes === String) - object.traceId = ""; - else { - object.traceId = []; - if (options.bytes !== Array) - object.traceId = $util.newBuffer(object.traceId); - } - if (options.bytes === String) - object.spanId = ""; - else { - object.spanId = []; - if (options.bytes !== Array) - object.spanId = $util.newBuffer(object.spanId); - } - object.traceState = ""; - if (options.bytes === String) - object.parentSpanId = ""; - else { - object.parentSpanId = []; - if (options.bytes !== Array) - object.parentSpanId = $util.newBuffer(object.parentSpanId); - } - object.name = ""; - object.kind = options.enums === String ? "SPAN_KIND_UNSPECIFIED" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.startTimeUnixNano = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.endTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.endTimeUnixNano = options.longs === String ? "0" : 0; - object.droppedAttributesCount = 0; - object.droppedEventsCount = 0; - object.droppedLinksCount = 0; - object.status = null; - object.flags = 0; - } - if (message.traceId != null && message.hasOwnProperty("traceId")) - object.traceId = options.bytes === String ? $util.base64.encode(message.traceId, 0, message.traceId.length) : options.bytes === Array ? Array.prototype.slice.call(message.traceId) : message.traceId; - if (message.spanId != null && message.hasOwnProperty("spanId")) - object.spanId = options.bytes === String ? $util.base64.encode(message.spanId, 0, message.spanId.length) : options.bytes === Array ? Array.prototype.slice.call(message.spanId) : message.spanId; - if (message.traceState != null && message.hasOwnProperty("traceState")) - object.traceState = message.traceState; - if (message.parentSpanId != null && message.hasOwnProperty("parentSpanId")) - object.parentSpanId = options.bytes === String ? $util.base64.encode(message.parentSpanId, 0, message.parentSpanId.length) : options.bytes === Array ? Array.prototype.slice.call(message.parentSpanId) : message.parentSpanId; - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.kind != null && message.hasOwnProperty("kind")) - object.kind = options.enums === String ? $root.opentelemetry.proto.trace.v1.Span.SpanKind[message.kind] === undefined ? message.kind : $root.opentelemetry.proto.trace.v1.Span.SpanKind[message.kind] : message.kind; - if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) - if (typeof message.startTimeUnixNano === "number") - object.startTimeUnixNano = options.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano; - else - object.startTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.startTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.startTimeUnixNano.low >>> 0, message.startTimeUnixNano.high >>> 0).toNumber() : message.startTimeUnixNano; - if (message.endTimeUnixNano != null && message.hasOwnProperty("endTimeUnixNano")) - if (typeof message.endTimeUnixNano === "number") - object.endTimeUnixNano = options.longs === String ? String(message.endTimeUnixNano) : message.endTimeUnixNano; - else - object.endTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.endTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.endTimeUnixNano.low >>> 0, message.endTimeUnixNano.high >>> 0).toNumber() : message.endTimeUnixNano; - if (message.attributes && message.attributes.length) { - object.attributes = []; - for (var j = 0; j < message.attributes.length; ++j) - object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options); - } - if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) - object.droppedAttributesCount = message.droppedAttributesCount; - if (message.events && message.events.length) { - object.events = []; - for (var j = 0; j < message.events.length; ++j) - object.events[j] = $root.opentelemetry.proto.trace.v1.Span.Event.toObject(message.events[j], options); - } - if (message.droppedEventsCount != null && message.hasOwnProperty("droppedEventsCount")) - object.droppedEventsCount = message.droppedEventsCount; - if (message.links && message.links.length) { - object.links = []; - for (var j = 0; j < message.links.length; ++j) - object.links[j] = $root.opentelemetry.proto.trace.v1.Span.Link.toObject(message.links[j], options); - } - if (message.droppedLinksCount != null && message.hasOwnProperty("droppedLinksCount")) - object.droppedLinksCount = message.droppedLinksCount; - if (message.status != null && message.hasOwnProperty("status")) - object.status = $root.opentelemetry.proto.trace.v1.Status.toObject(message.status, options); - if (message.flags != null && message.hasOwnProperty("flags")) - object.flags = message.flags; - return object; - }; - /** - * Converts this Span to JSON. - * @function toJSON - * @memberof opentelemetry.proto.trace.v1.Span - * @instance - * @returns {Object.} JSON object - */ - Span.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for Span - * @function getTypeUrl - * @memberof opentelemetry.proto.trace.v1.Span - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Span.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.trace.v1.Span"; - }; - /** - * SpanKind enum. - * @name opentelemetry.proto.trace.v1.Span.SpanKind - * @enum {number} - * @property {number} SPAN_KIND_UNSPECIFIED=0 SPAN_KIND_UNSPECIFIED value - * @property {number} SPAN_KIND_INTERNAL=1 SPAN_KIND_INTERNAL value - * @property {number} SPAN_KIND_SERVER=2 SPAN_KIND_SERVER value - * @property {number} SPAN_KIND_CLIENT=3 SPAN_KIND_CLIENT value - * @property {number} SPAN_KIND_PRODUCER=4 SPAN_KIND_PRODUCER value - * @property {number} SPAN_KIND_CONSUMER=5 SPAN_KIND_CONSUMER value - */ - Span.SpanKind = (function () { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "SPAN_KIND_UNSPECIFIED"] = 0; - values[valuesById[1] = "SPAN_KIND_INTERNAL"] = 1; - values[valuesById[2] = "SPAN_KIND_SERVER"] = 2; - values[valuesById[3] = "SPAN_KIND_CLIENT"] = 3; - values[valuesById[4] = "SPAN_KIND_PRODUCER"] = 4; - values[valuesById[5] = "SPAN_KIND_CONSUMER"] = 5; - return values; - })(); - Span.Event = (function () { - /** - * Properties of an Event. - * @memberof opentelemetry.proto.trace.v1.Span - * @interface IEvent - * @property {number|Long|null} [timeUnixNano] Event timeUnixNano - * @property {string|null} [name] Event name - * @property {Array.|null} [attributes] Event attributes - * @property {number|null} [droppedAttributesCount] Event droppedAttributesCount - */ - /** - * Constructs a new Event. - * @memberof opentelemetry.proto.trace.v1.Span - * @classdesc Represents an Event. - * @implements IEvent - * @constructor - * @param {opentelemetry.proto.trace.v1.Span.IEvent=} [properties] Properties to set - */ - function Event(properties) { - this.attributes = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * Event timeUnixNano. - * @member {number|Long|null|undefined} timeUnixNano - * @memberof opentelemetry.proto.trace.v1.Span.Event - * @instance - */ - Event.prototype.timeUnixNano = null; - /** - * Event name. - * @member {string|null|undefined} name - * @memberof opentelemetry.proto.trace.v1.Span.Event - * @instance - */ - Event.prototype.name = null; - /** - * Event attributes. - * @member {Array.} attributes - * @memberof opentelemetry.proto.trace.v1.Span.Event - * @instance - */ - Event.prototype.attributes = $util.emptyArray; - /** - * Event droppedAttributesCount. - * @member {number|null|undefined} droppedAttributesCount - * @memberof opentelemetry.proto.trace.v1.Span.Event - * @instance - */ - Event.prototype.droppedAttributesCount = null; - /** - * Creates a new Event instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.trace.v1.Span.Event - * @static - * @param {opentelemetry.proto.trace.v1.Span.IEvent=} [properties] Properties to set - * @returns {opentelemetry.proto.trace.v1.Span.Event} Event instance - */ - Event.create = function create(properties) { - return new Event(properties); - }; - /** - * Encodes the specified Event message. Does not implicitly {@link opentelemetry.proto.trace.v1.Span.Event.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.trace.v1.Span.Event - * @static - * @param {opentelemetry.proto.trace.v1.Span.IEvent} message Event message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Event.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano")) - writer.uint32(/* id 1, wireType 1 =*/ 9).fixed64(message.timeUnixNano); - if (message.name != null && Object.hasOwnProperty.call(message, "name")) - writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.name); - if (message.attributes != null && message.attributes.length) - for (var i = 0; i < message.attributes.length; ++i) - $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(/* id 3, wireType 2 =*/ 26).fork()).ldelim(); - if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount")) - writer.uint32(/* id 4, wireType 0 =*/ 32).uint32(message.droppedAttributesCount); - return writer; - }; - /** - * Encodes the specified Event message, length delimited. Does not implicitly {@link opentelemetry.proto.trace.v1.Span.Event.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.trace.v1.Span.Event - * @static - * @param {opentelemetry.proto.trace.v1.Span.IEvent} message Event message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Event.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes an Event message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.trace.v1.Span.Event - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.trace.v1.Span.Event} Event - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Event.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.Span.Event(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.timeUnixNano = reader.fixed64(); - break; - } - case 2: { - message.name = reader.string(); - break; - } - case 3: { - if (!(message.attributes && message.attributes.length)) - message.attributes = []; - message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); - break; - } - case 4: { - message.droppedAttributesCount = reader.uint32(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes an Event message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.trace.v1.Span.Event - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.trace.v1.Span.Event} Event - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Event.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies an Event message. - * @function verify - * @memberof opentelemetry.proto.trace.v1.Span.Event - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Event.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) - if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high))) - return "timeUnixNano: integer|Long expected"; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isString(message.name)) - return "name: string expected"; - if (message.attributes != null && message.hasOwnProperty("attributes")) { - if (!Array.isArray(message.attributes)) - return "attributes: array expected"; - for (var i = 0; i < message.attributes.length; ++i) { - var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]); - if (error) - return "attributes." + error; - } - } - if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) - if (!$util.isInteger(message.droppedAttributesCount)) - return "droppedAttributesCount: integer expected"; - return null; - }; - /** - * Creates an Event message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.trace.v1.Span.Event - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.trace.v1.Span.Event} Event - */ - Event.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.trace.v1.Span.Event) - return object; - var message = new $root.opentelemetry.proto.trace.v1.Span.Event(); - if (object.timeUnixNano != null) - if ($util.Long) - (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false; - else if (typeof object.timeUnixNano === "string") - message.timeUnixNano = parseInt(object.timeUnixNano, 10); - else if (typeof object.timeUnixNano === "number") - message.timeUnixNano = object.timeUnixNano; - else if (typeof object.timeUnixNano === "object") - message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber(); - if (object.name != null) - message.name = String(object.name); - if (object.attributes) { - if (!Array.isArray(object.attributes)) - throw TypeError(".opentelemetry.proto.trace.v1.Span.Event.attributes: array expected"); - message.attributes = []; - for (var i = 0; i < object.attributes.length; ++i) { - if (typeof object.attributes[i] !== "object") - throw TypeError(".opentelemetry.proto.trace.v1.Span.Event.attributes: object expected"); - message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]); - } - } - if (object.droppedAttributesCount != null) - message.droppedAttributesCount = object.droppedAttributesCount >>> 0; - return message; - }; - /** - * Creates a plain object from an Event message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.trace.v1.Span.Event - * @static - * @param {opentelemetry.proto.trace.v1.Span.Event} message Event - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Event.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.attributes = []; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.timeUnixNano = options.longs === String ? "0" : 0; - object.name = ""; - object.droppedAttributesCount = 0; - } - if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) - if (typeof message.timeUnixNano === "number") - object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano; - else - object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano; - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.attributes && message.attributes.length) { - object.attributes = []; - for (var j = 0; j < message.attributes.length; ++j) - object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options); - } - if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) - object.droppedAttributesCount = message.droppedAttributesCount; - return object; - }; - /** - * Converts this Event to JSON. - * @function toJSON - * @memberof opentelemetry.proto.trace.v1.Span.Event - * @instance - * @returns {Object.} JSON object - */ - Event.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for Event - * @function getTypeUrl - * @memberof opentelemetry.proto.trace.v1.Span.Event - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Event.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.trace.v1.Span.Event"; - }; - return Event; - })(); - Span.Link = (function () { - /** - * Properties of a Link. - * @memberof opentelemetry.proto.trace.v1.Span - * @interface ILink - * @property {Uint8Array|null} [traceId] Link traceId - * @property {Uint8Array|null} [spanId] Link spanId - * @property {string|null} [traceState] Link traceState - * @property {Array.|null} [attributes] Link attributes - * @property {number|null} [droppedAttributesCount] Link droppedAttributesCount - * @property {number|null} [flags] Link flags - */ - /** - * Constructs a new Link. - * @memberof opentelemetry.proto.trace.v1.Span - * @classdesc Represents a Link. - * @implements ILink - * @constructor - * @param {opentelemetry.proto.trace.v1.Span.ILink=} [properties] Properties to set - */ - function Link(properties) { - this.attributes = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * Link traceId. - * @member {Uint8Array|null|undefined} traceId - * @memberof opentelemetry.proto.trace.v1.Span.Link - * @instance - */ - Link.prototype.traceId = null; - /** - * Link spanId. - * @member {Uint8Array|null|undefined} spanId - * @memberof opentelemetry.proto.trace.v1.Span.Link - * @instance - */ - Link.prototype.spanId = null; - /** - * Link traceState. - * @member {string|null|undefined} traceState - * @memberof opentelemetry.proto.trace.v1.Span.Link - * @instance - */ - Link.prototype.traceState = null; - /** - * Link attributes. - * @member {Array.} attributes - * @memberof opentelemetry.proto.trace.v1.Span.Link - * @instance - */ - Link.prototype.attributes = $util.emptyArray; - /** - * Link droppedAttributesCount. - * @member {number|null|undefined} droppedAttributesCount - * @memberof opentelemetry.proto.trace.v1.Span.Link - * @instance - */ - Link.prototype.droppedAttributesCount = null; - /** - * Link flags. - * @member {number|null|undefined} flags - * @memberof opentelemetry.proto.trace.v1.Span.Link - * @instance - */ - Link.prototype.flags = null; - /** - * Creates a new Link instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.trace.v1.Span.Link - * @static - * @param {opentelemetry.proto.trace.v1.Span.ILink=} [properties] Properties to set - * @returns {opentelemetry.proto.trace.v1.Span.Link} Link instance - */ - Link.create = function create(properties) { - return new Link(properties); - }; - /** - * Encodes the specified Link message. Does not implicitly {@link opentelemetry.proto.trace.v1.Span.Link.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.trace.v1.Span.Link - * @static - * @param {opentelemetry.proto.trace.v1.Span.ILink} message Link message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Link.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.traceId != null && Object.hasOwnProperty.call(message, "traceId")) - writer.uint32(/* id 1, wireType 2 =*/ 10).bytes(message.traceId); - if (message.spanId != null && Object.hasOwnProperty.call(message, "spanId")) - writer.uint32(/* id 2, wireType 2 =*/ 18).bytes(message.spanId); - if (message.traceState != null && Object.hasOwnProperty.call(message, "traceState")) - writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.traceState); - if (message.attributes != null && message.attributes.length) - for (var i = 0; i < message.attributes.length; ++i) - $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(/* id 4, wireType 2 =*/ 34).fork()).ldelim(); - if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount")) - writer.uint32(/* id 5, wireType 0 =*/ 40).uint32(message.droppedAttributesCount); - if (message.flags != null && Object.hasOwnProperty.call(message, "flags")) - writer.uint32(/* id 6, wireType 5 =*/ 53).fixed32(message.flags); - return writer; - }; - /** - * Encodes the specified Link message, length delimited. Does not implicitly {@link opentelemetry.proto.trace.v1.Span.Link.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.trace.v1.Span.Link - * @static - * @param {opentelemetry.proto.trace.v1.Span.ILink} message Link message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Link.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a Link message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.trace.v1.Span.Link - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.trace.v1.Span.Link} Link - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Link.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.Span.Link(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.traceId = reader.bytes(); - break; - } - case 2: { - message.spanId = reader.bytes(); - break; - } - case 3: { - message.traceState = reader.string(); - break; - } - case 4: { - if (!(message.attributes && message.attributes.length)) - message.attributes = []; - message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); - break; - } - case 5: { - message.droppedAttributesCount = reader.uint32(); - break; - } - case 6: { - message.flags = reader.fixed32(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a Link message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.trace.v1.Span.Link - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.trace.v1.Span.Link} Link - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Link.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a Link message. - * @function verify - * @memberof opentelemetry.proto.trace.v1.Span.Link - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Link.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.traceId != null && message.hasOwnProperty("traceId")) - if (!(message.traceId && typeof message.traceId.length === "number" || $util.isString(message.traceId))) - return "traceId: buffer expected"; - if (message.spanId != null && message.hasOwnProperty("spanId")) - if (!(message.spanId && typeof message.spanId.length === "number" || $util.isString(message.spanId))) - return "spanId: buffer expected"; - if (message.traceState != null && message.hasOwnProperty("traceState")) - if (!$util.isString(message.traceState)) - return "traceState: string expected"; - if (message.attributes != null && message.hasOwnProperty("attributes")) { - if (!Array.isArray(message.attributes)) - return "attributes: array expected"; - for (var i = 0; i < message.attributes.length; ++i) { - var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]); - if (error) - return "attributes." + error; - } - } - if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) - if (!$util.isInteger(message.droppedAttributesCount)) - return "droppedAttributesCount: integer expected"; - if (message.flags != null && message.hasOwnProperty("flags")) - if (!$util.isInteger(message.flags)) - return "flags: integer expected"; - return null; - }; - /** - * Creates a Link message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.trace.v1.Span.Link - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.trace.v1.Span.Link} Link - */ - Link.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.trace.v1.Span.Link) - return object; - var message = new $root.opentelemetry.proto.trace.v1.Span.Link(); - if (object.traceId != null) - if (typeof object.traceId === "string") - $util.base64.decode(object.traceId, message.traceId = $util.newBuffer($util.base64.length(object.traceId)), 0); - else if (object.traceId.length >= 0) - message.traceId = object.traceId; - if (object.spanId != null) - if (typeof object.spanId === "string") - $util.base64.decode(object.spanId, message.spanId = $util.newBuffer($util.base64.length(object.spanId)), 0); - else if (object.spanId.length >= 0) - message.spanId = object.spanId; - if (object.traceState != null) - message.traceState = String(object.traceState); - if (object.attributes) { - if (!Array.isArray(object.attributes)) - throw TypeError(".opentelemetry.proto.trace.v1.Span.Link.attributes: array expected"); - message.attributes = []; - for (var i = 0; i < object.attributes.length; ++i) { - if (typeof object.attributes[i] !== "object") - throw TypeError(".opentelemetry.proto.trace.v1.Span.Link.attributes: object expected"); - message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]); - } - } - if (object.droppedAttributesCount != null) - message.droppedAttributesCount = object.droppedAttributesCount >>> 0; - if (object.flags != null) - message.flags = object.flags >>> 0; - return message; - }; - /** - * Creates a plain object from a Link message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.trace.v1.Span.Link - * @static - * @param {opentelemetry.proto.trace.v1.Span.Link} message Link - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Link.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.attributes = []; - if (options.defaults) { - if (options.bytes === String) - object.traceId = ""; - else { - object.traceId = []; - if (options.bytes !== Array) - object.traceId = $util.newBuffer(object.traceId); - } - if (options.bytes === String) - object.spanId = ""; - else { - object.spanId = []; - if (options.bytes !== Array) - object.spanId = $util.newBuffer(object.spanId); - } - object.traceState = ""; - object.droppedAttributesCount = 0; - object.flags = 0; - } - if (message.traceId != null && message.hasOwnProperty("traceId")) - object.traceId = options.bytes === String ? $util.base64.encode(message.traceId, 0, message.traceId.length) : options.bytes === Array ? Array.prototype.slice.call(message.traceId) : message.traceId; - if (message.spanId != null && message.hasOwnProperty("spanId")) - object.spanId = options.bytes === String ? $util.base64.encode(message.spanId, 0, message.spanId.length) : options.bytes === Array ? Array.prototype.slice.call(message.spanId) : message.spanId; - if (message.traceState != null && message.hasOwnProperty("traceState")) - object.traceState = message.traceState; - if (message.attributes && message.attributes.length) { - object.attributes = []; - for (var j = 0; j < message.attributes.length; ++j) - object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options); - } - if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) - object.droppedAttributesCount = message.droppedAttributesCount; - if (message.flags != null && message.hasOwnProperty("flags")) - object.flags = message.flags; - return object; - }; - /** - * Converts this Link to JSON. - * @function toJSON - * @memberof opentelemetry.proto.trace.v1.Span.Link - * @instance - * @returns {Object.} JSON object - */ - Link.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for Link - * @function getTypeUrl - * @memberof opentelemetry.proto.trace.v1.Span.Link - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Link.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.trace.v1.Span.Link"; - }; - return Link; - })(); - return Span; - })(); - v1.Status = (function () { - /** - * Properties of a Status. - * @memberof opentelemetry.proto.trace.v1 - * @interface IStatus - * @property {string|null} [message] Status message - * @property {opentelemetry.proto.trace.v1.Status.StatusCode|null} [code] Status code - */ - /** - * Constructs a new Status. - * @memberof opentelemetry.proto.trace.v1 - * @classdesc Represents a Status. - * @implements IStatus - * @constructor - * @param {opentelemetry.proto.trace.v1.IStatus=} [properties] Properties to set - */ - function Status(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * Status message. - * @member {string|null|undefined} message - * @memberof opentelemetry.proto.trace.v1.Status - * @instance - */ - Status.prototype.message = null; - /** - * Status code. - * @member {opentelemetry.proto.trace.v1.Status.StatusCode|null|undefined} code - * @memberof opentelemetry.proto.trace.v1.Status - * @instance - */ - Status.prototype.code = null; - /** - * Creates a new Status instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.trace.v1.Status - * @static - * @param {opentelemetry.proto.trace.v1.IStatus=} [properties] Properties to set - * @returns {opentelemetry.proto.trace.v1.Status} Status instance - */ - Status.create = function create(properties) { - return new Status(properties); - }; - /** - * Encodes the specified Status message. Does not implicitly {@link opentelemetry.proto.trace.v1.Status.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.trace.v1.Status - * @static - * @param {opentelemetry.proto.trace.v1.IStatus} message Status message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Status.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.message != null && Object.hasOwnProperty.call(message, "message")) - writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.message); - if (message.code != null && Object.hasOwnProperty.call(message, "code")) - writer.uint32(/* id 3, wireType 0 =*/ 24).int32(message.code); - return writer; - }; - /** - * Encodes the specified Status message, length delimited. Does not implicitly {@link opentelemetry.proto.trace.v1.Status.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.trace.v1.Status - * @static - * @param {opentelemetry.proto.trace.v1.IStatus} message Status message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Status.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a Status message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.trace.v1.Status - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.trace.v1.Status} Status - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Status.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.trace.v1.Status(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 2: { - message.message = reader.string(); - break; - } - case 3: { - message.code = reader.int32(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a Status message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.trace.v1.Status - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.trace.v1.Status} Status - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Status.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a Status message. - * @function verify - * @memberof opentelemetry.proto.trace.v1.Status - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Status.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.message != null && message.hasOwnProperty("message")) - if (!$util.isString(message.message)) - return "message: string expected"; - if (message.code != null && message.hasOwnProperty("code")) - switch (message.code) { - default: - return "code: enum value expected"; - case 0: - case 1: - case 2: - break; - } - return null; - }; - /** - * Creates a Status message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.trace.v1.Status - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.trace.v1.Status} Status - */ - Status.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.trace.v1.Status) - return object; - var message = new $root.opentelemetry.proto.trace.v1.Status(); - if (object.message != null) - message.message = String(object.message); - switch (object.code) { - default: - if (typeof object.code === "number") { - message.code = object.code; - break; - } - break; - case "STATUS_CODE_UNSET": - case 0: - message.code = 0; - break; - case "STATUS_CODE_OK": - case 1: - message.code = 1; - break; - case "STATUS_CODE_ERROR": - case 2: - message.code = 2; - break; - } - return message; - }; - /** - * Creates a plain object from a Status message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.trace.v1.Status - * @static - * @param {opentelemetry.proto.trace.v1.Status} message Status - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Status.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.message = ""; - object.code = options.enums === String ? "STATUS_CODE_UNSET" : 0; - } - if (message.message != null && message.hasOwnProperty("message")) - object.message = message.message; - if (message.code != null && message.hasOwnProperty("code")) - object.code = options.enums === String ? $root.opentelemetry.proto.trace.v1.Status.StatusCode[message.code] === undefined ? message.code : $root.opentelemetry.proto.trace.v1.Status.StatusCode[message.code] : message.code; - return object; - }; - /** - * Converts this Status to JSON. - * @function toJSON - * @memberof opentelemetry.proto.trace.v1.Status - * @instance - * @returns {Object.} JSON object - */ - Status.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for Status - * @function getTypeUrl - * @memberof opentelemetry.proto.trace.v1.Status - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Status.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.trace.v1.Status"; - }; - /** - * StatusCode enum. - * @name opentelemetry.proto.trace.v1.Status.StatusCode - * @enum {number} - * @property {number} STATUS_CODE_UNSET=0 STATUS_CODE_UNSET value - * @property {number} STATUS_CODE_OK=1 STATUS_CODE_OK value - * @property {number} STATUS_CODE_ERROR=2 STATUS_CODE_ERROR value - */ - Status.StatusCode = (function () { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "STATUS_CODE_UNSET"] = 0; - values[valuesById[1] = "STATUS_CODE_OK"] = 1; - values[valuesById[2] = "STATUS_CODE_ERROR"] = 2; - return values; - })(); - return Status; - })(); - /** - * SpanFlags enum. - * @name opentelemetry.proto.trace.v1.SpanFlags - * @enum {number} - * @property {number} SPAN_FLAGS_DO_NOT_USE=0 SPAN_FLAGS_DO_NOT_USE value - * @property {number} SPAN_FLAGS_TRACE_FLAGS_MASK=255 SPAN_FLAGS_TRACE_FLAGS_MASK value - * @property {number} SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK=256 SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK value - * @property {number} SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK=512 SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK value - */ - v1.SpanFlags = (function () { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "SPAN_FLAGS_DO_NOT_USE"] = 0; - values[valuesById[255] = "SPAN_FLAGS_TRACE_FLAGS_MASK"] = 255; - values[valuesById[256] = "SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK"] = 256; - values[valuesById[512] = "SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK"] = 512; - return values; - })(); - return v1; - })(); - return trace; - })(); - proto.collector = (function () { - /** - * Namespace collector. - * @memberof opentelemetry.proto - * @namespace - */ - var collector = {}; - collector.trace = (function () { - /** - * Namespace trace. - * @memberof opentelemetry.proto.collector - * @namespace - */ - var trace = {}; - trace.v1 = (function () { - /** - * Namespace v1. - * @memberof opentelemetry.proto.collector.trace - * @namespace - */ - var v1 = {}; - v1.TraceService = (function () { - /** - * Constructs a new TraceService service. - * @memberof opentelemetry.proto.collector.trace.v1 - * @classdesc Represents a TraceService - * @extends $protobuf.rpc.Service - * @constructor - * @param {$protobuf.RPCImpl} rpcImpl RPC implementation - * @param {boolean} [requestDelimited=false] Whether requests are length-delimited - * @param {boolean} [responseDelimited=false] Whether responses are length-delimited - */ - function TraceService(rpcImpl, requestDelimited, responseDelimited) { - $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); - } - (TraceService.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = TraceService; - /** - * Creates new TraceService service using the specified rpc implementation. - * @function create - * @memberof opentelemetry.proto.collector.trace.v1.TraceService - * @static - * @param {$protobuf.RPCImpl} rpcImpl RPC implementation - * @param {boolean} [requestDelimited=false] Whether requests are length-delimited - * @param {boolean} [responseDelimited=false] Whether responses are length-delimited - * @returns {TraceService} RPC service. Useful where requests and/or responses are streamed. - */ - TraceService.create = function create(rpcImpl, requestDelimited, responseDelimited) { - return new this(rpcImpl, requestDelimited, responseDelimited); - }; - /** - * Callback as used by {@link opentelemetry.proto.collector.trace.v1.TraceService#export_}. - * @memberof opentelemetry.proto.collector.trace.v1.TraceService - * @typedef ExportCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse} [response] ExportTraceServiceResponse - */ - /** - * Calls Export. - * @function export - * @memberof opentelemetry.proto.collector.trace.v1.TraceService - * @instance - * @param {opentelemetry.proto.collector.trace.v1.IExportTraceServiceRequest} request ExportTraceServiceRequest message or plain object - * @param {opentelemetry.proto.collector.trace.v1.TraceService.ExportCallback} callback Node-style callback called with the error, if any, and ExportTraceServiceResponse - * @returns {undefined} - * @variation 1 - */ - Object.defineProperty(TraceService.prototype["export"] = function export_(request, callback) { - return this.rpcCall(export_, $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest, $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse, request, callback); - }, "name", { value: "Export" }); - /** - * Calls Export. - * @function export - * @memberof opentelemetry.proto.collector.trace.v1.TraceService - * @instance - * @param {opentelemetry.proto.collector.trace.v1.IExportTraceServiceRequest} request ExportTraceServiceRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ - return TraceService; - })(); - v1.ExportTraceServiceRequest = (function () { - /** - * Properties of an ExportTraceServiceRequest. - * @memberof opentelemetry.proto.collector.trace.v1 - * @interface IExportTraceServiceRequest - * @property {Array.|null} [resourceSpans] ExportTraceServiceRequest resourceSpans - */ - /** - * Constructs a new ExportTraceServiceRequest. - * @memberof opentelemetry.proto.collector.trace.v1 - * @classdesc Represents an ExportTraceServiceRequest. - * @implements IExportTraceServiceRequest - * @constructor - * @param {opentelemetry.proto.collector.trace.v1.IExportTraceServiceRequest=} [properties] Properties to set - */ - function ExportTraceServiceRequest(properties) { - this.resourceSpans = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * ExportTraceServiceRequest resourceSpans. - * @member {Array.} resourceSpans - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest - * @instance - */ - ExportTraceServiceRequest.prototype.resourceSpans = $util.emptyArray; - /** - * Creates a new ExportTraceServiceRequest instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest - * @static - * @param {opentelemetry.proto.collector.trace.v1.IExportTraceServiceRequest=} [properties] Properties to set - * @returns {opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest} ExportTraceServiceRequest instance - */ - ExportTraceServiceRequest.create = function create(properties) { - return new ExportTraceServiceRequest(properties); - }; - /** - * Encodes the specified ExportTraceServiceRequest message. Does not implicitly {@link opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest - * @static - * @param {opentelemetry.proto.collector.trace.v1.IExportTraceServiceRequest} message ExportTraceServiceRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExportTraceServiceRequest.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.resourceSpans != null && message.resourceSpans.length) - for (var i = 0; i < message.resourceSpans.length; ++i) - $root.opentelemetry.proto.trace.v1.ResourceSpans.encode(message.resourceSpans[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - return writer; - }; - /** - * Encodes the specified ExportTraceServiceRequest message, length delimited. Does not implicitly {@link opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest - * @static - * @param {opentelemetry.proto.collector.trace.v1.IExportTraceServiceRequest} message ExportTraceServiceRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExportTraceServiceRequest.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes an ExportTraceServiceRequest message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest} ExportTraceServiceRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExportTraceServiceRequest.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - if (!(message.resourceSpans && message.resourceSpans.length)) - message.resourceSpans = []; - message.resourceSpans.push($root.opentelemetry.proto.trace.v1.ResourceSpans.decode(reader, reader.uint32())); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes an ExportTraceServiceRequest message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest} ExportTraceServiceRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExportTraceServiceRequest.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies an ExportTraceServiceRequest message. - * @function verify - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ExportTraceServiceRequest.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.resourceSpans != null && message.hasOwnProperty("resourceSpans")) { - if (!Array.isArray(message.resourceSpans)) - return "resourceSpans: array expected"; - for (var i = 0; i < message.resourceSpans.length; ++i) { - var error = $root.opentelemetry.proto.trace.v1.ResourceSpans.verify(message.resourceSpans[i]); - if (error) - return "resourceSpans." + error; - } - } - return null; - }; - /** - * Creates an ExportTraceServiceRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest} ExportTraceServiceRequest - */ - ExportTraceServiceRequest.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest) - return object; - var message = new $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest(); - if (object.resourceSpans) { - if (!Array.isArray(object.resourceSpans)) - throw TypeError(".opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.resourceSpans: array expected"); - message.resourceSpans = []; - for (var i = 0; i < object.resourceSpans.length; ++i) { - if (typeof object.resourceSpans[i] !== "object") - throw TypeError(".opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest.resourceSpans: object expected"); - message.resourceSpans[i] = $root.opentelemetry.proto.trace.v1.ResourceSpans.fromObject(object.resourceSpans[i]); - } - } - return message; - }; - /** - * Creates a plain object from an ExportTraceServiceRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest - * @static - * @param {opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest} message ExportTraceServiceRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExportTraceServiceRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.resourceSpans = []; - if (message.resourceSpans && message.resourceSpans.length) { - object.resourceSpans = []; - for (var j = 0; j < message.resourceSpans.length; ++j) - object.resourceSpans[j] = $root.opentelemetry.proto.trace.v1.ResourceSpans.toObject(message.resourceSpans[j], options); - } - return object; - }; - /** - * Converts this ExportTraceServiceRequest to JSON. - * @function toJSON - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest - * @instance - * @returns {Object.} JSON object - */ - ExportTraceServiceRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for ExportTraceServiceRequest - * @function getTypeUrl - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ExportTraceServiceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.collector.trace.v1.ExportTraceServiceRequest"; - }; - return ExportTraceServiceRequest; - })(); - v1.ExportTraceServiceResponse = (function () { - /** - * Properties of an ExportTraceServiceResponse. - * @memberof opentelemetry.proto.collector.trace.v1 - * @interface IExportTraceServiceResponse - * @property {opentelemetry.proto.collector.trace.v1.IExportTracePartialSuccess|null} [partialSuccess] ExportTraceServiceResponse partialSuccess - */ - /** - * Constructs a new ExportTraceServiceResponse. - * @memberof opentelemetry.proto.collector.trace.v1 - * @classdesc Represents an ExportTraceServiceResponse. - * @implements IExportTraceServiceResponse - * @constructor - * @param {opentelemetry.proto.collector.trace.v1.IExportTraceServiceResponse=} [properties] Properties to set - */ - function ExportTraceServiceResponse(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * ExportTraceServiceResponse partialSuccess. - * @member {opentelemetry.proto.collector.trace.v1.IExportTracePartialSuccess|null|undefined} partialSuccess - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse - * @instance - */ - ExportTraceServiceResponse.prototype.partialSuccess = null; - /** - * Creates a new ExportTraceServiceResponse instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse - * @static - * @param {opentelemetry.proto.collector.trace.v1.IExportTraceServiceResponse=} [properties] Properties to set - * @returns {opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse} ExportTraceServiceResponse instance - */ - ExportTraceServiceResponse.create = function create(properties) { - return new ExportTraceServiceResponse(properties); - }; - /** - * Encodes the specified ExportTraceServiceResponse message. Does not implicitly {@link opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse - * @static - * @param {opentelemetry.proto.collector.trace.v1.IExportTraceServiceResponse} message ExportTraceServiceResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExportTraceServiceResponse.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.partialSuccess != null && Object.hasOwnProperty.call(message, "partialSuccess")) - $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.encode(message.partialSuccess, writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - return writer; - }; - /** - * Encodes the specified ExportTraceServiceResponse message, length delimited. Does not implicitly {@link opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse - * @static - * @param {opentelemetry.proto.collector.trace.v1.IExportTraceServiceResponse} message ExportTraceServiceResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExportTraceServiceResponse.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes an ExportTraceServiceResponse message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse} ExportTraceServiceResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExportTraceServiceResponse.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.partialSuccess = $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.decode(reader, reader.uint32()); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes an ExportTraceServiceResponse message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse} ExportTraceServiceResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExportTraceServiceResponse.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies an ExportTraceServiceResponse message. - * @function verify - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ExportTraceServiceResponse.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess")) { - var error = $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.verify(message.partialSuccess); - if (error) - return "partialSuccess." + error; - } - return null; - }; - /** - * Creates an ExportTraceServiceResponse message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse} ExportTraceServiceResponse - */ - ExportTraceServiceResponse.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse) - return object; - var message = new $root.opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse(); - if (object.partialSuccess != null) { - if (typeof object.partialSuccess !== "object") - throw TypeError(".opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse.partialSuccess: object expected"); - message.partialSuccess = $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.fromObject(object.partialSuccess); - } - return message; - }; - /** - * Creates a plain object from an ExportTraceServiceResponse message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse - * @static - * @param {opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse} message ExportTraceServiceResponse - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExportTraceServiceResponse.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.partialSuccess = null; - if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess")) - object.partialSuccess = $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.toObject(message.partialSuccess, options); - return object; - }; - /** - * Converts this ExportTraceServiceResponse to JSON. - * @function toJSON - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse - * @instance - * @returns {Object.} JSON object - */ - ExportTraceServiceResponse.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for ExportTraceServiceResponse - * @function getTypeUrl - * @memberof opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ExportTraceServiceResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.collector.trace.v1.ExportTraceServiceResponse"; - }; - return ExportTraceServiceResponse; - })(); - v1.ExportTracePartialSuccess = (function () { - /** - * Properties of an ExportTracePartialSuccess. - * @memberof opentelemetry.proto.collector.trace.v1 - * @interface IExportTracePartialSuccess - * @property {number|Long|null} [rejectedSpans] ExportTracePartialSuccess rejectedSpans - * @property {string|null} [errorMessage] ExportTracePartialSuccess errorMessage - */ - /** - * Constructs a new ExportTracePartialSuccess. - * @memberof opentelemetry.proto.collector.trace.v1 - * @classdesc Represents an ExportTracePartialSuccess. - * @implements IExportTracePartialSuccess - * @constructor - * @param {opentelemetry.proto.collector.trace.v1.IExportTracePartialSuccess=} [properties] Properties to set - */ - function ExportTracePartialSuccess(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * ExportTracePartialSuccess rejectedSpans. - * @member {number|Long|null|undefined} rejectedSpans - * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess - * @instance - */ - ExportTracePartialSuccess.prototype.rejectedSpans = null; - /** - * ExportTracePartialSuccess errorMessage. - * @member {string|null|undefined} errorMessage - * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess - * @instance - */ - ExportTracePartialSuccess.prototype.errorMessage = null; - /** - * Creates a new ExportTracePartialSuccess instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess - * @static - * @param {opentelemetry.proto.collector.trace.v1.IExportTracePartialSuccess=} [properties] Properties to set - * @returns {opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess} ExportTracePartialSuccess instance - */ - ExportTracePartialSuccess.create = function create(properties) { - return new ExportTracePartialSuccess(properties); - }; - /** - * Encodes the specified ExportTracePartialSuccess message. Does not implicitly {@link opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess - * @static - * @param {opentelemetry.proto.collector.trace.v1.IExportTracePartialSuccess} message ExportTracePartialSuccess message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExportTracePartialSuccess.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.rejectedSpans != null && Object.hasOwnProperty.call(message, "rejectedSpans")) - writer.uint32(/* id 1, wireType 0 =*/ 8).int64(message.rejectedSpans); - if (message.errorMessage != null && Object.hasOwnProperty.call(message, "errorMessage")) - writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.errorMessage); - return writer; - }; - /** - * Encodes the specified ExportTracePartialSuccess message, length delimited. Does not implicitly {@link opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess - * @static - * @param {opentelemetry.proto.collector.trace.v1.IExportTracePartialSuccess} message ExportTracePartialSuccess message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExportTracePartialSuccess.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes an ExportTracePartialSuccess message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess} ExportTracePartialSuccess - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExportTracePartialSuccess.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.rejectedSpans = reader.int64(); - break; - } - case 2: { - message.errorMessage = reader.string(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes an ExportTracePartialSuccess message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess} ExportTracePartialSuccess - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExportTracePartialSuccess.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies an ExportTracePartialSuccess message. - * @function verify - * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ExportTracePartialSuccess.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.rejectedSpans != null && message.hasOwnProperty("rejectedSpans")) - if (!$util.isInteger(message.rejectedSpans) && !(message.rejectedSpans && $util.isInteger(message.rejectedSpans.low) && $util.isInteger(message.rejectedSpans.high))) - return "rejectedSpans: integer|Long expected"; - if (message.errorMessage != null && message.hasOwnProperty("errorMessage")) - if (!$util.isString(message.errorMessage)) - return "errorMessage: string expected"; - return null; - }; - /** - * Creates an ExportTracePartialSuccess message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess} ExportTracePartialSuccess - */ - ExportTracePartialSuccess.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess) - return object; - var message = new $root.opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess(); - if (object.rejectedSpans != null) - if ($util.Long) - (message.rejectedSpans = $util.Long.fromValue(object.rejectedSpans)).unsigned = false; - else if (typeof object.rejectedSpans === "string") - message.rejectedSpans = parseInt(object.rejectedSpans, 10); - else if (typeof object.rejectedSpans === "number") - message.rejectedSpans = object.rejectedSpans; - else if (typeof object.rejectedSpans === "object") - message.rejectedSpans = new $util.LongBits(object.rejectedSpans.low >>> 0, object.rejectedSpans.high >>> 0).toNumber(); - if (object.errorMessage != null) - message.errorMessage = String(object.errorMessage); - return message; - }; - /** - * Creates a plain object from an ExportTracePartialSuccess message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess - * @static - * @param {opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess} message ExportTracePartialSuccess - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExportTracePartialSuccess.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.rejectedSpans = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.rejectedSpans = options.longs === String ? "0" : 0; - object.errorMessage = ""; - } - if (message.rejectedSpans != null && message.hasOwnProperty("rejectedSpans")) - if (typeof message.rejectedSpans === "number") - object.rejectedSpans = options.longs === String ? String(message.rejectedSpans) : message.rejectedSpans; - else - object.rejectedSpans = options.longs === String ? $util.Long.prototype.toString.call(message.rejectedSpans) : options.longs === Number ? new $util.LongBits(message.rejectedSpans.low >>> 0, message.rejectedSpans.high >>> 0).toNumber() : message.rejectedSpans; - if (message.errorMessage != null && message.hasOwnProperty("errorMessage")) - object.errorMessage = message.errorMessage; - return object; - }; - /** - * Converts this ExportTracePartialSuccess to JSON. - * @function toJSON - * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess - * @instance - * @returns {Object.} JSON object - */ - ExportTracePartialSuccess.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for ExportTracePartialSuccess - * @function getTypeUrl - * @memberof opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ExportTracePartialSuccess.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.collector.trace.v1.ExportTracePartialSuccess"; - }; - return ExportTracePartialSuccess; - })(); - return v1; - })(); - return trace; - })(); - collector.metrics = (function () { - /** - * Namespace metrics. - * @memberof opentelemetry.proto.collector - * @namespace - */ - var metrics = {}; - metrics.v1 = (function () { - /** - * Namespace v1. - * @memberof opentelemetry.proto.collector.metrics - * @namespace - */ - var v1 = {}; - v1.MetricsService = (function () { - /** - * Constructs a new MetricsService service. - * @memberof opentelemetry.proto.collector.metrics.v1 - * @classdesc Represents a MetricsService - * @extends $protobuf.rpc.Service - * @constructor - * @param {$protobuf.RPCImpl} rpcImpl RPC implementation - * @param {boolean} [requestDelimited=false] Whether requests are length-delimited - * @param {boolean} [responseDelimited=false] Whether responses are length-delimited - */ - function MetricsService(rpcImpl, requestDelimited, responseDelimited) { - $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); - } - (MetricsService.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = MetricsService; - /** - * Creates new MetricsService service using the specified rpc implementation. - * @function create - * @memberof opentelemetry.proto.collector.metrics.v1.MetricsService - * @static - * @param {$protobuf.RPCImpl} rpcImpl RPC implementation - * @param {boolean} [requestDelimited=false] Whether requests are length-delimited - * @param {boolean} [responseDelimited=false] Whether responses are length-delimited - * @returns {MetricsService} RPC service. Useful where requests and/or responses are streamed. - */ - MetricsService.create = function create(rpcImpl, requestDelimited, responseDelimited) { - return new this(rpcImpl, requestDelimited, responseDelimited); - }; - /** - * Callback as used by {@link opentelemetry.proto.collector.metrics.v1.MetricsService#export_}. - * @memberof opentelemetry.proto.collector.metrics.v1.MetricsService - * @typedef ExportCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse} [response] ExportMetricsServiceResponse - */ - /** - * Calls Export. - * @function export - * @memberof opentelemetry.proto.collector.metrics.v1.MetricsService - * @instance - * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsServiceRequest} request ExportMetricsServiceRequest message or plain object - * @param {opentelemetry.proto.collector.metrics.v1.MetricsService.ExportCallback} callback Node-style callback called with the error, if any, and ExportMetricsServiceResponse - * @returns {undefined} - * @variation 1 - */ - Object.defineProperty(MetricsService.prototype["export"] = function export_(request, callback) { - return this.rpcCall(export_, $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest, $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse, request, callback); - }, "name", { value: "Export" }); - /** - * Calls Export. - * @function export - * @memberof opentelemetry.proto.collector.metrics.v1.MetricsService - * @instance - * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsServiceRequest} request ExportMetricsServiceRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ - return MetricsService; - })(); - v1.ExportMetricsServiceRequest = (function () { - /** - * Properties of an ExportMetricsServiceRequest. - * @memberof opentelemetry.proto.collector.metrics.v1 - * @interface IExportMetricsServiceRequest - * @property {Array.|null} [resourceMetrics] ExportMetricsServiceRequest resourceMetrics - */ - /** - * Constructs a new ExportMetricsServiceRequest. - * @memberof opentelemetry.proto.collector.metrics.v1 - * @classdesc Represents an ExportMetricsServiceRequest. - * @implements IExportMetricsServiceRequest - * @constructor - * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsServiceRequest=} [properties] Properties to set - */ - function ExportMetricsServiceRequest(properties) { - this.resourceMetrics = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * ExportMetricsServiceRequest resourceMetrics. - * @member {Array.} resourceMetrics - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest - * @instance - */ - ExportMetricsServiceRequest.prototype.resourceMetrics = $util.emptyArray; - /** - * Creates a new ExportMetricsServiceRequest instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest - * @static - * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsServiceRequest=} [properties] Properties to set - * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest} ExportMetricsServiceRequest instance - */ - ExportMetricsServiceRequest.create = function create(properties) { - return new ExportMetricsServiceRequest(properties); - }; - /** - * Encodes the specified ExportMetricsServiceRequest message. Does not implicitly {@link opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest - * @static - * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsServiceRequest} message ExportMetricsServiceRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExportMetricsServiceRequest.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.resourceMetrics != null && message.resourceMetrics.length) - for (var i = 0; i < message.resourceMetrics.length; ++i) - $root.opentelemetry.proto.metrics.v1.ResourceMetrics.encode(message.resourceMetrics[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - return writer; - }; - /** - * Encodes the specified ExportMetricsServiceRequest message, length delimited. Does not implicitly {@link opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest - * @static - * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsServiceRequest} message ExportMetricsServiceRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExportMetricsServiceRequest.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes an ExportMetricsServiceRequest message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest} ExportMetricsServiceRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExportMetricsServiceRequest.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - if (!(message.resourceMetrics && message.resourceMetrics.length)) - message.resourceMetrics = []; - message.resourceMetrics.push($root.opentelemetry.proto.metrics.v1.ResourceMetrics.decode(reader, reader.uint32())); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes an ExportMetricsServiceRequest message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest} ExportMetricsServiceRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExportMetricsServiceRequest.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies an ExportMetricsServiceRequest message. - * @function verify - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ExportMetricsServiceRequest.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.resourceMetrics != null && message.hasOwnProperty("resourceMetrics")) { - if (!Array.isArray(message.resourceMetrics)) - return "resourceMetrics: array expected"; - for (var i = 0; i < message.resourceMetrics.length; ++i) { - var error = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.verify(message.resourceMetrics[i]); - if (error) - return "resourceMetrics." + error; - } - } - return null; - }; - /** - * Creates an ExportMetricsServiceRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest} ExportMetricsServiceRequest - */ - ExportMetricsServiceRequest.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest) - return object; - var message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest(); - if (object.resourceMetrics) { - if (!Array.isArray(object.resourceMetrics)) - throw TypeError(".opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest.resourceMetrics: array expected"); - message.resourceMetrics = []; - for (var i = 0; i < object.resourceMetrics.length; ++i) { - if (typeof object.resourceMetrics[i] !== "object") - throw TypeError(".opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest.resourceMetrics: object expected"); - message.resourceMetrics[i] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.fromObject(object.resourceMetrics[i]); - } - } - return message; - }; - /** - * Creates a plain object from an ExportMetricsServiceRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest - * @static - * @param {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest} message ExportMetricsServiceRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExportMetricsServiceRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.resourceMetrics = []; - if (message.resourceMetrics && message.resourceMetrics.length) { - object.resourceMetrics = []; - for (var j = 0; j < message.resourceMetrics.length; ++j) - object.resourceMetrics[j] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.toObject(message.resourceMetrics[j], options); - } - return object; - }; - /** - * Converts this ExportMetricsServiceRequest to JSON. - * @function toJSON - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest - * @instance - * @returns {Object.} JSON object - */ - ExportMetricsServiceRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for ExportMetricsServiceRequest - * @function getTypeUrl - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ExportMetricsServiceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceRequest"; - }; - return ExportMetricsServiceRequest; - })(); - v1.ExportMetricsServiceResponse = (function () { - /** - * Properties of an ExportMetricsServiceResponse. - * @memberof opentelemetry.proto.collector.metrics.v1 - * @interface IExportMetricsServiceResponse - * @property {opentelemetry.proto.collector.metrics.v1.IExportMetricsPartialSuccess|null} [partialSuccess] ExportMetricsServiceResponse partialSuccess - */ - /** - * Constructs a new ExportMetricsServiceResponse. - * @memberof opentelemetry.proto.collector.metrics.v1 - * @classdesc Represents an ExportMetricsServiceResponse. - * @implements IExportMetricsServiceResponse - * @constructor - * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsServiceResponse=} [properties] Properties to set - */ - function ExportMetricsServiceResponse(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * ExportMetricsServiceResponse partialSuccess. - * @member {opentelemetry.proto.collector.metrics.v1.IExportMetricsPartialSuccess|null|undefined} partialSuccess - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse - * @instance - */ - ExportMetricsServiceResponse.prototype.partialSuccess = null; - /** - * Creates a new ExportMetricsServiceResponse instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse - * @static - * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsServiceResponse=} [properties] Properties to set - * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse} ExportMetricsServiceResponse instance - */ - ExportMetricsServiceResponse.create = function create(properties) { - return new ExportMetricsServiceResponse(properties); - }; - /** - * Encodes the specified ExportMetricsServiceResponse message. Does not implicitly {@link opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse - * @static - * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsServiceResponse} message ExportMetricsServiceResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExportMetricsServiceResponse.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.partialSuccess != null && Object.hasOwnProperty.call(message, "partialSuccess")) - $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.encode(message.partialSuccess, writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - return writer; - }; - /** - * Encodes the specified ExportMetricsServiceResponse message, length delimited. Does not implicitly {@link opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse - * @static - * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsServiceResponse} message ExportMetricsServiceResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExportMetricsServiceResponse.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes an ExportMetricsServiceResponse message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse} ExportMetricsServiceResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExportMetricsServiceResponse.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.partialSuccess = $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.decode(reader, reader.uint32()); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes an ExportMetricsServiceResponse message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse} ExportMetricsServiceResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExportMetricsServiceResponse.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies an ExportMetricsServiceResponse message. - * @function verify - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ExportMetricsServiceResponse.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess")) { - var error = $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.verify(message.partialSuccess); - if (error) - return "partialSuccess." + error; - } - return null; - }; - /** - * Creates an ExportMetricsServiceResponse message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse} ExportMetricsServiceResponse - */ - ExportMetricsServiceResponse.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse) - return object; - var message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse(); - if (object.partialSuccess != null) { - if (typeof object.partialSuccess !== "object") - throw TypeError(".opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse.partialSuccess: object expected"); - message.partialSuccess = $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.fromObject(object.partialSuccess); - } - return message; - }; - /** - * Creates a plain object from an ExportMetricsServiceResponse message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse - * @static - * @param {opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse} message ExportMetricsServiceResponse - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExportMetricsServiceResponse.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.partialSuccess = null; - if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess")) - object.partialSuccess = $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.toObject(message.partialSuccess, options); - return object; - }; - /** - * Converts this ExportMetricsServiceResponse to JSON. - * @function toJSON - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse - * @instance - * @returns {Object.} JSON object - */ - ExportMetricsServiceResponse.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for ExportMetricsServiceResponse - * @function getTypeUrl - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ExportMetricsServiceResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.collector.metrics.v1.ExportMetricsServiceResponse"; - }; - return ExportMetricsServiceResponse; - })(); - v1.ExportMetricsPartialSuccess = (function () { - /** - * Properties of an ExportMetricsPartialSuccess. - * @memberof opentelemetry.proto.collector.metrics.v1 - * @interface IExportMetricsPartialSuccess - * @property {number|Long|null} [rejectedDataPoints] ExportMetricsPartialSuccess rejectedDataPoints - * @property {string|null} [errorMessage] ExportMetricsPartialSuccess errorMessage - */ - /** - * Constructs a new ExportMetricsPartialSuccess. - * @memberof opentelemetry.proto.collector.metrics.v1 - * @classdesc Represents an ExportMetricsPartialSuccess. - * @implements IExportMetricsPartialSuccess - * @constructor - * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsPartialSuccess=} [properties] Properties to set - */ - function ExportMetricsPartialSuccess(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * ExportMetricsPartialSuccess rejectedDataPoints. - * @member {number|Long|null|undefined} rejectedDataPoints - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess - * @instance - */ - ExportMetricsPartialSuccess.prototype.rejectedDataPoints = null; - /** - * ExportMetricsPartialSuccess errorMessage. - * @member {string|null|undefined} errorMessage - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess - * @instance - */ - ExportMetricsPartialSuccess.prototype.errorMessage = null; - /** - * Creates a new ExportMetricsPartialSuccess instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess - * @static - * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsPartialSuccess=} [properties] Properties to set - * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess} ExportMetricsPartialSuccess instance - */ - ExportMetricsPartialSuccess.create = function create(properties) { - return new ExportMetricsPartialSuccess(properties); - }; - /** - * Encodes the specified ExportMetricsPartialSuccess message. Does not implicitly {@link opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess - * @static - * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsPartialSuccess} message ExportMetricsPartialSuccess message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExportMetricsPartialSuccess.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.rejectedDataPoints != null && Object.hasOwnProperty.call(message, "rejectedDataPoints")) - writer.uint32(/* id 1, wireType 0 =*/ 8).int64(message.rejectedDataPoints); - if (message.errorMessage != null && Object.hasOwnProperty.call(message, "errorMessage")) - writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.errorMessage); - return writer; - }; - /** - * Encodes the specified ExportMetricsPartialSuccess message, length delimited. Does not implicitly {@link opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess - * @static - * @param {opentelemetry.proto.collector.metrics.v1.IExportMetricsPartialSuccess} message ExportMetricsPartialSuccess message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExportMetricsPartialSuccess.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes an ExportMetricsPartialSuccess message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess} ExportMetricsPartialSuccess - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExportMetricsPartialSuccess.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.rejectedDataPoints = reader.int64(); - break; - } - case 2: { - message.errorMessage = reader.string(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes an ExportMetricsPartialSuccess message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess} ExportMetricsPartialSuccess - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExportMetricsPartialSuccess.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies an ExportMetricsPartialSuccess message. - * @function verify - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ExportMetricsPartialSuccess.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.rejectedDataPoints != null && message.hasOwnProperty("rejectedDataPoints")) - if (!$util.isInteger(message.rejectedDataPoints) && !(message.rejectedDataPoints && $util.isInteger(message.rejectedDataPoints.low) && $util.isInteger(message.rejectedDataPoints.high))) - return "rejectedDataPoints: integer|Long expected"; - if (message.errorMessage != null && message.hasOwnProperty("errorMessage")) - if (!$util.isString(message.errorMessage)) - return "errorMessage: string expected"; - return null; - }; - /** - * Creates an ExportMetricsPartialSuccess message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess} ExportMetricsPartialSuccess - */ - ExportMetricsPartialSuccess.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess) - return object; - var message = new $root.opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess(); - if (object.rejectedDataPoints != null) - if ($util.Long) - (message.rejectedDataPoints = $util.Long.fromValue(object.rejectedDataPoints)).unsigned = false; - else if (typeof object.rejectedDataPoints === "string") - message.rejectedDataPoints = parseInt(object.rejectedDataPoints, 10); - else if (typeof object.rejectedDataPoints === "number") - message.rejectedDataPoints = object.rejectedDataPoints; - else if (typeof object.rejectedDataPoints === "object") - message.rejectedDataPoints = new $util.LongBits(object.rejectedDataPoints.low >>> 0, object.rejectedDataPoints.high >>> 0).toNumber(); - if (object.errorMessage != null) - message.errorMessage = String(object.errorMessage); - return message; - }; - /** - * Creates a plain object from an ExportMetricsPartialSuccess message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess - * @static - * @param {opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess} message ExportMetricsPartialSuccess - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExportMetricsPartialSuccess.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.rejectedDataPoints = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.rejectedDataPoints = options.longs === String ? "0" : 0; - object.errorMessage = ""; - } - if (message.rejectedDataPoints != null && message.hasOwnProperty("rejectedDataPoints")) - if (typeof message.rejectedDataPoints === "number") - object.rejectedDataPoints = options.longs === String ? String(message.rejectedDataPoints) : message.rejectedDataPoints; - else - object.rejectedDataPoints = options.longs === String ? $util.Long.prototype.toString.call(message.rejectedDataPoints) : options.longs === Number ? new $util.LongBits(message.rejectedDataPoints.low >>> 0, message.rejectedDataPoints.high >>> 0).toNumber() : message.rejectedDataPoints; - if (message.errorMessage != null && message.hasOwnProperty("errorMessage")) - object.errorMessage = message.errorMessage; - return object; - }; - /** - * Converts this ExportMetricsPartialSuccess to JSON. - * @function toJSON - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess - * @instance - * @returns {Object.} JSON object - */ - ExportMetricsPartialSuccess.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for ExportMetricsPartialSuccess - * @function getTypeUrl - * @memberof opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ExportMetricsPartialSuccess.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.collector.metrics.v1.ExportMetricsPartialSuccess"; - }; - return ExportMetricsPartialSuccess; - })(); - return v1; - })(); - return metrics; - })(); - collector.logs = (function () { - /** - * Namespace logs. - * @memberof opentelemetry.proto.collector - * @namespace - */ - var logs = {}; - logs.v1 = (function () { - /** - * Namespace v1. - * @memberof opentelemetry.proto.collector.logs - * @namespace - */ - var v1 = {}; - v1.LogsService = (function () { - /** - * Constructs a new LogsService service. - * @memberof opentelemetry.proto.collector.logs.v1 - * @classdesc Represents a LogsService - * @extends $protobuf.rpc.Service - * @constructor - * @param {$protobuf.RPCImpl} rpcImpl RPC implementation - * @param {boolean} [requestDelimited=false] Whether requests are length-delimited - * @param {boolean} [responseDelimited=false] Whether responses are length-delimited - */ - function LogsService(rpcImpl, requestDelimited, responseDelimited) { - $protobuf.rpc.Service.call(this, rpcImpl, requestDelimited, responseDelimited); - } - (LogsService.prototype = Object.create($protobuf.rpc.Service.prototype)).constructor = LogsService; - /** - * Creates new LogsService service using the specified rpc implementation. - * @function create - * @memberof opentelemetry.proto.collector.logs.v1.LogsService - * @static - * @param {$protobuf.RPCImpl} rpcImpl RPC implementation - * @param {boolean} [requestDelimited=false] Whether requests are length-delimited - * @param {boolean} [responseDelimited=false] Whether responses are length-delimited - * @returns {LogsService} RPC service. Useful where requests and/or responses are streamed. - */ - LogsService.create = function create(rpcImpl, requestDelimited, responseDelimited) { - return new this(rpcImpl, requestDelimited, responseDelimited); - }; - /** - * Callback as used by {@link opentelemetry.proto.collector.logs.v1.LogsService#export_}. - * @memberof opentelemetry.proto.collector.logs.v1.LogsService - * @typedef ExportCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse} [response] ExportLogsServiceResponse - */ - /** - * Calls Export. - * @function export - * @memberof opentelemetry.proto.collector.logs.v1.LogsService - * @instance - * @param {opentelemetry.proto.collector.logs.v1.IExportLogsServiceRequest} request ExportLogsServiceRequest message or plain object - * @param {opentelemetry.proto.collector.logs.v1.LogsService.ExportCallback} callback Node-style callback called with the error, if any, and ExportLogsServiceResponse - * @returns {undefined} - * @variation 1 - */ - Object.defineProperty(LogsService.prototype["export"] = function export_(request, callback) { - return this.rpcCall(export_, $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest, $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse, request, callback); - }, "name", { value: "Export" }); - /** - * Calls Export. - * @function export - * @memberof opentelemetry.proto.collector.logs.v1.LogsService - * @instance - * @param {opentelemetry.proto.collector.logs.v1.IExportLogsServiceRequest} request ExportLogsServiceRequest message or plain object - * @returns {Promise} Promise - * @variation 2 - */ - return LogsService; - })(); - v1.ExportLogsServiceRequest = (function () { - /** - * Properties of an ExportLogsServiceRequest. - * @memberof opentelemetry.proto.collector.logs.v1 - * @interface IExportLogsServiceRequest - * @property {Array.|null} [resourceLogs] ExportLogsServiceRequest resourceLogs - */ - /** - * Constructs a new ExportLogsServiceRequest. - * @memberof opentelemetry.proto.collector.logs.v1 - * @classdesc Represents an ExportLogsServiceRequest. - * @implements IExportLogsServiceRequest - * @constructor - * @param {opentelemetry.proto.collector.logs.v1.IExportLogsServiceRequest=} [properties] Properties to set - */ - function ExportLogsServiceRequest(properties) { - this.resourceLogs = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * ExportLogsServiceRequest resourceLogs. - * @member {Array.} resourceLogs - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest - * @instance - */ - ExportLogsServiceRequest.prototype.resourceLogs = $util.emptyArray; - /** - * Creates a new ExportLogsServiceRequest instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest - * @static - * @param {opentelemetry.proto.collector.logs.v1.IExportLogsServiceRequest=} [properties] Properties to set - * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest} ExportLogsServiceRequest instance - */ - ExportLogsServiceRequest.create = function create(properties) { - return new ExportLogsServiceRequest(properties); - }; - /** - * Encodes the specified ExportLogsServiceRequest message. Does not implicitly {@link opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest - * @static - * @param {opentelemetry.proto.collector.logs.v1.IExportLogsServiceRequest} message ExportLogsServiceRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExportLogsServiceRequest.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.resourceLogs != null && message.resourceLogs.length) - for (var i = 0; i < message.resourceLogs.length; ++i) - $root.opentelemetry.proto.logs.v1.ResourceLogs.encode(message.resourceLogs[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - return writer; - }; - /** - * Encodes the specified ExportLogsServiceRequest message, length delimited. Does not implicitly {@link opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest - * @static - * @param {opentelemetry.proto.collector.logs.v1.IExportLogsServiceRequest} message ExportLogsServiceRequest message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExportLogsServiceRequest.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes an ExportLogsServiceRequest message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest} ExportLogsServiceRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExportLogsServiceRequest.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - if (!(message.resourceLogs && message.resourceLogs.length)) - message.resourceLogs = []; - message.resourceLogs.push($root.opentelemetry.proto.logs.v1.ResourceLogs.decode(reader, reader.uint32())); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes an ExportLogsServiceRequest message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest} ExportLogsServiceRequest - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExportLogsServiceRequest.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies an ExportLogsServiceRequest message. - * @function verify - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ExportLogsServiceRequest.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.resourceLogs != null && message.hasOwnProperty("resourceLogs")) { - if (!Array.isArray(message.resourceLogs)) - return "resourceLogs: array expected"; - for (var i = 0; i < message.resourceLogs.length; ++i) { - var error = $root.opentelemetry.proto.logs.v1.ResourceLogs.verify(message.resourceLogs[i]); - if (error) - return "resourceLogs." + error; - } - } - return null; - }; - /** - * Creates an ExportLogsServiceRequest message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest} ExportLogsServiceRequest - */ - ExportLogsServiceRequest.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest) - return object; - var message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest(); - if (object.resourceLogs) { - if (!Array.isArray(object.resourceLogs)) - throw TypeError(".opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.resourceLogs: array expected"); - message.resourceLogs = []; - for (var i = 0; i < object.resourceLogs.length; ++i) { - if (typeof object.resourceLogs[i] !== "object") - throw TypeError(".opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest.resourceLogs: object expected"); - message.resourceLogs[i] = $root.opentelemetry.proto.logs.v1.ResourceLogs.fromObject(object.resourceLogs[i]); - } - } - return message; - }; - /** - * Creates a plain object from an ExportLogsServiceRequest message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest - * @static - * @param {opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest} message ExportLogsServiceRequest - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExportLogsServiceRequest.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.resourceLogs = []; - if (message.resourceLogs && message.resourceLogs.length) { - object.resourceLogs = []; - for (var j = 0; j < message.resourceLogs.length; ++j) - object.resourceLogs[j] = $root.opentelemetry.proto.logs.v1.ResourceLogs.toObject(message.resourceLogs[j], options); - } - return object; - }; - /** - * Converts this ExportLogsServiceRequest to JSON. - * @function toJSON - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest - * @instance - * @returns {Object.} JSON object - */ - ExportLogsServiceRequest.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for ExportLogsServiceRequest - * @function getTypeUrl - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ExportLogsServiceRequest.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.collector.logs.v1.ExportLogsServiceRequest"; - }; - return ExportLogsServiceRequest; - })(); - v1.ExportLogsServiceResponse = (function () { - /** - * Properties of an ExportLogsServiceResponse. - * @memberof opentelemetry.proto.collector.logs.v1 - * @interface IExportLogsServiceResponse - * @property {opentelemetry.proto.collector.logs.v1.IExportLogsPartialSuccess|null} [partialSuccess] ExportLogsServiceResponse partialSuccess - */ - /** - * Constructs a new ExportLogsServiceResponse. - * @memberof opentelemetry.proto.collector.logs.v1 - * @classdesc Represents an ExportLogsServiceResponse. - * @implements IExportLogsServiceResponse - * @constructor - * @param {opentelemetry.proto.collector.logs.v1.IExportLogsServiceResponse=} [properties] Properties to set - */ - function ExportLogsServiceResponse(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * ExportLogsServiceResponse partialSuccess. - * @member {opentelemetry.proto.collector.logs.v1.IExportLogsPartialSuccess|null|undefined} partialSuccess - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse - * @instance - */ - ExportLogsServiceResponse.prototype.partialSuccess = null; - /** - * Creates a new ExportLogsServiceResponse instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse - * @static - * @param {opentelemetry.proto.collector.logs.v1.IExportLogsServiceResponse=} [properties] Properties to set - * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse} ExportLogsServiceResponse instance - */ - ExportLogsServiceResponse.create = function create(properties) { - return new ExportLogsServiceResponse(properties); - }; - /** - * Encodes the specified ExportLogsServiceResponse message. Does not implicitly {@link opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse - * @static - * @param {opentelemetry.proto.collector.logs.v1.IExportLogsServiceResponse} message ExportLogsServiceResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExportLogsServiceResponse.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.partialSuccess != null && Object.hasOwnProperty.call(message, "partialSuccess")) - $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.encode(message.partialSuccess, writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - return writer; - }; - /** - * Encodes the specified ExportLogsServiceResponse message, length delimited. Does not implicitly {@link opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse - * @static - * @param {opentelemetry.proto.collector.logs.v1.IExportLogsServiceResponse} message ExportLogsServiceResponse message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExportLogsServiceResponse.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes an ExportLogsServiceResponse message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse} ExportLogsServiceResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExportLogsServiceResponse.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.partialSuccess = $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.decode(reader, reader.uint32()); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes an ExportLogsServiceResponse message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse} ExportLogsServiceResponse - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExportLogsServiceResponse.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies an ExportLogsServiceResponse message. - * @function verify - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ExportLogsServiceResponse.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess")) { - var error = $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.verify(message.partialSuccess); - if (error) - return "partialSuccess." + error; - } - return null; - }; - /** - * Creates an ExportLogsServiceResponse message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse} ExportLogsServiceResponse - */ - ExportLogsServiceResponse.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse) - return object; - var message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse(); - if (object.partialSuccess != null) { - if (typeof object.partialSuccess !== "object") - throw TypeError(".opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse.partialSuccess: object expected"); - message.partialSuccess = $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.fromObject(object.partialSuccess); - } - return message; - }; - /** - * Creates a plain object from an ExportLogsServiceResponse message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse - * @static - * @param {opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse} message ExportLogsServiceResponse - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExportLogsServiceResponse.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) - object.partialSuccess = null; - if (message.partialSuccess != null && message.hasOwnProperty("partialSuccess")) - object.partialSuccess = $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.toObject(message.partialSuccess, options); - return object; - }; - /** - * Converts this ExportLogsServiceResponse to JSON. - * @function toJSON - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse - * @instance - * @returns {Object.} JSON object - */ - ExportLogsServiceResponse.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for ExportLogsServiceResponse - * @function getTypeUrl - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ExportLogsServiceResponse.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.collector.logs.v1.ExportLogsServiceResponse"; - }; - return ExportLogsServiceResponse; - })(); - v1.ExportLogsPartialSuccess = (function () { - /** - * Properties of an ExportLogsPartialSuccess. - * @memberof opentelemetry.proto.collector.logs.v1 - * @interface IExportLogsPartialSuccess - * @property {number|Long|null} [rejectedLogRecords] ExportLogsPartialSuccess rejectedLogRecords - * @property {string|null} [errorMessage] ExportLogsPartialSuccess errorMessage - */ - /** - * Constructs a new ExportLogsPartialSuccess. - * @memberof opentelemetry.proto.collector.logs.v1 - * @classdesc Represents an ExportLogsPartialSuccess. - * @implements IExportLogsPartialSuccess - * @constructor - * @param {opentelemetry.proto.collector.logs.v1.IExportLogsPartialSuccess=} [properties] Properties to set - */ - function ExportLogsPartialSuccess(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * ExportLogsPartialSuccess rejectedLogRecords. - * @member {number|Long|null|undefined} rejectedLogRecords - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess - * @instance - */ - ExportLogsPartialSuccess.prototype.rejectedLogRecords = null; - /** - * ExportLogsPartialSuccess errorMessage. - * @member {string|null|undefined} errorMessage - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess - * @instance - */ - ExportLogsPartialSuccess.prototype.errorMessage = null; - /** - * Creates a new ExportLogsPartialSuccess instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess - * @static - * @param {opentelemetry.proto.collector.logs.v1.IExportLogsPartialSuccess=} [properties] Properties to set - * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess} ExportLogsPartialSuccess instance - */ - ExportLogsPartialSuccess.create = function create(properties) { - return new ExportLogsPartialSuccess(properties); - }; - /** - * Encodes the specified ExportLogsPartialSuccess message. Does not implicitly {@link opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess - * @static - * @param {opentelemetry.proto.collector.logs.v1.IExportLogsPartialSuccess} message ExportLogsPartialSuccess message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExportLogsPartialSuccess.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.rejectedLogRecords != null && Object.hasOwnProperty.call(message, "rejectedLogRecords")) - writer.uint32(/* id 1, wireType 0 =*/ 8).int64(message.rejectedLogRecords); - if (message.errorMessage != null && Object.hasOwnProperty.call(message, "errorMessage")) - writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.errorMessage); - return writer; - }; - /** - * Encodes the specified ExportLogsPartialSuccess message, length delimited. Does not implicitly {@link opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess - * @static - * @param {opentelemetry.proto.collector.logs.v1.IExportLogsPartialSuccess} message ExportLogsPartialSuccess message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExportLogsPartialSuccess.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes an ExportLogsPartialSuccess message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess} ExportLogsPartialSuccess - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExportLogsPartialSuccess.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.rejectedLogRecords = reader.int64(); - break; - } - case 2: { - message.errorMessage = reader.string(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes an ExportLogsPartialSuccess message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess} ExportLogsPartialSuccess - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExportLogsPartialSuccess.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies an ExportLogsPartialSuccess message. - * @function verify - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ExportLogsPartialSuccess.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.rejectedLogRecords != null && message.hasOwnProperty("rejectedLogRecords")) - if (!$util.isInteger(message.rejectedLogRecords) && !(message.rejectedLogRecords && $util.isInteger(message.rejectedLogRecords.low) && $util.isInteger(message.rejectedLogRecords.high))) - return "rejectedLogRecords: integer|Long expected"; - if (message.errorMessage != null && message.hasOwnProperty("errorMessage")) - if (!$util.isString(message.errorMessage)) - return "errorMessage: string expected"; - return null; - }; - /** - * Creates an ExportLogsPartialSuccess message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess} ExportLogsPartialSuccess - */ - ExportLogsPartialSuccess.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess) - return object; - var message = new $root.opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess(); - if (object.rejectedLogRecords != null) - if ($util.Long) - (message.rejectedLogRecords = $util.Long.fromValue(object.rejectedLogRecords)).unsigned = false; - else if (typeof object.rejectedLogRecords === "string") - message.rejectedLogRecords = parseInt(object.rejectedLogRecords, 10); - else if (typeof object.rejectedLogRecords === "number") - message.rejectedLogRecords = object.rejectedLogRecords; - else if (typeof object.rejectedLogRecords === "object") - message.rejectedLogRecords = new $util.LongBits(object.rejectedLogRecords.low >>> 0, object.rejectedLogRecords.high >>> 0).toNumber(); - if (object.errorMessage != null) - message.errorMessage = String(object.errorMessage); - return message; - }; - /** - * Creates a plain object from an ExportLogsPartialSuccess message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess - * @static - * @param {opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess} message ExportLogsPartialSuccess - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExportLogsPartialSuccess.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.rejectedLogRecords = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.rejectedLogRecords = options.longs === String ? "0" : 0; - object.errorMessage = ""; - } - if (message.rejectedLogRecords != null && message.hasOwnProperty("rejectedLogRecords")) - if (typeof message.rejectedLogRecords === "number") - object.rejectedLogRecords = options.longs === String ? String(message.rejectedLogRecords) : message.rejectedLogRecords; - else - object.rejectedLogRecords = options.longs === String ? $util.Long.prototype.toString.call(message.rejectedLogRecords) : options.longs === Number ? new $util.LongBits(message.rejectedLogRecords.low >>> 0, message.rejectedLogRecords.high >>> 0).toNumber() : message.rejectedLogRecords; - if (message.errorMessage != null && message.hasOwnProperty("errorMessage")) - object.errorMessage = message.errorMessage; - return object; - }; - /** - * Converts this ExportLogsPartialSuccess to JSON. - * @function toJSON - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess - * @instance - * @returns {Object.} JSON object - */ - ExportLogsPartialSuccess.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for ExportLogsPartialSuccess - * @function getTypeUrl - * @memberof opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ExportLogsPartialSuccess.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.collector.logs.v1.ExportLogsPartialSuccess"; - }; - return ExportLogsPartialSuccess; - })(); - return v1; - })(); - return logs; - })(); - return collector; - })(); - proto.metrics = (function () { - /** - * Namespace metrics. - * @memberof opentelemetry.proto - * @namespace - */ - var metrics = {}; - metrics.v1 = (function () { - /** - * Namespace v1. - * @memberof opentelemetry.proto.metrics - * @namespace - */ - var v1 = {}; - v1.MetricsData = (function () { - /** - * Properties of a MetricsData. - * @memberof opentelemetry.proto.metrics.v1 - * @interface IMetricsData - * @property {Array.|null} [resourceMetrics] MetricsData resourceMetrics - */ - /** - * Constructs a new MetricsData. - * @memberof opentelemetry.proto.metrics.v1 - * @classdesc Represents a MetricsData. - * @implements IMetricsData - * @constructor - * @param {opentelemetry.proto.metrics.v1.IMetricsData=} [properties] Properties to set - */ - function MetricsData(properties) { - this.resourceMetrics = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * MetricsData resourceMetrics. - * @member {Array.} resourceMetrics - * @memberof opentelemetry.proto.metrics.v1.MetricsData - * @instance - */ - MetricsData.prototype.resourceMetrics = $util.emptyArray; - /** - * Creates a new MetricsData instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.metrics.v1.MetricsData - * @static - * @param {opentelemetry.proto.metrics.v1.IMetricsData=} [properties] Properties to set - * @returns {opentelemetry.proto.metrics.v1.MetricsData} MetricsData instance - */ - MetricsData.create = function create(properties) { - return new MetricsData(properties); - }; - /** - * Encodes the specified MetricsData message. Does not implicitly {@link opentelemetry.proto.metrics.v1.MetricsData.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.metrics.v1.MetricsData - * @static - * @param {opentelemetry.proto.metrics.v1.IMetricsData} message MetricsData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - MetricsData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.resourceMetrics != null && message.resourceMetrics.length) - for (var i = 0; i < message.resourceMetrics.length; ++i) - $root.opentelemetry.proto.metrics.v1.ResourceMetrics.encode(message.resourceMetrics[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - return writer; - }; - /** - * Encodes the specified MetricsData message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.MetricsData.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.metrics.v1.MetricsData - * @static - * @param {opentelemetry.proto.metrics.v1.IMetricsData} message MetricsData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - MetricsData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a MetricsData message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.metrics.v1.MetricsData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.metrics.v1.MetricsData} MetricsData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - MetricsData.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.MetricsData(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - if (!(message.resourceMetrics && message.resourceMetrics.length)) - message.resourceMetrics = []; - message.resourceMetrics.push($root.opentelemetry.proto.metrics.v1.ResourceMetrics.decode(reader, reader.uint32())); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a MetricsData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.metrics.v1.MetricsData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.metrics.v1.MetricsData} MetricsData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - MetricsData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a MetricsData message. - * @function verify - * @memberof opentelemetry.proto.metrics.v1.MetricsData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - MetricsData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.resourceMetrics != null && message.hasOwnProperty("resourceMetrics")) { - if (!Array.isArray(message.resourceMetrics)) - return "resourceMetrics: array expected"; - for (var i = 0; i < message.resourceMetrics.length; ++i) { - var error = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.verify(message.resourceMetrics[i]); - if (error) - return "resourceMetrics." + error; - } - } - return null; - }; - /** - * Creates a MetricsData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.metrics.v1.MetricsData - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.metrics.v1.MetricsData} MetricsData - */ - MetricsData.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.metrics.v1.MetricsData) - return object; - var message = new $root.opentelemetry.proto.metrics.v1.MetricsData(); - if (object.resourceMetrics) { - if (!Array.isArray(object.resourceMetrics)) - throw TypeError(".opentelemetry.proto.metrics.v1.MetricsData.resourceMetrics: array expected"); - message.resourceMetrics = []; - for (var i = 0; i < object.resourceMetrics.length; ++i) { - if (typeof object.resourceMetrics[i] !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.MetricsData.resourceMetrics: object expected"); - message.resourceMetrics[i] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.fromObject(object.resourceMetrics[i]); - } - } - return message; - }; - /** - * Creates a plain object from a MetricsData message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.metrics.v1.MetricsData - * @static - * @param {opentelemetry.proto.metrics.v1.MetricsData} message MetricsData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - MetricsData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.resourceMetrics = []; - if (message.resourceMetrics && message.resourceMetrics.length) { - object.resourceMetrics = []; - for (var j = 0; j < message.resourceMetrics.length; ++j) - object.resourceMetrics[j] = $root.opentelemetry.proto.metrics.v1.ResourceMetrics.toObject(message.resourceMetrics[j], options); - } - return object; - }; - /** - * Converts this MetricsData to JSON. - * @function toJSON - * @memberof opentelemetry.proto.metrics.v1.MetricsData - * @instance - * @returns {Object.} JSON object - */ - MetricsData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for MetricsData - * @function getTypeUrl - * @memberof opentelemetry.proto.metrics.v1.MetricsData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - MetricsData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.MetricsData"; - }; - return MetricsData; - })(); - v1.ResourceMetrics = (function () { - /** - * Properties of a ResourceMetrics. - * @memberof opentelemetry.proto.metrics.v1 - * @interface IResourceMetrics - * @property {opentelemetry.proto.resource.v1.IResource|null} [resource] ResourceMetrics resource - * @property {Array.|null} [scopeMetrics] ResourceMetrics scopeMetrics - * @property {string|null} [schemaUrl] ResourceMetrics schemaUrl - */ - /** - * Constructs a new ResourceMetrics. - * @memberof opentelemetry.proto.metrics.v1 - * @classdesc Represents a ResourceMetrics. - * @implements IResourceMetrics - * @constructor - * @param {opentelemetry.proto.metrics.v1.IResourceMetrics=} [properties] Properties to set - */ - function ResourceMetrics(properties) { - this.scopeMetrics = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * ResourceMetrics resource. - * @member {opentelemetry.proto.resource.v1.IResource|null|undefined} resource - * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics - * @instance - */ - ResourceMetrics.prototype.resource = null; - /** - * ResourceMetrics scopeMetrics. - * @member {Array.} scopeMetrics - * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics - * @instance - */ - ResourceMetrics.prototype.scopeMetrics = $util.emptyArray; - /** - * ResourceMetrics schemaUrl. - * @member {string|null|undefined} schemaUrl - * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics - * @instance - */ - ResourceMetrics.prototype.schemaUrl = null; - /** - * Creates a new ResourceMetrics instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics - * @static - * @param {opentelemetry.proto.metrics.v1.IResourceMetrics=} [properties] Properties to set - * @returns {opentelemetry.proto.metrics.v1.ResourceMetrics} ResourceMetrics instance - */ - ResourceMetrics.create = function create(properties) { - return new ResourceMetrics(properties); - }; - /** - * Encodes the specified ResourceMetrics message. Does not implicitly {@link opentelemetry.proto.metrics.v1.ResourceMetrics.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics - * @static - * @param {opentelemetry.proto.metrics.v1.IResourceMetrics} message ResourceMetrics message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ResourceMetrics.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) - $root.opentelemetry.proto.resource.v1.Resource.encode(message.resource, writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - if (message.scopeMetrics != null && message.scopeMetrics.length) - for (var i = 0; i < message.scopeMetrics.length; ++i) - $root.opentelemetry.proto.metrics.v1.ScopeMetrics.encode(message.scopeMetrics[i], writer.uint32(/* id 2, wireType 2 =*/ 18).fork()).ldelim(); - if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl")) - writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.schemaUrl); - return writer; - }; - /** - * Encodes the specified ResourceMetrics message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.ResourceMetrics.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics - * @static - * @param {opentelemetry.proto.metrics.v1.IResourceMetrics} message ResourceMetrics message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ResourceMetrics.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a ResourceMetrics message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.metrics.v1.ResourceMetrics} ResourceMetrics - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ResourceMetrics.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.ResourceMetrics(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.resource = $root.opentelemetry.proto.resource.v1.Resource.decode(reader, reader.uint32()); - break; - } - case 2: { - if (!(message.scopeMetrics && message.scopeMetrics.length)) - message.scopeMetrics = []; - message.scopeMetrics.push($root.opentelemetry.proto.metrics.v1.ScopeMetrics.decode(reader, reader.uint32())); - break; - } - case 3: { - message.schemaUrl = reader.string(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a ResourceMetrics message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.metrics.v1.ResourceMetrics} ResourceMetrics - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ResourceMetrics.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a ResourceMetrics message. - * @function verify - * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ResourceMetrics.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.resource != null && message.hasOwnProperty("resource")) { - var error = $root.opentelemetry.proto.resource.v1.Resource.verify(message.resource); - if (error) - return "resource." + error; - } - if (message.scopeMetrics != null && message.hasOwnProperty("scopeMetrics")) { - if (!Array.isArray(message.scopeMetrics)) - return "scopeMetrics: array expected"; - for (var i = 0; i < message.scopeMetrics.length; ++i) { - var error = $root.opentelemetry.proto.metrics.v1.ScopeMetrics.verify(message.scopeMetrics[i]); - if (error) - return "scopeMetrics." + error; - } - } - if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) - if (!$util.isString(message.schemaUrl)) - return "schemaUrl: string expected"; - return null; - }; - /** - * Creates a ResourceMetrics message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.metrics.v1.ResourceMetrics} ResourceMetrics - */ - ResourceMetrics.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.metrics.v1.ResourceMetrics) - return object; - var message = new $root.opentelemetry.proto.metrics.v1.ResourceMetrics(); - if (object.resource != null) { - if (typeof object.resource !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.ResourceMetrics.resource: object expected"); - message.resource = $root.opentelemetry.proto.resource.v1.Resource.fromObject(object.resource); - } - if (object.scopeMetrics) { - if (!Array.isArray(object.scopeMetrics)) - throw TypeError(".opentelemetry.proto.metrics.v1.ResourceMetrics.scopeMetrics: array expected"); - message.scopeMetrics = []; - for (var i = 0; i < object.scopeMetrics.length; ++i) { - if (typeof object.scopeMetrics[i] !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.ResourceMetrics.scopeMetrics: object expected"); - message.scopeMetrics[i] = $root.opentelemetry.proto.metrics.v1.ScopeMetrics.fromObject(object.scopeMetrics[i]); - } - } - if (object.schemaUrl != null) - message.schemaUrl = String(object.schemaUrl); - return message; - }; - /** - * Creates a plain object from a ResourceMetrics message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics - * @static - * @param {opentelemetry.proto.metrics.v1.ResourceMetrics} message ResourceMetrics - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ResourceMetrics.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.scopeMetrics = []; - if (options.defaults) { - object.resource = null; - object.schemaUrl = ""; - } - if (message.resource != null && message.hasOwnProperty("resource")) - object.resource = $root.opentelemetry.proto.resource.v1.Resource.toObject(message.resource, options); - if (message.scopeMetrics && message.scopeMetrics.length) { - object.scopeMetrics = []; - for (var j = 0; j < message.scopeMetrics.length; ++j) - object.scopeMetrics[j] = $root.opentelemetry.proto.metrics.v1.ScopeMetrics.toObject(message.scopeMetrics[j], options); - } - if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) - object.schemaUrl = message.schemaUrl; - return object; - }; - /** - * Converts this ResourceMetrics to JSON. - * @function toJSON - * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics - * @instance - * @returns {Object.} JSON object - */ - ResourceMetrics.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for ResourceMetrics - * @function getTypeUrl - * @memberof opentelemetry.proto.metrics.v1.ResourceMetrics - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ResourceMetrics.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.ResourceMetrics"; - }; - return ResourceMetrics; - })(); - v1.ScopeMetrics = (function () { - /** - * Properties of a ScopeMetrics. - * @memberof opentelemetry.proto.metrics.v1 - * @interface IScopeMetrics - * @property {opentelemetry.proto.common.v1.IInstrumentationScope|null} [scope] ScopeMetrics scope - * @property {Array.|null} [metrics] ScopeMetrics metrics - * @property {string|null} [schemaUrl] ScopeMetrics schemaUrl - */ - /** - * Constructs a new ScopeMetrics. - * @memberof opentelemetry.proto.metrics.v1 - * @classdesc Represents a ScopeMetrics. - * @implements IScopeMetrics - * @constructor - * @param {opentelemetry.proto.metrics.v1.IScopeMetrics=} [properties] Properties to set - */ - function ScopeMetrics(properties) { - this.metrics = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * ScopeMetrics scope. - * @member {opentelemetry.proto.common.v1.IInstrumentationScope|null|undefined} scope - * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics - * @instance - */ - ScopeMetrics.prototype.scope = null; - /** - * ScopeMetrics metrics. - * @member {Array.} metrics - * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics - * @instance - */ - ScopeMetrics.prototype.metrics = $util.emptyArray; - /** - * ScopeMetrics schemaUrl. - * @member {string|null|undefined} schemaUrl - * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics - * @instance - */ - ScopeMetrics.prototype.schemaUrl = null; - /** - * Creates a new ScopeMetrics instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics - * @static - * @param {opentelemetry.proto.metrics.v1.IScopeMetrics=} [properties] Properties to set - * @returns {opentelemetry.proto.metrics.v1.ScopeMetrics} ScopeMetrics instance - */ - ScopeMetrics.create = function create(properties) { - return new ScopeMetrics(properties); - }; - /** - * Encodes the specified ScopeMetrics message. Does not implicitly {@link opentelemetry.proto.metrics.v1.ScopeMetrics.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics - * @static - * @param {opentelemetry.proto.metrics.v1.IScopeMetrics} message ScopeMetrics message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ScopeMetrics.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.scope != null && Object.hasOwnProperty.call(message, "scope")) - $root.opentelemetry.proto.common.v1.InstrumentationScope.encode(message.scope, writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - if (message.metrics != null && message.metrics.length) - for (var i = 0; i < message.metrics.length; ++i) - $root.opentelemetry.proto.metrics.v1.Metric.encode(message.metrics[i], writer.uint32(/* id 2, wireType 2 =*/ 18).fork()).ldelim(); - if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl")) - writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.schemaUrl); - return writer; - }; - /** - * Encodes the specified ScopeMetrics message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.ScopeMetrics.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics - * @static - * @param {opentelemetry.proto.metrics.v1.IScopeMetrics} message ScopeMetrics message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ScopeMetrics.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a ScopeMetrics message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.metrics.v1.ScopeMetrics} ScopeMetrics - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ScopeMetrics.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.ScopeMetrics(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.decode(reader, reader.uint32()); - break; - } - case 2: { - if (!(message.metrics && message.metrics.length)) - message.metrics = []; - message.metrics.push($root.opentelemetry.proto.metrics.v1.Metric.decode(reader, reader.uint32())); - break; - } - case 3: { - message.schemaUrl = reader.string(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a ScopeMetrics message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.metrics.v1.ScopeMetrics} ScopeMetrics - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ScopeMetrics.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a ScopeMetrics message. - * @function verify - * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ScopeMetrics.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.scope != null && message.hasOwnProperty("scope")) { - var error = $root.opentelemetry.proto.common.v1.InstrumentationScope.verify(message.scope); - if (error) - return "scope." + error; - } - if (message.metrics != null && message.hasOwnProperty("metrics")) { - if (!Array.isArray(message.metrics)) - return "metrics: array expected"; - for (var i = 0; i < message.metrics.length; ++i) { - var error = $root.opentelemetry.proto.metrics.v1.Metric.verify(message.metrics[i]); - if (error) - return "metrics." + error; - } - } - if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) - if (!$util.isString(message.schemaUrl)) - return "schemaUrl: string expected"; - return null; - }; - /** - * Creates a ScopeMetrics message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.metrics.v1.ScopeMetrics} ScopeMetrics - */ - ScopeMetrics.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.metrics.v1.ScopeMetrics) - return object; - var message = new $root.opentelemetry.proto.metrics.v1.ScopeMetrics(); - if (object.scope != null) { - if (typeof object.scope !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.ScopeMetrics.scope: object expected"); - message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(object.scope); - } - if (object.metrics) { - if (!Array.isArray(object.metrics)) - throw TypeError(".opentelemetry.proto.metrics.v1.ScopeMetrics.metrics: array expected"); - message.metrics = []; - for (var i = 0; i < object.metrics.length; ++i) { - if (typeof object.metrics[i] !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.ScopeMetrics.metrics: object expected"); - message.metrics[i] = $root.opentelemetry.proto.metrics.v1.Metric.fromObject(object.metrics[i]); - } - } - if (object.schemaUrl != null) - message.schemaUrl = String(object.schemaUrl); - return message; - }; - /** - * Creates a plain object from a ScopeMetrics message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics - * @static - * @param {opentelemetry.proto.metrics.v1.ScopeMetrics} message ScopeMetrics - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ScopeMetrics.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.metrics = []; - if (options.defaults) { - object.scope = null; - object.schemaUrl = ""; - } - if (message.scope != null && message.hasOwnProperty("scope")) - object.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.toObject(message.scope, options); - if (message.metrics && message.metrics.length) { - object.metrics = []; - for (var j = 0; j < message.metrics.length; ++j) - object.metrics[j] = $root.opentelemetry.proto.metrics.v1.Metric.toObject(message.metrics[j], options); - } - if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) - object.schemaUrl = message.schemaUrl; - return object; - }; - /** - * Converts this ScopeMetrics to JSON. - * @function toJSON - * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics - * @instance - * @returns {Object.} JSON object - */ - ScopeMetrics.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for ScopeMetrics - * @function getTypeUrl - * @memberof opentelemetry.proto.metrics.v1.ScopeMetrics - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ScopeMetrics.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.ScopeMetrics"; - }; - return ScopeMetrics; - })(); - v1.Metric = (function () { - /** - * Properties of a Metric. - * @memberof opentelemetry.proto.metrics.v1 - * @interface IMetric - * @property {string|null} [name] Metric name - * @property {string|null} [description] Metric description - * @property {string|null} [unit] Metric unit - * @property {opentelemetry.proto.metrics.v1.IGauge|null} [gauge] Metric gauge - * @property {opentelemetry.proto.metrics.v1.ISum|null} [sum] Metric sum - * @property {opentelemetry.proto.metrics.v1.IHistogram|null} [histogram] Metric histogram - * @property {opentelemetry.proto.metrics.v1.IExponentialHistogram|null} [exponentialHistogram] Metric exponentialHistogram - * @property {opentelemetry.proto.metrics.v1.ISummary|null} [summary] Metric summary - * @property {Array.|null} [metadata] Metric metadata - */ - /** - * Constructs a new Metric. - * @memberof opentelemetry.proto.metrics.v1 - * @classdesc Represents a Metric. - * @implements IMetric - * @constructor - * @param {opentelemetry.proto.metrics.v1.IMetric=} [properties] Properties to set - */ - function Metric(properties) { - this.metadata = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * Metric name. - * @member {string|null|undefined} name - * @memberof opentelemetry.proto.metrics.v1.Metric - * @instance - */ - Metric.prototype.name = null; - /** - * Metric description. - * @member {string|null|undefined} description - * @memberof opentelemetry.proto.metrics.v1.Metric - * @instance - */ - Metric.prototype.description = null; - /** - * Metric unit. - * @member {string|null|undefined} unit - * @memberof opentelemetry.proto.metrics.v1.Metric - * @instance - */ - Metric.prototype.unit = null; - /** - * Metric gauge. - * @member {opentelemetry.proto.metrics.v1.IGauge|null|undefined} gauge - * @memberof opentelemetry.proto.metrics.v1.Metric - * @instance - */ - Metric.prototype.gauge = null; - /** - * Metric sum. - * @member {opentelemetry.proto.metrics.v1.ISum|null|undefined} sum - * @memberof opentelemetry.proto.metrics.v1.Metric - * @instance - */ - Metric.prototype.sum = null; - /** - * Metric histogram. - * @member {opentelemetry.proto.metrics.v1.IHistogram|null|undefined} histogram - * @memberof opentelemetry.proto.metrics.v1.Metric - * @instance - */ - Metric.prototype.histogram = null; - /** - * Metric exponentialHistogram. - * @member {opentelemetry.proto.metrics.v1.IExponentialHistogram|null|undefined} exponentialHistogram - * @memberof opentelemetry.proto.metrics.v1.Metric - * @instance - */ - Metric.prototype.exponentialHistogram = null; - /** - * Metric summary. - * @member {opentelemetry.proto.metrics.v1.ISummary|null|undefined} summary - * @memberof opentelemetry.proto.metrics.v1.Metric - * @instance - */ - Metric.prototype.summary = null; - /** - * Metric metadata. - * @member {Array.} metadata - * @memberof opentelemetry.proto.metrics.v1.Metric - * @instance - */ - Metric.prototype.metadata = $util.emptyArray; - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - /** - * Metric data. - * @member {"gauge"|"sum"|"histogram"|"exponentialHistogram"|"summary"|undefined} data - * @memberof opentelemetry.proto.metrics.v1.Metric - * @instance - */ - Object.defineProperty(Metric.prototype, "data", { - get: $util.oneOfGetter($oneOfFields = ["gauge", "sum", "histogram", "exponentialHistogram", "summary"]), - set: $util.oneOfSetter($oneOfFields) - }); - /** - * Creates a new Metric instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.metrics.v1.Metric - * @static - * @param {opentelemetry.proto.metrics.v1.IMetric=} [properties] Properties to set - * @returns {opentelemetry.proto.metrics.v1.Metric} Metric instance - */ - Metric.create = function create(properties) { - return new Metric(properties); - }; - /** - * Encodes the specified Metric message. Does not implicitly {@link opentelemetry.proto.metrics.v1.Metric.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.metrics.v1.Metric - * @static - * @param {opentelemetry.proto.metrics.v1.IMetric} message Metric message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Metric.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.name != null && Object.hasOwnProperty.call(message, "name")) - writer.uint32(/* id 1, wireType 2 =*/ 10).string(message.name); - if (message.description != null && Object.hasOwnProperty.call(message, "description")) - writer.uint32(/* id 2, wireType 2 =*/ 18).string(message.description); - if (message.unit != null && Object.hasOwnProperty.call(message, "unit")) - writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.unit); - if (message.gauge != null && Object.hasOwnProperty.call(message, "gauge")) - $root.opentelemetry.proto.metrics.v1.Gauge.encode(message.gauge, writer.uint32(/* id 5, wireType 2 =*/ 42).fork()).ldelim(); - if (message.sum != null && Object.hasOwnProperty.call(message, "sum")) - $root.opentelemetry.proto.metrics.v1.Sum.encode(message.sum, writer.uint32(/* id 7, wireType 2 =*/ 58).fork()).ldelim(); - if (message.histogram != null && Object.hasOwnProperty.call(message, "histogram")) - $root.opentelemetry.proto.metrics.v1.Histogram.encode(message.histogram, writer.uint32(/* id 9, wireType 2 =*/ 74).fork()).ldelim(); - if (message.exponentialHistogram != null && Object.hasOwnProperty.call(message, "exponentialHistogram")) - $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.encode(message.exponentialHistogram, writer.uint32(/* id 10, wireType 2 =*/ 82).fork()).ldelim(); - if (message.summary != null && Object.hasOwnProperty.call(message, "summary")) - $root.opentelemetry.proto.metrics.v1.Summary.encode(message.summary, writer.uint32(/* id 11, wireType 2 =*/ 90).fork()).ldelim(); - if (message.metadata != null && message.metadata.length) - for (var i = 0; i < message.metadata.length; ++i) - $root.opentelemetry.proto.common.v1.KeyValue.encode(message.metadata[i], writer.uint32(/* id 12, wireType 2 =*/ 98).fork()).ldelim(); - return writer; - }; - /** - * Encodes the specified Metric message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.Metric.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.metrics.v1.Metric - * @static - * @param {opentelemetry.proto.metrics.v1.IMetric} message Metric message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Metric.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a Metric message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.metrics.v1.Metric - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.metrics.v1.Metric} Metric - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Metric.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Metric(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.name = reader.string(); - break; - } - case 2: { - message.description = reader.string(); - break; - } - case 3: { - message.unit = reader.string(); - break; - } - case 5: { - message.gauge = $root.opentelemetry.proto.metrics.v1.Gauge.decode(reader, reader.uint32()); - break; - } - case 7: { - message.sum = $root.opentelemetry.proto.metrics.v1.Sum.decode(reader, reader.uint32()); - break; - } - case 9: { - message.histogram = $root.opentelemetry.proto.metrics.v1.Histogram.decode(reader, reader.uint32()); - break; - } - case 10: { - message.exponentialHistogram = $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.decode(reader, reader.uint32()); - break; - } - case 11: { - message.summary = $root.opentelemetry.proto.metrics.v1.Summary.decode(reader, reader.uint32()); - break; - } - case 12: { - if (!(message.metadata && message.metadata.length)) - message.metadata = []; - message.metadata.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a Metric message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.metrics.v1.Metric - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.metrics.v1.Metric} Metric - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Metric.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a Metric message. - * @function verify - * @memberof opentelemetry.proto.metrics.v1.Metric - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Metric.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.name != null && message.hasOwnProperty("name")) - if (!$util.isString(message.name)) - return "name: string expected"; - if (message.description != null && message.hasOwnProperty("description")) - if (!$util.isString(message.description)) - return "description: string expected"; - if (message.unit != null && message.hasOwnProperty("unit")) - if (!$util.isString(message.unit)) - return "unit: string expected"; - if (message.gauge != null && message.hasOwnProperty("gauge")) { - properties.data = 1; - { - var error = $root.opentelemetry.proto.metrics.v1.Gauge.verify(message.gauge); - if (error) - return "gauge." + error; - } - } - if (message.sum != null && message.hasOwnProperty("sum")) { - if (properties.data === 1) - return "data: multiple values"; - properties.data = 1; - { - var error = $root.opentelemetry.proto.metrics.v1.Sum.verify(message.sum); - if (error) - return "sum." + error; - } - } - if (message.histogram != null && message.hasOwnProperty("histogram")) { - if (properties.data === 1) - return "data: multiple values"; - properties.data = 1; - { - var error = $root.opentelemetry.proto.metrics.v1.Histogram.verify(message.histogram); - if (error) - return "histogram." + error; - } - } - if (message.exponentialHistogram != null && message.hasOwnProperty("exponentialHistogram")) { - if (properties.data === 1) - return "data: multiple values"; - properties.data = 1; - { - var error = $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.verify(message.exponentialHistogram); - if (error) - return "exponentialHistogram." + error; - } - } - if (message.summary != null && message.hasOwnProperty("summary")) { - if (properties.data === 1) - return "data: multiple values"; - properties.data = 1; - { - var error = $root.opentelemetry.proto.metrics.v1.Summary.verify(message.summary); - if (error) - return "summary." + error; - } - } - if (message.metadata != null && message.hasOwnProperty("metadata")) { - if (!Array.isArray(message.metadata)) - return "metadata: array expected"; - for (var i = 0; i < message.metadata.length; ++i) { - var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.metadata[i]); - if (error) - return "metadata." + error; - } - } - return null; - }; - /** - * Creates a Metric message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.metrics.v1.Metric - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.metrics.v1.Metric} Metric - */ - Metric.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.metrics.v1.Metric) - return object; - var message = new $root.opentelemetry.proto.metrics.v1.Metric(); - if (object.name != null) - message.name = String(object.name); - if (object.description != null) - message.description = String(object.description); - if (object.unit != null) - message.unit = String(object.unit); - if (object.gauge != null) { - if (typeof object.gauge !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.Metric.gauge: object expected"); - message.gauge = $root.opentelemetry.proto.metrics.v1.Gauge.fromObject(object.gauge); - } - if (object.sum != null) { - if (typeof object.sum !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.Metric.sum: object expected"); - message.sum = $root.opentelemetry.proto.metrics.v1.Sum.fromObject(object.sum); - } - if (object.histogram != null) { - if (typeof object.histogram !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.Metric.histogram: object expected"); - message.histogram = $root.opentelemetry.proto.metrics.v1.Histogram.fromObject(object.histogram); - } - if (object.exponentialHistogram != null) { - if (typeof object.exponentialHistogram !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.Metric.exponentialHistogram: object expected"); - message.exponentialHistogram = $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.fromObject(object.exponentialHistogram); - } - if (object.summary != null) { - if (typeof object.summary !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.Metric.summary: object expected"); - message.summary = $root.opentelemetry.proto.metrics.v1.Summary.fromObject(object.summary); - } - if (object.metadata) { - if (!Array.isArray(object.metadata)) - throw TypeError(".opentelemetry.proto.metrics.v1.Metric.metadata: array expected"); - message.metadata = []; - for (var i = 0; i < object.metadata.length; ++i) { - if (typeof object.metadata[i] !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.Metric.metadata: object expected"); - message.metadata[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.metadata[i]); - } - } - return message; - }; - /** - * Creates a plain object from a Metric message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.metrics.v1.Metric - * @static - * @param {opentelemetry.proto.metrics.v1.Metric} message Metric - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Metric.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.metadata = []; - if (options.defaults) { - object.name = ""; - object.description = ""; - object.unit = ""; - } - if (message.name != null && message.hasOwnProperty("name")) - object.name = message.name; - if (message.description != null && message.hasOwnProperty("description")) - object.description = message.description; - if (message.unit != null && message.hasOwnProperty("unit")) - object.unit = message.unit; - if (message.gauge != null && message.hasOwnProperty("gauge")) { - object.gauge = $root.opentelemetry.proto.metrics.v1.Gauge.toObject(message.gauge, options); - if (options.oneofs) - object.data = "gauge"; - } - if (message.sum != null && message.hasOwnProperty("sum")) { - object.sum = $root.opentelemetry.proto.metrics.v1.Sum.toObject(message.sum, options); - if (options.oneofs) - object.data = "sum"; - } - if (message.histogram != null && message.hasOwnProperty("histogram")) { - object.histogram = $root.opentelemetry.proto.metrics.v1.Histogram.toObject(message.histogram, options); - if (options.oneofs) - object.data = "histogram"; - } - if (message.exponentialHistogram != null && message.hasOwnProperty("exponentialHistogram")) { - object.exponentialHistogram = $root.opentelemetry.proto.metrics.v1.ExponentialHistogram.toObject(message.exponentialHistogram, options); - if (options.oneofs) - object.data = "exponentialHistogram"; - } - if (message.summary != null && message.hasOwnProperty("summary")) { - object.summary = $root.opentelemetry.proto.metrics.v1.Summary.toObject(message.summary, options); - if (options.oneofs) - object.data = "summary"; - } - if (message.metadata && message.metadata.length) { - object.metadata = []; - for (var j = 0; j < message.metadata.length; ++j) - object.metadata[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.metadata[j], options); - } - return object; - }; - /** - * Converts this Metric to JSON. - * @function toJSON - * @memberof opentelemetry.proto.metrics.v1.Metric - * @instance - * @returns {Object.} JSON object - */ - Metric.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for Metric - * @function getTypeUrl - * @memberof opentelemetry.proto.metrics.v1.Metric - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Metric.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Metric"; - }; - return Metric; - })(); - v1.Gauge = (function () { - /** - * Properties of a Gauge. - * @memberof opentelemetry.proto.metrics.v1 - * @interface IGauge - * @property {Array.|null} [dataPoints] Gauge dataPoints - */ - /** - * Constructs a new Gauge. - * @memberof opentelemetry.proto.metrics.v1 - * @classdesc Represents a Gauge. - * @implements IGauge - * @constructor - * @param {opentelemetry.proto.metrics.v1.IGauge=} [properties] Properties to set - */ - function Gauge(properties) { - this.dataPoints = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * Gauge dataPoints. - * @member {Array.} dataPoints - * @memberof opentelemetry.proto.metrics.v1.Gauge - * @instance - */ - Gauge.prototype.dataPoints = $util.emptyArray; - /** - * Creates a new Gauge instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.metrics.v1.Gauge - * @static - * @param {opentelemetry.proto.metrics.v1.IGauge=} [properties] Properties to set - * @returns {opentelemetry.proto.metrics.v1.Gauge} Gauge instance - */ - Gauge.create = function create(properties) { - return new Gauge(properties); - }; - /** - * Encodes the specified Gauge message. Does not implicitly {@link opentelemetry.proto.metrics.v1.Gauge.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.metrics.v1.Gauge - * @static - * @param {opentelemetry.proto.metrics.v1.IGauge} message Gauge message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Gauge.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.dataPoints != null && message.dataPoints.length) - for (var i = 0; i < message.dataPoints.length; ++i) - $root.opentelemetry.proto.metrics.v1.NumberDataPoint.encode(message.dataPoints[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - return writer; - }; - /** - * Encodes the specified Gauge message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.Gauge.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.metrics.v1.Gauge - * @static - * @param {opentelemetry.proto.metrics.v1.IGauge} message Gauge message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Gauge.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a Gauge message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.metrics.v1.Gauge - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.metrics.v1.Gauge} Gauge - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Gauge.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Gauge(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - if (!(message.dataPoints && message.dataPoints.length)) - message.dataPoints = []; - message.dataPoints.push($root.opentelemetry.proto.metrics.v1.NumberDataPoint.decode(reader, reader.uint32())); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a Gauge message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.metrics.v1.Gauge - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.metrics.v1.Gauge} Gauge - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Gauge.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a Gauge message. - * @function verify - * @memberof opentelemetry.proto.metrics.v1.Gauge - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Gauge.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.dataPoints != null && message.hasOwnProperty("dataPoints")) { - if (!Array.isArray(message.dataPoints)) - return "dataPoints: array expected"; - for (var i = 0; i < message.dataPoints.length; ++i) { - var error = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.verify(message.dataPoints[i]); - if (error) - return "dataPoints." + error; - } - } - return null; - }; - /** - * Creates a Gauge message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.metrics.v1.Gauge - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.metrics.v1.Gauge} Gauge - */ - Gauge.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.metrics.v1.Gauge) - return object; - var message = new $root.opentelemetry.proto.metrics.v1.Gauge(); - if (object.dataPoints) { - if (!Array.isArray(object.dataPoints)) - throw TypeError(".opentelemetry.proto.metrics.v1.Gauge.dataPoints: array expected"); - message.dataPoints = []; - for (var i = 0; i < object.dataPoints.length; ++i) { - if (typeof object.dataPoints[i] !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.Gauge.dataPoints: object expected"); - message.dataPoints[i] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.fromObject(object.dataPoints[i]); - } - } - return message; - }; - /** - * Creates a plain object from a Gauge message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.metrics.v1.Gauge - * @static - * @param {opentelemetry.proto.metrics.v1.Gauge} message Gauge - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Gauge.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.dataPoints = []; - if (message.dataPoints && message.dataPoints.length) { - object.dataPoints = []; - for (var j = 0; j < message.dataPoints.length; ++j) - object.dataPoints[j] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.toObject(message.dataPoints[j], options); - } - return object; - }; - /** - * Converts this Gauge to JSON. - * @function toJSON - * @memberof opentelemetry.proto.metrics.v1.Gauge - * @instance - * @returns {Object.} JSON object - */ - Gauge.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for Gauge - * @function getTypeUrl - * @memberof opentelemetry.proto.metrics.v1.Gauge - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Gauge.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Gauge"; - }; - return Gauge; - })(); - v1.Sum = (function () { - /** - * Properties of a Sum. - * @memberof opentelemetry.proto.metrics.v1 - * @interface ISum - * @property {Array.|null} [dataPoints] Sum dataPoints - * @property {opentelemetry.proto.metrics.v1.AggregationTemporality|null} [aggregationTemporality] Sum aggregationTemporality - * @property {boolean|null} [isMonotonic] Sum isMonotonic - */ - /** - * Constructs a new Sum. - * @memberof opentelemetry.proto.metrics.v1 - * @classdesc Represents a Sum. - * @implements ISum - * @constructor - * @param {opentelemetry.proto.metrics.v1.ISum=} [properties] Properties to set - */ - function Sum(properties) { - this.dataPoints = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * Sum dataPoints. - * @member {Array.} dataPoints - * @memberof opentelemetry.proto.metrics.v1.Sum - * @instance - */ - Sum.prototype.dataPoints = $util.emptyArray; - /** - * Sum aggregationTemporality. - * @member {opentelemetry.proto.metrics.v1.AggregationTemporality|null|undefined} aggregationTemporality - * @memberof opentelemetry.proto.metrics.v1.Sum - * @instance - */ - Sum.prototype.aggregationTemporality = null; - /** - * Sum isMonotonic. - * @member {boolean|null|undefined} isMonotonic - * @memberof opentelemetry.proto.metrics.v1.Sum - * @instance - */ - Sum.prototype.isMonotonic = null; - /** - * Creates a new Sum instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.metrics.v1.Sum - * @static - * @param {opentelemetry.proto.metrics.v1.ISum=} [properties] Properties to set - * @returns {opentelemetry.proto.metrics.v1.Sum} Sum instance - */ - Sum.create = function create(properties) { - return new Sum(properties); - }; - /** - * Encodes the specified Sum message. Does not implicitly {@link opentelemetry.proto.metrics.v1.Sum.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.metrics.v1.Sum - * @static - * @param {opentelemetry.proto.metrics.v1.ISum} message Sum message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Sum.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.dataPoints != null && message.dataPoints.length) - for (var i = 0; i < message.dataPoints.length; ++i) - $root.opentelemetry.proto.metrics.v1.NumberDataPoint.encode(message.dataPoints[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - if (message.aggregationTemporality != null && Object.hasOwnProperty.call(message, "aggregationTemporality")) - writer.uint32(/* id 2, wireType 0 =*/ 16).int32(message.aggregationTemporality); - if (message.isMonotonic != null && Object.hasOwnProperty.call(message, "isMonotonic")) - writer.uint32(/* id 3, wireType 0 =*/ 24).bool(message.isMonotonic); - return writer; - }; - /** - * Encodes the specified Sum message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.Sum.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.metrics.v1.Sum - * @static - * @param {opentelemetry.proto.metrics.v1.ISum} message Sum message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Sum.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a Sum message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.metrics.v1.Sum - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.metrics.v1.Sum} Sum - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Sum.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Sum(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - if (!(message.dataPoints && message.dataPoints.length)) - message.dataPoints = []; - message.dataPoints.push($root.opentelemetry.proto.metrics.v1.NumberDataPoint.decode(reader, reader.uint32())); - break; - } - case 2: { - message.aggregationTemporality = reader.int32(); - break; - } - case 3: { - message.isMonotonic = reader.bool(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a Sum message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.metrics.v1.Sum - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.metrics.v1.Sum} Sum - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Sum.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a Sum message. - * @function verify - * @memberof opentelemetry.proto.metrics.v1.Sum - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Sum.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.dataPoints != null && message.hasOwnProperty("dataPoints")) { - if (!Array.isArray(message.dataPoints)) - return "dataPoints: array expected"; - for (var i = 0; i < message.dataPoints.length; ++i) { - var error = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.verify(message.dataPoints[i]); - if (error) - return "dataPoints." + error; - } - } - if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality")) - switch (message.aggregationTemporality) { - default: - return "aggregationTemporality: enum value expected"; - case 0: - case 1: - case 2: - break; - } - if (message.isMonotonic != null && message.hasOwnProperty("isMonotonic")) - if (typeof message.isMonotonic !== "boolean") - return "isMonotonic: boolean expected"; - return null; - }; - /** - * Creates a Sum message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.metrics.v1.Sum - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.metrics.v1.Sum} Sum - */ - Sum.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.metrics.v1.Sum) - return object; - var message = new $root.opentelemetry.proto.metrics.v1.Sum(); - if (object.dataPoints) { - if (!Array.isArray(object.dataPoints)) - throw TypeError(".opentelemetry.proto.metrics.v1.Sum.dataPoints: array expected"); - message.dataPoints = []; - for (var i = 0; i < object.dataPoints.length; ++i) { - if (typeof object.dataPoints[i] !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.Sum.dataPoints: object expected"); - message.dataPoints[i] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.fromObject(object.dataPoints[i]); - } - } - switch (object.aggregationTemporality) { - default: - if (typeof object.aggregationTemporality === "number") { - message.aggregationTemporality = object.aggregationTemporality; - break; - } - break; - case "AGGREGATION_TEMPORALITY_UNSPECIFIED": - case 0: - message.aggregationTemporality = 0; - break; - case "AGGREGATION_TEMPORALITY_DELTA": - case 1: - message.aggregationTemporality = 1; - break; - case "AGGREGATION_TEMPORALITY_CUMULATIVE": - case 2: - message.aggregationTemporality = 2; - break; - } - if (object.isMonotonic != null) - message.isMonotonic = Boolean(object.isMonotonic); - return message; - }; - /** - * Creates a plain object from a Sum message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.metrics.v1.Sum - * @static - * @param {opentelemetry.proto.metrics.v1.Sum} message Sum - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Sum.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.dataPoints = []; - if (options.defaults) { - object.aggregationTemporality = options.enums === String ? "AGGREGATION_TEMPORALITY_UNSPECIFIED" : 0; - object.isMonotonic = false; - } - if (message.dataPoints && message.dataPoints.length) { - object.dataPoints = []; - for (var j = 0; j < message.dataPoints.length; ++j) - object.dataPoints[j] = $root.opentelemetry.proto.metrics.v1.NumberDataPoint.toObject(message.dataPoints[j], options); - } - if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality")) - object.aggregationTemporality = options.enums === String ? $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] === undefined ? message.aggregationTemporality : $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] : message.aggregationTemporality; - if (message.isMonotonic != null && message.hasOwnProperty("isMonotonic")) - object.isMonotonic = message.isMonotonic; - return object; - }; - /** - * Converts this Sum to JSON. - * @function toJSON - * @memberof opentelemetry.proto.metrics.v1.Sum - * @instance - * @returns {Object.} JSON object - */ - Sum.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for Sum - * @function getTypeUrl - * @memberof opentelemetry.proto.metrics.v1.Sum - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Sum.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Sum"; - }; - return Sum; - })(); - v1.Histogram = (function () { - /** - * Properties of a Histogram. - * @memberof opentelemetry.proto.metrics.v1 - * @interface IHistogram - * @property {Array.|null} [dataPoints] Histogram dataPoints - * @property {opentelemetry.proto.metrics.v1.AggregationTemporality|null} [aggregationTemporality] Histogram aggregationTemporality - */ - /** - * Constructs a new Histogram. - * @memberof opentelemetry.proto.metrics.v1 - * @classdesc Represents a Histogram. - * @implements IHistogram - * @constructor - * @param {opentelemetry.proto.metrics.v1.IHistogram=} [properties] Properties to set - */ - function Histogram(properties) { - this.dataPoints = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * Histogram dataPoints. - * @member {Array.} dataPoints - * @memberof opentelemetry.proto.metrics.v1.Histogram - * @instance - */ - Histogram.prototype.dataPoints = $util.emptyArray; - /** - * Histogram aggregationTemporality. - * @member {opentelemetry.proto.metrics.v1.AggregationTemporality|null|undefined} aggregationTemporality - * @memberof opentelemetry.proto.metrics.v1.Histogram - * @instance - */ - Histogram.prototype.aggregationTemporality = null; - /** - * Creates a new Histogram instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.metrics.v1.Histogram - * @static - * @param {opentelemetry.proto.metrics.v1.IHistogram=} [properties] Properties to set - * @returns {opentelemetry.proto.metrics.v1.Histogram} Histogram instance - */ - Histogram.create = function create(properties) { - return new Histogram(properties); - }; - /** - * Encodes the specified Histogram message. Does not implicitly {@link opentelemetry.proto.metrics.v1.Histogram.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.metrics.v1.Histogram - * @static - * @param {opentelemetry.proto.metrics.v1.IHistogram} message Histogram message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Histogram.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.dataPoints != null && message.dataPoints.length) - for (var i = 0; i < message.dataPoints.length; ++i) - $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.encode(message.dataPoints[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - if (message.aggregationTemporality != null && Object.hasOwnProperty.call(message, "aggregationTemporality")) - writer.uint32(/* id 2, wireType 0 =*/ 16).int32(message.aggregationTemporality); - return writer; - }; - /** - * Encodes the specified Histogram message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.Histogram.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.metrics.v1.Histogram - * @static - * @param {opentelemetry.proto.metrics.v1.IHistogram} message Histogram message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Histogram.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a Histogram message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.metrics.v1.Histogram - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.metrics.v1.Histogram} Histogram - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Histogram.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Histogram(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - if (!(message.dataPoints && message.dataPoints.length)) - message.dataPoints = []; - message.dataPoints.push($root.opentelemetry.proto.metrics.v1.HistogramDataPoint.decode(reader, reader.uint32())); - break; - } - case 2: { - message.aggregationTemporality = reader.int32(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a Histogram message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.metrics.v1.Histogram - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.metrics.v1.Histogram} Histogram - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Histogram.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a Histogram message. - * @function verify - * @memberof opentelemetry.proto.metrics.v1.Histogram - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Histogram.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.dataPoints != null && message.hasOwnProperty("dataPoints")) { - if (!Array.isArray(message.dataPoints)) - return "dataPoints: array expected"; - for (var i = 0; i < message.dataPoints.length; ++i) { - var error = $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.verify(message.dataPoints[i]); - if (error) - return "dataPoints." + error; - } - } - if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality")) - switch (message.aggregationTemporality) { - default: - return "aggregationTemporality: enum value expected"; - case 0: - case 1: - case 2: - break; - } - return null; - }; - /** - * Creates a Histogram message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.metrics.v1.Histogram - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.metrics.v1.Histogram} Histogram - */ - Histogram.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.metrics.v1.Histogram) - return object; - var message = new $root.opentelemetry.proto.metrics.v1.Histogram(); - if (object.dataPoints) { - if (!Array.isArray(object.dataPoints)) - throw TypeError(".opentelemetry.proto.metrics.v1.Histogram.dataPoints: array expected"); - message.dataPoints = []; - for (var i = 0; i < object.dataPoints.length; ++i) { - if (typeof object.dataPoints[i] !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.Histogram.dataPoints: object expected"); - message.dataPoints[i] = $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.fromObject(object.dataPoints[i]); - } - } - switch (object.aggregationTemporality) { - default: - if (typeof object.aggregationTemporality === "number") { - message.aggregationTemporality = object.aggregationTemporality; - break; - } - break; - case "AGGREGATION_TEMPORALITY_UNSPECIFIED": - case 0: - message.aggregationTemporality = 0; - break; - case "AGGREGATION_TEMPORALITY_DELTA": - case 1: - message.aggregationTemporality = 1; - break; - case "AGGREGATION_TEMPORALITY_CUMULATIVE": - case 2: - message.aggregationTemporality = 2; - break; - } - return message; - }; - /** - * Creates a plain object from a Histogram message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.metrics.v1.Histogram - * @static - * @param {opentelemetry.proto.metrics.v1.Histogram} message Histogram - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Histogram.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.dataPoints = []; - if (options.defaults) - object.aggregationTemporality = options.enums === String ? "AGGREGATION_TEMPORALITY_UNSPECIFIED" : 0; - if (message.dataPoints && message.dataPoints.length) { - object.dataPoints = []; - for (var j = 0; j < message.dataPoints.length; ++j) - object.dataPoints[j] = $root.opentelemetry.proto.metrics.v1.HistogramDataPoint.toObject(message.dataPoints[j], options); - } - if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality")) - object.aggregationTemporality = options.enums === String ? $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] === undefined ? message.aggregationTemporality : $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] : message.aggregationTemporality; - return object; - }; - /** - * Converts this Histogram to JSON. - * @function toJSON - * @memberof opentelemetry.proto.metrics.v1.Histogram - * @instance - * @returns {Object.} JSON object - */ - Histogram.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for Histogram - * @function getTypeUrl - * @memberof opentelemetry.proto.metrics.v1.Histogram - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Histogram.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Histogram"; - }; - return Histogram; - })(); - v1.ExponentialHistogram = (function () { - /** - * Properties of an ExponentialHistogram. - * @memberof opentelemetry.proto.metrics.v1 - * @interface IExponentialHistogram - * @property {Array.|null} [dataPoints] ExponentialHistogram dataPoints - * @property {opentelemetry.proto.metrics.v1.AggregationTemporality|null} [aggregationTemporality] ExponentialHistogram aggregationTemporality - */ - /** - * Constructs a new ExponentialHistogram. - * @memberof opentelemetry.proto.metrics.v1 - * @classdesc Represents an ExponentialHistogram. - * @implements IExponentialHistogram - * @constructor - * @param {opentelemetry.proto.metrics.v1.IExponentialHistogram=} [properties] Properties to set - */ - function ExponentialHistogram(properties) { - this.dataPoints = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * ExponentialHistogram dataPoints. - * @member {Array.} dataPoints - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram - * @instance - */ - ExponentialHistogram.prototype.dataPoints = $util.emptyArray; - /** - * ExponentialHistogram aggregationTemporality. - * @member {opentelemetry.proto.metrics.v1.AggregationTemporality|null|undefined} aggregationTemporality - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram - * @instance - */ - ExponentialHistogram.prototype.aggregationTemporality = null; - /** - * Creates a new ExponentialHistogram instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram - * @static - * @param {opentelemetry.proto.metrics.v1.IExponentialHistogram=} [properties] Properties to set - * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogram} ExponentialHistogram instance - */ - ExponentialHistogram.create = function create(properties) { - return new ExponentialHistogram(properties); - }; - /** - * Encodes the specified ExponentialHistogram message. Does not implicitly {@link opentelemetry.proto.metrics.v1.ExponentialHistogram.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram - * @static - * @param {opentelemetry.proto.metrics.v1.IExponentialHistogram} message ExponentialHistogram message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExponentialHistogram.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.dataPoints != null && message.dataPoints.length) - for (var i = 0; i < message.dataPoints.length; ++i) - $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.encode(message.dataPoints[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - if (message.aggregationTemporality != null && Object.hasOwnProperty.call(message, "aggregationTemporality")) - writer.uint32(/* id 2, wireType 0 =*/ 16).int32(message.aggregationTemporality); - return writer; - }; - /** - * Encodes the specified ExponentialHistogram message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.ExponentialHistogram.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram - * @static - * @param {opentelemetry.proto.metrics.v1.IExponentialHistogram} message ExponentialHistogram message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExponentialHistogram.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes an ExponentialHistogram message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogram} ExponentialHistogram - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExponentialHistogram.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogram(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - if (!(message.dataPoints && message.dataPoints.length)) - message.dataPoints = []; - message.dataPoints.push($root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.decode(reader, reader.uint32())); - break; - } - case 2: { - message.aggregationTemporality = reader.int32(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes an ExponentialHistogram message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogram} ExponentialHistogram - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExponentialHistogram.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies an ExponentialHistogram message. - * @function verify - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ExponentialHistogram.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.dataPoints != null && message.hasOwnProperty("dataPoints")) { - if (!Array.isArray(message.dataPoints)) - return "dataPoints: array expected"; - for (var i = 0; i < message.dataPoints.length; ++i) { - var error = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.verify(message.dataPoints[i]); - if (error) - return "dataPoints." + error; - } - } - if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality")) - switch (message.aggregationTemporality) { - default: - return "aggregationTemporality: enum value expected"; - case 0: - case 1: - case 2: - break; - } - return null; - }; - /** - * Creates an ExponentialHistogram message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogram} ExponentialHistogram - */ - ExponentialHistogram.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.metrics.v1.ExponentialHistogram) - return object; - var message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogram(); - if (object.dataPoints) { - if (!Array.isArray(object.dataPoints)) - throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogram.dataPoints: array expected"); - message.dataPoints = []; - for (var i = 0; i < object.dataPoints.length; ++i) { - if (typeof object.dataPoints[i] !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogram.dataPoints: object expected"); - message.dataPoints[i] = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.fromObject(object.dataPoints[i]); - } - } - switch (object.aggregationTemporality) { - default: - if (typeof object.aggregationTemporality === "number") { - message.aggregationTemporality = object.aggregationTemporality; - break; - } - break; - case "AGGREGATION_TEMPORALITY_UNSPECIFIED": - case 0: - message.aggregationTemporality = 0; - break; - case "AGGREGATION_TEMPORALITY_DELTA": - case 1: - message.aggregationTemporality = 1; - break; - case "AGGREGATION_TEMPORALITY_CUMULATIVE": - case 2: - message.aggregationTemporality = 2; - break; - } - return message; - }; - /** - * Creates a plain object from an ExponentialHistogram message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram - * @static - * @param {opentelemetry.proto.metrics.v1.ExponentialHistogram} message ExponentialHistogram - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExponentialHistogram.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.dataPoints = []; - if (options.defaults) - object.aggregationTemporality = options.enums === String ? "AGGREGATION_TEMPORALITY_UNSPECIFIED" : 0; - if (message.dataPoints && message.dataPoints.length) { - object.dataPoints = []; - for (var j = 0; j < message.dataPoints.length; ++j) - object.dataPoints[j] = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.toObject(message.dataPoints[j], options); - } - if (message.aggregationTemporality != null && message.hasOwnProperty("aggregationTemporality")) - object.aggregationTemporality = options.enums === String ? $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] === undefined ? message.aggregationTemporality : $root.opentelemetry.proto.metrics.v1.AggregationTemporality[message.aggregationTemporality] : message.aggregationTemporality; - return object; - }; - /** - * Converts this ExponentialHistogram to JSON. - * @function toJSON - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram - * @instance - * @returns {Object.} JSON object - */ - ExponentialHistogram.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for ExponentialHistogram - * @function getTypeUrl - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogram - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ExponentialHistogram.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.ExponentialHistogram"; - }; - return ExponentialHistogram; - })(); - v1.Summary = (function () { - /** - * Properties of a Summary. - * @memberof opentelemetry.proto.metrics.v1 - * @interface ISummary - * @property {Array.|null} [dataPoints] Summary dataPoints - */ - /** - * Constructs a new Summary. - * @memberof opentelemetry.proto.metrics.v1 - * @classdesc Represents a Summary. - * @implements ISummary - * @constructor - * @param {opentelemetry.proto.metrics.v1.ISummary=} [properties] Properties to set - */ - function Summary(properties) { - this.dataPoints = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * Summary dataPoints. - * @member {Array.} dataPoints - * @memberof opentelemetry.proto.metrics.v1.Summary - * @instance - */ - Summary.prototype.dataPoints = $util.emptyArray; - /** - * Creates a new Summary instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.metrics.v1.Summary - * @static - * @param {opentelemetry.proto.metrics.v1.ISummary=} [properties] Properties to set - * @returns {opentelemetry.proto.metrics.v1.Summary} Summary instance - */ - Summary.create = function create(properties) { - return new Summary(properties); - }; - /** - * Encodes the specified Summary message. Does not implicitly {@link opentelemetry.proto.metrics.v1.Summary.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.metrics.v1.Summary - * @static - * @param {opentelemetry.proto.metrics.v1.ISummary} message Summary message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Summary.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.dataPoints != null && message.dataPoints.length) - for (var i = 0; i < message.dataPoints.length; ++i) - $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.encode(message.dataPoints[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - return writer; - }; - /** - * Encodes the specified Summary message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.Summary.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.metrics.v1.Summary - * @static - * @param {opentelemetry.proto.metrics.v1.ISummary} message Summary message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Summary.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a Summary message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.metrics.v1.Summary - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.metrics.v1.Summary} Summary - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Summary.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Summary(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - if (!(message.dataPoints && message.dataPoints.length)) - message.dataPoints = []; - message.dataPoints.push($root.opentelemetry.proto.metrics.v1.SummaryDataPoint.decode(reader, reader.uint32())); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a Summary message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.metrics.v1.Summary - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.metrics.v1.Summary} Summary - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Summary.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a Summary message. - * @function verify - * @memberof opentelemetry.proto.metrics.v1.Summary - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Summary.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.dataPoints != null && message.hasOwnProperty("dataPoints")) { - if (!Array.isArray(message.dataPoints)) - return "dataPoints: array expected"; - for (var i = 0; i < message.dataPoints.length; ++i) { - var error = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.verify(message.dataPoints[i]); - if (error) - return "dataPoints." + error; - } - } - return null; - }; - /** - * Creates a Summary message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.metrics.v1.Summary - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.metrics.v1.Summary} Summary - */ - Summary.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.metrics.v1.Summary) - return object; - var message = new $root.opentelemetry.proto.metrics.v1.Summary(); - if (object.dataPoints) { - if (!Array.isArray(object.dataPoints)) - throw TypeError(".opentelemetry.proto.metrics.v1.Summary.dataPoints: array expected"); - message.dataPoints = []; - for (var i = 0; i < object.dataPoints.length; ++i) { - if (typeof object.dataPoints[i] !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.Summary.dataPoints: object expected"); - message.dataPoints[i] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.fromObject(object.dataPoints[i]); - } - } - return message; - }; - /** - * Creates a plain object from a Summary message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.metrics.v1.Summary - * @static - * @param {opentelemetry.proto.metrics.v1.Summary} message Summary - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Summary.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.dataPoints = []; - if (message.dataPoints && message.dataPoints.length) { - object.dataPoints = []; - for (var j = 0; j < message.dataPoints.length; ++j) - object.dataPoints[j] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.toObject(message.dataPoints[j], options); - } - return object; - }; - /** - * Converts this Summary to JSON. - * @function toJSON - * @memberof opentelemetry.proto.metrics.v1.Summary - * @instance - * @returns {Object.} JSON object - */ - Summary.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for Summary - * @function getTypeUrl - * @memberof opentelemetry.proto.metrics.v1.Summary - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Summary.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Summary"; - }; - return Summary; - })(); - /** - * AggregationTemporality enum. - * @name opentelemetry.proto.metrics.v1.AggregationTemporality - * @enum {number} - * @property {number} AGGREGATION_TEMPORALITY_UNSPECIFIED=0 AGGREGATION_TEMPORALITY_UNSPECIFIED value - * @property {number} AGGREGATION_TEMPORALITY_DELTA=1 AGGREGATION_TEMPORALITY_DELTA value - * @property {number} AGGREGATION_TEMPORALITY_CUMULATIVE=2 AGGREGATION_TEMPORALITY_CUMULATIVE value - */ - v1.AggregationTemporality = (function () { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "AGGREGATION_TEMPORALITY_UNSPECIFIED"] = 0; - values[valuesById[1] = "AGGREGATION_TEMPORALITY_DELTA"] = 1; - values[valuesById[2] = "AGGREGATION_TEMPORALITY_CUMULATIVE"] = 2; - return values; - })(); - /** - * DataPointFlags enum. - * @name opentelemetry.proto.metrics.v1.DataPointFlags - * @enum {number} - * @property {number} DATA_POINT_FLAGS_DO_NOT_USE=0 DATA_POINT_FLAGS_DO_NOT_USE value - * @property {number} DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK=1 DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK value - */ - v1.DataPointFlags = (function () { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "DATA_POINT_FLAGS_DO_NOT_USE"] = 0; - values[valuesById[1] = "DATA_POINT_FLAGS_NO_RECORDED_VALUE_MASK"] = 1; - return values; - })(); - v1.NumberDataPoint = (function () { - /** - * Properties of a NumberDataPoint. - * @memberof opentelemetry.proto.metrics.v1 - * @interface INumberDataPoint - * @property {Array.|null} [attributes] NumberDataPoint attributes - * @property {number|Long|null} [startTimeUnixNano] NumberDataPoint startTimeUnixNano - * @property {number|Long|null} [timeUnixNano] NumberDataPoint timeUnixNano - * @property {number|null} [asDouble] NumberDataPoint asDouble - * @property {number|Long|null} [asInt] NumberDataPoint asInt - * @property {Array.|null} [exemplars] NumberDataPoint exemplars - * @property {number|null} [flags] NumberDataPoint flags - */ - /** - * Constructs a new NumberDataPoint. - * @memberof opentelemetry.proto.metrics.v1 - * @classdesc Represents a NumberDataPoint. - * @implements INumberDataPoint - * @constructor - * @param {opentelemetry.proto.metrics.v1.INumberDataPoint=} [properties] Properties to set - */ - function NumberDataPoint(properties) { - this.attributes = []; - this.exemplars = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * NumberDataPoint attributes. - * @member {Array.} attributes - * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint - * @instance - */ - NumberDataPoint.prototype.attributes = $util.emptyArray; - /** - * NumberDataPoint startTimeUnixNano. - * @member {number|Long|null|undefined} startTimeUnixNano - * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint - * @instance - */ - NumberDataPoint.prototype.startTimeUnixNano = null; - /** - * NumberDataPoint timeUnixNano. - * @member {number|Long|null|undefined} timeUnixNano - * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint - * @instance - */ - NumberDataPoint.prototype.timeUnixNano = null; - /** - * NumberDataPoint asDouble. - * @member {number|null|undefined} asDouble - * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint - * @instance - */ - NumberDataPoint.prototype.asDouble = null; - /** - * NumberDataPoint asInt. - * @member {number|Long|null|undefined} asInt - * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint - * @instance - */ - NumberDataPoint.prototype.asInt = null; - /** - * NumberDataPoint exemplars. - * @member {Array.} exemplars - * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint - * @instance - */ - NumberDataPoint.prototype.exemplars = $util.emptyArray; - /** - * NumberDataPoint flags. - * @member {number|null|undefined} flags - * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint - * @instance - */ - NumberDataPoint.prototype.flags = null; - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - /** - * NumberDataPoint value. - * @member {"asDouble"|"asInt"|undefined} value - * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint - * @instance - */ - Object.defineProperty(NumberDataPoint.prototype, "value", { - get: $util.oneOfGetter($oneOfFields = ["asDouble", "asInt"]), - set: $util.oneOfSetter($oneOfFields) - }); - /** - * Creates a new NumberDataPoint instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint - * @static - * @param {opentelemetry.proto.metrics.v1.INumberDataPoint=} [properties] Properties to set - * @returns {opentelemetry.proto.metrics.v1.NumberDataPoint} NumberDataPoint instance - */ - NumberDataPoint.create = function create(properties) { - return new NumberDataPoint(properties); - }; - /** - * Encodes the specified NumberDataPoint message. Does not implicitly {@link opentelemetry.proto.metrics.v1.NumberDataPoint.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint - * @static - * @param {opentelemetry.proto.metrics.v1.INumberDataPoint} message NumberDataPoint message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - NumberDataPoint.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.startTimeUnixNano != null && Object.hasOwnProperty.call(message, "startTimeUnixNano")) - writer.uint32(/* id 2, wireType 1 =*/ 17).fixed64(message.startTimeUnixNano); - if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano")) - writer.uint32(/* id 3, wireType 1 =*/ 25).fixed64(message.timeUnixNano); - if (message.asDouble != null && Object.hasOwnProperty.call(message, "asDouble")) - writer.uint32(/* id 4, wireType 1 =*/ 33).double(message.asDouble); - if (message.exemplars != null && message.exemplars.length) - for (var i = 0; i < message.exemplars.length; ++i) - $root.opentelemetry.proto.metrics.v1.Exemplar.encode(message.exemplars[i], writer.uint32(/* id 5, wireType 2 =*/ 42).fork()).ldelim(); - if (message.asInt != null && Object.hasOwnProperty.call(message, "asInt")) - writer.uint32(/* id 6, wireType 1 =*/ 49).sfixed64(message.asInt); - if (message.attributes != null && message.attributes.length) - for (var i = 0; i < message.attributes.length; ++i) - $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(/* id 7, wireType 2 =*/ 58).fork()).ldelim(); - if (message.flags != null && Object.hasOwnProperty.call(message, "flags")) - writer.uint32(/* id 8, wireType 0 =*/ 64).uint32(message.flags); - return writer; - }; - /** - * Encodes the specified NumberDataPoint message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.NumberDataPoint.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint - * @static - * @param {opentelemetry.proto.metrics.v1.INumberDataPoint} message NumberDataPoint message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - NumberDataPoint.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a NumberDataPoint message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.metrics.v1.NumberDataPoint} NumberDataPoint - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - NumberDataPoint.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.NumberDataPoint(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 7: { - if (!(message.attributes && message.attributes.length)) - message.attributes = []; - message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); - break; - } - case 2: { - message.startTimeUnixNano = reader.fixed64(); - break; - } - case 3: { - message.timeUnixNano = reader.fixed64(); - break; - } - case 4: { - message.asDouble = reader.double(); - break; - } - case 6: { - message.asInt = reader.sfixed64(); - break; - } - case 5: { - if (!(message.exemplars && message.exemplars.length)) - message.exemplars = []; - message.exemplars.push($root.opentelemetry.proto.metrics.v1.Exemplar.decode(reader, reader.uint32())); - break; - } - case 8: { - message.flags = reader.uint32(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a NumberDataPoint message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.metrics.v1.NumberDataPoint} NumberDataPoint - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - NumberDataPoint.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a NumberDataPoint message. - * @function verify - * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - NumberDataPoint.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.attributes != null && message.hasOwnProperty("attributes")) { - if (!Array.isArray(message.attributes)) - return "attributes: array expected"; - for (var i = 0; i < message.attributes.length; ++i) { - var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]); - if (error) - return "attributes." + error; - } - } - if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) - if (!$util.isInteger(message.startTimeUnixNano) && !(message.startTimeUnixNano && $util.isInteger(message.startTimeUnixNano.low) && $util.isInteger(message.startTimeUnixNano.high))) - return "startTimeUnixNano: integer|Long expected"; - if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) - if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high))) - return "timeUnixNano: integer|Long expected"; - if (message.asDouble != null && message.hasOwnProperty("asDouble")) { - properties.value = 1; - if (typeof message.asDouble !== "number") - return "asDouble: number expected"; - } - if (message.asInt != null && message.hasOwnProperty("asInt")) { - if (properties.value === 1) - return "value: multiple values"; - properties.value = 1; - if (!$util.isInteger(message.asInt) && !(message.asInt && $util.isInteger(message.asInt.low) && $util.isInteger(message.asInt.high))) - return "asInt: integer|Long expected"; - } - if (message.exemplars != null && message.hasOwnProperty("exemplars")) { - if (!Array.isArray(message.exemplars)) - return "exemplars: array expected"; - for (var i = 0; i < message.exemplars.length; ++i) { - var error = $root.opentelemetry.proto.metrics.v1.Exemplar.verify(message.exemplars[i]); - if (error) - return "exemplars." + error; - } - } - if (message.flags != null && message.hasOwnProperty("flags")) - if (!$util.isInteger(message.flags)) - return "flags: integer expected"; - return null; - }; - /** - * Creates a NumberDataPoint message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.metrics.v1.NumberDataPoint} NumberDataPoint - */ - NumberDataPoint.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.metrics.v1.NumberDataPoint) - return object; - var message = new $root.opentelemetry.proto.metrics.v1.NumberDataPoint(); - if (object.attributes) { - if (!Array.isArray(object.attributes)) - throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.attributes: array expected"); - message.attributes = []; - for (var i = 0; i < object.attributes.length; ++i) { - if (typeof object.attributes[i] !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.attributes: object expected"); - message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]); - } - } - if (object.startTimeUnixNano != null) - if ($util.Long) - (message.startTimeUnixNano = $util.Long.fromValue(object.startTimeUnixNano)).unsigned = false; - else if (typeof object.startTimeUnixNano === "string") - message.startTimeUnixNano = parseInt(object.startTimeUnixNano, 10); - else if (typeof object.startTimeUnixNano === "number") - message.startTimeUnixNano = object.startTimeUnixNano; - else if (typeof object.startTimeUnixNano === "object") - message.startTimeUnixNano = new $util.LongBits(object.startTimeUnixNano.low >>> 0, object.startTimeUnixNano.high >>> 0).toNumber(); - if (object.timeUnixNano != null) - if ($util.Long) - (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false; - else if (typeof object.timeUnixNano === "string") - message.timeUnixNano = parseInt(object.timeUnixNano, 10); - else if (typeof object.timeUnixNano === "number") - message.timeUnixNano = object.timeUnixNano; - else if (typeof object.timeUnixNano === "object") - message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber(); - if (object.asDouble != null) - message.asDouble = Number(object.asDouble); - if (object.asInt != null) - if ($util.Long) - (message.asInt = $util.Long.fromValue(object.asInt)).unsigned = false; - else if (typeof object.asInt === "string") - message.asInt = parseInt(object.asInt, 10); - else if (typeof object.asInt === "number") - message.asInt = object.asInt; - else if (typeof object.asInt === "object") - message.asInt = new $util.LongBits(object.asInt.low >>> 0, object.asInt.high >>> 0).toNumber(); - if (object.exemplars) { - if (!Array.isArray(object.exemplars)) - throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.exemplars: array expected"); - message.exemplars = []; - for (var i = 0; i < object.exemplars.length; ++i) { - if (typeof object.exemplars[i] !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.NumberDataPoint.exemplars: object expected"); - message.exemplars[i] = $root.opentelemetry.proto.metrics.v1.Exemplar.fromObject(object.exemplars[i]); - } - } - if (object.flags != null) - message.flags = object.flags >>> 0; - return message; - }; - /** - * Creates a plain object from a NumberDataPoint message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint - * @static - * @param {opentelemetry.proto.metrics.v1.NumberDataPoint} message NumberDataPoint - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - NumberDataPoint.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) { - object.exemplars = []; - object.attributes = []; - } - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.startTimeUnixNano = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.timeUnixNano = options.longs === String ? "0" : 0; - object.flags = 0; - } - if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) - if (typeof message.startTimeUnixNano === "number") - object.startTimeUnixNano = options.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano; - else - object.startTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.startTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.startTimeUnixNano.low >>> 0, message.startTimeUnixNano.high >>> 0).toNumber() : message.startTimeUnixNano; - if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) - if (typeof message.timeUnixNano === "number") - object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano; - else - object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano; - if (message.asDouble != null && message.hasOwnProperty("asDouble")) { - object.asDouble = options.json && !isFinite(message.asDouble) ? String(message.asDouble) : message.asDouble; - if (options.oneofs) - object.value = "asDouble"; - } - if (message.exemplars && message.exemplars.length) { - object.exemplars = []; - for (var j = 0; j < message.exemplars.length; ++j) - object.exemplars[j] = $root.opentelemetry.proto.metrics.v1.Exemplar.toObject(message.exemplars[j], options); - } - if (message.asInt != null && message.hasOwnProperty("asInt")) { - if (typeof message.asInt === "number") - object.asInt = options.longs === String ? String(message.asInt) : message.asInt; - else - object.asInt = options.longs === String ? $util.Long.prototype.toString.call(message.asInt) : options.longs === Number ? new $util.LongBits(message.asInt.low >>> 0, message.asInt.high >>> 0).toNumber() : message.asInt; - if (options.oneofs) - object.value = "asInt"; - } - if (message.attributes && message.attributes.length) { - object.attributes = []; - for (var j = 0; j < message.attributes.length; ++j) - object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options); - } - if (message.flags != null && message.hasOwnProperty("flags")) - object.flags = message.flags; - return object; - }; - /** - * Converts this NumberDataPoint to JSON. - * @function toJSON - * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint - * @instance - * @returns {Object.} JSON object - */ - NumberDataPoint.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for NumberDataPoint - * @function getTypeUrl - * @memberof opentelemetry.proto.metrics.v1.NumberDataPoint - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - NumberDataPoint.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.NumberDataPoint"; - }; - return NumberDataPoint; - })(); - v1.HistogramDataPoint = (function () { - /** - * Properties of a HistogramDataPoint. - * @memberof opentelemetry.proto.metrics.v1 - * @interface IHistogramDataPoint - * @property {Array.|null} [attributes] HistogramDataPoint attributes - * @property {number|Long|null} [startTimeUnixNano] HistogramDataPoint startTimeUnixNano - * @property {number|Long|null} [timeUnixNano] HistogramDataPoint timeUnixNano - * @property {number|Long|null} [count] HistogramDataPoint count - * @property {number|null} [sum] HistogramDataPoint sum - * @property {Array.|null} [bucketCounts] HistogramDataPoint bucketCounts - * @property {Array.|null} [explicitBounds] HistogramDataPoint explicitBounds - * @property {Array.|null} [exemplars] HistogramDataPoint exemplars - * @property {number|null} [flags] HistogramDataPoint flags - * @property {number|null} [min] HistogramDataPoint min - * @property {number|null} [max] HistogramDataPoint max - */ - /** - * Constructs a new HistogramDataPoint. - * @memberof opentelemetry.proto.metrics.v1 - * @classdesc Represents a HistogramDataPoint. - * @implements IHistogramDataPoint - * @constructor - * @param {opentelemetry.proto.metrics.v1.IHistogramDataPoint=} [properties] Properties to set - */ - function HistogramDataPoint(properties) { - this.attributes = []; - this.bucketCounts = []; - this.explicitBounds = []; - this.exemplars = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * HistogramDataPoint attributes. - * @member {Array.} attributes - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @instance - */ - HistogramDataPoint.prototype.attributes = $util.emptyArray; - /** - * HistogramDataPoint startTimeUnixNano. - * @member {number|Long|null|undefined} startTimeUnixNano - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @instance - */ - HistogramDataPoint.prototype.startTimeUnixNano = null; - /** - * HistogramDataPoint timeUnixNano. - * @member {number|Long|null|undefined} timeUnixNano - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @instance - */ - HistogramDataPoint.prototype.timeUnixNano = null; - /** - * HistogramDataPoint count. - * @member {number|Long|null|undefined} count - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @instance - */ - HistogramDataPoint.prototype.count = null; - /** - * HistogramDataPoint sum. - * @member {number|null|undefined} sum - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @instance - */ - HistogramDataPoint.prototype.sum = null; - /** - * HistogramDataPoint bucketCounts. - * @member {Array.} bucketCounts - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @instance - */ - HistogramDataPoint.prototype.bucketCounts = $util.emptyArray; - /** - * HistogramDataPoint explicitBounds. - * @member {Array.} explicitBounds - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @instance - */ - HistogramDataPoint.prototype.explicitBounds = $util.emptyArray; - /** - * HistogramDataPoint exemplars. - * @member {Array.} exemplars - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @instance - */ - HistogramDataPoint.prototype.exemplars = $util.emptyArray; - /** - * HistogramDataPoint flags. - * @member {number|null|undefined} flags - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @instance - */ - HistogramDataPoint.prototype.flags = null; - /** - * HistogramDataPoint min. - * @member {number|null|undefined} min - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @instance - */ - HistogramDataPoint.prototype.min = null; - /** - * HistogramDataPoint max. - * @member {number|null|undefined} max - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @instance - */ - HistogramDataPoint.prototype.max = null; - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - /** - * HistogramDataPoint _sum. - * @member {"sum"|undefined} _sum - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @instance - */ - Object.defineProperty(HistogramDataPoint.prototype, "_sum", { - get: $util.oneOfGetter($oneOfFields = ["sum"]), - set: $util.oneOfSetter($oneOfFields) - }); - /** - * HistogramDataPoint _min. - * @member {"min"|undefined} _min - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @instance - */ - Object.defineProperty(HistogramDataPoint.prototype, "_min", { - get: $util.oneOfGetter($oneOfFields = ["min"]), - set: $util.oneOfSetter($oneOfFields) - }); - /** - * HistogramDataPoint _max. - * @member {"max"|undefined} _max - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @instance - */ - Object.defineProperty(HistogramDataPoint.prototype, "_max", { - get: $util.oneOfGetter($oneOfFields = ["max"]), - set: $util.oneOfSetter($oneOfFields) - }); - /** - * Creates a new HistogramDataPoint instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @static - * @param {opentelemetry.proto.metrics.v1.IHistogramDataPoint=} [properties] Properties to set - * @returns {opentelemetry.proto.metrics.v1.HistogramDataPoint} HistogramDataPoint instance - */ - HistogramDataPoint.create = function create(properties) { - return new HistogramDataPoint(properties); - }; - /** - * Encodes the specified HistogramDataPoint message. Does not implicitly {@link opentelemetry.proto.metrics.v1.HistogramDataPoint.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @static - * @param {opentelemetry.proto.metrics.v1.IHistogramDataPoint} message HistogramDataPoint message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - HistogramDataPoint.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.startTimeUnixNano != null && Object.hasOwnProperty.call(message, "startTimeUnixNano")) - writer.uint32(/* id 2, wireType 1 =*/ 17).fixed64(message.startTimeUnixNano); - if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano")) - writer.uint32(/* id 3, wireType 1 =*/ 25).fixed64(message.timeUnixNano); - if (message.count != null && Object.hasOwnProperty.call(message, "count")) - writer.uint32(/* id 4, wireType 1 =*/ 33).fixed64(message.count); - if (message.sum != null && Object.hasOwnProperty.call(message, "sum")) - writer.uint32(/* id 5, wireType 1 =*/ 41).double(message.sum); - if (message.bucketCounts != null && message.bucketCounts.length) { - writer.uint32(/* id 6, wireType 2 =*/ 50).fork(); - for (var i = 0; i < message.bucketCounts.length; ++i) - writer.fixed64(message.bucketCounts[i]); - writer.ldelim(); - } - if (message.explicitBounds != null && message.explicitBounds.length) { - writer.uint32(/* id 7, wireType 2 =*/ 58).fork(); - for (var i = 0; i < message.explicitBounds.length; ++i) - writer.double(message.explicitBounds[i]); - writer.ldelim(); - } - if (message.exemplars != null && message.exemplars.length) - for (var i = 0; i < message.exemplars.length; ++i) - $root.opentelemetry.proto.metrics.v1.Exemplar.encode(message.exemplars[i], writer.uint32(/* id 8, wireType 2 =*/ 66).fork()).ldelim(); - if (message.attributes != null && message.attributes.length) - for (var i = 0; i < message.attributes.length; ++i) - $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(/* id 9, wireType 2 =*/ 74).fork()).ldelim(); - if (message.flags != null && Object.hasOwnProperty.call(message, "flags")) - writer.uint32(/* id 10, wireType 0 =*/ 80).uint32(message.flags); - if (message.min != null && Object.hasOwnProperty.call(message, "min")) - writer.uint32(/* id 11, wireType 1 =*/ 89).double(message.min); - if (message.max != null && Object.hasOwnProperty.call(message, "max")) - writer.uint32(/* id 12, wireType 1 =*/ 97).double(message.max); - return writer; - }; - /** - * Encodes the specified HistogramDataPoint message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.HistogramDataPoint.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @static - * @param {opentelemetry.proto.metrics.v1.IHistogramDataPoint} message HistogramDataPoint message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - HistogramDataPoint.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a HistogramDataPoint message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.metrics.v1.HistogramDataPoint} HistogramDataPoint - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - HistogramDataPoint.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.HistogramDataPoint(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 9: { - if (!(message.attributes && message.attributes.length)) - message.attributes = []; - message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); - break; - } - case 2: { - message.startTimeUnixNano = reader.fixed64(); - break; - } - case 3: { - message.timeUnixNano = reader.fixed64(); - break; - } - case 4: { - message.count = reader.fixed64(); - break; - } - case 5: { - message.sum = reader.double(); - break; - } - case 6: { - if (!(message.bucketCounts && message.bucketCounts.length)) - message.bucketCounts = []; - if ((tag & 7) === 2) { - var end2 = reader.uint32() + reader.pos; - while (reader.pos < end2) - message.bucketCounts.push(reader.fixed64()); - } - else - message.bucketCounts.push(reader.fixed64()); - break; - } - case 7: { - if (!(message.explicitBounds && message.explicitBounds.length)) - message.explicitBounds = []; - if ((tag & 7) === 2) { - var end2 = reader.uint32() + reader.pos; - while (reader.pos < end2) - message.explicitBounds.push(reader.double()); - } - else - message.explicitBounds.push(reader.double()); - break; - } - case 8: { - if (!(message.exemplars && message.exemplars.length)) - message.exemplars = []; - message.exemplars.push($root.opentelemetry.proto.metrics.v1.Exemplar.decode(reader, reader.uint32())); - break; - } - case 10: { - message.flags = reader.uint32(); - break; - } - case 11: { - message.min = reader.double(); - break; - } - case 12: { - message.max = reader.double(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a HistogramDataPoint message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.metrics.v1.HistogramDataPoint} HistogramDataPoint - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - HistogramDataPoint.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a HistogramDataPoint message. - * @function verify - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - HistogramDataPoint.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.attributes != null && message.hasOwnProperty("attributes")) { - if (!Array.isArray(message.attributes)) - return "attributes: array expected"; - for (var i = 0; i < message.attributes.length; ++i) { - var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]); - if (error) - return "attributes." + error; - } - } - if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) - if (!$util.isInteger(message.startTimeUnixNano) && !(message.startTimeUnixNano && $util.isInteger(message.startTimeUnixNano.low) && $util.isInteger(message.startTimeUnixNano.high))) - return "startTimeUnixNano: integer|Long expected"; - if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) - if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high))) - return "timeUnixNano: integer|Long expected"; - if (message.count != null && message.hasOwnProperty("count")) - if (!$util.isInteger(message.count) && !(message.count && $util.isInteger(message.count.low) && $util.isInteger(message.count.high))) - return "count: integer|Long expected"; - if (message.sum != null && message.hasOwnProperty("sum")) { - properties._sum = 1; - if (typeof message.sum !== "number") - return "sum: number expected"; - } - if (message.bucketCounts != null && message.hasOwnProperty("bucketCounts")) { - if (!Array.isArray(message.bucketCounts)) - return "bucketCounts: array expected"; - for (var i = 0; i < message.bucketCounts.length; ++i) - if (!$util.isInteger(message.bucketCounts[i]) && !(message.bucketCounts[i] && $util.isInteger(message.bucketCounts[i].low) && $util.isInteger(message.bucketCounts[i].high))) - return "bucketCounts: integer|Long[] expected"; - } - if (message.explicitBounds != null && message.hasOwnProperty("explicitBounds")) { - if (!Array.isArray(message.explicitBounds)) - return "explicitBounds: array expected"; - for (var i = 0; i < message.explicitBounds.length; ++i) - if (typeof message.explicitBounds[i] !== "number") - return "explicitBounds: number[] expected"; - } - if (message.exemplars != null && message.hasOwnProperty("exemplars")) { - if (!Array.isArray(message.exemplars)) - return "exemplars: array expected"; - for (var i = 0; i < message.exemplars.length; ++i) { - var error = $root.opentelemetry.proto.metrics.v1.Exemplar.verify(message.exemplars[i]); - if (error) - return "exemplars." + error; - } - } - if (message.flags != null && message.hasOwnProperty("flags")) - if (!$util.isInteger(message.flags)) - return "flags: integer expected"; - if (message.min != null && message.hasOwnProperty("min")) { - properties._min = 1; - if (typeof message.min !== "number") - return "min: number expected"; - } - if (message.max != null && message.hasOwnProperty("max")) { - properties._max = 1; - if (typeof message.max !== "number") - return "max: number expected"; - } - return null; - }; - /** - * Creates a HistogramDataPoint message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.metrics.v1.HistogramDataPoint} HistogramDataPoint - */ - HistogramDataPoint.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.metrics.v1.HistogramDataPoint) - return object; - var message = new $root.opentelemetry.proto.metrics.v1.HistogramDataPoint(); - if (object.attributes) { - if (!Array.isArray(object.attributes)) - throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.attributes: array expected"); - message.attributes = []; - for (var i = 0; i < object.attributes.length; ++i) { - if (typeof object.attributes[i] !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.attributes: object expected"); - message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]); - } - } - if (object.startTimeUnixNano != null) - if ($util.Long) - (message.startTimeUnixNano = $util.Long.fromValue(object.startTimeUnixNano)).unsigned = false; - else if (typeof object.startTimeUnixNano === "string") - message.startTimeUnixNano = parseInt(object.startTimeUnixNano, 10); - else if (typeof object.startTimeUnixNano === "number") - message.startTimeUnixNano = object.startTimeUnixNano; - else if (typeof object.startTimeUnixNano === "object") - message.startTimeUnixNano = new $util.LongBits(object.startTimeUnixNano.low >>> 0, object.startTimeUnixNano.high >>> 0).toNumber(); - if (object.timeUnixNano != null) - if ($util.Long) - (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false; - else if (typeof object.timeUnixNano === "string") - message.timeUnixNano = parseInt(object.timeUnixNano, 10); - else if (typeof object.timeUnixNano === "number") - message.timeUnixNano = object.timeUnixNano; - else if (typeof object.timeUnixNano === "object") - message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber(); - if (object.count != null) - if ($util.Long) - (message.count = $util.Long.fromValue(object.count)).unsigned = false; - else if (typeof object.count === "string") - message.count = parseInt(object.count, 10); - else if (typeof object.count === "number") - message.count = object.count; - else if (typeof object.count === "object") - message.count = new $util.LongBits(object.count.low >>> 0, object.count.high >>> 0).toNumber(); - if (object.sum != null) - message.sum = Number(object.sum); - if (object.bucketCounts) { - if (!Array.isArray(object.bucketCounts)) - throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.bucketCounts: array expected"); - message.bucketCounts = []; - for (var i = 0; i < object.bucketCounts.length; ++i) - if ($util.Long) - (message.bucketCounts[i] = $util.Long.fromValue(object.bucketCounts[i])).unsigned = false; - else if (typeof object.bucketCounts[i] === "string") - message.bucketCounts[i] = parseInt(object.bucketCounts[i], 10); - else if (typeof object.bucketCounts[i] === "number") - message.bucketCounts[i] = object.bucketCounts[i]; - else if (typeof object.bucketCounts[i] === "object") - message.bucketCounts[i] = new $util.LongBits(object.bucketCounts[i].low >>> 0, object.bucketCounts[i].high >>> 0).toNumber(); - } - if (object.explicitBounds) { - if (!Array.isArray(object.explicitBounds)) - throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.explicitBounds: array expected"); - message.explicitBounds = []; - for (var i = 0; i < object.explicitBounds.length; ++i) - message.explicitBounds[i] = Number(object.explicitBounds[i]); - } - if (object.exemplars) { - if (!Array.isArray(object.exemplars)) - throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.exemplars: array expected"); - message.exemplars = []; - for (var i = 0; i < object.exemplars.length; ++i) { - if (typeof object.exemplars[i] !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.HistogramDataPoint.exemplars: object expected"); - message.exemplars[i] = $root.opentelemetry.proto.metrics.v1.Exemplar.fromObject(object.exemplars[i]); - } - } - if (object.flags != null) - message.flags = object.flags >>> 0; - if (object.min != null) - message.min = Number(object.min); - if (object.max != null) - message.max = Number(object.max); - return message; - }; - /** - * Creates a plain object from a HistogramDataPoint message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @static - * @param {opentelemetry.proto.metrics.v1.HistogramDataPoint} message HistogramDataPoint - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - HistogramDataPoint.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) { - object.bucketCounts = []; - object.explicitBounds = []; - object.exemplars = []; - object.attributes = []; - } - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.startTimeUnixNano = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.timeUnixNano = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.count = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.count = options.longs === String ? "0" : 0; - object.flags = 0; - } - if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) - if (typeof message.startTimeUnixNano === "number") - object.startTimeUnixNano = options.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano; - else - object.startTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.startTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.startTimeUnixNano.low >>> 0, message.startTimeUnixNano.high >>> 0).toNumber() : message.startTimeUnixNano; - if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) - if (typeof message.timeUnixNano === "number") - object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano; - else - object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano; - if (message.count != null && message.hasOwnProperty("count")) - if (typeof message.count === "number") - object.count = options.longs === String ? String(message.count) : message.count; - else - object.count = options.longs === String ? $util.Long.prototype.toString.call(message.count) : options.longs === Number ? new $util.LongBits(message.count.low >>> 0, message.count.high >>> 0).toNumber() : message.count; - if (message.sum != null && message.hasOwnProperty("sum")) { - object.sum = options.json && !isFinite(message.sum) ? String(message.sum) : message.sum; - if (options.oneofs) - object._sum = "sum"; - } - if (message.bucketCounts && message.bucketCounts.length) { - object.bucketCounts = []; - for (var j = 0; j < message.bucketCounts.length; ++j) - if (typeof message.bucketCounts[j] === "number") - object.bucketCounts[j] = options.longs === String ? String(message.bucketCounts[j]) : message.bucketCounts[j]; - else - object.bucketCounts[j] = options.longs === String ? $util.Long.prototype.toString.call(message.bucketCounts[j]) : options.longs === Number ? new $util.LongBits(message.bucketCounts[j].low >>> 0, message.bucketCounts[j].high >>> 0).toNumber() : message.bucketCounts[j]; - } - if (message.explicitBounds && message.explicitBounds.length) { - object.explicitBounds = []; - for (var j = 0; j < message.explicitBounds.length; ++j) - object.explicitBounds[j] = options.json && !isFinite(message.explicitBounds[j]) ? String(message.explicitBounds[j]) : message.explicitBounds[j]; - } - if (message.exemplars && message.exemplars.length) { - object.exemplars = []; - for (var j = 0; j < message.exemplars.length; ++j) - object.exemplars[j] = $root.opentelemetry.proto.metrics.v1.Exemplar.toObject(message.exemplars[j], options); - } - if (message.attributes && message.attributes.length) { - object.attributes = []; - for (var j = 0; j < message.attributes.length; ++j) - object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options); - } - if (message.flags != null && message.hasOwnProperty("flags")) - object.flags = message.flags; - if (message.min != null && message.hasOwnProperty("min")) { - object.min = options.json && !isFinite(message.min) ? String(message.min) : message.min; - if (options.oneofs) - object._min = "min"; - } - if (message.max != null && message.hasOwnProperty("max")) { - object.max = options.json && !isFinite(message.max) ? String(message.max) : message.max; - if (options.oneofs) - object._max = "max"; - } - return object; - }; - /** - * Converts this HistogramDataPoint to JSON. - * @function toJSON - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @instance - * @returns {Object.} JSON object - */ - HistogramDataPoint.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for HistogramDataPoint - * @function getTypeUrl - * @memberof opentelemetry.proto.metrics.v1.HistogramDataPoint - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - HistogramDataPoint.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.HistogramDataPoint"; - }; - return HistogramDataPoint; - })(); - v1.ExponentialHistogramDataPoint = (function () { - /** - * Properties of an ExponentialHistogramDataPoint. - * @memberof opentelemetry.proto.metrics.v1 - * @interface IExponentialHistogramDataPoint - * @property {Array.|null} [attributes] ExponentialHistogramDataPoint attributes - * @property {number|Long|null} [startTimeUnixNano] ExponentialHistogramDataPoint startTimeUnixNano - * @property {number|Long|null} [timeUnixNano] ExponentialHistogramDataPoint timeUnixNano - * @property {number|Long|null} [count] ExponentialHistogramDataPoint count - * @property {number|null} [sum] ExponentialHistogramDataPoint sum - * @property {number|null} [scale] ExponentialHistogramDataPoint scale - * @property {number|Long|null} [zeroCount] ExponentialHistogramDataPoint zeroCount - * @property {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.IBuckets|null} [positive] ExponentialHistogramDataPoint positive - * @property {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.IBuckets|null} [negative] ExponentialHistogramDataPoint negative - * @property {number|null} [flags] ExponentialHistogramDataPoint flags - * @property {Array.|null} [exemplars] ExponentialHistogramDataPoint exemplars - * @property {number|null} [min] ExponentialHistogramDataPoint min - * @property {number|null} [max] ExponentialHistogramDataPoint max - * @property {number|null} [zeroThreshold] ExponentialHistogramDataPoint zeroThreshold - */ - /** - * Constructs a new ExponentialHistogramDataPoint. - * @memberof opentelemetry.proto.metrics.v1 - * @classdesc Represents an ExponentialHistogramDataPoint. - * @implements IExponentialHistogramDataPoint - * @constructor - * @param {opentelemetry.proto.metrics.v1.IExponentialHistogramDataPoint=} [properties] Properties to set - */ - function ExponentialHistogramDataPoint(properties) { - this.attributes = []; - this.exemplars = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * ExponentialHistogramDataPoint attributes. - * @member {Array.} attributes - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @instance - */ - ExponentialHistogramDataPoint.prototype.attributes = $util.emptyArray; - /** - * ExponentialHistogramDataPoint startTimeUnixNano. - * @member {number|Long|null|undefined} startTimeUnixNano - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @instance - */ - ExponentialHistogramDataPoint.prototype.startTimeUnixNano = null; - /** - * ExponentialHistogramDataPoint timeUnixNano. - * @member {number|Long|null|undefined} timeUnixNano - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @instance - */ - ExponentialHistogramDataPoint.prototype.timeUnixNano = null; - /** - * ExponentialHistogramDataPoint count. - * @member {number|Long|null|undefined} count - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @instance - */ - ExponentialHistogramDataPoint.prototype.count = null; - /** - * ExponentialHistogramDataPoint sum. - * @member {number|null|undefined} sum - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @instance - */ - ExponentialHistogramDataPoint.prototype.sum = null; - /** - * ExponentialHistogramDataPoint scale. - * @member {number|null|undefined} scale - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @instance - */ - ExponentialHistogramDataPoint.prototype.scale = null; - /** - * ExponentialHistogramDataPoint zeroCount. - * @member {number|Long|null|undefined} zeroCount - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @instance - */ - ExponentialHistogramDataPoint.prototype.zeroCount = null; - /** - * ExponentialHistogramDataPoint positive. - * @member {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.IBuckets|null|undefined} positive - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @instance - */ - ExponentialHistogramDataPoint.prototype.positive = null; - /** - * ExponentialHistogramDataPoint negative. - * @member {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.IBuckets|null|undefined} negative - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @instance - */ - ExponentialHistogramDataPoint.prototype.negative = null; - /** - * ExponentialHistogramDataPoint flags. - * @member {number|null|undefined} flags - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @instance - */ - ExponentialHistogramDataPoint.prototype.flags = null; - /** - * ExponentialHistogramDataPoint exemplars. - * @member {Array.} exemplars - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @instance - */ - ExponentialHistogramDataPoint.prototype.exemplars = $util.emptyArray; - /** - * ExponentialHistogramDataPoint min. - * @member {number|null|undefined} min - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @instance - */ - ExponentialHistogramDataPoint.prototype.min = null; - /** - * ExponentialHistogramDataPoint max. - * @member {number|null|undefined} max - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @instance - */ - ExponentialHistogramDataPoint.prototype.max = null; - /** - * ExponentialHistogramDataPoint zeroThreshold. - * @member {number|null|undefined} zeroThreshold - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @instance - */ - ExponentialHistogramDataPoint.prototype.zeroThreshold = null; - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - /** - * ExponentialHistogramDataPoint _sum. - * @member {"sum"|undefined} _sum - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @instance - */ - Object.defineProperty(ExponentialHistogramDataPoint.prototype, "_sum", { - get: $util.oneOfGetter($oneOfFields = ["sum"]), - set: $util.oneOfSetter($oneOfFields) - }); - /** - * ExponentialHistogramDataPoint _min. - * @member {"min"|undefined} _min - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @instance - */ - Object.defineProperty(ExponentialHistogramDataPoint.prototype, "_min", { - get: $util.oneOfGetter($oneOfFields = ["min"]), - set: $util.oneOfSetter($oneOfFields) - }); - /** - * ExponentialHistogramDataPoint _max. - * @member {"max"|undefined} _max - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @instance - */ - Object.defineProperty(ExponentialHistogramDataPoint.prototype, "_max", { - get: $util.oneOfGetter($oneOfFields = ["max"]), - set: $util.oneOfSetter($oneOfFields) - }); - /** - * Creates a new ExponentialHistogramDataPoint instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @static - * @param {opentelemetry.proto.metrics.v1.IExponentialHistogramDataPoint=} [properties] Properties to set - * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint} ExponentialHistogramDataPoint instance - */ - ExponentialHistogramDataPoint.create = function create(properties) { - return new ExponentialHistogramDataPoint(properties); - }; - /** - * Encodes the specified ExponentialHistogramDataPoint message. Does not implicitly {@link opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @static - * @param {opentelemetry.proto.metrics.v1.IExponentialHistogramDataPoint} message ExponentialHistogramDataPoint message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExponentialHistogramDataPoint.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.attributes != null && message.attributes.length) - for (var i = 0; i < message.attributes.length; ++i) - $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - if (message.startTimeUnixNano != null && Object.hasOwnProperty.call(message, "startTimeUnixNano")) - writer.uint32(/* id 2, wireType 1 =*/ 17).fixed64(message.startTimeUnixNano); - if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano")) - writer.uint32(/* id 3, wireType 1 =*/ 25).fixed64(message.timeUnixNano); - if (message.count != null && Object.hasOwnProperty.call(message, "count")) - writer.uint32(/* id 4, wireType 1 =*/ 33).fixed64(message.count); - if (message.sum != null && Object.hasOwnProperty.call(message, "sum")) - writer.uint32(/* id 5, wireType 1 =*/ 41).double(message.sum); - if (message.scale != null && Object.hasOwnProperty.call(message, "scale")) - writer.uint32(/* id 6, wireType 0 =*/ 48).sint32(message.scale); - if (message.zeroCount != null && Object.hasOwnProperty.call(message, "zeroCount")) - writer.uint32(/* id 7, wireType 1 =*/ 57).fixed64(message.zeroCount); - if (message.positive != null && Object.hasOwnProperty.call(message, "positive")) - $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.encode(message.positive, writer.uint32(/* id 8, wireType 2 =*/ 66).fork()).ldelim(); - if (message.negative != null && Object.hasOwnProperty.call(message, "negative")) - $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.encode(message.negative, writer.uint32(/* id 9, wireType 2 =*/ 74).fork()).ldelim(); - if (message.flags != null && Object.hasOwnProperty.call(message, "flags")) - writer.uint32(/* id 10, wireType 0 =*/ 80).uint32(message.flags); - if (message.exemplars != null && message.exemplars.length) - for (var i = 0; i < message.exemplars.length; ++i) - $root.opentelemetry.proto.metrics.v1.Exemplar.encode(message.exemplars[i], writer.uint32(/* id 11, wireType 2 =*/ 90).fork()).ldelim(); - if (message.min != null && Object.hasOwnProperty.call(message, "min")) - writer.uint32(/* id 12, wireType 1 =*/ 97).double(message.min); - if (message.max != null && Object.hasOwnProperty.call(message, "max")) - writer.uint32(/* id 13, wireType 1 =*/ 105).double(message.max); - if (message.zeroThreshold != null && Object.hasOwnProperty.call(message, "zeroThreshold")) - writer.uint32(/* id 14, wireType 1 =*/ 113).double(message.zeroThreshold); - return writer; - }; - /** - * Encodes the specified ExponentialHistogramDataPoint message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @static - * @param {opentelemetry.proto.metrics.v1.IExponentialHistogramDataPoint} message ExponentialHistogramDataPoint message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ExponentialHistogramDataPoint.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes an ExponentialHistogramDataPoint message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint} ExponentialHistogramDataPoint - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExponentialHistogramDataPoint.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - if (!(message.attributes && message.attributes.length)) - message.attributes = []; - message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); - break; - } - case 2: { - message.startTimeUnixNano = reader.fixed64(); - break; - } - case 3: { - message.timeUnixNano = reader.fixed64(); - break; - } - case 4: { - message.count = reader.fixed64(); - break; - } - case 5: { - message.sum = reader.double(); - break; - } - case 6: { - message.scale = reader.sint32(); - break; - } - case 7: { - message.zeroCount = reader.fixed64(); - break; - } - case 8: { - message.positive = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.decode(reader, reader.uint32()); - break; - } - case 9: { - message.negative = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.decode(reader, reader.uint32()); - break; - } - case 10: { - message.flags = reader.uint32(); - break; - } - case 11: { - if (!(message.exemplars && message.exemplars.length)) - message.exemplars = []; - message.exemplars.push($root.opentelemetry.proto.metrics.v1.Exemplar.decode(reader, reader.uint32())); - break; - } - case 12: { - message.min = reader.double(); - break; - } - case 13: { - message.max = reader.double(); - break; - } - case 14: { - message.zeroThreshold = reader.double(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes an ExponentialHistogramDataPoint message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint} ExponentialHistogramDataPoint - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ExponentialHistogramDataPoint.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies an ExponentialHistogramDataPoint message. - * @function verify - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ExponentialHistogramDataPoint.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.attributes != null && message.hasOwnProperty("attributes")) { - if (!Array.isArray(message.attributes)) - return "attributes: array expected"; - for (var i = 0; i < message.attributes.length; ++i) { - var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]); - if (error) - return "attributes." + error; - } - } - if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) - if (!$util.isInteger(message.startTimeUnixNano) && !(message.startTimeUnixNano && $util.isInteger(message.startTimeUnixNano.low) && $util.isInteger(message.startTimeUnixNano.high))) - return "startTimeUnixNano: integer|Long expected"; - if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) - if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high))) - return "timeUnixNano: integer|Long expected"; - if (message.count != null && message.hasOwnProperty("count")) - if (!$util.isInteger(message.count) && !(message.count && $util.isInteger(message.count.low) && $util.isInteger(message.count.high))) - return "count: integer|Long expected"; - if (message.sum != null && message.hasOwnProperty("sum")) { - properties._sum = 1; - if (typeof message.sum !== "number") - return "sum: number expected"; - } - if (message.scale != null && message.hasOwnProperty("scale")) - if (!$util.isInteger(message.scale)) - return "scale: integer expected"; - if (message.zeroCount != null && message.hasOwnProperty("zeroCount")) - if (!$util.isInteger(message.zeroCount) && !(message.zeroCount && $util.isInteger(message.zeroCount.low) && $util.isInteger(message.zeroCount.high))) - return "zeroCount: integer|Long expected"; - if (message.positive != null && message.hasOwnProperty("positive")) { - var error = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.verify(message.positive); - if (error) - return "positive." + error; - } - if (message.negative != null && message.hasOwnProperty("negative")) { - var error = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.verify(message.negative); - if (error) - return "negative." + error; - } - if (message.flags != null && message.hasOwnProperty("flags")) - if (!$util.isInteger(message.flags)) - return "flags: integer expected"; - if (message.exemplars != null && message.hasOwnProperty("exemplars")) { - if (!Array.isArray(message.exemplars)) - return "exemplars: array expected"; - for (var i = 0; i < message.exemplars.length; ++i) { - var error = $root.opentelemetry.proto.metrics.v1.Exemplar.verify(message.exemplars[i]); - if (error) - return "exemplars." + error; - } - } - if (message.min != null && message.hasOwnProperty("min")) { - properties._min = 1; - if (typeof message.min !== "number") - return "min: number expected"; - } - if (message.max != null && message.hasOwnProperty("max")) { - properties._max = 1; - if (typeof message.max !== "number") - return "max: number expected"; - } - if (message.zeroThreshold != null && message.hasOwnProperty("zeroThreshold")) - if (typeof message.zeroThreshold !== "number") - return "zeroThreshold: number expected"; - return null; - }; - /** - * Creates an ExponentialHistogramDataPoint message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint} ExponentialHistogramDataPoint - */ - ExponentialHistogramDataPoint.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint) - return object; - var message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint(); - if (object.attributes) { - if (!Array.isArray(object.attributes)) - throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.attributes: array expected"); - message.attributes = []; - for (var i = 0; i < object.attributes.length; ++i) { - if (typeof object.attributes[i] !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.attributes: object expected"); - message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]); - } - } - if (object.startTimeUnixNano != null) - if ($util.Long) - (message.startTimeUnixNano = $util.Long.fromValue(object.startTimeUnixNano)).unsigned = false; - else if (typeof object.startTimeUnixNano === "string") - message.startTimeUnixNano = parseInt(object.startTimeUnixNano, 10); - else if (typeof object.startTimeUnixNano === "number") - message.startTimeUnixNano = object.startTimeUnixNano; - else if (typeof object.startTimeUnixNano === "object") - message.startTimeUnixNano = new $util.LongBits(object.startTimeUnixNano.low >>> 0, object.startTimeUnixNano.high >>> 0).toNumber(); - if (object.timeUnixNano != null) - if ($util.Long) - (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false; - else if (typeof object.timeUnixNano === "string") - message.timeUnixNano = parseInt(object.timeUnixNano, 10); - else if (typeof object.timeUnixNano === "number") - message.timeUnixNano = object.timeUnixNano; - else if (typeof object.timeUnixNano === "object") - message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber(); - if (object.count != null) - if ($util.Long) - (message.count = $util.Long.fromValue(object.count)).unsigned = false; - else if (typeof object.count === "string") - message.count = parseInt(object.count, 10); - else if (typeof object.count === "number") - message.count = object.count; - else if (typeof object.count === "object") - message.count = new $util.LongBits(object.count.low >>> 0, object.count.high >>> 0).toNumber(); - if (object.sum != null) - message.sum = Number(object.sum); - if (object.scale != null) - message.scale = object.scale | 0; - if (object.zeroCount != null) - if ($util.Long) - (message.zeroCount = $util.Long.fromValue(object.zeroCount)).unsigned = false; - else if (typeof object.zeroCount === "string") - message.zeroCount = parseInt(object.zeroCount, 10); - else if (typeof object.zeroCount === "number") - message.zeroCount = object.zeroCount; - else if (typeof object.zeroCount === "object") - message.zeroCount = new $util.LongBits(object.zeroCount.low >>> 0, object.zeroCount.high >>> 0).toNumber(); - if (object.positive != null) { - if (typeof object.positive !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.positive: object expected"); - message.positive = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.fromObject(object.positive); - } - if (object.negative != null) { - if (typeof object.negative !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.negative: object expected"); - message.negative = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.fromObject(object.negative); - } - if (object.flags != null) - message.flags = object.flags >>> 0; - if (object.exemplars) { - if (!Array.isArray(object.exemplars)) - throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.exemplars: array expected"); - message.exemplars = []; - for (var i = 0; i < object.exemplars.length; ++i) { - if (typeof object.exemplars[i] !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.exemplars: object expected"); - message.exemplars[i] = $root.opentelemetry.proto.metrics.v1.Exemplar.fromObject(object.exemplars[i]); - } - } - if (object.min != null) - message.min = Number(object.min); - if (object.max != null) - message.max = Number(object.max); - if (object.zeroThreshold != null) - message.zeroThreshold = Number(object.zeroThreshold); - return message; - }; - /** - * Creates a plain object from an ExponentialHistogramDataPoint message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @static - * @param {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint} message ExponentialHistogramDataPoint - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ExponentialHistogramDataPoint.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) { - object.attributes = []; - object.exemplars = []; - } - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.startTimeUnixNano = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.timeUnixNano = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.count = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.count = options.longs === String ? "0" : 0; - object.scale = 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.zeroCount = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.zeroCount = options.longs === String ? "0" : 0; - object.positive = null; - object.negative = null; - object.flags = 0; - object.zeroThreshold = 0; - } - if (message.attributes && message.attributes.length) { - object.attributes = []; - for (var j = 0; j < message.attributes.length; ++j) - object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options); - } - if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) - if (typeof message.startTimeUnixNano === "number") - object.startTimeUnixNano = options.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano; - else - object.startTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.startTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.startTimeUnixNano.low >>> 0, message.startTimeUnixNano.high >>> 0).toNumber() : message.startTimeUnixNano; - if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) - if (typeof message.timeUnixNano === "number") - object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano; - else - object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano; - if (message.count != null && message.hasOwnProperty("count")) - if (typeof message.count === "number") - object.count = options.longs === String ? String(message.count) : message.count; - else - object.count = options.longs === String ? $util.Long.prototype.toString.call(message.count) : options.longs === Number ? new $util.LongBits(message.count.low >>> 0, message.count.high >>> 0).toNumber() : message.count; - if (message.sum != null && message.hasOwnProperty("sum")) { - object.sum = options.json && !isFinite(message.sum) ? String(message.sum) : message.sum; - if (options.oneofs) - object._sum = "sum"; - } - if (message.scale != null && message.hasOwnProperty("scale")) - object.scale = message.scale; - if (message.zeroCount != null && message.hasOwnProperty("zeroCount")) - if (typeof message.zeroCount === "number") - object.zeroCount = options.longs === String ? String(message.zeroCount) : message.zeroCount; - else - object.zeroCount = options.longs === String ? $util.Long.prototype.toString.call(message.zeroCount) : options.longs === Number ? new $util.LongBits(message.zeroCount.low >>> 0, message.zeroCount.high >>> 0).toNumber() : message.zeroCount; - if (message.positive != null && message.hasOwnProperty("positive")) - object.positive = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.toObject(message.positive, options); - if (message.negative != null && message.hasOwnProperty("negative")) - object.negative = $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.toObject(message.negative, options); - if (message.flags != null && message.hasOwnProperty("flags")) - object.flags = message.flags; - if (message.exemplars && message.exemplars.length) { - object.exemplars = []; - for (var j = 0; j < message.exemplars.length; ++j) - object.exemplars[j] = $root.opentelemetry.proto.metrics.v1.Exemplar.toObject(message.exemplars[j], options); - } - if (message.min != null && message.hasOwnProperty("min")) { - object.min = options.json && !isFinite(message.min) ? String(message.min) : message.min; - if (options.oneofs) - object._min = "min"; - } - if (message.max != null && message.hasOwnProperty("max")) { - object.max = options.json && !isFinite(message.max) ? String(message.max) : message.max; - if (options.oneofs) - object._max = "max"; - } - if (message.zeroThreshold != null && message.hasOwnProperty("zeroThreshold")) - object.zeroThreshold = options.json && !isFinite(message.zeroThreshold) ? String(message.zeroThreshold) : message.zeroThreshold; - return object; - }; - /** - * Converts this ExponentialHistogramDataPoint to JSON. - * @function toJSON - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @instance - * @returns {Object.} JSON object - */ - ExponentialHistogramDataPoint.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for ExponentialHistogramDataPoint - * @function getTypeUrl - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ExponentialHistogramDataPoint.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint"; - }; - ExponentialHistogramDataPoint.Buckets = (function () { - /** - * Properties of a Buckets. - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @interface IBuckets - * @property {number|null} [offset] Buckets offset - * @property {Array.|null} [bucketCounts] Buckets bucketCounts - */ - /** - * Constructs a new Buckets. - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint - * @classdesc Represents a Buckets. - * @implements IBuckets - * @constructor - * @param {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.IBuckets=} [properties] Properties to set - */ - function Buckets(properties) { - this.bucketCounts = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * Buckets offset. - * @member {number|null|undefined} offset - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets - * @instance - */ - Buckets.prototype.offset = null; - /** - * Buckets bucketCounts. - * @member {Array.} bucketCounts - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets - * @instance - */ - Buckets.prototype.bucketCounts = $util.emptyArray; - /** - * Creates a new Buckets instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets - * @static - * @param {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.IBuckets=} [properties] Properties to set - * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets} Buckets instance - */ - Buckets.create = function create(properties) { - return new Buckets(properties); - }; - /** - * Encodes the specified Buckets message. Does not implicitly {@link opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets - * @static - * @param {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.IBuckets} message Buckets message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Buckets.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.offset != null && Object.hasOwnProperty.call(message, "offset")) - writer.uint32(/* id 1, wireType 0 =*/ 8).sint32(message.offset); - if (message.bucketCounts != null && message.bucketCounts.length) { - writer.uint32(/* id 2, wireType 2 =*/ 18).fork(); - for (var i = 0; i < message.bucketCounts.length; ++i) - writer.uint64(message.bucketCounts[i]); - writer.ldelim(); - } - return writer; - }; - /** - * Encodes the specified Buckets message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets - * @static - * @param {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.IBuckets} message Buckets message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Buckets.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a Buckets message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets} Buckets - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Buckets.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.offset = reader.sint32(); - break; - } - case 2: { - if (!(message.bucketCounts && message.bucketCounts.length)) - message.bucketCounts = []; - if ((tag & 7) === 2) { - var end2 = reader.uint32() + reader.pos; - while (reader.pos < end2) - message.bucketCounts.push(reader.uint64()); - } - else - message.bucketCounts.push(reader.uint64()); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a Buckets message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets} Buckets - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Buckets.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a Buckets message. - * @function verify - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Buckets.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.offset != null && message.hasOwnProperty("offset")) - if (!$util.isInteger(message.offset)) - return "offset: integer expected"; - if (message.bucketCounts != null && message.hasOwnProperty("bucketCounts")) { - if (!Array.isArray(message.bucketCounts)) - return "bucketCounts: array expected"; - for (var i = 0; i < message.bucketCounts.length; ++i) - if (!$util.isInteger(message.bucketCounts[i]) && !(message.bucketCounts[i] && $util.isInteger(message.bucketCounts[i].low) && $util.isInteger(message.bucketCounts[i].high))) - return "bucketCounts: integer|Long[] expected"; - } - return null; - }; - /** - * Creates a Buckets message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets} Buckets - */ - Buckets.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets) - return object; - var message = new $root.opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets(); - if (object.offset != null) - message.offset = object.offset | 0; - if (object.bucketCounts) { - if (!Array.isArray(object.bucketCounts)) - throw TypeError(".opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets.bucketCounts: array expected"); - message.bucketCounts = []; - for (var i = 0; i < object.bucketCounts.length; ++i) - if ($util.Long) - (message.bucketCounts[i] = $util.Long.fromValue(object.bucketCounts[i])).unsigned = true; - else if (typeof object.bucketCounts[i] === "string") - message.bucketCounts[i] = parseInt(object.bucketCounts[i], 10); - else if (typeof object.bucketCounts[i] === "number") - message.bucketCounts[i] = object.bucketCounts[i]; - else if (typeof object.bucketCounts[i] === "object") - message.bucketCounts[i] = new $util.LongBits(object.bucketCounts[i].low >>> 0, object.bucketCounts[i].high >>> 0).toNumber(true); - } - return message; - }; - /** - * Creates a plain object from a Buckets message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets - * @static - * @param {opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets} message Buckets - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Buckets.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.bucketCounts = []; - if (options.defaults) - object.offset = 0; - if (message.offset != null && message.hasOwnProperty("offset")) - object.offset = message.offset; - if (message.bucketCounts && message.bucketCounts.length) { - object.bucketCounts = []; - for (var j = 0; j < message.bucketCounts.length; ++j) - if (typeof message.bucketCounts[j] === "number") - object.bucketCounts[j] = options.longs === String ? String(message.bucketCounts[j]) : message.bucketCounts[j]; - else - object.bucketCounts[j] = options.longs === String ? $util.Long.prototype.toString.call(message.bucketCounts[j]) : options.longs === Number ? new $util.LongBits(message.bucketCounts[j].low >>> 0, message.bucketCounts[j].high >>> 0).toNumber(true) : message.bucketCounts[j]; - } - return object; - }; - /** - * Converts this Buckets to JSON. - * @function toJSON - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets - * @instance - * @returns {Object.} JSON object - */ - Buckets.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for Buckets - * @function getTypeUrl - * @memberof opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Buckets.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.ExponentialHistogramDataPoint.Buckets"; - }; - return Buckets; - })(); - return ExponentialHistogramDataPoint; - })(); - v1.SummaryDataPoint = (function () { - /** - * Properties of a SummaryDataPoint. - * @memberof opentelemetry.proto.metrics.v1 - * @interface ISummaryDataPoint - * @property {Array.|null} [attributes] SummaryDataPoint attributes - * @property {number|Long|null} [startTimeUnixNano] SummaryDataPoint startTimeUnixNano - * @property {number|Long|null} [timeUnixNano] SummaryDataPoint timeUnixNano - * @property {number|Long|null} [count] SummaryDataPoint count - * @property {number|null} [sum] SummaryDataPoint sum - * @property {Array.|null} [quantileValues] SummaryDataPoint quantileValues - * @property {number|null} [flags] SummaryDataPoint flags - */ - /** - * Constructs a new SummaryDataPoint. - * @memberof opentelemetry.proto.metrics.v1 - * @classdesc Represents a SummaryDataPoint. - * @implements ISummaryDataPoint - * @constructor - * @param {opentelemetry.proto.metrics.v1.ISummaryDataPoint=} [properties] Properties to set - */ - function SummaryDataPoint(properties) { - this.attributes = []; - this.quantileValues = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * SummaryDataPoint attributes. - * @member {Array.} attributes - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint - * @instance - */ - SummaryDataPoint.prototype.attributes = $util.emptyArray; - /** - * SummaryDataPoint startTimeUnixNano. - * @member {number|Long|null|undefined} startTimeUnixNano - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint - * @instance - */ - SummaryDataPoint.prototype.startTimeUnixNano = null; - /** - * SummaryDataPoint timeUnixNano. - * @member {number|Long|null|undefined} timeUnixNano - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint - * @instance - */ - SummaryDataPoint.prototype.timeUnixNano = null; - /** - * SummaryDataPoint count. - * @member {number|Long|null|undefined} count - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint - * @instance - */ - SummaryDataPoint.prototype.count = null; - /** - * SummaryDataPoint sum. - * @member {number|null|undefined} sum - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint - * @instance - */ - SummaryDataPoint.prototype.sum = null; - /** - * SummaryDataPoint quantileValues. - * @member {Array.} quantileValues - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint - * @instance - */ - SummaryDataPoint.prototype.quantileValues = $util.emptyArray; - /** - * SummaryDataPoint flags. - * @member {number|null|undefined} flags - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint - * @instance - */ - SummaryDataPoint.prototype.flags = null; - /** - * Creates a new SummaryDataPoint instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint - * @static - * @param {opentelemetry.proto.metrics.v1.ISummaryDataPoint=} [properties] Properties to set - * @returns {opentelemetry.proto.metrics.v1.SummaryDataPoint} SummaryDataPoint instance - */ - SummaryDataPoint.create = function create(properties) { - return new SummaryDataPoint(properties); - }; - /** - * Encodes the specified SummaryDataPoint message. Does not implicitly {@link opentelemetry.proto.metrics.v1.SummaryDataPoint.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint - * @static - * @param {opentelemetry.proto.metrics.v1.ISummaryDataPoint} message SummaryDataPoint message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SummaryDataPoint.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.startTimeUnixNano != null && Object.hasOwnProperty.call(message, "startTimeUnixNano")) - writer.uint32(/* id 2, wireType 1 =*/ 17).fixed64(message.startTimeUnixNano); - if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano")) - writer.uint32(/* id 3, wireType 1 =*/ 25).fixed64(message.timeUnixNano); - if (message.count != null && Object.hasOwnProperty.call(message, "count")) - writer.uint32(/* id 4, wireType 1 =*/ 33).fixed64(message.count); - if (message.sum != null && Object.hasOwnProperty.call(message, "sum")) - writer.uint32(/* id 5, wireType 1 =*/ 41).double(message.sum); - if (message.quantileValues != null && message.quantileValues.length) - for (var i = 0; i < message.quantileValues.length; ++i) - $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.encode(message.quantileValues[i], writer.uint32(/* id 6, wireType 2 =*/ 50).fork()).ldelim(); - if (message.attributes != null && message.attributes.length) - for (var i = 0; i < message.attributes.length; ++i) - $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(/* id 7, wireType 2 =*/ 58).fork()).ldelim(); - if (message.flags != null && Object.hasOwnProperty.call(message, "flags")) - writer.uint32(/* id 8, wireType 0 =*/ 64).uint32(message.flags); - return writer; - }; - /** - * Encodes the specified SummaryDataPoint message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.SummaryDataPoint.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint - * @static - * @param {opentelemetry.proto.metrics.v1.ISummaryDataPoint} message SummaryDataPoint message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - SummaryDataPoint.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a SummaryDataPoint message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.metrics.v1.SummaryDataPoint} SummaryDataPoint - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SummaryDataPoint.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.SummaryDataPoint(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 7: { - if (!(message.attributes && message.attributes.length)) - message.attributes = []; - message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); - break; - } - case 2: { - message.startTimeUnixNano = reader.fixed64(); - break; - } - case 3: { - message.timeUnixNano = reader.fixed64(); - break; - } - case 4: { - message.count = reader.fixed64(); - break; - } - case 5: { - message.sum = reader.double(); - break; - } - case 6: { - if (!(message.quantileValues && message.quantileValues.length)) - message.quantileValues = []; - message.quantileValues.push($root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.decode(reader, reader.uint32())); - break; - } - case 8: { - message.flags = reader.uint32(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a SummaryDataPoint message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.metrics.v1.SummaryDataPoint} SummaryDataPoint - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - SummaryDataPoint.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a SummaryDataPoint message. - * @function verify - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - SummaryDataPoint.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.attributes != null && message.hasOwnProperty("attributes")) { - if (!Array.isArray(message.attributes)) - return "attributes: array expected"; - for (var i = 0; i < message.attributes.length; ++i) { - var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]); - if (error) - return "attributes." + error; - } - } - if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) - if (!$util.isInteger(message.startTimeUnixNano) && !(message.startTimeUnixNano && $util.isInteger(message.startTimeUnixNano.low) && $util.isInteger(message.startTimeUnixNano.high))) - return "startTimeUnixNano: integer|Long expected"; - if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) - if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high))) - return "timeUnixNano: integer|Long expected"; - if (message.count != null && message.hasOwnProperty("count")) - if (!$util.isInteger(message.count) && !(message.count && $util.isInteger(message.count.low) && $util.isInteger(message.count.high))) - return "count: integer|Long expected"; - if (message.sum != null && message.hasOwnProperty("sum")) - if (typeof message.sum !== "number") - return "sum: number expected"; - if (message.quantileValues != null && message.hasOwnProperty("quantileValues")) { - if (!Array.isArray(message.quantileValues)) - return "quantileValues: array expected"; - for (var i = 0; i < message.quantileValues.length; ++i) { - var error = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.verify(message.quantileValues[i]); - if (error) - return "quantileValues." + error; - } - } - if (message.flags != null && message.hasOwnProperty("flags")) - if (!$util.isInteger(message.flags)) - return "flags: integer expected"; - return null; - }; - /** - * Creates a SummaryDataPoint message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.metrics.v1.SummaryDataPoint} SummaryDataPoint - */ - SummaryDataPoint.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.metrics.v1.SummaryDataPoint) - return object; - var message = new $root.opentelemetry.proto.metrics.v1.SummaryDataPoint(); - if (object.attributes) { - if (!Array.isArray(object.attributes)) - throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.attributes: array expected"); - message.attributes = []; - for (var i = 0; i < object.attributes.length; ++i) { - if (typeof object.attributes[i] !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.attributes: object expected"); - message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]); - } - } - if (object.startTimeUnixNano != null) - if ($util.Long) - (message.startTimeUnixNano = $util.Long.fromValue(object.startTimeUnixNano)).unsigned = false; - else if (typeof object.startTimeUnixNano === "string") - message.startTimeUnixNano = parseInt(object.startTimeUnixNano, 10); - else if (typeof object.startTimeUnixNano === "number") - message.startTimeUnixNano = object.startTimeUnixNano; - else if (typeof object.startTimeUnixNano === "object") - message.startTimeUnixNano = new $util.LongBits(object.startTimeUnixNano.low >>> 0, object.startTimeUnixNano.high >>> 0).toNumber(); - if (object.timeUnixNano != null) - if ($util.Long) - (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false; - else if (typeof object.timeUnixNano === "string") - message.timeUnixNano = parseInt(object.timeUnixNano, 10); - else if (typeof object.timeUnixNano === "number") - message.timeUnixNano = object.timeUnixNano; - else if (typeof object.timeUnixNano === "object") - message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber(); - if (object.count != null) - if ($util.Long) - (message.count = $util.Long.fromValue(object.count)).unsigned = false; - else if (typeof object.count === "string") - message.count = parseInt(object.count, 10); - else if (typeof object.count === "number") - message.count = object.count; - else if (typeof object.count === "object") - message.count = new $util.LongBits(object.count.low >>> 0, object.count.high >>> 0).toNumber(); - if (object.sum != null) - message.sum = Number(object.sum); - if (object.quantileValues) { - if (!Array.isArray(object.quantileValues)) - throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.quantileValues: array expected"); - message.quantileValues = []; - for (var i = 0; i < object.quantileValues.length; ++i) { - if (typeof object.quantileValues[i] !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.SummaryDataPoint.quantileValues: object expected"); - message.quantileValues[i] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.fromObject(object.quantileValues[i]); - } - } - if (object.flags != null) - message.flags = object.flags >>> 0; - return message; - }; - /** - * Creates a plain object from a SummaryDataPoint message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint - * @static - * @param {opentelemetry.proto.metrics.v1.SummaryDataPoint} message SummaryDataPoint - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - SummaryDataPoint.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) { - object.quantileValues = []; - object.attributes = []; - } - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.startTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.startTimeUnixNano = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.timeUnixNano = options.longs === String ? "0" : 0; - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.count = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.count = options.longs === String ? "0" : 0; - object.sum = 0; - object.flags = 0; - } - if (message.startTimeUnixNano != null && message.hasOwnProperty("startTimeUnixNano")) - if (typeof message.startTimeUnixNano === "number") - object.startTimeUnixNano = options.longs === String ? String(message.startTimeUnixNano) : message.startTimeUnixNano; - else - object.startTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.startTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.startTimeUnixNano.low >>> 0, message.startTimeUnixNano.high >>> 0).toNumber() : message.startTimeUnixNano; - if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) - if (typeof message.timeUnixNano === "number") - object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano; - else - object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano; - if (message.count != null && message.hasOwnProperty("count")) - if (typeof message.count === "number") - object.count = options.longs === String ? String(message.count) : message.count; - else - object.count = options.longs === String ? $util.Long.prototype.toString.call(message.count) : options.longs === Number ? new $util.LongBits(message.count.low >>> 0, message.count.high >>> 0).toNumber() : message.count; - if (message.sum != null && message.hasOwnProperty("sum")) - object.sum = options.json && !isFinite(message.sum) ? String(message.sum) : message.sum; - if (message.quantileValues && message.quantileValues.length) { - object.quantileValues = []; - for (var j = 0; j < message.quantileValues.length; ++j) - object.quantileValues[j] = $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.toObject(message.quantileValues[j], options); - } - if (message.attributes && message.attributes.length) { - object.attributes = []; - for (var j = 0; j < message.attributes.length; ++j) - object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options); - } - if (message.flags != null && message.hasOwnProperty("flags")) - object.flags = message.flags; - return object; - }; - /** - * Converts this SummaryDataPoint to JSON. - * @function toJSON - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint - * @instance - * @returns {Object.} JSON object - */ - SummaryDataPoint.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for SummaryDataPoint - * @function getTypeUrl - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - SummaryDataPoint.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.SummaryDataPoint"; - }; - SummaryDataPoint.ValueAtQuantile = (function () { - /** - * Properties of a ValueAtQuantile. - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint - * @interface IValueAtQuantile - * @property {number|null} [quantile] ValueAtQuantile quantile - * @property {number|null} [value] ValueAtQuantile value - */ - /** - * Constructs a new ValueAtQuantile. - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint - * @classdesc Represents a ValueAtQuantile. - * @implements IValueAtQuantile - * @constructor - * @param {opentelemetry.proto.metrics.v1.SummaryDataPoint.IValueAtQuantile=} [properties] Properties to set - */ - function ValueAtQuantile(properties) { - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * ValueAtQuantile quantile. - * @member {number|null|undefined} quantile - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile - * @instance - */ - ValueAtQuantile.prototype.quantile = null; - /** - * ValueAtQuantile value. - * @member {number|null|undefined} value - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile - * @instance - */ - ValueAtQuantile.prototype.value = null; - /** - * Creates a new ValueAtQuantile instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile - * @static - * @param {opentelemetry.proto.metrics.v1.SummaryDataPoint.IValueAtQuantile=} [properties] Properties to set - * @returns {opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile} ValueAtQuantile instance - */ - ValueAtQuantile.create = function create(properties) { - return new ValueAtQuantile(properties); - }; - /** - * Encodes the specified ValueAtQuantile message. Does not implicitly {@link opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile - * @static - * @param {opentelemetry.proto.metrics.v1.SummaryDataPoint.IValueAtQuantile} message ValueAtQuantile message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ValueAtQuantile.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.quantile != null && Object.hasOwnProperty.call(message, "quantile")) - writer.uint32(/* id 1, wireType 1 =*/ 9).double(message.quantile); - if (message.value != null && Object.hasOwnProperty.call(message, "value")) - writer.uint32(/* id 2, wireType 1 =*/ 17).double(message.value); - return writer; - }; - /** - * Encodes the specified ValueAtQuantile message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile - * @static - * @param {opentelemetry.proto.metrics.v1.SummaryDataPoint.IValueAtQuantile} message ValueAtQuantile message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ValueAtQuantile.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a ValueAtQuantile message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile} ValueAtQuantile - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ValueAtQuantile.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.quantile = reader.double(); - break; - } - case 2: { - message.value = reader.double(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a ValueAtQuantile message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile} ValueAtQuantile - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ValueAtQuantile.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a ValueAtQuantile message. - * @function verify - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ValueAtQuantile.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.quantile != null && message.hasOwnProperty("quantile")) - if (typeof message.quantile !== "number") - return "quantile: number expected"; - if (message.value != null && message.hasOwnProperty("value")) - if (typeof message.value !== "number") - return "value: number expected"; - return null; - }; - /** - * Creates a ValueAtQuantile message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile} ValueAtQuantile - */ - ValueAtQuantile.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile) - return object; - var message = new $root.opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile(); - if (object.quantile != null) - message.quantile = Number(object.quantile); - if (object.value != null) - message.value = Number(object.value); - return message; - }; - /** - * Creates a plain object from a ValueAtQuantile message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile - * @static - * @param {opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile} message ValueAtQuantile - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ValueAtQuantile.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.defaults) { - object.quantile = 0; - object.value = 0; - } - if (message.quantile != null && message.hasOwnProperty("quantile")) - object.quantile = options.json && !isFinite(message.quantile) ? String(message.quantile) : message.quantile; - if (message.value != null && message.hasOwnProperty("value")) - object.value = options.json && !isFinite(message.value) ? String(message.value) : message.value; - return object; - }; - /** - * Converts this ValueAtQuantile to JSON. - * @function toJSON - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile - * @instance - * @returns {Object.} JSON object - */ - ValueAtQuantile.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for ValueAtQuantile - * @function getTypeUrl - * @memberof opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ValueAtQuantile.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.SummaryDataPoint.ValueAtQuantile"; - }; - return ValueAtQuantile; - })(); - return SummaryDataPoint; - })(); - v1.Exemplar = (function () { - /** - * Properties of an Exemplar. - * @memberof opentelemetry.proto.metrics.v1 - * @interface IExemplar - * @property {Array.|null} [filteredAttributes] Exemplar filteredAttributes - * @property {number|Long|null} [timeUnixNano] Exemplar timeUnixNano - * @property {number|null} [asDouble] Exemplar asDouble - * @property {number|Long|null} [asInt] Exemplar asInt - * @property {Uint8Array|null} [spanId] Exemplar spanId - * @property {Uint8Array|null} [traceId] Exemplar traceId - */ - /** - * Constructs a new Exemplar. - * @memberof opentelemetry.proto.metrics.v1 - * @classdesc Represents an Exemplar. - * @implements IExemplar - * @constructor - * @param {opentelemetry.proto.metrics.v1.IExemplar=} [properties] Properties to set - */ - function Exemplar(properties) { - this.filteredAttributes = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * Exemplar filteredAttributes. - * @member {Array.} filteredAttributes - * @memberof opentelemetry.proto.metrics.v1.Exemplar - * @instance - */ - Exemplar.prototype.filteredAttributes = $util.emptyArray; - /** - * Exemplar timeUnixNano. - * @member {number|Long|null|undefined} timeUnixNano - * @memberof opentelemetry.proto.metrics.v1.Exemplar - * @instance - */ - Exemplar.prototype.timeUnixNano = null; - /** - * Exemplar asDouble. - * @member {number|null|undefined} asDouble - * @memberof opentelemetry.proto.metrics.v1.Exemplar - * @instance - */ - Exemplar.prototype.asDouble = null; - /** - * Exemplar asInt. - * @member {number|Long|null|undefined} asInt - * @memberof opentelemetry.proto.metrics.v1.Exemplar - * @instance - */ - Exemplar.prototype.asInt = null; - /** - * Exemplar spanId. - * @member {Uint8Array|null|undefined} spanId - * @memberof opentelemetry.proto.metrics.v1.Exemplar - * @instance - */ - Exemplar.prototype.spanId = null; - /** - * Exemplar traceId. - * @member {Uint8Array|null|undefined} traceId - * @memberof opentelemetry.proto.metrics.v1.Exemplar - * @instance - */ - Exemplar.prototype.traceId = null; - // OneOf field names bound to virtual getters and setters - var $oneOfFields; - /** - * Exemplar value. - * @member {"asDouble"|"asInt"|undefined} value - * @memberof opentelemetry.proto.metrics.v1.Exemplar - * @instance - */ - Object.defineProperty(Exemplar.prototype, "value", { - get: $util.oneOfGetter($oneOfFields = ["asDouble", "asInt"]), - set: $util.oneOfSetter($oneOfFields) - }); - /** - * Creates a new Exemplar instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.metrics.v1.Exemplar - * @static - * @param {opentelemetry.proto.metrics.v1.IExemplar=} [properties] Properties to set - * @returns {opentelemetry.proto.metrics.v1.Exemplar} Exemplar instance - */ - Exemplar.create = function create(properties) { - return new Exemplar(properties); - }; - /** - * Encodes the specified Exemplar message. Does not implicitly {@link opentelemetry.proto.metrics.v1.Exemplar.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.metrics.v1.Exemplar - * @static - * @param {opentelemetry.proto.metrics.v1.IExemplar} message Exemplar message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Exemplar.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano")) - writer.uint32(/* id 2, wireType 1 =*/ 17).fixed64(message.timeUnixNano); - if (message.asDouble != null && Object.hasOwnProperty.call(message, "asDouble")) - writer.uint32(/* id 3, wireType 1 =*/ 25).double(message.asDouble); - if (message.spanId != null && Object.hasOwnProperty.call(message, "spanId")) - writer.uint32(/* id 4, wireType 2 =*/ 34).bytes(message.spanId); - if (message.traceId != null && Object.hasOwnProperty.call(message, "traceId")) - writer.uint32(/* id 5, wireType 2 =*/ 42).bytes(message.traceId); - if (message.asInt != null && Object.hasOwnProperty.call(message, "asInt")) - writer.uint32(/* id 6, wireType 1 =*/ 49).sfixed64(message.asInt); - if (message.filteredAttributes != null && message.filteredAttributes.length) - for (var i = 0; i < message.filteredAttributes.length; ++i) - $root.opentelemetry.proto.common.v1.KeyValue.encode(message.filteredAttributes[i], writer.uint32(/* id 7, wireType 2 =*/ 58).fork()).ldelim(); - return writer; - }; - /** - * Encodes the specified Exemplar message, length delimited. Does not implicitly {@link opentelemetry.proto.metrics.v1.Exemplar.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.metrics.v1.Exemplar - * @static - * @param {opentelemetry.proto.metrics.v1.IExemplar} message Exemplar message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - Exemplar.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes an Exemplar message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.metrics.v1.Exemplar - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.metrics.v1.Exemplar} Exemplar - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Exemplar.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.metrics.v1.Exemplar(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 7: { - if (!(message.filteredAttributes && message.filteredAttributes.length)) - message.filteredAttributes = []; - message.filteredAttributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); - break; - } - case 2: { - message.timeUnixNano = reader.fixed64(); - break; - } - case 3: { - message.asDouble = reader.double(); - break; - } - case 6: { - message.asInt = reader.sfixed64(); - break; - } - case 4: { - message.spanId = reader.bytes(); - break; - } - case 5: { - message.traceId = reader.bytes(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes an Exemplar message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.metrics.v1.Exemplar - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.metrics.v1.Exemplar} Exemplar - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - Exemplar.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies an Exemplar message. - * @function verify - * @memberof opentelemetry.proto.metrics.v1.Exemplar - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - Exemplar.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - var properties = {}; - if (message.filteredAttributes != null && message.hasOwnProperty("filteredAttributes")) { - if (!Array.isArray(message.filteredAttributes)) - return "filteredAttributes: array expected"; - for (var i = 0; i < message.filteredAttributes.length; ++i) { - var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.filteredAttributes[i]); - if (error) - return "filteredAttributes." + error; - } - } - if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) - if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high))) - return "timeUnixNano: integer|Long expected"; - if (message.asDouble != null && message.hasOwnProperty("asDouble")) { - properties.value = 1; - if (typeof message.asDouble !== "number") - return "asDouble: number expected"; - } - if (message.asInt != null && message.hasOwnProperty("asInt")) { - if (properties.value === 1) - return "value: multiple values"; - properties.value = 1; - if (!$util.isInteger(message.asInt) && !(message.asInt && $util.isInteger(message.asInt.low) && $util.isInteger(message.asInt.high))) - return "asInt: integer|Long expected"; - } - if (message.spanId != null && message.hasOwnProperty("spanId")) - if (!(message.spanId && typeof message.spanId.length === "number" || $util.isString(message.spanId))) - return "spanId: buffer expected"; - if (message.traceId != null && message.hasOwnProperty("traceId")) - if (!(message.traceId && typeof message.traceId.length === "number" || $util.isString(message.traceId))) - return "traceId: buffer expected"; - return null; - }; - /** - * Creates an Exemplar message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.metrics.v1.Exemplar - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.metrics.v1.Exemplar} Exemplar - */ - Exemplar.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.metrics.v1.Exemplar) - return object; - var message = new $root.opentelemetry.proto.metrics.v1.Exemplar(); - if (object.filteredAttributes) { - if (!Array.isArray(object.filteredAttributes)) - throw TypeError(".opentelemetry.proto.metrics.v1.Exemplar.filteredAttributes: array expected"); - message.filteredAttributes = []; - for (var i = 0; i < object.filteredAttributes.length; ++i) { - if (typeof object.filteredAttributes[i] !== "object") - throw TypeError(".opentelemetry.proto.metrics.v1.Exemplar.filteredAttributes: object expected"); - message.filteredAttributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.filteredAttributes[i]); - } - } - if (object.timeUnixNano != null) - if ($util.Long) - (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false; - else if (typeof object.timeUnixNano === "string") - message.timeUnixNano = parseInt(object.timeUnixNano, 10); - else if (typeof object.timeUnixNano === "number") - message.timeUnixNano = object.timeUnixNano; - else if (typeof object.timeUnixNano === "object") - message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber(); - if (object.asDouble != null) - message.asDouble = Number(object.asDouble); - if (object.asInt != null) - if ($util.Long) - (message.asInt = $util.Long.fromValue(object.asInt)).unsigned = false; - else if (typeof object.asInt === "string") - message.asInt = parseInt(object.asInt, 10); - else if (typeof object.asInt === "number") - message.asInt = object.asInt; - else if (typeof object.asInt === "object") - message.asInt = new $util.LongBits(object.asInt.low >>> 0, object.asInt.high >>> 0).toNumber(); - if (object.spanId != null) - if (typeof object.spanId === "string") - $util.base64.decode(object.spanId, message.spanId = $util.newBuffer($util.base64.length(object.spanId)), 0); - else if (object.spanId.length >= 0) - message.spanId = object.spanId; - if (object.traceId != null) - if (typeof object.traceId === "string") - $util.base64.decode(object.traceId, message.traceId = $util.newBuffer($util.base64.length(object.traceId)), 0); - else if (object.traceId.length >= 0) - message.traceId = object.traceId; - return message; - }; - /** - * Creates a plain object from an Exemplar message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.metrics.v1.Exemplar - * @static - * @param {opentelemetry.proto.metrics.v1.Exemplar} message Exemplar - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - Exemplar.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.filteredAttributes = []; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.timeUnixNano = options.longs === String ? "0" : 0; - if (options.bytes === String) - object.spanId = ""; - else { - object.spanId = []; - if (options.bytes !== Array) - object.spanId = $util.newBuffer(object.spanId); - } - if (options.bytes === String) - object.traceId = ""; - else { - object.traceId = []; - if (options.bytes !== Array) - object.traceId = $util.newBuffer(object.traceId); - } - } - if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) - if (typeof message.timeUnixNano === "number") - object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano; - else - object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano; - if (message.asDouble != null && message.hasOwnProperty("asDouble")) { - object.asDouble = options.json && !isFinite(message.asDouble) ? String(message.asDouble) : message.asDouble; - if (options.oneofs) - object.value = "asDouble"; - } - if (message.spanId != null && message.hasOwnProperty("spanId")) - object.spanId = options.bytes === String ? $util.base64.encode(message.spanId, 0, message.spanId.length) : options.bytes === Array ? Array.prototype.slice.call(message.spanId) : message.spanId; - if (message.traceId != null && message.hasOwnProperty("traceId")) - object.traceId = options.bytes === String ? $util.base64.encode(message.traceId, 0, message.traceId.length) : options.bytes === Array ? Array.prototype.slice.call(message.traceId) : message.traceId; - if (message.asInt != null && message.hasOwnProperty("asInt")) { - if (typeof message.asInt === "number") - object.asInt = options.longs === String ? String(message.asInt) : message.asInt; - else - object.asInt = options.longs === String ? $util.Long.prototype.toString.call(message.asInt) : options.longs === Number ? new $util.LongBits(message.asInt.low >>> 0, message.asInt.high >>> 0).toNumber() : message.asInt; - if (options.oneofs) - object.value = "asInt"; - } - if (message.filteredAttributes && message.filteredAttributes.length) { - object.filteredAttributes = []; - for (var j = 0; j < message.filteredAttributes.length; ++j) - object.filteredAttributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.filteredAttributes[j], options); - } - return object; - }; - /** - * Converts this Exemplar to JSON. - * @function toJSON - * @memberof opentelemetry.proto.metrics.v1.Exemplar - * @instance - * @returns {Object.} JSON object - */ - Exemplar.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for Exemplar - * @function getTypeUrl - * @memberof opentelemetry.proto.metrics.v1.Exemplar - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - Exemplar.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.metrics.v1.Exemplar"; - }; - return Exemplar; - })(); - return v1; - })(); - return metrics; - })(); - proto.logs = (function () { - /** - * Namespace logs. - * @memberof opentelemetry.proto - * @namespace - */ - var logs = {}; - logs.v1 = (function () { - /** - * Namespace v1. - * @memberof opentelemetry.proto.logs - * @namespace - */ - var v1 = {}; - v1.LogsData = (function () { - /** - * Properties of a LogsData. - * @memberof opentelemetry.proto.logs.v1 - * @interface ILogsData - * @property {Array.|null} [resourceLogs] LogsData resourceLogs - */ - /** - * Constructs a new LogsData. - * @memberof opentelemetry.proto.logs.v1 - * @classdesc Represents a LogsData. - * @implements ILogsData - * @constructor - * @param {opentelemetry.proto.logs.v1.ILogsData=} [properties] Properties to set - */ - function LogsData(properties) { - this.resourceLogs = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * LogsData resourceLogs. - * @member {Array.} resourceLogs - * @memberof opentelemetry.proto.logs.v1.LogsData - * @instance - */ - LogsData.prototype.resourceLogs = $util.emptyArray; - /** - * Creates a new LogsData instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.logs.v1.LogsData - * @static - * @param {opentelemetry.proto.logs.v1.ILogsData=} [properties] Properties to set - * @returns {opentelemetry.proto.logs.v1.LogsData} LogsData instance - */ - LogsData.create = function create(properties) { - return new LogsData(properties); - }; - /** - * Encodes the specified LogsData message. Does not implicitly {@link opentelemetry.proto.logs.v1.LogsData.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.logs.v1.LogsData - * @static - * @param {opentelemetry.proto.logs.v1.ILogsData} message LogsData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - LogsData.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.resourceLogs != null && message.resourceLogs.length) - for (var i = 0; i < message.resourceLogs.length; ++i) - $root.opentelemetry.proto.logs.v1.ResourceLogs.encode(message.resourceLogs[i], writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - return writer; - }; - /** - * Encodes the specified LogsData message, length delimited. Does not implicitly {@link opentelemetry.proto.logs.v1.LogsData.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.logs.v1.LogsData - * @static - * @param {opentelemetry.proto.logs.v1.ILogsData} message LogsData message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - LogsData.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a LogsData message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.logs.v1.LogsData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.logs.v1.LogsData} LogsData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - LogsData.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.logs.v1.LogsData(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - if (!(message.resourceLogs && message.resourceLogs.length)) - message.resourceLogs = []; - message.resourceLogs.push($root.opentelemetry.proto.logs.v1.ResourceLogs.decode(reader, reader.uint32())); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a LogsData message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.logs.v1.LogsData - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.logs.v1.LogsData} LogsData - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - LogsData.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a LogsData message. - * @function verify - * @memberof opentelemetry.proto.logs.v1.LogsData - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - LogsData.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.resourceLogs != null && message.hasOwnProperty("resourceLogs")) { - if (!Array.isArray(message.resourceLogs)) - return "resourceLogs: array expected"; - for (var i = 0; i < message.resourceLogs.length; ++i) { - var error = $root.opentelemetry.proto.logs.v1.ResourceLogs.verify(message.resourceLogs[i]); - if (error) - return "resourceLogs." + error; - } - } - return null; - }; - /** - * Creates a LogsData message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.logs.v1.LogsData - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.logs.v1.LogsData} LogsData - */ - LogsData.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.logs.v1.LogsData) - return object; - var message = new $root.opentelemetry.proto.logs.v1.LogsData(); - if (object.resourceLogs) { - if (!Array.isArray(object.resourceLogs)) - throw TypeError(".opentelemetry.proto.logs.v1.LogsData.resourceLogs: array expected"); - message.resourceLogs = []; - for (var i = 0; i < object.resourceLogs.length; ++i) { - if (typeof object.resourceLogs[i] !== "object") - throw TypeError(".opentelemetry.proto.logs.v1.LogsData.resourceLogs: object expected"); - message.resourceLogs[i] = $root.opentelemetry.proto.logs.v1.ResourceLogs.fromObject(object.resourceLogs[i]); - } - } - return message; - }; - /** - * Creates a plain object from a LogsData message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.logs.v1.LogsData - * @static - * @param {opentelemetry.proto.logs.v1.LogsData} message LogsData - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - LogsData.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.resourceLogs = []; - if (message.resourceLogs && message.resourceLogs.length) { - object.resourceLogs = []; - for (var j = 0; j < message.resourceLogs.length; ++j) - object.resourceLogs[j] = $root.opentelemetry.proto.logs.v1.ResourceLogs.toObject(message.resourceLogs[j], options); - } - return object; - }; - /** - * Converts this LogsData to JSON. - * @function toJSON - * @memberof opentelemetry.proto.logs.v1.LogsData - * @instance - * @returns {Object.} JSON object - */ - LogsData.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for LogsData - * @function getTypeUrl - * @memberof opentelemetry.proto.logs.v1.LogsData - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - LogsData.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.logs.v1.LogsData"; - }; - return LogsData; - })(); - v1.ResourceLogs = (function () { - /** - * Properties of a ResourceLogs. - * @memberof opentelemetry.proto.logs.v1 - * @interface IResourceLogs - * @property {opentelemetry.proto.resource.v1.IResource|null} [resource] ResourceLogs resource - * @property {Array.|null} [scopeLogs] ResourceLogs scopeLogs - * @property {string|null} [schemaUrl] ResourceLogs schemaUrl - */ - /** - * Constructs a new ResourceLogs. - * @memberof opentelemetry.proto.logs.v1 - * @classdesc Represents a ResourceLogs. - * @implements IResourceLogs - * @constructor - * @param {opentelemetry.proto.logs.v1.IResourceLogs=} [properties] Properties to set - */ - function ResourceLogs(properties) { - this.scopeLogs = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * ResourceLogs resource. - * @member {opentelemetry.proto.resource.v1.IResource|null|undefined} resource - * @memberof opentelemetry.proto.logs.v1.ResourceLogs - * @instance - */ - ResourceLogs.prototype.resource = null; - /** - * ResourceLogs scopeLogs. - * @member {Array.} scopeLogs - * @memberof opentelemetry.proto.logs.v1.ResourceLogs - * @instance - */ - ResourceLogs.prototype.scopeLogs = $util.emptyArray; - /** - * ResourceLogs schemaUrl. - * @member {string|null|undefined} schemaUrl - * @memberof opentelemetry.proto.logs.v1.ResourceLogs - * @instance - */ - ResourceLogs.prototype.schemaUrl = null; - /** - * Creates a new ResourceLogs instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.logs.v1.ResourceLogs - * @static - * @param {opentelemetry.proto.logs.v1.IResourceLogs=} [properties] Properties to set - * @returns {opentelemetry.proto.logs.v1.ResourceLogs} ResourceLogs instance - */ - ResourceLogs.create = function create(properties) { - return new ResourceLogs(properties); - }; - /** - * Encodes the specified ResourceLogs message. Does not implicitly {@link opentelemetry.proto.logs.v1.ResourceLogs.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.logs.v1.ResourceLogs - * @static - * @param {opentelemetry.proto.logs.v1.IResourceLogs} message ResourceLogs message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ResourceLogs.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.resource != null && Object.hasOwnProperty.call(message, "resource")) - $root.opentelemetry.proto.resource.v1.Resource.encode(message.resource, writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - if (message.scopeLogs != null && message.scopeLogs.length) - for (var i = 0; i < message.scopeLogs.length; ++i) - $root.opentelemetry.proto.logs.v1.ScopeLogs.encode(message.scopeLogs[i], writer.uint32(/* id 2, wireType 2 =*/ 18).fork()).ldelim(); - if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl")) - writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.schemaUrl); - return writer; - }; - /** - * Encodes the specified ResourceLogs message, length delimited. Does not implicitly {@link opentelemetry.proto.logs.v1.ResourceLogs.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.logs.v1.ResourceLogs - * @static - * @param {opentelemetry.proto.logs.v1.IResourceLogs} message ResourceLogs message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ResourceLogs.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a ResourceLogs message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.logs.v1.ResourceLogs - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.logs.v1.ResourceLogs} ResourceLogs - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ResourceLogs.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.logs.v1.ResourceLogs(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.resource = $root.opentelemetry.proto.resource.v1.Resource.decode(reader, reader.uint32()); - break; - } - case 2: { - if (!(message.scopeLogs && message.scopeLogs.length)) - message.scopeLogs = []; - message.scopeLogs.push($root.opentelemetry.proto.logs.v1.ScopeLogs.decode(reader, reader.uint32())); - break; - } - case 3: { - message.schemaUrl = reader.string(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a ResourceLogs message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.logs.v1.ResourceLogs - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.logs.v1.ResourceLogs} ResourceLogs - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ResourceLogs.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a ResourceLogs message. - * @function verify - * @memberof opentelemetry.proto.logs.v1.ResourceLogs - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ResourceLogs.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.resource != null && message.hasOwnProperty("resource")) { - var error = $root.opentelemetry.proto.resource.v1.Resource.verify(message.resource); - if (error) - return "resource." + error; - } - if (message.scopeLogs != null && message.hasOwnProperty("scopeLogs")) { - if (!Array.isArray(message.scopeLogs)) - return "scopeLogs: array expected"; - for (var i = 0; i < message.scopeLogs.length; ++i) { - var error = $root.opentelemetry.proto.logs.v1.ScopeLogs.verify(message.scopeLogs[i]); - if (error) - return "scopeLogs." + error; - } - } - if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) - if (!$util.isString(message.schemaUrl)) - return "schemaUrl: string expected"; - return null; - }; - /** - * Creates a ResourceLogs message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.logs.v1.ResourceLogs - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.logs.v1.ResourceLogs} ResourceLogs - */ - ResourceLogs.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.logs.v1.ResourceLogs) - return object; - var message = new $root.opentelemetry.proto.logs.v1.ResourceLogs(); - if (object.resource != null) { - if (typeof object.resource !== "object") - throw TypeError(".opentelemetry.proto.logs.v1.ResourceLogs.resource: object expected"); - message.resource = $root.opentelemetry.proto.resource.v1.Resource.fromObject(object.resource); - } - if (object.scopeLogs) { - if (!Array.isArray(object.scopeLogs)) - throw TypeError(".opentelemetry.proto.logs.v1.ResourceLogs.scopeLogs: array expected"); - message.scopeLogs = []; - for (var i = 0; i < object.scopeLogs.length; ++i) { - if (typeof object.scopeLogs[i] !== "object") - throw TypeError(".opentelemetry.proto.logs.v1.ResourceLogs.scopeLogs: object expected"); - message.scopeLogs[i] = $root.opentelemetry.proto.logs.v1.ScopeLogs.fromObject(object.scopeLogs[i]); - } - } - if (object.schemaUrl != null) - message.schemaUrl = String(object.schemaUrl); - return message; - }; - /** - * Creates a plain object from a ResourceLogs message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.logs.v1.ResourceLogs - * @static - * @param {opentelemetry.proto.logs.v1.ResourceLogs} message ResourceLogs - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ResourceLogs.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.scopeLogs = []; - if (options.defaults) { - object.resource = null; - object.schemaUrl = ""; - } - if (message.resource != null && message.hasOwnProperty("resource")) - object.resource = $root.opentelemetry.proto.resource.v1.Resource.toObject(message.resource, options); - if (message.scopeLogs && message.scopeLogs.length) { - object.scopeLogs = []; - for (var j = 0; j < message.scopeLogs.length; ++j) - object.scopeLogs[j] = $root.opentelemetry.proto.logs.v1.ScopeLogs.toObject(message.scopeLogs[j], options); - } - if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) - object.schemaUrl = message.schemaUrl; - return object; - }; - /** - * Converts this ResourceLogs to JSON. - * @function toJSON - * @memberof opentelemetry.proto.logs.v1.ResourceLogs - * @instance - * @returns {Object.} JSON object - */ - ResourceLogs.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for ResourceLogs - * @function getTypeUrl - * @memberof opentelemetry.proto.logs.v1.ResourceLogs - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ResourceLogs.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.logs.v1.ResourceLogs"; - }; - return ResourceLogs; - })(); - v1.ScopeLogs = (function () { - /** - * Properties of a ScopeLogs. - * @memberof opentelemetry.proto.logs.v1 - * @interface IScopeLogs - * @property {opentelemetry.proto.common.v1.IInstrumentationScope|null} [scope] ScopeLogs scope - * @property {Array.|null} [logRecords] ScopeLogs logRecords - * @property {string|null} [schemaUrl] ScopeLogs schemaUrl - */ - /** - * Constructs a new ScopeLogs. - * @memberof opentelemetry.proto.logs.v1 - * @classdesc Represents a ScopeLogs. - * @implements IScopeLogs - * @constructor - * @param {opentelemetry.proto.logs.v1.IScopeLogs=} [properties] Properties to set - */ - function ScopeLogs(properties) { - this.logRecords = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * ScopeLogs scope. - * @member {opentelemetry.proto.common.v1.IInstrumentationScope|null|undefined} scope - * @memberof opentelemetry.proto.logs.v1.ScopeLogs - * @instance - */ - ScopeLogs.prototype.scope = null; - /** - * ScopeLogs logRecords. - * @member {Array.} logRecords - * @memberof opentelemetry.proto.logs.v1.ScopeLogs - * @instance - */ - ScopeLogs.prototype.logRecords = $util.emptyArray; - /** - * ScopeLogs schemaUrl. - * @member {string|null|undefined} schemaUrl - * @memberof opentelemetry.proto.logs.v1.ScopeLogs - * @instance - */ - ScopeLogs.prototype.schemaUrl = null; - /** - * Creates a new ScopeLogs instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.logs.v1.ScopeLogs - * @static - * @param {opentelemetry.proto.logs.v1.IScopeLogs=} [properties] Properties to set - * @returns {opentelemetry.proto.logs.v1.ScopeLogs} ScopeLogs instance - */ - ScopeLogs.create = function create(properties) { - return new ScopeLogs(properties); - }; - /** - * Encodes the specified ScopeLogs message. Does not implicitly {@link opentelemetry.proto.logs.v1.ScopeLogs.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.logs.v1.ScopeLogs - * @static - * @param {opentelemetry.proto.logs.v1.IScopeLogs} message ScopeLogs message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ScopeLogs.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.scope != null && Object.hasOwnProperty.call(message, "scope")) - $root.opentelemetry.proto.common.v1.InstrumentationScope.encode(message.scope, writer.uint32(/* id 1, wireType 2 =*/ 10).fork()).ldelim(); - if (message.logRecords != null && message.logRecords.length) - for (var i = 0; i < message.logRecords.length; ++i) - $root.opentelemetry.proto.logs.v1.LogRecord.encode(message.logRecords[i], writer.uint32(/* id 2, wireType 2 =*/ 18).fork()).ldelim(); - if (message.schemaUrl != null && Object.hasOwnProperty.call(message, "schemaUrl")) - writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.schemaUrl); - return writer; - }; - /** - * Encodes the specified ScopeLogs message, length delimited. Does not implicitly {@link opentelemetry.proto.logs.v1.ScopeLogs.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.logs.v1.ScopeLogs - * @static - * @param {opentelemetry.proto.logs.v1.IScopeLogs} message ScopeLogs message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - ScopeLogs.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a ScopeLogs message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.logs.v1.ScopeLogs - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.logs.v1.ScopeLogs} ScopeLogs - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ScopeLogs.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.logs.v1.ScopeLogs(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.decode(reader, reader.uint32()); - break; - } - case 2: { - if (!(message.logRecords && message.logRecords.length)) - message.logRecords = []; - message.logRecords.push($root.opentelemetry.proto.logs.v1.LogRecord.decode(reader, reader.uint32())); - break; - } - case 3: { - message.schemaUrl = reader.string(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a ScopeLogs message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.logs.v1.ScopeLogs - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.logs.v1.ScopeLogs} ScopeLogs - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - ScopeLogs.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a ScopeLogs message. - * @function verify - * @memberof opentelemetry.proto.logs.v1.ScopeLogs - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - ScopeLogs.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.scope != null && message.hasOwnProperty("scope")) { - var error = $root.opentelemetry.proto.common.v1.InstrumentationScope.verify(message.scope); - if (error) - return "scope." + error; - } - if (message.logRecords != null && message.hasOwnProperty("logRecords")) { - if (!Array.isArray(message.logRecords)) - return "logRecords: array expected"; - for (var i = 0; i < message.logRecords.length; ++i) { - var error = $root.opentelemetry.proto.logs.v1.LogRecord.verify(message.logRecords[i]); - if (error) - return "logRecords." + error; - } - } - if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) - if (!$util.isString(message.schemaUrl)) - return "schemaUrl: string expected"; - return null; - }; - /** - * Creates a ScopeLogs message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.logs.v1.ScopeLogs - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.logs.v1.ScopeLogs} ScopeLogs - */ - ScopeLogs.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.logs.v1.ScopeLogs) - return object; - var message = new $root.opentelemetry.proto.logs.v1.ScopeLogs(); - if (object.scope != null) { - if (typeof object.scope !== "object") - throw TypeError(".opentelemetry.proto.logs.v1.ScopeLogs.scope: object expected"); - message.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.fromObject(object.scope); - } - if (object.logRecords) { - if (!Array.isArray(object.logRecords)) - throw TypeError(".opentelemetry.proto.logs.v1.ScopeLogs.logRecords: array expected"); - message.logRecords = []; - for (var i = 0; i < object.logRecords.length; ++i) { - if (typeof object.logRecords[i] !== "object") - throw TypeError(".opentelemetry.proto.logs.v1.ScopeLogs.logRecords: object expected"); - message.logRecords[i] = $root.opentelemetry.proto.logs.v1.LogRecord.fromObject(object.logRecords[i]); - } - } - if (object.schemaUrl != null) - message.schemaUrl = String(object.schemaUrl); - return message; - }; - /** - * Creates a plain object from a ScopeLogs message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.logs.v1.ScopeLogs - * @static - * @param {opentelemetry.proto.logs.v1.ScopeLogs} message ScopeLogs - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - ScopeLogs.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.logRecords = []; - if (options.defaults) { - object.scope = null; - object.schemaUrl = ""; - } - if (message.scope != null && message.hasOwnProperty("scope")) - object.scope = $root.opentelemetry.proto.common.v1.InstrumentationScope.toObject(message.scope, options); - if (message.logRecords && message.logRecords.length) { - object.logRecords = []; - for (var j = 0; j < message.logRecords.length; ++j) - object.logRecords[j] = $root.opentelemetry.proto.logs.v1.LogRecord.toObject(message.logRecords[j], options); - } - if (message.schemaUrl != null && message.hasOwnProperty("schemaUrl")) - object.schemaUrl = message.schemaUrl; - return object; - }; - /** - * Converts this ScopeLogs to JSON. - * @function toJSON - * @memberof opentelemetry.proto.logs.v1.ScopeLogs - * @instance - * @returns {Object.} JSON object - */ - ScopeLogs.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for ScopeLogs - * @function getTypeUrl - * @memberof opentelemetry.proto.logs.v1.ScopeLogs - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - ScopeLogs.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.logs.v1.ScopeLogs"; - }; - return ScopeLogs; - })(); - /** - * SeverityNumber enum. - * @name opentelemetry.proto.logs.v1.SeverityNumber - * @enum {number} - * @property {number} SEVERITY_NUMBER_UNSPECIFIED=0 SEVERITY_NUMBER_UNSPECIFIED value - * @property {number} SEVERITY_NUMBER_TRACE=1 SEVERITY_NUMBER_TRACE value - * @property {number} SEVERITY_NUMBER_TRACE2=2 SEVERITY_NUMBER_TRACE2 value - * @property {number} SEVERITY_NUMBER_TRACE3=3 SEVERITY_NUMBER_TRACE3 value - * @property {number} SEVERITY_NUMBER_TRACE4=4 SEVERITY_NUMBER_TRACE4 value - * @property {number} SEVERITY_NUMBER_DEBUG=5 SEVERITY_NUMBER_DEBUG value - * @property {number} SEVERITY_NUMBER_DEBUG2=6 SEVERITY_NUMBER_DEBUG2 value - * @property {number} SEVERITY_NUMBER_DEBUG3=7 SEVERITY_NUMBER_DEBUG3 value - * @property {number} SEVERITY_NUMBER_DEBUG4=8 SEVERITY_NUMBER_DEBUG4 value - * @property {number} SEVERITY_NUMBER_INFO=9 SEVERITY_NUMBER_INFO value - * @property {number} SEVERITY_NUMBER_INFO2=10 SEVERITY_NUMBER_INFO2 value - * @property {number} SEVERITY_NUMBER_INFO3=11 SEVERITY_NUMBER_INFO3 value - * @property {number} SEVERITY_NUMBER_INFO4=12 SEVERITY_NUMBER_INFO4 value - * @property {number} SEVERITY_NUMBER_WARN=13 SEVERITY_NUMBER_WARN value - * @property {number} SEVERITY_NUMBER_WARN2=14 SEVERITY_NUMBER_WARN2 value - * @property {number} SEVERITY_NUMBER_WARN3=15 SEVERITY_NUMBER_WARN3 value - * @property {number} SEVERITY_NUMBER_WARN4=16 SEVERITY_NUMBER_WARN4 value - * @property {number} SEVERITY_NUMBER_ERROR=17 SEVERITY_NUMBER_ERROR value - * @property {number} SEVERITY_NUMBER_ERROR2=18 SEVERITY_NUMBER_ERROR2 value - * @property {number} SEVERITY_NUMBER_ERROR3=19 SEVERITY_NUMBER_ERROR3 value - * @property {number} SEVERITY_NUMBER_ERROR4=20 SEVERITY_NUMBER_ERROR4 value - * @property {number} SEVERITY_NUMBER_FATAL=21 SEVERITY_NUMBER_FATAL value - * @property {number} SEVERITY_NUMBER_FATAL2=22 SEVERITY_NUMBER_FATAL2 value - * @property {number} SEVERITY_NUMBER_FATAL3=23 SEVERITY_NUMBER_FATAL3 value - * @property {number} SEVERITY_NUMBER_FATAL4=24 SEVERITY_NUMBER_FATAL4 value - */ - v1.SeverityNumber = (function () { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "SEVERITY_NUMBER_UNSPECIFIED"] = 0; - values[valuesById[1] = "SEVERITY_NUMBER_TRACE"] = 1; - values[valuesById[2] = "SEVERITY_NUMBER_TRACE2"] = 2; - values[valuesById[3] = "SEVERITY_NUMBER_TRACE3"] = 3; - values[valuesById[4] = "SEVERITY_NUMBER_TRACE4"] = 4; - values[valuesById[5] = "SEVERITY_NUMBER_DEBUG"] = 5; - values[valuesById[6] = "SEVERITY_NUMBER_DEBUG2"] = 6; - values[valuesById[7] = "SEVERITY_NUMBER_DEBUG3"] = 7; - values[valuesById[8] = "SEVERITY_NUMBER_DEBUG4"] = 8; - values[valuesById[9] = "SEVERITY_NUMBER_INFO"] = 9; - values[valuesById[10] = "SEVERITY_NUMBER_INFO2"] = 10; - values[valuesById[11] = "SEVERITY_NUMBER_INFO3"] = 11; - values[valuesById[12] = "SEVERITY_NUMBER_INFO4"] = 12; - values[valuesById[13] = "SEVERITY_NUMBER_WARN"] = 13; - values[valuesById[14] = "SEVERITY_NUMBER_WARN2"] = 14; - values[valuesById[15] = "SEVERITY_NUMBER_WARN3"] = 15; - values[valuesById[16] = "SEVERITY_NUMBER_WARN4"] = 16; - values[valuesById[17] = "SEVERITY_NUMBER_ERROR"] = 17; - values[valuesById[18] = "SEVERITY_NUMBER_ERROR2"] = 18; - values[valuesById[19] = "SEVERITY_NUMBER_ERROR3"] = 19; - values[valuesById[20] = "SEVERITY_NUMBER_ERROR4"] = 20; - values[valuesById[21] = "SEVERITY_NUMBER_FATAL"] = 21; - values[valuesById[22] = "SEVERITY_NUMBER_FATAL2"] = 22; - values[valuesById[23] = "SEVERITY_NUMBER_FATAL3"] = 23; - values[valuesById[24] = "SEVERITY_NUMBER_FATAL4"] = 24; - return values; - })(); - /** - * LogRecordFlags enum. - * @name opentelemetry.proto.logs.v1.LogRecordFlags - * @enum {number} - * @property {number} LOG_RECORD_FLAGS_DO_NOT_USE=0 LOG_RECORD_FLAGS_DO_NOT_USE value - * @property {number} LOG_RECORD_FLAGS_TRACE_FLAGS_MASK=255 LOG_RECORD_FLAGS_TRACE_FLAGS_MASK value - */ - v1.LogRecordFlags = (function () { - var valuesById = {}, values = Object.create(valuesById); - values[valuesById[0] = "LOG_RECORD_FLAGS_DO_NOT_USE"] = 0; - values[valuesById[255] = "LOG_RECORD_FLAGS_TRACE_FLAGS_MASK"] = 255; - return values; - })(); - v1.LogRecord = (function () { - /** - * Properties of a LogRecord. - * @memberof opentelemetry.proto.logs.v1 - * @interface ILogRecord - * @property {number|Long|null} [timeUnixNano] LogRecord timeUnixNano - * @property {number|Long|null} [observedTimeUnixNano] LogRecord observedTimeUnixNano - * @property {opentelemetry.proto.logs.v1.SeverityNumber|null} [severityNumber] LogRecord severityNumber - * @property {string|null} [severityText] LogRecord severityText - * @property {opentelemetry.proto.common.v1.IAnyValue|null} [body] LogRecord body - * @property {Array.|null} [attributes] LogRecord attributes - * @property {number|null} [droppedAttributesCount] LogRecord droppedAttributesCount - * @property {number|null} [flags] LogRecord flags - * @property {Uint8Array|null} [traceId] LogRecord traceId - * @property {Uint8Array|null} [spanId] LogRecord spanId - * @property {string|null} [eventName] LogRecord eventName - */ - /** - * Constructs a new LogRecord. - * @memberof opentelemetry.proto.logs.v1 - * @classdesc Represents a LogRecord. - * @implements ILogRecord - * @constructor - * @param {opentelemetry.proto.logs.v1.ILogRecord=} [properties] Properties to set - */ - function LogRecord(properties) { - this.attributes = []; - if (properties) - for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) - if (properties[keys[i]] != null) - this[keys[i]] = properties[keys[i]]; - } - /** - * LogRecord timeUnixNano. - * @member {number|Long|null|undefined} timeUnixNano - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @instance - */ - LogRecord.prototype.timeUnixNano = null; - /** - * LogRecord observedTimeUnixNano. - * @member {number|Long|null|undefined} observedTimeUnixNano - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @instance - */ - LogRecord.prototype.observedTimeUnixNano = null; - /** - * LogRecord severityNumber. - * @member {opentelemetry.proto.logs.v1.SeverityNumber|null|undefined} severityNumber - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @instance - */ - LogRecord.prototype.severityNumber = null; - /** - * LogRecord severityText. - * @member {string|null|undefined} severityText - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @instance - */ - LogRecord.prototype.severityText = null; - /** - * LogRecord body. - * @member {opentelemetry.proto.common.v1.IAnyValue|null|undefined} body - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @instance - */ - LogRecord.prototype.body = null; - /** - * LogRecord attributes. - * @member {Array.} attributes - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @instance - */ - LogRecord.prototype.attributes = $util.emptyArray; - /** - * LogRecord droppedAttributesCount. - * @member {number|null|undefined} droppedAttributesCount - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @instance - */ - LogRecord.prototype.droppedAttributesCount = null; - /** - * LogRecord flags. - * @member {number|null|undefined} flags - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @instance - */ - LogRecord.prototype.flags = null; - /** - * LogRecord traceId. - * @member {Uint8Array|null|undefined} traceId - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @instance - */ - LogRecord.prototype.traceId = null; - /** - * LogRecord spanId. - * @member {Uint8Array|null|undefined} spanId - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @instance - */ - LogRecord.prototype.spanId = null; - /** - * LogRecord eventName. - * @member {string|null|undefined} eventName - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @instance - */ - LogRecord.prototype.eventName = null; - /** - * Creates a new LogRecord instance using the specified properties. - * @function create - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @static - * @param {opentelemetry.proto.logs.v1.ILogRecord=} [properties] Properties to set - * @returns {opentelemetry.proto.logs.v1.LogRecord} LogRecord instance - */ - LogRecord.create = function create(properties) { - return new LogRecord(properties); - }; - /** - * Encodes the specified LogRecord message. Does not implicitly {@link opentelemetry.proto.logs.v1.LogRecord.verify|verify} messages. - * @function encode - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @static - * @param {opentelemetry.proto.logs.v1.ILogRecord} message LogRecord message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - LogRecord.encode = function encode(message, writer) { - if (!writer) - writer = $Writer.create(); - if (message.timeUnixNano != null && Object.hasOwnProperty.call(message, "timeUnixNano")) - writer.uint32(/* id 1, wireType 1 =*/ 9).fixed64(message.timeUnixNano); - if (message.severityNumber != null && Object.hasOwnProperty.call(message, "severityNumber")) - writer.uint32(/* id 2, wireType 0 =*/ 16).int32(message.severityNumber); - if (message.severityText != null && Object.hasOwnProperty.call(message, "severityText")) - writer.uint32(/* id 3, wireType 2 =*/ 26).string(message.severityText); - if (message.body != null && Object.hasOwnProperty.call(message, "body")) - $root.opentelemetry.proto.common.v1.AnyValue.encode(message.body, writer.uint32(/* id 5, wireType 2 =*/ 42).fork()).ldelim(); - if (message.attributes != null && message.attributes.length) - for (var i = 0; i < message.attributes.length; ++i) - $root.opentelemetry.proto.common.v1.KeyValue.encode(message.attributes[i], writer.uint32(/* id 6, wireType 2 =*/ 50).fork()).ldelim(); - if (message.droppedAttributesCount != null && Object.hasOwnProperty.call(message, "droppedAttributesCount")) - writer.uint32(/* id 7, wireType 0 =*/ 56).uint32(message.droppedAttributesCount); - if (message.flags != null && Object.hasOwnProperty.call(message, "flags")) - writer.uint32(/* id 8, wireType 5 =*/ 69).fixed32(message.flags); - if (message.traceId != null && Object.hasOwnProperty.call(message, "traceId")) - writer.uint32(/* id 9, wireType 2 =*/ 74).bytes(message.traceId); - if (message.spanId != null && Object.hasOwnProperty.call(message, "spanId")) - writer.uint32(/* id 10, wireType 2 =*/ 82).bytes(message.spanId); - if (message.observedTimeUnixNano != null && Object.hasOwnProperty.call(message, "observedTimeUnixNano")) - writer.uint32(/* id 11, wireType 1 =*/ 89).fixed64(message.observedTimeUnixNano); - if (message.eventName != null && Object.hasOwnProperty.call(message, "eventName")) - writer.uint32(/* id 12, wireType 2 =*/ 98).string(message.eventName); - return writer; - }; - /** - * Encodes the specified LogRecord message, length delimited. Does not implicitly {@link opentelemetry.proto.logs.v1.LogRecord.verify|verify} messages. - * @function encodeDelimited - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @static - * @param {opentelemetry.proto.logs.v1.ILogRecord} message LogRecord message or plain object to encode - * @param {$protobuf.Writer} [writer] Writer to encode to - * @returns {$protobuf.Writer} Writer - */ - LogRecord.encodeDelimited = function encodeDelimited(message, writer) { - return this.encode(message, writer).ldelim(); - }; - /** - * Decodes a LogRecord message from the specified reader or buffer. - * @function decode - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @param {number} [length] Message length if known beforehand - * @returns {opentelemetry.proto.logs.v1.LogRecord} LogRecord - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - LogRecord.decode = function decode(reader, length, error) { - if (!(reader instanceof $Reader)) - reader = $Reader.create(reader); - var end = length === undefined ? reader.len : reader.pos + length, message = new $root.opentelemetry.proto.logs.v1.LogRecord(); - while (reader.pos < end) { - var tag = reader.uint32(); - if (tag === error) - break; - switch (tag >>> 3) { - case 1: { - message.timeUnixNano = reader.fixed64(); - break; - } - case 11: { - message.observedTimeUnixNano = reader.fixed64(); - break; - } - case 2: { - message.severityNumber = reader.int32(); - break; - } - case 3: { - message.severityText = reader.string(); - break; - } - case 5: { - message.body = $root.opentelemetry.proto.common.v1.AnyValue.decode(reader, reader.uint32()); - break; - } - case 6: { - if (!(message.attributes && message.attributes.length)) - message.attributes = []; - message.attributes.push($root.opentelemetry.proto.common.v1.KeyValue.decode(reader, reader.uint32())); - break; - } - case 7: { - message.droppedAttributesCount = reader.uint32(); - break; - } - case 8: { - message.flags = reader.fixed32(); - break; - } - case 9: { - message.traceId = reader.bytes(); - break; - } - case 10: { - message.spanId = reader.bytes(); - break; - } - case 12: { - message.eventName = reader.string(); - break; - } - default: - reader.skipType(tag & 7); - break; - } - } - return message; - }; - /** - * Decodes a LogRecord message from the specified reader or buffer, length delimited. - * @function decodeDelimited - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @static - * @param {$protobuf.Reader|Uint8Array} reader Reader or buffer to decode from - * @returns {opentelemetry.proto.logs.v1.LogRecord} LogRecord - * @throws {Error} If the payload is not a reader or valid buffer - * @throws {$protobuf.util.ProtocolError} If required fields are missing - */ - LogRecord.decodeDelimited = function decodeDelimited(reader) { - if (!(reader instanceof $Reader)) - reader = new $Reader(reader); - return this.decode(reader, reader.uint32()); - }; - /** - * Verifies a LogRecord message. - * @function verify - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @static - * @param {Object.} message Plain object to verify - * @returns {string|null} `null` if valid, otherwise the reason why it is not - */ - LogRecord.verify = function verify(message) { - if (typeof message !== "object" || message === null) - return "object expected"; - if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) - if (!$util.isInteger(message.timeUnixNano) && !(message.timeUnixNano && $util.isInteger(message.timeUnixNano.low) && $util.isInteger(message.timeUnixNano.high))) - return "timeUnixNano: integer|Long expected"; - if (message.observedTimeUnixNano != null && message.hasOwnProperty("observedTimeUnixNano")) - if (!$util.isInteger(message.observedTimeUnixNano) && !(message.observedTimeUnixNano && $util.isInteger(message.observedTimeUnixNano.low) && $util.isInteger(message.observedTimeUnixNano.high))) - return "observedTimeUnixNano: integer|Long expected"; - if (message.severityNumber != null && message.hasOwnProperty("severityNumber")) - switch (message.severityNumber) { - default: - return "severityNumber: enum value expected"; - case 0: - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - case 8: - case 9: - case 10: - case 11: - case 12: - case 13: - case 14: - case 15: - case 16: - case 17: - case 18: - case 19: - case 20: - case 21: - case 22: - case 23: - case 24: - break; - } - if (message.severityText != null && message.hasOwnProperty("severityText")) - if (!$util.isString(message.severityText)) - return "severityText: string expected"; - if (message.body != null && message.hasOwnProperty("body")) { - var error = $root.opentelemetry.proto.common.v1.AnyValue.verify(message.body); - if (error) - return "body." + error; - } - if (message.attributes != null && message.hasOwnProperty("attributes")) { - if (!Array.isArray(message.attributes)) - return "attributes: array expected"; - for (var i = 0; i < message.attributes.length; ++i) { - var error = $root.opentelemetry.proto.common.v1.KeyValue.verify(message.attributes[i]); - if (error) - return "attributes." + error; - } - } - if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) - if (!$util.isInteger(message.droppedAttributesCount)) - return "droppedAttributesCount: integer expected"; - if (message.flags != null && message.hasOwnProperty("flags")) - if (!$util.isInteger(message.flags)) - return "flags: integer expected"; - if (message.traceId != null && message.hasOwnProperty("traceId")) - if (!(message.traceId && typeof message.traceId.length === "number" || $util.isString(message.traceId))) - return "traceId: buffer expected"; - if (message.spanId != null && message.hasOwnProperty("spanId")) - if (!(message.spanId && typeof message.spanId.length === "number" || $util.isString(message.spanId))) - return "spanId: buffer expected"; - if (message.eventName != null && message.hasOwnProperty("eventName")) - if (!$util.isString(message.eventName)) - return "eventName: string expected"; - return null; - }; - /** - * Creates a LogRecord message from a plain object. Also converts values to their respective internal types. - * @function fromObject - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @static - * @param {Object.} object Plain object - * @returns {opentelemetry.proto.logs.v1.LogRecord} LogRecord - */ - LogRecord.fromObject = function fromObject(object) { - if (object instanceof $root.opentelemetry.proto.logs.v1.LogRecord) - return object; - var message = new $root.opentelemetry.proto.logs.v1.LogRecord(); - if (object.timeUnixNano != null) - if ($util.Long) - (message.timeUnixNano = $util.Long.fromValue(object.timeUnixNano)).unsigned = false; - else if (typeof object.timeUnixNano === "string") - message.timeUnixNano = parseInt(object.timeUnixNano, 10); - else if (typeof object.timeUnixNano === "number") - message.timeUnixNano = object.timeUnixNano; - else if (typeof object.timeUnixNano === "object") - message.timeUnixNano = new $util.LongBits(object.timeUnixNano.low >>> 0, object.timeUnixNano.high >>> 0).toNumber(); - if (object.observedTimeUnixNano != null) - if ($util.Long) - (message.observedTimeUnixNano = $util.Long.fromValue(object.observedTimeUnixNano)).unsigned = false; - else if (typeof object.observedTimeUnixNano === "string") - message.observedTimeUnixNano = parseInt(object.observedTimeUnixNano, 10); - else if (typeof object.observedTimeUnixNano === "number") - message.observedTimeUnixNano = object.observedTimeUnixNano; - else if (typeof object.observedTimeUnixNano === "object") - message.observedTimeUnixNano = new $util.LongBits(object.observedTimeUnixNano.low >>> 0, object.observedTimeUnixNano.high >>> 0).toNumber(); - switch (object.severityNumber) { - default: - if (typeof object.severityNumber === "number") { - message.severityNumber = object.severityNumber; - break; - } - break; - case "SEVERITY_NUMBER_UNSPECIFIED": - case 0: - message.severityNumber = 0; - break; - case "SEVERITY_NUMBER_TRACE": - case 1: - message.severityNumber = 1; - break; - case "SEVERITY_NUMBER_TRACE2": - case 2: - message.severityNumber = 2; - break; - case "SEVERITY_NUMBER_TRACE3": - case 3: - message.severityNumber = 3; - break; - case "SEVERITY_NUMBER_TRACE4": - case 4: - message.severityNumber = 4; - break; - case "SEVERITY_NUMBER_DEBUG": - case 5: - message.severityNumber = 5; - break; - case "SEVERITY_NUMBER_DEBUG2": - case 6: - message.severityNumber = 6; - break; - case "SEVERITY_NUMBER_DEBUG3": - case 7: - message.severityNumber = 7; - break; - case "SEVERITY_NUMBER_DEBUG4": - case 8: - message.severityNumber = 8; - break; - case "SEVERITY_NUMBER_INFO": - case 9: - message.severityNumber = 9; - break; - case "SEVERITY_NUMBER_INFO2": - case 10: - message.severityNumber = 10; - break; - case "SEVERITY_NUMBER_INFO3": - case 11: - message.severityNumber = 11; - break; - case "SEVERITY_NUMBER_INFO4": - case 12: - message.severityNumber = 12; - break; - case "SEVERITY_NUMBER_WARN": - case 13: - message.severityNumber = 13; - break; - case "SEVERITY_NUMBER_WARN2": - case 14: - message.severityNumber = 14; - break; - case "SEVERITY_NUMBER_WARN3": - case 15: - message.severityNumber = 15; - break; - case "SEVERITY_NUMBER_WARN4": - case 16: - message.severityNumber = 16; - break; - case "SEVERITY_NUMBER_ERROR": - case 17: - message.severityNumber = 17; - break; - case "SEVERITY_NUMBER_ERROR2": - case 18: - message.severityNumber = 18; - break; - case "SEVERITY_NUMBER_ERROR3": - case 19: - message.severityNumber = 19; - break; - case "SEVERITY_NUMBER_ERROR4": - case 20: - message.severityNumber = 20; - break; - case "SEVERITY_NUMBER_FATAL": - case 21: - message.severityNumber = 21; - break; - case "SEVERITY_NUMBER_FATAL2": - case 22: - message.severityNumber = 22; - break; - case "SEVERITY_NUMBER_FATAL3": - case 23: - message.severityNumber = 23; - break; - case "SEVERITY_NUMBER_FATAL4": - case 24: - message.severityNumber = 24; - break; - } - if (object.severityText != null) - message.severityText = String(object.severityText); - if (object.body != null) { - if (typeof object.body !== "object") - throw TypeError(".opentelemetry.proto.logs.v1.LogRecord.body: object expected"); - message.body = $root.opentelemetry.proto.common.v1.AnyValue.fromObject(object.body); - } - if (object.attributes) { - if (!Array.isArray(object.attributes)) - throw TypeError(".opentelemetry.proto.logs.v1.LogRecord.attributes: array expected"); - message.attributes = []; - for (var i = 0; i < object.attributes.length; ++i) { - if (typeof object.attributes[i] !== "object") - throw TypeError(".opentelemetry.proto.logs.v1.LogRecord.attributes: object expected"); - message.attributes[i] = $root.opentelemetry.proto.common.v1.KeyValue.fromObject(object.attributes[i]); - } - } - if (object.droppedAttributesCount != null) - message.droppedAttributesCount = object.droppedAttributesCount >>> 0; - if (object.flags != null) - message.flags = object.flags >>> 0; - if (object.traceId != null) - if (typeof object.traceId === "string") - $util.base64.decode(object.traceId, message.traceId = $util.newBuffer($util.base64.length(object.traceId)), 0); - else if (object.traceId.length >= 0) - message.traceId = object.traceId; - if (object.spanId != null) - if (typeof object.spanId === "string") - $util.base64.decode(object.spanId, message.spanId = $util.newBuffer($util.base64.length(object.spanId)), 0); - else if (object.spanId.length >= 0) - message.spanId = object.spanId; - if (object.eventName != null) - message.eventName = String(object.eventName); - return message; - }; - /** - * Creates a plain object from a LogRecord message. Also converts values to other types if specified. - * @function toObject - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @static - * @param {opentelemetry.proto.logs.v1.LogRecord} message LogRecord - * @param {$protobuf.IConversionOptions} [options] Conversion options - * @returns {Object.} Plain object - */ - LogRecord.toObject = function toObject(message, options) { - if (!options) - options = {}; - var object = {}; - if (options.arrays || options.defaults) - object.attributes = []; - if (options.defaults) { - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.timeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.timeUnixNano = options.longs === String ? "0" : 0; - object.severityNumber = options.enums === String ? "SEVERITY_NUMBER_UNSPECIFIED" : 0; - object.severityText = ""; - object.body = null; - object.droppedAttributesCount = 0; - object.flags = 0; - if (options.bytes === String) - object.traceId = ""; - else { - object.traceId = []; - if (options.bytes !== Array) - object.traceId = $util.newBuffer(object.traceId); - } - if (options.bytes === String) - object.spanId = ""; - else { - object.spanId = []; - if (options.bytes !== Array) - object.spanId = $util.newBuffer(object.spanId); - } - if ($util.Long) { - var long = new $util.Long(0, 0, false); - object.observedTimeUnixNano = options.longs === String ? long.toString() : options.longs === Number ? long.toNumber() : long; - } - else - object.observedTimeUnixNano = options.longs === String ? "0" : 0; - object.eventName = ""; - } - if (message.timeUnixNano != null && message.hasOwnProperty("timeUnixNano")) - if (typeof message.timeUnixNano === "number") - object.timeUnixNano = options.longs === String ? String(message.timeUnixNano) : message.timeUnixNano; - else - object.timeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.timeUnixNano) : options.longs === Number ? new $util.LongBits(message.timeUnixNano.low >>> 0, message.timeUnixNano.high >>> 0).toNumber() : message.timeUnixNano; - if (message.severityNumber != null && message.hasOwnProperty("severityNumber")) - object.severityNumber = options.enums === String ? $root.opentelemetry.proto.logs.v1.SeverityNumber[message.severityNumber] === undefined ? message.severityNumber : $root.opentelemetry.proto.logs.v1.SeverityNumber[message.severityNumber] : message.severityNumber; - if (message.severityText != null && message.hasOwnProperty("severityText")) - object.severityText = message.severityText; - if (message.body != null && message.hasOwnProperty("body")) - object.body = $root.opentelemetry.proto.common.v1.AnyValue.toObject(message.body, options); - if (message.attributes && message.attributes.length) { - object.attributes = []; - for (var j = 0; j < message.attributes.length; ++j) - object.attributes[j] = $root.opentelemetry.proto.common.v1.KeyValue.toObject(message.attributes[j], options); - } - if (message.droppedAttributesCount != null && message.hasOwnProperty("droppedAttributesCount")) - object.droppedAttributesCount = message.droppedAttributesCount; - if (message.flags != null && message.hasOwnProperty("flags")) - object.flags = message.flags; - if (message.traceId != null && message.hasOwnProperty("traceId")) - object.traceId = options.bytes === String ? $util.base64.encode(message.traceId, 0, message.traceId.length) : options.bytes === Array ? Array.prototype.slice.call(message.traceId) : message.traceId; - if (message.spanId != null && message.hasOwnProperty("spanId")) - object.spanId = options.bytes === String ? $util.base64.encode(message.spanId, 0, message.spanId.length) : options.bytes === Array ? Array.prototype.slice.call(message.spanId) : message.spanId; - if (message.observedTimeUnixNano != null && message.hasOwnProperty("observedTimeUnixNano")) - if (typeof message.observedTimeUnixNano === "number") - object.observedTimeUnixNano = options.longs === String ? String(message.observedTimeUnixNano) : message.observedTimeUnixNano; - else - object.observedTimeUnixNano = options.longs === String ? $util.Long.prototype.toString.call(message.observedTimeUnixNano) : options.longs === Number ? new $util.LongBits(message.observedTimeUnixNano.low >>> 0, message.observedTimeUnixNano.high >>> 0).toNumber() : message.observedTimeUnixNano; - if (message.eventName != null && message.hasOwnProperty("eventName")) - object.eventName = message.eventName; - return object; - }; - /** - * Converts this LogRecord to JSON. - * @function toJSON - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @instance - * @returns {Object.} JSON object - */ - LogRecord.prototype.toJSON = function toJSON() { - return this.constructor.toObject(this, $protobuf.util.toJSONOptions); - }; - /** - * Gets the default type url for LogRecord - * @function getTypeUrl - * @memberof opentelemetry.proto.logs.v1.LogRecord - * @static - * @param {string} [typeUrlPrefix] your custom typeUrlPrefix(default "type.googleapis.com") - * @returns {string} The default type url - */ - LogRecord.getTypeUrl = function getTypeUrl(typeUrlPrefix) { - if (typeUrlPrefix === undefined) { - typeUrlPrefix = "type.googleapis.com"; - } - return typeUrlPrefix + "/opentelemetry.proto.logs.v1.LogRecord"; - }; - return LogRecord; - })(); - return v1; - })(); - return logs; - })(); - return proto; - })(); - return opentelemetry; -})(); -module.exports = $root; -//# sourceMappingURL=root.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/index.js deleted file mode 100644 index eaa486c8..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/index.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.JsonTraceSerializer = exports.JsonMetricsSerializer = exports.JsonLogsSerializer = exports.ProtobufTraceSerializer = exports.ProtobufMetricsSerializer = exports.ProtobufLogsSerializer = void 0; -var protobuf_1 = require("./logs/protobuf"); -Object.defineProperty(exports, "ProtobufLogsSerializer", { enumerable: true, get: function () { return protobuf_1.ProtobufLogsSerializer; } }); -var protobuf_2 = require("./metrics/protobuf"); -Object.defineProperty(exports, "ProtobufMetricsSerializer", { enumerable: true, get: function () { return protobuf_2.ProtobufMetricsSerializer; } }); -var protobuf_3 = require("./trace/protobuf"); -Object.defineProperty(exports, "ProtobufTraceSerializer", { enumerable: true, get: function () { return protobuf_3.ProtobufTraceSerializer; } }); -var json_1 = require("./logs/json"); -Object.defineProperty(exports, "JsonLogsSerializer", { enumerable: true, get: function () { return json_1.JsonLogsSerializer; } }); -var json_2 = require("./metrics/json"); -Object.defineProperty(exports, "JsonMetricsSerializer", { enumerable: true, get: function () { return json_2.JsonMetricsSerializer; } }); -var json_3 = require("./trace/json"); -Object.defineProperty(exports, "JsonTraceSerializer", { enumerable: true, get: function () { return json_3.JsonTraceSerializer; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/internal.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/internal.js deleted file mode 100644 index d9f60ea1..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/internal.js +++ /dev/null @@ -1,86 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.toLogAttributes = exports.createExportLogsServiceRequest = void 0; -const utils_1 = require("../common/utils"); -const internal_1 = require("../common/internal"); -function createExportLogsServiceRequest(logRecords, options) { - const encoder = (0, utils_1.getOtlpEncoder)(options); - return { - resourceLogs: logRecordsToResourceLogs(logRecords, encoder), - }; -} -exports.createExportLogsServiceRequest = createExportLogsServiceRequest; -function createResourceMap(logRecords) { - const resourceMap = new Map(); - for (const record of logRecords) { - const { resource, instrumentationScope: { name, version = '', schemaUrl = '' }, } = record; - let ismMap = resourceMap.get(resource); - if (!ismMap) { - ismMap = new Map(); - resourceMap.set(resource, ismMap); - } - const ismKey = `${name}@${version}:${schemaUrl}`; - let records = ismMap.get(ismKey); - if (!records) { - records = []; - ismMap.set(ismKey, records); - } - records.push(record); - } - return resourceMap; -} -function logRecordsToResourceLogs(logRecords, encoder) { - const resourceMap = createResourceMap(logRecords); - return Array.from(resourceMap, ([resource, ismMap]) => { - const processedResource = (0, internal_1.createResource)(resource); - return { - resource: processedResource, - scopeLogs: Array.from(ismMap, ([, scopeLogs]) => { - return { - scope: (0, internal_1.createInstrumentationScope)(scopeLogs[0].instrumentationScope), - logRecords: scopeLogs.map(log => toLogRecord(log, encoder)), - schemaUrl: scopeLogs[0].instrumentationScope.schemaUrl, - }; - }), - schemaUrl: processedResource.schemaUrl, - }; - }); -} -function toLogRecord(log, encoder) { - return { - timeUnixNano: encoder.encodeHrTime(log.hrTime), - observedTimeUnixNano: encoder.encodeHrTime(log.hrTimeObserved), - severityNumber: toSeverityNumber(log.severityNumber), - severityText: log.severityText, - body: (0, internal_1.toAnyValue)(log.body), - eventName: log.eventName, - attributes: toLogAttributes(log.attributes), - droppedAttributesCount: log.droppedAttributesCount, - flags: log.spanContext?.traceFlags, - traceId: encoder.encodeOptionalSpanContext(log.spanContext?.traceId), - spanId: encoder.encodeOptionalSpanContext(log.spanContext?.spanId), - }; -} -function toSeverityNumber(severityNumber) { - return severityNumber; -} -function toLogAttributes(attributes) { - return Object.keys(attributes).map(key => (0, internal_1.toKeyValue)(key, attributes[key])); -} -exports.toLogAttributes = toLogAttributes; -//# sourceMappingURL=internal.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/index.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/index.js deleted file mode 100644 index 80688f86..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/index.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.JsonLogsSerializer = void 0; -// IMPORTANT: exports added here are public -var logs_1 = require("./logs"); -Object.defineProperty(exports, "JsonLogsSerializer", { enumerable: true, get: function () { return logs_1.JsonLogsSerializer; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/logs.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/logs.js deleted file mode 100644 index 36c3e6d4..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/json/logs.js +++ /dev/null @@ -1,25 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.JsonLogsSerializer = void 0; -const internal_1 = require("../internal"); -/* - * @experimental this serializer may receive breaking changes in minor versions, pin this package's version when using this constant - */ -exports.JsonLogsSerializer = { - serializeRequest: (arg) => { - const request = (0, internal_1.createExportLogsServiceRequest)(arg, { - useHex: true, - useLongBits: false, - }); - const encoder = new TextEncoder(); - return encoder.encode(JSON.stringify(request)); - }, - deserializeResponse: (arg) => { - if (arg.length === 0) { - return {}; - } - const decoder = new TextDecoder(); - return JSON.parse(decoder.decode(arg)); - }, -}; -//# sourceMappingURL=logs.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/index.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/index.js deleted file mode 100644 index 0bc6a597..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ProtobufLogsSerializer = void 0; -var logs_1 = require("./logs"); -Object.defineProperty(exports, "ProtobufLogsSerializer", { enumerable: true, get: function () { return logs_1.ProtobufLogsSerializer; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/logs.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/logs.js deleted file mode 100644 index afccb35c..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/logs/protobuf/logs.js +++ /dev/null @@ -1,37 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ProtobufLogsSerializer = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const root = require("../../generated/root"); -const internal_1 = require("../internal"); -const logsResponseType = root.opentelemetry.proto.collector.logs.v1 - .ExportLogsServiceResponse; -const logsRequestType = root.opentelemetry.proto.collector.logs.v1 - .ExportLogsServiceRequest; -/* - * @experimental this serializer may receive breaking changes in minor versions, pin this package's version when using this constant - */ -exports.ProtobufLogsSerializer = { - serializeRequest: (arg) => { - const request = (0, internal_1.createExportLogsServiceRequest)(arg); - return logsRequestType.encode(request).finish(); - }, - deserializeResponse: (arg) => { - return logsResponseType.decode(arg); - }, -}; -//# sourceMappingURL=logs.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal-types.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal-types.js deleted file mode 100644 index b5bcaefb..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal-types.js +++ /dev/null @@ -1,75 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.EAggregationTemporality = void 0; -/** - * AggregationTemporality defines how a metric aggregator reports aggregated - * values. It describes how those values relate to the time interval over - * which they are aggregated. - */ -var EAggregationTemporality; -(function (EAggregationTemporality) { - /* UNSPECIFIED is the default AggregationTemporality, it MUST not be used. */ - EAggregationTemporality[EAggregationTemporality["AGGREGATION_TEMPORALITY_UNSPECIFIED"] = 0] = "AGGREGATION_TEMPORALITY_UNSPECIFIED"; - /** DELTA is an AggregationTemporality for a metric aggregator which reports - changes since last report time. Successive metrics contain aggregation of - values from continuous and non-overlapping intervals. - - The values for a DELTA metric are based only on the time interval - associated with one measurement cycle. There is no dependency on - previous measurements like is the case for CUMULATIVE metrics. - - For example, consider a system measuring the number of requests that - it receives and reports the sum of these requests every second as a - DELTA metric: - - 1. The system starts receiving at time=t_0. - 2. A request is received, the system measures 1 request. - 3. A request is received, the system measures 1 request. - 4. A request is received, the system measures 1 request. - 5. The 1 second collection cycle ends. A metric is exported for the - number of requests received over the interval of time t_0 to - t_0+1 with a value of 3. - 6. A request is received, the system measures 1 request. - 7. A request is received, the system measures 1 request. - 8. The 1 second collection cycle ends. A metric is exported for the - number of requests received over the interval of time t_0+1 to - t_0+2 with a value of 2. */ - EAggregationTemporality[EAggregationTemporality["AGGREGATION_TEMPORALITY_DELTA"] = 1] = "AGGREGATION_TEMPORALITY_DELTA"; - /** CUMULATIVE is an AggregationTemporality for a metric aggregator which - reports changes since a fixed start time. This means that current values - of a CUMULATIVE metric depend on all previous measurements since the - start time. Because of this, the sender is required to retain this state - in some form. If this state is lost or invalidated, the CUMULATIVE metric - values MUST be reset and a new fixed start time following the last - reported measurement time sent MUST be used. - - For example, consider a system measuring the number of requests that - it receives and reports the sum of these requests every second as a - CUMULATIVE metric: - - 1. The system starts receiving at time=t_0. - 2. A request is received, the system measures 1 request. - 3. A request is received, the system measures 1 request. - 4. A request is received, the system measures 1 request. - 5. The 1 second collection cycle ends. A metric is exported for the - number of requests received over the interval of time t_0 to - t_0+1 with a value of 3. - 6. A request is received, the system measures 1 request. - 7. A request is received, the system measures 1 request. - 8. The 1 second collection cycle ends. A metric is exported for the - number of requests received over the interval of time t_0 to - t_0+2 with a value of 5. - 9. The system experiences a fault and loses state. - 10. The system recovers and resumes receiving at time=t_1. - 11. A request is received, the system measures 1 request. - 12. The 1 second collection cycle ends. A metric is exported for the - number of requests received over the interval of time t_1 to - t_0+1 with a value of 1. - - Note: Even though, when reporting changes since last report time, using - CUMULATIVE is valid, it is not recommended. This may cause problems for - systems that do not use start_time to determine when the aggregation - value was reset (e.g. Prometheus). */ - EAggregationTemporality[EAggregationTemporality["AGGREGATION_TEMPORALITY_CUMULATIVE"] = 2] = "AGGREGATION_TEMPORALITY_CUMULATIVE"; -})(EAggregationTemporality = exports.EAggregationTemporality || (exports.EAggregationTemporality = {})); -//# sourceMappingURL=internal-types.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal.js deleted file mode 100644 index 0192a262..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/internal.js +++ /dev/null @@ -1,138 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createExportMetricsServiceRequest = exports.toMetric = exports.toScopeMetrics = exports.toResourceMetrics = void 0; -const api_1 = require("@opentelemetry/api"); -const sdk_metrics_1 = require("@opentelemetry/sdk-metrics"); -const internal_types_1 = require("./internal-types"); -const utils_1 = require("../common/utils"); -const internal_1 = require("../common/internal"); -function toResourceMetrics(resourceMetrics, options) { - const encoder = (0, utils_1.getOtlpEncoder)(options); - const processedResource = (0, internal_1.createResource)(resourceMetrics.resource); - return { - resource: processedResource, - schemaUrl: processedResource.schemaUrl, - scopeMetrics: toScopeMetrics(resourceMetrics.scopeMetrics, encoder), - }; -} -exports.toResourceMetrics = toResourceMetrics; -function toScopeMetrics(scopeMetrics, encoder) { - return Array.from(scopeMetrics.map(metrics => ({ - scope: (0, internal_1.createInstrumentationScope)(metrics.scope), - metrics: metrics.metrics.map(metricData => toMetric(metricData, encoder)), - schemaUrl: metrics.scope.schemaUrl, - }))); -} -exports.toScopeMetrics = toScopeMetrics; -function toMetric(metricData, encoder) { - const out = { - name: metricData.descriptor.name, - description: metricData.descriptor.description, - unit: metricData.descriptor.unit, - }; - const aggregationTemporality = toAggregationTemporality(metricData.aggregationTemporality); - switch (metricData.dataPointType) { - case sdk_metrics_1.DataPointType.SUM: - out.sum = { - aggregationTemporality, - isMonotonic: metricData.isMonotonic, - dataPoints: toSingularDataPoints(metricData, encoder), - }; - break; - case sdk_metrics_1.DataPointType.GAUGE: - out.gauge = { - dataPoints: toSingularDataPoints(metricData, encoder), - }; - break; - case sdk_metrics_1.DataPointType.HISTOGRAM: - out.histogram = { - aggregationTemporality, - dataPoints: toHistogramDataPoints(metricData, encoder), - }; - break; - case sdk_metrics_1.DataPointType.EXPONENTIAL_HISTOGRAM: - out.exponentialHistogram = { - aggregationTemporality, - dataPoints: toExponentialHistogramDataPoints(metricData, encoder), - }; - break; - } - return out; -} -exports.toMetric = toMetric; -function toSingularDataPoint(dataPoint, valueType, encoder) { - const out = { - attributes: (0, internal_1.toAttributes)(dataPoint.attributes), - startTimeUnixNano: encoder.encodeHrTime(dataPoint.startTime), - timeUnixNano: encoder.encodeHrTime(dataPoint.endTime), - }; - switch (valueType) { - case api_1.ValueType.INT: - out.asInt = dataPoint.value; - break; - case api_1.ValueType.DOUBLE: - out.asDouble = dataPoint.value; - break; - } - return out; -} -function toSingularDataPoints(metricData, encoder) { - return metricData.dataPoints.map(dataPoint => { - return toSingularDataPoint(dataPoint, metricData.descriptor.valueType, encoder); - }); -} -function toHistogramDataPoints(metricData, encoder) { - return metricData.dataPoints.map(dataPoint => { - const histogram = dataPoint.value; - return { - attributes: (0, internal_1.toAttributes)(dataPoint.attributes), - bucketCounts: histogram.buckets.counts, - explicitBounds: histogram.buckets.boundaries, - count: histogram.count, - sum: histogram.sum, - min: histogram.min, - max: histogram.max, - startTimeUnixNano: encoder.encodeHrTime(dataPoint.startTime), - timeUnixNano: encoder.encodeHrTime(dataPoint.endTime), - }; - }); -} -function toExponentialHistogramDataPoints(metricData, encoder) { - return metricData.dataPoints.map(dataPoint => { - const histogram = dataPoint.value; - return { - attributes: (0, internal_1.toAttributes)(dataPoint.attributes), - count: histogram.count, - min: histogram.min, - max: histogram.max, - sum: histogram.sum, - positive: { - offset: histogram.positive.offset, - bucketCounts: histogram.positive.bucketCounts, - }, - negative: { - offset: histogram.negative.offset, - bucketCounts: histogram.negative.bucketCounts, - }, - scale: histogram.scale, - zeroCount: histogram.zeroCount, - startTimeUnixNano: encoder.encodeHrTime(dataPoint.startTime), - timeUnixNano: encoder.encodeHrTime(dataPoint.endTime), - }; - }); -} -function toAggregationTemporality(temporality) { - switch (temporality) { - case sdk_metrics_1.AggregationTemporality.DELTA: - return internal_types_1.EAggregationTemporality.AGGREGATION_TEMPORALITY_DELTA; - case sdk_metrics_1.AggregationTemporality.CUMULATIVE: - return internal_types_1.EAggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE; - } -} -function createExportMetricsServiceRequest(resourceMetrics, options) { - return { - resourceMetrics: resourceMetrics.map(metrics => toResourceMetrics(metrics, options)), - }; -} -exports.createExportMetricsServiceRequest = createExportMetricsServiceRequest; -//# sourceMappingURL=internal.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/index.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/index.js deleted file mode 100644 index 40747ae8..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/index.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.JsonMetricsSerializer = void 0; -// IMPORTANT: exports added here are public -var metrics_1 = require("./metrics"); -Object.defineProperty(exports, "JsonMetricsSerializer", { enumerable: true, get: function () { return metrics_1.JsonMetricsSerializer; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/metrics.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/metrics.js deleted file mode 100644 index e97feb9b..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/json/metrics.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.JsonMetricsSerializer = void 0; -const internal_1 = require("../internal"); -exports.JsonMetricsSerializer = { - serializeRequest: (arg) => { - const request = (0, internal_1.createExportMetricsServiceRequest)([arg], { - useLongBits: false, - }); - const encoder = new TextEncoder(); - return encoder.encode(JSON.stringify(request)); - }, - deserializeResponse: (arg) => { - if (arg.length === 0) { - return {}; - } - const decoder = new TextDecoder(); - return JSON.parse(decoder.decode(arg)); - }, -}; -//# sourceMappingURL=metrics.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/index.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/index.js deleted file mode 100644 index 54a2467d..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/index.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ProtobufMetricsSerializer = void 0; -// IMPORTANT: exports added here are public -var metrics_1 = require("./metrics"); -Object.defineProperty(exports, "ProtobufMetricsSerializer", { enumerable: true, get: function () { return metrics_1.ProtobufMetricsSerializer; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/metrics.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/metrics.js deleted file mode 100644 index 5b5ea249..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/metrics/protobuf/metrics.js +++ /dev/null @@ -1,34 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ProtobufMetricsSerializer = void 0; -const root = require("../../generated/root"); -const internal_1 = require("../internal"); -const metricsResponseType = root.opentelemetry.proto.collector.metrics.v1 - .ExportMetricsServiceResponse; -const metricsRequestType = root.opentelemetry.proto.collector.metrics.v1 - .ExportMetricsServiceRequest; -exports.ProtobufMetricsSerializer = { - serializeRequest: (arg) => { - const request = (0, internal_1.createExportMetricsServiceRequest)([arg]); - return metricsRequestType.encode(request).finish(); - }, - deserializeResponse: (arg) => { - return metricsResponseType.decode(arg); - }, -}; -//# sourceMappingURL=metrics.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/internal.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/internal.js deleted file mode 100644 index 2737bb10..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/internal.js +++ /dev/null @@ -1,148 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createExportTraceServiceRequest = exports.toOtlpSpanEvent = exports.toOtlpLink = exports.sdkSpanToOtlpSpan = void 0; -const internal_1 = require("../common/internal"); -const utils_1 = require("../common/utils"); -// Span flags constants matching the OTLP specification -const SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK = 0x100; -const SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK = 0x200; -/** - * Builds the 32-bit span flags value combining the low 8-bit W3C TraceFlags - * with the HAS_IS_REMOTE and IS_REMOTE bits according to the OTLP spec. - */ -function buildSpanFlagsFrom(traceFlags, isRemote) { - // low 8 bits are W3C TraceFlags (e.g., sampled) - let flags = (traceFlags & 0xff) | SPAN_FLAGS_CONTEXT_HAS_IS_REMOTE_MASK; - if (isRemote) { - flags |= SPAN_FLAGS_CONTEXT_IS_REMOTE_MASK; - } - return flags; -} -function sdkSpanToOtlpSpan(span, encoder) { - const ctx = span.spanContext(); - const status = span.status; - const parentSpanId = span.parentSpanContext?.spanId - ? encoder.encodeSpanContext(span.parentSpanContext?.spanId) - : undefined; - return { - traceId: encoder.encodeSpanContext(ctx.traceId), - spanId: encoder.encodeSpanContext(ctx.spanId), - parentSpanId: parentSpanId, - traceState: ctx.traceState?.serialize(), - name: span.name, - // Span kind is offset by 1 because the API does not define a value for unset - kind: span.kind == null ? 0 : span.kind + 1, - startTimeUnixNano: encoder.encodeHrTime(span.startTime), - endTimeUnixNano: encoder.encodeHrTime(span.endTime), - attributes: (0, internal_1.toAttributes)(span.attributes), - droppedAttributesCount: span.droppedAttributesCount, - events: span.events.map(event => toOtlpSpanEvent(event, encoder)), - droppedEventsCount: span.droppedEventsCount, - status: { - // API and proto enums share the same values - code: status.code, - message: status.message, - }, - links: span.links.map(link => toOtlpLink(link, encoder)), - droppedLinksCount: span.droppedLinksCount, - flags: buildSpanFlagsFrom(ctx.traceFlags, span.parentSpanContext?.isRemote), - }; -} -exports.sdkSpanToOtlpSpan = sdkSpanToOtlpSpan; -function toOtlpLink(link, encoder) { - return { - attributes: link.attributes ? (0, internal_1.toAttributes)(link.attributes) : [], - spanId: encoder.encodeSpanContext(link.context.spanId), - traceId: encoder.encodeSpanContext(link.context.traceId), - traceState: link.context.traceState?.serialize(), - droppedAttributesCount: link.droppedAttributesCount || 0, - flags: buildSpanFlagsFrom(link.context.traceFlags, link.context.isRemote), - }; -} -exports.toOtlpLink = toOtlpLink; -function toOtlpSpanEvent(timedEvent, encoder) { - return { - attributes: timedEvent.attributes - ? (0, internal_1.toAttributes)(timedEvent.attributes) - : [], - name: timedEvent.name, - timeUnixNano: encoder.encodeHrTime(timedEvent.time), - droppedAttributesCount: timedEvent.droppedAttributesCount || 0, - }; -} -exports.toOtlpSpanEvent = toOtlpSpanEvent; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function createExportTraceServiceRequest(spans, options) { - const encoder = (0, utils_1.getOtlpEncoder)(options); - return { - resourceSpans: spanRecordsToResourceSpans(spans, encoder), - }; -} -exports.createExportTraceServiceRequest = createExportTraceServiceRequest; -function createResourceMap(readableSpans) { - const resourceMap = new Map(); - for (const record of readableSpans) { - let ilsMap = resourceMap.get(record.resource); - if (!ilsMap) { - ilsMap = new Map(); - resourceMap.set(record.resource, ilsMap); - } - // TODO this is duplicated in basic tracer. Consolidate on a common helper in core - const instrumentationScopeKey = `${record.instrumentationScope.name}@${record.instrumentationScope.version || ''}:${record.instrumentationScope.schemaUrl || ''}`; - let records = ilsMap.get(instrumentationScopeKey); - if (!records) { - records = []; - ilsMap.set(instrumentationScopeKey, records); - } - records.push(record); - } - return resourceMap; -} -function spanRecordsToResourceSpans(readableSpans, encoder) { - const resourceMap = createResourceMap(readableSpans); - const out = []; - const entryIterator = resourceMap.entries(); - let entry = entryIterator.next(); - while (!entry.done) { - const [resource, ilmMap] = entry.value; - const scopeResourceSpans = []; - const ilmIterator = ilmMap.values(); - let ilmEntry = ilmIterator.next(); - while (!ilmEntry.done) { - const scopeSpans = ilmEntry.value; - if (scopeSpans.length > 0) { - const spans = scopeSpans.map(readableSpan => sdkSpanToOtlpSpan(readableSpan, encoder)); - scopeResourceSpans.push({ - scope: (0, internal_1.createInstrumentationScope)(scopeSpans[0].instrumentationScope), - spans: spans, - schemaUrl: scopeSpans[0].instrumentationScope.schemaUrl, - }); - } - ilmEntry = ilmIterator.next(); - } - const processedResource = (0, internal_1.createResource)(resource); - const transformedSpans = { - resource: processedResource, - scopeSpans: scopeResourceSpans, - schemaUrl: processedResource.schemaUrl, - }; - out.push(transformedSpans); - entry = entryIterator.next(); - } - return out; -} -//# sourceMappingURL=internal.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/index.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/index.js deleted file mode 100644 index 2dcfdbc4..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/index.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.JsonTraceSerializer = void 0; -// IMPORTANT: exports added here are public -var trace_1 = require("./trace"); -Object.defineProperty(exports, "JsonTraceSerializer", { enumerable: true, get: function () { return trace_1.JsonTraceSerializer; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/trace.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/trace.js deleted file mode 100644 index 490c8248..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/json/trace.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.JsonTraceSerializer = void 0; -const internal_1 = require("../internal"); -exports.JsonTraceSerializer = { - serializeRequest: (arg) => { - const request = (0, internal_1.createExportTraceServiceRequest)(arg, { - useHex: true, - useLongBits: false, - }); - const encoder = new TextEncoder(); - return encoder.encode(JSON.stringify(request)); - }, - deserializeResponse: (arg) => { - if (arg.length === 0) { - return {}; - } - const decoder = new TextDecoder(); - return JSON.parse(decoder.decode(arg)); - }, -}; -//# sourceMappingURL=trace.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/index.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/index.js deleted file mode 100644 index cd1baa1b..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/index.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ProtobufTraceSerializer = void 0; -// IMPORTANT: exports added here are public -var trace_1 = require("./trace"); -Object.defineProperty(exports, "ProtobufTraceSerializer", { enumerable: true, get: function () { return trace_1.ProtobufTraceSerializer; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/trace.js b/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/trace.js deleted file mode 100644 index f4b79ddd..00000000 --- a/claude-code-source/node_modules/@opentelemetry/otlp-transformer/build/src/trace/protobuf/trace.js +++ /dev/null @@ -1,34 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ProtobufTraceSerializer = void 0; -const root = require("../../generated/root"); -const internal_1 = require("../internal"); -const traceResponseType = root.opentelemetry.proto.collector.trace.v1 - .ExportTraceServiceResponse; -const traceRequestType = root.opentelemetry.proto.collector.trace.v1 - .ExportTraceServiceRequest; -exports.ProtobufTraceSerializer = { - serializeRequest: (arg) => { - const request = (0, internal_1.createExportTraceServiceRequest)(arg); - return traceRequestType.encode(request).finish(); - }, - deserializeResponse: (arg) => { - return traceResponseType.decode(arg); - }, -}; -//# sourceMappingURL=trace.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/ResourceImpl.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/ResourceImpl.js deleted file mode 100644 index 378ce6b5..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/ResourceImpl.js +++ /dev/null @@ -1,167 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.defaultResource = exports.emptyResource = exports.resourceFromDetectedResource = exports.resourceFromAttributes = void 0; -const api_1 = require("@opentelemetry/api"); -const core_1 = require("@opentelemetry/core"); -const semantic_conventions_1 = require("@opentelemetry/semantic-conventions"); -const platform_1 = require("./platform"); -const utils_1 = require("./utils"); -class ResourceImpl { - _rawAttributes; - _asyncAttributesPending = false; - _schemaUrl; - _memoizedAttributes; - static FromAttributeList(attributes, options) { - const res = new ResourceImpl({}, options); - res._rawAttributes = guardedRawAttributes(attributes); - res._asyncAttributesPending = - attributes.filter(([_, val]) => (0, utils_1.isPromiseLike)(val)).length > 0; - return res; - } - constructor( - /** - * A dictionary of attributes with string keys and values that provide - * information about the entity as numbers, strings or booleans - * TODO: Consider to add check/validation on attributes. - */ - resource, options) { - const attributes = resource.attributes ?? {}; - this._rawAttributes = Object.entries(attributes).map(([k, v]) => { - if ((0, utils_1.isPromiseLike)(v)) { - // side-effect - this._asyncAttributesPending = true; - } - return [k, v]; - }); - this._rawAttributes = guardedRawAttributes(this._rawAttributes); - this._schemaUrl = validateSchemaUrl(options?.schemaUrl); - } - get asyncAttributesPending() { - return this._asyncAttributesPending; - } - async waitForAsyncAttributes() { - if (!this.asyncAttributesPending) { - return; - } - for (let i = 0; i < this._rawAttributes.length; i++) { - const [k, v] = this._rawAttributes[i]; - this._rawAttributes[i] = [k, (0, utils_1.isPromiseLike)(v) ? await v : v]; - } - this._asyncAttributesPending = false; - } - get attributes() { - if (this.asyncAttributesPending) { - api_1.diag.error('Accessing resource attributes before async attributes settled'); - } - if (this._memoizedAttributes) { - return this._memoizedAttributes; - } - const attrs = {}; - for (const [k, v] of this._rawAttributes) { - if ((0, utils_1.isPromiseLike)(v)) { - api_1.diag.debug(`Unsettled resource attribute ${k} skipped`); - continue; - } - if (v != null) { - attrs[k] ??= v; - } - } - // only memoize output if all attributes are settled - if (!this._asyncAttributesPending) { - this._memoizedAttributes = attrs; - } - return attrs; - } - getRawAttributes() { - return this._rawAttributes; - } - get schemaUrl() { - return this._schemaUrl; - } - merge(resource) { - if (resource == null) - return this; - // Order is important - // Spec states incoming attributes override existing attributes - const mergedSchemaUrl = mergeSchemaUrl(this, resource); - const mergedOptions = mergedSchemaUrl - ? { schemaUrl: mergedSchemaUrl } - : undefined; - return ResourceImpl.FromAttributeList([...resource.getRawAttributes(), ...this.getRawAttributes()], mergedOptions); - } -} -function resourceFromAttributes(attributes, options) { - return ResourceImpl.FromAttributeList(Object.entries(attributes), options); -} -exports.resourceFromAttributes = resourceFromAttributes; -function resourceFromDetectedResource(detectedResource, options) { - return new ResourceImpl(detectedResource, options); -} -exports.resourceFromDetectedResource = resourceFromDetectedResource; -function emptyResource() { - return resourceFromAttributes({}); -} -exports.emptyResource = emptyResource; -function defaultResource() { - return resourceFromAttributes({ - [semantic_conventions_1.ATTR_SERVICE_NAME]: (0, platform_1.defaultServiceName)(), - [semantic_conventions_1.ATTR_TELEMETRY_SDK_LANGUAGE]: core_1.SDK_INFO[semantic_conventions_1.ATTR_TELEMETRY_SDK_LANGUAGE], - [semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME]: core_1.SDK_INFO[semantic_conventions_1.ATTR_TELEMETRY_SDK_NAME], - [semantic_conventions_1.ATTR_TELEMETRY_SDK_VERSION]: core_1.SDK_INFO[semantic_conventions_1.ATTR_TELEMETRY_SDK_VERSION], - }); -} -exports.defaultResource = defaultResource; -function guardedRawAttributes(attributes) { - return attributes.map(([k, v]) => { - if ((0, utils_1.isPromiseLike)(v)) { - return [ - k, - v.catch(err => { - api_1.diag.debug('promise rejection for resource attribute: %s - %s', k, err); - return undefined; - }), - ]; - } - return [k, v]; - }); -} -function validateSchemaUrl(schemaUrl) { - if (typeof schemaUrl === 'string' || schemaUrl === undefined) { - return schemaUrl; - } - api_1.diag.warn('Schema URL must be string or undefined, got %s. Schema URL will be ignored.', schemaUrl); - return undefined; -} -function mergeSchemaUrl(old, updating) { - const oldSchemaUrl = old?.schemaUrl; - const updatingSchemaUrl = updating?.schemaUrl; - const isOldEmpty = oldSchemaUrl === undefined || oldSchemaUrl === ''; - const isUpdatingEmpty = updatingSchemaUrl === undefined || updatingSchemaUrl === ''; - if (isOldEmpty) { - return updatingSchemaUrl; - } - if (isUpdatingEmpty) { - return oldSchemaUrl; - } - if (oldSchemaUrl === updatingSchemaUrl) { - return oldSchemaUrl; - } - api_1.diag.warn('Schema URL merge conflict: old resource has "%s", updating resource has "%s". Resulting resource will have undefined Schema URL.', oldSchemaUrl, updatingSchemaUrl); - return undefined; -} -//# sourceMappingURL=ResourceImpl.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detect-resources.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detect-resources.js deleted file mode 100644 index 0e9d28db..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detect-resources.js +++ /dev/null @@ -1,41 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.detectResources = void 0; -const api_1 = require("@opentelemetry/api"); -const ResourceImpl_1 = require("./ResourceImpl"); -/** - * Runs all resource detectors and returns the results merged into a single Resource. - * - * @param config Configuration for resource detection - */ -const detectResources = (config = {}) => { - const resources = (config.detectors || []).map(d => { - try { - const resource = (0, ResourceImpl_1.resourceFromDetectedResource)(d.detect(config)); - api_1.diag.debug(`${d.constructor.name} found resource.`, resource); - return resource; - } - catch (e) { - api_1.diag.debug(`${d.constructor.name} failed: ${e.message}`); - return (0, ResourceImpl_1.emptyResource)(); - } - }); - return resources.reduce((acc, resource) => acc.merge(resource), (0, ResourceImpl_1.emptyResource)()); -}; -exports.detectResources = detectResources; -//# sourceMappingURL=detect-resources.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/EnvDetector.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/EnvDetector.js deleted file mode 100644 index d88be5c9..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/EnvDetector.js +++ /dev/null @@ -1,134 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.envDetector = void 0; -const api_1 = require("@opentelemetry/api"); -const semantic_conventions_1 = require("@opentelemetry/semantic-conventions"); -const core_1 = require("@opentelemetry/core"); -/** - * EnvDetector can be used to detect the presence of and create a Resource - * from the OTEL_RESOURCE_ATTRIBUTES environment variable. - */ -class EnvDetector { - // Type, attribute keys, and attribute values should not exceed 256 characters. - _MAX_LENGTH = 255; - // OTEL_RESOURCE_ATTRIBUTES is a comma-separated list of attributes. - _COMMA_SEPARATOR = ','; - // OTEL_RESOURCE_ATTRIBUTES contains key value pair separated by '='. - _LABEL_KEY_VALUE_SPLITTER = '='; - _ERROR_MESSAGE_INVALID_CHARS = 'should be a ASCII string with a length greater than 0 and not exceed ' + - this._MAX_LENGTH + - ' characters.'; - _ERROR_MESSAGE_INVALID_VALUE = 'should be a ASCII string with a length not exceed ' + - this._MAX_LENGTH + - ' characters.'; - /** - * Returns a {@link Resource} populated with attributes from the - * OTEL_RESOURCE_ATTRIBUTES environment variable. Note this is an async - * function to conform to the Detector interface. - * - * @param config The resource detection config - */ - detect(_config) { - const attributes = {}; - const rawAttributes = (0, core_1.getStringFromEnv)('OTEL_RESOURCE_ATTRIBUTES'); - const serviceName = (0, core_1.getStringFromEnv)('OTEL_SERVICE_NAME'); - if (rawAttributes) { - try { - const parsedAttributes = this._parseResourceAttributes(rawAttributes); - Object.assign(attributes, parsedAttributes); - } - catch (e) { - api_1.diag.debug(`EnvDetector failed: ${e.message}`); - } - } - if (serviceName) { - attributes[semantic_conventions_1.ATTR_SERVICE_NAME] = serviceName; - } - return { attributes }; - } - /** - * Creates an attribute map from the OTEL_RESOURCE_ATTRIBUTES environment - * variable. - * - * OTEL_RESOURCE_ATTRIBUTES: A comma-separated list of attributes describing - * the source in more detail, e.g. “key1=val1,key2=val2”. Domain names and - * paths are accepted as attribute keys. Values may be quoted or unquoted in - * general. If a value contains whitespace, =, or " characters, it must - * always be quoted. - * - * @param rawEnvAttributes The resource attributes as a comma-separated list - * of key/value pairs. - * @returns The sanitized resource attributes. - */ - _parseResourceAttributes(rawEnvAttributes) { - if (!rawEnvAttributes) - return {}; - const attributes = {}; - const rawAttributes = rawEnvAttributes.split(this._COMMA_SEPARATOR, -1); - for (const rawAttribute of rawAttributes) { - const keyValuePair = rawAttribute.split(this._LABEL_KEY_VALUE_SPLITTER, -1); - if (keyValuePair.length !== 2) { - continue; - } - let [key, value] = keyValuePair; - // Leading and trailing whitespaces are trimmed. - key = key.trim(); - value = value.trim().split(/^"|"$/).join(''); - if (!this._isValidAndNotEmpty(key)) { - throw new Error(`Attribute key ${this._ERROR_MESSAGE_INVALID_CHARS}`); - } - if (!this._isValid(value)) { - throw new Error(`Attribute value ${this._ERROR_MESSAGE_INVALID_VALUE}`); - } - attributes[key] = decodeURIComponent(value); - } - return attributes; - } - /** - * Determines whether the given String is a valid printable ASCII string with - * a length not exceed _MAX_LENGTH characters. - * - * @param str The String to be validated. - * @returns Whether the String is valid. - */ - _isValid(name) { - return name.length <= this._MAX_LENGTH && this._isBaggageOctetString(name); - } - // https://www.w3.org/TR/baggage/#definition - _isBaggageOctetString(str) { - for (let i = 0; i < str.length; i++) { - const ch = str.charCodeAt(i); - if (ch < 0x21 || ch === 0x2c || ch === 0x3b || ch === 0x5c || ch > 0x7e) { - return false; - } - } - return true; - } - /** - * Determines whether the given String is a valid printable ASCII string with - * a length greater than 0 and not exceed _MAX_LENGTH characters. - * - * @param str The String to be validated. - * @returns Whether the String is valid and not empty. - */ - _isValidAndNotEmpty(str) { - return str.length > 0 && this._isValid(str); - } -} -exports.envDetector = new EnvDetector(); -//# sourceMappingURL=EnvDetector.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/NoopDetector.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/NoopDetector.js deleted file mode 100644 index eb2cd7df..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/NoopDetector.js +++ /dev/null @@ -1,28 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.noopDetector = exports.NoopDetector = void 0; -class NoopDetector { - detect() { - return { - attributes: {}, - }; - } -} -exports.NoopDetector = NoopDetector; -exports.noopDetector = new NoopDetector(); -//# sourceMappingURL=NoopDetector.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/index.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/index.js deleted file mode 100644 index 73da00da..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/index.js +++ /dev/null @@ -1,28 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.noopDetector = exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = exports.envDetector = void 0; -var EnvDetector_1 = require("./EnvDetector"); -Object.defineProperty(exports, "envDetector", { enumerable: true, get: function () { return EnvDetector_1.envDetector; } }); -var platform_1 = require("./platform"); -Object.defineProperty(exports, "hostDetector", { enumerable: true, get: function () { return platform_1.hostDetector; } }); -Object.defineProperty(exports, "osDetector", { enumerable: true, get: function () { return platform_1.osDetector; } }); -Object.defineProperty(exports, "processDetector", { enumerable: true, get: function () { return platform_1.processDetector; } }); -Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: function () { return platform_1.serviceInstanceIdDetector; } }); -var NoopDetector_1 = require("./NoopDetector"); -Object.defineProperty(exports, "noopDetector", { enumerable: true, get: function () { return NoopDetector_1.noopDetector; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/index.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/index.js deleted file mode 100644 index 333c428d..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/index.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var node_1 = require("./node"); -Object.defineProperty(exports, "hostDetector", { enumerable: true, get: function () { return node_1.hostDetector; } }); -Object.defineProperty(exports, "osDetector", { enumerable: true, get: function () { return node_1.osDetector; } }); -Object.defineProperty(exports, "processDetector", { enumerable: true, get: function () { return node_1.processDetector; } }); -Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: function () { return node_1.serviceInstanceIdDetector; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/HostDetector.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/HostDetector.js deleted file mode 100644 index da3f41d9..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/HostDetector.js +++ /dev/null @@ -1,38 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.hostDetector = void 0; -const semconv_1 = require("../../../semconv"); -const os_1 = require("os"); -const getMachineId_1 = require("./machine-id/getMachineId"); -const utils_1 = require("./utils"); -/** - * HostDetector detects the resources related to the host current process is - * running on. Currently only non-cloud-based attributes are included. - */ -class HostDetector { - detect(_config) { - const attributes = { - [semconv_1.ATTR_HOST_NAME]: (0, os_1.hostname)(), - [semconv_1.ATTR_HOST_ARCH]: (0, utils_1.normalizeArch)((0, os_1.arch)()), - [semconv_1.ATTR_HOST_ID]: (0, getMachineId_1.getMachineId)(), - }; - return { attributes }; - } -} -exports.hostDetector = new HostDetector(); -//# sourceMappingURL=HostDetector.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/OSDetector.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/OSDetector.js deleted file mode 100644 index 2af15dc4..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/OSDetector.js +++ /dev/null @@ -1,36 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.osDetector = void 0; -const semconv_1 = require("../../../semconv"); -const os_1 = require("os"); -const utils_1 = require("./utils"); -/** - * OSDetector detects the resources related to the operating system (OS) on - * which the process represented by this resource is running. - */ -class OSDetector { - detect(_config) { - const attributes = { - [semconv_1.ATTR_OS_TYPE]: (0, utils_1.normalizeType)((0, os_1.platform)()), - [semconv_1.ATTR_OS_VERSION]: (0, os_1.release)(), - }; - return { attributes }; - } -} -exports.osDetector = new OSDetector(); -//# sourceMappingURL=OSDetector.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ProcessDetector.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ProcessDetector.js deleted file mode 100644 index 32c3aaa3..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ProcessDetector.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.processDetector = void 0; -const api_1 = require("@opentelemetry/api"); -const semconv_1 = require("../../../semconv"); -const os = require("os"); -/** - * ProcessDetector will be used to detect the resources related current process running - * and being instrumented from the NodeJS Process module. - */ -class ProcessDetector { - detect(_config) { - const attributes = { - [semconv_1.ATTR_PROCESS_PID]: process.pid, - [semconv_1.ATTR_PROCESS_EXECUTABLE_NAME]: process.title, - [semconv_1.ATTR_PROCESS_EXECUTABLE_PATH]: process.execPath, - [semconv_1.ATTR_PROCESS_COMMAND_ARGS]: [ - process.argv[0], - ...process.execArgv, - ...process.argv.slice(1), - ], - [semconv_1.ATTR_PROCESS_RUNTIME_VERSION]: process.versions.node, - [semconv_1.ATTR_PROCESS_RUNTIME_NAME]: 'nodejs', - [semconv_1.ATTR_PROCESS_RUNTIME_DESCRIPTION]: 'Node.js', - }; - if (process.argv.length > 1) { - attributes[semconv_1.ATTR_PROCESS_COMMAND] = process.argv[1]; - } - try { - const userInfo = os.userInfo(); - attributes[semconv_1.ATTR_PROCESS_OWNER] = userInfo.username; - } - catch (e) { - api_1.diag.debug(`error obtaining process owner: ${e}`); - } - return { attributes }; - } -} -exports.processDetector = new ProcessDetector(); -//# sourceMappingURL=ProcessDetector.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ServiceInstanceIdDetector.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ServiceInstanceIdDetector.js deleted file mode 100644 index c849fe4c..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/ServiceInstanceIdDetector.js +++ /dev/null @@ -1,37 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.serviceInstanceIdDetector = void 0; -const semconv_1 = require("../../../semconv"); -const crypto_1 = require("crypto"); -/** - * ServiceInstanceIdDetector detects the resources related to the service instance ID. - */ -class ServiceInstanceIdDetector { - detect(_config) { - return { - attributes: { - [semconv_1.ATTR_SERVICE_INSTANCE_ID]: (0, crypto_1.randomUUID)(), - }, - }; - } -} -/** - * @experimental - */ -exports.serviceInstanceIdDetector = new ServiceInstanceIdDetector(); -//# sourceMappingURL=ServiceInstanceIdDetector.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/index.js deleted file mode 100644 index 9fc4c70e..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/index.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = void 0; -var HostDetector_1 = require("./HostDetector"); -Object.defineProperty(exports, "hostDetector", { enumerable: true, get: function () { return HostDetector_1.hostDetector; } }); -var OSDetector_1 = require("./OSDetector"); -Object.defineProperty(exports, "osDetector", { enumerable: true, get: function () { return OSDetector_1.osDetector; } }); -var ProcessDetector_1 = require("./ProcessDetector"); -Object.defineProperty(exports, "processDetector", { enumerable: true, get: function () { return ProcessDetector_1.processDetector; } }); -var ServiceInstanceIdDetector_1 = require("./ServiceInstanceIdDetector"); -Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: function () { return ServiceInstanceIdDetector_1.serviceInstanceIdDetector; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/execAsync.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/execAsync.js deleted file mode 100644 index 6688a2a0..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/execAsync.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.execAsync = void 0; -const child_process = require("child_process"); -const util = require("util"); -exports.execAsync = util.promisify(child_process.exec); -//# sourceMappingURL=execAsync.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-bsd.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-bsd.js deleted file mode 100644 index 282aa321..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-bsd.js +++ /dev/null @@ -1,40 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getMachineId = void 0; -const fs_1 = require("fs"); -const execAsync_1 = require("./execAsync"); -const api_1 = require("@opentelemetry/api"); -async function getMachineId() { - try { - const result = await fs_1.promises.readFile('/etc/hostid', { encoding: 'utf8' }); - return result.trim(); - } - catch (e) { - api_1.diag.debug(`error reading machine id: ${e}`); - } - try { - const result = await (0, execAsync_1.execAsync)('kenv -q smbios.system.uuid'); - return result.stdout.trim(); - } - catch (e) { - api_1.diag.debug(`error reading machine id: ${e}`); - } - return undefined; -} -exports.getMachineId = getMachineId; -//# sourceMappingURL=getMachineId-bsd.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-darwin.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-darwin.js deleted file mode 100644 index 143945e6..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-darwin.js +++ /dev/null @@ -1,41 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getMachineId = void 0; -const execAsync_1 = require("./execAsync"); -const api_1 = require("@opentelemetry/api"); -async function getMachineId() { - try { - const result = await (0, execAsync_1.execAsync)('ioreg -rd1 -c "IOPlatformExpertDevice"'); - const idLine = result.stdout - .split('\n') - .find(line => line.includes('IOPlatformUUID')); - if (!idLine) { - return undefined; - } - const parts = idLine.split('" = "'); - if (parts.length === 2) { - return parts[1].slice(0, -1); - } - } - catch (e) { - api_1.diag.debug(`error reading machine id: ${e}`); - } - return undefined; -} -exports.getMachineId = getMachineId; -//# sourceMappingURL=getMachineId-darwin.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-linux.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-linux.js deleted file mode 100644 index 8214dd37..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-linux.js +++ /dev/null @@ -1,35 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getMachineId = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const fs_1 = require("fs"); -const api_1 = require("@opentelemetry/api"); -async function getMachineId() { - const paths = ['/etc/machine-id', '/var/lib/dbus/machine-id']; - for (const path of paths) { - try { - const result = await fs_1.promises.readFile(path, { encoding: 'utf8' }); - return result.trim(); - } - catch (e) { - api_1.diag.debug(`error reading machine id: ${e}`); - } - } - return undefined; -} -exports.getMachineId = getMachineId; -//# sourceMappingURL=getMachineId-linux.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-unsupported.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-unsupported.js deleted file mode 100644 index f68a1fa2..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-unsupported.js +++ /dev/null @@ -1,25 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getMachineId = void 0; -const api_1 = require("@opentelemetry/api"); -async function getMachineId() { - api_1.diag.debug('could not read machine-id: unsupported platform'); - return undefined; -} -exports.getMachineId = getMachineId; -//# sourceMappingURL=getMachineId-unsupported.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-win.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-win.js deleted file mode 100644 index 1d3f784b..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId-win.js +++ /dev/null @@ -1,41 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getMachineId = void 0; -const process = require("process"); -const execAsync_1 = require("./execAsync"); -const api_1 = require("@opentelemetry/api"); -async function getMachineId() { - const args = 'QUERY HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography /v MachineGuid'; - let command = '%windir%\\System32\\REG.exe'; - if (process.arch === 'ia32' && 'PROCESSOR_ARCHITEW6432' in process.env) { - command = '%windir%\\sysnative\\cmd.exe /c ' + command; - } - try { - const result = await (0, execAsync_1.execAsync)(`${command} ${args}`); - const parts = result.stdout.split('REG_SZ'); - if (parts.length === 2) { - return parts[1].trim(); - } - } - catch (e) { - api_1.diag.debug(`error reading machine id: ${e}`); - } - return undefined; -} -exports.getMachineId = getMachineId; -//# sourceMappingURL=getMachineId-win.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId.js deleted file mode 100644 index e10c3f9a..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/machine-id/getMachineId.js +++ /dev/null @@ -1,47 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getMachineId = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const process = require("process"); -let getMachineIdImpl; -async function getMachineId() { - if (!getMachineIdImpl) { - switch (process.platform) { - case 'darwin': - getMachineIdImpl = (await import('./getMachineId-darwin.js')) - .getMachineId; - break; - case 'linux': - getMachineIdImpl = (await import('./getMachineId-linux.js')) - .getMachineId; - break; - case 'freebsd': - getMachineIdImpl = (await import('./getMachineId-bsd.js')).getMachineId; - break; - case 'win32': - getMachineIdImpl = (await import('./getMachineId-win.js')).getMachineId; - break; - default: - getMachineIdImpl = (await import('./getMachineId-unsupported.js')) - .getMachineId; - break; - } - } - return getMachineIdImpl(); -} -exports.getMachineId = getMachineId; -//# sourceMappingURL=getMachineId.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/utils.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/utils.js deleted file mode 100644 index 33675c98..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/detectors/platform/node/utils.js +++ /dev/null @@ -1,47 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.normalizeType = exports.normalizeArch = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const normalizeArch = (nodeArchString) => { - // Maps from https://nodejs.org/api/os.html#osarch to arch values in spec: - // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/host.md - switch (nodeArchString) { - case 'arm': - return 'arm32'; - case 'ppc': - return 'ppc32'; - case 'x64': - return 'amd64'; - default: - return nodeArchString; - } -}; -exports.normalizeArch = normalizeArch; -const normalizeType = (nodePlatform) => { - // Maps from https://nodejs.org/api/os.html#osplatform to arch values in spec: - // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/resource/semantic_conventions/os.md - switch (nodePlatform) { - case 'sunos': - return 'solaris'; - case 'win32': - return 'windows'; - default: - return nodePlatform; - } -}; -exports.normalizeType = normalizeType; -//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/index.js deleted file mode 100644 index 11e3d56b..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/index.js +++ /dev/null @@ -1,33 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.defaultServiceName = exports.emptyResource = exports.defaultResource = exports.resourceFromAttributes = exports.serviceInstanceIdDetector = exports.processDetector = exports.osDetector = exports.hostDetector = exports.envDetector = exports.detectResources = void 0; -var detect_resources_1 = require("./detect-resources"); -Object.defineProperty(exports, "detectResources", { enumerable: true, get: function () { return detect_resources_1.detectResources; } }); -var detectors_1 = require("./detectors"); -Object.defineProperty(exports, "envDetector", { enumerable: true, get: function () { return detectors_1.envDetector; } }); -Object.defineProperty(exports, "hostDetector", { enumerable: true, get: function () { return detectors_1.hostDetector; } }); -Object.defineProperty(exports, "osDetector", { enumerable: true, get: function () { return detectors_1.osDetector; } }); -Object.defineProperty(exports, "processDetector", { enumerable: true, get: function () { return detectors_1.processDetector; } }); -Object.defineProperty(exports, "serviceInstanceIdDetector", { enumerable: true, get: function () { return detectors_1.serviceInstanceIdDetector; } }); -var ResourceImpl_1 = require("./ResourceImpl"); -Object.defineProperty(exports, "resourceFromAttributes", { enumerable: true, get: function () { return ResourceImpl_1.resourceFromAttributes; } }); -Object.defineProperty(exports, "defaultResource", { enumerable: true, get: function () { return ResourceImpl_1.defaultResource; } }); -Object.defineProperty(exports, "emptyResource", { enumerable: true, get: function () { return ResourceImpl_1.emptyResource; } }); -var platform_1 = require("./platform"); -Object.defineProperty(exports, "defaultServiceName", { enumerable: true, get: function () { return platform_1.defaultServiceName; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/index.js deleted file mode 100644 index 50930322..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.defaultServiceName = void 0; -var node_1 = require("./node"); -Object.defineProperty(exports, "defaultServiceName", { enumerable: true, get: function () { return node_1.defaultServiceName; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/node/default-service-name.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/node/default-service-name.js deleted file mode 100644 index 8b1f0d3f..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/node/default-service-name.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.defaultServiceName = void 0; -function defaultServiceName() { - return `unknown_service:${process.argv0}`; -} -exports.defaultServiceName = defaultServiceName; -//# sourceMappingURL=default-service-name.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/node/index.js deleted file mode 100644 index 6f5a2814..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/platform/node/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.defaultServiceName = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var default_service_name_1 = require("./default-service-name"); -Object.defineProperty(exports, "defaultServiceName", { enumerable: true, get: function () { return default_service_name_1.defaultServiceName; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/semconv.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/semconv.js deleted file mode 100644 index 73c98da2..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/semconv.js +++ /dev/null @@ -1,335 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ATTR_WEBENGINE_VERSION = exports.ATTR_WEBENGINE_NAME = exports.ATTR_WEBENGINE_DESCRIPTION = exports.ATTR_SERVICE_NAMESPACE = exports.ATTR_SERVICE_INSTANCE_ID = exports.ATTR_PROCESS_RUNTIME_VERSION = exports.ATTR_PROCESS_RUNTIME_NAME = exports.ATTR_PROCESS_RUNTIME_DESCRIPTION = exports.ATTR_PROCESS_PID = exports.ATTR_PROCESS_OWNER = exports.ATTR_PROCESS_EXECUTABLE_PATH = exports.ATTR_PROCESS_EXECUTABLE_NAME = exports.ATTR_PROCESS_COMMAND_ARGS = exports.ATTR_PROCESS_COMMAND = exports.ATTR_OS_VERSION = exports.ATTR_OS_TYPE = exports.ATTR_K8S_POD_NAME = exports.ATTR_K8S_NAMESPACE_NAME = exports.ATTR_K8S_DEPLOYMENT_NAME = exports.ATTR_K8S_CLUSTER_NAME = exports.ATTR_HOST_TYPE = exports.ATTR_HOST_NAME = exports.ATTR_HOST_IMAGE_VERSION = exports.ATTR_HOST_IMAGE_NAME = exports.ATTR_HOST_IMAGE_ID = exports.ATTR_HOST_ID = exports.ATTR_HOST_ARCH = exports.ATTR_CONTAINER_NAME = exports.ATTR_CONTAINER_IMAGE_TAGS = exports.ATTR_CONTAINER_IMAGE_NAME = exports.ATTR_CONTAINER_ID = exports.ATTR_CLOUD_REGION = exports.ATTR_CLOUD_PROVIDER = exports.ATTR_CLOUD_AVAILABILITY_ZONE = exports.ATTR_CLOUD_ACCOUNT_ID = void 0; -/* - * This file contains a copy of unstable semantic convention definitions - * used by this package. - * @see https://github.com/open-telemetry/opentelemetry-js/tree/main/semantic-conventions#unstable-semconv - */ -/** - * The cloud account ID the resource is assigned to. - * - * @example 111111111111 - * @example opentelemetry - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_CLOUD_ACCOUNT_ID = 'cloud.account.id'; -/** - * Cloud regions often have multiple, isolated locations known as zones to increase availability. Availability zone represents the zone where the resource is running. - * - * @example us-east-1c - * - * @note Availability zones are called "zones" on Alibaba Cloud and Google Cloud. - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_CLOUD_AVAILABILITY_ZONE = 'cloud.availability_zone'; -/** - * Name of the cloud provider. - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_CLOUD_PROVIDER = 'cloud.provider'; -/** - * The geographical region the resource is running. - * - * @example us-central1 - * @example us-east-1 - * - * @note Refer to your provider's docs to see the available regions, for example [Alibaba Cloud regions](https://www.alibabacloud.com/help/doc-detail/40654.htm), [AWS regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/), [Azure regions](https://azure.microsoft.com/global-infrastructure/geographies/), [Google Cloud regions](https://cloud.google.com/about/locations), or [Tencent Cloud regions](https://www.tencentcloud.com/document/product/213/6091). - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_CLOUD_REGION = 'cloud.region'; -/** - * Container ID. Usually a UUID, as for example used to [identify Docker containers](https://docs.docker.com/engine/containers/run/#container-identification). The UUID might be abbreviated. - * - * @example a3bf90e006b2 - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_CONTAINER_ID = 'container.id'; -/** - * Name of the image the container was built on. - * - * @example gcr.io/opentelemetry/operator - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_CONTAINER_IMAGE_NAME = 'container.image.name'; -/** - * Container image tags. An example can be found in [Docker Image Inspect](https://docs.docker.com/engine/api/v1.43/#tag/Image/operation/ImageInspect). Should be only the `` section of the full name for example from `registry.example.com/my-org/my-image:`. - * - * @example ["v1.27.1", "3.5.7-0"] - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_CONTAINER_IMAGE_TAGS = 'container.image.tags'; -/** - * Container name used by container runtime. - * - * @example opentelemetry-autoconf - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_CONTAINER_NAME = 'container.name'; -/** - * The CPU architecture the host system is running on. - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_HOST_ARCH = 'host.arch'; -/** - * Unique host ID. For Cloud, this must be the instance_id assigned by the cloud provider. For non-containerized systems, this should be the `machine-id`. See the table below for the sources to use to determine the `machine-id` based on operating system. - * - * @example fdbf79e8af94cb7f9e8df36789187052 - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_HOST_ID = 'host.id'; -/** - * VM image ID or host OS image ID. For Cloud, this value is from the provider. - * - * @example ami-07b06b442921831e5 - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_HOST_IMAGE_ID = 'host.image.id'; -/** - * Name of the VM image or OS install the host was instantiated from. - * - * @example infra-ami-eks-worker-node-7d4ec78312 - * @example CentOS-8-x86_64-1905 - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_HOST_IMAGE_NAME = 'host.image.name'; -/** - * The version string of the VM image or host OS as defined in [Version Attributes](/docs/resource/README.md#version-attributes). - * - * @example 0.1 - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_HOST_IMAGE_VERSION = 'host.image.version'; -/** - * Name of the host. On Unix systems, it may contain what the hostname command returns, or the fully qualified hostname, or another name specified by the user. - * - * @example opentelemetry-test - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_HOST_NAME = 'host.name'; -/** - * Type of host. For Cloud, this must be the machine type. - * - * @example n1-standard-1 - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_HOST_TYPE = 'host.type'; -/** - * The name of the cluster. - * - * @example opentelemetry-cluster - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_K8S_CLUSTER_NAME = 'k8s.cluster.name'; -/** - * The name of the Deployment. - * - * @example opentelemetry - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_K8S_DEPLOYMENT_NAME = 'k8s.deployment.name'; -/** - * The name of the namespace that the pod is running in. - * - * @example default - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_K8S_NAMESPACE_NAME = 'k8s.namespace.name'; -/** - * The name of the Pod. - * - * @example opentelemetry-pod-autoconf - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_K8S_POD_NAME = 'k8s.pod.name'; -/** - * The operating system type. - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_OS_TYPE = 'os.type'; -/** - * The version string of the operating system as defined in [Version Attributes](/docs/resource/README.md#version-attributes). - * - * @example 14.2.1 - * @example 18.04.1 - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_OS_VERSION = 'os.version'; -/** - * The command used to launch the process (i.e. the command name). On Linux based systems, can be set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can be set to the first parameter extracted from `GetCommandLineW`. - * - * @example cmd/otelcol - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_PROCESS_COMMAND = 'process.command'; -/** - * All the command arguments (including the command/executable itself) as received by the process. On Linux-based systems (and some other Unixoid systems supporting procfs), can be set according to the list of null-delimited strings extracted from `proc/[pid]/cmdline`. For libc-based executables, this would be the full argv vector passed to `main`. - * - * @example ["cmd/otecol", "--config=config.yaml"] - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_PROCESS_COMMAND_ARGS = 'process.command_args'; -/** - * The name of the process executable. On Linux based systems, this **SHOULD** be set to the base name of the target of `/proc/[pid]/exe`. On Windows, this **SHOULD** be set to the base name of `GetProcessImageFileNameW`. - * - * @example otelcol - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_PROCESS_EXECUTABLE_NAME = 'process.executable.name'; -/** - * The full path to the process executable. On Linux based systems, can be set to the target of `proc/[pid]/exe`. On Windows, can be set to the result of `GetProcessImageFileNameW`. - * - * @example /usr/bin/cmd/otelcol - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_PROCESS_EXECUTABLE_PATH = 'process.executable.path'; -/** - * The username of the user that owns the process. - * - * @example root - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_PROCESS_OWNER = 'process.owner'; -/** - * Process identifier (PID). - * - * @example 1234 - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_PROCESS_PID = 'process.pid'; -/** - * An additional description about the runtime of the process, for example a specific vendor customization of the runtime environment. - * - * @example "Eclipse OpenJ9 Eclipse OpenJ9 VM openj9-0.21.0" - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_PROCESS_RUNTIME_DESCRIPTION = 'process.runtime.description'; -/** - * The name of the runtime of this process. - * - * @example OpenJDK Runtime Environment - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_PROCESS_RUNTIME_NAME = 'process.runtime.name'; -/** - * The version of the runtime of this process, as returned by the runtime without modification. - * - * @example "14.0.2" - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_PROCESS_RUNTIME_VERSION = 'process.runtime.version'; -/** - * The string ID of the service instance. - * - * @example 627cc493-f310-47de-96bd-71410b7dec09 - * - * @note **MUST** be unique for each instance of the same `service.namespace,service.name` pair (in other words - * `service.namespace,service.name,service.instance.id` triplet **MUST** be globally unique). The ID helps to - * distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled - * service). - * - * Implementations, such as SDKs, are recommended to generate a random Version 1 or Version 4 [RFC - * 4122](https://www.ietf.org/rfc/rfc4122.txt) UUID, but are free to use an inherent unique ID as the source of - * this value if stability is desirable. In that case, the ID **SHOULD** be used as source of a UUID Version 5 and - * **SHOULD** use the following UUID as the namespace: `4d63009a-8d0f-11ee-aad7-4c796ed8e320`. - * - * UUIDs are typically recommended, as only an opaque value for the purposes of identifying a service instance is - * needed. Similar to what can be seen in the man page for the - * [`/etc/machine-id`](https://www.freedesktop.org/software/systemd/man/latest/machine-id.html) file, the underlying - * data, such as pod name and namespace should be treated as confidential, being the user's choice to expose it - * or not via another resource attribute. - * - * For applications running behind an application server (like unicorn), we do not recommend using one identifier - * for all processes participating in the application. Instead, it's recommended each division (e.g. a worker - * thread in unicorn) to have its own instance.id. - * - * It's not recommended for a Collector to set `service.instance.id` if it can't unambiguously determine the - * service instance that is generating that telemetry. For instance, creating an UUID based on `pod.name` will - * likely be wrong, as the Collector might not know from which container within that pod the telemetry originated. - * However, Collectors can set the `service.instance.id` if they can unambiguously determine the service instance - * for that telemetry. This is typically the case for scraping receivers, as they know the target address and - * port. - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_SERVICE_INSTANCE_ID = 'service.instance.id'; -/** - * A namespace for `service.name`. - * - * @example Shop - * - * @note A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace. - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_SERVICE_NAMESPACE = 'service.namespace'; -/** - * Additional description of the web engine (e.g. detailed version and edition information). - * - * @example WildFly Full 21.0.0.Final (WildFly Core 13.0.1.Final) - 2.2.2.Final - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_WEBENGINE_DESCRIPTION = 'webengine.description'; -/** - * The name of the web engine. - * - * @example WildFly - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_WEBENGINE_NAME = 'webengine.name'; -/** - * The version of the web engine. - * - * @example 21.0.0 - * - * @experimental This attribute is experimental and is subject to breaking changes in minor releases of `@opentelemetry/semantic-conventions`. - */ -exports.ATTR_WEBENGINE_VERSION = 'webengine.version'; -//# sourceMappingURL=semconv.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/resources/build/src/utils.js b/claude-code-source/node_modules/@opentelemetry/resources/build/src/utils.js deleted file mode 100644 index 3344e5e7..00000000 --- a/claude-code-source/node_modules/@opentelemetry/resources/build/src/utils.js +++ /dev/null @@ -1,29 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.identity = exports.isPromiseLike = void 0; -const isPromiseLike = (val) => { - return (val !== null && - typeof val === 'object' && - typeof val.then === 'function'); -}; -exports.isPromiseLike = isPromiseLike; -function identity(_) { - return _; -} -exports.identity = identity; -//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/LogRecordImpl.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/LogRecordImpl.js deleted file mode 100644 index 2252257c..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/LogRecordImpl.js +++ /dev/null @@ -1,193 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.LogRecordImpl = void 0; -const api = require("@opentelemetry/api"); -const core_1 = require("@opentelemetry/core"); -class LogRecordImpl { - hrTime; - hrTimeObserved; - spanContext; - resource; - instrumentationScope; - attributes = {}; - _severityText; - _severityNumber; - _body; - _eventName; - totalAttributesCount = 0; - _isReadonly = false; - _logRecordLimits; - set severityText(severityText) { - if (this._isLogRecordReadonly()) { - return; - } - this._severityText = severityText; - } - get severityText() { - return this._severityText; - } - set severityNumber(severityNumber) { - if (this._isLogRecordReadonly()) { - return; - } - this._severityNumber = severityNumber; - } - get severityNumber() { - return this._severityNumber; - } - set body(body) { - if (this._isLogRecordReadonly()) { - return; - } - this._body = body; - } - get body() { - return this._body; - } - get eventName() { - return this._eventName; - } - set eventName(eventName) { - if (this._isLogRecordReadonly()) { - return; - } - this._eventName = eventName; - } - get droppedAttributesCount() { - return this.totalAttributesCount - Object.keys(this.attributes).length; - } - constructor(_sharedState, instrumentationScope, logRecord) { - const { timestamp, observedTimestamp, eventName, severityNumber, severityText, body, attributes = {}, context, } = logRecord; - const now = Date.now(); - this.hrTime = (0, core_1.timeInputToHrTime)(timestamp ?? now); - this.hrTimeObserved = (0, core_1.timeInputToHrTime)(observedTimestamp ?? now); - if (context) { - const spanContext = api.trace.getSpanContext(context); - if (spanContext && api.isSpanContextValid(spanContext)) { - this.spanContext = spanContext; - } - } - this.severityNumber = severityNumber; - this.severityText = severityText; - this.body = body; - this.resource = _sharedState.resource; - this.instrumentationScope = instrumentationScope; - this._logRecordLimits = _sharedState.logRecordLimits; - this._eventName = eventName; - this.setAttributes(attributes); - } - setAttribute(key, value) { - if (this._isLogRecordReadonly()) { - return this; - } - if (value === null) { - return this; - } - if (key.length === 0) { - api.diag.warn(`Invalid attribute key: ${key}`); - return this; - } - if (!(0, core_1.isAttributeValue)(value) && - !(typeof value === 'object' && - !Array.isArray(value) && - Object.keys(value).length > 0)) { - api.diag.warn(`Invalid attribute value set for key: ${key}`); - return this; - } - this.totalAttributesCount += 1; - if (Object.keys(this.attributes).length >= - this._logRecordLimits.attributeCountLimit && - !Object.prototype.hasOwnProperty.call(this.attributes, key)) { - // This logic is to create drop message at most once per LogRecord to prevent excessive logging. - if (this.droppedAttributesCount === 1) { - api.diag.warn('Dropping extra attributes.'); - } - return this; - } - if ((0, core_1.isAttributeValue)(value)) { - this.attributes[key] = this._truncateToSize(value); - } - else { - this.attributes[key] = value; - } - return this; - } - setAttributes(attributes) { - for (const [k, v] of Object.entries(attributes)) { - this.setAttribute(k, v); - } - return this; - } - setBody(body) { - this.body = body; - return this; - } - setEventName(eventName) { - this.eventName = eventName; - return this; - } - setSeverityNumber(severityNumber) { - this.severityNumber = severityNumber; - return this; - } - setSeverityText(severityText) { - this.severityText = severityText; - return this; - } - /** - * @internal - * A LogRecordProcessor may freely modify logRecord for the duration of the OnEmit call. - * If logRecord is needed after OnEmit returns (i.e. for asynchronous processing) only reads are permitted. - */ - _makeReadonly() { - this._isReadonly = true; - } - _truncateToSize(value) { - const limit = this._logRecordLimits.attributeValueLengthLimit; - // Check limit - if (limit <= 0) { - // Negative values are invalid, so do not truncate - api.diag.warn(`Attribute value limit must be positive, got ${limit}`); - return value; - } - // String - if (typeof value === 'string') { - return this._truncateToLimitUtil(value, limit); - } - // Array of strings - if (Array.isArray(value)) { - return value.map(val => typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val); - } - // Other types, no need to apply value length limit - return value; - } - _truncateToLimitUtil(value, limit) { - if (value.length <= limit) { - return value; - } - return value.substring(0, limit); - } - _isLogRecordReadonly() { - if (this._isReadonly) { - api.diag.warn('Can not execute the operation on emitted log record'); - } - return this._isReadonly; - } -} -exports.LogRecordImpl = LogRecordImpl; -//# sourceMappingURL=LogRecordImpl.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/Logger.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/Logger.js deleted file mode 100644 index 1a1c6357..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/Logger.js +++ /dev/null @@ -1,52 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Logger = void 0; -const api_1 = require("@opentelemetry/api"); -const LogRecordImpl_1 = require("./LogRecordImpl"); -class Logger { - instrumentationScope; - _sharedState; - constructor(instrumentationScope, _sharedState) { - this.instrumentationScope = instrumentationScope; - this._sharedState = _sharedState; - } - emit(logRecord) { - const currentContext = logRecord.context || api_1.context.active(); - /** - * If a Logger was obtained with include_trace_context=true, - * the LogRecords it emits MUST automatically include the Trace Context from the active Context, - * if Context has not been explicitly set. - */ - const logRecordInstance = new LogRecordImpl_1.LogRecordImpl(this._sharedState, this.instrumentationScope, { - context: currentContext, - ...logRecord, - }); - /** - * the explicitly passed Context, - * the current Context, or an empty Context if the Logger was obtained with include_trace_context=false - */ - this._sharedState.activeProcessor.onEmit(logRecordInstance, currentContext); - /** - * A LogRecordProcessor may freely modify logRecord for the duration of the OnEmit call. - * If logRecord is needed after OnEmit returns (i.e. for asynchronous processing) only reads are permitted. - */ - logRecordInstance._makeReadonly(); - } -} -exports.Logger = Logger; -//# sourceMappingURL=Logger.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/LoggerProvider.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/LoggerProvider.js deleted file mode 100644 index 02d0b6fa..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/LoggerProvider.js +++ /dev/null @@ -1,86 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.LoggerProvider = exports.DEFAULT_LOGGER_NAME = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const api_1 = require("@opentelemetry/api"); -const api_logs_1 = require("@opentelemetry/api-logs"); -const resources_1 = require("@opentelemetry/resources"); -const core_1 = require("@opentelemetry/core"); -const Logger_1 = require("./Logger"); -const config_1 = require("./config"); -const LoggerProviderSharedState_1 = require("./internal/LoggerProviderSharedState"); -exports.DEFAULT_LOGGER_NAME = 'unknown'; -class LoggerProvider { - _shutdownOnce; - _sharedState; - constructor(config = {}) { - const mergedConfig = (0, core_1.merge)({}, (0, config_1.loadDefaultConfig)(), config); - const resource = config.resource ?? (0, resources_1.defaultResource)(); - this._sharedState = new LoggerProviderSharedState_1.LoggerProviderSharedState(resource, mergedConfig.forceFlushTimeoutMillis, (0, config_1.reconfigureLimits)(mergedConfig.logRecordLimits), config?.processors ?? []); - this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this); - } - /** - * Get a logger with the configuration of the LoggerProvider. - */ - getLogger(name, version, options) { - if (this._shutdownOnce.isCalled) { - api_1.diag.warn('A shutdown LoggerProvider cannot provide a Logger'); - return api_logs_1.NOOP_LOGGER; - } - if (!name) { - api_1.diag.warn('Logger requested without instrumentation scope name.'); - } - const loggerName = name || exports.DEFAULT_LOGGER_NAME; - const key = `${loggerName}@${version || ''}:${options?.schemaUrl || ''}`; - if (!this._sharedState.loggers.has(key)) { - this._sharedState.loggers.set(key, new Logger_1.Logger({ name: loggerName, version, schemaUrl: options?.schemaUrl }, this._sharedState)); - } - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - return this._sharedState.loggers.get(key); - } - /** - * Notifies all registered LogRecordProcessor to flush any buffered data. - * - * Returns a promise which is resolved when all flushes are complete. - */ - forceFlush() { - // do not flush after shutdown - if (this._shutdownOnce.isCalled) { - api_1.diag.warn('invalid attempt to force flush after LoggerProvider shutdown'); - return this._shutdownOnce.promise; - } - return this._sharedState.activeProcessor.forceFlush(); - } - /** - * Flush all buffered data and shut down the LoggerProvider and all registered - * LogRecordProcessor. - * - * Returns a promise which is resolved when all flushes are complete. - */ - shutdown() { - if (this._shutdownOnce.isCalled) { - api_1.diag.warn('shutdown may only be called once per LoggerProvider'); - return this._shutdownOnce.promise; - } - return this._shutdownOnce.call(); - } - _shutdown() { - return this._sharedState.activeProcessor.shutdown(); - } -} -exports.LoggerProvider = LoggerProvider; -//# sourceMappingURL=LoggerProvider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/MultiLogRecordProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/MultiLogRecordProcessor.js deleted file mode 100644 index 9852dbd6..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/MultiLogRecordProcessor.js +++ /dev/null @@ -1,43 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MultiLogRecordProcessor = void 0; -const core_1 = require("@opentelemetry/core"); -/** - * Implementation of the {@link LogRecordProcessor} that simply forwards all - * received events to a list of {@link LogRecordProcessor}s. - */ -class MultiLogRecordProcessor { - processors; - forceFlushTimeoutMillis; - constructor(processors, forceFlushTimeoutMillis) { - this.processors = processors; - this.forceFlushTimeoutMillis = forceFlushTimeoutMillis; - } - async forceFlush() { - const timeout = this.forceFlushTimeoutMillis; - await Promise.all(this.processors.map(processor => (0, core_1.callWithTimeout)(processor.forceFlush(), timeout))); - } - onEmit(logRecord, context) { - this.processors.forEach(processors => processors.onEmit(logRecord, context)); - } - async shutdown() { - await Promise.all(this.processors.map(processor => processor.shutdown())); - } -} -exports.MultiLogRecordProcessor = MultiLogRecordProcessor; -//# sourceMappingURL=MultiLogRecordProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/config.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/config.js deleted file mode 100644 index e3433b7e..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/config.js +++ /dev/null @@ -1,56 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.reconfigureLimits = exports.loadDefaultConfig = void 0; -const core_1 = require("@opentelemetry/core"); -function loadDefaultConfig() { - return { - forceFlushTimeoutMillis: 30000, - logRecordLimits: { - attributeValueLengthLimit: (0, core_1.getNumberFromEnv)('OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? - Infinity, - attributeCountLimit: (0, core_1.getNumberFromEnv)('OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT') ?? 128, - }, - includeTraceContext: true, - }; -} -exports.loadDefaultConfig = loadDefaultConfig; -/** - * When general limits are provided and model specific limits are not, - * configures the model specific limits by using the values from the general ones. - * @param logRecordLimits User provided limits configuration - */ -function reconfigureLimits(logRecordLimits) { - return { - /** - * Reassign log record attribute count limit to use first non null value defined by user or use default value - */ - attributeCountLimit: logRecordLimits.attributeCountLimit ?? - (0, core_1.getNumberFromEnv)('OTEL_LOGRECORD_ATTRIBUTE_COUNT_LIMIT') ?? - (0, core_1.getNumberFromEnv)('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? - 128, - /** - * Reassign log record attribute value length limit to use first non null value defined by user or use default value - */ - attributeValueLengthLimit: logRecordLimits.attributeValueLengthLimit ?? - (0, core_1.getNumberFromEnv)('OTEL_LOGRECORD_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? - (0, core_1.getNumberFromEnv)('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? - Infinity, - }; -} -exports.reconfigureLimits = reconfigureLimits; -//# sourceMappingURL=config.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/BatchLogRecordProcessorBase.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/BatchLogRecordProcessorBase.js deleted file mode 100644 index 47156d0e..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/BatchLogRecordProcessorBase.js +++ /dev/null @@ -1,172 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BatchLogRecordProcessorBase = void 0; -const api_1 = require("@opentelemetry/api"); -const core_1 = require("@opentelemetry/core"); -class BatchLogRecordProcessorBase { - _exporter; - _maxExportBatchSize; - _maxQueueSize; - _scheduledDelayMillis; - _exportTimeoutMillis; - _isExporting = false; - _finishedLogRecords = []; - _timer; - _shutdownOnce; - constructor(_exporter, config) { - this._exporter = _exporter; - this._maxExportBatchSize = - config?.maxExportBatchSize ?? - (0, core_1.getNumberFromEnv)('OTEL_BLRP_MAX_EXPORT_BATCH_SIZE') ?? - 512; - this._maxQueueSize = - config?.maxQueueSize ?? - (0, core_1.getNumberFromEnv)('OTEL_BLRP_MAX_QUEUE_SIZE') ?? - 2048; - this._scheduledDelayMillis = - config?.scheduledDelayMillis ?? - (0, core_1.getNumberFromEnv)('OTEL_BLRP_SCHEDULE_DELAY') ?? - 5000; - this._exportTimeoutMillis = - config?.exportTimeoutMillis ?? - (0, core_1.getNumberFromEnv)('OTEL_BLRP_EXPORT_TIMEOUT') ?? - 30000; - this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this); - if (this._maxExportBatchSize > this._maxQueueSize) { - api_1.diag.warn('BatchLogRecordProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'); - this._maxExportBatchSize = this._maxQueueSize; - } - } - onEmit(logRecord) { - if (this._shutdownOnce.isCalled) { - return; - } - this._addToBuffer(logRecord); - } - forceFlush() { - if (this._shutdownOnce.isCalled) { - return this._shutdownOnce.promise; - } - return this._flushAll(); - } - shutdown() { - return this._shutdownOnce.call(); - } - async _shutdown() { - this.onShutdown(); - await this._flushAll(); - await this._exporter.shutdown(); - } - /** Add a LogRecord in the buffer. */ - _addToBuffer(logRecord) { - if (this._finishedLogRecords.length >= this._maxQueueSize) { - return; - } - this._finishedLogRecords.push(logRecord); - this._maybeStartTimer(); - } - /** - * Send all LogRecords to the exporter respecting the batch size limit - * This function is used only on forceFlush or shutdown, - * for all other cases _flush should be used - * */ - _flushAll() { - return new Promise((resolve, reject) => { - const promises = []; - const batchCount = Math.ceil(this._finishedLogRecords.length / this._maxExportBatchSize); - for (let i = 0; i < batchCount; i++) { - promises.push(this._flushOneBatch()); - } - Promise.all(promises) - .then(() => { - resolve(); - }) - .catch(reject); - }); - } - _flushOneBatch() { - this._clearTimer(); - if (this._finishedLogRecords.length === 0) { - return Promise.resolve(); - } - return new Promise((resolve, reject) => { - (0, core_1.callWithTimeout)(this._export(this._finishedLogRecords.splice(0, this._maxExportBatchSize)), this._exportTimeoutMillis) - .then(() => resolve()) - .catch(reject); - }); - } - _maybeStartTimer() { - if (this._isExporting) - return; - const flush = () => { - this._isExporting = true; - this._flushOneBatch() - .then(() => { - this._isExporting = false; - if (this._finishedLogRecords.length > 0) { - this._clearTimer(); - this._maybeStartTimer(); - } - }) - .catch(e => { - this._isExporting = false; - (0, core_1.globalErrorHandler)(e); - }); - }; - // we only wait if the queue doesn't have enough elements yet - if (this._finishedLogRecords.length >= this._maxExportBatchSize) { - return flush(); - } - if (this._timer !== undefined) - return; - this._timer = setTimeout(() => flush(), this._scheduledDelayMillis); - // depending on runtime, this may be a 'number' or NodeJS.Timeout - if (typeof this._timer !== 'number') { - this._timer.unref(); - } - } - _clearTimer() { - if (this._timer !== undefined) { - clearTimeout(this._timer); - this._timer = undefined; - } - } - _export(logRecords) { - const doExport = () => core_1.internal - ._export(this._exporter, logRecords) - .then((result) => { - if (result.code !== core_1.ExportResultCode.SUCCESS) { - (0, core_1.globalErrorHandler)(result.error ?? - new Error(`BatchLogRecordProcessor: log record export failed (status ${result})`)); - } - }) - .catch(core_1.globalErrorHandler); - const pendingResources = logRecords - .map(logRecord => logRecord.resource) - .filter(resource => resource.asyncAttributesPending); - // Avoid scheduling a promise to make the behavior more predictable and easier to test - if (pendingResources.length === 0) { - return doExport(); - } - else { - return Promise.all(pendingResources.map(resource => resource.waitForAsyncAttributes?.())).then(doExport, core_1.globalErrorHandler); - } - } -} -exports.BatchLogRecordProcessorBase = BatchLogRecordProcessorBase; -//# sourceMappingURL=BatchLogRecordProcessorBase.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/ConsoleLogRecordExporter.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/ConsoleLogRecordExporter.js deleted file mode 100644 index 45ad2268..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/ConsoleLogRecordExporter.js +++ /dev/null @@ -1,75 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConsoleLogRecordExporter = void 0; -const core_1 = require("@opentelemetry/core"); -/** - * This is implementation of {@link LogRecordExporter} that prints LogRecords to the - * console. This class can be used for diagnostic purposes. - * - * NOTE: This {@link LogRecordExporter} is intended for diagnostics use only, output rendered to the console may change at any time. - */ -/* eslint-disable no-console */ -class ConsoleLogRecordExporter { - /** - * Export logs. - * @param logs - * @param resultCallback - */ - export(logs, resultCallback) { - this._sendLogRecords(logs, resultCallback); - } - /** - * Shutdown the exporter. - */ - shutdown() { - return Promise.resolve(); - } - /** - * converts logRecord info into more readable format - * @param logRecord - */ - _exportInfo(logRecord) { - return { - resource: { - attributes: logRecord.resource.attributes, - }, - instrumentationScope: logRecord.instrumentationScope, - timestamp: (0, core_1.hrTimeToMicroseconds)(logRecord.hrTime), - traceId: logRecord.spanContext?.traceId, - spanId: logRecord.spanContext?.spanId, - traceFlags: logRecord.spanContext?.traceFlags, - severityText: logRecord.severityText, - severityNumber: logRecord.severityNumber, - body: logRecord.body, - attributes: logRecord.attributes, - }; - } - /** - * Showing logs in console - * @param logRecords - * @param done - */ - _sendLogRecords(logRecords, done) { - for (const logRecord of logRecords) { - console.dir(this._exportInfo(logRecord), { depth: 3 }); - } - done?.({ code: core_1.ExportResultCode.SUCCESS }); - } -} -exports.ConsoleLogRecordExporter = ConsoleLogRecordExporter; -//# sourceMappingURL=ConsoleLogRecordExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/InMemoryLogRecordExporter.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/InMemoryLogRecordExporter.js deleted file mode 100644 index ffe46bbd..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/InMemoryLogRecordExporter.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.InMemoryLogRecordExporter = void 0; -const core_1 = require("@opentelemetry/core"); -/** - * This class can be used for testing purposes. It stores the exported LogRecords - * in a list in memory that can be retrieved using the `getFinishedLogRecords()` - * method. - */ -class InMemoryLogRecordExporter { - _finishedLogRecords = []; - /** - * Indicates if the exporter has been "shutdown." - * When false, exported log records will not be stored in-memory. - */ - _stopped = false; - export(logs, resultCallback) { - if (this._stopped) { - return resultCallback({ - code: core_1.ExportResultCode.FAILED, - error: new Error('Exporter has been stopped'), - }); - } - this._finishedLogRecords.push(...logs); - resultCallback({ code: core_1.ExportResultCode.SUCCESS }); - } - shutdown() { - this._stopped = true; - this.reset(); - return Promise.resolve(); - } - getFinishedLogRecords() { - return this._finishedLogRecords; - } - reset() { - this._finishedLogRecords = []; - } -} -exports.InMemoryLogRecordExporter = InMemoryLogRecordExporter; -//# sourceMappingURL=InMemoryLogRecordExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/NoopLogRecordProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/NoopLogRecordProcessor.js deleted file mode 100644 index a845099a..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/NoopLogRecordProcessor.js +++ /dev/null @@ -1,29 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.NoopLogRecordProcessor = void 0; -class NoopLogRecordProcessor { - forceFlush() { - return Promise.resolve(); - } - onEmit(_logRecord, _context) { } - shutdown() { - return Promise.resolve(); - } -} -exports.NoopLogRecordProcessor = NoopLogRecordProcessor; -//# sourceMappingURL=NoopLogRecordProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/SimpleLogRecordProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/SimpleLogRecordProcessor.js deleted file mode 100644 index 5b4490e6..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/export/SimpleLogRecordProcessor.js +++ /dev/null @@ -1,83 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SimpleLogRecordProcessor = void 0; -const core_1 = require("@opentelemetry/core"); -/** - * An implementation of the {@link LogRecordProcessor} interface that exports - * each {@link LogRecord} as it is emitted. - * - * NOTE: This {@link LogRecordProcessor} exports every {@link LogRecord} - * individually instead of batching them together, which can cause significant - * performance overhead with most exporters. For production use, please consider - * using the {@link BatchLogRecordProcessor} instead. - */ -class SimpleLogRecordProcessor { - _exporter; - _shutdownOnce; - _unresolvedExports; - constructor(_exporter) { - this._exporter = _exporter; - this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this); - this._unresolvedExports = new Set(); - } - onEmit(logRecord) { - if (this._shutdownOnce.isCalled) { - return; - } - const doExport = () => core_1.internal - ._export(this._exporter, [logRecord]) - .then((result) => { - if (result.code !== core_1.ExportResultCode.SUCCESS) { - (0, core_1.globalErrorHandler)(result.error ?? - new Error(`SimpleLogRecordProcessor: log record export failed (status ${result})`)); - } - }) - .catch(core_1.globalErrorHandler); - // Avoid scheduling a promise to make the behavior more predictable and easier to test - if (logRecord.resource.asyncAttributesPending) { - const exportPromise = logRecord.resource - .waitForAsyncAttributes?.() - .then(() => { - // Using TS Non-null assertion operator because exportPromise could not be null in here - // if waitForAsyncAttributes is not present this code will never be reached - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - this._unresolvedExports.delete(exportPromise); - return doExport(); - }, core_1.globalErrorHandler); - // store the unresolved exports - if (exportPromise != null) { - this._unresolvedExports.add(exportPromise); - } - } - else { - void doExport(); - } - } - async forceFlush() { - // await unresolved resources before resolving - await Promise.all(Array.from(this._unresolvedExports)); - } - shutdown() { - return this._shutdownOnce.call(); - } - _shutdown() { - return this._exporter.shutdown(); - } -} -exports.SimpleLogRecordProcessor = SimpleLogRecordProcessor; -//# sourceMappingURL=SimpleLogRecordProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/index.js deleted file mode 100644 index 5bb9f418..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/index.js +++ /dev/null @@ -1,29 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BatchLogRecordProcessor = exports.InMemoryLogRecordExporter = exports.SimpleLogRecordProcessor = exports.ConsoleLogRecordExporter = exports.LoggerProvider = void 0; -var LoggerProvider_1 = require("./LoggerProvider"); -Object.defineProperty(exports, "LoggerProvider", { enumerable: true, get: function () { return LoggerProvider_1.LoggerProvider; } }); -var ConsoleLogRecordExporter_1 = require("./export/ConsoleLogRecordExporter"); -Object.defineProperty(exports, "ConsoleLogRecordExporter", { enumerable: true, get: function () { return ConsoleLogRecordExporter_1.ConsoleLogRecordExporter; } }); -var SimpleLogRecordProcessor_1 = require("./export/SimpleLogRecordProcessor"); -Object.defineProperty(exports, "SimpleLogRecordProcessor", { enumerable: true, get: function () { return SimpleLogRecordProcessor_1.SimpleLogRecordProcessor; } }); -var InMemoryLogRecordExporter_1 = require("./export/InMemoryLogRecordExporter"); -Object.defineProperty(exports, "InMemoryLogRecordExporter", { enumerable: true, get: function () { return InMemoryLogRecordExporter_1.InMemoryLogRecordExporter; } }); -var platform_1 = require("./platform"); -Object.defineProperty(exports, "BatchLogRecordProcessor", { enumerable: true, get: function () { return platform_1.BatchLogRecordProcessor; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/internal/LoggerProviderSharedState.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/internal/LoggerProviderSharedState.js deleted file mode 100644 index 9a58a2e0..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/internal/LoggerProviderSharedState.js +++ /dev/null @@ -1,44 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.LoggerProviderSharedState = void 0; -const NoopLogRecordProcessor_1 = require("../export/NoopLogRecordProcessor"); -const MultiLogRecordProcessor_1 = require("../MultiLogRecordProcessor"); -class LoggerProviderSharedState { - resource; - forceFlushTimeoutMillis; - logRecordLimits; - processors; - loggers = new Map(); - activeProcessor; - registeredLogRecordProcessors = []; - constructor(resource, forceFlushTimeoutMillis, logRecordLimits, processors) { - this.resource = resource; - this.forceFlushTimeoutMillis = forceFlushTimeoutMillis; - this.logRecordLimits = logRecordLimits; - this.processors = processors; - if (processors.length > 0) { - this.registeredLogRecordProcessors = processors; - this.activeProcessor = new MultiLogRecordProcessor_1.MultiLogRecordProcessor(this.registeredLogRecordProcessors, this.forceFlushTimeoutMillis); - } - else { - this.activeProcessor = new NoopLogRecordProcessor_1.NoopLogRecordProcessor(); - } - } -} -exports.LoggerProviderSharedState = LoggerProviderSharedState; -//# sourceMappingURL=LoggerProviderSharedState.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/index.js deleted file mode 100644 index b76b4fc5..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BatchLogRecordProcessor = void 0; -var node_1 = require("./node"); -Object.defineProperty(exports, "BatchLogRecordProcessor", { enumerable: true, get: function () { return node_1.BatchLogRecordProcessor; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/node/export/BatchLogRecordProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/node/export/BatchLogRecordProcessor.js deleted file mode 100644 index b6d2413a..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/node/export/BatchLogRecordProcessor.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BatchLogRecordProcessor = void 0; -const BatchLogRecordProcessorBase_1 = require("../../../export/BatchLogRecordProcessorBase"); -class BatchLogRecordProcessor extends BatchLogRecordProcessorBase_1.BatchLogRecordProcessorBase { - onShutdown() { } -} -exports.BatchLogRecordProcessor = BatchLogRecordProcessor; -//# sourceMappingURL=BatchLogRecordProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/node/index.js deleted file mode 100644 index b23b699c..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-logs/build/src/platform/node/index.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BatchLogRecordProcessor = void 0; -var BatchLogRecordProcessor_1 = require("./export/BatchLogRecordProcessor"); -Object.defineProperty(exports, "BatchLogRecordProcessor", { enumerable: true, get: function () { return BatchLogRecordProcessor_1.BatchLogRecordProcessor; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/InstrumentDescriptor.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/InstrumentDescriptor.js deleted file mode 100644 index b429f2ea..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/InstrumentDescriptor.js +++ /dev/null @@ -1,61 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isValidName = exports.isDescriptorCompatibleWith = exports.createInstrumentDescriptorWithView = exports.createInstrumentDescriptor = void 0; -const api_1 = require("@opentelemetry/api"); -const utils_1 = require("./utils"); -function createInstrumentDescriptor(name, type, options) { - if (!isValidName(name)) { - api_1.diag.warn(`Invalid metric name: "${name}". The metric name should be a ASCII string with a length no greater than 255 characters.`); - } - return { - name, - type, - description: options?.description ?? '', - unit: options?.unit ?? '', - valueType: options?.valueType ?? api_1.ValueType.DOUBLE, - advice: options?.advice ?? {}, - }; -} -exports.createInstrumentDescriptor = createInstrumentDescriptor; -function createInstrumentDescriptorWithView(view, instrument) { - return { - name: view.name ?? instrument.name, - description: view.description ?? instrument.description, - type: instrument.type, - unit: instrument.unit, - valueType: instrument.valueType, - advice: instrument.advice, - }; -} -exports.createInstrumentDescriptorWithView = createInstrumentDescriptorWithView; -function isDescriptorCompatibleWith(descriptor, otherDescriptor) { - // Names are case-insensitive strings. - return ((0, utils_1.equalsCaseInsensitive)(descriptor.name, otherDescriptor.name) && - descriptor.unit === otherDescriptor.unit && - descriptor.type === otherDescriptor.type && - descriptor.valueType === otherDescriptor.valueType); -} -exports.isDescriptorCompatibleWith = isDescriptorCompatibleWith; -// ASCII string with a length no greater than 255 characters. -// NB: the first character counted separately from the rest. -const NAME_REGEXP = /^[a-z][a-z0-9_.\-/]{0,254}$/i; -function isValidName(name) { - return name.match(NAME_REGEXP) != null; -} -exports.isValidName = isValidName; -//# sourceMappingURL=InstrumentDescriptor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/Instruments.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/Instruments.js deleted file mode 100644 index 22f32e4b..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/Instruments.js +++ /dev/null @@ -1,140 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isObservableInstrument = exports.ObservableUpDownCounterInstrument = exports.ObservableGaugeInstrument = exports.ObservableCounterInstrument = exports.ObservableInstrument = exports.HistogramInstrument = exports.GaugeInstrument = exports.CounterInstrument = exports.UpDownCounterInstrument = exports.SyncInstrument = void 0; -const api_1 = require("@opentelemetry/api"); -const core_1 = require("@opentelemetry/core"); -class SyncInstrument { - _writableMetricStorage; - _descriptor; - constructor(_writableMetricStorage, _descriptor) { - this._writableMetricStorage = _writableMetricStorage; - this._descriptor = _descriptor; - } - _record(value, attributes = {}, context = api_1.context.active()) { - if (typeof value !== 'number') { - api_1.diag.warn(`non-number value provided to metric ${this._descriptor.name}: ${value}`); - return; - } - if (this._descriptor.valueType === api_1.ValueType.INT && - !Number.isInteger(value)) { - api_1.diag.warn(`INT value type cannot accept a floating-point value for ${this._descriptor.name}, ignoring the fractional digits.`); - value = Math.trunc(value); - // ignore non-finite values. - if (!Number.isInteger(value)) { - return; - } - } - this._writableMetricStorage.record(value, attributes, context, (0, core_1.millisToHrTime)(Date.now())); - } -} -exports.SyncInstrument = SyncInstrument; -/** - * The class implements {@link UpDownCounter} interface. - */ -class UpDownCounterInstrument extends SyncInstrument { - /** - * Increment value of counter by the input. Inputs may be negative. - */ - add(value, attributes, ctx) { - this._record(value, attributes, ctx); - } -} -exports.UpDownCounterInstrument = UpDownCounterInstrument; -/** - * The class implements {@link Counter} interface. - */ -class CounterInstrument extends SyncInstrument { - /** - * Increment value of counter by the input. Inputs may not be negative. - */ - add(value, attributes, ctx) { - if (value < 0) { - api_1.diag.warn(`negative value provided to counter ${this._descriptor.name}: ${value}`); - return; - } - this._record(value, attributes, ctx); - } -} -exports.CounterInstrument = CounterInstrument; -/** - * The class implements {@link Gauge} interface. - */ -class GaugeInstrument extends SyncInstrument { - /** - * Records a measurement. - */ - record(value, attributes, ctx) { - this._record(value, attributes, ctx); - } -} -exports.GaugeInstrument = GaugeInstrument; -/** - * The class implements {@link Histogram} interface. - */ -class HistogramInstrument extends SyncInstrument { - /** - * Records a measurement. Value of the measurement must not be negative. - */ - record(value, attributes, ctx) { - if (value < 0) { - api_1.diag.warn(`negative value provided to histogram ${this._descriptor.name}: ${value}`); - return; - } - this._record(value, attributes, ctx); - } -} -exports.HistogramInstrument = HistogramInstrument; -class ObservableInstrument { - _observableRegistry; - /** @internal */ - _metricStorages; - /** @internal */ - _descriptor; - constructor(descriptor, metricStorages, _observableRegistry) { - this._observableRegistry = _observableRegistry; - this._descriptor = descriptor; - this._metricStorages = metricStorages; - } - /** - * @see {Observable.addCallback} - */ - addCallback(callback) { - this._observableRegistry.addCallback(callback, this); - } - /** - * @see {Observable.removeCallback} - */ - removeCallback(callback) { - this._observableRegistry.removeCallback(callback, this); - } -} -exports.ObservableInstrument = ObservableInstrument; -class ObservableCounterInstrument extends ObservableInstrument { -} -exports.ObservableCounterInstrument = ObservableCounterInstrument; -class ObservableGaugeInstrument extends ObservableInstrument { -} -exports.ObservableGaugeInstrument = ObservableGaugeInstrument; -class ObservableUpDownCounterInstrument extends ObservableInstrument { -} -exports.ObservableUpDownCounterInstrument = ObservableUpDownCounterInstrument; -function isObservableInstrument(it) { - return it instanceof ObservableInstrument; -} -exports.isObservableInstrument = isObservableInstrument; -//# sourceMappingURL=Instruments.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/Meter.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/Meter.js deleted file mode 100644 index 63f1909c..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/Meter.js +++ /dev/null @@ -1,100 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Meter = void 0; -const InstrumentDescriptor_1 = require("./InstrumentDescriptor"); -const Instruments_1 = require("./Instruments"); -const MetricData_1 = require("./export/MetricData"); -/** - * This class implements the {@link IMeter} interface. - */ -class Meter { - _meterSharedState; - constructor(_meterSharedState) { - this._meterSharedState = _meterSharedState; - } - /** - * Create a {@link Gauge} instrument. - */ - createGauge(name, options) { - const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.GAUGE, options); - const storage = this._meterSharedState.registerMetricStorage(descriptor); - return new Instruments_1.GaugeInstrument(storage, descriptor); - } - /** - * Create a {@link Histogram} instrument. - */ - createHistogram(name, options) { - const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.HISTOGRAM, options); - const storage = this._meterSharedState.registerMetricStorage(descriptor); - return new Instruments_1.HistogramInstrument(storage, descriptor); - } - /** - * Create a {@link Counter} instrument. - */ - createCounter(name, options) { - const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.COUNTER, options); - const storage = this._meterSharedState.registerMetricStorage(descriptor); - return new Instruments_1.CounterInstrument(storage, descriptor); - } - /** - * Create a {@link UpDownCounter} instrument. - */ - createUpDownCounter(name, options) { - const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.UP_DOWN_COUNTER, options); - const storage = this._meterSharedState.registerMetricStorage(descriptor); - return new Instruments_1.UpDownCounterInstrument(storage, descriptor); - } - /** - * Create a {@link ObservableGauge} instrument. - */ - createObservableGauge(name, options) { - const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.OBSERVABLE_GAUGE, options); - const storages = this._meterSharedState.registerAsyncMetricStorage(descriptor); - return new Instruments_1.ObservableGaugeInstrument(descriptor, storages, this._meterSharedState.observableRegistry); - } - /** - * Create a {@link ObservableCounter} instrument. - */ - createObservableCounter(name, options) { - const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.OBSERVABLE_COUNTER, options); - const storages = this._meterSharedState.registerAsyncMetricStorage(descriptor); - return new Instruments_1.ObservableCounterInstrument(descriptor, storages, this._meterSharedState.observableRegistry); - } - /** - * Create a {@link ObservableUpDownCounter} instrument. - */ - createObservableUpDownCounter(name, options) { - const descriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(name, MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER, options); - const storages = this._meterSharedState.registerAsyncMetricStorage(descriptor); - return new Instruments_1.ObservableUpDownCounterInstrument(descriptor, storages, this._meterSharedState.observableRegistry); - } - /** - * @see {@link Meter.addBatchObservableCallback} - */ - addBatchObservableCallback(callback, observables) { - this._meterSharedState.observableRegistry.addBatchCallback(callback, observables); - } - /** - * @see {@link Meter.removeBatchObservableCallback} - */ - removeBatchObservableCallback(callback, observables) { - this._meterSharedState.observableRegistry.removeBatchCallback(callback, observables); - } -} -exports.Meter = Meter; -//# sourceMappingURL=Meter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/MeterProvider.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/MeterProvider.js deleted file mode 100644 index 068cca7f..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/MeterProvider.js +++ /dev/null @@ -1,93 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MeterProvider = void 0; -const api_1 = require("@opentelemetry/api"); -const resources_1 = require("@opentelemetry/resources"); -const MeterProviderSharedState_1 = require("./state/MeterProviderSharedState"); -const MetricCollector_1 = require("./state/MetricCollector"); -const View_1 = require("./view/View"); -/** - * This class implements the {@link MeterProvider} interface. - */ -class MeterProvider { - _sharedState; - _shutdown = false; - constructor(options) { - this._sharedState = new MeterProviderSharedState_1.MeterProviderSharedState(options?.resource ?? (0, resources_1.defaultResource)()); - if (options?.views != null && options.views.length > 0) { - for (const viewOption of options.views) { - this._sharedState.viewRegistry.addView(new View_1.View(viewOption)); - } - } - if (options?.readers != null && options.readers.length > 0) { - for (const metricReader of options.readers) { - const collector = new MetricCollector_1.MetricCollector(this._sharedState, metricReader); - metricReader.setMetricProducer(collector); - this._sharedState.metricCollectors.push(collector); - } - } - } - /** - * Get a meter with the configuration of the MeterProvider. - */ - getMeter(name, version = '', options = {}) { - // https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/sdk.md#meter-creation - if (this._shutdown) { - api_1.diag.warn('A shutdown MeterProvider cannot provide a Meter'); - return (0, api_1.createNoopMeter)(); - } - return this._sharedState.getMeterSharedState({ - name, - version, - schemaUrl: options.schemaUrl, - }).meter; - } - /** - * Shut down the MeterProvider and all registered - * MetricReaders. - * - * Returns a promise which is resolved when all flushes are complete. - */ - async shutdown(options) { - if (this._shutdown) { - api_1.diag.warn('shutdown may only be called once per MeterProvider'); - return; - } - this._shutdown = true; - await Promise.all(this._sharedState.metricCollectors.map(collector => { - return collector.shutdown(options); - })); - } - /** - * Notifies all registered MetricReaders to flush any buffered data. - * - * Returns a promise which is resolved when all flushes are complete. - */ - async forceFlush(options) { - // do not flush after shutdown - if (this._shutdown) { - api_1.diag.warn('invalid attempt to force flush after MeterProvider shutdown'); - return; - } - await Promise.all(this._sharedState.metricCollectors.map(collector => { - return collector.forceFlush(options); - })); - } -} -exports.MeterProvider = MeterProvider; -//# sourceMappingURL=MeterProvider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/ObservableResult.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/ObservableResult.js deleted file mode 100644 index 3203e1ac..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/ObservableResult.js +++ /dev/null @@ -1,93 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BatchObservableResultImpl = exports.ObservableResultImpl = void 0; -const api_1 = require("@opentelemetry/api"); -const HashMap_1 = require("./state/HashMap"); -const Instruments_1 = require("./Instruments"); -/** - * The class implements {@link ObservableResult} interface. - */ -class ObservableResultImpl { - _instrumentName; - _valueType; - /** - * @internal - */ - _buffer = new HashMap_1.AttributeHashMap(); - constructor(_instrumentName, _valueType) { - this._instrumentName = _instrumentName; - this._valueType = _valueType; - } - /** - * Observe a measurement of the value associated with the given attributes. - */ - observe(value, attributes = {}) { - if (typeof value !== 'number') { - api_1.diag.warn(`non-number value provided to metric ${this._instrumentName}: ${value}`); - return; - } - if (this._valueType === api_1.ValueType.INT && !Number.isInteger(value)) { - api_1.diag.warn(`INT value type cannot accept a floating-point value for ${this._instrumentName}, ignoring the fractional digits.`); - value = Math.trunc(value); - // ignore non-finite values. - if (!Number.isInteger(value)) { - return; - } - } - this._buffer.set(attributes, value); - } -} -exports.ObservableResultImpl = ObservableResultImpl; -/** - * The class implements {@link BatchObservableCallback} interface. - */ -class BatchObservableResultImpl { - /** - * @internal - */ - _buffer = new Map(); - /** - * Observe a measurement of the value associated with the given attributes. - */ - observe(metric, value, attributes = {}) { - if (!(0, Instruments_1.isObservableInstrument)(metric)) { - return; - } - let map = this._buffer.get(metric); - if (map == null) { - map = new HashMap_1.AttributeHashMap(); - this._buffer.set(metric, map); - } - if (typeof value !== 'number') { - api_1.diag.warn(`non-number value provided to metric ${metric._descriptor.name}: ${value}`); - return; - } - if (metric._descriptor.valueType === api_1.ValueType.INT && - !Number.isInteger(value)) { - api_1.diag.warn(`INT value type cannot accept a floating-point value for ${metric._descriptor.name}, ignoring the fractional digits.`); - value = Math.trunc(value); - // ignore non-finite values. - if (!Number.isInteger(value)) { - return; - } - } - map.set(attributes, value); - } -} -exports.BatchObservableResultImpl = BatchObservableResultImpl; -//# sourceMappingURL=ObservableResult.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Drop.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Drop.js deleted file mode 100644 index ff68a76f..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Drop.js +++ /dev/null @@ -1,37 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DropAggregator = void 0; -const types_1 = require("./types"); -/** Basic aggregator for None which keeps no recorded value. */ -class DropAggregator { - kind = types_1.AggregatorKind.DROP; - createAccumulation() { - return undefined; - } - merge(_previous, _delta) { - return undefined; - } - diff(_previous, _current) { - return undefined; - } - toMetricData(_descriptor, _aggregationTemporality, _accumulationByAttributes, _endTime) { - return undefined; - } -} -exports.DropAggregator = DropAggregator; -//# sourceMappingURL=Drop.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/ExponentialHistogram.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/ExponentialHistogram.js deleted file mode 100644 index 2c563666..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/ExponentialHistogram.js +++ /dev/null @@ -1,480 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ExponentialHistogramAggregator = exports.ExponentialHistogramAccumulation = void 0; -const types_1 = require("./types"); -const MetricData_1 = require("../export/MetricData"); -const api_1 = require("@opentelemetry/api"); -const Buckets_1 = require("./exponential-histogram/Buckets"); -const getMapping_1 = require("./exponential-histogram/mapping/getMapping"); -const util_1 = require("./exponential-histogram/util"); -// HighLow is a utility class used for computing a common scale for -// two exponential histogram accumulations -class HighLow { - low; - high; - static combine(h1, h2) { - return new HighLow(Math.min(h1.low, h2.low), Math.max(h1.high, h2.high)); - } - constructor(low, high) { - this.low = low; - this.high = high; - } -} -const MAX_SCALE = 20; -const DEFAULT_MAX_SIZE = 160; -const MIN_MAX_SIZE = 2; -class ExponentialHistogramAccumulation { - startTime; - _maxSize; - _recordMinMax; - _sum; - _count; - _zeroCount; - _min; - _max; - _positive; - _negative; - _mapping; - constructor(startTime, _maxSize = DEFAULT_MAX_SIZE, _recordMinMax = true, _sum = 0, _count = 0, _zeroCount = 0, _min = Number.POSITIVE_INFINITY, _max = Number.NEGATIVE_INFINITY, _positive = new Buckets_1.Buckets(), _negative = new Buckets_1.Buckets(), _mapping = (0, getMapping_1.getMapping)(MAX_SCALE)) { - this.startTime = startTime; - this._maxSize = _maxSize; - this._recordMinMax = _recordMinMax; - this._sum = _sum; - this._count = _count; - this._zeroCount = _zeroCount; - this._min = _min; - this._max = _max; - this._positive = _positive; - this._negative = _negative; - this._mapping = _mapping; - if (this._maxSize < MIN_MAX_SIZE) { - api_1.diag.warn(`Exponential Histogram Max Size set to ${this._maxSize}, \ - changing to the minimum size of: ${MIN_MAX_SIZE}`); - this._maxSize = MIN_MAX_SIZE; - } - } - /** - * record updates a histogram with a single count - * @param {Number} value - */ - record(value) { - this.updateByIncrement(value, 1); - } - /** - * Sets the start time for this accumulation - * @param {HrTime} startTime - */ - setStartTime(startTime) { - this.startTime = startTime; - } - /** - * Returns the datapoint representation of this accumulation - * @param {HrTime} startTime - */ - toPointValue() { - return { - hasMinMax: this._recordMinMax, - min: this.min, - max: this.max, - sum: this.sum, - positive: { - offset: this.positive.offset, - bucketCounts: this.positive.counts(), - }, - negative: { - offset: this.negative.offset, - bucketCounts: this.negative.counts(), - }, - count: this.count, - scale: this.scale, - zeroCount: this.zeroCount, - }; - } - /** - * @returns {Number} The sum of values recorded by this accumulation - */ - get sum() { - return this._sum; - } - /** - * @returns {Number} The minimum value recorded by this accumulation - */ - get min() { - return this._min; - } - /** - * @returns {Number} The maximum value recorded by this accumulation - */ - get max() { - return this._max; - } - /** - * @returns {Number} The count of values recorded by this accumulation - */ - get count() { - return this._count; - } - /** - * @returns {Number} The number of 0 values recorded by this accumulation - */ - get zeroCount() { - return this._zeroCount; - } - /** - * @returns {Number} The scale used by this accumulation - */ - get scale() { - if (this._count === this._zeroCount) { - // all zeros! scale doesn't matter, use zero - return 0; - } - return this._mapping.scale; - } - /** - * positive holds the positive values - * @returns {Buckets} - */ - get positive() { - return this._positive; - } - /** - * negative holds the negative values by their absolute value - * @returns {Buckets} - */ - get negative() { - return this._negative; - } - /** - * updateByIncr supports updating a histogram with a non-negative - * increment. - * @param value - * @param increment - */ - updateByIncrement(value, increment) { - // NaN does not fall into any bucket, is not zero and should not be counted, - // NaN is never greater than max nor less than min, therefore return as there's nothing for us to do. - if (Number.isNaN(value)) { - return; - } - if (value > this._max) { - this._max = value; - } - if (value < this._min) { - this._min = value; - } - this._count += increment; - if (value === 0) { - this._zeroCount += increment; - return; - } - this._sum += value * increment; - if (value > 0) { - this._updateBuckets(this._positive, value, increment); - } - else { - this._updateBuckets(this._negative, -value, increment); - } - } - /** - * merge combines data from previous value into self - * @param {ExponentialHistogramAccumulation} previous - */ - merge(previous) { - if (this._count === 0) { - this._min = previous.min; - this._max = previous.max; - } - else if (previous.count !== 0) { - if (previous.min < this.min) { - this._min = previous.min; - } - if (previous.max > this.max) { - this._max = previous.max; - } - } - this.startTime = previous.startTime; - this._sum += previous.sum; - this._count += previous.count; - this._zeroCount += previous.zeroCount; - const minScale = this._minScale(previous); - this._downscale(this.scale - minScale); - this._mergeBuckets(this.positive, previous, previous.positive, minScale); - this._mergeBuckets(this.negative, previous, previous.negative, minScale); - } - /** - * diff subtracts other from self - * @param {ExponentialHistogramAccumulation} other - */ - diff(other) { - this._min = Infinity; - this._max = -Infinity; - this._sum -= other.sum; - this._count -= other.count; - this._zeroCount -= other.zeroCount; - const minScale = this._minScale(other); - this._downscale(this.scale - minScale); - this._diffBuckets(this.positive, other, other.positive, minScale); - this._diffBuckets(this.negative, other, other.negative, minScale); - } - /** - * clone returns a deep copy of self - * @returns {ExponentialHistogramAccumulation} - */ - clone() { - return new ExponentialHistogramAccumulation(this.startTime, this._maxSize, this._recordMinMax, this._sum, this._count, this._zeroCount, this._min, this._max, this.positive.clone(), this.negative.clone(), this._mapping); - } - /** - * _updateBuckets maps the incoming value to a bucket index for the current - * scale. If the bucket index is outside of the range of the backing array, - * it will rescale the backing array and update the mapping for the new scale. - */ - _updateBuckets(buckets, value, increment) { - let index = this._mapping.mapToIndex(value); - // rescale the mapping if needed - let rescalingNeeded = false; - let high = 0; - let low = 0; - if (buckets.length === 0) { - buckets.indexStart = index; - buckets.indexEnd = buckets.indexStart; - buckets.indexBase = buckets.indexStart; - } - else if (index < buckets.indexStart && - buckets.indexEnd - index >= this._maxSize) { - rescalingNeeded = true; - low = index; - high = buckets.indexEnd; - } - else if (index > buckets.indexEnd && - index - buckets.indexStart >= this._maxSize) { - rescalingNeeded = true; - low = buckets.indexStart; - high = index; - } - // rescale and compute index at new scale - if (rescalingNeeded) { - const change = this._changeScale(high, low); - this._downscale(change); - index = this._mapping.mapToIndex(value); - } - this._incrementIndexBy(buckets, index, increment); - } - /** - * _incrementIndexBy increments the count of the bucket specified by `index`. - * If the index is outside of the range [buckets.indexStart, buckets.indexEnd] - * the boundaries of the backing array will be adjusted and more buckets will - * be added if needed. - */ - _incrementIndexBy(buckets, index, increment) { - if (increment === 0) { - // nothing to do for a zero increment, can happen during a merge operation - return; - } - if (buckets.length === 0) { - buckets.indexStart = buckets.indexEnd = buckets.indexBase = index; - } - if (index < buckets.indexStart) { - const span = buckets.indexEnd - index; - if (span >= buckets.backing.length) { - this._grow(buckets, span + 1); - } - buckets.indexStart = index; - } - else if (index > buckets.indexEnd) { - const span = index - buckets.indexStart; - if (span >= buckets.backing.length) { - this._grow(buckets, span + 1); - } - buckets.indexEnd = index; - } - let bucketIndex = index - buckets.indexBase; - if (bucketIndex < 0) { - bucketIndex += buckets.backing.length; - } - buckets.incrementBucket(bucketIndex, increment); - } - /** - * grow resizes the backing array by doubling in size up to maxSize. - * This extends the array with a bunch of zeros and copies the - * existing counts to the same position. - */ - _grow(buckets, needed) { - const size = buckets.backing.length; - const bias = buckets.indexBase - buckets.indexStart; - const oldPositiveLimit = size - bias; - let newSize = (0, util_1.nextGreaterSquare)(needed); - if (newSize > this._maxSize) { - newSize = this._maxSize; - } - const newPositiveLimit = newSize - bias; - buckets.backing.growTo(newSize, oldPositiveLimit, newPositiveLimit); - } - /** - * _changeScale computes how much downscaling is needed by shifting the - * high and low values until they are separated by no more than size. - */ - _changeScale(high, low) { - let change = 0; - while (high - low >= this._maxSize) { - high >>= 1; - low >>= 1; - change++; - } - return change; - } - /** - * _downscale subtracts `change` from the current mapping scale. - */ - _downscale(change) { - if (change === 0) { - return; - } - if (change < 0) { - // Note: this should be impossible. If we get here it's because - // there is a bug in the implementation. - throw new Error(`impossible change of scale: ${this.scale}`); - } - const newScale = this._mapping.scale - change; - this._positive.downscale(change); - this._negative.downscale(change); - this._mapping = (0, getMapping_1.getMapping)(newScale); - } - /** - * _minScale is used by diff and merge to compute an ideal combined scale - */ - _minScale(other) { - const minScale = Math.min(this.scale, other.scale); - const highLowPos = HighLow.combine(this._highLowAtScale(this.positive, this.scale, minScale), this._highLowAtScale(other.positive, other.scale, minScale)); - const highLowNeg = HighLow.combine(this._highLowAtScale(this.negative, this.scale, minScale), this._highLowAtScale(other.negative, other.scale, minScale)); - return Math.min(minScale - this._changeScale(highLowPos.high, highLowPos.low), minScale - this._changeScale(highLowNeg.high, highLowNeg.low)); - } - /** - * _highLowAtScale is used by diff and merge to compute an ideal combined scale. - */ - _highLowAtScale(buckets, currentScale, newScale) { - if (buckets.length === 0) { - return new HighLow(0, -1); - } - const shift = currentScale - newScale; - return new HighLow(buckets.indexStart >> shift, buckets.indexEnd >> shift); - } - /** - * _mergeBuckets translates index values from another histogram and - * adds the values into the corresponding buckets of this histogram. - */ - _mergeBuckets(ours, other, theirs, scale) { - const theirOffset = theirs.offset; - const theirChange = other.scale - scale; - for (let i = 0; i < theirs.length; i++) { - this._incrementIndexBy(ours, (theirOffset + i) >> theirChange, theirs.at(i)); - } - } - /** - * _diffBuckets translates index values from another histogram and - * subtracts the values in the corresponding buckets of this histogram. - */ - _diffBuckets(ours, other, theirs, scale) { - const theirOffset = theirs.offset; - const theirChange = other.scale - scale; - for (let i = 0; i < theirs.length; i++) { - const ourIndex = (theirOffset + i) >> theirChange; - let bucketIndex = ourIndex - ours.indexBase; - if (bucketIndex < 0) { - bucketIndex += ours.backing.length; - } - ours.decrementBucket(bucketIndex, theirs.at(i)); - } - ours.trim(); - } -} -exports.ExponentialHistogramAccumulation = ExponentialHistogramAccumulation; -/** - * Aggregator for ExponentialHistogramAccumulations - */ -class ExponentialHistogramAggregator { - _maxSize; - _recordMinMax; - kind = types_1.AggregatorKind.EXPONENTIAL_HISTOGRAM; - /** - * @param _maxSize Maximum number of buckets for each of the positive - * and negative ranges, exclusive of the zero-bucket. - * @param _recordMinMax If set to true, min and max will be recorded. - * Otherwise, min and max will not be recorded. - */ - constructor(_maxSize, _recordMinMax) { - this._maxSize = _maxSize; - this._recordMinMax = _recordMinMax; - } - createAccumulation(startTime) { - return new ExponentialHistogramAccumulation(startTime, this._maxSize, this._recordMinMax); - } - /** - * Return the result of the merge of two exponential histogram accumulations. - */ - merge(previous, delta) { - const result = delta.clone(); - result.merge(previous); - return result; - } - /** - * Returns a new DELTA aggregation by comparing two cumulative measurements. - */ - diff(previous, current) { - const result = current.clone(); - result.diff(previous); - return result; - } - toMetricData(descriptor, aggregationTemporality, accumulationByAttributes, endTime) { - return { - descriptor, - aggregationTemporality, - dataPointType: MetricData_1.DataPointType.EXPONENTIAL_HISTOGRAM, - dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => { - const pointValue = accumulation.toPointValue(); - // determine if instrument allows negative values. - const allowsNegativeValues = descriptor.type === MetricData_1.InstrumentType.GAUGE || - descriptor.type === MetricData_1.InstrumentType.UP_DOWN_COUNTER || - descriptor.type === MetricData_1.InstrumentType.OBSERVABLE_GAUGE || - descriptor.type === MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER; - return { - attributes, - startTime: accumulation.startTime, - endTime, - value: { - min: pointValue.hasMinMax ? pointValue.min : undefined, - max: pointValue.hasMinMax ? pointValue.max : undefined, - sum: !allowsNegativeValues ? pointValue.sum : undefined, - positive: { - offset: pointValue.positive.offset, - bucketCounts: pointValue.positive.bucketCounts, - }, - negative: { - offset: pointValue.negative.offset, - bucketCounts: pointValue.negative.bucketCounts, - }, - count: pointValue.count, - scale: pointValue.scale, - zeroCount: pointValue.zeroCount, - }, - }; - }), - }; - } -} -exports.ExponentialHistogramAggregator = ExponentialHistogramAggregator; -//# sourceMappingURL=ExponentialHistogram.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Histogram.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Histogram.js deleted file mode 100644 index 250a2b95..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Histogram.js +++ /dev/null @@ -1,187 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.HistogramAggregator = exports.HistogramAccumulation = void 0; -const types_1 = require("./types"); -const MetricData_1 = require("../export/MetricData"); -const utils_1 = require("../utils"); -function createNewEmptyCheckpoint(boundaries) { - const counts = boundaries.map(() => 0); - counts.push(0); - return { - buckets: { - boundaries, - counts, - }, - sum: 0, - count: 0, - hasMinMax: false, - min: Infinity, - max: -Infinity, - }; -} -class HistogramAccumulation { - startTime; - _boundaries; - _recordMinMax; - _current; - constructor(startTime, _boundaries, _recordMinMax = true, _current = createNewEmptyCheckpoint(_boundaries)) { - this.startTime = startTime; - this._boundaries = _boundaries; - this._recordMinMax = _recordMinMax; - this._current = _current; - } - record(value) { - // NaN does not fall into any bucket, is not zero and should not be counted, - // NaN is never greater than max nor less than min, therefore return as there's nothing for us to do. - if (Number.isNaN(value)) { - return; - } - this._current.count += 1; - this._current.sum += value; - if (this._recordMinMax) { - this._current.min = Math.min(value, this._current.min); - this._current.max = Math.max(value, this._current.max); - this._current.hasMinMax = true; - } - const idx = (0, utils_1.binarySearchUB)(this._boundaries, value); - this._current.buckets.counts[idx] += 1; - } - setStartTime(startTime) { - this.startTime = startTime; - } - toPointValue() { - return this._current; - } -} -exports.HistogramAccumulation = HistogramAccumulation; -/** - * Basic aggregator which observes events and counts them in pre-defined buckets - * and provides the total sum and count of all observations. - */ -class HistogramAggregator { - _boundaries; - _recordMinMax; - kind = types_1.AggregatorKind.HISTOGRAM; - /** - * @param _boundaries sorted upper bounds of recorded values. - * @param _recordMinMax If set to true, min and max will be recorded. Otherwise, min and max will not be recorded. - */ - constructor(_boundaries, _recordMinMax) { - this._boundaries = _boundaries; - this._recordMinMax = _recordMinMax; - } - createAccumulation(startTime) { - return new HistogramAccumulation(startTime, this._boundaries, this._recordMinMax); - } - /** - * Return the result of the merge of two histogram accumulations. As long as one Aggregator - * instance produces all Accumulations with constant boundaries we don't need to worry about - * merging accumulations with different boundaries. - */ - merge(previous, delta) { - const previousValue = previous.toPointValue(); - const deltaValue = delta.toPointValue(); - const previousCounts = previousValue.buckets.counts; - const deltaCounts = deltaValue.buckets.counts; - const mergedCounts = new Array(previousCounts.length); - for (let idx = 0; idx < previousCounts.length; idx++) { - mergedCounts[idx] = previousCounts[idx] + deltaCounts[idx]; - } - let min = Infinity; - let max = -Infinity; - if (this._recordMinMax) { - if (previousValue.hasMinMax && deltaValue.hasMinMax) { - min = Math.min(previousValue.min, deltaValue.min); - max = Math.max(previousValue.max, deltaValue.max); - } - else if (previousValue.hasMinMax) { - min = previousValue.min; - max = previousValue.max; - } - else if (deltaValue.hasMinMax) { - min = deltaValue.min; - max = deltaValue.max; - } - } - return new HistogramAccumulation(previous.startTime, previousValue.buckets.boundaries, this._recordMinMax, { - buckets: { - boundaries: previousValue.buckets.boundaries, - counts: mergedCounts, - }, - count: previousValue.count + deltaValue.count, - sum: previousValue.sum + deltaValue.sum, - hasMinMax: this._recordMinMax && - (previousValue.hasMinMax || deltaValue.hasMinMax), - min: min, - max: max, - }); - } - /** - * Returns a new DELTA aggregation by comparing two cumulative measurements. - */ - diff(previous, current) { - const previousValue = previous.toPointValue(); - const currentValue = current.toPointValue(); - const previousCounts = previousValue.buckets.counts; - const currentCounts = currentValue.buckets.counts; - const diffedCounts = new Array(previousCounts.length); - for (let idx = 0; idx < previousCounts.length; idx++) { - diffedCounts[idx] = currentCounts[idx] - previousCounts[idx]; - } - return new HistogramAccumulation(current.startTime, previousValue.buckets.boundaries, this._recordMinMax, { - buckets: { - boundaries: previousValue.buckets.boundaries, - counts: diffedCounts, - }, - count: currentValue.count - previousValue.count, - sum: currentValue.sum - previousValue.sum, - hasMinMax: false, - min: Infinity, - max: -Infinity, - }); - } - toMetricData(descriptor, aggregationTemporality, accumulationByAttributes, endTime) { - return { - descriptor, - aggregationTemporality, - dataPointType: MetricData_1.DataPointType.HISTOGRAM, - dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => { - const pointValue = accumulation.toPointValue(); - // determine if instrument allows negative values. - const allowsNegativeValues = descriptor.type === MetricData_1.InstrumentType.GAUGE || - descriptor.type === MetricData_1.InstrumentType.UP_DOWN_COUNTER || - descriptor.type === MetricData_1.InstrumentType.OBSERVABLE_GAUGE || - descriptor.type === MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER; - return { - attributes, - startTime: accumulation.startTime, - endTime, - value: { - min: pointValue.hasMinMax ? pointValue.min : undefined, - max: pointValue.hasMinMax ? pointValue.max : undefined, - sum: !allowsNegativeValues ? pointValue.sum : undefined, - buckets: pointValue.buckets, - count: pointValue.count, - }, - }; - }), - }; - } -} -exports.HistogramAggregator = HistogramAggregator; -//# sourceMappingURL=Histogram.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/LastValue.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/LastValue.js deleted file mode 100644 index 00e945c7..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/LastValue.js +++ /dev/null @@ -1,93 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.LastValueAggregator = exports.LastValueAccumulation = void 0; -const types_1 = require("./types"); -const core_1 = require("@opentelemetry/core"); -const MetricData_1 = require("../export/MetricData"); -class LastValueAccumulation { - startTime; - _current; - sampleTime; - constructor(startTime, _current = 0, sampleTime = [0, 0]) { - this.startTime = startTime; - this._current = _current; - this.sampleTime = sampleTime; - } - record(value) { - this._current = value; - this.sampleTime = (0, core_1.millisToHrTime)(Date.now()); - } - setStartTime(startTime) { - this.startTime = startTime; - } - toPointValue() { - return this._current; - } -} -exports.LastValueAccumulation = LastValueAccumulation; -/** Basic aggregator which calculates a LastValue from individual measurements. */ -class LastValueAggregator { - kind = types_1.AggregatorKind.LAST_VALUE; - createAccumulation(startTime) { - return new LastValueAccumulation(startTime); - } - /** - * Returns the result of the merge of the given accumulations. - * - * Return the newly captured (delta) accumulation for LastValueAggregator. - */ - merge(previous, delta) { - // nanoseconds may lose precisions. - const latestAccumulation = (0, core_1.hrTimeToMicroseconds)(delta.sampleTime) >= - (0, core_1.hrTimeToMicroseconds)(previous.sampleTime) - ? delta - : previous; - return new LastValueAccumulation(previous.startTime, latestAccumulation.toPointValue(), latestAccumulation.sampleTime); - } - /** - * Returns a new DELTA aggregation by comparing two cumulative measurements. - * - * A delta aggregation is not meaningful to LastValueAggregator, just return - * the newly captured (delta) accumulation for LastValueAggregator. - */ - diff(previous, current) { - // nanoseconds may lose precisions. - const latestAccumulation = (0, core_1.hrTimeToMicroseconds)(current.sampleTime) >= - (0, core_1.hrTimeToMicroseconds)(previous.sampleTime) - ? current - : previous; - return new LastValueAccumulation(current.startTime, latestAccumulation.toPointValue(), latestAccumulation.sampleTime); - } - toMetricData(descriptor, aggregationTemporality, accumulationByAttributes, endTime) { - return { - descriptor, - aggregationTemporality, - dataPointType: MetricData_1.DataPointType.GAUGE, - dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => { - return { - attributes, - startTime: accumulation.startTime, - endTime, - value: accumulation.toPointValue(), - }; - }), - }; - } -} -exports.LastValueAggregator = LastValueAggregator; -//# sourceMappingURL=LastValue.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Sum.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Sum.js deleted file mode 100644 index 9fdb343f..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/Sum.js +++ /dev/null @@ -1,101 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SumAggregator = exports.SumAccumulation = void 0; -const types_1 = require("./types"); -const MetricData_1 = require("../export/MetricData"); -class SumAccumulation { - startTime; - monotonic; - _current; - reset; - constructor(startTime, monotonic, _current = 0, reset = false) { - this.startTime = startTime; - this.monotonic = monotonic; - this._current = _current; - this.reset = reset; - } - record(value) { - if (this.monotonic && value < 0) { - return; - } - this._current += value; - } - setStartTime(startTime) { - this.startTime = startTime; - } - toPointValue() { - return this._current; - } -} -exports.SumAccumulation = SumAccumulation; -/** Basic aggregator which calculates a Sum from individual measurements. */ -class SumAggregator { - monotonic; - kind = types_1.AggregatorKind.SUM; - constructor(monotonic) { - this.monotonic = monotonic; - } - createAccumulation(startTime) { - return new SumAccumulation(startTime, this.monotonic); - } - /** - * Returns the result of the merge of the given accumulations. - */ - merge(previous, delta) { - const prevPv = previous.toPointValue(); - const deltaPv = delta.toPointValue(); - if (delta.reset) { - return new SumAccumulation(delta.startTime, this.monotonic, deltaPv, delta.reset); - } - return new SumAccumulation(previous.startTime, this.monotonic, prevPv + deltaPv); - } - /** - * Returns a new DELTA aggregation by comparing two cumulative measurements. - */ - diff(previous, current) { - const prevPv = previous.toPointValue(); - const currPv = current.toPointValue(); - /** - * If the SumAggregator is a monotonic one and the previous point value is - * greater than the current one, a reset is deemed to be happened. - * Return the current point value to prevent the value from been reset. - */ - if (this.monotonic && prevPv > currPv) { - return new SumAccumulation(current.startTime, this.monotonic, currPv, true); - } - return new SumAccumulation(current.startTime, this.monotonic, currPv - prevPv); - } - toMetricData(descriptor, aggregationTemporality, accumulationByAttributes, endTime) { - return { - descriptor, - aggregationTemporality, - dataPointType: MetricData_1.DataPointType.SUM, - dataPoints: accumulationByAttributes.map(([attributes, accumulation]) => { - return { - attributes, - startTime: accumulation.startTime, - endTime, - value: accumulation.toPointValue(), - }; - }), - isMonotonic: this.monotonic, - }; - } -} -exports.SumAggregator = SumAggregator; -//# sourceMappingURL=Sum.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/Buckets.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/Buckets.js deleted file mode 100644 index cf61e328..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/Buckets.js +++ /dev/null @@ -1,277 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Buckets = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -class Buckets { - backing; - indexBase; - indexStart; - indexEnd; - /** - * The term index refers to the number of the exponential histogram bucket - * used to determine its boundaries. The lower boundary of a bucket is - * determined by base ** index and the upper boundary of a bucket is - * determined by base ** (index + 1). index values are signed to account - * for values less than or equal to 1. - * - * indexBase is the index of the 0th position in the - * backing array, i.e., backing[0] is the count - * in the bucket with index `indexBase`. - * - * indexStart is the smallest index value represented - * in the backing array. - * - * indexEnd is the largest index value represented in - * the backing array. - */ - constructor(backing = new BucketsBacking(), indexBase = 0, indexStart = 0, indexEnd = 0) { - this.backing = backing; - this.indexBase = indexBase; - this.indexStart = indexStart; - this.indexEnd = indexEnd; - } - /** - * Offset is the bucket index of the smallest entry in the counts array - * @returns {number} - */ - get offset() { - return this.indexStart; - } - /** - * Buckets is a view into the backing array. - * @returns {number} - */ - get length() { - if (this.backing.length === 0) { - return 0; - } - if (this.indexEnd === this.indexStart && this.at(0) === 0) { - return 0; - } - return this.indexEnd - this.indexStart + 1; - } - /** - * An array of counts, where count[i] carries the count - * of the bucket at index (offset+i). count[i] is the count of - * values greater than base^(offset+i) and less than or equal to - * base^(offset+i+1). - * @returns {number} The logical counts based on the backing array - */ - counts() { - return Array.from({ length: this.length }, (_, i) => this.at(i)); - } - /** - * At returns the count of the bucket at a position in the logical - * array of counts. - * @param position - * @returns {number} - */ - at(position) { - const bias = this.indexBase - this.indexStart; - if (position < bias) { - position += this.backing.length; - } - position -= bias; - return this.backing.countAt(position); - } - /** - * incrementBucket increments the backing array index by `increment` - * @param bucketIndex - * @param increment - */ - incrementBucket(bucketIndex, increment) { - this.backing.increment(bucketIndex, increment); - } - /** - * decrementBucket decrements the backing array index by `decrement` - * if decrement is greater than the current value, it's set to 0. - * @param bucketIndex - * @param decrement - */ - decrementBucket(bucketIndex, decrement) { - this.backing.decrement(bucketIndex, decrement); - } - /** - * trim removes leading and / or trailing zero buckets (which can occur - * after diffing two histos) and rotates the backing array so that the - * smallest non-zero index is in the 0th position of the backing array - */ - trim() { - for (let i = 0; i < this.length; i++) { - if (this.at(i) !== 0) { - this.indexStart += i; - break; - } - else if (i === this.length - 1) { - //the entire array is zeroed out - this.indexStart = this.indexEnd = this.indexBase = 0; - return; - } - } - for (let i = this.length - 1; i >= 0; i--) { - if (this.at(i) !== 0) { - this.indexEnd -= this.length - i - 1; - break; - } - } - this._rotate(); - } - /** - * downscale first rotates, then collapses 2**`by`-to-1 buckets. - * @param by - */ - downscale(by) { - this._rotate(); - const size = 1 + this.indexEnd - this.indexStart; - const each = 1 << by; - let inpos = 0; - let outpos = 0; - for (let pos = this.indexStart; pos <= this.indexEnd;) { - let mod = pos % each; - if (mod < 0) { - mod += each; - } - for (let i = mod; i < each && inpos < size; i++) { - this._relocateBucket(outpos, inpos); - inpos++; - pos++; - } - outpos++; - } - this.indexStart >>= by; - this.indexEnd >>= by; - this.indexBase = this.indexStart; - } - /** - * Clone returns a deep copy of Buckets - * @returns {Buckets} - */ - clone() { - return new Buckets(this.backing.clone(), this.indexBase, this.indexStart, this.indexEnd); - } - /** - * _rotate shifts the backing array contents so that indexStart == - * indexBase to simplify the downscale logic. - */ - _rotate() { - const bias = this.indexBase - this.indexStart; - if (bias === 0) { - return; - } - else if (bias > 0) { - this.backing.reverse(0, this.backing.length); - this.backing.reverse(0, bias); - this.backing.reverse(bias, this.backing.length); - } - else { - // negative bias, this can happen when diffing two histograms - this.backing.reverse(0, this.backing.length); - this.backing.reverse(0, this.backing.length + bias); - } - this.indexBase = this.indexStart; - } - /** - * _relocateBucket adds the count in counts[src] to counts[dest] and - * resets count[src] to zero. - */ - _relocateBucket(dest, src) { - if (dest === src) { - return; - } - this.incrementBucket(dest, this.backing.emptyBucket(src)); - } -} -exports.Buckets = Buckets; -/** - * BucketsBacking holds the raw buckets and some utility methods to - * manage them. - */ -class BucketsBacking { - _counts; - constructor(_counts = [0]) { - this._counts = _counts; - } - /** - * length returns the physical size of the backing array, which - * is >= buckets.length() - */ - get length() { - return this._counts.length; - } - /** - * countAt returns the count in a specific bucket - */ - countAt(pos) { - return this._counts[pos]; - } - /** - * growTo grows a backing array and copies old entries - * into their correct new positions. - */ - growTo(newSize, oldPositiveLimit, newPositiveLimit) { - const tmp = new Array(newSize).fill(0); - tmp.splice(newPositiveLimit, this._counts.length - oldPositiveLimit, ...this._counts.slice(oldPositiveLimit)); - tmp.splice(0, oldPositiveLimit, ...this._counts.slice(0, oldPositiveLimit)); - this._counts = tmp; - } - /** - * reverse the items in the backing array in the range [from, limit). - */ - reverse(from, limit) { - const num = Math.floor((from + limit) / 2) - from; - for (let i = 0; i < num; i++) { - const tmp = this._counts[from + i]; - this._counts[from + i] = this._counts[limit - i - 1]; - this._counts[limit - i - 1] = tmp; - } - } - /** - * emptyBucket empties the count from a bucket, for - * moving into another. - */ - emptyBucket(src) { - const tmp = this._counts[src]; - this._counts[src] = 0; - return tmp; - } - /** - * increments a bucket by `increment` - */ - increment(bucketIndex, increment) { - this._counts[bucketIndex] += increment; - } - /** - * decrements a bucket by `decrement` - */ - decrement(bucketIndex, decrement) { - if (this._counts[bucketIndex] >= decrement) { - this._counts[bucketIndex] -= decrement; - } - else { - // this should not happen, but we're being defensive against - // negative counts. - this._counts[bucketIndex] = 0; - } - } - /** - * clone returns a deep copy of BucketsBacking - */ - clone() { - return new BucketsBacking([...this._counts]); - } -} -//# sourceMappingURL=Buckets.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ExponentMapping.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ExponentMapping.js deleted file mode 100644 index 7ce881f0..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ExponentMapping.js +++ /dev/null @@ -1,90 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ExponentMapping = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const ieee754 = require("./ieee754"); -const util = require("../util"); -const types_1 = require("./types"); -/** - * ExponentMapping implements exponential mapping functions for - * scales <=0. For scales > 0 LogarithmMapping should be used. - */ -class ExponentMapping { - _shift; - constructor(scale) { - this._shift = -scale; - } - /** - * Maps positive floating point values to indexes corresponding to scale - * @param value - * @returns {number} index for provided value at the current scale - */ - mapToIndex(value) { - if (value < ieee754.MIN_VALUE) { - return this._minNormalLowerBoundaryIndex(); - } - const exp = ieee754.getNormalBase2(value); - // In case the value is an exact power of two, compute a - // correction of -1. Note, we are using a custom _rightShift - // to accommodate a 52-bit argument, which the native bitwise - // operators do not support - const correction = this._rightShift(ieee754.getSignificand(value) - 1, ieee754.SIGNIFICAND_WIDTH); - return (exp + correction) >> this._shift; - } - /** - * Returns the lower bucket boundary for the given index for scale - * - * @param index - * @returns {number} - */ - lowerBoundary(index) { - const minIndex = this._minNormalLowerBoundaryIndex(); - if (index < minIndex) { - throw new types_1.MappingError(`underflow: ${index} is < minimum lower boundary: ${minIndex}`); - } - const maxIndex = this._maxNormalLowerBoundaryIndex(); - if (index > maxIndex) { - throw new types_1.MappingError(`overflow: ${index} is > maximum lower boundary: ${maxIndex}`); - } - return util.ldexp(1, index << this._shift); - } - /** - * The scale used by this mapping - * @returns {number} - */ - get scale() { - if (this._shift === 0) { - return 0; - } - return -this._shift; - } - _minNormalLowerBoundaryIndex() { - let index = ieee754.MIN_NORMAL_EXPONENT >> this._shift; - if (this._shift < 2) { - index--; - } - return index; - } - _maxNormalLowerBoundaryIndex() { - return ieee754.MAX_NORMAL_EXPONENT >> this._shift; - } - _rightShift(value, shift) { - return Math.floor(value * Math.pow(2, -shift)); - } -} -exports.ExponentMapping = ExponentMapping; -//# sourceMappingURL=ExponentMapping.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/LogarithmMapping.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/LogarithmMapping.js deleted file mode 100644 index 0ce364a9..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/LogarithmMapping.js +++ /dev/null @@ -1,98 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.LogarithmMapping = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const ieee754 = require("./ieee754"); -const util = require("../util"); -const types_1 = require("./types"); -/** - * LogarithmMapping implements exponential mapping functions for scale > 0. - * For scales <= 0 the exponent mapping should be used. - */ -class LogarithmMapping { - _scale; - _scaleFactor; - _inverseFactor; - constructor(scale) { - this._scale = scale; - this._scaleFactor = util.ldexp(Math.LOG2E, scale); - this._inverseFactor = util.ldexp(Math.LN2, -scale); - } - /** - * Maps positive floating point values to indexes corresponding to scale - * @param value - * @returns {number} index for provided value at the current scale - */ - mapToIndex(value) { - if (value <= ieee754.MIN_VALUE) { - return this._minNormalLowerBoundaryIndex() - 1; - } - // exact power of two special case - if (ieee754.getSignificand(value) === 0) { - const exp = ieee754.getNormalBase2(value); - return (exp << this._scale) - 1; - } - // non-power of two cases. use Math.floor to round the scaled logarithm - const index = Math.floor(Math.log(value) * this._scaleFactor); - const maxIndex = this._maxNormalLowerBoundaryIndex(); - if (index >= maxIndex) { - return maxIndex; - } - return index; - } - /** - * Returns the lower bucket boundary for the given index for scale - * - * @param index - * @returns {number} - */ - lowerBoundary(index) { - const maxIndex = this._maxNormalLowerBoundaryIndex(); - if (index >= maxIndex) { - if (index === maxIndex) { - return 2 * Math.exp((index - (1 << this._scale)) / this._scaleFactor); - } - throw new types_1.MappingError(`overflow: ${index} is > maximum lower boundary: ${maxIndex}`); - } - const minIndex = this._minNormalLowerBoundaryIndex(); - if (index <= minIndex) { - if (index === minIndex) { - return ieee754.MIN_VALUE; - } - else if (index === minIndex - 1) { - return Math.exp((index + (1 << this._scale)) / this._scaleFactor) / 2; - } - throw new types_1.MappingError(`overflow: ${index} is < minimum lower boundary: ${minIndex}`); - } - return Math.exp(index * this._inverseFactor); - } - /** - * The scale used by this mapping - * @returns {number} - */ - get scale() { - return this._scale; - } - _minNormalLowerBoundaryIndex() { - return ieee754.MIN_NORMAL_EXPONENT << this._scale; - } - _maxNormalLowerBoundaryIndex() { - return ((ieee754.MAX_NORMAL_EXPONENT + 1) << this._scale) - 1; - } -} -exports.LogarithmMapping = LogarithmMapping; -//# sourceMappingURL=LogarithmMapping.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/getMapping.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/getMapping.js deleted file mode 100644 index 5ba88f3a..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/getMapping.js +++ /dev/null @@ -1,45 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getMapping = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const ExponentMapping_1 = require("./ExponentMapping"); -const LogarithmMapping_1 = require("./LogarithmMapping"); -const types_1 = require("./types"); -const MIN_SCALE = -10; -const MAX_SCALE = 20; -const PREBUILT_MAPPINGS = Array.from({ length: 31 }, (_, i) => { - if (i > 10) { - return new LogarithmMapping_1.LogarithmMapping(i - 10); - } - return new ExponentMapping_1.ExponentMapping(i - 10); -}); -/** - * getMapping returns an appropriate mapping for the given scale. For scales -10 - * to 0 the underlying type will be ExponentMapping. For scales 1 to 20 the - * underlying type will be LogarithmMapping. - * @param scale a number in the range [-10, 20] - * @returns {Mapping} - */ -function getMapping(scale) { - if (scale > MAX_SCALE || scale < MIN_SCALE) { - throw new types_1.MappingError(`expected scale >= ${MIN_SCALE} && <= ${MAX_SCALE}, got: ${scale}`); - } - // mappings are offset by 10. scale -10 is at position 0 and scale 20 is at 30 - return PREBUILT_MAPPINGS[scale + 10]; -} -exports.getMapping = getMapping; -//# sourceMappingURL=getMapping.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ieee754.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ieee754.js deleted file mode 100644 index f5323182..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/ieee754.js +++ /dev/null @@ -1,94 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getSignificand = exports.getNormalBase2 = exports.MIN_VALUE = exports.MAX_NORMAL_EXPONENT = exports.MIN_NORMAL_EXPONENT = exports.SIGNIFICAND_WIDTH = void 0; -/** - * The functions and constants in this file allow us to interact - * with the internal representation of an IEEE 64-bit floating point - * number. We need to work with all 64-bits, thus, care needs to be - * taken when working with Javascript's bitwise operators (<<, >>, &, - * |, etc) as they truncate operands to 32-bits. In order to work around - * this we work with the 64-bits as two 32-bit halves, perform bitwise - * operations on them independently, and combine the results (if needed). - */ -exports.SIGNIFICAND_WIDTH = 52; -/** - * EXPONENT_MASK is set to 1 for the hi 32-bits of an IEEE 754 - * floating point exponent: 0x7ff00000. - */ -const EXPONENT_MASK = 0x7ff00000; -/** - * SIGNIFICAND_MASK is the mask for the significand portion of the hi 32-bits - * of an IEEE 754 double-precision floating-point value: 0xfffff - */ -const SIGNIFICAND_MASK = 0xfffff; -/** - * EXPONENT_BIAS is the exponent bias specified for encoding - * the IEEE 754 double-precision floating point exponent: 1023 - */ -const EXPONENT_BIAS = 1023; -/** - * MIN_NORMAL_EXPONENT is the minimum exponent of a normalized - * floating point: -1022. - */ -exports.MIN_NORMAL_EXPONENT = -EXPONENT_BIAS + 1; -/** - * MAX_NORMAL_EXPONENT is the maximum exponent of a normalized - * floating point: 1023. - */ -exports.MAX_NORMAL_EXPONENT = EXPONENT_BIAS; -/** - * MIN_VALUE is the smallest normal number - */ -exports.MIN_VALUE = Math.pow(2, -1022); -/** - * getNormalBase2 extracts the normalized base-2 fractional exponent. - * This returns k for the equation f x 2**k where f is - * in the range [1, 2). Note that this function is not called for - * subnormal numbers. - * @param {number} value - the value to determine normalized base-2 fractional - * exponent for - * @returns {number} the normalized base-2 exponent - */ -function getNormalBase2(value) { - const dv = new DataView(new ArrayBuffer(8)); - dv.setFloat64(0, value); - // access the raw 64-bit float as 32-bit uints - const hiBits = dv.getUint32(0); - const expBits = (hiBits & EXPONENT_MASK) >> 20; - return expBits - EXPONENT_BIAS; -} -exports.getNormalBase2 = getNormalBase2; -/** - * GetSignificand returns the 52 bit (unsigned) significand as a signed value. - * @param {number} value - the floating point number to extract the significand from - * @returns {number} The 52-bit significand - */ -function getSignificand(value) { - const dv = new DataView(new ArrayBuffer(8)); - dv.setFloat64(0, value); - // access the raw 64-bit float as two 32-bit uints - const hiBits = dv.getUint32(0); - const loBits = dv.getUint32(4); - // extract the significand bits from the hi bits and left shift 32 places note: - // we can't use the native << operator as it will truncate the result to 32-bits - const significandHiBits = (hiBits & SIGNIFICAND_MASK) * Math.pow(2, 32); - // combine the hi and lo bits and return - return significandHiBits + loBits; -} -exports.getSignificand = getSignificand; -//# sourceMappingURL=ieee754.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/types.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/types.js deleted file mode 100644 index 49602b80..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/mapping/types.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MappingError = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -class MappingError extends Error { -} -exports.MappingError = MappingError; -//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/util.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/util.js deleted file mode 100644 index 1c1734d3..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/exponential-histogram/util.js +++ /dev/null @@ -1,63 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.nextGreaterSquare = exports.ldexp = void 0; -/** - * Note: other languages provide this as a built in function. This is - * a naive, but functionally correct implementation. This is used sparingly, - * when creating a new mapping in a running application. - * - * ldexp returns frac × 2**exp. With the following special cases: - * ldexp(±0, exp) = ±0 - * ldexp(±Inf, exp) = ±Inf - * ldexp(NaN, exp) = NaN - * @param frac - * @param exp - * @returns {number} - */ -function ldexp(frac, exp) { - if (frac === 0 || - frac === Number.POSITIVE_INFINITY || - frac === Number.NEGATIVE_INFINITY || - Number.isNaN(frac)) { - return frac; - } - return frac * Math.pow(2, exp); -} -exports.ldexp = ldexp; -/** - * Computes the next power of two that is greater than or equal to v. - * This implementation more efficient than, but functionally equivalent - * to Math.pow(2, Math.ceil(Math.log(x)/Math.log(2))). - * @param v - * @returns {number} - */ -function nextGreaterSquare(v) { - // The following expression computes the least power-of-two - // that is >= v. There are a number of tricky ways to - // do this, see https://stackoverflow.com/questions/466204/rounding-up-to-next-power-of-2 - v--; - v |= v >> 1; - v |= v >> 2; - v |= v >> 4; - v |= v >> 8; - v |= v >> 16; - v++; - return v; -} -exports.nextGreaterSquare = nextGreaterSquare; -//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/index.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/index.js deleted file mode 100644 index ba6195bc..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/index.js +++ /dev/null @@ -1,33 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SumAggregator = exports.SumAccumulation = exports.LastValueAggregator = exports.LastValueAccumulation = exports.ExponentialHistogramAggregator = exports.ExponentialHistogramAccumulation = exports.HistogramAggregator = exports.HistogramAccumulation = exports.DropAggregator = void 0; -var Drop_1 = require("./Drop"); -Object.defineProperty(exports, "DropAggregator", { enumerable: true, get: function () { return Drop_1.DropAggregator; } }); -var Histogram_1 = require("./Histogram"); -Object.defineProperty(exports, "HistogramAccumulation", { enumerable: true, get: function () { return Histogram_1.HistogramAccumulation; } }); -Object.defineProperty(exports, "HistogramAggregator", { enumerable: true, get: function () { return Histogram_1.HistogramAggregator; } }); -var ExponentialHistogram_1 = require("./ExponentialHistogram"); -Object.defineProperty(exports, "ExponentialHistogramAccumulation", { enumerable: true, get: function () { return ExponentialHistogram_1.ExponentialHistogramAccumulation; } }); -Object.defineProperty(exports, "ExponentialHistogramAggregator", { enumerable: true, get: function () { return ExponentialHistogram_1.ExponentialHistogramAggregator; } }); -var LastValue_1 = require("./LastValue"); -Object.defineProperty(exports, "LastValueAccumulation", { enumerable: true, get: function () { return LastValue_1.LastValueAccumulation; } }); -Object.defineProperty(exports, "LastValueAggregator", { enumerable: true, get: function () { return LastValue_1.LastValueAggregator; } }); -var Sum_1 = require("./Sum"); -Object.defineProperty(exports, "SumAccumulation", { enumerable: true, get: function () { return Sum_1.SumAccumulation; } }); -Object.defineProperty(exports, "SumAggregator", { enumerable: true, get: function () { return Sum_1.SumAggregator; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/types.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/types.js deleted file mode 100644 index 5f62e885..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/aggregator/types.js +++ /dev/null @@ -1,28 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AggregatorKind = void 0; -/** The kind of aggregator. */ -var AggregatorKind; -(function (AggregatorKind) { - AggregatorKind[AggregatorKind["DROP"] = 0] = "DROP"; - AggregatorKind[AggregatorKind["SUM"] = 1] = "SUM"; - AggregatorKind[AggregatorKind["LAST_VALUE"] = 2] = "LAST_VALUE"; - AggregatorKind[AggregatorKind["HISTOGRAM"] = 3] = "HISTOGRAM"; - AggregatorKind[AggregatorKind["EXPONENTIAL_HISTOGRAM"] = 4] = "EXPONENTIAL_HISTOGRAM"; -})(AggregatorKind = exports.AggregatorKind || (exports.AggregatorKind = {})); -//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationSelector.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationSelector.js deleted file mode 100644 index 6564b194..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationSelector.js +++ /dev/null @@ -1,29 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = exports.DEFAULT_AGGREGATION_SELECTOR = void 0; -const AggregationTemporality_1 = require("./AggregationTemporality"); -const AggregationOption_1 = require("../view/AggregationOption"); -const DEFAULT_AGGREGATION_SELECTOR = _instrumentType => { - return { - type: AggregationOption_1.AggregationType.DEFAULT, - }; -}; -exports.DEFAULT_AGGREGATION_SELECTOR = DEFAULT_AGGREGATION_SELECTOR; -const DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = _instrumentType => AggregationTemporality_1.AggregationTemporality.CUMULATIVE; -exports.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR = DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR; -//# sourceMappingURL=AggregationSelector.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationTemporality.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationTemporality.js deleted file mode 100644 index e2334706..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/AggregationTemporality.js +++ /dev/null @@ -1,27 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AggregationTemporality = void 0; -/** - * AggregationTemporality indicates the way additive quantities are expressed. - */ -var AggregationTemporality; -(function (AggregationTemporality) { - AggregationTemporality[AggregationTemporality["DELTA"] = 0] = "DELTA"; - AggregationTemporality[AggregationTemporality["CUMULATIVE"] = 1] = "CUMULATIVE"; -})(AggregationTemporality = exports.AggregationTemporality || (exports.AggregationTemporality = {})); -//# sourceMappingURL=AggregationTemporality.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/ConsoleMetricExporter.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/ConsoleMetricExporter.js deleted file mode 100644 index 04933858..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/ConsoleMetricExporter.js +++ /dev/null @@ -1,67 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConsoleMetricExporter = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const core_1 = require("@opentelemetry/core"); -const AggregationSelector_1 = require("./AggregationSelector"); -/** - * This is an implementation of {@link PushMetricExporter} that prints metrics to the - * console. This class can be used for diagnostic purposes. - * - * NOTE: This {@link PushMetricExporter} is intended for diagnostics use only, output rendered to the console may change at any time. - */ -/* eslint-disable no-console */ -class ConsoleMetricExporter { - _shutdown = false; - _temporalitySelector; - constructor(options) { - this._temporalitySelector = - options?.temporalitySelector ?? AggregationSelector_1.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR; - } - export(metrics, resultCallback) { - if (this._shutdown) { - // If the exporter is shutting down, by spec, we need to return FAILED as export result - setImmediate(resultCallback, { code: core_1.ExportResultCode.FAILED }); - return; - } - return ConsoleMetricExporter._sendMetrics(metrics, resultCallback); - } - forceFlush() { - return Promise.resolve(); - } - selectAggregationTemporality(_instrumentType) { - return this._temporalitySelector(_instrumentType); - } - shutdown() { - this._shutdown = true; - return Promise.resolve(); - } - static _sendMetrics(metrics, done) { - for (const scopeMetrics of metrics.scopeMetrics) { - for (const metric of scopeMetrics.metrics) { - console.dir({ - descriptor: metric.descriptor, - dataPointType: metric.dataPointType, - dataPoints: metric.dataPoints, - }, { depth: null }); - } - } - done({ code: core_1.ExportResultCode.SUCCESS }); - } -} -exports.ConsoleMetricExporter = ConsoleMetricExporter; -//# sourceMappingURL=ConsoleMetricExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/InMemoryMetricExporter.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/InMemoryMetricExporter.js deleted file mode 100644 index 6033484b..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/InMemoryMetricExporter.js +++ /dev/null @@ -1,66 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.InMemoryMetricExporter = void 0; -const core_1 = require("@opentelemetry/core"); -/** - * In-memory Metrics Exporter is a Push Metric Exporter - * which accumulates metrics data in the local memory and - * allows to inspect it (useful for e.g. unit tests). - */ -class InMemoryMetricExporter { - _shutdown = false; - _aggregationTemporality; - _metrics = []; - constructor(aggregationTemporality) { - this._aggregationTemporality = aggregationTemporality; - } - /** - * @inheritedDoc - */ - export(metrics, resultCallback) { - // Avoid storing metrics when exporter is shutdown - if (this._shutdown) { - setTimeout(() => resultCallback({ code: core_1.ExportResultCode.FAILED }), 0); - return; - } - this._metrics.push(metrics); - setTimeout(() => resultCallback({ code: core_1.ExportResultCode.SUCCESS }), 0); - } - /** - * Returns all the collected resource metrics - * @returns ResourceMetrics[] - */ - getMetrics() { - return this._metrics; - } - forceFlush() { - return Promise.resolve(); - } - reset() { - this._metrics = []; - } - selectAggregationTemporality(_instrumentType) { - return this._aggregationTemporality; - } - shutdown() { - this._shutdown = true; - return Promise.resolve(); - } -} -exports.InMemoryMetricExporter = InMemoryMetricExporter; -//# sourceMappingURL=InMemoryMetricExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricData.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricData.js deleted file mode 100644 index 576dbf0f..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricData.js +++ /dev/null @@ -1,60 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DataPointType = exports.InstrumentType = void 0; -/** - * Supported types of metric instruments. - */ -var InstrumentType; -(function (InstrumentType) { - InstrumentType["COUNTER"] = "COUNTER"; - InstrumentType["GAUGE"] = "GAUGE"; - InstrumentType["HISTOGRAM"] = "HISTOGRAM"; - InstrumentType["UP_DOWN_COUNTER"] = "UP_DOWN_COUNTER"; - InstrumentType["OBSERVABLE_COUNTER"] = "OBSERVABLE_COUNTER"; - InstrumentType["OBSERVABLE_GAUGE"] = "OBSERVABLE_GAUGE"; - InstrumentType["OBSERVABLE_UP_DOWN_COUNTER"] = "OBSERVABLE_UP_DOWN_COUNTER"; -})(InstrumentType = exports.InstrumentType || (exports.InstrumentType = {})); -/** - * The aggregated point data type. - */ -var DataPointType; -(function (DataPointType) { - /** - * A histogram data point contains a histogram statistics of collected - * values with a list of explicit bucket boundaries and statistics such - * as min, max, count, and sum of all collected values. - */ - DataPointType[DataPointType["HISTOGRAM"] = 0] = "HISTOGRAM"; - /** - * An exponential histogram data point contains a histogram statistics of - * collected values where bucket boundaries are automatically calculated - * using an exponential function, and statistics such as min, max, count, - * and sum of all collected values. - */ - DataPointType[DataPointType["EXPONENTIAL_HISTOGRAM"] = 1] = "EXPONENTIAL_HISTOGRAM"; - /** - * A gauge metric data point has only a single numeric value. - */ - DataPointType[DataPointType["GAUGE"] = 2] = "GAUGE"; - /** - * A sum metric data point has a single numeric value and a - * monotonicity-indicator. - */ - DataPointType[DataPointType["SUM"] = 3] = "SUM"; -})(DataPointType = exports.DataPointType || (exports.DataPointType = {})); -//# sourceMappingURL=MetricData.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricReader.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricReader.js deleted file mode 100644 index 5417d584..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/MetricReader.js +++ /dev/null @@ -1,128 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MetricReader = void 0; -const api = require("@opentelemetry/api"); -const utils_1 = require("../utils"); -const AggregationSelector_1 = require("./AggregationSelector"); -/** - * A registered reader of metrics that, when linked to a {@link MetricProducer}, offers global - * control over metrics. - */ -class MetricReader { - // Tracks the shutdown state. - // TODO: use BindOncePromise here once a new version of @opentelemetry/core is available. - _shutdown = false; - // Additional MetricProducers which will be combined with the SDK's output - _metricProducers; - // MetricProducer used by this instance which produces metrics from the SDK - _sdkMetricProducer; - _aggregationTemporalitySelector; - _aggregationSelector; - _cardinalitySelector; - constructor(options) { - this._aggregationSelector = - options?.aggregationSelector ?? AggregationSelector_1.DEFAULT_AGGREGATION_SELECTOR; - this._aggregationTemporalitySelector = - options?.aggregationTemporalitySelector ?? - AggregationSelector_1.DEFAULT_AGGREGATION_TEMPORALITY_SELECTOR; - this._metricProducers = options?.metricProducers ?? []; - this._cardinalitySelector = options?.cardinalitySelector; - } - setMetricProducer(metricProducer) { - if (this._sdkMetricProducer) { - throw new Error('MetricReader can not be bound to a MeterProvider again.'); - } - this._sdkMetricProducer = metricProducer; - this.onInitialized(); - } - selectAggregation(instrumentType) { - return this._aggregationSelector(instrumentType); - } - selectAggregationTemporality(instrumentType) { - return this._aggregationTemporalitySelector(instrumentType); - } - selectCardinalityLimit(instrumentType) { - return this._cardinalitySelector - ? this._cardinalitySelector(instrumentType) - : 2000; // default value if no selector is provided - } - /** - * Handle once the SDK has initialized this {@link MetricReader} - * Overriding this method is optional. - */ - onInitialized() { - // Default implementation is empty. - } - async collect(options) { - if (this._sdkMetricProducer === undefined) { - throw new Error('MetricReader is not bound to a MetricProducer'); - } - // Subsequent invocations to collect are not allowed. SDKs SHOULD return some failure for these calls. - if (this._shutdown) { - throw new Error('MetricReader is shutdown'); - } - const [sdkCollectionResults, ...additionalCollectionResults] = await Promise.all([ - this._sdkMetricProducer.collect({ - timeoutMillis: options?.timeoutMillis, - }), - ...this._metricProducers.map(producer => producer.collect({ - timeoutMillis: options?.timeoutMillis, - })), - ]); - // Merge the results, keeping the SDK's Resource - const errors = sdkCollectionResults.errors.concat((0, utils_1.FlatMap)(additionalCollectionResults, result => result.errors)); - const resource = sdkCollectionResults.resourceMetrics.resource; - const scopeMetrics = sdkCollectionResults.resourceMetrics.scopeMetrics.concat((0, utils_1.FlatMap)(additionalCollectionResults, result => result.resourceMetrics.scopeMetrics)); - return { - resourceMetrics: { - resource, - scopeMetrics, - }, - errors, - }; - } - async shutdown(options) { - // Do not call shutdown again if it has already been called. - if (this._shutdown) { - api.diag.error('Cannot call shutdown twice.'); - return; - } - // No timeout if timeoutMillis is undefined or null. - if (options?.timeoutMillis == null) { - await this.onShutdown(); - } - else { - await (0, utils_1.callWithTimeout)(this.onShutdown(), options.timeoutMillis); - } - this._shutdown = true; - } - async forceFlush(options) { - if (this._shutdown) { - api.diag.warn('Cannot forceFlush on already shutdown MetricReader.'); - return; - } - // No timeout if timeoutMillis is undefined or null. - if (options?.timeoutMillis == null) { - await this.onForceFlush(); - return; - } - await (0, utils_1.callWithTimeout)(this.onForceFlush(), options.timeoutMillis); - } -} -exports.MetricReader = MetricReader; -//# sourceMappingURL=MetricReader.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/PeriodicExportingMetricReader.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/PeriodicExportingMetricReader.js deleted file mode 100644 index b8080c78..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/export/PeriodicExportingMetricReader.js +++ /dev/null @@ -1,115 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PeriodicExportingMetricReader = void 0; -const api = require("@opentelemetry/api"); -const core_1 = require("@opentelemetry/core"); -const MetricReader_1 = require("./MetricReader"); -const utils_1 = require("../utils"); -/** - * {@link MetricReader} which collects metrics based on a user-configurable time interval, and passes the metrics to - * the configured {@link PushMetricExporter} - */ -class PeriodicExportingMetricReader extends MetricReader_1.MetricReader { - _interval; - _exporter; - _exportInterval; - _exportTimeout; - constructor(options) { - super({ - aggregationSelector: options.exporter.selectAggregation?.bind(options.exporter), - aggregationTemporalitySelector: options.exporter.selectAggregationTemporality?.bind(options.exporter), - metricProducers: options.metricProducers, - }); - if (options.exportIntervalMillis !== undefined && - options.exportIntervalMillis <= 0) { - throw Error('exportIntervalMillis must be greater than 0'); - } - if (options.exportTimeoutMillis !== undefined && - options.exportTimeoutMillis <= 0) { - throw Error('exportTimeoutMillis must be greater than 0'); - } - if (options.exportTimeoutMillis !== undefined && - options.exportIntervalMillis !== undefined && - options.exportIntervalMillis < options.exportTimeoutMillis) { - throw Error('exportIntervalMillis must be greater than or equal to exportTimeoutMillis'); - } - this._exportInterval = options.exportIntervalMillis ?? 60000; - this._exportTimeout = options.exportTimeoutMillis ?? 30000; - this._exporter = options.exporter; - } - async _runOnce() { - try { - await (0, utils_1.callWithTimeout)(this._doRun(), this._exportTimeout); - } - catch (err) { - if (err instanceof utils_1.TimeoutError) { - api.diag.error('Export took longer than %s milliseconds and timed out.', this._exportTimeout); - return; - } - (0, core_1.globalErrorHandler)(err); - } - } - async _doRun() { - const { resourceMetrics, errors } = await this.collect({ - timeoutMillis: this._exportTimeout, - }); - if (errors.length > 0) { - api.diag.error('PeriodicExportingMetricReader: metrics collection errors', ...errors); - } - if (resourceMetrics.resource.asyncAttributesPending) { - try { - await resourceMetrics.resource.waitForAsyncAttributes?.(); - } - catch (e) { - api.diag.debug('Error while resolving async portion of resource: ', e); - (0, core_1.globalErrorHandler)(e); - } - } - if (resourceMetrics.scopeMetrics.length === 0) { - return; - } - const result = await core_1.internal._export(this._exporter, resourceMetrics); - if (result.code !== core_1.ExportResultCode.SUCCESS) { - throw new Error(`PeriodicExportingMetricReader: metrics export failed (error ${result.error})`); - } - } - onInitialized() { - // start running the interval as soon as this reader is initialized and keep handle for shutdown. - this._interval = setInterval(() => { - // this._runOnce never rejects. Using void operator to suppress @typescript-eslint/no-floating-promises. - void this._runOnce(); - }, this._exportInterval); - // depending on runtime, this may be a 'number' or NodeJS.Timeout - if (typeof this._interval !== 'number') { - this._interval.unref(); - } - } - async onForceFlush() { - await this._runOnce(); - await this._exporter.forceFlush(); - } - async onShutdown() { - if (this._interval) { - clearInterval(this._interval); - } - await this.onForceFlush(); - await this._exporter.shutdown(); - } -} -exports.PeriodicExportingMetricReader = PeriodicExportingMetricReader; -//# sourceMappingURL=PeriodicExportingMetricReader.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/index.js deleted file mode 100644 index 8013d085..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/index.js +++ /dev/null @@ -1,41 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TimeoutError = exports.createDenyListAttributesProcessor = exports.createAllowListAttributesProcessor = exports.AggregationType = exports.MeterProvider = exports.ConsoleMetricExporter = exports.InMemoryMetricExporter = exports.PeriodicExportingMetricReader = exports.MetricReader = exports.InstrumentType = exports.DataPointType = exports.AggregationTemporality = void 0; -var AggregationTemporality_1 = require("./export/AggregationTemporality"); -Object.defineProperty(exports, "AggregationTemporality", { enumerable: true, get: function () { return AggregationTemporality_1.AggregationTemporality; } }); -var MetricData_1 = require("./export/MetricData"); -Object.defineProperty(exports, "DataPointType", { enumerable: true, get: function () { return MetricData_1.DataPointType; } }); -Object.defineProperty(exports, "InstrumentType", { enumerable: true, get: function () { return MetricData_1.InstrumentType; } }); -var MetricReader_1 = require("./export/MetricReader"); -Object.defineProperty(exports, "MetricReader", { enumerable: true, get: function () { return MetricReader_1.MetricReader; } }); -var PeriodicExportingMetricReader_1 = require("./export/PeriodicExportingMetricReader"); -Object.defineProperty(exports, "PeriodicExportingMetricReader", { enumerable: true, get: function () { return PeriodicExportingMetricReader_1.PeriodicExportingMetricReader; } }); -var InMemoryMetricExporter_1 = require("./export/InMemoryMetricExporter"); -Object.defineProperty(exports, "InMemoryMetricExporter", { enumerable: true, get: function () { return InMemoryMetricExporter_1.InMemoryMetricExporter; } }); -var ConsoleMetricExporter_1 = require("./export/ConsoleMetricExporter"); -Object.defineProperty(exports, "ConsoleMetricExporter", { enumerable: true, get: function () { return ConsoleMetricExporter_1.ConsoleMetricExporter; } }); -var MeterProvider_1 = require("./MeterProvider"); -Object.defineProperty(exports, "MeterProvider", { enumerable: true, get: function () { return MeterProvider_1.MeterProvider; } }); -var AggregationOption_1 = require("./view/AggregationOption"); -Object.defineProperty(exports, "AggregationType", { enumerable: true, get: function () { return AggregationOption_1.AggregationType; } }); -var AttributesProcessor_1 = require("./view/AttributesProcessor"); -Object.defineProperty(exports, "createAllowListAttributesProcessor", { enumerable: true, get: function () { return AttributesProcessor_1.createAllowListAttributesProcessor; } }); -Object.defineProperty(exports, "createDenyListAttributesProcessor", { enumerable: true, get: function () { return AttributesProcessor_1.createDenyListAttributesProcessor; } }); -var utils_1 = require("./utils"); -Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function () { return utils_1.TimeoutError; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/AsyncMetricStorage.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/AsyncMetricStorage.js deleted file mode 100644 index 281ac9c1..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/AsyncMetricStorage.js +++ /dev/null @@ -1,60 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AsyncMetricStorage = void 0; -const MetricStorage_1 = require("./MetricStorage"); -const DeltaMetricProcessor_1 = require("./DeltaMetricProcessor"); -const TemporalMetricProcessor_1 = require("./TemporalMetricProcessor"); -const HashMap_1 = require("./HashMap"); -/** - * Internal interface. - * - * Stores and aggregates {@link MetricData} for asynchronous instruments. - */ -class AsyncMetricStorage extends MetricStorage_1.MetricStorage { - _attributesProcessor; - _aggregationCardinalityLimit; - _deltaMetricStorage; - _temporalMetricStorage; - constructor(_instrumentDescriptor, aggregator, _attributesProcessor, collectorHandles, _aggregationCardinalityLimit) { - super(_instrumentDescriptor); - this._attributesProcessor = _attributesProcessor; - this._aggregationCardinalityLimit = _aggregationCardinalityLimit; - this._deltaMetricStorage = new DeltaMetricProcessor_1.DeltaMetricProcessor(aggregator, this._aggregationCardinalityLimit); - this._temporalMetricStorage = new TemporalMetricProcessor_1.TemporalMetricProcessor(aggregator, collectorHandles); - } - record(measurements, observationTime) { - const processed = new HashMap_1.AttributeHashMap(); - Array.from(measurements.entries()).forEach(([attributes, value]) => { - processed.set(this._attributesProcessor.process(attributes), value); - }); - this._deltaMetricStorage.batchCumulate(processed, observationTime); - } - /** - * Collects the metrics from this storage. The ObservableCallback is invoked - * during the collection. - * - * Note: This is a stateful operation and may reset any interval-related - * state for the MetricCollector. - */ - collect(collector, collectionTime) { - const accumulations = this._deltaMetricStorage.collect(); - return this._temporalMetricStorage.buildMetrics(collector, this._instrumentDescriptor, accumulations, collectionTime); - } -} -exports.AsyncMetricStorage = AsyncMetricStorage; -//# sourceMappingURL=AsyncMetricStorage.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/DeltaMetricProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/DeltaMetricProcessor.js deleted file mode 100644 index a703f06f..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/DeltaMetricProcessor.js +++ /dev/null @@ -1,103 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DeltaMetricProcessor = void 0; -const utils_1 = require("../utils"); -const HashMap_1 = require("./HashMap"); -/** - * Internal interface. - * - * Allows synchronous collection of metrics. This processor should allow - * allocation of new aggregation cells for metrics and convert cumulative - * recording to delta data points. - */ -class DeltaMetricProcessor { - _aggregator; - _activeCollectionStorage = new HashMap_1.AttributeHashMap(); - // TODO: find a reasonable mean to clean the memo; - // https://github.com/open-telemetry/opentelemetry-specification/pull/2208 - _cumulativeMemoStorage = new HashMap_1.AttributeHashMap(); - _cardinalityLimit; - _overflowAttributes = { 'otel.metric.overflow': true }; - _overflowHashCode; - constructor(_aggregator, aggregationCardinalityLimit) { - this._aggregator = _aggregator; - this._cardinalityLimit = (aggregationCardinalityLimit ?? 2000) - 1; - this._overflowHashCode = (0, utils_1.hashAttributes)(this._overflowAttributes); - } - record(value, attributes, _context, collectionTime) { - let accumulation = this._activeCollectionStorage.get(attributes); - if (!accumulation) { - if (this._activeCollectionStorage.size >= this._cardinalityLimit) { - const overflowAccumulation = this._activeCollectionStorage.getOrDefault(this._overflowAttributes, () => this._aggregator.createAccumulation(collectionTime)); - overflowAccumulation?.record(value); - return; - } - accumulation = this._aggregator.createAccumulation(collectionTime); - this._activeCollectionStorage.set(attributes, accumulation); - } - accumulation?.record(value); - } - batchCumulate(measurements, collectionTime) { - Array.from(measurements.entries()).forEach(([attributes, value, hashCode]) => { - const accumulation = this._aggregator.createAccumulation(collectionTime); - accumulation?.record(value); - let delta = accumulation; - // Diff with recorded cumulative memo. - if (this._cumulativeMemoStorage.has(attributes, hashCode)) { - // has() returned true, previous is present. - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const previous = this._cumulativeMemoStorage.get(attributes, hashCode); - delta = this._aggregator.diff(previous, accumulation); - } - else { - // If the cardinality limit is reached, we need to change the attributes - if (this._cumulativeMemoStorage.size >= this._cardinalityLimit) { - attributes = this._overflowAttributes; - hashCode = this._overflowHashCode; - if (this._cumulativeMemoStorage.has(attributes, hashCode)) { - // has() returned true, previous is present. - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const previous = this._cumulativeMemoStorage.get(attributes, hashCode); - delta = this._aggregator.diff(previous, accumulation); - } - } - } - // Merge with uncollected active delta. - if (this._activeCollectionStorage.has(attributes, hashCode)) { - // has() returned true, active is present. - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const active = this._activeCollectionStorage.get(attributes, hashCode); - delta = this._aggregator.merge(active, delta); - } - // Save the current record and the delta record. - this._cumulativeMemoStorage.set(attributes, accumulation, hashCode); - this._activeCollectionStorage.set(attributes, delta, hashCode); - }); - } - /** - * Returns a collection of delta metrics. Start time is the when first - * time event collected. - */ - collect() { - const unreportedDelta = this._activeCollectionStorage; - this._activeCollectionStorage = new HashMap_1.AttributeHashMap(); - return unreportedDelta; - } -} -exports.DeltaMetricProcessor = DeltaMetricProcessor; -//# sourceMappingURL=DeltaMetricProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/HashMap.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/HashMap.js deleted file mode 100644 index 3bf96e35..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/HashMap.js +++ /dev/null @@ -1,83 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AttributeHashMap = exports.HashMap = void 0; -const utils_1 = require("../utils"); -class HashMap { - _hash; - _valueMap = new Map(); - _keyMap = new Map(); - constructor(_hash) { - this._hash = _hash; - } - get(key, hashCode) { - hashCode ??= this._hash(key); - return this._valueMap.get(hashCode); - } - getOrDefault(key, defaultFactory) { - const hash = this._hash(key); - if (this._valueMap.has(hash)) { - return this._valueMap.get(hash); - } - const val = defaultFactory(); - if (!this._keyMap.has(hash)) { - this._keyMap.set(hash, key); - } - this._valueMap.set(hash, val); - return val; - } - set(key, value, hashCode) { - hashCode ??= this._hash(key); - if (!this._keyMap.has(hashCode)) { - this._keyMap.set(hashCode, key); - } - this._valueMap.set(hashCode, value); - } - has(key, hashCode) { - hashCode ??= this._hash(key); - return this._valueMap.has(hashCode); - } - *keys() { - const keyIterator = this._keyMap.entries(); - let next = keyIterator.next(); - while (next.done !== true) { - yield [next.value[1], next.value[0]]; - next = keyIterator.next(); - } - } - *entries() { - const valueIterator = this._valueMap.entries(); - let next = valueIterator.next(); - while (next.done !== true) { - // next.value[0] here can not be undefined - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - yield [this._keyMap.get(next.value[0]), next.value[1], next.value[0]]; - next = valueIterator.next(); - } - } - get size() { - return this._valueMap.size; - } -} -exports.HashMap = HashMap; -class AttributeHashMap extends HashMap { - constructor() { - super(utils_1.hashAttributes); - } -} -exports.AttributeHashMap = AttributeHashMap; -//# sourceMappingURL=HashMap.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterProviderSharedState.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterProviderSharedState.js deleted file mode 100644 index d617123c..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterProviderSharedState.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MeterProviderSharedState = void 0; -const utils_1 = require("../utils"); -const ViewRegistry_1 = require("../view/ViewRegistry"); -const MeterSharedState_1 = require("./MeterSharedState"); -const AggregationOption_1 = require("../view/AggregationOption"); -/** - * An internal record for shared meter provider states. - */ -class MeterProviderSharedState { - resource; - viewRegistry = new ViewRegistry_1.ViewRegistry(); - metricCollectors = []; - meterSharedStates = new Map(); - constructor(resource) { - this.resource = resource; - } - getMeterSharedState(instrumentationScope) { - const id = (0, utils_1.instrumentationScopeId)(instrumentationScope); - let meterSharedState = this.meterSharedStates.get(id); - if (meterSharedState == null) { - meterSharedState = new MeterSharedState_1.MeterSharedState(this, instrumentationScope); - this.meterSharedStates.set(id, meterSharedState); - } - return meterSharedState; - } - selectAggregations(instrumentType) { - const result = []; - for (const collector of this.metricCollectors) { - result.push([ - collector, - (0, AggregationOption_1.toAggregation)(collector.selectAggregation(instrumentType)), - ]); - } - return result; - } -} -exports.MeterProviderSharedState = MeterProviderSharedState; -//# sourceMappingURL=MeterProviderSharedState.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterSharedState.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterSharedState.js deleted file mode 100644 index 701204ef..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MeterSharedState.js +++ /dev/null @@ -1,120 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MeterSharedState = void 0; -const InstrumentDescriptor_1 = require("../InstrumentDescriptor"); -const Meter_1 = require("../Meter"); -const utils_1 = require("../utils"); -const AsyncMetricStorage_1 = require("./AsyncMetricStorage"); -const MetricStorageRegistry_1 = require("./MetricStorageRegistry"); -const MultiWritableMetricStorage_1 = require("./MultiWritableMetricStorage"); -const ObservableRegistry_1 = require("./ObservableRegistry"); -const SyncMetricStorage_1 = require("./SyncMetricStorage"); -const AttributesProcessor_1 = require("../view/AttributesProcessor"); -/** - * An internal record for shared meter provider states. - */ -class MeterSharedState { - _meterProviderSharedState; - _instrumentationScope; - metricStorageRegistry = new MetricStorageRegistry_1.MetricStorageRegistry(); - observableRegistry = new ObservableRegistry_1.ObservableRegistry(); - meter; - constructor(_meterProviderSharedState, _instrumentationScope) { - this._meterProviderSharedState = _meterProviderSharedState; - this._instrumentationScope = _instrumentationScope; - this.meter = new Meter_1.Meter(this); - } - registerMetricStorage(descriptor) { - const storages = this._registerMetricStorage(descriptor, SyncMetricStorage_1.SyncMetricStorage); - if (storages.length === 1) { - return storages[0]; - } - return new MultiWritableMetricStorage_1.MultiMetricStorage(storages); - } - registerAsyncMetricStorage(descriptor) { - const storages = this._registerMetricStorage(descriptor, AsyncMetricStorage_1.AsyncMetricStorage); - return storages; - } - /** - * @param collector opaque handle of {@link MetricCollector} which initiated the collection. - * @param collectionTime the HrTime at which the collection was initiated. - * @param options options for collection. - * @returns the list of metric data collected. - */ - async collect(collector, collectionTime, options) { - /** - * 1. Call all observable callbacks first. - * 2. Collect metric result for the collector. - */ - const errors = await this.observableRegistry.observe(collectionTime, options?.timeoutMillis); - const storages = this.metricStorageRegistry.getStorages(collector); - // prevent more allocations if there are no storages. - if (storages.length === 0) { - return null; - } - const metricDataList = storages - .map(metricStorage => { - return metricStorage.collect(collector, collectionTime); - }) - .filter(utils_1.isNotNullish); - // skip this scope if no data was collected (storage created, but no data observed) - if (metricDataList.length === 0) { - return { errors }; - } - return { - scopeMetrics: { - scope: this._instrumentationScope, - metrics: metricDataList, - }, - errors, - }; - } - _registerMetricStorage(descriptor, MetricStorageType) { - const views = this._meterProviderSharedState.viewRegistry.findViews(descriptor, this._instrumentationScope); - let storages = views.map(view => { - const viewDescriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptorWithView)(view, descriptor); - const compatibleStorage = this.metricStorageRegistry.findOrUpdateCompatibleStorage(viewDescriptor); - if (compatibleStorage != null) { - return compatibleStorage; - } - const aggregator = view.aggregation.createAggregator(viewDescriptor); - const viewStorage = new MetricStorageType(viewDescriptor, aggregator, view.attributesProcessor, this._meterProviderSharedState.metricCollectors, view.aggregationCardinalityLimit); - this.metricStorageRegistry.register(viewStorage); - return viewStorage; - }); - // Fallback to the per-collector aggregations if no view is configured for the instrument. - if (storages.length === 0) { - const perCollectorAggregations = this._meterProviderSharedState.selectAggregations(descriptor.type); - const collectorStorages = perCollectorAggregations.map(([collector, aggregation]) => { - const compatibleStorage = this.metricStorageRegistry.findOrUpdateCompatibleCollectorStorage(collector, descriptor); - if (compatibleStorage != null) { - return compatibleStorage; - } - const aggregator = aggregation.createAggregator(descriptor); - const cardinalityLimit = collector.selectCardinalityLimit(descriptor.type); - const storage = new MetricStorageType(descriptor, aggregator, (0, AttributesProcessor_1.createNoopAttributesProcessor)(), [collector], cardinalityLimit); - this.metricStorageRegistry.registerForCollector(collector, storage); - return storage; - }); - storages = storages.concat(collectorStorages); - } - return storages; - } -} -exports.MeterSharedState = MeterSharedState; -//# sourceMappingURL=MeterSharedState.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricCollector.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricCollector.js deleted file mode 100644 index 2bafeb0e..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricCollector.js +++ /dev/null @@ -1,83 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MetricCollector = void 0; -const core_1 = require("@opentelemetry/core"); -/** - * An internal opaque interface that the MetricReader receives as - * MetricProducer. It acts as the storage key to the internal metric stream - * state for each MetricReader. - */ -class MetricCollector { - _sharedState; - _metricReader; - constructor(_sharedState, _metricReader) { - this._sharedState = _sharedState; - this._metricReader = _metricReader; - } - async collect(options) { - const collectionTime = (0, core_1.millisToHrTime)(Date.now()); - const scopeMetrics = []; - const errors = []; - const meterCollectionPromises = Array.from(this._sharedState.meterSharedStates.values()).map(async (meterSharedState) => { - const current = await meterSharedState.collect(this, collectionTime, options); - // only add scope metrics if available - if (current?.scopeMetrics != null) { - scopeMetrics.push(current.scopeMetrics); - } - // only add errors if available - if (current?.errors != null) { - errors.push(...current.errors); - } - }); - await Promise.all(meterCollectionPromises); - return { - resourceMetrics: { - resource: this._sharedState.resource, - scopeMetrics: scopeMetrics, - }, - errors: errors, - }; - } - /** - * Delegates for MetricReader.forceFlush. - */ - async forceFlush(options) { - await this._metricReader.forceFlush(options); - } - /** - * Delegates for MetricReader.shutdown. - */ - async shutdown(options) { - await this._metricReader.shutdown(options); - } - selectAggregationTemporality(instrumentType) { - return this._metricReader.selectAggregationTemporality(instrumentType); - } - selectAggregation(instrumentType) { - return this._metricReader.selectAggregation(instrumentType); - } - /** - * Select the cardinality limit for the given {@link InstrumentType} for this - * collector. - */ - selectCardinalityLimit(instrumentType) { - return this._metricReader.selectCardinalityLimit?.(instrumentType) ?? 2000; - } -} -exports.MetricCollector = MetricCollector; -//# sourceMappingURL=MetricCollector.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorage.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorage.js deleted file mode 100644 index fdfd8bb2..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorage.js +++ /dev/null @@ -1,43 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MetricStorage = void 0; -const InstrumentDescriptor_1 = require("../InstrumentDescriptor"); -/** - * Internal interface. - * - * Represents a storage from which we can collect metrics. - */ -class MetricStorage { - _instrumentDescriptor; - constructor(_instrumentDescriptor) { - this._instrumentDescriptor = _instrumentDescriptor; - } - getInstrumentDescriptor() { - return this._instrumentDescriptor; - } - updateDescription(description) { - this._instrumentDescriptor = (0, InstrumentDescriptor_1.createInstrumentDescriptor)(this._instrumentDescriptor.name, this._instrumentDescriptor.type, { - description: description, - valueType: this._instrumentDescriptor.valueType, - unit: this._instrumentDescriptor.unit, - advice: this._instrumentDescriptor.advice, - }); - } -} -exports.MetricStorage = MetricStorage; -//# sourceMappingURL=MetricStorage.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorageRegistry.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorageRegistry.js deleted file mode 100644 index 3dab0e7a..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MetricStorageRegistry.js +++ /dev/null @@ -1,112 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MetricStorageRegistry = void 0; -const InstrumentDescriptor_1 = require("../InstrumentDescriptor"); -const api = require("@opentelemetry/api"); -const RegistrationConflicts_1 = require("../view/RegistrationConflicts"); -/** - * Internal class for storing {@link MetricStorage} - */ -class MetricStorageRegistry { - _sharedRegistry = new Map(); - _perCollectorRegistry = new Map(); - static create() { - return new MetricStorageRegistry(); - } - getStorages(collector) { - let storages = []; - for (const metricStorages of this._sharedRegistry.values()) { - storages = storages.concat(metricStorages); - } - const perCollectorStorages = this._perCollectorRegistry.get(collector); - if (perCollectorStorages != null) { - for (const metricStorages of perCollectorStorages.values()) { - storages = storages.concat(metricStorages); - } - } - return storages; - } - register(storage) { - this._registerStorage(storage, this._sharedRegistry); - } - registerForCollector(collector, storage) { - let storageMap = this._perCollectorRegistry.get(collector); - if (storageMap == null) { - storageMap = new Map(); - this._perCollectorRegistry.set(collector, storageMap); - } - this._registerStorage(storage, storageMap); - } - findOrUpdateCompatibleStorage(expectedDescriptor) { - const storages = this._sharedRegistry.get(expectedDescriptor.name); - if (storages === undefined) { - return null; - } - // If the descriptor is compatible, the type of their metric storage - // (either SyncMetricStorage or AsyncMetricStorage) must be compatible. - return this._findOrUpdateCompatibleStorage(expectedDescriptor, storages); - } - findOrUpdateCompatibleCollectorStorage(collector, expectedDescriptor) { - const storageMap = this._perCollectorRegistry.get(collector); - if (storageMap === undefined) { - return null; - } - const storages = storageMap.get(expectedDescriptor.name); - if (storages === undefined) { - return null; - } - // If the descriptor is compatible, the type of their metric storage - // (either SyncMetricStorage or AsyncMetricStorage) must be compatible. - return this._findOrUpdateCompatibleStorage(expectedDescriptor, storages); - } - _registerStorage(storage, storageMap) { - const descriptor = storage.getInstrumentDescriptor(); - const storages = storageMap.get(descriptor.name); - if (storages === undefined) { - storageMap.set(descriptor.name, [storage]); - return; - } - storages.push(storage); - } - _findOrUpdateCompatibleStorage(expectedDescriptor, existingStorages) { - let compatibleStorage = null; - for (const existingStorage of existingStorages) { - const existingDescriptor = existingStorage.getInstrumentDescriptor(); - if ((0, InstrumentDescriptor_1.isDescriptorCompatibleWith)(existingDescriptor, expectedDescriptor)) { - // Use the longer description if it does not match. - if (existingDescriptor.description !== expectedDescriptor.description) { - if (expectedDescriptor.description.length > - existingDescriptor.description.length) { - existingStorage.updateDescription(expectedDescriptor.description); - } - api.diag.warn('A view or instrument with the name ', expectedDescriptor.name, ' has already been registered, but has a different description and is incompatible with another registered view.\n', 'Details:\n', (0, RegistrationConflicts_1.getIncompatibilityDetails)(existingDescriptor, expectedDescriptor), 'The longer description will be used.\nTo resolve the conflict:', (0, RegistrationConflicts_1.getConflictResolutionRecipe)(existingDescriptor, expectedDescriptor)); - } - // Storage is fully compatible. There will never be more than one pre-existing fully compatible storage. - compatibleStorage = existingStorage; - } - else { - // The implementation SHOULD warn about duplicate instrument registration - // conflicts after applying View configuration. - api.diag.warn('A view or instrument with the name ', expectedDescriptor.name, ' has already been registered and is incompatible with another registered view.\n', 'Details:\n', (0, RegistrationConflicts_1.getIncompatibilityDetails)(existingDescriptor, expectedDescriptor), 'To resolve the conflict:\n', (0, RegistrationConflicts_1.getConflictResolutionRecipe)(existingDescriptor, expectedDescriptor)); - } - } - return compatibleStorage; - } -} -exports.MetricStorageRegistry = MetricStorageRegistry; -//# sourceMappingURL=MetricStorageRegistry.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MultiWritableMetricStorage.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MultiWritableMetricStorage.js deleted file mode 100644 index ec9e733c..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/MultiWritableMetricStorage.js +++ /dev/null @@ -1,34 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MultiMetricStorage = void 0; -/** - * Internal interface. - */ -class MultiMetricStorage { - _backingStorages; - constructor(_backingStorages) { - this._backingStorages = _backingStorages; - } - record(value, attributes, context, recordTime) { - this._backingStorages.forEach(it => { - it.record(value, attributes, context, recordTime); - }); - } -} -exports.MultiMetricStorage = MultiMetricStorage; -//# sourceMappingURL=MultiWritableMetricStorage.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/ObservableRegistry.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/ObservableRegistry.js deleted file mode 100644 index f33ba010..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/ObservableRegistry.js +++ /dev/null @@ -1,128 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ObservableRegistry = void 0; -const api_1 = require("@opentelemetry/api"); -const Instruments_1 = require("../Instruments"); -const ObservableResult_1 = require("../ObservableResult"); -const utils_1 = require("../utils"); -/** - * An internal interface for managing ObservableCallbacks. - * - * Every registered callback associated with a set of instruments are be evaluated - * exactly once during collection prior to reading data for that instrument. - */ -class ObservableRegistry { - _callbacks = []; - _batchCallbacks = []; - addCallback(callback, instrument) { - const idx = this._findCallback(callback, instrument); - if (idx >= 0) { - return; - } - this._callbacks.push({ callback, instrument }); - } - removeCallback(callback, instrument) { - const idx = this._findCallback(callback, instrument); - if (idx < 0) { - return; - } - this._callbacks.splice(idx, 1); - } - addBatchCallback(callback, instruments) { - // Create a set of unique instruments. - const observableInstruments = new Set(instruments.filter(Instruments_1.isObservableInstrument)); - if (observableInstruments.size === 0) { - api_1.diag.error('BatchObservableCallback is not associated with valid instruments', instruments); - return; - } - const idx = this._findBatchCallback(callback, observableInstruments); - if (idx >= 0) { - return; - } - this._batchCallbacks.push({ callback, instruments: observableInstruments }); - } - removeBatchCallback(callback, instruments) { - // Create a set of unique instruments. - const observableInstruments = new Set(instruments.filter(Instruments_1.isObservableInstrument)); - const idx = this._findBatchCallback(callback, observableInstruments); - if (idx < 0) { - return; - } - this._batchCallbacks.splice(idx, 1); - } - /** - * @returns a promise of rejected reasons for invoking callbacks. - */ - async observe(collectionTime, timeoutMillis) { - const callbackFutures = this._observeCallbacks(collectionTime, timeoutMillis); - const batchCallbackFutures = this._observeBatchCallbacks(collectionTime, timeoutMillis); - const results = await (0, utils_1.PromiseAllSettled)([ - ...callbackFutures, - ...batchCallbackFutures, - ]); - const rejections = results - .filter(utils_1.isPromiseAllSettledRejectionResult) - .map(it => it.reason); - return rejections; - } - _observeCallbacks(observationTime, timeoutMillis) { - return this._callbacks.map(async ({ callback, instrument }) => { - const observableResult = new ObservableResult_1.ObservableResultImpl(instrument._descriptor.name, instrument._descriptor.valueType); - let callPromise = Promise.resolve(callback(observableResult)); - if (timeoutMillis != null) { - callPromise = (0, utils_1.callWithTimeout)(callPromise, timeoutMillis); - } - await callPromise; - instrument._metricStorages.forEach(metricStorage => { - metricStorage.record(observableResult._buffer, observationTime); - }); - }); - } - _observeBatchCallbacks(observationTime, timeoutMillis) { - return this._batchCallbacks.map(async ({ callback, instruments }) => { - const observableResult = new ObservableResult_1.BatchObservableResultImpl(); - let callPromise = Promise.resolve(callback(observableResult)); - if (timeoutMillis != null) { - callPromise = (0, utils_1.callWithTimeout)(callPromise, timeoutMillis); - } - await callPromise; - instruments.forEach(instrument => { - const buffer = observableResult._buffer.get(instrument); - if (buffer == null) { - return; - } - instrument._metricStorages.forEach(metricStorage => { - metricStorage.record(buffer, observationTime); - }); - }); - }); - } - _findCallback(callback, instrument) { - return this._callbacks.findIndex(record => { - return record.callback === callback && record.instrument === instrument; - }); - } - _findBatchCallback(callback, instruments) { - return this._batchCallbacks.findIndex(record => { - return (record.callback === callback && - (0, utils_1.setEquals)(record.instruments, instruments)); - }); - } -} -exports.ObservableRegistry = ObservableRegistry; -//# sourceMappingURL=ObservableRegistry.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/SyncMetricStorage.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/SyncMetricStorage.js deleted file mode 100644 index d075757a..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/SyncMetricStorage.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SyncMetricStorage = void 0; -const MetricStorage_1 = require("./MetricStorage"); -const DeltaMetricProcessor_1 = require("./DeltaMetricProcessor"); -const TemporalMetricProcessor_1 = require("./TemporalMetricProcessor"); -/** - * Internal interface. - * - * Stores and aggregates {@link MetricData} for synchronous instruments. - */ -class SyncMetricStorage extends MetricStorage_1.MetricStorage { - _attributesProcessor; - _aggregationCardinalityLimit; - _deltaMetricStorage; - _temporalMetricStorage; - constructor(instrumentDescriptor, aggregator, _attributesProcessor, collectorHandles, _aggregationCardinalityLimit) { - super(instrumentDescriptor); - this._attributesProcessor = _attributesProcessor; - this._aggregationCardinalityLimit = _aggregationCardinalityLimit; - this._deltaMetricStorage = new DeltaMetricProcessor_1.DeltaMetricProcessor(aggregator, this._aggregationCardinalityLimit); - this._temporalMetricStorage = new TemporalMetricProcessor_1.TemporalMetricProcessor(aggregator, collectorHandles); - } - record(value, attributes, context, recordTime) { - attributes = this._attributesProcessor.process(attributes, context); - this._deltaMetricStorage.record(value, attributes, context, recordTime); - } - /** - * Collects the metrics from this storage. - * - * Note: This is a stateful operation and may reset any interval-related - * state for the MetricCollector. - */ - collect(collector, collectionTime) { - const accumulations = this._deltaMetricStorage.collect(); - return this._temporalMetricStorage.buildMetrics(collector, this._instrumentDescriptor, accumulations, collectionTime); - } -} -exports.SyncMetricStorage = SyncMetricStorage; -//# sourceMappingURL=SyncMetricStorage.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/TemporalMetricProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/TemporalMetricProcessor.js deleted file mode 100644 index b4220218..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/state/TemporalMetricProcessor.js +++ /dev/null @@ -1,156 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TemporalMetricProcessor = void 0; -const AggregationTemporality_1 = require("../export/AggregationTemporality"); -const HashMap_1 = require("./HashMap"); -/** - * Internal interface. - * - * Provides unique reporting for each collector. Allows synchronous collection - * of metrics and reports given temporality values. - */ -class TemporalMetricProcessor { - _aggregator; - _unreportedAccumulations = new Map(); - _reportHistory = new Map(); - constructor(_aggregator, collectorHandles) { - this._aggregator = _aggregator; - collectorHandles.forEach(handle => { - this._unreportedAccumulations.set(handle, []); - }); - } - /** - * Builds the {@link MetricData} streams to report against a specific MetricCollector. - * @param collector The information of the MetricCollector. - * @param collectors The registered collectors. - * @param instrumentDescriptor The instrumentation descriptor that these metrics generated with. - * @param currentAccumulations The current accumulation of metric data from instruments. - * @param collectionTime The current collection timestamp. - * @returns The {@link MetricData} points or `null`. - */ - buildMetrics(collector, instrumentDescriptor, currentAccumulations, collectionTime) { - this._stashAccumulations(currentAccumulations); - const unreportedAccumulations = this._getMergedUnreportedAccumulations(collector); - let result = unreportedAccumulations; - let aggregationTemporality; - // Check our last report time. - if (this._reportHistory.has(collector)) { - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const last = this._reportHistory.get(collector); - const lastCollectionTime = last.collectionTime; - aggregationTemporality = last.aggregationTemporality; - // Use aggregation temporality + instrument to determine if we do a merge or a diff of - // previous. We have the following four scenarios: - // 1. Cumulative Aggregation (temporality) + Delta recording (sync instrument). - // Here we merge with our last record to get a cumulative aggregation. - // 2. Cumulative Aggregation + Cumulative recording (async instrument). - // Cumulative records are converted to delta recording with DeltaMetricProcessor. - // Here we merge with our last record to get a cumulative aggregation. - // 3. Delta Aggregation + Delta recording - // Calibrate the startTime of metric streams to be the reader's lastCollectionTime. - // 4. Delta Aggregation + Cumulative recording. - // Cumulative records are converted to delta recording with DeltaMetricProcessor. - // Calibrate the startTime of metric streams to be the reader's lastCollectionTime. - if (aggregationTemporality === AggregationTemporality_1.AggregationTemporality.CUMULATIVE) { - // We need to make sure the current delta recording gets merged into the previous cumulative - // for the next cumulative recording. - result = TemporalMetricProcessor.merge(last.accumulations, unreportedAccumulations, this._aggregator); - } - else { - result = TemporalMetricProcessor.calibrateStartTime(last.accumulations, unreportedAccumulations, lastCollectionTime); - } - } - else { - // Call into user code to select aggregation temporality for the instrument. - aggregationTemporality = collector.selectAggregationTemporality(instrumentDescriptor.type); - } - // Update last reported (cumulative) accumulation. - this._reportHistory.set(collector, { - accumulations: result, - collectionTime, - aggregationTemporality, - }); - const accumulationRecords = AttributesMapToAccumulationRecords(result); - // do not convert to metric data if there is nothing to convert. - if (accumulationRecords.length === 0) { - return undefined; - } - return this._aggregator.toMetricData(instrumentDescriptor, aggregationTemporality, accumulationRecords, - /* endTime */ collectionTime); - } - _stashAccumulations(currentAccumulation) { - const registeredCollectors = this._unreportedAccumulations.keys(); - for (const collector of registeredCollectors) { - let stash = this._unreportedAccumulations.get(collector); - if (stash === undefined) { - stash = []; - this._unreportedAccumulations.set(collector, stash); - } - stash.push(currentAccumulation); - } - } - _getMergedUnreportedAccumulations(collector) { - let result = new HashMap_1.AttributeHashMap(); - const unreportedList = this._unreportedAccumulations.get(collector); - this._unreportedAccumulations.set(collector, []); - if (unreportedList === undefined) { - return result; - } - for (const it of unreportedList) { - result = TemporalMetricProcessor.merge(result, it, this._aggregator); - } - return result; - } - static merge(last, current, aggregator) { - const result = last; - const iterator = current.entries(); - let next = iterator.next(); - while (next.done !== true) { - const [key, record, hash] = next.value; - if (last.has(key, hash)) { - const lastAccumulation = last.get(key, hash); - // last.has() returned true, lastAccumulation is present. - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - const accumulation = aggregator.merge(lastAccumulation, record); - result.set(key, accumulation, hash); - } - else { - result.set(key, record, hash); - } - next = iterator.next(); - } - return result; - } - /** - * Calibrate the reported metric streams' startTime to lastCollectionTime. Leaves - * the new stream to be the initial observation time unchanged. - */ - static calibrateStartTime(last, current, lastCollectionTime) { - for (const [key, hash] of last.keys()) { - const currentAccumulation = current.get(key, hash); - currentAccumulation?.setStartTime(lastCollectionTime); - } - return current; - } -} -exports.TemporalMetricProcessor = TemporalMetricProcessor; -// TypeScript complains about converting 3 elements tuple to AccumulationRecord. -function AttributesMapToAccumulationRecords(map) { - return Array.from(map.entries()); -} -//# sourceMappingURL=TemporalMetricProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/utils.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/utils.js deleted file mode 100644 index a37099b8..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/utils.js +++ /dev/null @@ -1,156 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.equalsCaseInsensitive = exports.binarySearchUB = exports.setEquals = exports.FlatMap = exports.isPromiseAllSettledRejectionResult = exports.PromiseAllSettled = exports.callWithTimeout = exports.TimeoutError = exports.instrumentationScopeId = exports.hashAttributes = exports.isNotNullish = void 0; -function isNotNullish(item) { - return item !== undefined && item !== null; -} -exports.isNotNullish = isNotNullish; -/** - * Converting the unordered attributes into unique identifier string. - * @param attributes user provided unordered Attributes. - */ -function hashAttributes(attributes) { - let keys = Object.keys(attributes); - if (keys.length === 0) - return ''; - // Return a string that is stable on key orders. - keys = keys.sort(); - return JSON.stringify(keys.map(key => [key, attributes[key]])); -} -exports.hashAttributes = hashAttributes; -/** - * Converting the instrumentation scope object to a unique identifier string. - * @param instrumentationScope - */ -function instrumentationScopeId(instrumentationScope) { - return `${instrumentationScope.name}:${instrumentationScope.version ?? ''}:${instrumentationScope.schemaUrl ?? ''}`; -} -exports.instrumentationScopeId = instrumentationScopeId; -/** - * Error that is thrown on timeouts. - */ -class TimeoutError extends Error { - constructor(message) { - super(message); - // manually adjust prototype to retain `instanceof` functionality when targeting ES5, see: - // https://github.com/Microsoft/TypeScript-wiki/blob/main/Breaking-Changes.md#extending-built-ins-like-error-array-and-map-may-no-longer-work - Object.setPrototypeOf(this, TimeoutError.prototype); - } -} -exports.TimeoutError = TimeoutError; -/** - * Adds a timeout to a promise and rejects if the specified timeout has elapsed. Also rejects if the specified promise - * rejects, and resolves if the specified promise resolves. - * - *

    NOTE: this operation will continue even after it throws a {@link TimeoutError}. - * - * @param promise promise to use with timeout. - * @param timeout the timeout in milliseconds until the returned promise is rejected. - */ -function callWithTimeout(promise, timeout) { - let timeoutHandle; - const timeoutPromise = new Promise(function timeoutFunction(_resolve, reject) { - timeoutHandle = setTimeout(function timeoutHandler() { - reject(new TimeoutError('Operation timed out.')); - }, timeout); - }); - return Promise.race([promise, timeoutPromise]).then(result => { - clearTimeout(timeoutHandle); - return result; - }, reason => { - clearTimeout(timeoutHandle); - throw reason; - }); -} -exports.callWithTimeout = callWithTimeout; -/** - * Node.js v12.9 lower and browser compatible `Promise.allSettled`. - */ -async function PromiseAllSettled(promises) { - return Promise.all(promises.map(async (p) => { - try { - const ret = await p; - return { - status: 'fulfilled', - value: ret, - }; - } - catch (e) { - return { - status: 'rejected', - reason: e, - }; - } - })); -} -exports.PromiseAllSettled = PromiseAllSettled; -function isPromiseAllSettledRejectionResult(it) { - return it.status === 'rejected'; -} -exports.isPromiseAllSettledRejectionResult = isPromiseAllSettledRejectionResult; -/** - * Node.js v11.0 lower and browser compatible `Array.prototype.flatMap`. - */ -function FlatMap(arr, fn) { - const result = []; - arr.forEach(it => { - result.push(...fn(it)); - }); - return result; -} -exports.FlatMap = FlatMap; -function setEquals(lhs, rhs) { - if (lhs.size !== rhs.size) { - return false; - } - for (const item of lhs) { - if (!rhs.has(item)) { - return false; - } - } - return true; -} -exports.setEquals = setEquals; -/** - * Binary search the sorted array to the find upper bound for the value. - * @param arr - * @param value - * @returns - */ -function binarySearchUB(arr, value) { - let lo = 0; - let hi = arr.length - 1; - let ret = arr.length; - while (hi >= lo) { - const mid = lo + Math.trunc((hi - lo) / 2); - if (arr[mid] < value) { - lo = mid + 1; - } - else { - ret = mid; - hi = mid - 1; - } - } - return ret; -} -exports.binarySearchUB = binarySearchUB; -function equalsCaseInsensitive(lhs, rhs) { - return lhs.toLowerCase() === rhs.toLowerCase(); -} -exports.equalsCaseInsensitive = equalsCaseInsensitive; -//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/Aggregation.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/Aggregation.js deleted file mode 100644 index 45086bb6..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/Aggregation.js +++ /dev/null @@ -1,156 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DEFAULT_AGGREGATION = exports.EXPONENTIAL_HISTOGRAM_AGGREGATION = exports.HISTOGRAM_AGGREGATION = exports.LAST_VALUE_AGGREGATION = exports.SUM_AGGREGATION = exports.DROP_AGGREGATION = exports.DefaultAggregation = exports.ExponentialHistogramAggregation = exports.ExplicitBucketHistogramAggregation = exports.HistogramAggregation = exports.LastValueAggregation = exports.SumAggregation = exports.DropAggregation = void 0; -const api = require("@opentelemetry/api"); -const aggregator_1 = require("../aggregator"); -const MetricData_1 = require("../export/MetricData"); -/** - * The default drop aggregation. - */ -class DropAggregation { - static DEFAULT_INSTANCE = new aggregator_1.DropAggregator(); - createAggregator(_instrument) { - return DropAggregation.DEFAULT_INSTANCE; - } -} -exports.DropAggregation = DropAggregation; -/** - * The default sum aggregation. - */ -class SumAggregation { - static MONOTONIC_INSTANCE = new aggregator_1.SumAggregator(true); - static NON_MONOTONIC_INSTANCE = new aggregator_1.SumAggregator(false); - createAggregator(instrument) { - switch (instrument.type) { - case MetricData_1.InstrumentType.COUNTER: - case MetricData_1.InstrumentType.OBSERVABLE_COUNTER: - case MetricData_1.InstrumentType.HISTOGRAM: { - return SumAggregation.MONOTONIC_INSTANCE; - } - default: { - return SumAggregation.NON_MONOTONIC_INSTANCE; - } - } - } -} -exports.SumAggregation = SumAggregation; -/** - * The default last value aggregation. - */ -class LastValueAggregation { - static DEFAULT_INSTANCE = new aggregator_1.LastValueAggregator(); - createAggregator(_instrument) { - return LastValueAggregation.DEFAULT_INSTANCE; - } -} -exports.LastValueAggregation = LastValueAggregation; -/** - * The default histogram aggregation. - - */ -class HistogramAggregation { - static DEFAULT_INSTANCE = new aggregator_1.HistogramAggregator([0, 5, 10, 25, 50, 75, 100, 250, 500, 750, 1000, 2500, 5000, 7500, 10000], true); - createAggregator(_instrument) { - return HistogramAggregation.DEFAULT_INSTANCE; - } -} -exports.HistogramAggregation = HistogramAggregation; -/** - * The explicit bucket histogram aggregation. - */ -class ExplicitBucketHistogramAggregation { - _recordMinMax; - _boundaries; - /** - * @param boundaries the bucket boundaries of the histogram aggregation - * @param _recordMinMax If set to true, min and max will be recorded. Otherwise, min and max will not be recorded. - */ - constructor(boundaries, _recordMinMax = true) { - this._recordMinMax = _recordMinMax; - if (boundaries == null) { - throw new Error('ExplicitBucketHistogramAggregation should be created with explicit boundaries, if a single bucket histogram is required, please pass an empty array'); - } - // Copy the boundaries array for modification. - boundaries = boundaries.concat(); - // We need to an ordered set to be able to correctly compute count for each - // boundary since we'll iterate on each in order. - boundaries = boundaries.sort((a, b) => a - b); - // Remove all Infinity from the boundaries. - const minusInfinityIndex = boundaries.lastIndexOf(-Infinity); - let infinityIndex = boundaries.indexOf(Infinity); - if (infinityIndex === -1) { - infinityIndex = undefined; - } - this._boundaries = boundaries.slice(minusInfinityIndex + 1, infinityIndex); - } - createAggregator(_instrument) { - return new aggregator_1.HistogramAggregator(this._boundaries, this._recordMinMax); - } -} -exports.ExplicitBucketHistogramAggregation = ExplicitBucketHistogramAggregation; -class ExponentialHistogramAggregation { - _maxSize; - _recordMinMax; - constructor(_maxSize = 160, _recordMinMax = true) { - this._maxSize = _maxSize; - this._recordMinMax = _recordMinMax; - } - createAggregator(_instrument) { - return new aggregator_1.ExponentialHistogramAggregator(this._maxSize, this._recordMinMax); - } -} -exports.ExponentialHistogramAggregation = ExponentialHistogramAggregation; -/** - * The default aggregation. - */ -class DefaultAggregation { - _resolve(instrument) { - // cast to unknown to disable complaints on the (unreachable) fallback. - switch (instrument.type) { - case MetricData_1.InstrumentType.COUNTER: - case MetricData_1.InstrumentType.UP_DOWN_COUNTER: - case MetricData_1.InstrumentType.OBSERVABLE_COUNTER: - case MetricData_1.InstrumentType.OBSERVABLE_UP_DOWN_COUNTER: { - return exports.SUM_AGGREGATION; - } - case MetricData_1.InstrumentType.GAUGE: - case MetricData_1.InstrumentType.OBSERVABLE_GAUGE: { - return exports.LAST_VALUE_AGGREGATION; - } - case MetricData_1.InstrumentType.HISTOGRAM: { - if (instrument.advice.explicitBucketBoundaries) { - return new ExplicitBucketHistogramAggregation(instrument.advice.explicitBucketBoundaries); - } - return exports.HISTOGRAM_AGGREGATION; - } - } - api.diag.warn(`Unable to recognize instrument type: ${instrument.type}`); - return exports.DROP_AGGREGATION; - } - createAggregator(instrument) { - return this._resolve(instrument).createAggregator(instrument); - } -} -exports.DefaultAggregation = DefaultAggregation; -exports.DROP_AGGREGATION = new DropAggregation(); -exports.SUM_AGGREGATION = new SumAggregation(); -exports.LAST_VALUE_AGGREGATION = new LastValueAggregation(); -exports.HISTOGRAM_AGGREGATION = new HistogramAggregation(); -exports.EXPONENTIAL_HISTOGRAM_AGGREGATION = new ExponentialHistogramAggregation(); -exports.DEFAULT_AGGREGATION = new DefaultAggregation(); -//# sourceMappingURL=Aggregation.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/AggregationOption.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/AggregationOption.js deleted file mode 100644 index fef93f71..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/AggregationOption.js +++ /dev/null @@ -1,57 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.toAggregation = exports.AggregationType = void 0; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const Aggregation_1 = require("./Aggregation"); -var AggregationType; -(function (AggregationType) { - AggregationType[AggregationType["DEFAULT"] = 0] = "DEFAULT"; - AggregationType[AggregationType["DROP"] = 1] = "DROP"; - AggregationType[AggregationType["SUM"] = 2] = "SUM"; - AggregationType[AggregationType["LAST_VALUE"] = 3] = "LAST_VALUE"; - AggregationType[AggregationType["EXPLICIT_BUCKET_HISTOGRAM"] = 4] = "EXPLICIT_BUCKET_HISTOGRAM"; - AggregationType[AggregationType["EXPONENTIAL_HISTOGRAM"] = 5] = "EXPONENTIAL_HISTOGRAM"; -})(AggregationType = exports.AggregationType || (exports.AggregationType = {})); -function toAggregation(option) { - switch (option.type) { - case AggregationType.DEFAULT: - return Aggregation_1.DEFAULT_AGGREGATION; - case AggregationType.DROP: - return Aggregation_1.DROP_AGGREGATION; - case AggregationType.SUM: - return Aggregation_1.SUM_AGGREGATION; - case AggregationType.LAST_VALUE: - return Aggregation_1.LAST_VALUE_AGGREGATION; - case AggregationType.EXPONENTIAL_HISTOGRAM: { - const expOption = option; - return new Aggregation_1.ExponentialHistogramAggregation(expOption.options?.maxSize, expOption.options?.recordMinMax); - } - case AggregationType.EXPLICIT_BUCKET_HISTOGRAM: { - const expOption = option; - if (expOption.options == null) { - return Aggregation_1.HISTOGRAM_AGGREGATION; - } - else { - return new Aggregation_1.ExplicitBucketHistogramAggregation(expOption.options?.boundaries, expOption.options?.recordMinMax); - } - } - default: - throw new Error('Unsupported Aggregation'); - } -} -exports.toAggregation = toAggregation; -//# sourceMappingURL=AggregationOption.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/AttributesProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/AttributesProcessor.js deleted file mode 100644 index 43b8cd8c..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/AttributesProcessor.js +++ /dev/null @@ -1,99 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createDenyListAttributesProcessor = exports.createAllowListAttributesProcessor = exports.createMultiAttributesProcessor = exports.createNoopAttributesProcessor = void 0; -class NoopAttributesProcessor { - process(incoming, _context) { - return incoming; - } -} -class MultiAttributesProcessor { - _processors; - constructor(_processors) { - this._processors = _processors; - } - process(incoming, context) { - let filteredAttributes = incoming; - for (const processor of this._processors) { - filteredAttributes = processor.process(filteredAttributes, context); - } - return filteredAttributes; - } -} -class AllowListProcessor { - _allowedAttributeNames; - constructor(_allowedAttributeNames) { - this._allowedAttributeNames = _allowedAttributeNames; - } - process(incoming, _context) { - const filteredAttributes = {}; - Object.keys(incoming) - .filter(attributeName => this._allowedAttributeNames.includes(attributeName)) - .forEach(attributeName => (filteredAttributes[attributeName] = incoming[attributeName])); - return filteredAttributes; - } -} -class DenyListProcessor { - _deniedAttributeNames; - constructor(_deniedAttributeNames) { - this._deniedAttributeNames = _deniedAttributeNames; - } - process(incoming, _context) { - const filteredAttributes = {}; - Object.keys(incoming) - .filter(attributeName => !this._deniedAttributeNames.includes(attributeName)) - .forEach(attributeName => (filteredAttributes[attributeName] = incoming[attributeName])); - return filteredAttributes; - } -} -/** - * @internal - * - * Create an {@link IAttributesProcessor} that acts as a simple pass-through for attributes. - */ -function createNoopAttributesProcessor() { - return NOOP; -} -exports.createNoopAttributesProcessor = createNoopAttributesProcessor; -/** - * @internal - * - * Create an {@link IAttributesProcessor} that applies all processors from the provided list in order. - * - * @param processors Processors to apply in order. - */ -function createMultiAttributesProcessor(processors) { - return new MultiAttributesProcessor(processors); -} -exports.createMultiAttributesProcessor = createMultiAttributesProcessor; -/** - * Create an {@link IAttributesProcessor} that filters by allowed attribute names and drops any names that are not in the - * allow list. - */ -function createAllowListAttributesProcessor(attributeAllowList) { - return new AllowListProcessor(attributeAllowList); -} -exports.createAllowListAttributesProcessor = createAllowListAttributesProcessor; -/** - * Create an {@link IAttributesProcessor} that drops attributes based on the names provided in the deny list - */ -function createDenyListAttributesProcessor(attributeDenyList) { - return new DenyListProcessor(attributeDenyList); -} -exports.createDenyListAttributesProcessor = createDenyListAttributesProcessor; -const NOOP = new NoopAttributesProcessor(); -//# sourceMappingURL=AttributesProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/InstrumentSelector.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/InstrumentSelector.js deleted file mode 100644 index e9f32603..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/InstrumentSelector.js +++ /dev/null @@ -1,40 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.InstrumentSelector = void 0; -const Predicate_1 = require("./Predicate"); -class InstrumentSelector { - _nameFilter; - _type; - _unitFilter; - constructor(criteria) { - this._nameFilter = new Predicate_1.PatternPredicate(criteria?.name ?? '*'); - this._type = criteria?.type; - this._unitFilter = new Predicate_1.ExactPredicate(criteria?.unit); - } - getType() { - return this._type; - } - getNameFilter() { - return this._nameFilter; - } - getUnitFilter() { - return this._unitFilter; - } -} -exports.InstrumentSelector = InstrumentSelector; -//# sourceMappingURL=InstrumentSelector.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/MeterSelector.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/MeterSelector.js deleted file mode 100644 index 5dbaaffc..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/MeterSelector.js +++ /dev/null @@ -1,43 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MeterSelector = void 0; -const Predicate_1 = require("./Predicate"); -class MeterSelector { - _nameFilter; - _versionFilter; - _schemaUrlFilter; - constructor(criteria) { - this._nameFilter = new Predicate_1.ExactPredicate(criteria?.name); - this._versionFilter = new Predicate_1.ExactPredicate(criteria?.version); - this._schemaUrlFilter = new Predicate_1.ExactPredicate(criteria?.schemaUrl); - } - getNameFilter() { - return this._nameFilter; - } - /** - * TODO: semver filter? no spec yet. - */ - getVersionFilter() { - return this._versionFilter; - } - getSchemaUrlFilter() { - return this._schemaUrlFilter; - } -} -exports.MeterSelector = MeterSelector; -//# sourceMappingURL=MeterSelector.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/Predicate.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/Predicate.js deleted file mode 100644 index 287df97c..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/Predicate.js +++ /dev/null @@ -1,71 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ExactPredicate = exports.PatternPredicate = void 0; -// https://tc39.es/proposal-regex-escaping -// escape ^ $ \ . + ? ( ) [ ] { } | -// do not need to escape * as we interpret it as wildcard -const ESCAPE = /[\^$\\.+?()[\]{}|]/g; -/** - * Wildcard pattern predicate, supports patterns like `*`, `foo*`, `*bar`. - */ -class PatternPredicate { - _matchAll; - _regexp; - constructor(pattern) { - if (pattern === '*') { - this._matchAll = true; - this._regexp = /.*/; - } - else { - this._matchAll = false; - this._regexp = new RegExp(PatternPredicate.escapePattern(pattern)); - } - } - match(str) { - if (this._matchAll) { - return true; - } - return this._regexp.test(str); - } - static escapePattern(pattern) { - return `^${pattern.replace(ESCAPE, '\\$&').replace('*', '.*')}$`; - } - static hasWildcard(pattern) { - return pattern.includes('*'); - } -} -exports.PatternPredicate = PatternPredicate; -class ExactPredicate { - _matchAll; - _pattern; - constructor(pattern) { - this._matchAll = pattern === undefined; - this._pattern = pattern; - } - match(str) { - if (this._matchAll) { - return true; - } - if (str === this._pattern) { - return true; - } - return false; - } -} -exports.ExactPredicate = ExactPredicate; -//# sourceMappingURL=Predicate.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/RegistrationConflicts.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/RegistrationConflicts.js deleted file mode 100644 index d9daedb3..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/RegistrationConflicts.js +++ /dev/null @@ -1,85 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getConflictResolutionRecipe = exports.getDescriptionResolutionRecipe = exports.getTypeConflictResolutionRecipe = exports.getUnitConflictResolutionRecipe = exports.getValueTypeConflictResolutionRecipe = exports.getIncompatibilityDetails = void 0; -function getIncompatibilityDetails(existing, otherDescriptor) { - let incompatibility = ''; - if (existing.unit !== otherDescriptor.unit) { - incompatibility += `\t- Unit '${existing.unit}' does not match '${otherDescriptor.unit}'\n`; - } - if (existing.type !== otherDescriptor.type) { - incompatibility += `\t- Type '${existing.type}' does not match '${otherDescriptor.type}'\n`; - } - if (existing.valueType !== otherDescriptor.valueType) { - incompatibility += `\t- Value Type '${existing.valueType}' does not match '${otherDescriptor.valueType}'\n`; - } - if (existing.description !== otherDescriptor.description) { - incompatibility += `\t- Description '${existing.description}' does not match '${otherDescriptor.description}'\n`; - } - return incompatibility; -} -exports.getIncompatibilityDetails = getIncompatibilityDetails; -function getValueTypeConflictResolutionRecipe(existing, otherDescriptor) { - return `\t- use valueType '${existing.valueType}' on instrument creation or use an instrument name other than '${otherDescriptor.name}'`; -} -exports.getValueTypeConflictResolutionRecipe = getValueTypeConflictResolutionRecipe; -function getUnitConflictResolutionRecipe(existing, otherDescriptor) { - return `\t- use unit '${existing.unit}' on instrument creation or use an instrument name other than '${otherDescriptor.name}'`; -} -exports.getUnitConflictResolutionRecipe = getUnitConflictResolutionRecipe; -function getTypeConflictResolutionRecipe(existing, otherDescriptor) { - const selector = { - name: otherDescriptor.name, - type: otherDescriptor.type, - unit: otherDescriptor.unit, - }; - const selectorString = JSON.stringify(selector); - return `\t- create a new view with a name other than '${existing.name}' and InstrumentSelector '${selectorString}'`; -} -exports.getTypeConflictResolutionRecipe = getTypeConflictResolutionRecipe; -function getDescriptionResolutionRecipe(existing, otherDescriptor) { - const selector = { - name: otherDescriptor.name, - type: otherDescriptor.type, - unit: otherDescriptor.unit, - }; - const selectorString = JSON.stringify(selector); - return `\t- create a new view with a name other than '${existing.name}' and InstrumentSelector '${selectorString}' - \t- OR - create a new view with the name ${existing.name} and description '${existing.description}' and InstrumentSelector ${selectorString} - \t- OR - create a new view with the name ${otherDescriptor.name} and description '${existing.description}' and InstrumentSelector ${selectorString}`; -} -exports.getDescriptionResolutionRecipe = getDescriptionResolutionRecipe; -function getConflictResolutionRecipe(existing, otherDescriptor) { - // Conflicts that cannot be solved via views. - if (existing.valueType !== otherDescriptor.valueType) { - return getValueTypeConflictResolutionRecipe(existing, otherDescriptor); - } - if (existing.unit !== otherDescriptor.unit) { - return getUnitConflictResolutionRecipe(existing, otherDescriptor); - } - // Conflicts that can be solved via views. - if (existing.type !== otherDescriptor.type) { - // this will automatically solve possible description conflicts. - return getTypeConflictResolutionRecipe(existing, otherDescriptor); - } - if (existing.description !== otherDescriptor.description) { - return getDescriptionResolutionRecipe(existing, otherDescriptor); - } - return ''; -} -exports.getConflictResolutionRecipe = getConflictResolutionRecipe; -//# sourceMappingURL=RegistrationConflicts.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/View.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/View.js deleted file mode 100644 index 6fbb53c6..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/View.js +++ /dev/null @@ -1,139 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.View = void 0; -const Predicate_1 = require("./Predicate"); -const AttributesProcessor_1 = require("./AttributesProcessor"); -const InstrumentSelector_1 = require("./InstrumentSelector"); -const MeterSelector_1 = require("./MeterSelector"); -const AggregationOption_1 = require("./AggregationOption"); -function isSelectorNotProvided(options) { - return (options.instrumentName == null && - options.instrumentType == null && - options.instrumentUnit == null && - options.meterName == null && - options.meterVersion == null && - options.meterSchemaUrl == null); -} -function validateViewOptions(viewOptions) { - // If no criteria is provided, the SDK SHOULD treat it as an error. - // It is recommended that the SDK implementations fail fast. - if (isSelectorNotProvided(viewOptions)) { - throw new Error('Cannot create view with no selector arguments supplied'); - } - // the SDK SHOULD NOT allow Views with a specified name to be declared with instrument selectors that - // may select more than one instrument (e.g. wild card instrument name) in the same Meter. - if (viewOptions.name != null && - (viewOptions?.instrumentName == null || - Predicate_1.PatternPredicate.hasWildcard(viewOptions.instrumentName))) { - throw new Error('Views with a specified name must be declared with an instrument selector that selects at most one instrument per meter.'); - } -} -/** - * Can be passed to a {@link MeterProvider} to select instruments and alter their metric stream. - */ -class View { - name; - description; - aggregation; - attributesProcessor; - instrumentSelector; - meterSelector; - aggregationCardinalityLimit; - /** - * Create a new {@link View} instance. - * - * Parameters can be categorized as two types: - * Instrument selection criteria: Used to describe the instrument(s) this view will be applied to. - * Will be treated as additive (the Instrument has to meet all the provided criteria to be selected). - * - * Metric stream altering: Alter the metric stream of instruments selected by instrument selection criteria. - * - * @param viewOptions {@link ViewOptions} for altering the metric stream and instrument selection. - * @param viewOptions.name - * Alters the metric stream: - * This will be used as the name of the metrics stream. - * If not provided, the original Instrument name will be used. - * @param viewOptions.description - * Alters the metric stream: - * This will be used as the description of the metrics stream. - * If not provided, the original Instrument description will be used by default. - * @param viewOptions.attributesProcessors - * Alters the metric stream: - * If provided, the attributes will be modified as defined by the added processors. - * If not provided, all attribute keys will be used by default. - * @param viewOptions.aggregationCardinalityLimit - * Alters the metric stream: - * Sets a limit on the number of unique attribute combinations (cardinality) that can be aggregated. - * If not provided, the default limit of 2000 will be used. - * @param viewOptions.aggregation - * Alters the metric stream: - * Alters the {@link Aggregation} of the metric stream. - * @param viewOptions.instrumentName - * Instrument selection criteria: - * Original name of the Instrument(s) with wildcard support. - * @param viewOptions.instrumentType - * Instrument selection criteria: - * The original type of the Instrument(s). - * @param viewOptions.instrumentUnit - * Instrument selection criteria: - * The unit of the Instrument(s). - * @param viewOptions.meterName - * Instrument selection criteria: - * The name of the Meter. No wildcard support, name must match the meter exactly. - * @param viewOptions.meterVersion - * Instrument selection criteria: - * The version of the Meter. No wildcard support, version must match exactly. - * @param viewOptions.meterSchemaUrl - * Instrument selection criteria: - * The schema URL of the Meter. No wildcard support, schema URL must match exactly. - * - * @example - * // Create a view that changes the Instrument 'my.instrument' to use to an - * // ExplicitBucketHistogramAggregation with the boundaries [20, 30, 40] - * new View({ - * aggregation: new ExplicitBucketHistogramAggregation([20, 30, 40]), - * instrumentName: 'my.instrument' - * }) - */ - constructor(viewOptions) { - validateViewOptions(viewOptions); - // Create multi-processor if attributesProcessors are defined. - if (viewOptions.attributesProcessors != null) { - this.attributesProcessor = (0, AttributesProcessor_1.createMultiAttributesProcessor)(viewOptions.attributesProcessors); - } - else { - this.attributesProcessor = (0, AttributesProcessor_1.createNoopAttributesProcessor)(); - } - this.name = viewOptions.name; - this.description = viewOptions.description; - this.aggregation = (0, AggregationOption_1.toAggregation)(viewOptions.aggregation ?? { type: AggregationOption_1.AggregationType.DEFAULT }); - this.instrumentSelector = new InstrumentSelector_1.InstrumentSelector({ - name: viewOptions.instrumentName, - type: viewOptions.instrumentType, - unit: viewOptions.instrumentUnit, - }); - this.meterSelector = new MeterSelector_1.MeterSelector({ - name: viewOptions.meterName, - version: viewOptions.meterVersion, - schemaUrl: viewOptions.meterSchemaUrl, - }); - this.aggregationCardinalityLimit = viewOptions.aggregationCardinalityLimit; - } -} -exports.View = View; -//# sourceMappingURL=View.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/ViewRegistry.js b/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/ViewRegistry.js deleted file mode 100644 index 58c5c632..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-metrics/build/src/view/ViewRegistry.js +++ /dev/null @@ -1,46 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ViewRegistry = void 0; -class ViewRegistry { - _registeredViews = []; - addView(view) { - this._registeredViews.push(view); - } - findViews(instrument, meter) { - const views = this._registeredViews.filter(registeredView => { - return (this._matchInstrument(registeredView.instrumentSelector, instrument) && - this._matchMeter(registeredView.meterSelector, meter)); - }); - return views; - } - _matchInstrument(selector, instrument) { - return ((selector.getType() === undefined || - instrument.type === selector.getType()) && - selector.getNameFilter().match(instrument.name) && - selector.getUnitFilter().match(instrument.unit)); - } - _matchMeter(selector, meter) { - return (selector.getNameFilter().match(meter.name) && - (meter.version === undefined || - selector.getVersionFilter().match(meter.version)) && - (meter.schemaUrl === undefined || - selector.getSchemaUrlFilter().match(meter.schemaUrl))); - } -} -exports.ViewRegistry = ViewRegistry; -//# sourceMappingURL=ViewRegistry.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/BasicTracerProvider.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/BasicTracerProvider.js deleted file mode 100644 index baa41902..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/BasicTracerProvider.js +++ /dev/null @@ -1,104 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BasicTracerProvider = exports.ForceFlushState = void 0; -const core_1 = require("@opentelemetry/core"); -const resources_1 = require("@opentelemetry/resources"); -const Tracer_1 = require("./Tracer"); -const config_1 = require("./config"); -const MultiSpanProcessor_1 = require("./MultiSpanProcessor"); -const utility_1 = require("./utility"); -var ForceFlushState; -(function (ForceFlushState) { - ForceFlushState[ForceFlushState["resolved"] = 0] = "resolved"; - ForceFlushState[ForceFlushState["timeout"] = 1] = "timeout"; - ForceFlushState[ForceFlushState["error"] = 2] = "error"; - ForceFlushState[ForceFlushState["unresolved"] = 3] = "unresolved"; -})(ForceFlushState = exports.ForceFlushState || (exports.ForceFlushState = {})); -/** - * This class represents a basic tracer provider which platform libraries can extend - */ -class BasicTracerProvider { - _config; - _tracers = new Map(); - _resource; - _activeSpanProcessor; - constructor(config = {}) { - const mergedConfig = (0, core_1.merge)({}, (0, config_1.loadDefaultConfig)(), (0, utility_1.reconfigureLimits)(config)); - this._resource = mergedConfig.resource ?? (0, resources_1.defaultResource)(); - this._config = Object.assign({}, mergedConfig, { - resource: this._resource, - }); - const spanProcessors = []; - if (config.spanProcessors?.length) { - spanProcessors.push(...config.spanProcessors); - } - this._activeSpanProcessor = new MultiSpanProcessor_1.MultiSpanProcessor(spanProcessors); - } - getTracer(name, version, options) { - const key = `${name}@${version || ''}:${options?.schemaUrl || ''}`; - if (!this._tracers.has(key)) { - this._tracers.set(key, new Tracer_1.Tracer({ name, version, schemaUrl: options?.schemaUrl }, this._config, this._resource, this._activeSpanProcessor)); - } - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - return this._tracers.get(key); - } - forceFlush() { - const timeout = this._config.forceFlushTimeoutMillis; - const promises = this._activeSpanProcessor['_spanProcessors'].map((spanProcessor) => { - return new Promise(resolve => { - let state; - const timeoutInterval = setTimeout(() => { - resolve(new Error(`Span processor did not completed within timeout period of ${timeout} ms`)); - state = ForceFlushState.timeout; - }, timeout); - spanProcessor - .forceFlush() - .then(() => { - clearTimeout(timeoutInterval); - if (state !== ForceFlushState.timeout) { - state = ForceFlushState.resolved; - resolve(state); - } - }) - .catch(error => { - clearTimeout(timeoutInterval); - state = ForceFlushState.error; - resolve(error); - }); - }); - }); - return new Promise((resolve, reject) => { - Promise.all(promises) - .then(results => { - const errors = results.filter(result => result !== ForceFlushState.resolved); - if (errors.length > 0) { - reject(errors); - } - else { - resolve(); - } - }) - .catch(error => reject([error])); - }); - } - shutdown() { - return this._activeSpanProcessor.shutdown(); - } -} -exports.BasicTracerProvider = BasicTracerProvider; -//# sourceMappingURL=BasicTracerProvider.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/MultiSpanProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/MultiSpanProcessor.js deleted file mode 100644 index de577b79..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/MultiSpanProcessor.js +++ /dev/null @@ -1,68 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.MultiSpanProcessor = void 0; -const core_1 = require("@opentelemetry/core"); -/** - * Implementation of the {@link SpanProcessor} that simply forwards all - * received events to a list of {@link SpanProcessor}s. - */ -class MultiSpanProcessor { - _spanProcessors; - constructor(_spanProcessors) { - this._spanProcessors = _spanProcessors; - } - forceFlush() { - const promises = []; - for (const spanProcessor of this._spanProcessors) { - promises.push(spanProcessor.forceFlush()); - } - return new Promise(resolve => { - Promise.all(promises) - .then(() => { - resolve(); - }) - .catch(error => { - (0, core_1.globalErrorHandler)(error || new Error('MultiSpanProcessor: forceFlush failed')); - resolve(); - }); - }); - } - onStart(span, context) { - for (const spanProcessor of this._spanProcessors) { - spanProcessor.onStart(span, context); - } - } - onEnd(span) { - for (const spanProcessor of this._spanProcessors) { - spanProcessor.onEnd(span); - } - } - shutdown() { - const promises = []; - for (const spanProcessor of this._spanProcessors) { - promises.push(spanProcessor.shutdown()); - } - return new Promise((resolve, reject) => { - Promise.all(promises).then(() => { - resolve(); - }, reject); - }); - } -} -exports.MultiSpanProcessor = MultiSpanProcessor; -//# sourceMappingURL=MultiSpanProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Sampler.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Sampler.js deleted file mode 100644 index ddb4b599..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Sampler.js +++ /dev/null @@ -1,41 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SamplingDecision = void 0; -/** - * A sampling decision that determines how a {@link Span} will be recorded - * and collected. - */ -var SamplingDecision; -(function (SamplingDecision) { - /** - * `Span.isRecording() === false`, span will not be recorded and all events - * and attributes will be dropped. - */ - SamplingDecision[SamplingDecision["NOT_RECORD"] = 0] = "NOT_RECORD"; - /** - * `Span.isRecording() === true`, but `Sampled` flag in {@link TraceFlags} - * MUST NOT be set. - */ - SamplingDecision[SamplingDecision["RECORD"] = 1] = "RECORD"; - /** - * `Span.isRecording() === true` AND `Sampled` flag in {@link TraceFlags} - * MUST be set. - */ - SamplingDecision[SamplingDecision["RECORD_AND_SAMPLED"] = 2] = "RECORD_AND_SAMPLED"; -})(SamplingDecision = exports.SamplingDecision || (exports.SamplingDecision = {})); -//# sourceMappingURL=Sampler.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Span.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Span.js deleted file mode 100644 index 5a807fe2..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Span.js +++ /dev/null @@ -1,312 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SpanImpl = void 0; -const api_1 = require("@opentelemetry/api"); -const core_1 = require("@opentelemetry/core"); -const semantic_conventions_1 = require("@opentelemetry/semantic-conventions"); -const enums_1 = require("./enums"); -/** - * This class represents a span. - */ -class SpanImpl { - // Below properties are included to implement ReadableSpan for export - // purposes but are not intended to be written-to directly. - _spanContext; - kind; - parentSpanContext; - attributes = {}; - links = []; - events = []; - startTime; - resource; - instrumentationScope; - _droppedAttributesCount = 0; - _droppedEventsCount = 0; - _droppedLinksCount = 0; - name; - status = { - code: api_1.SpanStatusCode.UNSET, - }; - endTime = [0, 0]; - _ended = false; - _duration = [-1, -1]; - _spanProcessor; - _spanLimits; - _attributeValueLengthLimit; - _performanceStartTime; - _performanceOffset; - _startTimeProvided; - /** - * Constructs a new SpanImpl instance. - */ - constructor(opts) { - const now = Date.now(); - this._spanContext = opts.spanContext; - this._performanceStartTime = core_1.otperformance.now(); - this._performanceOffset = - now - (this._performanceStartTime + (0, core_1.getTimeOrigin)()); - this._startTimeProvided = opts.startTime != null; - this._spanLimits = opts.spanLimits; - this._attributeValueLengthLimit = - this._spanLimits.attributeValueLengthLimit || 0; - this._spanProcessor = opts.spanProcessor; - this.name = opts.name; - this.parentSpanContext = opts.parentSpanContext; - this.kind = opts.kind; - this.links = opts.links || []; - this.startTime = this._getTime(opts.startTime ?? now); - this.resource = opts.resource; - this.instrumentationScope = opts.scope; - if (opts.attributes != null) { - this.setAttributes(opts.attributes); - } - this._spanProcessor.onStart(this, opts.context); - } - spanContext() { - return this._spanContext; - } - setAttribute(key, value) { - if (value == null || this._isSpanEnded()) - return this; - if (key.length === 0) { - api_1.diag.warn(`Invalid attribute key: ${key}`); - return this; - } - if (!(0, core_1.isAttributeValue)(value)) { - api_1.diag.warn(`Invalid attribute value set for key: ${key}`); - return this; - } - const { attributeCountLimit } = this._spanLimits; - if (attributeCountLimit !== undefined && - Object.keys(this.attributes).length >= attributeCountLimit && - !Object.prototype.hasOwnProperty.call(this.attributes, key)) { - this._droppedAttributesCount++; - return this; - } - this.attributes[key] = this._truncateToSize(value); - return this; - } - setAttributes(attributes) { - for (const [k, v] of Object.entries(attributes)) { - this.setAttribute(k, v); - } - return this; - } - /** - * - * @param name Span Name - * @param [attributesOrStartTime] Span attributes or start time - * if type is {@type TimeInput} and 3rd param is undefined - * @param [timeStamp] Specified time stamp for the event - */ - addEvent(name, attributesOrStartTime, timeStamp) { - if (this._isSpanEnded()) - return this; - const { eventCountLimit } = this._spanLimits; - if (eventCountLimit === 0) { - api_1.diag.warn('No events allowed.'); - this._droppedEventsCount++; - return this; - } - if (eventCountLimit !== undefined && - this.events.length >= eventCountLimit) { - if (this._droppedEventsCount === 0) { - api_1.diag.debug('Dropping extra events.'); - } - this.events.shift(); - this._droppedEventsCount++; - } - if ((0, core_1.isTimeInput)(attributesOrStartTime)) { - if (!(0, core_1.isTimeInput)(timeStamp)) { - timeStamp = attributesOrStartTime; - } - attributesOrStartTime = undefined; - } - const attributes = (0, core_1.sanitizeAttributes)(attributesOrStartTime); - this.events.push({ - name, - attributes, - time: this._getTime(timeStamp), - droppedAttributesCount: 0, - }); - return this; - } - addLink(link) { - this.links.push(link); - return this; - } - addLinks(links) { - this.links.push(...links); - return this; - } - setStatus(status) { - if (this._isSpanEnded()) - return this; - this.status = { ...status }; - // When using try-catch, the caught "error" is of type `any`. When then assigning `any` to `status.message`, - // TypeScript will not error. While this can happen during use of any API, it is more common on Span#setStatus() - // as it's likely used in a catch-block. Therefore, we validate if `status.message` is actually a string, null, or - // undefined to avoid an incorrect type causing issues downstream. - if (this.status.message != null && typeof status.message !== 'string') { - api_1.diag.warn(`Dropping invalid status.message of type '${typeof status.message}', expected 'string'`); - delete this.status.message; - } - return this; - } - updateName(name) { - if (this._isSpanEnded()) - return this; - this.name = name; - return this; - } - end(endTime) { - if (this._isSpanEnded()) { - api_1.diag.error(`${this.name} ${this._spanContext.traceId}-${this._spanContext.spanId} - You can only call end() on a span once.`); - return; - } - this._ended = true; - this.endTime = this._getTime(endTime); - this._duration = (0, core_1.hrTimeDuration)(this.startTime, this.endTime); - if (this._duration[0] < 0) { - api_1.diag.warn('Inconsistent start and end time, startTime > endTime. Setting span duration to 0ms.', this.startTime, this.endTime); - this.endTime = this.startTime.slice(); - this._duration = [0, 0]; - } - if (this._droppedEventsCount > 0) { - api_1.diag.warn(`Dropped ${this._droppedEventsCount} events because eventCountLimit reached`); - } - this._spanProcessor.onEnd(this); - } - _getTime(inp) { - if (typeof inp === 'number' && inp <= core_1.otperformance.now()) { - // must be a performance timestamp - // apply correction and convert to hrtime - return (0, core_1.hrTime)(inp + this._performanceOffset); - } - if (typeof inp === 'number') { - return (0, core_1.millisToHrTime)(inp); - } - if (inp instanceof Date) { - return (0, core_1.millisToHrTime)(inp.getTime()); - } - if ((0, core_1.isTimeInputHrTime)(inp)) { - return inp; - } - if (this._startTimeProvided) { - // if user provided a time for the start manually - // we can't use duration to calculate event/end times - return (0, core_1.millisToHrTime)(Date.now()); - } - const msDuration = core_1.otperformance.now() - this._performanceStartTime; - return (0, core_1.addHrTimes)(this.startTime, (0, core_1.millisToHrTime)(msDuration)); - } - isRecording() { - return this._ended === false; - } - recordException(exception, time) { - const attributes = {}; - if (typeof exception === 'string') { - attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE] = exception; - } - else if (exception) { - if (exception.code) { - attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] = exception.code.toString(); - } - else if (exception.name) { - attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] = exception.name; - } - if (exception.message) { - attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE] = exception.message; - } - if (exception.stack) { - attributes[semantic_conventions_1.ATTR_EXCEPTION_STACKTRACE] = exception.stack; - } - } - // these are minimum requirements from spec - if (attributes[semantic_conventions_1.ATTR_EXCEPTION_TYPE] || attributes[semantic_conventions_1.ATTR_EXCEPTION_MESSAGE]) { - this.addEvent(enums_1.ExceptionEventName, attributes, time); - } - else { - api_1.diag.warn(`Failed to record an exception ${exception}`); - } - } - get duration() { - return this._duration; - } - get ended() { - return this._ended; - } - get droppedAttributesCount() { - return this._droppedAttributesCount; - } - get droppedEventsCount() { - return this._droppedEventsCount; - } - get droppedLinksCount() { - return this._droppedLinksCount; - } - _isSpanEnded() { - if (this._ended) { - const error = new Error(`Operation attempted on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`); - api_1.diag.warn(`Cannot execute the operation on ended Span {traceId: ${this._spanContext.traceId}, spanId: ${this._spanContext.spanId}}`, error); - } - return this._ended; - } - // Utility function to truncate given value within size - // for value type of string, will truncate to given limit - // for type of non-string, will return same value - _truncateToLimitUtil(value, limit) { - if (value.length <= limit) { - return value; - } - return value.substring(0, limit); - } - /** - * If the given attribute value is of type string and has more characters than given {@code attributeValueLengthLimit} then - * return string with truncated to {@code attributeValueLengthLimit} characters - * - * If the given attribute value is array of strings then - * return new array of strings with each element truncated to {@code attributeValueLengthLimit} characters - * - * Otherwise return same Attribute {@code value} - * - * @param value Attribute value - * @returns truncated attribute value if required, otherwise same value - */ - _truncateToSize(value) { - const limit = this._attributeValueLengthLimit; - // Check limit - if (limit <= 0) { - // Negative values are invalid, so do not truncate - api_1.diag.warn(`Attribute value limit must be positive, got ${limit}`); - return value; - } - // String - if (typeof value === 'string') { - return this._truncateToLimitUtil(value, limit); - } - // Array of strings - if (Array.isArray(value)) { - return value.map(val => typeof val === 'string' ? this._truncateToLimitUtil(val, limit) : val); - } - // Other types, no need to apply value length limit - return value; - } -} -exports.SpanImpl = SpanImpl; -//# sourceMappingURL=Span.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Tracer.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Tracer.js deleted file mode 100644 index ec08e4a6..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/Tracer.js +++ /dev/null @@ -1,152 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Tracer = void 0; -const api = require("@opentelemetry/api"); -const core_1 = require("@opentelemetry/core"); -const Span_1 = require("./Span"); -const utility_1 = require("./utility"); -const platform_1 = require("./platform"); -/** - * This class represents a basic tracer. - */ -class Tracer { - _sampler; - _generalLimits; - _spanLimits; - _idGenerator; - instrumentationScope; - _resource; - _spanProcessor; - /** - * Constructs a new Tracer instance. - */ - constructor(instrumentationScope, config, resource, spanProcessor) { - const localConfig = (0, utility_1.mergeConfig)(config); - this._sampler = localConfig.sampler; - this._generalLimits = localConfig.generalLimits; - this._spanLimits = localConfig.spanLimits; - this._idGenerator = config.idGenerator || new platform_1.RandomIdGenerator(); - this._resource = resource; - this._spanProcessor = spanProcessor; - this.instrumentationScope = instrumentationScope; - } - /** - * Starts a new Span or returns the default NoopSpan based on the sampling - * decision. - */ - startSpan(name, options = {}, context = api.context.active()) { - // remove span from context in case a root span is requested via options - if (options.root) { - context = api.trace.deleteSpan(context); - } - const parentSpan = api.trace.getSpan(context); - if ((0, core_1.isTracingSuppressed)(context)) { - api.diag.debug('Instrumentation suppressed, returning Noop Span'); - const nonRecordingSpan = api.trace.wrapSpanContext(api.INVALID_SPAN_CONTEXT); - return nonRecordingSpan; - } - const parentSpanContext = parentSpan?.spanContext(); - const spanId = this._idGenerator.generateSpanId(); - let validParentSpanContext; - let traceId; - let traceState; - if (!parentSpanContext || - !api.trace.isSpanContextValid(parentSpanContext)) { - // New root span. - traceId = this._idGenerator.generateTraceId(); - } - else { - // New child span. - traceId = parentSpanContext.traceId; - traceState = parentSpanContext.traceState; - validParentSpanContext = parentSpanContext; - } - const spanKind = options.kind ?? api.SpanKind.INTERNAL; - const links = (options.links ?? []).map(link => { - return { - context: link.context, - attributes: (0, core_1.sanitizeAttributes)(link.attributes), - }; - }); - const attributes = (0, core_1.sanitizeAttributes)(options.attributes); - // make sampling decision - const samplingResult = this._sampler.shouldSample(context, traceId, name, spanKind, attributes, links); - traceState = samplingResult.traceState ?? traceState; - const traceFlags = samplingResult.decision === api.SamplingDecision.RECORD_AND_SAMPLED - ? api.TraceFlags.SAMPLED - : api.TraceFlags.NONE; - const spanContext = { traceId, spanId, traceFlags, traceState }; - if (samplingResult.decision === api.SamplingDecision.NOT_RECORD) { - api.diag.debug('Recording is off, propagating context in a non-recording span'); - const nonRecordingSpan = api.trace.wrapSpanContext(spanContext); - return nonRecordingSpan; - } - // Set initial span attributes. The attributes object may have been mutated - // by the sampler, so we sanitize the merged attributes before setting them. - const initAttributes = (0, core_1.sanitizeAttributes)(Object.assign(attributes, samplingResult.attributes)); - const span = new Span_1.SpanImpl({ - resource: this._resource, - scope: this.instrumentationScope, - context, - spanContext, - name, - kind: spanKind, - links, - parentSpanContext: validParentSpanContext, - attributes: initAttributes, - startTime: options.startTime, - spanProcessor: this._spanProcessor, - spanLimits: this._spanLimits, - }); - return span; - } - startActiveSpan(name, arg2, arg3, arg4) { - let opts; - let ctx; - let fn; - if (arguments.length < 2) { - return; - } - else if (arguments.length === 2) { - fn = arg2; - } - else if (arguments.length === 3) { - opts = arg2; - fn = arg3; - } - else { - opts = arg2; - ctx = arg3; - fn = arg4; - } - const parentContext = ctx ?? api.context.active(); - const span = this.startSpan(name, opts, parentContext); - const contextWithSpanSet = api.trace.setSpan(parentContext, span); - return api.context.with(contextWithSpanSet, fn, undefined, span); - } - /** Returns the active {@link GeneralLimits}. */ - getGeneralLimits() { - return this._generalLimits; - } - /** Returns the active {@link SpanLimits}. */ - getSpanLimits() { - return this._spanLimits; - } -} -exports.Tracer = Tracer; -//# sourceMappingURL=Tracer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/config.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/config.js deleted file mode 100644 index 118b84af..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/config.js +++ /dev/null @@ -1,107 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.buildSamplerFromEnv = exports.loadDefaultConfig = void 0; -const api_1 = require("@opentelemetry/api"); -const core_1 = require("@opentelemetry/core"); -const AlwaysOffSampler_1 = require("./sampler/AlwaysOffSampler"); -const AlwaysOnSampler_1 = require("./sampler/AlwaysOnSampler"); -const ParentBasedSampler_1 = require("./sampler/ParentBasedSampler"); -const TraceIdRatioBasedSampler_1 = require("./sampler/TraceIdRatioBasedSampler"); -var TracesSamplerValues; -(function (TracesSamplerValues) { - TracesSamplerValues["AlwaysOff"] = "always_off"; - TracesSamplerValues["AlwaysOn"] = "always_on"; - TracesSamplerValues["ParentBasedAlwaysOff"] = "parentbased_always_off"; - TracesSamplerValues["ParentBasedAlwaysOn"] = "parentbased_always_on"; - TracesSamplerValues["ParentBasedTraceIdRatio"] = "parentbased_traceidratio"; - TracesSamplerValues["TraceIdRatio"] = "traceidratio"; -})(TracesSamplerValues || (TracesSamplerValues = {})); -const DEFAULT_RATIO = 1; -/** - * Load default configuration. For fields with primitive values, any user-provided - * value will override the corresponding default value. For fields with - * non-primitive values (like `spanLimits`), the user-provided value will be - * used to extend the default value. - */ -// object needs to be wrapped in this function and called when needed otherwise -// envs are parsed before tests are ran - causes tests using these envs to fail -function loadDefaultConfig() { - return { - sampler: buildSamplerFromEnv(), - forceFlushTimeoutMillis: 30000, - generalLimits: { - attributeValueLengthLimit: (0, core_1.getNumberFromEnv)('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity, - attributeCountLimit: (0, core_1.getNumberFromEnv)('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? 128, - }, - spanLimits: { - attributeValueLengthLimit: (0, core_1.getNumberFromEnv)('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? Infinity, - attributeCountLimit: (0, core_1.getNumberFromEnv)('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ?? 128, - linkCountLimit: (0, core_1.getNumberFromEnv)('OTEL_SPAN_LINK_COUNT_LIMIT') ?? 128, - eventCountLimit: (0, core_1.getNumberFromEnv)('OTEL_SPAN_EVENT_COUNT_LIMIT') ?? 128, - attributePerEventCountLimit: (0, core_1.getNumberFromEnv)('OTEL_SPAN_ATTRIBUTE_PER_EVENT_COUNT_LIMIT') ?? 128, - attributePerLinkCountLimit: (0, core_1.getNumberFromEnv)('OTEL_SPAN_ATTRIBUTE_PER_LINK_COUNT_LIMIT') ?? 128, - }, - }; -} -exports.loadDefaultConfig = loadDefaultConfig; -/** - * Based on environment, builds a sampler, complies with specification. - */ -function buildSamplerFromEnv() { - const sampler = (0, core_1.getStringFromEnv)('OTEL_TRACES_SAMPLER') ?? - TracesSamplerValues.ParentBasedAlwaysOn; - switch (sampler) { - case TracesSamplerValues.AlwaysOn: - return new AlwaysOnSampler_1.AlwaysOnSampler(); - case TracesSamplerValues.AlwaysOff: - return new AlwaysOffSampler_1.AlwaysOffSampler(); - case TracesSamplerValues.ParentBasedAlwaysOn: - return new ParentBasedSampler_1.ParentBasedSampler({ - root: new AlwaysOnSampler_1.AlwaysOnSampler(), - }); - case TracesSamplerValues.ParentBasedAlwaysOff: - return new ParentBasedSampler_1.ParentBasedSampler({ - root: new AlwaysOffSampler_1.AlwaysOffSampler(), - }); - case TracesSamplerValues.TraceIdRatio: - return new TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()); - case TracesSamplerValues.ParentBasedTraceIdRatio: - return new ParentBasedSampler_1.ParentBasedSampler({ - root: new TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler(getSamplerProbabilityFromEnv()), - }); - default: - api_1.diag.error(`OTEL_TRACES_SAMPLER value "${sampler}" invalid, defaulting to "${TracesSamplerValues.ParentBasedAlwaysOn}".`); - return new ParentBasedSampler_1.ParentBasedSampler({ - root: new AlwaysOnSampler_1.AlwaysOnSampler(), - }); - } -} -exports.buildSamplerFromEnv = buildSamplerFromEnv; -function getSamplerProbabilityFromEnv() { - const probability = (0, core_1.getNumberFromEnv)('OTEL_TRACES_SAMPLER_ARG'); - if (probability == null) { - api_1.diag.error(`OTEL_TRACES_SAMPLER_ARG is blank, defaulting to ${DEFAULT_RATIO}.`); - return DEFAULT_RATIO; - } - if (probability < 0 || probability > 1) { - api_1.diag.error(`OTEL_TRACES_SAMPLER_ARG=${probability} was given, but it is out of range ([0..1]), defaulting to ${DEFAULT_RATIO}.`); - return DEFAULT_RATIO; - } - return probability; -} -//# sourceMappingURL=config.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/enums.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/enums.js deleted file mode 100644 index aecbce0b..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/enums.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ExceptionEventName = void 0; -// Event name definitions -exports.ExceptionEventName = 'exception'; -//# sourceMappingURL=enums.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/BatchSpanProcessorBase.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/BatchSpanProcessorBase.js deleted file mode 100644 index 255baeec..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/BatchSpanProcessorBase.js +++ /dev/null @@ -1,223 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BatchSpanProcessorBase = void 0; -const api_1 = require("@opentelemetry/api"); -const core_1 = require("@opentelemetry/core"); -/** - * Implementation of the {@link SpanProcessor} that batches spans exported by - * the SDK then pushes them to the exporter pipeline. - */ -class BatchSpanProcessorBase { - _exporter; - _maxExportBatchSize; - _maxQueueSize; - _scheduledDelayMillis; - _exportTimeoutMillis; - _isExporting = false; - _finishedSpans = []; - _timer; - _shutdownOnce; - _droppedSpansCount = 0; - constructor(_exporter, config) { - this._exporter = _exporter; - this._maxExportBatchSize = - typeof config?.maxExportBatchSize === 'number' - ? config.maxExportBatchSize - : ((0, core_1.getNumberFromEnv)('OTEL_BSP_MAX_EXPORT_BATCH_SIZE') ?? 512); - this._maxQueueSize = - typeof config?.maxQueueSize === 'number' - ? config.maxQueueSize - : ((0, core_1.getNumberFromEnv)('OTEL_BSP_MAX_QUEUE_SIZE') ?? 2048); - this._scheduledDelayMillis = - typeof config?.scheduledDelayMillis === 'number' - ? config.scheduledDelayMillis - : ((0, core_1.getNumberFromEnv)('OTEL_BSP_SCHEDULE_DELAY') ?? 5000); - this._exportTimeoutMillis = - typeof config?.exportTimeoutMillis === 'number' - ? config.exportTimeoutMillis - : ((0, core_1.getNumberFromEnv)('OTEL_BSP_EXPORT_TIMEOUT') ?? 30000); - this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this); - if (this._maxExportBatchSize > this._maxQueueSize) { - api_1.diag.warn('BatchSpanProcessor: maxExportBatchSize must be smaller or equal to maxQueueSize, setting maxExportBatchSize to match maxQueueSize'); - this._maxExportBatchSize = this._maxQueueSize; - } - } - forceFlush() { - if (this._shutdownOnce.isCalled) { - return this._shutdownOnce.promise; - } - return this._flushAll(); - } - // does nothing. - onStart(_span, _parentContext) { } - onEnd(span) { - if (this._shutdownOnce.isCalled) { - return; - } - if ((span.spanContext().traceFlags & api_1.TraceFlags.SAMPLED) === 0) { - return; - } - this._addToBuffer(span); - } - shutdown() { - return this._shutdownOnce.call(); - } - _shutdown() { - return Promise.resolve() - .then(() => { - return this.onShutdown(); - }) - .then(() => { - return this._flushAll(); - }) - .then(() => { - return this._exporter.shutdown(); - }); - } - /** Add a span in the buffer. */ - _addToBuffer(span) { - if (this._finishedSpans.length >= this._maxQueueSize) { - // limit reached, drop span - if (this._droppedSpansCount === 0) { - api_1.diag.debug('maxQueueSize reached, dropping spans'); - } - this._droppedSpansCount++; - return; - } - if (this._droppedSpansCount > 0) { - // some spans were dropped, log once with count of spans dropped - api_1.diag.warn(`Dropped ${this._droppedSpansCount} spans because maxQueueSize reached`); - this._droppedSpansCount = 0; - } - this._finishedSpans.push(span); - this._maybeStartTimer(); - } - /** - * Send all spans to the exporter respecting the batch size limit - * This function is used only on forceFlush or shutdown, - * for all other cases _flush should be used - * */ - _flushAll() { - return new Promise((resolve, reject) => { - const promises = []; - // calculate number of batches - const count = Math.ceil(this._finishedSpans.length / this._maxExportBatchSize); - for (let i = 0, j = count; i < j; i++) { - promises.push(this._flushOneBatch()); - } - Promise.all(promises) - .then(() => { - resolve(); - }) - .catch(reject); - }); - } - _flushOneBatch() { - this._clearTimer(); - if (this._finishedSpans.length === 0) { - return Promise.resolve(); - } - return new Promise((resolve, reject) => { - const timer = setTimeout(() => { - // don't wait anymore for export, this way the next batch can start - reject(new Error('Timeout')); - }, this._exportTimeoutMillis); - // prevent downstream exporter calls from generating spans - api_1.context.with((0, core_1.suppressTracing)(api_1.context.active()), () => { - // Reset the finished spans buffer here because the next invocations of the _flush method - // could pass the same finished spans to the exporter if the buffer is cleared - // outside the execution of this callback. - let spans; - if (this._finishedSpans.length <= this._maxExportBatchSize) { - spans = this._finishedSpans; - this._finishedSpans = []; - } - else { - spans = this._finishedSpans.splice(0, this._maxExportBatchSize); - } - const doExport = () => this._exporter.export(spans, result => { - clearTimeout(timer); - if (result.code === core_1.ExportResultCode.SUCCESS) { - resolve(); - } - else { - reject(result.error ?? - new Error('BatchSpanProcessor: span export failed')); - } - }); - let pendingResources = null; - for (let i = 0, len = spans.length; i < len; i++) { - const span = spans[i]; - if (span.resource.asyncAttributesPending && - span.resource.waitForAsyncAttributes) { - pendingResources ??= []; - pendingResources.push(span.resource.waitForAsyncAttributes()); - } - } - // Avoid scheduling a promise to make the behavior more predictable and easier to test - if (pendingResources === null) { - doExport(); - } - else { - Promise.all(pendingResources).then(doExport, err => { - (0, core_1.globalErrorHandler)(err); - reject(err); - }); - } - }); - }); - } - _maybeStartTimer() { - if (this._isExporting) - return; - const flush = () => { - this._isExporting = true; - this._flushOneBatch() - .finally(() => { - this._isExporting = false; - if (this._finishedSpans.length > 0) { - this._clearTimer(); - this._maybeStartTimer(); - } - }) - .catch(e => { - this._isExporting = false; - (0, core_1.globalErrorHandler)(e); - }); - }; - // we only wait if the queue doesn't have enough elements yet - if (this._finishedSpans.length >= this._maxExportBatchSize) { - return flush(); - } - if (this._timer !== undefined) - return; - this._timer = setTimeout(() => flush(), this._scheduledDelayMillis); - // depending on runtime, this may be a 'number' or NodeJS.Timeout - if (typeof this._timer !== 'number') { - this._timer.unref(); - } - } - _clearTimer() { - if (this._timer !== undefined) { - clearTimeout(this._timer); - this._timer = undefined; - } - } -} -exports.BatchSpanProcessorBase = BatchSpanProcessorBase; -//# sourceMappingURL=BatchSpanProcessorBase.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/ConsoleSpanExporter.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/ConsoleSpanExporter.js deleted file mode 100644 index 7f22fd96..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/ConsoleSpanExporter.js +++ /dev/null @@ -1,88 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ConsoleSpanExporter = void 0; -const core_1 = require("@opentelemetry/core"); -/** - * This is implementation of {@link SpanExporter} that prints spans to the - * console. This class can be used for diagnostic purposes. - * - * NOTE: This {@link SpanExporter} is intended for diagnostics use only, output rendered to the console may change at any time. - */ -/* eslint-disable no-console */ -class ConsoleSpanExporter { - /** - * Export spans. - * @param spans - * @param resultCallback - */ - export(spans, resultCallback) { - return this._sendSpans(spans, resultCallback); - } - /** - * Shutdown the exporter. - */ - shutdown() { - this._sendSpans([]); - return this.forceFlush(); - } - /** - * Exports any pending spans in exporter - */ - forceFlush() { - return Promise.resolve(); - } - /** - * converts span info into more readable format - * @param span - */ - _exportInfo(span) { - return { - resource: { - attributes: span.resource.attributes, - }, - instrumentationScope: span.instrumentationScope, - traceId: span.spanContext().traceId, - parentSpanContext: span.parentSpanContext, - traceState: span.spanContext().traceState?.serialize(), - name: span.name, - id: span.spanContext().spanId, - kind: span.kind, - timestamp: (0, core_1.hrTimeToMicroseconds)(span.startTime), - duration: (0, core_1.hrTimeToMicroseconds)(span.duration), - attributes: span.attributes, - status: span.status, - events: span.events, - links: span.links, - }; - } - /** - * Showing spans in console - * @param spans - * @param done - */ - _sendSpans(spans, done) { - for (const span of spans) { - console.dir(this._exportInfo(span), { depth: 3 }); - } - if (done) { - return done({ code: core_1.ExportResultCode.SUCCESS }); - } - } -} -exports.ConsoleSpanExporter = ConsoleSpanExporter; -//# sourceMappingURL=ConsoleSpanExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/InMemorySpanExporter.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/InMemorySpanExporter.js deleted file mode 100644 index f8344647..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/InMemorySpanExporter.js +++ /dev/null @@ -1,60 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.InMemorySpanExporter = void 0; -const core_1 = require("@opentelemetry/core"); -/** - * This class can be used for testing purposes. It stores the exported spans - * in a list in memory that can be retrieved using the `getFinishedSpans()` - * method. - */ -class InMemorySpanExporter { - _finishedSpans = []; - /** - * Indicates if the exporter has been "shutdown." - * When false, exported spans will not be stored in-memory. - */ - _stopped = false; - export(spans, resultCallback) { - if (this._stopped) - return resultCallback({ - code: core_1.ExportResultCode.FAILED, - error: new Error('Exporter has been stopped'), - }); - this._finishedSpans.push(...spans); - setTimeout(() => resultCallback({ code: core_1.ExportResultCode.SUCCESS }), 0); - } - shutdown() { - this._stopped = true; - this._finishedSpans = []; - return this.forceFlush(); - } - /** - * Exports any pending spans in the exporter - */ - forceFlush() { - return Promise.resolve(); - } - reset() { - this._finishedSpans = []; - } - getFinishedSpans() { - return this._finishedSpans; - } -} -exports.InMemorySpanExporter = InMemorySpanExporter; -//# sourceMappingURL=InMemorySpanExporter.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/NoopSpanProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/NoopSpanProcessor.js deleted file mode 100644 index d0778657..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/NoopSpanProcessor.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.NoopSpanProcessor = void 0; -/** No-op implementation of SpanProcessor */ -class NoopSpanProcessor { - onStart(_span, _context) { } - onEnd(_span) { } - shutdown() { - return Promise.resolve(); - } - forceFlush() { - return Promise.resolve(); - } -} -exports.NoopSpanProcessor = NoopSpanProcessor; -//# sourceMappingURL=NoopSpanProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/SimpleSpanProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/SimpleSpanProcessor.js deleted file mode 100644 index 312a3be4..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/export/SimpleSpanProcessor.js +++ /dev/null @@ -1,76 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SimpleSpanProcessor = void 0; -const api_1 = require("@opentelemetry/api"); -const core_1 = require("@opentelemetry/core"); -/** - * An implementation of the {@link SpanProcessor} that converts the {@link Span} - * to {@link ReadableSpan} and passes it to the configured exporter. - * - * Only spans that are sampled are converted. - * - * NOTE: This {@link SpanProcessor} exports every ended span individually instead of batching spans together, which causes significant performance overhead with most exporters. For production use, please consider using the {@link BatchSpanProcessor} instead. - */ -class SimpleSpanProcessor { - _exporter; - _shutdownOnce; - _pendingExports; - constructor(_exporter) { - this._exporter = _exporter; - this._shutdownOnce = new core_1.BindOnceFuture(this._shutdown, this); - this._pendingExports = new Set(); - } - async forceFlush() { - await Promise.all(Array.from(this._pendingExports)); - if (this._exporter.forceFlush) { - await this._exporter.forceFlush(); - } - } - onStart(_span, _parentContext) { } - onEnd(span) { - if (this._shutdownOnce.isCalled) { - return; - } - if ((span.spanContext().traceFlags & api_1.TraceFlags.SAMPLED) === 0) { - return; - } - const pendingExport = this._doExport(span).catch(err => (0, core_1.globalErrorHandler)(err)); - // Enqueue this export to the pending list so it can be flushed by the user. - this._pendingExports.add(pendingExport); - void pendingExport.finally(() => this._pendingExports.delete(pendingExport)); - } - async _doExport(span) { - if (span.resource.asyncAttributesPending) { - // Ensure resource is fully resolved before exporting. - await span.resource.waitForAsyncAttributes?.(); - } - const result = await core_1.internal._export(this._exporter, [span]); - if (result.code !== core_1.ExportResultCode.SUCCESS) { - throw (result.error ?? - new Error(`SimpleSpanProcessor: span export failed (status ${result})`)); - } - } - shutdown() { - return this._shutdownOnce.call(); - } - _shutdown() { - return this._exporter.shutdown(); - } -} -exports.SimpleSpanProcessor = SimpleSpanProcessor; -//# sourceMappingURL=SimpleSpanProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/index.js deleted file mode 100644 index 632f563f..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/index.js +++ /dev/null @@ -1,42 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SamplingDecision = exports.TraceIdRatioBasedSampler = exports.ParentBasedSampler = exports.AlwaysOnSampler = exports.AlwaysOffSampler = exports.NoopSpanProcessor = exports.SimpleSpanProcessor = exports.InMemorySpanExporter = exports.ConsoleSpanExporter = exports.RandomIdGenerator = exports.BatchSpanProcessor = exports.BasicTracerProvider = void 0; -var BasicTracerProvider_1 = require("./BasicTracerProvider"); -Object.defineProperty(exports, "BasicTracerProvider", { enumerable: true, get: function () { return BasicTracerProvider_1.BasicTracerProvider; } }); -var platform_1 = require("./platform"); -Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: function () { return platform_1.BatchSpanProcessor; } }); -Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: function () { return platform_1.RandomIdGenerator; } }); -var ConsoleSpanExporter_1 = require("./export/ConsoleSpanExporter"); -Object.defineProperty(exports, "ConsoleSpanExporter", { enumerable: true, get: function () { return ConsoleSpanExporter_1.ConsoleSpanExporter; } }); -var InMemorySpanExporter_1 = require("./export/InMemorySpanExporter"); -Object.defineProperty(exports, "InMemorySpanExporter", { enumerable: true, get: function () { return InMemorySpanExporter_1.InMemorySpanExporter; } }); -var SimpleSpanProcessor_1 = require("./export/SimpleSpanProcessor"); -Object.defineProperty(exports, "SimpleSpanProcessor", { enumerable: true, get: function () { return SimpleSpanProcessor_1.SimpleSpanProcessor; } }); -var NoopSpanProcessor_1 = require("./export/NoopSpanProcessor"); -Object.defineProperty(exports, "NoopSpanProcessor", { enumerable: true, get: function () { return NoopSpanProcessor_1.NoopSpanProcessor; } }); -var AlwaysOffSampler_1 = require("./sampler/AlwaysOffSampler"); -Object.defineProperty(exports, "AlwaysOffSampler", { enumerable: true, get: function () { return AlwaysOffSampler_1.AlwaysOffSampler; } }); -var AlwaysOnSampler_1 = require("./sampler/AlwaysOnSampler"); -Object.defineProperty(exports, "AlwaysOnSampler", { enumerable: true, get: function () { return AlwaysOnSampler_1.AlwaysOnSampler; } }); -var ParentBasedSampler_1 = require("./sampler/ParentBasedSampler"); -Object.defineProperty(exports, "ParentBasedSampler", { enumerable: true, get: function () { return ParentBasedSampler_1.ParentBasedSampler; } }); -var TraceIdRatioBasedSampler_1 = require("./sampler/TraceIdRatioBasedSampler"); -Object.defineProperty(exports, "TraceIdRatioBasedSampler", { enumerable: true, get: function () { return TraceIdRatioBasedSampler_1.TraceIdRatioBasedSampler; } }); -var Sampler_1 = require("./Sampler"); -Object.defineProperty(exports, "SamplingDecision", { enumerable: true, get: function () { return Sampler_1.SamplingDecision; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/index.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/index.js deleted file mode 100644 index 7357cec3..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/index.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RandomIdGenerator = exports.BatchSpanProcessor = void 0; -var node_1 = require("./node"); -Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: function () { return node_1.BatchSpanProcessor; } }); -Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: function () { return node_1.RandomIdGenerator; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/RandomIdGenerator.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/RandomIdGenerator.js deleted file mode 100644 index 47621738..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/RandomIdGenerator.js +++ /dev/null @@ -1,54 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RandomIdGenerator = void 0; -const SPAN_ID_BYTES = 8; -const TRACE_ID_BYTES = 16; -class RandomIdGenerator { - /** - * Returns a random 16-byte trace ID formatted/encoded as a 32 lowercase hex - * characters corresponding to 128 bits. - */ - generateTraceId = getIdGenerator(TRACE_ID_BYTES); - /** - * Returns a random 8-byte span ID formatted/encoded as a 16 lowercase hex - * characters corresponding to 64 bits. - */ - generateSpanId = getIdGenerator(SPAN_ID_BYTES); -} -exports.RandomIdGenerator = RandomIdGenerator; -const SHARED_BUFFER = Buffer.allocUnsafe(TRACE_ID_BYTES); -function getIdGenerator(bytes) { - return function generateId() { - for (let i = 0; i < bytes / 4; i++) { - // unsigned right shift drops decimal part of the number - // it is required because if a number between 2**32 and 2**32 - 1 is generated, an out of range error is thrown by writeUInt32BE - SHARED_BUFFER.writeUInt32BE((Math.random() * 2 ** 32) >>> 0, i * 4); - } - // If buffer is all 0, set the last byte to 1 to guarantee a valid w3c id is generated - for (let i = 0; i < bytes; i++) { - if (SHARED_BUFFER[i] > 0) { - break; - } - else if (i === bytes - 1) { - SHARED_BUFFER[bytes - 1] = 1; - } - } - return SHARED_BUFFER.toString('hex', 0, bytes); - }; -} -//# sourceMappingURL=RandomIdGenerator.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/export/BatchSpanProcessor.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/export/BatchSpanProcessor.js deleted file mode 100644 index 91e47b28..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/export/BatchSpanProcessor.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BatchSpanProcessor = void 0; -const BatchSpanProcessorBase_1 = require("../../../export/BatchSpanProcessorBase"); -class BatchSpanProcessor extends BatchSpanProcessorBase_1.BatchSpanProcessorBase { - onShutdown() { } -} -exports.BatchSpanProcessor = BatchSpanProcessor; -//# sourceMappingURL=BatchSpanProcessor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/index.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/index.js deleted file mode 100644 index ca80efd6..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/platform/node/index.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.RandomIdGenerator = exports.BatchSpanProcessor = void 0; -var BatchSpanProcessor_1 = require("./export/BatchSpanProcessor"); -Object.defineProperty(exports, "BatchSpanProcessor", { enumerable: true, get: function () { return BatchSpanProcessor_1.BatchSpanProcessor; } }); -var RandomIdGenerator_1 = require("./RandomIdGenerator"); -Object.defineProperty(exports, "RandomIdGenerator", { enumerable: true, get: function () { return RandomIdGenerator_1.RandomIdGenerator; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOffSampler.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOffSampler.js deleted file mode 100644 index 7341f108..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOffSampler.js +++ /dev/null @@ -1,32 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AlwaysOffSampler = void 0; -const Sampler_1 = require("../Sampler"); -/** Sampler that samples no traces. */ -class AlwaysOffSampler { - shouldSample() { - return { - decision: Sampler_1.SamplingDecision.NOT_RECORD, - }; - } - toString() { - return 'AlwaysOffSampler'; - } -} -exports.AlwaysOffSampler = AlwaysOffSampler; -//# sourceMappingURL=AlwaysOffSampler.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOnSampler.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOnSampler.js deleted file mode 100644 index 223b7707..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/AlwaysOnSampler.js +++ /dev/null @@ -1,32 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AlwaysOnSampler = void 0; -const Sampler_1 = require("../Sampler"); -/** Sampler that samples all traces. */ -class AlwaysOnSampler { - shouldSample() { - return { - decision: Sampler_1.SamplingDecision.RECORD_AND_SAMPLED, - }; - } - toString() { - return 'AlwaysOnSampler'; - } -} -exports.AlwaysOnSampler = AlwaysOnSampler; -//# sourceMappingURL=AlwaysOnSampler.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/ParentBasedSampler.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/ParentBasedSampler.js deleted file mode 100644 index c77b4386..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/ParentBasedSampler.js +++ /dev/null @@ -1,69 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ParentBasedSampler = void 0; -const api_1 = require("@opentelemetry/api"); -const core_1 = require("@opentelemetry/core"); -const AlwaysOffSampler_1 = require("./AlwaysOffSampler"); -const AlwaysOnSampler_1 = require("./AlwaysOnSampler"); -/** - * A composite sampler that either respects the parent span's sampling decision - * or delegates to `delegateSampler` for root spans. - */ -class ParentBasedSampler { - _root; - _remoteParentSampled; - _remoteParentNotSampled; - _localParentSampled; - _localParentNotSampled; - constructor(config) { - this._root = config.root; - if (!this._root) { - (0, core_1.globalErrorHandler)(new Error('ParentBasedSampler must have a root sampler configured')); - this._root = new AlwaysOnSampler_1.AlwaysOnSampler(); - } - this._remoteParentSampled = - config.remoteParentSampled ?? new AlwaysOnSampler_1.AlwaysOnSampler(); - this._remoteParentNotSampled = - config.remoteParentNotSampled ?? new AlwaysOffSampler_1.AlwaysOffSampler(); - this._localParentSampled = - config.localParentSampled ?? new AlwaysOnSampler_1.AlwaysOnSampler(); - this._localParentNotSampled = - config.localParentNotSampled ?? new AlwaysOffSampler_1.AlwaysOffSampler(); - } - shouldSample(context, traceId, spanName, spanKind, attributes, links) { - const parentContext = api_1.trace.getSpanContext(context); - if (!parentContext || !(0, api_1.isSpanContextValid)(parentContext)) { - return this._root.shouldSample(context, traceId, spanName, spanKind, attributes, links); - } - if (parentContext.isRemote) { - if (parentContext.traceFlags & api_1.TraceFlags.SAMPLED) { - return this._remoteParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links); - } - return this._remoteParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links); - } - if (parentContext.traceFlags & api_1.TraceFlags.SAMPLED) { - return this._localParentSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links); - } - return this._localParentNotSampled.shouldSample(context, traceId, spanName, spanKind, attributes, links); - } - toString() { - return `ParentBased{root=${this._root.toString()}, remoteParentSampled=${this._remoteParentSampled.toString()}, remoteParentNotSampled=${this._remoteParentNotSampled.toString()}, localParentSampled=${this._localParentSampled.toString()}, localParentNotSampled=${this._localParentNotSampled.toString()}}`; - } -} -exports.ParentBasedSampler = ParentBasedSampler; -//# sourceMappingURL=ParentBasedSampler.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/TraceIdRatioBasedSampler.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/TraceIdRatioBasedSampler.js deleted file mode 100644 index 38a5b14e..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/sampler/TraceIdRatioBasedSampler.js +++ /dev/null @@ -1,56 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.TraceIdRatioBasedSampler = void 0; -const api_1 = require("@opentelemetry/api"); -const Sampler_1 = require("../Sampler"); -/** Sampler that samples a given fraction of traces based of trace id deterministically. */ -class TraceIdRatioBasedSampler { - _ratio; - _upperBound; - constructor(_ratio = 0) { - this._ratio = _ratio; - this._ratio = this._normalize(_ratio); - this._upperBound = Math.floor(this._ratio * 0xffffffff); - } - shouldSample(context, traceId) { - return { - decision: (0, api_1.isValidTraceId)(traceId) && this._accumulate(traceId) < this._upperBound - ? Sampler_1.SamplingDecision.RECORD_AND_SAMPLED - : Sampler_1.SamplingDecision.NOT_RECORD, - }; - } - toString() { - return `TraceIdRatioBased{${this._ratio}}`; - } - _normalize(ratio) { - if (typeof ratio !== 'number' || isNaN(ratio)) - return 0; - return ratio >= 1 ? 1 : ratio <= 0 ? 0 : ratio; - } - _accumulate(traceId) { - let accumulation = 0; - for (let i = 0; i < traceId.length / 8; i++) { - const pos = i * 8; - const part = parseInt(traceId.slice(pos, pos + 8), 16); - accumulation = (accumulation ^ part) >>> 0; - } - return accumulation; - } -} -exports.TraceIdRatioBasedSampler = TraceIdRatioBasedSampler; -//# sourceMappingURL=TraceIdRatioBasedSampler.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/utility.js b/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/utility.js deleted file mode 100644 index bd49cca6..00000000 --- a/claude-code-source/node_modules/@opentelemetry/sdk-trace-base/build/src/utility.js +++ /dev/null @@ -1,66 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.reconfigureLimits = exports.mergeConfig = exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT = void 0; -const config_1 = require("./config"); -const core_1 = require("@opentelemetry/core"); -exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT = 128; -exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT = Infinity; -/** - * Function to merge Default configuration (as specified in './config') with - * user provided configurations. - */ -function mergeConfig(userConfig) { - const perInstanceDefaults = { - sampler: (0, config_1.buildSamplerFromEnv)(), - }; - const DEFAULT_CONFIG = (0, config_1.loadDefaultConfig)(); - const target = Object.assign({}, DEFAULT_CONFIG, perInstanceDefaults, userConfig); - target.generalLimits = Object.assign({}, DEFAULT_CONFIG.generalLimits, userConfig.generalLimits || {}); - target.spanLimits = Object.assign({}, DEFAULT_CONFIG.spanLimits, userConfig.spanLimits || {}); - return target; -} -exports.mergeConfig = mergeConfig; -/** - * When general limits are provided and model specific limits are not, - * configures the model specific limits by using the values from the general ones. - * @param userConfig User provided tracer configuration - */ -function reconfigureLimits(userConfig) { - const spanLimits = Object.assign({}, userConfig.spanLimits); - /** - * Reassign span attribute count limit to use first non null value defined by user or use default value - */ - spanLimits.attributeCountLimit = - userConfig.spanLimits?.attributeCountLimit ?? - userConfig.generalLimits?.attributeCountLimit ?? - (0, core_1.getNumberFromEnv)('OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT') ?? - (0, core_1.getNumberFromEnv)('OTEL_ATTRIBUTE_COUNT_LIMIT') ?? - exports.DEFAULT_ATTRIBUTE_COUNT_LIMIT; - /** - * Reassign span attribute value length limit to use first non null value defined by user or use default value - */ - spanLimits.attributeValueLengthLimit = - userConfig.spanLimits?.attributeValueLengthLimit ?? - userConfig.generalLimits?.attributeValueLengthLimit ?? - (0, core_1.getNumberFromEnv)('OTEL_SPAN_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? - (0, core_1.getNumberFromEnv)('OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT') ?? - exports.DEFAULT_ATTRIBUTE_VALUE_LENGTH_LIMIT; - return Object.assign({}, userConfig, { spanLimits }); -} -exports.reconfigureLimits = reconfigureLimits; -//# sourceMappingURL=utility.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/index.js b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/index.js deleted file mode 100644 index abfca434..00000000 --- a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/index.js +++ /dev/null @@ -1,43 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -/* eslint-disable no-restricted-syntax -- - * These re-exports are only of constants, only two-levels deep, and - * should not cause problems for tree-shakers. - */ -// Deprecated. These are kept around for compatibility purposes -__exportStar(require("./trace"), exports); -__exportStar(require("./resource"), exports); -// Use these instead -__exportStar(require("./stable_attributes"), exports); -__exportStar(require("./stable_metrics"), exports); -__exportStar(require("./stable_events"), exports); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/internal/utils.js b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/internal/utils.js deleted file mode 100644 index c5cc1c5f..00000000 --- a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/internal/utils.js +++ /dev/null @@ -1,38 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createConstMap = void 0; -/** - * Creates a const map from the given values - * @param values - An array of values to be used as keys and values in the map. - * @returns A populated version of the map with the values and keys derived from the values. - */ -/*#__NO_SIDE_EFFECTS__*/ -function createConstMap(values) { - // eslint-disable-next-line prefer-const, @typescript-eslint/no-explicit-any - let res = {}; - const len = values.length; - for (let lp = 0; lp < len; lp++) { - const val = values[lp]; - if (val) { - res[String(val).toUpperCase().replace(/[-.]/g, '_')] = val; - } - } - return res; -} -exports.createConstMap = createConstMap; -//# sourceMappingURL=utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/resource/SemanticResourceAttributes.js b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/resource/SemanticResourceAttributes.js deleted file mode 100644 index dc0c8af2..00000000 --- a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/resource/SemanticResourceAttributes.js +++ /dev/null @@ -1,1266 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SEMRESATTRS_K8S_STATEFULSET_NAME = exports.SEMRESATTRS_K8S_STATEFULSET_UID = exports.SEMRESATTRS_K8S_DEPLOYMENT_NAME = exports.SEMRESATTRS_K8S_DEPLOYMENT_UID = exports.SEMRESATTRS_K8S_REPLICASET_NAME = exports.SEMRESATTRS_K8S_REPLICASET_UID = exports.SEMRESATTRS_K8S_CONTAINER_NAME = exports.SEMRESATTRS_K8S_POD_NAME = exports.SEMRESATTRS_K8S_POD_UID = exports.SEMRESATTRS_K8S_NAMESPACE_NAME = exports.SEMRESATTRS_K8S_NODE_UID = exports.SEMRESATTRS_K8S_NODE_NAME = exports.SEMRESATTRS_K8S_CLUSTER_NAME = exports.SEMRESATTRS_HOST_IMAGE_VERSION = exports.SEMRESATTRS_HOST_IMAGE_ID = exports.SEMRESATTRS_HOST_IMAGE_NAME = exports.SEMRESATTRS_HOST_ARCH = exports.SEMRESATTRS_HOST_TYPE = exports.SEMRESATTRS_HOST_NAME = exports.SEMRESATTRS_HOST_ID = exports.SEMRESATTRS_FAAS_MAX_MEMORY = exports.SEMRESATTRS_FAAS_INSTANCE = exports.SEMRESATTRS_FAAS_VERSION = exports.SEMRESATTRS_FAAS_ID = exports.SEMRESATTRS_FAAS_NAME = exports.SEMRESATTRS_DEVICE_MODEL_NAME = exports.SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = exports.SEMRESATTRS_DEVICE_ID = exports.SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = exports.SEMRESATTRS_CONTAINER_IMAGE_TAG = exports.SEMRESATTRS_CONTAINER_IMAGE_NAME = exports.SEMRESATTRS_CONTAINER_RUNTIME = exports.SEMRESATTRS_CONTAINER_ID = exports.SEMRESATTRS_CONTAINER_NAME = exports.SEMRESATTRS_AWS_LOG_STREAM_ARNS = exports.SEMRESATTRS_AWS_LOG_STREAM_NAMES = exports.SEMRESATTRS_AWS_LOG_GROUP_ARNS = exports.SEMRESATTRS_AWS_LOG_GROUP_NAMES = exports.SEMRESATTRS_AWS_EKS_CLUSTER_ARN = exports.SEMRESATTRS_AWS_ECS_TASK_REVISION = exports.SEMRESATTRS_AWS_ECS_TASK_FAMILY = exports.SEMRESATTRS_AWS_ECS_TASK_ARN = exports.SEMRESATTRS_AWS_ECS_LAUNCHTYPE = exports.SEMRESATTRS_AWS_ECS_CLUSTER_ARN = exports.SEMRESATTRS_AWS_ECS_CONTAINER_ARN = exports.SEMRESATTRS_CLOUD_PLATFORM = exports.SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = exports.SEMRESATTRS_CLOUD_REGION = exports.SEMRESATTRS_CLOUD_ACCOUNT_ID = exports.SEMRESATTRS_CLOUD_PROVIDER = void 0; -exports.CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = exports.CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = exports.CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = exports.CLOUDPLATFORMVALUES_AZURE_AKS = exports.CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = exports.CLOUDPLATFORMVALUES_AZURE_VM = exports.CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = exports.CLOUDPLATFORMVALUES_AWS_LAMBDA = exports.CLOUDPLATFORMVALUES_AWS_EKS = exports.CLOUDPLATFORMVALUES_AWS_ECS = exports.CLOUDPLATFORMVALUES_AWS_EC2 = exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = exports.CloudProviderValues = exports.CLOUDPROVIDERVALUES_GCP = exports.CLOUDPROVIDERVALUES_AZURE = exports.CLOUDPROVIDERVALUES_AWS = exports.CLOUDPROVIDERVALUES_ALIBABA_CLOUD = exports.SemanticResourceAttributes = exports.SEMRESATTRS_WEBENGINE_DESCRIPTION = exports.SEMRESATTRS_WEBENGINE_VERSION = exports.SEMRESATTRS_WEBENGINE_NAME = exports.SEMRESATTRS_TELEMETRY_AUTO_VERSION = exports.SEMRESATTRS_TELEMETRY_SDK_VERSION = exports.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = exports.SEMRESATTRS_TELEMETRY_SDK_NAME = exports.SEMRESATTRS_SERVICE_VERSION = exports.SEMRESATTRS_SERVICE_INSTANCE_ID = exports.SEMRESATTRS_SERVICE_NAMESPACE = exports.SEMRESATTRS_SERVICE_NAME = exports.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = exports.SEMRESATTRS_PROCESS_RUNTIME_VERSION = exports.SEMRESATTRS_PROCESS_RUNTIME_NAME = exports.SEMRESATTRS_PROCESS_OWNER = exports.SEMRESATTRS_PROCESS_COMMAND_ARGS = exports.SEMRESATTRS_PROCESS_COMMAND_LINE = exports.SEMRESATTRS_PROCESS_COMMAND = exports.SEMRESATTRS_PROCESS_EXECUTABLE_PATH = exports.SEMRESATTRS_PROCESS_EXECUTABLE_NAME = exports.SEMRESATTRS_PROCESS_PID = exports.SEMRESATTRS_OS_VERSION = exports.SEMRESATTRS_OS_NAME = exports.SEMRESATTRS_OS_DESCRIPTION = exports.SEMRESATTRS_OS_TYPE = exports.SEMRESATTRS_K8S_CRONJOB_NAME = exports.SEMRESATTRS_K8S_CRONJOB_UID = exports.SEMRESATTRS_K8S_JOB_NAME = exports.SEMRESATTRS_K8S_JOB_UID = exports.SEMRESATTRS_K8S_DAEMONSET_NAME = exports.SEMRESATTRS_K8S_DAEMONSET_UID = void 0; -exports.TelemetrySdkLanguageValues = exports.TELEMETRYSDKLANGUAGEVALUES_WEBJS = exports.TELEMETRYSDKLANGUAGEVALUES_RUBY = exports.TELEMETRYSDKLANGUAGEVALUES_PYTHON = exports.TELEMETRYSDKLANGUAGEVALUES_PHP = exports.TELEMETRYSDKLANGUAGEVALUES_NODEJS = exports.TELEMETRYSDKLANGUAGEVALUES_JAVA = exports.TELEMETRYSDKLANGUAGEVALUES_GO = exports.TELEMETRYSDKLANGUAGEVALUES_ERLANG = exports.TELEMETRYSDKLANGUAGEVALUES_DOTNET = exports.TELEMETRYSDKLANGUAGEVALUES_CPP = exports.OsTypeValues = exports.OSTYPEVALUES_Z_OS = exports.OSTYPEVALUES_SOLARIS = exports.OSTYPEVALUES_AIX = exports.OSTYPEVALUES_HPUX = exports.OSTYPEVALUES_DRAGONFLYBSD = exports.OSTYPEVALUES_OPENBSD = exports.OSTYPEVALUES_NETBSD = exports.OSTYPEVALUES_FREEBSD = exports.OSTYPEVALUES_DARWIN = exports.OSTYPEVALUES_LINUX = exports.OSTYPEVALUES_WINDOWS = exports.HostArchValues = exports.HOSTARCHVALUES_X86 = exports.HOSTARCHVALUES_PPC64 = exports.HOSTARCHVALUES_PPC32 = exports.HOSTARCHVALUES_IA64 = exports.HOSTARCHVALUES_ARM64 = exports.HOSTARCHVALUES_ARM32 = exports.HOSTARCHVALUES_AMD64 = exports.AwsEcsLaunchtypeValues = exports.AWSECSLAUNCHTYPEVALUES_FARGATE = exports.AWSECSLAUNCHTYPEVALUES_EC2 = exports.CloudPlatformValues = exports.CLOUDPLATFORMVALUES_GCP_APP_ENGINE = exports.CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = exports.CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = exports.CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = void 0; -const utils_1 = require("../internal/utils"); -//---------------------------------------------------------------------------------------------------------- -// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates//templates/SemanticAttributes.ts.j2 -//---------------------------------------------------------------------------------------------------------- -//---------------------------------------------------------------------------------------------------------- -// Constant values for SemanticResourceAttributes -//---------------------------------------------------------------------------------------------------------- -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_CLOUD_PROVIDER = 'cloud.provider'; -const TMP_CLOUD_ACCOUNT_ID = 'cloud.account.id'; -const TMP_CLOUD_REGION = 'cloud.region'; -const TMP_CLOUD_AVAILABILITY_ZONE = 'cloud.availability_zone'; -const TMP_CLOUD_PLATFORM = 'cloud.platform'; -const TMP_AWS_ECS_CONTAINER_ARN = 'aws.ecs.container.arn'; -const TMP_AWS_ECS_CLUSTER_ARN = 'aws.ecs.cluster.arn'; -const TMP_AWS_ECS_LAUNCHTYPE = 'aws.ecs.launchtype'; -const TMP_AWS_ECS_TASK_ARN = 'aws.ecs.task.arn'; -const TMP_AWS_ECS_TASK_FAMILY = 'aws.ecs.task.family'; -const TMP_AWS_ECS_TASK_REVISION = 'aws.ecs.task.revision'; -const TMP_AWS_EKS_CLUSTER_ARN = 'aws.eks.cluster.arn'; -const TMP_AWS_LOG_GROUP_NAMES = 'aws.log.group.names'; -const TMP_AWS_LOG_GROUP_ARNS = 'aws.log.group.arns'; -const TMP_AWS_LOG_STREAM_NAMES = 'aws.log.stream.names'; -const TMP_AWS_LOG_STREAM_ARNS = 'aws.log.stream.arns'; -const TMP_CONTAINER_NAME = 'container.name'; -const TMP_CONTAINER_ID = 'container.id'; -const TMP_CONTAINER_RUNTIME = 'container.runtime'; -const TMP_CONTAINER_IMAGE_NAME = 'container.image.name'; -const TMP_CONTAINER_IMAGE_TAG = 'container.image.tag'; -const TMP_DEPLOYMENT_ENVIRONMENT = 'deployment.environment'; -const TMP_DEVICE_ID = 'device.id'; -const TMP_DEVICE_MODEL_IDENTIFIER = 'device.model.identifier'; -const TMP_DEVICE_MODEL_NAME = 'device.model.name'; -const TMP_FAAS_NAME = 'faas.name'; -const TMP_FAAS_ID = 'faas.id'; -const TMP_FAAS_VERSION = 'faas.version'; -const TMP_FAAS_INSTANCE = 'faas.instance'; -const TMP_FAAS_MAX_MEMORY = 'faas.max_memory'; -const TMP_HOST_ID = 'host.id'; -const TMP_HOST_NAME = 'host.name'; -const TMP_HOST_TYPE = 'host.type'; -const TMP_HOST_ARCH = 'host.arch'; -const TMP_HOST_IMAGE_NAME = 'host.image.name'; -const TMP_HOST_IMAGE_ID = 'host.image.id'; -const TMP_HOST_IMAGE_VERSION = 'host.image.version'; -const TMP_K8S_CLUSTER_NAME = 'k8s.cluster.name'; -const TMP_K8S_NODE_NAME = 'k8s.node.name'; -const TMP_K8S_NODE_UID = 'k8s.node.uid'; -const TMP_K8S_NAMESPACE_NAME = 'k8s.namespace.name'; -const TMP_K8S_POD_UID = 'k8s.pod.uid'; -const TMP_K8S_POD_NAME = 'k8s.pod.name'; -const TMP_K8S_CONTAINER_NAME = 'k8s.container.name'; -const TMP_K8S_REPLICASET_UID = 'k8s.replicaset.uid'; -const TMP_K8S_REPLICASET_NAME = 'k8s.replicaset.name'; -const TMP_K8S_DEPLOYMENT_UID = 'k8s.deployment.uid'; -const TMP_K8S_DEPLOYMENT_NAME = 'k8s.deployment.name'; -const TMP_K8S_STATEFULSET_UID = 'k8s.statefulset.uid'; -const TMP_K8S_STATEFULSET_NAME = 'k8s.statefulset.name'; -const TMP_K8S_DAEMONSET_UID = 'k8s.daemonset.uid'; -const TMP_K8S_DAEMONSET_NAME = 'k8s.daemonset.name'; -const TMP_K8S_JOB_UID = 'k8s.job.uid'; -const TMP_K8S_JOB_NAME = 'k8s.job.name'; -const TMP_K8S_CRONJOB_UID = 'k8s.cronjob.uid'; -const TMP_K8S_CRONJOB_NAME = 'k8s.cronjob.name'; -const TMP_OS_TYPE = 'os.type'; -const TMP_OS_DESCRIPTION = 'os.description'; -const TMP_OS_NAME = 'os.name'; -const TMP_OS_VERSION = 'os.version'; -const TMP_PROCESS_PID = 'process.pid'; -const TMP_PROCESS_EXECUTABLE_NAME = 'process.executable.name'; -const TMP_PROCESS_EXECUTABLE_PATH = 'process.executable.path'; -const TMP_PROCESS_COMMAND = 'process.command'; -const TMP_PROCESS_COMMAND_LINE = 'process.command_line'; -const TMP_PROCESS_COMMAND_ARGS = 'process.command_args'; -const TMP_PROCESS_OWNER = 'process.owner'; -const TMP_PROCESS_RUNTIME_NAME = 'process.runtime.name'; -const TMP_PROCESS_RUNTIME_VERSION = 'process.runtime.version'; -const TMP_PROCESS_RUNTIME_DESCRIPTION = 'process.runtime.description'; -const TMP_SERVICE_NAME = 'service.name'; -const TMP_SERVICE_NAMESPACE = 'service.namespace'; -const TMP_SERVICE_INSTANCE_ID = 'service.instance.id'; -const TMP_SERVICE_VERSION = 'service.version'; -const TMP_TELEMETRY_SDK_NAME = 'telemetry.sdk.name'; -const TMP_TELEMETRY_SDK_LANGUAGE = 'telemetry.sdk.language'; -const TMP_TELEMETRY_SDK_VERSION = 'telemetry.sdk.version'; -const TMP_TELEMETRY_AUTO_VERSION = 'telemetry.auto.version'; -const TMP_WEBENGINE_NAME = 'webengine.name'; -const TMP_WEBENGINE_VERSION = 'webengine.version'; -const TMP_WEBENGINE_DESCRIPTION = 'webengine.description'; -/** - * Name of the cloud provider. - * - * @deprecated Use ATTR_CLOUD_PROVIDER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_CLOUD_PROVIDER = TMP_CLOUD_PROVIDER; -/** - * The cloud account ID the resource is assigned to. - * - * @deprecated Use ATTR_CLOUD_ACCOUNT_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_CLOUD_ACCOUNT_ID = TMP_CLOUD_ACCOUNT_ID; -/** - * The geographical region the resource is running. Refer to your provider's docs to see the available regions, for example [Alibaba Cloud regions](https://www.alibabacloud.com/help/doc-detail/40654.htm), [AWS regions](https://aws.amazon.com/about-aws/global-infrastructure/regions_az/), [Azure regions](https://azure.microsoft.com/en-us/global-infrastructure/geographies/), or [Google Cloud regions](https://cloud.google.com/about/locations). - * - * @deprecated Use ATTR_CLOUD_REGION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_CLOUD_REGION = TMP_CLOUD_REGION; -/** - * Cloud regions often have multiple, isolated locations known as zones to increase availability. Availability zone represents the zone where the resource is running. - * - * Note: Availability zones are called "zones" on Alibaba Cloud and Google Cloud. - * - * @deprecated Use ATTR_CLOUD_AVAILABILITY_ZONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_CLOUD_AVAILABILITY_ZONE = TMP_CLOUD_AVAILABILITY_ZONE; -/** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use ATTR_CLOUD_PLATFORM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_CLOUD_PLATFORM = TMP_CLOUD_PLATFORM; -/** - * The Amazon Resource Name (ARN) of an [ECS container instance](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/ECS_instances.html). - * - * @deprecated Use ATTR_AWS_ECS_CONTAINER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_AWS_ECS_CONTAINER_ARN = TMP_AWS_ECS_CONTAINER_ARN; -/** - * The ARN of an [ECS cluster](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/clusters.html). - * - * @deprecated Use ATTR_AWS_ECS_CLUSTER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_AWS_ECS_CLUSTER_ARN = TMP_AWS_ECS_CLUSTER_ARN; -/** - * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. - * - * @deprecated Use ATTR_AWS_ECS_LAUNCHTYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_AWS_ECS_LAUNCHTYPE = TMP_AWS_ECS_LAUNCHTYPE; -/** - * The ARN of an [ECS task definition](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/task_definitions.html). - * - * @deprecated Use ATTR_AWS_ECS_TASK_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_AWS_ECS_TASK_ARN = TMP_AWS_ECS_TASK_ARN; -/** - * The task definition family this task definition is a member of. - * - * @deprecated Use ATTR_AWS_ECS_TASK_FAMILY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_AWS_ECS_TASK_FAMILY = TMP_AWS_ECS_TASK_FAMILY; -/** - * The revision for this task definition. - * - * @deprecated Use ATTR_AWS_ECS_TASK_REVISION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_AWS_ECS_TASK_REVISION = TMP_AWS_ECS_TASK_REVISION; -/** - * The ARN of an EKS cluster. - * - * @deprecated Use ATTR_AWS_EKS_CLUSTER_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_AWS_EKS_CLUSTER_ARN = TMP_AWS_EKS_CLUSTER_ARN; -/** - * The name(s) of the AWS log group(s) an application is writing to. - * - * Note: Multiple log groups must be supported for cases like multi-container applications, where a single application has sidecar containers, and each write to their own log group. - * - * @deprecated Use ATTR_AWS_LOG_GROUP_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_AWS_LOG_GROUP_NAMES = TMP_AWS_LOG_GROUP_NAMES; -/** - * The Amazon Resource Name(s) (ARN) of the AWS log group(s). - * - * Note: See the [log group ARN format documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). - * - * @deprecated Use ATTR_AWS_LOG_GROUP_ARNS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_AWS_LOG_GROUP_ARNS = TMP_AWS_LOG_GROUP_ARNS; -/** - * The name(s) of the AWS log stream(s) an application is writing to. - * - * @deprecated Use ATTR_AWS_LOG_STREAM_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_AWS_LOG_STREAM_NAMES = TMP_AWS_LOG_STREAM_NAMES; -/** - * The ARN(s) of the AWS log stream(s). - * - * Note: See the [log stream ARN format documentation](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/iam-access-control-overview-cwl.html#CWL_ARN_Format). One log group can contain several log streams, so these ARNs necessarily identify both a log group and a log stream. - * - * @deprecated Use ATTR_AWS_LOG_STREAM_ARNS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_AWS_LOG_STREAM_ARNS = TMP_AWS_LOG_STREAM_ARNS; -/** - * Container name. - * - * @deprecated Use ATTR_CONTAINER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_CONTAINER_NAME = TMP_CONTAINER_NAME; -/** - * Container ID. Usually a UUID, as for example used to [identify Docker containers](https://docs.docker.com/engine/reference/run/#container-identification). The UUID might be abbreviated. - * - * @deprecated Use ATTR_CONTAINER_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_CONTAINER_ID = TMP_CONTAINER_ID; -/** - * The container runtime managing this container. - * - * @deprecated Use ATTR_CONTAINER_RUNTIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_CONTAINER_RUNTIME = TMP_CONTAINER_RUNTIME; -/** - * Name of the image the container was built on. - * - * @deprecated Use ATTR_CONTAINER_IMAGE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_CONTAINER_IMAGE_NAME = TMP_CONTAINER_IMAGE_NAME; -/** - * Container image tag. - * - * @deprecated Use ATTR_CONTAINER_IMAGE_TAGS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_CONTAINER_IMAGE_TAG = TMP_CONTAINER_IMAGE_TAG; -/** - * Name of the [deployment environment](https://en.wikipedia.org/wiki/Deployment_environment) (aka deployment tier). - * - * @deprecated Use ATTR_DEPLOYMENT_ENVIRONMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_DEPLOYMENT_ENVIRONMENT = TMP_DEPLOYMENT_ENVIRONMENT; -/** - * A unique identifier representing the device. - * - * Note: The device identifier MUST only be defined using the values outlined below. This value is not an advertising identifier and MUST NOT be used as such. On iOS (Swift or Objective-C), this value MUST be equal to the [vendor identifier](https://developer.apple.com/documentation/uikit/uidevice/1620059-identifierforvendor). On Android (Java or Kotlin), this value MUST be equal to the Firebase Installation ID or a globally unique UUID which is persisted across sessions in your application. More information can be found [here](https://developer.android.com/training/articles/user-data-ids) on best practices and exact implementation details. Caution should be taken when storing personal data or anything which can identify a user. GDPR and data protection laws may apply, ensure you do your own due diligence. - * - * @deprecated Use ATTR_DEVICE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_DEVICE_ID = TMP_DEVICE_ID; -/** - * The model identifier for the device. - * - * Note: It's recommended this value represents a machine readable version of the model identifier rather than the market or consumer-friendly name of the device. - * - * @deprecated Use ATTR_DEVICE_MODEL_IDENTIFIER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_DEVICE_MODEL_IDENTIFIER = TMP_DEVICE_MODEL_IDENTIFIER; -/** - * The marketing name for the device model. - * - * Note: It's recommended this value represents a human readable version of the device model rather than a machine readable alternative. - * - * @deprecated Use ATTR_DEVICE_MODEL_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_DEVICE_MODEL_NAME = TMP_DEVICE_MODEL_NAME; -/** - * The name of the single function that this runtime instance executes. - * - * Note: This is the name of the function as configured/deployed on the FaaS platform and is usually different from the name of the callback function (which may be stored in the [`code.namespace`/`code.function`](../../trace/semantic_conventions/span-general.md#source-code-attributes) span attributes). - * - * @deprecated Use ATTR_FAAS_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_FAAS_NAME = TMP_FAAS_NAME; -/** -* The unique ID of the single function that this runtime instance executes. -* -* Note: Depending on the cloud provider, use: - -* **AWS Lambda:** The function [ARN](https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html). -Take care not to use the "invoked ARN" directly but replace any -[alias suffix](https://docs.aws.amazon.com/lambda/latest/dg/configuration-aliases.html) with the resolved function version, as the same runtime instance may be invokable with multiple -different aliases. -* **GCP:** The [URI of the resource](https://cloud.google.com/iam/docs/full-resource-names) -* **Azure:** The [Fully Qualified Resource ID](https://docs.microsoft.com/en-us/rest/api/resources/resources/get-by-id). - -On some providers, it may not be possible to determine the full ID at startup, -which is why this field cannot be made required. For example, on AWS the account ID -part of the ARN is not available without calling another AWS API -which may be deemed too slow for a short-running lambda function. -As an alternative, consider setting `faas.id` as a span attribute instead. -* -* @deprecated Use ATTR_CLOUD_RESOURCE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). -*/ -exports.SEMRESATTRS_FAAS_ID = TMP_FAAS_ID; -/** -* The immutable version of the function being executed. -* -* Note: Depending on the cloud provider and platform, use: - -* **AWS Lambda:** The [function version](https://docs.aws.amazon.com/lambda/latest/dg/configuration-versions.html) - (an integer represented as a decimal string). -* **Google Cloud Run:** The [revision](https://cloud.google.com/run/docs/managing/revisions) - (i.e., the function name plus the revision suffix). -* **Google Cloud Functions:** The value of the - [`K_REVISION` environment variable](https://cloud.google.com/functions/docs/env-var#runtime_environment_variables_set_automatically). -* **Azure Functions:** Not applicable. Do not set this attribute. -* -* @deprecated Use ATTR_FAAS_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). -*/ -exports.SEMRESATTRS_FAAS_VERSION = TMP_FAAS_VERSION; -/** - * The execution environment ID as a string, that will be potentially reused for other invocations to the same function/function version. - * - * Note: * **AWS Lambda:** Use the (full) log stream name. - * - * @deprecated Use ATTR_FAAS_INSTANCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_FAAS_INSTANCE = TMP_FAAS_INSTANCE; -/** - * The amount of memory available to the serverless function in MiB. - * - * Note: It's recommended to set this attribute since e.g. too little memory can easily stop a Java AWS Lambda function from working correctly. On AWS Lambda, the environment variable `AWS_LAMBDA_FUNCTION_MEMORY_SIZE` provides this information. - * - * @deprecated Use ATTR_FAAS_MAX_MEMORY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_FAAS_MAX_MEMORY = TMP_FAAS_MAX_MEMORY; -/** - * Unique host ID. For Cloud, this must be the instance_id assigned by the cloud provider. - * - * @deprecated Use ATTR_HOST_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_HOST_ID = TMP_HOST_ID; -/** - * Name of the host. On Unix systems, it may contain what the hostname command returns, or the fully qualified hostname, or another name specified by the user. - * - * @deprecated Use ATTR_HOST_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_HOST_NAME = TMP_HOST_NAME; -/** - * Type of host. For Cloud, this must be the machine type. - * - * @deprecated Use ATTR_HOST_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_HOST_TYPE = TMP_HOST_TYPE; -/** - * The CPU architecture the host system is running on. - * - * @deprecated Use ATTR_HOST_ARCH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_HOST_ARCH = TMP_HOST_ARCH; -/** - * Name of the VM image or OS install the host was instantiated from. - * - * @deprecated Use ATTR_HOST_IMAGE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_HOST_IMAGE_NAME = TMP_HOST_IMAGE_NAME; -/** - * VM image ID. For Cloud, this value is from the provider. - * - * @deprecated Use ATTR_HOST_IMAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_HOST_IMAGE_ID = TMP_HOST_IMAGE_ID; -/** - * The version string of the VM image as defined in [Version Attributes](README.md#version-attributes). - * - * @deprecated Use ATTR_HOST_IMAGE_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_HOST_IMAGE_VERSION = TMP_HOST_IMAGE_VERSION; -/** - * The name of the cluster. - * - * @deprecated Use ATTR_K8S_CLUSTER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_K8S_CLUSTER_NAME = TMP_K8S_CLUSTER_NAME; -/** - * The name of the Node. - * - * @deprecated Use ATTR_K8S_NODE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_K8S_NODE_NAME = TMP_K8S_NODE_NAME; -/** - * The UID of the Node. - * - * @deprecated Use ATTR_K8S_NODE_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_K8S_NODE_UID = TMP_K8S_NODE_UID; -/** - * The name of the namespace that the pod is running in. - * - * @deprecated Use ATTR_K8S_NAMESPACE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_K8S_NAMESPACE_NAME = TMP_K8S_NAMESPACE_NAME; -/** - * The UID of the Pod. - * - * @deprecated Use ATTR_K8S_POD_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_K8S_POD_UID = TMP_K8S_POD_UID; -/** - * The name of the Pod. - * - * @deprecated Use ATTR_K8S_POD_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_K8S_POD_NAME = TMP_K8S_POD_NAME; -/** - * The name of the Container in a Pod template. - * - * @deprecated Use ATTR_K8S_CONTAINER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_K8S_CONTAINER_NAME = TMP_K8S_CONTAINER_NAME; -/** - * The UID of the ReplicaSet. - * - * @deprecated Use ATTR_K8S_REPLICASET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_K8S_REPLICASET_UID = TMP_K8S_REPLICASET_UID; -/** - * The name of the ReplicaSet. - * - * @deprecated Use ATTR_K8S_REPLICASET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_K8S_REPLICASET_NAME = TMP_K8S_REPLICASET_NAME; -/** - * The UID of the Deployment. - * - * @deprecated Use ATTR_K8S_DEPLOYMENT_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_K8S_DEPLOYMENT_UID = TMP_K8S_DEPLOYMENT_UID; -/** - * The name of the Deployment. - * - * @deprecated Use ATTR_K8S_DEPLOYMENT_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_K8S_DEPLOYMENT_NAME = TMP_K8S_DEPLOYMENT_NAME; -/** - * The UID of the StatefulSet. - * - * @deprecated Use ATTR_K8S_STATEFULSET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_K8S_STATEFULSET_UID = TMP_K8S_STATEFULSET_UID; -/** - * The name of the StatefulSet. - * - * @deprecated Use ATTR_K8S_STATEFULSET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_K8S_STATEFULSET_NAME = TMP_K8S_STATEFULSET_NAME; -/** - * The UID of the DaemonSet. - * - * @deprecated Use ATTR_K8S_DAEMONSET_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_K8S_DAEMONSET_UID = TMP_K8S_DAEMONSET_UID; -/** - * The name of the DaemonSet. - * - * @deprecated Use ATTR_K8S_DAEMONSET_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_K8S_DAEMONSET_NAME = TMP_K8S_DAEMONSET_NAME; -/** - * The UID of the Job. - * - * @deprecated Use ATTR_K8S_JOB_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_K8S_JOB_UID = TMP_K8S_JOB_UID; -/** - * The name of the Job. - * - * @deprecated Use ATTR_K8S_JOB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_K8S_JOB_NAME = TMP_K8S_JOB_NAME; -/** - * The UID of the CronJob. - * - * @deprecated Use ATTR_K8S_CRONJOB_UID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_K8S_CRONJOB_UID = TMP_K8S_CRONJOB_UID; -/** - * The name of the CronJob. - * - * @deprecated Use ATTR_K8S_CRONJOB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_K8S_CRONJOB_NAME = TMP_K8S_CRONJOB_NAME; -/** - * The operating system type. - * - * @deprecated Use ATTR_OS_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_OS_TYPE = TMP_OS_TYPE; -/** - * Human readable (not intended to be parsed) OS version information, like e.g. reported by `ver` or `lsb_release -a` commands. - * - * @deprecated Use ATTR_OS_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_OS_DESCRIPTION = TMP_OS_DESCRIPTION; -/** - * Human readable operating system name. - * - * @deprecated Use ATTR_OS_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_OS_NAME = TMP_OS_NAME; -/** - * The version string of the operating system as defined in [Version Attributes](../../resource/semantic_conventions/README.md#version-attributes). - * - * @deprecated Use ATTR_OS_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_OS_VERSION = TMP_OS_VERSION; -/** - * Process identifier (PID). - * - * @deprecated Use ATTR_PROCESS_PID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_PROCESS_PID = TMP_PROCESS_PID; -/** - * The name of the process executable. On Linux based systems, can be set to the `Name` in `proc/[pid]/status`. On Windows, can be set to the base name of `GetProcessImageFileNameW`. - * - * @deprecated Use ATTR_PROCESS_EXECUTABLE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_PROCESS_EXECUTABLE_NAME = TMP_PROCESS_EXECUTABLE_NAME; -/** - * The full path to the process executable. On Linux based systems, can be set to the target of `proc/[pid]/exe`. On Windows, can be set to the result of `GetProcessImageFileNameW`. - * - * @deprecated Use ATTR_PROCESS_EXECUTABLE_PATH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_PROCESS_EXECUTABLE_PATH = TMP_PROCESS_EXECUTABLE_PATH; -/** - * The command used to launch the process (i.e. the command name). On Linux based systems, can be set to the zeroth string in `proc/[pid]/cmdline`. On Windows, can be set to the first parameter extracted from `GetCommandLineW`. - * - * @deprecated Use ATTR_PROCESS_COMMAND in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_PROCESS_COMMAND = TMP_PROCESS_COMMAND; -/** - * The full command used to launch the process as a single string representing the full command. On Windows, can be set to the result of `GetCommandLineW`. Do not set this if you have to assemble it just for monitoring; use `process.command_args` instead. - * - * @deprecated Use ATTR_PROCESS_COMMAND_LINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_PROCESS_COMMAND_LINE = TMP_PROCESS_COMMAND_LINE; -/** - * All the command arguments (including the command/executable itself) as received by the process. On Linux-based systems (and some other Unixoid systems supporting procfs), can be set according to the list of null-delimited strings extracted from `proc/[pid]/cmdline`. For libc-based executables, this would be the full argv vector passed to `main`. - * - * @deprecated Use ATTR_PROCESS_COMMAND_ARGS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_PROCESS_COMMAND_ARGS = TMP_PROCESS_COMMAND_ARGS; -/** - * The username of the user that owns the process. - * - * @deprecated Use ATTR_PROCESS_OWNER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_PROCESS_OWNER = TMP_PROCESS_OWNER; -/** - * The name of the runtime of this process. For compiled native binaries, this SHOULD be the name of the compiler. - * - * @deprecated Use ATTR_PROCESS_RUNTIME_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_PROCESS_RUNTIME_NAME = TMP_PROCESS_RUNTIME_NAME; -/** - * The version of the runtime of this process, as returned by the runtime without modification. - * - * @deprecated Use ATTR_PROCESS_RUNTIME_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_PROCESS_RUNTIME_VERSION = TMP_PROCESS_RUNTIME_VERSION; -/** - * An additional description about the runtime of the process, for example a specific vendor customization of the runtime environment. - * - * @deprecated Use ATTR_PROCESS_RUNTIME_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_PROCESS_RUNTIME_DESCRIPTION = TMP_PROCESS_RUNTIME_DESCRIPTION; -/** - * Logical name of the service. - * - * Note: MUST be the same for all instances of horizontally scaled services. If the value was not specified, SDKs MUST fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md#process), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value MUST be set to `unknown_service`. - * - * @deprecated Use ATTR_SERVICE_NAME. - */ -exports.SEMRESATTRS_SERVICE_NAME = TMP_SERVICE_NAME; -/** - * A namespace for `service.name`. - * - * Note: A string value having a meaning that helps to distinguish a group of services, for example the team name that owns a group of services. `service.name` is expected to be unique within the same namespace. If `service.namespace` is not specified in the Resource then `service.name` is expected to be unique for all services that have no explicit namespace defined (so the empty/unspecified namespace is simply one more valid namespace). Zero-length namespace string is assumed equal to unspecified namespace. - * - * @deprecated Use ATTR_SERVICE_NAMESPACE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_SERVICE_NAMESPACE = TMP_SERVICE_NAMESPACE; -/** - * The string ID of the service instance. - * - * Note: MUST be unique for each instance of the same `service.namespace,service.name` pair (in other words `service.namespace,service.name,service.instance.id` triplet MUST be globally unique). The ID helps to distinguish instances of the same service that exist at the same time (e.g. instances of a horizontally scaled service). It is preferable for the ID to be persistent and stay the same for the lifetime of the service instance, however it is acceptable that the ID is ephemeral and changes during important lifetime events for the service (e.g. service restarts). If the service has no inherent unique ID that can be used as the value of this attribute it is recommended to generate a random Version 1 or Version 4 RFC 4122 UUID (services aiming for reproducible UUIDs may also use Version 5, see RFC 4122 for more recommendations). - * - * @deprecated Use ATTR_SERVICE_INSTANCE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_SERVICE_INSTANCE_ID = TMP_SERVICE_INSTANCE_ID; -/** - * The version string of the service API or implementation. - * - * @deprecated Use ATTR_SERVICE_VERSION. - */ -exports.SEMRESATTRS_SERVICE_VERSION = TMP_SERVICE_VERSION; -/** - * The name of the telemetry SDK as defined above. - * - * @deprecated Use ATTR_TELEMETRY_SDK_NAME. - */ -exports.SEMRESATTRS_TELEMETRY_SDK_NAME = TMP_TELEMETRY_SDK_NAME; -/** - * The language of the telemetry SDK. - * - * @deprecated Use ATTR_TELEMETRY_SDK_LANGUAGE. - */ -exports.SEMRESATTRS_TELEMETRY_SDK_LANGUAGE = TMP_TELEMETRY_SDK_LANGUAGE; -/** - * The version string of the telemetry SDK. - * - * @deprecated Use ATTR_TELEMETRY_SDK_VERSION. - */ -exports.SEMRESATTRS_TELEMETRY_SDK_VERSION = TMP_TELEMETRY_SDK_VERSION; -/** - * The version string of the auto instrumentation agent, if used. - * - * @deprecated Use ATTR_TELEMETRY_DISTRO_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_TELEMETRY_AUTO_VERSION = TMP_TELEMETRY_AUTO_VERSION; -/** - * The name of the web engine. - * - * @deprecated Use ATTR_WEBENGINE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_WEBENGINE_NAME = TMP_WEBENGINE_NAME; -/** - * The version of the web engine. - * - * @deprecated Use ATTR_WEBENGINE_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_WEBENGINE_VERSION = TMP_WEBENGINE_VERSION; -/** - * Additional description of the web engine (e.g. detailed version and edition information). - * - * @deprecated Use ATTR_WEBENGINE_DESCRIPTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMRESATTRS_WEBENGINE_DESCRIPTION = TMP_WEBENGINE_DESCRIPTION; -/** - * Create exported Value Map for SemanticResourceAttributes values - * @deprecated Use the SEMRESATTRS_XXXXX constants rather than the SemanticResourceAttributes.XXXXX for bundle minification - */ -exports.SemanticResourceAttributes = -/*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_CLOUD_PROVIDER, - TMP_CLOUD_ACCOUNT_ID, - TMP_CLOUD_REGION, - TMP_CLOUD_AVAILABILITY_ZONE, - TMP_CLOUD_PLATFORM, - TMP_AWS_ECS_CONTAINER_ARN, - TMP_AWS_ECS_CLUSTER_ARN, - TMP_AWS_ECS_LAUNCHTYPE, - TMP_AWS_ECS_TASK_ARN, - TMP_AWS_ECS_TASK_FAMILY, - TMP_AWS_ECS_TASK_REVISION, - TMP_AWS_EKS_CLUSTER_ARN, - TMP_AWS_LOG_GROUP_NAMES, - TMP_AWS_LOG_GROUP_ARNS, - TMP_AWS_LOG_STREAM_NAMES, - TMP_AWS_LOG_STREAM_ARNS, - TMP_CONTAINER_NAME, - TMP_CONTAINER_ID, - TMP_CONTAINER_RUNTIME, - TMP_CONTAINER_IMAGE_NAME, - TMP_CONTAINER_IMAGE_TAG, - TMP_DEPLOYMENT_ENVIRONMENT, - TMP_DEVICE_ID, - TMP_DEVICE_MODEL_IDENTIFIER, - TMP_DEVICE_MODEL_NAME, - TMP_FAAS_NAME, - TMP_FAAS_ID, - TMP_FAAS_VERSION, - TMP_FAAS_INSTANCE, - TMP_FAAS_MAX_MEMORY, - TMP_HOST_ID, - TMP_HOST_NAME, - TMP_HOST_TYPE, - TMP_HOST_ARCH, - TMP_HOST_IMAGE_NAME, - TMP_HOST_IMAGE_ID, - TMP_HOST_IMAGE_VERSION, - TMP_K8S_CLUSTER_NAME, - TMP_K8S_NODE_NAME, - TMP_K8S_NODE_UID, - TMP_K8S_NAMESPACE_NAME, - TMP_K8S_POD_UID, - TMP_K8S_POD_NAME, - TMP_K8S_CONTAINER_NAME, - TMP_K8S_REPLICASET_UID, - TMP_K8S_REPLICASET_NAME, - TMP_K8S_DEPLOYMENT_UID, - TMP_K8S_DEPLOYMENT_NAME, - TMP_K8S_STATEFULSET_UID, - TMP_K8S_STATEFULSET_NAME, - TMP_K8S_DAEMONSET_UID, - TMP_K8S_DAEMONSET_NAME, - TMP_K8S_JOB_UID, - TMP_K8S_JOB_NAME, - TMP_K8S_CRONJOB_UID, - TMP_K8S_CRONJOB_NAME, - TMP_OS_TYPE, - TMP_OS_DESCRIPTION, - TMP_OS_NAME, - TMP_OS_VERSION, - TMP_PROCESS_PID, - TMP_PROCESS_EXECUTABLE_NAME, - TMP_PROCESS_EXECUTABLE_PATH, - TMP_PROCESS_COMMAND, - TMP_PROCESS_COMMAND_LINE, - TMP_PROCESS_COMMAND_ARGS, - TMP_PROCESS_OWNER, - TMP_PROCESS_RUNTIME_NAME, - TMP_PROCESS_RUNTIME_VERSION, - TMP_PROCESS_RUNTIME_DESCRIPTION, - TMP_SERVICE_NAME, - TMP_SERVICE_NAMESPACE, - TMP_SERVICE_INSTANCE_ID, - TMP_SERVICE_VERSION, - TMP_TELEMETRY_SDK_NAME, - TMP_TELEMETRY_SDK_LANGUAGE, - TMP_TELEMETRY_SDK_VERSION, - TMP_TELEMETRY_AUTO_VERSION, - TMP_WEBENGINE_NAME, - TMP_WEBENGINE_VERSION, - TMP_WEBENGINE_DESCRIPTION, -]); -/* ---------------------------------------------------------------------------------------------------------- - * Constant values for CloudProviderValues enum definition - * - * Name of the cloud provider. - * ---------------------------------------------------------------------------------------------------------- */ -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD = 'alibaba_cloud'; -const TMP_CLOUDPROVIDERVALUES_AWS = 'aws'; -const TMP_CLOUDPROVIDERVALUES_AZURE = 'azure'; -const TMP_CLOUDPROVIDERVALUES_GCP = 'gcp'; -/** - * Name of the cloud provider. - * - * @deprecated Use CLOUD_PROVIDER_VALUE_ALIBABA_CLOUD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPROVIDERVALUES_ALIBABA_CLOUD = TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD; -/** - * Name of the cloud provider. - * - * @deprecated Use CLOUD_PROVIDER_VALUE_AWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPROVIDERVALUES_AWS = TMP_CLOUDPROVIDERVALUES_AWS; -/** - * Name of the cloud provider. - * - * @deprecated Use CLOUD_PROVIDER_VALUE_AZURE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPROVIDERVALUES_AZURE = TMP_CLOUDPROVIDERVALUES_AZURE; -/** - * Name of the cloud provider. - * - * @deprecated Use CLOUD_PROVIDER_VALUE_GCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPROVIDERVALUES_GCP = TMP_CLOUDPROVIDERVALUES_GCP; -/** - * The constant map of values for CloudProviderValues. - * @deprecated Use the CLOUDPROVIDERVALUES_XXXXX constants rather than the CloudProviderValues.XXXXX for bundle minification. - */ -exports.CloudProviderValues = -/*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_CLOUDPROVIDERVALUES_ALIBABA_CLOUD, - TMP_CLOUDPROVIDERVALUES_AWS, - TMP_CLOUDPROVIDERVALUES_AZURE, - TMP_CLOUDPROVIDERVALUES_GCP, -]); -/* ---------------------------------------------------------------------------------------------------------- - * Constant values for CloudPlatformValues enum definition - * - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * ---------------------------------------------------------------------------------------------------------- */ -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = 'alibaba_cloud_ecs'; -const TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = 'alibaba_cloud_fc'; -const TMP_CLOUDPLATFORMVALUES_AWS_EC2 = 'aws_ec2'; -const TMP_CLOUDPLATFORMVALUES_AWS_ECS = 'aws_ecs'; -const TMP_CLOUDPLATFORMVALUES_AWS_EKS = 'aws_eks'; -const TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA = 'aws_lambda'; -const TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = 'aws_elastic_beanstalk'; -const TMP_CLOUDPLATFORMVALUES_AZURE_VM = 'azure_vm'; -const TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = 'azure_container_instances'; -const TMP_CLOUDPLATFORMVALUES_AZURE_AKS = 'azure_aks'; -const TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = 'azure_functions'; -const TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = 'azure_app_service'; -const TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = 'gcp_compute_engine'; -const TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = 'gcp_cloud_run'; -const TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = 'gcp_kubernetes_engine'; -const TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = 'gcp_cloud_functions'; -const TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE = 'gcp_app_engine'; -/** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_ALIBABA_CLOUD_ECS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS; -/** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_ALIBABA_CLOUD_FC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC = TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC; -/** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_EC2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPLATFORMVALUES_AWS_EC2 = TMP_CLOUDPLATFORMVALUES_AWS_EC2; -/** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_ECS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPLATFORMVALUES_AWS_ECS = TMP_CLOUDPLATFORMVALUES_AWS_ECS; -/** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_EKS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPLATFORMVALUES_AWS_EKS = TMP_CLOUDPLATFORMVALUES_AWS_EKS; -/** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_LAMBDA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPLATFORMVALUES_AWS_LAMBDA = TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA; -/** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AWS_ELASTIC_BEANSTALK in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK = TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK; -/** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_VM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPLATFORMVALUES_AZURE_VM = TMP_CLOUDPLATFORMVALUES_AZURE_VM; -/** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_CONTAINER_INSTANCES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES = TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES; -/** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_AKS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPLATFORMVALUES_AZURE_AKS = TMP_CLOUDPLATFORMVALUES_AZURE_AKS; -/** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_FUNCTIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPLATFORMVALUES_AZURE_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS; -/** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_AZURE_APP_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPLATFORMVALUES_AZURE_APP_SERVICE = TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE; -/** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_COMPUTE_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE; -/** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_CLOUD_RUN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPLATFORMVALUES_GCP_CLOUD_RUN = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN; -/** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_KUBERNETES_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE; -/** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_CLOUD_FUNCTIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS = TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS; -/** - * The cloud platform in use. - * - * Note: The prefix of the service SHOULD match the one specified in `cloud.provider`. - * - * @deprecated Use CLOUD_PLATFORM_VALUE_GCP_APP_ENGINE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.CLOUDPLATFORMVALUES_GCP_APP_ENGINE = TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE; -/** - * The constant map of values for CloudPlatformValues. - * @deprecated Use the CLOUDPLATFORMVALUES_XXXXX constants rather than the CloudPlatformValues.XXXXX for bundle minification. - */ -exports.CloudPlatformValues = -/*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_ECS, - TMP_CLOUDPLATFORMVALUES_ALIBABA_CLOUD_FC, - TMP_CLOUDPLATFORMVALUES_AWS_EC2, - TMP_CLOUDPLATFORMVALUES_AWS_ECS, - TMP_CLOUDPLATFORMVALUES_AWS_EKS, - TMP_CLOUDPLATFORMVALUES_AWS_LAMBDA, - TMP_CLOUDPLATFORMVALUES_AWS_ELASTIC_BEANSTALK, - TMP_CLOUDPLATFORMVALUES_AZURE_VM, - TMP_CLOUDPLATFORMVALUES_AZURE_CONTAINER_INSTANCES, - TMP_CLOUDPLATFORMVALUES_AZURE_AKS, - TMP_CLOUDPLATFORMVALUES_AZURE_FUNCTIONS, - TMP_CLOUDPLATFORMVALUES_AZURE_APP_SERVICE, - TMP_CLOUDPLATFORMVALUES_GCP_COMPUTE_ENGINE, - TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_RUN, - TMP_CLOUDPLATFORMVALUES_GCP_KUBERNETES_ENGINE, - TMP_CLOUDPLATFORMVALUES_GCP_CLOUD_FUNCTIONS, - TMP_CLOUDPLATFORMVALUES_GCP_APP_ENGINE, -]); -/* ---------------------------------------------------------------------------------------------------------- - * Constant values for AwsEcsLaunchtypeValues enum definition - * - * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. - * ---------------------------------------------------------------------------------------------------------- */ -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_AWSECSLAUNCHTYPEVALUES_EC2 = 'ec2'; -const TMP_AWSECSLAUNCHTYPEVALUES_FARGATE = 'fargate'; -/** - * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. - * - * @deprecated Use AWS_ECS_LAUNCHTYPE_VALUE_EC2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.AWSECSLAUNCHTYPEVALUES_EC2 = TMP_AWSECSLAUNCHTYPEVALUES_EC2; -/** - * The [launch type](https://docs.aws.amazon.com/AmazonECS/latest/developerguide/launch_types.html) for an ECS task. - * - * @deprecated Use AWS_ECS_LAUNCHTYPE_VALUE_FARGATE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.AWSECSLAUNCHTYPEVALUES_FARGATE = TMP_AWSECSLAUNCHTYPEVALUES_FARGATE; -/** - * The constant map of values for AwsEcsLaunchtypeValues. - * @deprecated Use the AWSECSLAUNCHTYPEVALUES_XXXXX constants rather than the AwsEcsLaunchtypeValues.XXXXX for bundle minification. - */ -exports.AwsEcsLaunchtypeValues = -/*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_AWSECSLAUNCHTYPEVALUES_EC2, - TMP_AWSECSLAUNCHTYPEVALUES_FARGATE, -]); -/* ---------------------------------------------------------------------------------------------------------- - * Constant values for HostArchValues enum definition - * - * The CPU architecture the host system is running on. - * ---------------------------------------------------------------------------------------------------------- */ -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_HOSTARCHVALUES_AMD64 = 'amd64'; -const TMP_HOSTARCHVALUES_ARM32 = 'arm32'; -const TMP_HOSTARCHVALUES_ARM64 = 'arm64'; -const TMP_HOSTARCHVALUES_IA64 = 'ia64'; -const TMP_HOSTARCHVALUES_PPC32 = 'ppc32'; -const TMP_HOSTARCHVALUES_PPC64 = 'ppc64'; -const TMP_HOSTARCHVALUES_X86 = 'x86'; -/** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_AMD64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.HOSTARCHVALUES_AMD64 = TMP_HOSTARCHVALUES_AMD64; -/** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_ARM32 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.HOSTARCHVALUES_ARM32 = TMP_HOSTARCHVALUES_ARM32; -/** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_ARM64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.HOSTARCHVALUES_ARM64 = TMP_HOSTARCHVALUES_ARM64; -/** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_IA64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.HOSTARCHVALUES_IA64 = TMP_HOSTARCHVALUES_IA64; -/** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_PPC32 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.HOSTARCHVALUES_PPC32 = TMP_HOSTARCHVALUES_PPC32; -/** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_PPC64 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.HOSTARCHVALUES_PPC64 = TMP_HOSTARCHVALUES_PPC64; -/** - * The CPU architecture the host system is running on. - * - * @deprecated Use HOST_ARCH_VALUE_X86 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.HOSTARCHVALUES_X86 = TMP_HOSTARCHVALUES_X86; -/** - * The constant map of values for HostArchValues. - * @deprecated Use the HOSTARCHVALUES_XXXXX constants rather than the HostArchValues.XXXXX for bundle minification. - */ -exports.HostArchValues = -/*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_HOSTARCHVALUES_AMD64, - TMP_HOSTARCHVALUES_ARM32, - TMP_HOSTARCHVALUES_ARM64, - TMP_HOSTARCHVALUES_IA64, - TMP_HOSTARCHVALUES_PPC32, - TMP_HOSTARCHVALUES_PPC64, - TMP_HOSTARCHVALUES_X86, -]); -/* ---------------------------------------------------------------------------------------------------------- - * Constant values for OsTypeValues enum definition - * - * The operating system type. - * ---------------------------------------------------------------------------------------------------------- */ -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_OSTYPEVALUES_WINDOWS = 'windows'; -const TMP_OSTYPEVALUES_LINUX = 'linux'; -const TMP_OSTYPEVALUES_DARWIN = 'darwin'; -const TMP_OSTYPEVALUES_FREEBSD = 'freebsd'; -const TMP_OSTYPEVALUES_NETBSD = 'netbsd'; -const TMP_OSTYPEVALUES_OPENBSD = 'openbsd'; -const TMP_OSTYPEVALUES_DRAGONFLYBSD = 'dragonflybsd'; -const TMP_OSTYPEVALUES_HPUX = 'hpux'; -const TMP_OSTYPEVALUES_AIX = 'aix'; -const TMP_OSTYPEVALUES_SOLARIS = 'solaris'; -const TMP_OSTYPEVALUES_Z_OS = 'z_os'; -/** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_WINDOWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.OSTYPEVALUES_WINDOWS = TMP_OSTYPEVALUES_WINDOWS; -/** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_LINUX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.OSTYPEVALUES_LINUX = TMP_OSTYPEVALUES_LINUX; -/** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_DARWIN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.OSTYPEVALUES_DARWIN = TMP_OSTYPEVALUES_DARWIN; -/** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_FREEBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.OSTYPEVALUES_FREEBSD = TMP_OSTYPEVALUES_FREEBSD; -/** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_NETBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.OSTYPEVALUES_NETBSD = TMP_OSTYPEVALUES_NETBSD; -/** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_OPENBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.OSTYPEVALUES_OPENBSD = TMP_OSTYPEVALUES_OPENBSD; -/** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_DRAGONFLYBSD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.OSTYPEVALUES_DRAGONFLYBSD = TMP_OSTYPEVALUES_DRAGONFLYBSD; -/** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_HPUX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.OSTYPEVALUES_HPUX = TMP_OSTYPEVALUES_HPUX; -/** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_AIX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.OSTYPEVALUES_AIX = TMP_OSTYPEVALUES_AIX; -/** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_SOLARIS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.OSTYPEVALUES_SOLARIS = TMP_OSTYPEVALUES_SOLARIS; -/** - * The operating system type. - * - * @deprecated Use OS_TYPE_VALUE_Z_OS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.OSTYPEVALUES_Z_OS = TMP_OSTYPEVALUES_Z_OS; -/** - * The constant map of values for OsTypeValues. - * @deprecated Use the OSTYPEVALUES_XXXXX constants rather than the OsTypeValues.XXXXX for bundle minification. - */ -exports.OsTypeValues = -/*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_OSTYPEVALUES_WINDOWS, - TMP_OSTYPEVALUES_LINUX, - TMP_OSTYPEVALUES_DARWIN, - TMP_OSTYPEVALUES_FREEBSD, - TMP_OSTYPEVALUES_NETBSD, - TMP_OSTYPEVALUES_OPENBSD, - TMP_OSTYPEVALUES_DRAGONFLYBSD, - TMP_OSTYPEVALUES_HPUX, - TMP_OSTYPEVALUES_AIX, - TMP_OSTYPEVALUES_SOLARIS, - TMP_OSTYPEVALUES_Z_OS, -]); -/* ---------------------------------------------------------------------------------------------------------- - * Constant values for TelemetrySdkLanguageValues enum definition - * - * The language of the telemetry SDK. - * ---------------------------------------------------------------------------------------------------------- */ -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_TELEMETRYSDKLANGUAGEVALUES_CPP = 'cpp'; -const TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET = 'dotnet'; -const TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG = 'erlang'; -const TMP_TELEMETRYSDKLANGUAGEVALUES_GO = 'go'; -const TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA = 'java'; -const TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS = 'nodejs'; -const TMP_TELEMETRYSDKLANGUAGEVALUES_PHP = 'php'; -const TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON = 'python'; -const TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY = 'ruby'; -const TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS = 'webjs'; -/** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_CPP. - */ -exports.TELEMETRYSDKLANGUAGEVALUES_CPP = TMP_TELEMETRYSDKLANGUAGEVALUES_CPP; -/** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET. - */ -exports.TELEMETRYSDKLANGUAGEVALUES_DOTNET = TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET; -/** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG. - */ -exports.TELEMETRYSDKLANGUAGEVALUES_ERLANG = TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG; -/** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_GO. - */ -exports.TELEMETRYSDKLANGUAGEVALUES_GO = TMP_TELEMETRYSDKLANGUAGEVALUES_GO; -/** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_JAVA. - */ -exports.TELEMETRYSDKLANGUAGEVALUES_JAVA = TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA; -/** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS. - */ -exports.TELEMETRYSDKLANGUAGEVALUES_NODEJS = TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS; -/** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_PHP. - */ -exports.TELEMETRYSDKLANGUAGEVALUES_PHP = TMP_TELEMETRYSDKLANGUAGEVALUES_PHP; -/** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON. - */ -exports.TELEMETRYSDKLANGUAGEVALUES_PYTHON = TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON; -/** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_RUBY. - */ -exports.TELEMETRYSDKLANGUAGEVALUES_RUBY = TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY; -/** - * The language of the telemetry SDK. - * - * @deprecated Use TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS. - */ -exports.TELEMETRYSDKLANGUAGEVALUES_WEBJS = TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS; -/** - * The constant map of values for TelemetrySdkLanguageValues. - * @deprecated Use the TELEMETRYSDKLANGUAGEVALUES_XXXXX constants rather than the TelemetrySdkLanguageValues.XXXXX for bundle minification. - */ -exports.TelemetrySdkLanguageValues = -/*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_TELEMETRYSDKLANGUAGEVALUES_CPP, - TMP_TELEMETRYSDKLANGUAGEVALUES_DOTNET, - TMP_TELEMETRYSDKLANGUAGEVALUES_ERLANG, - TMP_TELEMETRYSDKLANGUAGEVALUES_GO, - TMP_TELEMETRYSDKLANGUAGEVALUES_JAVA, - TMP_TELEMETRYSDKLANGUAGEVALUES_NODEJS, - TMP_TELEMETRYSDKLANGUAGEVALUES_PHP, - TMP_TELEMETRYSDKLANGUAGEVALUES_PYTHON, - TMP_TELEMETRYSDKLANGUAGEVALUES_RUBY, - TMP_TELEMETRYSDKLANGUAGEVALUES_WEBJS, -]); -//# sourceMappingURL=SemanticResourceAttributes.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/resource/index.js b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/resource/index.js deleted file mode 100644 index aa8ee5bd..00000000 --- a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/resource/index.js +++ /dev/null @@ -1,37 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -/* eslint-disable no-restricted-syntax -- - * These re-exports are only of constants, only one-level deep at this point, - * and should not cause problems for tree-shakers. - */ -__exportStar(require("./SemanticResourceAttributes"), exports); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_attributes.js b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_attributes.js deleted file mode 100644 index df1cc9a1..00000000 --- a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_attributes.js +++ /dev/null @@ -1,1085 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ATTR_EXCEPTION_TYPE = exports.ATTR_EXCEPTION_STACKTRACE = exports.ATTR_EXCEPTION_MESSAGE = exports.ATTR_EXCEPTION_ESCAPED = exports.ERROR_TYPE_VALUE_OTHER = exports.ATTR_ERROR_TYPE = exports.DOTNET_GC_HEAP_GENERATION_VALUE_POH = exports.DOTNET_GC_HEAP_GENERATION_VALUE_LOH = exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = exports.ATTR_DOTNET_GC_HEAP_GENERATION = exports.DB_SYSTEM_NAME_VALUE_POSTGRESQL = exports.DB_SYSTEM_NAME_VALUE_MYSQL = exports.DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = exports.DB_SYSTEM_NAME_VALUE_MARIADB = exports.ATTR_DB_SYSTEM_NAME = exports.ATTR_DB_STORED_PROCEDURE_NAME = exports.ATTR_DB_RESPONSE_STATUS_CODE = exports.ATTR_DB_QUERY_TEXT = exports.ATTR_DB_QUERY_SUMMARY = exports.ATTR_DB_OPERATION_NAME = exports.ATTR_DB_OPERATION_BATCH_SIZE = exports.ATTR_DB_NAMESPACE = exports.ATTR_DB_COLLECTION_NAME = exports.ATTR_CODE_STACKTRACE = exports.ATTR_CODE_LINE_NUMBER = exports.ATTR_CODE_FUNCTION_NAME = exports.ATTR_CODE_FILE_PATH = exports.ATTR_CODE_COLUMN_NUMBER = exports.ATTR_CLIENT_PORT = exports.ATTR_CLIENT_ADDRESS = exports.ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = exports.ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = exports.ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = exports.ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = exports.ATTR_ASPNETCORE_RATE_LIMITING_RESULT = exports.ATTR_ASPNETCORE_RATE_LIMITING_POLICY = exports.ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = exports.ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = void 0; -exports.OTEL_STATUS_CODE_VALUE_ERROR = exports.ATTR_OTEL_STATUS_CODE = exports.ATTR_OTEL_SCOPE_VERSION = exports.ATTR_OTEL_SCOPE_NAME = exports.NETWORK_TYPE_VALUE_IPV6 = exports.NETWORK_TYPE_VALUE_IPV4 = exports.ATTR_NETWORK_TYPE = exports.NETWORK_TRANSPORT_VALUE_UNIX = exports.NETWORK_TRANSPORT_VALUE_UDP = exports.NETWORK_TRANSPORT_VALUE_TCP = exports.NETWORK_TRANSPORT_VALUE_QUIC = exports.NETWORK_TRANSPORT_VALUE_PIPE = exports.ATTR_NETWORK_TRANSPORT = exports.ATTR_NETWORK_PROTOCOL_VERSION = exports.ATTR_NETWORK_PROTOCOL_NAME = exports.ATTR_NETWORK_PEER_PORT = exports.ATTR_NETWORK_PEER_ADDRESS = exports.ATTR_NETWORK_LOCAL_PORT = exports.ATTR_NETWORK_LOCAL_ADDRESS = exports.JVM_THREAD_STATE_VALUE_WAITING = exports.JVM_THREAD_STATE_VALUE_TIMED_WAITING = exports.JVM_THREAD_STATE_VALUE_TERMINATED = exports.JVM_THREAD_STATE_VALUE_RUNNABLE = exports.JVM_THREAD_STATE_VALUE_NEW = exports.JVM_THREAD_STATE_VALUE_BLOCKED = exports.ATTR_JVM_THREAD_STATE = exports.ATTR_JVM_THREAD_DAEMON = exports.JVM_MEMORY_TYPE_VALUE_NON_HEAP = exports.JVM_MEMORY_TYPE_VALUE_HEAP = exports.ATTR_JVM_MEMORY_TYPE = exports.ATTR_JVM_MEMORY_POOL_NAME = exports.ATTR_JVM_GC_NAME = exports.ATTR_JVM_GC_ACTION = exports.ATTR_HTTP_ROUTE = exports.ATTR_HTTP_RESPONSE_STATUS_CODE = exports.ATTR_HTTP_RESPONSE_HEADER = exports.ATTR_HTTP_REQUEST_RESEND_COUNT = exports.ATTR_HTTP_REQUEST_METHOD_ORIGINAL = exports.HTTP_REQUEST_METHOD_VALUE_TRACE = exports.HTTP_REQUEST_METHOD_VALUE_PUT = exports.HTTP_REQUEST_METHOD_VALUE_POST = exports.HTTP_REQUEST_METHOD_VALUE_PATCH = exports.HTTP_REQUEST_METHOD_VALUE_OPTIONS = exports.HTTP_REQUEST_METHOD_VALUE_HEAD = exports.HTTP_REQUEST_METHOD_VALUE_GET = exports.HTTP_REQUEST_METHOD_VALUE_DELETE = exports.HTTP_REQUEST_METHOD_VALUE_CONNECT = exports.HTTP_REQUEST_METHOD_VALUE_OTHER = exports.ATTR_HTTP_REQUEST_METHOD = exports.ATTR_HTTP_REQUEST_HEADER = void 0; -exports.ATTR_USER_AGENT_ORIGINAL = exports.ATTR_URL_SCHEME = exports.ATTR_URL_QUERY = exports.ATTR_URL_PATH = exports.ATTR_URL_FULL = exports.ATTR_URL_FRAGMENT = exports.ATTR_TELEMETRY_SDK_VERSION = exports.ATTR_TELEMETRY_SDK_NAME = exports.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = exports.TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUST = exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = exports.TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = exports.TELEMETRY_SDK_LANGUAGE_VALUE_PHP = exports.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = exports.TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = exports.TELEMETRY_SDK_LANGUAGE_VALUE_GO = exports.TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = exports.TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = exports.TELEMETRY_SDK_LANGUAGE_VALUE_CPP = exports.ATTR_TELEMETRY_SDK_LANGUAGE = exports.SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = exports.SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = exports.SIGNALR_TRANSPORT_VALUE_LONG_POLLING = exports.ATTR_SIGNALR_TRANSPORT = exports.SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = exports.SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = exports.SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = exports.ATTR_SIGNALR_CONNECTION_STATUS = exports.ATTR_SERVICE_VERSION = exports.ATTR_SERVICE_NAME = exports.ATTR_SERVER_PORT = exports.ATTR_SERVER_ADDRESS = exports.ATTR_OTEL_STATUS_DESCRIPTION = exports.OTEL_STATUS_CODE_VALUE_OK = void 0; -//---------------------------------------------------------------------------------------------------------- -// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/registry/stable/attributes.ts.j2 -//---------------------------------------------------------------------------------------------------------- -/** - * ASP.NET Core exception middleware handling result. - * - * @example handled - * @example unhandled - */ -exports.ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT = 'aspnetcore.diagnostics.exception.result'; -/** - * Enum value "aborted" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. - * - * Exception handling didn't run because the request was aborted. - */ -exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_ABORTED = "aborted"; -/** - * Enum value "handled" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. - * - * Exception was handled by the exception handling middleware. - */ -exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_HANDLED = "handled"; -/** - * Enum value "skipped" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. - * - * Exception handling was skipped because the response had started. - */ -exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_SKIPPED = "skipped"; -/** - * Enum value "unhandled" for attribute {@link ATTR_ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT}. - * - * Exception was not handled by the exception handling middleware. - */ -exports.ASPNETCORE_DIAGNOSTICS_EXCEPTION_RESULT_VALUE_UNHANDLED = "unhandled"; -/** - * Full type name of the [`IExceptionHandler`](https://learn.microsoft.com/dotnet/api/microsoft.aspnetcore.diagnostics.iexceptionhandler) implementation that handled the exception. - * - * @example Contoso.MyHandler - */ -exports.ATTR_ASPNETCORE_DIAGNOSTICS_HANDLER_TYPE = 'aspnetcore.diagnostics.handler.type'; -/** - * Rate limiting policy name. - * - * @example fixed - * @example sliding - * @example token - */ -exports.ATTR_ASPNETCORE_RATE_LIMITING_POLICY = 'aspnetcore.rate_limiting.policy'; -/** - * Rate-limiting result, shows whether the lease was acquired or contains a rejection reason - * - * @example acquired - * @example request_canceled - */ -exports.ATTR_ASPNETCORE_RATE_LIMITING_RESULT = 'aspnetcore.rate_limiting.result'; -/** - * Enum value "acquired" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. - * - * Lease was acquired - */ -exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ACQUIRED = "acquired"; -/** - * Enum value "endpoint_limiter" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. - * - * Lease request was rejected by the endpoint limiter - */ -exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_ENDPOINT_LIMITER = "endpoint_limiter"; -/** - * Enum value "global_limiter" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. - * - * Lease request was rejected by the global limiter - */ -exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_GLOBAL_LIMITER = "global_limiter"; -/** - * Enum value "request_canceled" for attribute {@link ATTR_ASPNETCORE_RATE_LIMITING_RESULT}. - * - * Lease request was canceled - */ -exports.ASPNETCORE_RATE_LIMITING_RESULT_VALUE_REQUEST_CANCELED = "request_canceled"; -/** - * Flag indicating if request was handled by the application pipeline. - * - * @example true - */ -exports.ATTR_ASPNETCORE_REQUEST_IS_UNHANDLED = 'aspnetcore.request.is_unhandled'; -/** - * A value that indicates whether the matched route is a fallback route. - * - * @example true - */ -exports.ATTR_ASPNETCORE_ROUTING_IS_FALLBACK = 'aspnetcore.routing.is_fallback'; -/** - * Match result - success or failure - * - * @example success - * @example failure - */ -exports.ATTR_ASPNETCORE_ROUTING_MATCH_STATUS = 'aspnetcore.routing.match_status'; -/** - * Enum value "failure" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}. - * - * Match failed - */ -exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_FAILURE = "failure"; -/** - * Enum value "success" for attribute {@link ATTR_ASPNETCORE_ROUTING_MATCH_STATUS}. - * - * Match succeeded - */ -exports.ASPNETCORE_ROUTING_MATCH_STATUS_VALUE_SUCCESS = "success"; -/** - * A value that indicates whether the user is authenticated. - * - * @example true - */ -exports.ATTR_ASPNETCORE_USER_IS_AUTHENTICATED = 'aspnetcore.user.is_authenticated'; -/** - * Client address - domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name. - * - * @example client.example.com - * @example 10.1.2.80 - * @example /tmp/my.sock - * - * @note When observed from the server side, and when communicating through an intermediary, `client.address` **SHOULD** represent the client address behind any intermediaries, for example proxies, if it's available. - */ -exports.ATTR_CLIENT_ADDRESS = 'client.address'; -/** - * Client port number. - * - * @example 65123 - * - * @note When observed from the server side, and when communicating through an intermediary, `client.port` **SHOULD** represent the client port behind any intermediaries, for example proxies, if it's available. - */ -exports.ATTR_CLIENT_PORT = 'client.port'; -/** - * The column number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity. - * - * @example 16 - */ -exports.ATTR_CODE_COLUMN_NUMBER = 'code.column.number'; -/** - * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity. - * - * @example "/usr/local/MyApplication/content_root/app/index.php" - */ -exports.ATTR_CODE_FILE_PATH = 'code.file.path'; -/** - * The method or function fully-qualified name without arguments. The value should fit the natural representation of the language runtime, which is also likely the same used within `code.stacktrace` attribute value. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Function'. This constraint is imposed to prevent redundancy and maintain data integrity. - * - * @example com.example.MyHttpService.serveRequest - * @example GuzzleHttp\\Client::transfer - * @example fopen - * - * @note Values and format depends on each language runtime, thus it is impossible to provide an exhaustive list of examples. - * The values are usually the same (or prefixes of) the ones found in native stack trace representation stored in - * `code.stacktrace` without information on arguments. - * - * Examples: - * - * - Java method: `com.example.MyHttpService.serveRequest` - * - Java anonymous class method: `com.mycompany.Main$1.myMethod` - * - Java lambda method: `com.mycompany.Main$$Lambda/0x0000748ae4149c00.myMethod` - * - PHP function: `GuzzleHttp\Client::transfer` - * - Go function: `github.com/my/repo/pkg.foo.func5` - * - Elixir: `OpenTelemetry.Ctx.new` - * - Erlang: `opentelemetry_ctx:new` - * - Rust: `playground::my_module::my_cool_func` - * - C function: `fopen` - */ -exports.ATTR_CODE_FUNCTION_NAME = 'code.function.name'; -/** - * The line number in `code.file.path` best representing the operation. It **SHOULD** point within the code unit named in `code.function.name`. This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Line'. This constraint is imposed to prevent redundancy and maintain data integrity. - * - * @example 42 - */ -exports.ATTR_CODE_LINE_NUMBER = 'code.line.number'; -/** - * A stacktrace as a string in the natural representation for the language runtime. The representation is identical to [`exception.stacktrace`](/docs/exceptions/exceptions-spans.md#stacktrace-representation). This attribute **MUST NOT** be used on the Profile signal since the data is already captured in 'message Location'. This constraint is imposed to prevent redundancy and maintain data integrity. - * - * @example "at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\n" - */ -exports.ATTR_CODE_STACKTRACE = 'code.stacktrace'; -/** - * The name of a collection (table, container) within the database. - * - * @example public.users - * @example customers - * - * @note It is **RECOMMENDED** to capture the value as provided by the application - * without attempting to do any case normalization. - * - * The collection name **SHOULD NOT** be extracted from `db.query.text`, - * when the database system supports query text with multiple collections - * in non-batch operations. - * - * For batch operations, if the individual operations are known to have the same - * collection name then that collection name **SHOULD** be used. - */ -exports.ATTR_DB_COLLECTION_NAME = 'db.collection.name'; -/** - * The name of the database, fully qualified within the server address and port. - * - * @example customers - * @example test.users - * - * @note If a database system has multiple namespace components, they **SHOULD** be concatenated from the most general to the most specific namespace component, using `|` as a separator between the components. Any missing components (and their associated separators) **SHOULD** be omitted. - * Semantic conventions for individual database systems **SHOULD** document what `db.namespace` means in the context of that system. - * It is **RECOMMENDED** to capture the value as provided by the application without attempting to do any case normalization. - */ -exports.ATTR_DB_NAMESPACE = 'db.namespace'; -/** - * The number of queries included in a batch operation. - * - * @example 2 - * @example 3 - * @example 4 - * - * @note Operations are only considered batches when they contain two or more operations, and so `db.operation.batch.size` **SHOULD** never be `1`. - */ -exports.ATTR_DB_OPERATION_BATCH_SIZE = 'db.operation.batch.size'; -/** - * The name of the operation or command being executed. - * - * @example findAndModify - * @example HMSET - * @example SELECT - * - * @note It is **RECOMMENDED** to capture the value as provided by the application - * without attempting to do any case normalization. - * - * The operation name **SHOULD NOT** be extracted from `db.query.text`, - * when the database system supports query text with multiple operations - * in non-batch operations. - * - * If spaces can occur in the operation name, multiple consecutive spaces - * **SHOULD** be normalized to a single space. - * - * For batch operations, if the individual operations are known to have the same operation name - * then that operation name **SHOULD** be used prepended by `BATCH `, - * otherwise `db.operation.name` **SHOULD** be `BATCH` or some other database - * system specific term if more applicable. - */ -exports.ATTR_DB_OPERATION_NAME = 'db.operation.name'; -/** - * Low cardinality summary of a database query. - * - * @example SELECT wuser_table - * @example INSERT shipping_details SELECT orders - * @example get user by id - * - * @note The query summary describes a class of database queries and is useful - * as a grouping key, especially when analyzing telemetry for database - * calls involving complex queries. - * - * Summary may be available to the instrumentation through - * instrumentation hooks or other means. If it is not available, instrumentations - * that support query parsing **SHOULD** generate a summary following - * [Generating query summary](/docs/database/database-spans.md#generating-a-summary-of-the-query) - * section. - */ -exports.ATTR_DB_QUERY_SUMMARY = 'db.query.summary'; -/** - * The database query being executed. - * - * @example SELECT * FROM wuser_table where username = ? - * @example SET mykey ? - * - * @note For sanitization see [Sanitization of `db.query.text`](/docs/database/database-spans.md#sanitization-of-dbquerytext). - * For batch operations, if the individual operations are known to have the same query text then that query text **SHOULD** be used, otherwise all of the individual query texts **SHOULD** be concatenated with separator `; ` or some other database system specific separator if more applicable. - * Parameterized query text **SHOULD NOT** be sanitized. Even though parameterized query text can potentially have sensitive data, by using a parameterized query the user is giving a strong signal that any sensitive data will be passed as parameter values, and the benefit to observability of capturing the static part of the query text by default outweighs the risk. - */ -exports.ATTR_DB_QUERY_TEXT = 'db.query.text'; -/** - * Database response status code. - * - * @example 102 - * @example ORA-17002 - * @example 08P01 - * @example 404 - * - * @note The status code returned by the database. Usually it represents an error code, but may also represent partial success, warning, or differentiate between various types of successful outcomes. - * Semantic conventions for individual database systems **SHOULD** document what `db.response.status_code` means in the context of that system. - */ -exports.ATTR_DB_RESPONSE_STATUS_CODE = 'db.response.status_code'; -/** - * The name of a stored procedure within the database. - * - * @example GetCustomer - * - * @note It is **RECOMMENDED** to capture the value as provided by the application - * without attempting to do any case normalization. - * - * For batch operations, if the individual operations are known to have the same - * stored procedure name then that stored procedure name **SHOULD** be used. - */ -exports.ATTR_DB_STORED_PROCEDURE_NAME = 'db.stored_procedure.name'; -/** - * The database management system (DBMS) product as identified by the client instrumentation. - * - * @note The actual DBMS may differ from the one identified by the client. For example, when using PostgreSQL client libraries to connect to a CockroachDB, the `db.system.name` is set to `postgresql` based on the instrumentation's best knowledge. - */ -exports.ATTR_DB_SYSTEM_NAME = 'db.system.name'; -/** - * Enum value "mariadb" for attribute {@link ATTR_DB_SYSTEM_NAME}. - * - * [MariaDB](https://mariadb.org/) - */ -exports.DB_SYSTEM_NAME_VALUE_MARIADB = "mariadb"; -/** - * Enum value "microsoft.sql_server" for attribute {@link ATTR_DB_SYSTEM_NAME}. - * - * [Microsoft SQL Server](https://www.microsoft.com/sql-server) - */ -exports.DB_SYSTEM_NAME_VALUE_MICROSOFT_SQL_SERVER = "microsoft.sql_server"; -/** - * Enum value "mysql" for attribute {@link ATTR_DB_SYSTEM_NAME}. - * - * [MySQL](https://www.mysql.com/) - */ -exports.DB_SYSTEM_NAME_VALUE_MYSQL = "mysql"; -/** - * Enum value "postgresql" for attribute {@link ATTR_DB_SYSTEM_NAME}. - * - * [PostgreSQL](https://www.postgresql.org/) - */ -exports.DB_SYSTEM_NAME_VALUE_POSTGRESQL = "postgresql"; -/** - * Name of the garbage collector managed heap generation. - * - * @example gen0 - * @example gen1 - * @example gen2 - */ -exports.ATTR_DOTNET_GC_HEAP_GENERATION = 'dotnet.gc.heap.generation'; -/** - * Enum value "gen0" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. - * - * Generation 0 - */ -exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN0 = "gen0"; -/** - * Enum value "gen1" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. - * - * Generation 1 - */ -exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN1 = "gen1"; -/** - * Enum value "gen2" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. - * - * Generation 2 - */ -exports.DOTNET_GC_HEAP_GENERATION_VALUE_GEN2 = "gen2"; -/** - * Enum value "loh" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. - * - * Large Object Heap - */ -exports.DOTNET_GC_HEAP_GENERATION_VALUE_LOH = "loh"; -/** - * Enum value "poh" for attribute {@link ATTR_DOTNET_GC_HEAP_GENERATION}. - * - * Pinned Object Heap - */ -exports.DOTNET_GC_HEAP_GENERATION_VALUE_POH = "poh"; -/** - * Describes a class of error the operation ended with. - * - * @example timeout - * @example java.net.UnknownHostException - * @example server_certificate_invalid - * @example 500 - * - * @note The `error.type` **SHOULD** be predictable, and **SHOULD** have low cardinality. - * - * When `error.type` is set to a type (e.g., an exception type), its - * canonical class name identifying the type within the artifact **SHOULD** be used. - * - * Instrumentations **SHOULD** document the list of errors they report. - * - * The cardinality of `error.type` within one instrumentation library **SHOULD** be low. - * Telemetry consumers that aggregate data from multiple instrumentation libraries and applications - * should be prepared for `error.type` to have high cardinality at query time when no - * additional filters are applied. - * - * If the operation has completed successfully, instrumentations **SHOULD NOT** set `error.type`. - * - * If a specific domain defines its own set of error identifiers (such as HTTP or gRPC status codes), - * it's **RECOMMENDED** to: - * - * - Use a domain-specific attribute - * - Set `error.type` to capture all errors, regardless of whether they are defined within the domain-specific set or not. - */ -exports.ATTR_ERROR_TYPE = 'error.type'; -/** - * Enum value "_OTHER" for attribute {@link ATTR_ERROR_TYPE}. - * - * A fallback error value to be used when the instrumentation doesn't define a custom value. - */ -exports.ERROR_TYPE_VALUE_OTHER = "_OTHER"; -/** - * Indicates that the exception is escaping the scope of the span. - * - * @deprecated It's no longer recommended to record exceptions that are handled and do not escape the scope of a span. - */ -exports.ATTR_EXCEPTION_ESCAPED = 'exception.escaped'; -/** - * The exception message. - * - * @example Division by zero - * @example Can't convert 'int' object to str implicitly - */ -exports.ATTR_EXCEPTION_MESSAGE = 'exception.message'; -/** - * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG. - * - * @example "Exception in thread "main" java.lang.RuntimeException: Test exception\\n at com.example.GenerateTrace.methodB(GenerateTrace.java:13)\\n at com.example.GenerateTrace.methodA(GenerateTrace.java:9)\\n at com.example.GenerateTrace.main(GenerateTrace.java:5)\\n" - */ -exports.ATTR_EXCEPTION_STACKTRACE = 'exception.stacktrace'; -/** - * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it. - * - * @example java.net.ConnectException - * @example OSError - */ -exports.ATTR_EXCEPTION_TYPE = 'exception.type'; -/** - * HTTP request headers, `` being the normalized HTTP Header name (lowercase), the value being the header values. - * - * @example ["application/json"] - * @example ["1.2.3.4", "1.2.3.5"] - * - * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured. - * Including all request headers can be a security risk - explicit configuration helps avoid leaking sensitive information. - * - * The `User-Agent` header is already captured in the `user_agent.original` attribute. - * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended. - * - * The attribute value **MUST** consist of either multiple header values as an array of strings - * or a single-item array containing a possibly comma-concatenated string, depending on the way - * the HTTP library provides access to headers. - * - * Examples: - * - * - A header `Content-Type: application/json` **SHOULD** be recorded as the `http.request.header.content-type` - * attribute with value `["application/json"]`. - * - A header `X-Forwarded-For: 1.2.3.4, 1.2.3.5` **SHOULD** be recorded as the `http.request.header.x-forwarded-for` - * attribute with value `["1.2.3.4", "1.2.3.5"]` or `["1.2.3.4, 1.2.3.5"]` depending on the HTTP library. - */ -const ATTR_HTTP_REQUEST_HEADER = (key) => `http.request.header.${key}`; -exports.ATTR_HTTP_REQUEST_HEADER = ATTR_HTTP_REQUEST_HEADER; -/** - * HTTP request method. - * - * @example GET - * @example POST - * @example HEAD - * - * @note HTTP request method value **SHOULD** be "known" to the instrumentation. - * By default, this convention defines "known" methods as the ones listed in [RFC9110](https://www.rfc-editor.org/rfc/rfc9110.html#name-methods) - * and the PATCH method defined in [RFC5789](https://www.rfc-editor.org/rfc/rfc5789.html). - * - * If the HTTP request method is not known to instrumentation, it **MUST** set the `http.request.method` attribute to `_OTHER`. - * - * If the HTTP instrumentation could end up converting valid HTTP request methods to `_OTHER`, then it **MUST** provide a way to override - * the list of known HTTP methods. If this override is done via environment variable, then the environment variable **MUST** be named - * OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS and support a comma-separated list of case-sensitive known HTTP methods - * (this list **MUST** be a full override of the default known method, it is not a list of known methods in addition to the defaults). - * - * HTTP method names are case-sensitive and `http.request.method` attribute value **MUST** match a known HTTP method name exactly. - * Instrumentations for specific web frameworks that consider HTTP methods to be case insensitive, **SHOULD** populate a canonical equivalent. - * Tracing instrumentations that do so, **MUST** also set `http.request.method_original` to the original value. - */ -exports.ATTR_HTTP_REQUEST_METHOD = 'http.request.method'; -/** - * Enum value "_OTHER" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * Any HTTP method that the instrumentation has no prior knowledge of. - */ -exports.HTTP_REQUEST_METHOD_VALUE_OTHER = "_OTHER"; -/** - * Enum value "CONNECT" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * CONNECT method. - */ -exports.HTTP_REQUEST_METHOD_VALUE_CONNECT = "CONNECT"; -/** - * Enum value "DELETE" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * DELETE method. - */ -exports.HTTP_REQUEST_METHOD_VALUE_DELETE = "DELETE"; -/** - * Enum value "GET" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * GET method. - */ -exports.HTTP_REQUEST_METHOD_VALUE_GET = "GET"; -/** - * Enum value "HEAD" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * HEAD method. - */ -exports.HTTP_REQUEST_METHOD_VALUE_HEAD = "HEAD"; -/** - * Enum value "OPTIONS" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * OPTIONS method. - */ -exports.HTTP_REQUEST_METHOD_VALUE_OPTIONS = "OPTIONS"; -/** - * Enum value "PATCH" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * PATCH method. - */ -exports.HTTP_REQUEST_METHOD_VALUE_PATCH = "PATCH"; -/** - * Enum value "POST" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * POST method. - */ -exports.HTTP_REQUEST_METHOD_VALUE_POST = "POST"; -/** - * Enum value "PUT" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * PUT method. - */ -exports.HTTP_REQUEST_METHOD_VALUE_PUT = "PUT"; -/** - * Enum value "TRACE" for attribute {@link ATTR_HTTP_REQUEST_METHOD}. - * - * TRACE method. - */ -exports.HTTP_REQUEST_METHOD_VALUE_TRACE = "TRACE"; -/** - * Original HTTP method sent by the client in the request line. - * - * @example GeT - * @example ACL - * @example foo - */ -exports.ATTR_HTTP_REQUEST_METHOD_ORIGINAL = 'http.request.method_original'; -/** - * The ordinal number of request resending attempt (for any reason, including redirects). - * - * @example 3 - * - * @note The resend count **SHOULD** be updated each time an HTTP request gets resent by the client, regardless of what was the cause of the resending (e.g. redirection, authorization failure, 503 Server Unavailable, network issues, or any other). - */ -exports.ATTR_HTTP_REQUEST_RESEND_COUNT = 'http.request.resend_count'; -/** - * HTTP response headers, `` being the normalized HTTP Header name (lowercase), the value being the header values. - * - * @example ["application/json"] - * @example ["abc", "def"] - * - * @note Instrumentations **SHOULD** require an explicit configuration of which headers are to be captured. - * Including all response headers can be a security risk - explicit configuration helps avoid leaking sensitive information. - * - * Users **MAY** explicitly configure instrumentations to capture them even though it is not recommended. - * - * The attribute value **MUST** consist of either multiple header values as an array of strings - * or a single-item array containing a possibly comma-concatenated string, depending on the way - * the HTTP library provides access to headers. - * - * Examples: - * - * - A header `Content-Type: application/json` header **SHOULD** be recorded as the `http.request.response.content-type` - * attribute with value `["application/json"]`. - * - A header `My-custom-header: abc, def` header **SHOULD** be recorded as the `http.response.header.my-custom-header` - * attribute with value `["abc", "def"]` or `["abc, def"]` depending on the HTTP library. - */ -const ATTR_HTTP_RESPONSE_HEADER = (key) => `http.response.header.${key}`; -exports.ATTR_HTTP_RESPONSE_HEADER = ATTR_HTTP_RESPONSE_HEADER; -/** - * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6). - * - * @example 200 - */ -exports.ATTR_HTTP_RESPONSE_STATUS_CODE = 'http.response.status_code'; -/** - * The matched route, that is, the path template in the format used by the respective server framework. - * - * @example /users/:userID? - * @example {controller}/{action}/{id?} - * - * @note **MUST NOT** be populated when this is not supported by the HTTP server framework as the route attribute should have low-cardinality and the URI path can NOT substitute it. - * **SHOULD** include the [application root](/docs/http/http-spans.md#http-server-definitions) if there is one. - */ -exports.ATTR_HTTP_ROUTE = 'http.route'; -/** - * Name of the garbage collector action. - * - * @example end of minor GC - * @example end of major GC - * - * @note Garbage collector action is generally obtained via [GarbageCollectionNotificationInfo#getGcAction()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcAction()). - */ -exports.ATTR_JVM_GC_ACTION = 'jvm.gc.action'; -/** - * Name of the garbage collector. - * - * @example G1 Young Generation - * @example G1 Old Generation - * - * @note Garbage collector name is generally obtained via [GarbageCollectionNotificationInfo#getGcName()](https://docs.oracle.com/en/java/javase/11/docs/api/jdk.management/com/sun/management/GarbageCollectionNotificationInfo.html#getGcName()). - */ -exports.ATTR_JVM_GC_NAME = 'jvm.gc.name'; -/** - * Name of the memory pool. - * - * @example G1 Old Gen - * @example G1 Eden space - * @example G1 Survivor Space - * - * @note Pool names are generally obtained via [MemoryPoolMXBean#getName()](https://docs.oracle.com/en/java/javase/11/docs/api/java.management/java/lang/management/MemoryPoolMXBean.html#getName()). - */ -exports.ATTR_JVM_MEMORY_POOL_NAME = 'jvm.memory.pool.name'; -/** - * The type of memory. - * - * @example heap - * @example non_heap - */ -exports.ATTR_JVM_MEMORY_TYPE = 'jvm.memory.type'; -/** - * Enum value "heap" for attribute {@link ATTR_JVM_MEMORY_TYPE}. - * - * Heap memory. - */ -exports.JVM_MEMORY_TYPE_VALUE_HEAP = "heap"; -/** - * Enum value "non_heap" for attribute {@link ATTR_JVM_MEMORY_TYPE}. - * - * Non-heap memory - */ -exports.JVM_MEMORY_TYPE_VALUE_NON_HEAP = "non_heap"; -/** - * Whether the thread is daemon or not. - */ -exports.ATTR_JVM_THREAD_DAEMON = 'jvm.thread.daemon'; -/** - * State of the thread. - * - * @example runnable - * @example blocked - */ -exports.ATTR_JVM_THREAD_STATE = 'jvm.thread.state'; -/** - * Enum value "blocked" for attribute {@link ATTR_JVM_THREAD_STATE}. - * - * A thread that is blocked waiting for a monitor lock is in this state. - */ -exports.JVM_THREAD_STATE_VALUE_BLOCKED = "blocked"; -/** - * Enum value "new" for attribute {@link ATTR_JVM_THREAD_STATE}. - * - * A thread that has not yet started is in this state. - */ -exports.JVM_THREAD_STATE_VALUE_NEW = "new"; -/** - * Enum value "runnable" for attribute {@link ATTR_JVM_THREAD_STATE}. - * - * A thread executing in the Java virtual machine is in this state. - */ -exports.JVM_THREAD_STATE_VALUE_RUNNABLE = "runnable"; -/** - * Enum value "terminated" for attribute {@link ATTR_JVM_THREAD_STATE}. - * - * A thread that has exited is in this state. - */ -exports.JVM_THREAD_STATE_VALUE_TERMINATED = "terminated"; -/** - * Enum value "timed_waiting" for attribute {@link ATTR_JVM_THREAD_STATE}. - * - * A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state. - */ -exports.JVM_THREAD_STATE_VALUE_TIMED_WAITING = "timed_waiting"; -/** - * Enum value "waiting" for attribute {@link ATTR_JVM_THREAD_STATE}. - * - * A thread that is waiting indefinitely for another thread to perform a particular action is in this state. - */ -exports.JVM_THREAD_STATE_VALUE_WAITING = "waiting"; -/** - * Local address of the network connection - IP address or Unix domain socket name. - * - * @example 10.1.2.80 - * @example /tmp/my.sock - */ -exports.ATTR_NETWORK_LOCAL_ADDRESS = 'network.local.address'; -/** - * Local port number of the network connection. - * - * @example 65123 - */ -exports.ATTR_NETWORK_LOCAL_PORT = 'network.local.port'; -/** - * Peer address of the network connection - IP address or Unix domain socket name. - * - * @example 10.1.2.80 - * @example /tmp/my.sock - */ -exports.ATTR_NETWORK_PEER_ADDRESS = 'network.peer.address'; -/** - * Peer port number of the network connection. - * - * @example 65123 - */ -exports.ATTR_NETWORK_PEER_PORT = 'network.peer.port'; -/** - * [OSI application layer](https://wikipedia.org/wiki/Application_layer) or non-OSI equivalent. - * - * @example amqp - * @example http - * @example mqtt - * - * @note The value **SHOULD** be normalized to lowercase. - */ -exports.ATTR_NETWORK_PROTOCOL_NAME = 'network.protocol.name'; -/** - * The actual version of the protocol used for network communication. - * - * @example 1.1 - * @example 2 - * - * @note If protocol version is subject to negotiation (for example using [ALPN](https://www.rfc-editor.org/rfc/rfc7301.html)), this attribute **SHOULD** be set to the negotiated version. If the actual protocol version is not known, this attribute **SHOULD NOT** be set. - */ -exports.ATTR_NETWORK_PROTOCOL_VERSION = 'network.protocol.version'; -/** - * [OSI transport layer](https://wikipedia.org/wiki/Transport_layer) or [inter-process communication method](https://wikipedia.org/wiki/Inter-process_communication). - * - * @example tcp - * @example udp - * - * @note The value **SHOULD** be normalized to lowercase. - * - * Consider always setting the transport when setting a port number, since - * a port number is ambiguous without knowing the transport. For example - * different processes could be listening on TCP port 12345 and UDP port 12345. - */ -exports.ATTR_NETWORK_TRANSPORT = 'network.transport'; -/** - * Enum value "pipe" for attribute {@link ATTR_NETWORK_TRANSPORT}. - * - * Named or anonymous pipe. - */ -exports.NETWORK_TRANSPORT_VALUE_PIPE = "pipe"; -/** - * Enum value "quic" for attribute {@link ATTR_NETWORK_TRANSPORT}. - * - * QUIC - */ -exports.NETWORK_TRANSPORT_VALUE_QUIC = "quic"; -/** - * Enum value "tcp" for attribute {@link ATTR_NETWORK_TRANSPORT}. - * - * TCP - */ -exports.NETWORK_TRANSPORT_VALUE_TCP = "tcp"; -/** - * Enum value "udp" for attribute {@link ATTR_NETWORK_TRANSPORT}. - * - * UDP - */ -exports.NETWORK_TRANSPORT_VALUE_UDP = "udp"; -/** - * Enum value "unix" for attribute {@link ATTR_NETWORK_TRANSPORT}. - * - * Unix domain socket - */ -exports.NETWORK_TRANSPORT_VALUE_UNIX = "unix"; -/** - * [OSI network layer](https://wikipedia.org/wiki/Network_layer) or non-OSI equivalent. - * - * @example ipv4 - * @example ipv6 - * - * @note The value **SHOULD** be normalized to lowercase. - */ -exports.ATTR_NETWORK_TYPE = 'network.type'; -/** - * Enum value "ipv4" for attribute {@link ATTR_NETWORK_TYPE}. - * - * IPv4 - */ -exports.NETWORK_TYPE_VALUE_IPV4 = "ipv4"; -/** - * Enum value "ipv6" for attribute {@link ATTR_NETWORK_TYPE}. - * - * IPv6 - */ -exports.NETWORK_TYPE_VALUE_IPV6 = "ipv6"; -/** - * The name of the instrumentation scope - (`InstrumentationScope.Name` in OTLP). - * - * @example io.opentelemetry.contrib.mongodb - */ -exports.ATTR_OTEL_SCOPE_NAME = 'otel.scope.name'; -/** - * The version of the instrumentation scope - (`InstrumentationScope.Version` in OTLP). - * - * @example 1.0.0 - */ -exports.ATTR_OTEL_SCOPE_VERSION = 'otel.scope.version'; -/** - * Name of the code, either "OK" or "ERROR". **MUST NOT** be set if the status code is UNSET. - */ -exports.ATTR_OTEL_STATUS_CODE = 'otel.status_code'; -/** - * Enum value "ERROR" for attribute {@link ATTR_OTEL_STATUS_CODE}. - * - * The operation contains an error. - */ -exports.OTEL_STATUS_CODE_VALUE_ERROR = "ERROR"; -/** - * Enum value "OK" for attribute {@link ATTR_OTEL_STATUS_CODE}. - * - * The operation has been validated by an Application developer or Operator to have completed successfully. - */ -exports.OTEL_STATUS_CODE_VALUE_OK = "OK"; -/** - * Description of the Status if it has a value, otherwise not set. - * - * @example resource not found - */ -exports.ATTR_OTEL_STATUS_DESCRIPTION = 'otel.status_description'; -/** - * Server domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name. - * - * @example example.com - * @example 10.1.2.80 - * @example /tmp/my.sock - * - * @note When observed from the client side, and when communicating through an intermediary, `server.address` **SHOULD** represent the server address behind any intermediaries, for example proxies, if it's available. - */ -exports.ATTR_SERVER_ADDRESS = 'server.address'; -/** - * Server port number. - * - * @example 80 - * @example 8080 - * @example 443 - * - * @note When observed from the client side, and when communicating through an intermediary, `server.port` **SHOULD** represent the server port behind any intermediaries, for example proxies, if it's available. - */ -exports.ATTR_SERVER_PORT = 'server.port'; -/** - * Logical name of the service. - * - * @example shoppingcart - * - * @note **MUST** be the same for all instances of horizontally scaled services. If the value was not specified, SDKs **MUST** fallback to `unknown_service:` concatenated with [`process.executable.name`](process.md), e.g. `unknown_service:bash`. If `process.executable.name` is not available, the value **MUST** be set to `unknown_service`. - */ -exports.ATTR_SERVICE_NAME = 'service.name'; -/** - * The version string of the service API or implementation. The format is not defined by these conventions. - * - * @example 2.0.0 - * @example a01dbef8a - */ -exports.ATTR_SERVICE_VERSION = 'service.version'; -/** - * SignalR HTTP connection closure status. - * - * @example app_shutdown - * @example timeout - */ -exports.ATTR_SIGNALR_CONNECTION_STATUS = 'signalr.connection.status'; -/** - * Enum value "app_shutdown" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}. - * - * The connection was closed because the app is shutting down. - */ -exports.SIGNALR_CONNECTION_STATUS_VALUE_APP_SHUTDOWN = "app_shutdown"; -/** - * Enum value "normal_closure" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}. - * - * The connection was closed normally. - */ -exports.SIGNALR_CONNECTION_STATUS_VALUE_NORMAL_CLOSURE = "normal_closure"; -/** - * Enum value "timeout" for attribute {@link ATTR_SIGNALR_CONNECTION_STATUS}. - * - * The connection was closed due to a timeout. - */ -exports.SIGNALR_CONNECTION_STATUS_VALUE_TIMEOUT = "timeout"; -/** - * [SignalR transport type](https://github.com/dotnet/aspnetcore/blob/main/src/SignalR/docs/specs/TransportProtocols.md) - * - * @example web_sockets - * @example long_polling - */ -exports.ATTR_SIGNALR_TRANSPORT = 'signalr.transport'; -/** - * Enum value "long_polling" for attribute {@link ATTR_SIGNALR_TRANSPORT}. - * - * LongPolling protocol - */ -exports.SIGNALR_TRANSPORT_VALUE_LONG_POLLING = "long_polling"; -/** - * Enum value "server_sent_events" for attribute {@link ATTR_SIGNALR_TRANSPORT}. - * - * ServerSentEvents protocol - */ -exports.SIGNALR_TRANSPORT_VALUE_SERVER_SENT_EVENTS = "server_sent_events"; -/** - * Enum value "web_sockets" for attribute {@link ATTR_SIGNALR_TRANSPORT}. - * - * WebSockets protocol - */ -exports.SIGNALR_TRANSPORT_VALUE_WEB_SOCKETS = "web_sockets"; -/** - * The language of the telemetry SDK. - */ -exports.ATTR_TELEMETRY_SDK_LANGUAGE = 'telemetry.sdk.language'; -/** - * Enum value "cpp" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ -exports.TELEMETRY_SDK_LANGUAGE_VALUE_CPP = "cpp"; -/** - * Enum value "dotnet" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ -exports.TELEMETRY_SDK_LANGUAGE_VALUE_DOTNET = "dotnet"; -/** - * Enum value "erlang" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ -exports.TELEMETRY_SDK_LANGUAGE_VALUE_ERLANG = "erlang"; -/** - * Enum value "go" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ -exports.TELEMETRY_SDK_LANGUAGE_VALUE_GO = "go"; -/** - * Enum value "java" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ -exports.TELEMETRY_SDK_LANGUAGE_VALUE_JAVA = "java"; -/** - * Enum value "nodejs" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ -exports.TELEMETRY_SDK_LANGUAGE_VALUE_NODEJS = "nodejs"; -/** - * Enum value "php" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ -exports.TELEMETRY_SDK_LANGUAGE_VALUE_PHP = "php"; -/** - * Enum value "python" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ -exports.TELEMETRY_SDK_LANGUAGE_VALUE_PYTHON = "python"; -/** - * Enum value "ruby" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ -exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUBY = "ruby"; -/** - * Enum value "rust" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ -exports.TELEMETRY_SDK_LANGUAGE_VALUE_RUST = "rust"; -/** - * Enum value "swift" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ -exports.TELEMETRY_SDK_LANGUAGE_VALUE_SWIFT = "swift"; -/** - * Enum value "webjs" for attribute {@link ATTR_TELEMETRY_SDK_LANGUAGE}. - */ -exports.TELEMETRY_SDK_LANGUAGE_VALUE_WEBJS = "webjs"; -/** - * The name of the telemetry SDK as defined above. - * - * @example opentelemetry - * - * @note The OpenTelemetry SDK **MUST** set the `telemetry.sdk.name` attribute to `opentelemetry`. - * If another SDK, like a fork or a vendor-provided implementation, is used, this SDK **MUST** set the - * `telemetry.sdk.name` attribute to the fully-qualified class or module name of this SDK's main entry point - * or another suitable identifier depending on the language. - * The identifier `opentelemetry` is reserved and **MUST NOT** be used in this case. - * All custom identifiers **SHOULD** be stable across different versions of an implementation. - */ -exports.ATTR_TELEMETRY_SDK_NAME = 'telemetry.sdk.name'; -/** - * The version string of the telemetry SDK. - * - * @example 1.2.3 - */ -exports.ATTR_TELEMETRY_SDK_VERSION = 'telemetry.sdk.version'; -/** - * The [URI fragment](https://www.rfc-editor.org/rfc/rfc3986#section-3.5) component - * - * @example SemConv - */ -exports.ATTR_URL_FRAGMENT = 'url.fragment'; -/** - * Absolute URL describing a network resource according to [RFC3986](https://www.rfc-editor.org/rfc/rfc3986) - * - * @example https://www.foo.bar/search?q=OpenTelemetry#SemConv - * @example //localhost - * - * @note For network calls, URL usually has `scheme://host[:port][path][?query][#fragment]` format, where the fragment - * is not transmitted over HTTP, but if it is known, it **SHOULD** be included nevertheless. - * - * `url.full` **MUST NOT** contain credentials passed via URL in form of `https://username:password@www.example.com/`. - * In such case username and password **SHOULD** be redacted and attribute's value **SHOULD** be `https://REDACTED:REDACTED@www.example.com/`. - * - * `url.full` **SHOULD** capture the absolute URL when it is available (or can be reconstructed). - * - * Sensitive content provided in `url.full` **SHOULD** be scrubbed when instrumentations can identify it. - * - * - * Query string values for the following keys **SHOULD** be redacted by default and replaced by the - * value `REDACTED`: - * - * - [`AWSAccessKeyId`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth) - * - [`Signature`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth) - * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token) - * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls) - * - * This list is subject to change over time. - * - * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g. - * `https://www.example.com/path?color=blue&sig=REDACTED`. - */ -exports.ATTR_URL_FULL = 'url.full'; -/** - * The [URI path](https://www.rfc-editor.org/rfc/rfc3986#section-3.3) component - * - * @example /search - * - * @note Sensitive content provided in `url.path` **SHOULD** be scrubbed when instrumentations can identify it. - */ -exports.ATTR_URL_PATH = 'url.path'; -/** - * The [URI query](https://www.rfc-editor.org/rfc/rfc3986#section-3.4) component - * - * @example q=OpenTelemetry - * - * @note Sensitive content provided in `url.query` **SHOULD** be scrubbed when instrumentations can identify it. - * - * - * Query string values for the following keys **SHOULD** be redacted by default and replaced by the value `REDACTED`: - * - * - [`AWSAccessKeyId`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth) - * - [`Signature`](https://docs.aws.amazon.com/AmazonS3/latest/userguide/RESTAuthentication.html#RESTAuthenticationQueryStringAuth) - * - [`sig`](https://learn.microsoft.com/azure/storage/common/storage-sas-overview#sas-token) - * - [`X-Goog-Signature`](https://cloud.google.com/storage/docs/access-control/signed-urls) - * - * This list is subject to change over time. - * - * When a query string value is redacted, the query string key **SHOULD** still be preserved, e.g. - * `q=OpenTelemetry&sig=REDACTED`. - */ -exports.ATTR_URL_QUERY = 'url.query'; -/** - * The [URI scheme](https://www.rfc-editor.org/rfc/rfc3986#section-3.1) component identifying the used protocol. - * - * @example https - * @example ftp - * @example telnet - */ -exports.ATTR_URL_SCHEME = 'url.scheme'; -/** - * Value of the [HTTP User-Agent](https://www.rfc-editor.org/rfc/rfc9110.html#field.user-agent) header sent by the client. - * - * @example CERN-LineMode/2.15 libwww/2.17b3 - * @example Mozilla/5.0 (iPhone; CPU iPhone OS 14_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.2 Mobile/15E148 Safari/604.1 - * @example YourApp/1.0.0 grpc-java-okhttp/1.27.2 - */ -exports.ATTR_USER_AGENT_ORIGINAL = 'user_agent.original'; -//# sourceMappingURL=stable_attributes.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_events.js b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_events.js deleted file mode 100644 index 23ddfd7a..00000000 --- a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_events.js +++ /dev/null @@ -1,26 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.EVENT_EXCEPTION = void 0; -//----------------------------------------------------------------------------------------------------------- -// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/registry/ts-stable/events.ts.j2 -//----------------------------------------------------------------------------------------------------------- -/** - * This event describes a single exception. - */ -exports.EVENT_EXCEPTION = 'exception'; -//# sourceMappingURL=stable_events.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_metrics.js b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_metrics.js deleted file mode 100644 index 371fe857..00000000 --- a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/stable_metrics.js +++ /dev/null @@ -1,330 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = exports.METRIC_KESTREL_UPGRADED_CONNECTIONS = exports.METRIC_KESTREL_TLS_HANDSHAKE_DURATION = exports.METRIC_KESTREL_REJECTED_CONNECTIONS = exports.METRIC_KESTREL_QUEUED_REQUESTS = exports.METRIC_KESTREL_QUEUED_CONNECTIONS = exports.METRIC_KESTREL_CONNECTION_DURATION = exports.METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = exports.METRIC_KESTREL_ACTIVE_CONNECTIONS = exports.METRIC_JVM_THREAD_COUNT = exports.METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = exports.METRIC_JVM_MEMORY_USED = exports.METRIC_JVM_MEMORY_LIMIT = exports.METRIC_JVM_MEMORY_COMMITTED = exports.METRIC_JVM_GC_DURATION = exports.METRIC_JVM_CPU_TIME = exports.METRIC_JVM_CPU_RECENT_UTILIZATION = exports.METRIC_JVM_CPU_COUNT = exports.METRIC_JVM_CLASS_UNLOADED = exports.METRIC_JVM_CLASS_LOADED = exports.METRIC_JVM_CLASS_COUNT = exports.METRIC_HTTP_SERVER_REQUEST_DURATION = exports.METRIC_HTTP_CLIENT_REQUEST_DURATION = exports.METRIC_DOTNET_TIMER_COUNT = exports.METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT = exports.METRIC_DOTNET_THREAD_POOL_THREAD_COUNT = exports.METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH = exports.METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET = exports.METRIC_DOTNET_PROCESS_CPU_TIME = exports.METRIC_DOTNET_PROCESS_CPU_COUNT = exports.METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS = exports.METRIC_DOTNET_JIT_COMPILED_METHODS = exports.METRIC_DOTNET_JIT_COMPILED_IL_SIZE = exports.METRIC_DOTNET_JIT_COMPILATION_TIME = exports.METRIC_DOTNET_GC_PAUSE_TIME = exports.METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE = exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE = exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE = exports.METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED = exports.METRIC_DOTNET_GC_COLLECTIONS = exports.METRIC_DOTNET_EXCEPTIONS = exports.METRIC_DOTNET_ASSEMBLY_COUNT = exports.METRIC_DB_CLIENT_OPERATION_DURATION = exports.METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = exports.METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = exports.METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = exports.METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = void 0; -exports.METRIC_SIGNALR_SERVER_CONNECTION_DURATION = void 0; -//---------------------------------------------------------------------------------------------------------- -// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates/register/stable/metrics.ts.j2 -//---------------------------------------------------------------------------------------------------------- -/** - * Number of exceptions caught by exception handling middleware. - * - * @note Meter name: `Microsoft.AspNetCore.Diagnostics`; Added in: ASP.NET Core 8.0 - */ -exports.METRIC_ASPNETCORE_DIAGNOSTICS_EXCEPTIONS = 'aspnetcore.diagnostics.exceptions'; -/** - * Number of requests that are currently active on the server that hold a rate limiting lease. - * - * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 - */ -exports.METRIC_ASPNETCORE_RATE_LIMITING_ACTIVE_REQUEST_LEASES = 'aspnetcore.rate_limiting.active_request_leases'; -/** - * Number of requests that are currently queued, waiting to acquire a rate limiting lease. - * - * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 - */ -exports.METRIC_ASPNETCORE_RATE_LIMITING_QUEUED_REQUESTS = 'aspnetcore.rate_limiting.queued_requests'; -/** - * The time the request spent in a queue waiting to acquire a rate limiting lease. - * - * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 - */ -exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_TIME_IN_QUEUE = 'aspnetcore.rate_limiting.request.time_in_queue'; -/** - * The duration of rate limiting lease held by requests on the server. - * - * @note Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 - */ -exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUEST_LEASE_DURATION = 'aspnetcore.rate_limiting.request_lease.duration'; -/** - * Number of requests that tried to acquire a rate limiting lease. - * - * @note Requests could be: - * - * - Rejected by global or endpoint rate limiting policies - * - Canceled while waiting for the lease. - * - * Meter name: `Microsoft.AspNetCore.RateLimiting`; Added in: ASP.NET Core 8.0 - */ -exports.METRIC_ASPNETCORE_RATE_LIMITING_REQUESTS = 'aspnetcore.rate_limiting.requests'; -/** - * Number of requests that were attempted to be matched to an endpoint. - * - * @note Meter name: `Microsoft.AspNetCore.Routing`; Added in: ASP.NET Core 8.0 - */ -exports.METRIC_ASPNETCORE_ROUTING_MATCH_ATTEMPTS = 'aspnetcore.routing.match_attempts'; -/** - * Duration of database client operations. - * - * @note Batch operations **SHOULD** be recorded as a single operation. - */ -exports.METRIC_DB_CLIENT_OPERATION_DURATION = 'db.client.operation.duration'; -/** - * The number of .NET assemblies that are currently loaded. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`AppDomain.CurrentDomain.GetAssemblies().Length`](https://learn.microsoft.com/dotnet/api/system.appdomain.getassemblies). - */ -exports.METRIC_DOTNET_ASSEMBLY_COUNT = 'dotnet.assembly.count'; -/** - * The number of exceptions that have been thrown in managed code. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as counting calls to [`AppDomain.CurrentDomain.FirstChanceException`](https://learn.microsoft.com/dotnet/api/system.appdomain.firstchanceexception). - */ -exports.METRIC_DOTNET_EXCEPTIONS = 'dotnet.exceptions'; -/** - * The number of garbage collections that have occurred since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric uses the [`GC.CollectionCount(int generation)`](https://learn.microsoft.com/dotnet/api/system.gc.collectioncount) API to calculate exclusive collections per generation. - */ -exports.METRIC_DOTNET_GC_COLLECTIONS = 'dotnet.gc.collections'; -/** - * The *approximate* number of bytes allocated on the managed GC heap since the process has started. The returned value does not include any native allocations. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`GC.GetTotalAllocatedBytes()`](https://learn.microsoft.com/dotnet/api/system.gc.gettotalallocatedbytes). - */ -exports.METRIC_DOTNET_GC_HEAP_TOTAL_ALLOCATED = 'dotnet.gc.heap.total_allocated'; -/** - * The heap fragmentation, as observed during the latest garbage collection. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`GC.GetGCMemoryInfo().GenerationInfo.FragmentationAfterBytes`](https://learn.microsoft.com/dotnet/api/system.gcgenerationinfo.fragmentationafterbytes). - */ -exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_FRAGMENTATION_SIZE = 'dotnet.gc.last_collection.heap.fragmentation.size'; -/** - * The managed GC heap size (including fragmentation), as observed during the latest garbage collection. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`GC.GetGCMemoryInfo().GenerationInfo.SizeAfterBytes`](https://learn.microsoft.com/dotnet/api/system.gcgenerationinfo.sizeafterbytes). - */ -exports.METRIC_DOTNET_GC_LAST_COLLECTION_HEAP_SIZE = 'dotnet.gc.last_collection.heap.size'; -/** - * The amount of committed virtual memory in use by the .NET GC, as observed during the latest garbage collection. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`GC.GetGCMemoryInfo().TotalCommittedBytes`](https://learn.microsoft.com/dotnet/api/system.gcmemoryinfo.totalcommittedbytes). Committed virtual memory may be larger than the heap size because it includes both memory for storing existing objects (the heap size) and some extra memory that is ready to handle newly allocated objects in the future. - */ -exports.METRIC_DOTNET_GC_LAST_COLLECTION_MEMORY_COMMITTED_SIZE = 'dotnet.gc.last_collection.memory.committed_size'; -/** - * The total amount of time paused in GC since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`GC.GetTotalPauseDuration()`](https://learn.microsoft.com/dotnet/api/system.gc.gettotalpauseduration). - */ -exports.METRIC_DOTNET_GC_PAUSE_TIME = 'dotnet.gc.pause.time'; -/** - * The amount of time the JIT compiler has spent compiling methods since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`JitInfo.GetCompilationTime()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompilationtime). - */ -exports.METRIC_DOTNET_JIT_COMPILATION_TIME = 'dotnet.jit.compilation.time'; -/** - * Count of bytes of intermediate language that have been compiled since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`JitInfo.GetCompiledILBytes()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompiledilbytes). - */ -exports.METRIC_DOTNET_JIT_COMPILED_IL_SIZE = 'dotnet.jit.compiled_il.size'; -/** - * The number of times the JIT compiler (re)compiled methods since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`JitInfo.GetCompiledMethodCount()`](https://learn.microsoft.com/dotnet/api/system.runtime.jitinfo.getcompiledmethodcount). - */ -exports.METRIC_DOTNET_JIT_COMPILED_METHODS = 'dotnet.jit.compiled_methods'; -/** - * The number of times there was contention when trying to acquire a monitor lock since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`Monitor.LockContentionCount`](https://learn.microsoft.com/dotnet/api/system.threading.monitor.lockcontentioncount). - */ -exports.METRIC_DOTNET_MONITOR_LOCK_CONTENTIONS = 'dotnet.monitor.lock_contentions'; -/** - * The number of processors available to the process. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as accessing [`Environment.ProcessorCount`](https://learn.microsoft.com/dotnet/api/system.environment.processorcount). - */ -exports.METRIC_DOTNET_PROCESS_CPU_COUNT = 'dotnet.process.cpu.count'; -/** - * CPU time used by the process. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as accessing the corresponding processor time properties on [`System.Diagnostics.Process`](https://learn.microsoft.com/dotnet/api/system.diagnostics.process). - */ -exports.METRIC_DOTNET_PROCESS_CPU_TIME = 'dotnet.process.cpu.time'; -/** - * The number of bytes of physical memory mapped to the process context. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`Environment.WorkingSet`](https://learn.microsoft.com/dotnet/api/system.environment.workingset). - */ -exports.METRIC_DOTNET_PROCESS_MEMORY_WORKING_SET = 'dotnet.process.memory.working_set'; -/** - * The number of work items that are currently queued to be processed by the thread pool. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`ThreadPool.PendingWorkItemCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.pendingworkitemcount). - */ -exports.METRIC_DOTNET_THREAD_POOL_QUEUE_LENGTH = 'dotnet.thread_pool.queue.length'; -/** - * The number of thread pool threads that currently exist. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`ThreadPool.ThreadCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.threadcount). - */ -exports.METRIC_DOTNET_THREAD_POOL_THREAD_COUNT = 'dotnet.thread_pool.thread.count'; -/** - * The number of work items that the thread pool has completed since the process has started. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`ThreadPool.CompletedWorkItemCount`](https://learn.microsoft.com/dotnet/api/system.threading.threadpool.completedworkitemcount). - */ -exports.METRIC_DOTNET_THREAD_POOL_WORK_ITEM_COUNT = 'dotnet.thread_pool.work_item.count'; -/** - * The number of timer instances that are currently active. - * - * @note Meter name: `System.Runtime`; Added in: .NET 9.0. - * This metric reports the same values as calling [`Timer.ActiveCount`](https://learn.microsoft.com/dotnet/api/system.threading.timer.activecount). - */ -exports.METRIC_DOTNET_TIMER_COUNT = 'dotnet.timer.count'; -/** - * Duration of HTTP client requests. - */ -exports.METRIC_HTTP_CLIENT_REQUEST_DURATION = 'http.client.request.duration'; -/** - * Duration of HTTP server requests. - */ -exports.METRIC_HTTP_SERVER_REQUEST_DURATION = 'http.server.request.duration'; -/** - * Number of classes currently loaded. - */ -exports.METRIC_JVM_CLASS_COUNT = 'jvm.class.count'; -/** - * Number of classes loaded since JVM start. - */ -exports.METRIC_JVM_CLASS_LOADED = 'jvm.class.loaded'; -/** - * Number of classes unloaded since JVM start. - */ -exports.METRIC_JVM_CLASS_UNLOADED = 'jvm.class.unloaded'; -/** - * Number of processors available to the Java virtual machine. - */ -exports.METRIC_JVM_CPU_COUNT = 'jvm.cpu.count'; -/** - * Recent CPU utilization for the process as reported by the JVM. - * - * @note The value range is [0.0,1.0]. This utilization is not defined as being for the specific interval since last measurement (unlike `system.cpu.utilization`). [Reference](https://docs.oracle.com/en/java/javase/17/docs/api/jdk.management/com/sun/management/OperatingSystemMXBean.html#getProcessCpuLoad()). - */ -exports.METRIC_JVM_CPU_RECENT_UTILIZATION = 'jvm.cpu.recent_utilization'; -/** - * CPU time used by the process as reported by the JVM. - */ -exports.METRIC_JVM_CPU_TIME = 'jvm.cpu.time'; -/** - * Duration of JVM garbage collection actions. - */ -exports.METRIC_JVM_GC_DURATION = 'jvm.gc.duration'; -/** - * Measure of memory committed. - */ -exports.METRIC_JVM_MEMORY_COMMITTED = 'jvm.memory.committed'; -/** - * Measure of max obtainable memory. - */ -exports.METRIC_JVM_MEMORY_LIMIT = 'jvm.memory.limit'; -/** - * Measure of memory used. - */ -exports.METRIC_JVM_MEMORY_USED = 'jvm.memory.used'; -/** - * Measure of memory used, as measured after the most recent garbage collection event on this pool. - */ -exports.METRIC_JVM_MEMORY_USED_AFTER_LAST_GC = 'jvm.memory.used_after_last_gc'; -/** - * Number of executing platform threads. - */ -exports.METRIC_JVM_THREAD_COUNT = 'jvm.thread.count'; -/** - * Number of connections that are currently active on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ -exports.METRIC_KESTREL_ACTIVE_CONNECTIONS = 'kestrel.active_connections'; -/** - * Number of TLS handshakes that are currently in progress on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ -exports.METRIC_KESTREL_ACTIVE_TLS_HANDSHAKES = 'kestrel.active_tls_handshakes'; -/** - * The duration of connections on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ -exports.METRIC_KESTREL_CONNECTION_DURATION = 'kestrel.connection.duration'; -/** - * Number of connections that are currently queued and are waiting to start. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ -exports.METRIC_KESTREL_QUEUED_CONNECTIONS = 'kestrel.queued_connections'; -/** - * Number of HTTP requests on multiplexed connections (HTTP/2 and HTTP/3) that are currently queued and are waiting to start. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ -exports.METRIC_KESTREL_QUEUED_REQUESTS = 'kestrel.queued_requests'; -/** - * Number of connections rejected by the server. - * - * @note Connections are rejected when the currently active count exceeds the value configured with `MaxConcurrentConnections`. - * Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ -exports.METRIC_KESTREL_REJECTED_CONNECTIONS = 'kestrel.rejected_connections'; -/** - * The duration of TLS handshakes on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ -exports.METRIC_KESTREL_TLS_HANDSHAKE_DURATION = 'kestrel.tls_handshake.duration'; -/** - * Number of connections that are currently upgraded (WebSockets). . - * - * @note The counter only tracks HTTP/1.1 connections. - * - * Meter name: `Microsoft.AspNetCore.Server.Kestrel`; Added in: ASP.NET Core 8.0 - */ -exports.METRIC_KESTREL_UPGRADED_CONNECTIONS = 'kestrel.upgraded_connections'; -/** - * Number of connections that are currently active on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Http.Connections`; Added in: ASP.NET Core 8.0 - */ -exports.METRIC_SIGNALR_SERVER_ACTIVE_CONNECTIONS = 'signalr.server.active_connections'; -/** - * The duration of connections on the server. - * - * @note Meter name: `Microsoft.AspNetCore.Http.Connections`; Added in: ASP.NET Core 8.0 - */ -exports.METRIC_SIGNALR_SERVER_CONNECTION_DURATION = 'signalr.server.connection.duration'; -//# sourceMappingURL=stable_metrics.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/trace/SemanticAttributes.js b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/trace/SemanticAttributes.js deleted file mode 100644 index d7337171..00000000 --- a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/trace/SemanticAttributes.js +++ /dev/null @@ -1,2379 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.SEMATTRS_NET_HOST_CARRIER_ICC = exports.SEMATTRS_NET_HOST_CARRIER_MNC = exports.SEMATTRS_NET_HOST_CARRIER_MCC = exports.SEMATTRS_NET_HOST_CARRIER_NAME = exports.SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = exports.SEMATTRS_NET_HOST_CONNECTION_TYPE = exports.SEMATTRS_NET_HOST_NAME = exports.SEMATTRS_NET_HOST_PORT = exports.SEMATTRS_NET_HOST_IP = exports.SEMATTRS_NET_PEER_NAME = exports.SEMATTRS_NET_PEER_PORT = exports.SEMATTRS_NET_PEER_IP = exports.SEMATTRS_NET_TRANSPORT = exports.SEMATTRS_FAAS_INVOKED_REGION = exports.SEMATTRS_FAAS_INVOKED_PROVIDER = exports.SEMATTRS_FAAS_INVOKED_NAME = exports.SEMATTRS_FAAS_COLDSTART = exports.SEMATTRS_FAAS_CRON = exports.SEMATTRS_FAAS_TIME = exports.SEMATTRS_FAAS_DOCUMENT_NAME = exports.SEMATTRS_FAAS_DOCUMENT_TIME = exports.SEMATTRS_FAAS_DOCUMENT_OPERATION = exports.SEMATTRS_FAAS_DOCUMENT_COLLECTION = exports.SEMATTRS_FAAS_EXECUTION = exports.SEMATTRS_FAAS_TRIGGER = exports.SEMATTRS_EXCEPTION_ESCAPED = exports.SEMATTRS_EXCEPTION_STACKTRACE = exports.SEMATTRS_EXCEPTION_MESSAGE = exports.SEMATTRS_EXCEPTION_TYPE = exports.SEMATTRS_DB_SQL_TABLE = exports.SEMATTRS_DB_MONGODB_COLLECTION = exports.SEMATTRS_DB_REDIS_DATABASE_INDEX = exports.SEMATTRS_DB_HBASE_NAMESPACE = exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = exports.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = exports.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = exports.SEMATTRS_DB_CASSANDRA_TABLE = exports.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = exports.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = exports.SEMATTRS_DB_CASSANDRA_KEYSPACE = exports.SEMATTRS_DB_MSSQL_INSTANCE_NAME = exports.SEMATTRS_DB_OPERATION = exports.SEMATTRS_DB_STATEMENT = exports.SEMATTRS_DB_NAME = exports.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = exports.SEMATTRS_DB_USER = exports.SEMATTRS_DB_CONNECTION_STRING = exports.SEMATTRS_DB_SYSTEM = exports.SEMATTRS_AWS_LAMBDA_INVOKED_ARN = void 0; -exports.SEMATTRS_MESSAGING_DESTINATION_KIND = exports.SEMATTRS_MESSAGING_DESTINATION = exports.SEMATTRS_MESSAGING_SYSTEM = exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = exports.SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = exports.SEMATTRS_AWS_DYNAMODB_COUNT = exports.SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = exports.SEMATTRS_AWS_DYNAMODB_SEGMENT = exports.SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = exports.SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = exports.SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = exports.SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = exports.SEMATTRS_AWS_DYNAMODB_SELECT = exports.SEMATTRS_AWS_DYNAMODB_INDEX_NAME = exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = exports.SEMATTRS_AWS_DYNAMODB_LIMIT = exports.SEMATTRS_AWS_DYNAMODB_PROJECTION = exports.SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = exports.SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = exports.SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = exports.SEMATTRS_HTTP_CLIENT_IP = exports.SEMATTRS_HTTP_ROUTE = exports.SEMATTRS_HTTP_SERVER_NAME = exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = exports.SEMATTRS_HTTP_USER_AGENT = exports.SEMATTRS_HTTP_FLAVOR = exports.SEMATTRS_HTTP_STATUS_CODE = exports.SEMATTRS_HTTP_SCHEME = exports.SEMATTRS_HTTP_HOST = exports.SEMATTRS_HTTP_TARGET = exports.SEMATTRS_HTTP_URL = exports.SEMATTRS_HTTP_METHOD = exports.SEMATTRS_CODE_LINENO = exports.SEMATTRS_CODE_FILEPATH = exports.SEMATTRS_CODE_NAMESPACE = exports.SEMATTRS_CODE_FUNCTION = exports.SEMATTRS_THREAD_NAME = exports.SEMATTRS_THREAD_ID = exports.SEMATTRS_ENDUSER_SCOPE = exports.SEMATTRS_ENDUSER_ROLE = exports.SEMATTRS_ENDUSER_ID = exports.SEMATTRS_PEER_SERVICE = void 0; -exports.DBSYSTEMVALUES_FILEMAKER = exports.DBSYSTEMVALUES_DERBY = exports.DBSYSTEMVALUES_FIREBIRD = exports.DBSYSTEMVALUES_ADABAS = exports.DBSYSTEMVALUES_CACHE = exports.DBSYSTEMVALUES_EDB = exports.DBSYSTEMVALUES_FIRSTSQL = exports.DBSYSTEMVALUES_INGRES = exports.DBSYSTEMVALUES_HANADB = exports.DBSYSTEMVALUES_MAXDB = exports.DBSYSTEMVALUES_PROGRESS = exports.DBSYSTEMVALUES_HSQLDB = exports.DBSYSTEMVALUES_CLOUDSCAPE = exports.DBSYSTEMVALUES_HIVE = exports.DBSYSTEMVALUES_REDSHIFT = exports.DBSYSTEMVALUES_POSTGRESQL = exports.DBSYSTEMVALUES_DB2 = exports.DBSYSTEMVALUES_ORACLE = exports.DBSYSTEMVALUES_MYSQL = exports.DBSYSTEMVALUES_MSSQL = exports.DBSYSTEMVALUES_OTHER_SQL = exports.SemanticAttributes = exports.SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = exports.SEMATTRS_MESSAGE_COMPRESSED_SIZE = exports.SEMATTRS_MESSAGE_ID = exports.SEMATTRS_MESSAGE_TYPE = exports.SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = exports.SEMATTRS_RPC_JSONRPC_ERROR_CODE = exports.SEMATTRS_RPC_JSONRPC_REQUEST_ID = exports.SEMATTRS_RPC_JSONRPC_VERSION = exports.SEMATTRS_RPC_GRPC_STATUS_CODE = exports.SEMATTRS_RPC_METHOD = exports.SEMATTRS_RPC_SERVICE = exports.SEMATTRS_RPC_SYSTEM = exports.SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = exports.SEMATTRS_MESSAGING_KAFKA_PARTITION = exports.SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = exports.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = exports.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = exports.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = exports.SEMATTRS_MESSAGING_CONSUMER_ID = exports.SEMATTRS_MESSAGING_OPERATION = exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = exports.SEMATTRS_MESSAGING_CONVERSATION_ID = exports.SEMATTRS_MESSAGING_MESSAGE_ID = exports.SEMATTRS_MESSAGING_URL = exports.SEMATTRS_MESSAGING_PROTOCOL_VERSION = exports.SEMATTRS_MESSAGING_PROTOCOL = exports.SEMATTRS_MESSAGING_TEMP_DESTINATION = void 0; -exports.FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = exports.FaasDocumentOperationValues = exports.FAASDOCUMENTOPERATIONVALUES_DELETE = exports.FAASDOCUMENTOPERATIONVALUES_EDIT = exports.FAASDOCUMENTOPERATIONVALUES_INSERT = exports.FaasTriggerValues = exports.FAASTRIGGERVALUES_OTHER = exports.FAASTRIGGERVALUES_TIMER = exports.FAASTRIGGERVALUES_PUBSUB = exports.FAASTRIGGERVALUES_HTTP = exports.FAASTRIGGERVALUES_DATASOURCE = exports.DbCassandraConsistencyLevelValues = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = exports.DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ANY = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_THREE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_TWO = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ONE = exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = exports.DBCASSANDRACONSISTENCYLEVELVALUES_ALL = exports.DbSystemValues = exports.DBSYSTEMVALUES_COCKROACHDB = exports.DBSYSTEMVALUES_MEMCACHED = exports.DBSYSTEMVALUES_ELASTICSEARCH = exports.DBSYSTEMVALUES_GEODE = exports.DBSYSTEMVALUES_NEO4J = exports.DBSYSTEMVALUES_DYNAMODB = exports.DBSYSTEMVALUES_COSMOSDB = exports.DBSYSTEMVALUES_COUCHDB = exports.DBSYSTEMVALUES_COUCHBASE = exports.DBSYSTEMVALUES_REDIS = exports.DBSYSTEMVALUES_MONGODB = exports.DBSYSTEMVALUES_HBASE = exports.DBSYSTEMVALUES_CASSANDRA = exports.DBSYSTEMVALUES_COLDFUSION = exports.DBSYSTEMVALUES_H2 = exports.DBSYSTEMVALUES_VERTICA = exports.DBSYSTEMVALUES_TERADATA = exports.DBSYSTEMVALUES_SYBASE = exports.DBSYSTEMVALUES_SQLITE = exports.DBSYSTEMVALUES_POINTBASE = exports.DBSYSTEMVALUES_PERVASIVE = exports.DBSYSTEMVALUES_NETEZZA = exports.DBSYSTEMVALUES_MARIADB = exports.DBSYSTEMVALUES_INTERBASE = exports.DBSYSTEMVALUES_INSTANTDB = exports.DBSYSTEMVALUES_INFORMIX = void 0; -exports.MESSAGINGOPERATIONVALUES_RECEIVE = exports.MessagingDestinationKindValues = exports.MESSAGINGDESTINATIONKINDVALUES_TOPIC = exports.MESSAGINGDESTINATIONKINDVALUES_QUEUE = exports.HttpFlavorValues = exports.HTTPFLAVORVALUES_QUIC = exports.HTTPFLAVORVALUES_SPDY = exports.HTTPFLAVORVALUES_HTTP_2_0 = exports.HTTPFLAVORVALUES_HTTP_1_1 = exports.HTTPFLAVORVALUES_HTTP_1_0 = exports.NetHostConnectionSubtypeValues = exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_NR = exports.NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = exports.NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_GSM = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = exports.NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = exports.NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = exports.NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = exports.NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = exports.NetHostConnectionTypeValues = exports.NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = exports.NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = exports.NETHOSTCONNECTIONTYPEVALUES_CELL = exports.NETHOSTCONNECTIONTYPEVALUES_WIRED = exports.NETHOSTCONNECTIONTYPEVALUES_WIFI = exports.NetTransportValues = exports.NETTRANSPORTVALUES_OTHER = exports.NETTRANSPORTVALUES_INPROC = exports.NETTRANSPORTVALUES_PIPE = exports.NETTRANSPORTVALUES_UNIX = exports.NETTRANSPORTVALUES_IP = exports.NETTRANSPORTVALUES_IP_UDP = exports.NETTRANSPORTVALUES_IP_TCP = exports.FaasInvokedProviderValues = exports.FAASINVOKEDPROVIDERVALUES_GCP = exports.FAASINVOKEDPROVIDERVALUES_AZURE = exports.FAASINVOKEDPROVIDERVALUES_AWS = void 0; -exports.MessageTypeValues = exports.MESSAGETYPEVALUES_RECEIVED = exports.MESSAGETYPEVALUES_SENT = exports.RpcGrpcStatusCodeValues = exports.RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = exports.RPCGRPCSTATUSCODEVALUES_DATA_LOSS = exports.RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = exports.RPCGRPCSTATUSCODEVALUES_INTERNAL = exports.RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = exports.RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = exports.RPCGRPCSTATUSCODEVALUES_ABORTED = exports.RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = exports.RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = exports.RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = exports.RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = exports.RPCGRPCSTATUSCODEVALUES_NOT_FOUND = exports.RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = exports.RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = exports.RPCGRPCSTATUSCODEVALUES_UNKNOWN = exports.RPCGRPCSTATUSCODEVALUES_CANCELLED = exports.RPCGRPCSTATUSCODEVALUES_OK = exports.MessagingOperationValues = exports.MESSAGINGOPERATIONVALUES_PROCESS = void 0; -const utils_1 = require("../internal/utils"); -//---------------------------------------------------------------------------------------------------------- -// DO NOT EDIT, this is an Auto-generated file from scripts/semconv/templates//templates/SemanticAttributes.ts.j2 -//---------------------------------------------------------------------------------------------------------- -//---------------------------------------------------------------------------------------------------------- -// Constant values for SemanticAttributes -//---------------------------------------------------------------------------------------------------------- -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_AWS_LAMBDA_INVOKED_ARN = 'aws.lambda.invoked_arn'; -const TMP_DB_SYSTEM = 'db.system'; -const TMP_DB_CONNECTION_STRING = 'db.connection_string'; -const TMP_DB_USER = 'db.user'; -const TMP_DB_JDBC_DRIVER_CLASSNAME = 'db.jdbc.driver_classname'; -const TMP_DB_NAME = 'db.name'; -const TMP_DB_STATEMENT = 'db.statement'; -const TMP_DB_OPERATION = 'db.operation'; -const TMP_DB_MSSQL_INSTANCE_NAME = 'db.mssql.instance_name'; -const TMP_DB_CASSANDRA_KEYSPACE = 'db.cassandra.keyspace'; -const TMP_DB_CASSANDRA_PAGE_SIZE = 'db.cassandra.page_size'; -const TMP_DB_CASSANDRA_CONSISTENCY_LEVEL = 'db.cassandra.consistency_level'; -const TMP_DB_CASSANDRA_TABLE = 'db.cassandra.table'; -const TMP_DB_CASSANDRA_IDEMPOTENCE = 'db.cassandra.idempotence'; -const TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = 'db.cassandra.speculative_execution_count'; -const TMP_DB_CASSANDRA_COORDINATOR_ID = 'db.cassandra.coordinator.id'; -const TMP_DB_CASSANDRA_COORDINATOR_DC = 'db.cassandra.coordinator.dc'; -const TMP_DB_HBASE_NAMESPACE = 'db.hbase.namespace'; -const TMP_DB_REDIS_DATABASE_INDEX = 'db.redis.database_index'; -const TMP_DB_MONGODB_COLLECTION = 'db.mongodb.collection'; -const TMP_DB_SQL_TABLE = 'db.sql.table'; -const TMP_EXCEPTION_TYPE = 'exception.type'; -const TMP_EXCEPTION_MESSAGE = 'exception.message'; -const TMP_EXCEPTION_STACKTRACE = 'exception.stacktrace'; -const TMP_EXCEPTION_ESCAPED = 'exception.escaped'; -const TMP_FAAS_TRIGGER = 'faas.trigger'; -const TMP_FAAS_EXECUTION = 'faas.execution'; -const TMP_FAAS_DOCUMENT_COLLECTION = 'faas.document.collection'; -const TMP_FAAS_DOCUMENT_OPERATION = 'faas.document.operation'; -const TMP_FAAS_DOCUMENT_TIME = 'faas.document.time'; -const TMP_FAAS_DOCUMENT_NAME = 'faas.document.name'; -const TMP_FAAS_TIME = 'faas.time'; -const TMP_FAAS_CRON = 'faas.cron'; -const TMP_FAAS_COLDSTART = 'faas.coldstart'; -const TMP_FAAS_INVOKED_NAME = 'faas.invoked_name'; -const TMP_FAAS_INVOKED_PROVIDER = 'faas.invoked_provider'; -const TMP_FAAS_INVOKED_REGION = 'faas.invoked_region'; -const TMP_NET_TRANSPORT = 'net.transport'; -const TMP_NET_PEER_IP = 'net.peer.ip'; -const TMP_NET_PEER_PORT = 'net.peer.port'; -const TMP_NET_PEER_NAME = 'net.peer.name'; -const TMP_NET_HOST_IP = 'net.host.ip'; -const TMP_NET_HOST_PORT = 'net.host.port'; -const TMP_NET_HOST_NAME = 'net.host.name'; -const TMP_NET_HOST_CONNECTION_TYPE = 'net.host.connection.type'; -const TMP_NET_HOST_CONNECTION_SUBTYPE = 'net.host.connection.subtype'; -const TMP_NET_HOST_CARRIER_NAME = 'net.host.carrier.name'; -const TMP_NET_HOST_CARRIER_MCC = 'net.host.carrier.mcc'; -const TMP_NET_HOST_CARRIER_MNC = 'net.host.carrier.mnc'; -const TMP_NET_HOST_CARRIER_ICC = 'net.host.carrier.icc'; -const TMP_PEER_SERVICE = 'peer.service'; -const TMP_ENDUSER_ID = 'enduser.id'; -const TMP_ENDUSER_ROLE = 'enduser.role'; -const TMP_ENDUSER_SCOPE = 'enduser.scope'; -const TMP_THREAD_ID = 'thread.id'; -const TMP_THREAD_NAME = 'thread.name'; -const TMP_CODE_FUNCTION = 'code.function'; -const TMP_CODE_NAMESPACE = 'code.namespace'; -const TMP_CODE_FILEPATH = 'code.filepath'; -const TMP_CODE_LINENO = 'code.lineno'; -const TMP_HTTP_METHOD = 'http.method'; -const TMP_HTTP_URL = 'http.url'; -const TMP_HTTP_TARGET = 'http.target'; -const TMP_HTTP_HOST = 'http.host'; -const TMP_HTTP_SCHEME = 'http.scheme'; -const TMP_HTTP_STATUS_CODE = 'http.status_code'; -const TMP_HTTP_FLAVOR = 'http.flavor'; -const TMP_HTTP_USER_AGENT = 'http.user_agent'; -const TMP_HTTP_REQUEST_CONTENT_LENGTH = 'http.request_content_length'; -const TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = 'http.request_content_length_uncompressed'; -const TMP_HTTP_RESPONSE_CONTENT_LENGTH = 'http.response_content_length'; -const TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = 'http.response_content_length_uncompressed'; -const TMP_HTTP_SERVER_NAME = 'http.server_name'; -const TMP_HTTP_ROUTE = 'http.route'; -const TMP_HTTP_CLIENT_IP = 'http.client_ip'; -const TMP_AWS_DYNAMODB_TABLE_NAMES = 'aws.dynamodb.table_names'; -const TMP_AWS_DYNAMODB_CONSUMED_CAPACITY = 'aws.dynamodb.consumed_capacity'; -const TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = 'aws.dynamodb.item_collection_metrics'; -const TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = 'aws.dynamodb.provisioned_read_capacity'; -const TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = 'aws.dynamodb.provisioned_write_capacity'; -const TMP_AWS_DYNAMODB_CONSISTENT_READ = 'aws.dynamodb.consistent_read'; -const TMP_AWS_DYNAMODB_PROJECTION = 'aws.dynamodb.projection'; -const TMP_AWS_DYNAMODB_LIMIT = 'aws.dynamodb.limit'; -const TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET = 'aws.dynamodb.attributes_to_get'; -const TMP_AWS_DYNAMODB_INDEX_NAME = 'aws.dynamodb.index_name'; -const TMP_AWS_DYNAMODB_SELECT = 'aws.dynamodb.select'; -const TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = 'aws.dynamodb.global_secondary_indexes'; -const TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = 'aws.dynamodb.local_secondary_indexes'; -const TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = 'aws.dynamodb.exclusive_start_table'; -const TMP_AWS_DYNAMODB_TABLE_COUNT = 'aws.dynamodb.table_count'; -const TMP_AWS_DYNAMODB_SCAN_FORWARD = 'aws.dynamodb.scan_forward'; -const TMP_AWS_DYNAMODB_SEGMENT = 'aws.dynamodb.segment'; -const TMP_AWS_DYNAMODB_TOTAL_SEGMENTS = 'aws.dynamodb.total_segments'; -const TMP_AWS_DYNAMODB_COUNT = 'aws.dynamodb.count'; -const TMP_AWS_DYNAMODB_SCANNED_COUNT = 'aws.dynamodb.scanned_count'; -const TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = 'aws.dynamodb.attribute_definitions'; -const TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = 'aws.dynamodb.global_secondary_index_updates'; -const TMP_MESSAGING_SYSTEM = 'messaging.system'; -const TMP_MESSAGING_DESTINATION = 'messaging.destination'; -const TMP_MESSAGING_DESTINATION_KIND = 'messaging.destination_kind'; -const TMP_MESSAGING_TEMP_DESTINATION = 'messaging.temp_destination'; -const TMP_MESSAGING_PROTOCOL = 'messaging.protocol'; -const TMP_MESSAGING_PROTOCOL_VERSION = 'messaging.protocol_version'; -const TMP_MESSAGING_URL = 'messaging.url'; -const TMP_MESSAGING_MESSAGE_ID = 'messaging.message_id'; -const TMP_MESSAGING_CONVERSATION_ID = 'messaging.conversation_id'; -const TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = 'messaging.message_payload_size_bytes'; -const TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = 'messaging.message_payload_compressed_size_bytes'; -const TMP_MESSAGING_OPERATION = 'messaging.operation'; -const TMP_MESSAGING_CONSUMER_ID = 'messaging.consumer_id'; -const TMP_MESSAGING_RABBITMQ_ROUTING_KEY = 'messaging.rabbitmq.routing_key'; -const TMP_MESSAGING_KAFKA_MESSAGE_KEY = 'messaging.kafka.message_key'; -const TMP_MESSAGING_KAFKA_CONSUMER_GROUP = 'messaging.kafka.consumer_group'; -const TMP_MESSAGING_KAFKA_CLIENT_ID = 'messaging.kafka.client_id'; -const TMP_MESSAGING_KAFKA_PARTITION = 'messaging.kafka.partition'; -const TMP_MESSAGING_KAFKA_TOMBSTONE = 'messaging.kafka.tombstone'; -const TMP_RPC_SYSTEM = 'rpc.system'; -const TMP_RPC_SERVICE = 'rpc.service'; -const TMP_RPC_METHOD = 'rpc.method'; -const TMP_RPC_GRPC_STATUS_CODE = 'rpc.grpc.status_code'; -const TMP_RPC_JSONRPC_VERSION = 'rpc.jsonrpc.version'; -const TMP_RPC_JSONRPC_REQUEST_ID = 'rpc.jsonrpc.request_id'; -const TMP_RPC_JSONRPC_ERROR_CODE = 'rpc.jsonrpc.error_code'; -const TMP_RPC_JSONRPC_ERROR_MESSAGE = 'rpc.jsonrpc.error_message'; -const TMP_MESSAGE_TYPE = 'message.type'; -const TMP_MESSAGE_ID = 'message.id'; -const TMP_MESSAGE_COMPRESSED_SIZE = 'message.compressed_size'; -const TMP_MESSAGE_UNCOMPRESSED_SIZE = 'message.uncompressed_size'; -/** - * The full invoked ARN as provided on the `Context` passed to the function (`Lambda-Runtime-Invoked-Function-Arn` header on the `/runtime/invocation/next` applicable). - * - * Note: This may be different from `faas.id` if an alias is involved. - * - * @deprecated Use ATTR_AWS_LAMBDA_INVOKED_ARN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_LAMBDA_INVOKED_ARN = TMP_AWS_LAMBDA_INVOKED_ARN; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use ATTR_DB_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_DB_SYSTEM = TMP_DB_SYSTEM; -/** - * The connection string used to connect to the database. It is recommended to remove embedded credentials. - * - * @deprecated Use ATTR_DB_CONNECTION_STRING in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_DB_CONNECTION_STRING = TMP_DB_CONNECTION_STRING; -/** - * Username for accessing the database. - * - * @deprecated Use ATTR_DB_USER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_DB_USER = TMP_DB_USER; -/** - * The fully-qualified class name of the [Java Database Connectivity (JDBC)](https://docs.oracle.com/javase/8/docs/technotes/guides/jdbc/) driver used to connect. - * - * @deprecated Use ATTR_DB_JDBC_DRIVER_CLASSNAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_DB_JDBC_DRIVER_CLASSNAME = TMP_DB_JDBC_DRIVER_CLASSNAME; -/** - * If no [tech-specific attribute](#call-level-attributes-for-specific-technologies) is defined, this attribute is used to report the name of the database being accessed. For commands that switch the database, this should be set to the target database (even if the command fails). - * - * Note: In some SQL databases, the database name to be used is called "schema name". - * - * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_DB_NAME = TMP_DB_NAME; -/** - * The database statement being executed. - * - * Note: The value may be sanitized to exclude sensitive information. - * - * @deprecated Use ATTR_DB_STATEMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_DB_STATEMENT = TMP_DB_STATEMENT; -/** - * The name of the operation being executed, e.g. the [MongoDB command name](https://docs.mongodb.com/manual/reference/command/#database-operations) such as `findAndModify`, or the SQL keyword. - * - * Note: When setting this to an SQL keyword, it is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if the operation name is provided by the library being instrumented. If the SQL statement has an ambiguous operation, or performs more than one operation, this value may be omitted. - * - * @deprecated Use ATTR_DB_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_DB_OPERATION = TMP_DB_OPERATION; -/** - * The Microsoft SQL Server [instance name](https://docs.microsoft.com/en-us/sql/connect/jdbc/building-the-connection-url?view=sql-server-ver15) connecting to. This name is used to determine the port of a named instance. - * - * Note: If setting a `db.mssql.instance_name`, `net.peer.port` is no longer required (but still recommended if non-standard). - * - * @deprecated Use ATTR_DB_MSSQL_INSTANCE_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_DB_MSSQL_INSTANCE_NAME = TMP_DB_MSSQL_INSTANCE_NAME; -/** - * The name of the keyspace being accessed. To be used instead of the generic `db.name` attribute. - * - * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_DB_CASSANDRA_KEYSPACE = TMP_DB_CASSANDRA_KEYSPACE; -/** - * The fetch size used for paging, i.e. how many rows will be returned at once. - * - * @deprecated Use ATTR_DB_CASSANDRA_PAGE_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_DB_CASSANDRA_PAGE_SIZE = TMP_DB_CASSANDRA_PAGE_SIZE; -/** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use ATTR_DB_CASSANDRA_CONSISTENCY_LEVEL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_DB_CASSANDRA_CONSISTENCY_LEVEL = TMP_DB_CASSANDRA_CONSISTENCY_LEVEL; -/** - * The name of the primary table that the operation is acting upon, including the schema name (if applicable). - * - * Note: This mirrors the db.sql.table attribute but references cassandra rather than sql. It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if it is provided by the library being instrumented. If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set. - * - * @deprecated Use ATTR_DB_CASSANDRA_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_DB_CASSANDRA_TABLE = TMP_DB_CASSANDRA_TABLE; -/** - * Whether or not the query is idempotent. - * - * @deprecated Use ATTR_DB_CASSANDRA_IDEMPOTENCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_DB_CASSANDRA_IDEMPOTENCE = TMP_DB_CASSANDRA_IDEMPOTENCE; -/** - * The number of times a query was speculatively executed. Not set or `0` if the query was not executed speculatively. - * - * @deprecated Use ATTR_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT = TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT; -/** - * The ID of the coordinating node for a query. - * - * @deprecated Use ATTR_DB_CASSANDRA_COORDINATOR_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_ID = TMP_DB_CASSANDRA_COORDINATOR_ID; -/** - * The data center of the coordinating node for a query. - * - * @deprecated Use ATTR_DB_CASSANDRA_COORDINATOR_DC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_DB_CASSANDRA_COORDINATOR_DC = TMP_DB_CASSANDRA_COORDINATOR_DC; -/** - * The [HBase namespace](https://hbase.apache.org/book.html#_namespace) being accessed. To be used instead of the generic `db.name` attribute. - * - * @deprecated Use ATTR_DB_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_DB_HBASE_NAMESPACE = TMP_DB_HBASE_NAMESPACE; -/** - * The index of the database being accessed as used in the [`SELECT` command](https://redis.io/commands/select), provided as an integer. To be used instead of the generic `db.name` attribute. - * - * @deprecated Use ATTR_DB_REDIS_DATABASE_INDEX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_DB_REDIS_DATABASE_INDEX = TMP_DB_REDIS_DATABASE_INDEX; -/** - * The collection being accessed within the database stated in `db.name`. - * - * @deprecated Use ATTR_DB_MONGODB_COLLECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_DB_MONGODB_COLLECTION = TMP_DB_MONGODB_COLLECTION; -/** - * The name of the primary table that the operation is acting upon, including the schema name (if applicable). - * - * Note: It is not recommended to attempt any client-side parsing of `db.statement` just to get this property, but it should be set if it is provided by the library being instrumented. If the operation is acting upon an anonymous table, or more than one table, this value MUST NOT be set. - * - * @deprecated Use ATTR_DB_SQL_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_DB_SQL_TABLE = TMP_DB_SQL_TABLE; -/** - * The type of the exception (its fully-qualified class name, if applicable). The dynamic type of the exception should be preferred over the static type in languages that support it. - * - * @deprecated Use ATTR_EXCEPTION_TYPE. - */ -exports.SEMATTRS_EXCEPTION_TYPE = TMP_EXCEPTION_TYPE; -/** - * The exception message. - * - * @deprecated Use ATTR_EXCEPTION_MESSAGE. - */ -exports.SEMATTRS_EXCEPTION_MESSAGE = TMP_EXCEPTION_MESSAGE; -/** - * A stacktrace as a string in the natural representation for the language runtime. The representation is to be determined and documented by each language SIG. - * - * @deprecated Use ATTR_EXCEPTION_STACKTRACE. - */ -exports.SEMATTRS_EXCEPTION_STACKTRACE = TMP_EXCEPTION_STACKTRACE; -/** -* SHOULD be set to true if the exception event is recorded at a point where it is known that the exception is escaping the scope of the span. -* -* Note: An exception is considered to have escaped (or left) the scope of a span, -if that span is ended while the exception is still logically "in flight". -This may be actually "in flight" in some languages (e.g. if the exception -is passed to a Context manager's `__exit__` method in Python) but will -usually be caught at the point of recording the exception in most languages. - -It is usually not possible to determine at the point where an exception is thrown -whether it will escape the scope of a span. -However, it is trivial to know that an exception -will escape, if one checks for an active exception just before ending the span, -as done in the [example above](#exception-end-example). - -It follows that an exception may still escape the scope of the span -even if the `exception.escaped` attribute was not set or set to false, -since the event might have been recorded at a time where it was not -clear whether the exception will escape. -* -* @deprecated Use ATTR_EXCEPTION_ESCAPED. -*/ -exports.SEMATTRS_EXCEPTION_ESCAPED = TMP_EXCEPTION_ESCAPED; -/** - * Type of the trigger on which the function is executed. - * - * @deprecated Use ATTR_FAAS_TRIGGER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_FAAS_TRIGGER = TMP_FAAS_TRIGGER; -/** - * The execution ID of the current function execution. - * - * @deprecated Use ATTR_FAAS_INVOCATION_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_FAAS_EXECUTION = TMP_FAAS_EXECUTION; -/** - * The name of the source on which the triggering operation was performed. For example, in Cloud Storage or S3 corresponds to the bucket name, and in Cosmos DB to the database name. - * - * @deprecated Use ATTR_FAAS_DOCUMENT_COLLECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_FAAS_DOCUMENT_COLLECTION = TMP_FAAS_DOCUMENT_COLLECTION; -/** - * Describes the type of the operation that was performed on the data. - * - * @deprecated Use ATTR_FAAS_DOCUMENT_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_FAAS_DOCUMENT_OPERATION = TMP_FAAS_DOCUMENT_OPERATION; -/** - * A string containing the time when the data was accessed in the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). - * - * @deprecated Use ATTR_FAAS_DOCUMENT_TIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_FAAS_DOCUMENT_TIME = TMP_FAAS_DOCUMENT_TIME; -/** - * The document name/table subjected to the operation. For example, in Cloud Storage or S3 is the name of the file, and in Cosmos DB the table name. - * - * @deprecated Use ATTR_FAAS_DOCUMENT_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_FAAS_DOCUMENT_NAME = TMP_FAAS_DOCUMENT_NAME; -/** - * A string containing the function invocation time in the [ISO 8601](https://www.iso.org/iso-8601-date-and-time-format.html) format expressed in [UTC](https://www.w3.org/TR/NOTE-datetime). - * - * @deprecated Use ATTR_FAAS_TIME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_FAAS_TIME = TMP_FAAS_TIME; -/** - * A string containing the schedule period as [Cron Expression](https://docs.oracle.com/cd/E12058_01/doc/doc.1014/e12030/cron_expressions.htm). - * - * @deprecated Use ATTR_FAAS_CRON in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_FAAS_CRON = TMP_FAAS_CRON; -/** - * A boolean that is true if the serverless function is executed for the first time (aka cold-start). - * - * @deprecated Use ATTR_FAAS_COLDSTART in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_FAAS_COLDSTART = TMP_FAAS_COLDSTART; -/** - * The name of the invoked function. - * - * Note: SHOULD be equal to the `faas.name` resource attribute of the invoked function. - * - * @deprecated Use ATTR_FAAS_INVOKED_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_FAAS_INVOKED_NAME = TMP_FAAS_INVOKED_NAME; -/** - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * - * @deprecated Use ATTR_FAAS_INVOKED_PROVIDER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_FAAS_INVOKED_PROVIDER = TMP_FAAS_INVOKED_PROVIDER; -/** - * The cloud region of the invoked function. - * - * Note: SHOULD be equal to the `cloud.region` resource attribute of the invoked function. - * - * @deprecated Use ATTR_FAAS_INVOKED_REGION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_FAAS_INVOKED_REGION = TMP_FAAS_INVOKED_REGION; -/** - * Transport protocol used. See note below. - * - * @deprecated Use ATTR_NET_TRANSPORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_NET_TRANSPORT = TMP_NET_TRANSPORT; -/** - * Remote address of the peer (dotted decimal for IPv4 or [RFC5952](https://tools.ietf.org/html/rfc5952) for IPv6). - * - * @deprecated Use ATTR_NET_PEER_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_NET_PEER_IP = TMP_NET_PEER_IP; -/** - * Remote port number. - * - * @deprecated Use ATTR_NET_PEER_PORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_NET_PEER_PORT = TMP_NET_PEER_PORT; -/** - * Remote hostname or similar, see note below. - * - * @deprecated Use ATTR_NET_PEER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_NET_PEER_NAME = TMP_NET_PEER_NAME; -/** - * Like `net.peer.ip` but for the host IP. Useful in case of a multi-IP host. - * - * @deprecated Use ATTR_NET_HOST_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_NET_HOST_IP = TMP_NET_HOST_IP; -/** - * Like `net.peer.port` but for the host port. - * - * @deprecated Use ATTR_NET_HOST_PORT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_NET_HOST_PORT = TMP_NET_HOST_PORT; -/** - * Local hostname or similar, see note below. - * - * @deprecated Use ATTR_NET_HOST_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_NET_HOST_NAME = TMP_NET_HOST_NAME; -/** - * The internet connection type currently being used by the host. - * - * @deprecated Use ATTR_NETWORK_CONNECTION_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_NET_HOST_CONNECTION_TYPE = TMP_NET_HOST_CONNECTION_TYPE; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use ATTR_NETWORK_CONNECTION_SUBTYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_NET_HOST_CONNECTION_SUBTYPE = TMP_NET_HOST_CONNECTION_SUBTYPE; -/** - * The name of the mobile carrier. - * - * @deprecated Use ATTR_NETWORK_CARRIER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_NET_HOST_CARRIER_NAME = TMP_NET_HOST_CARRIER_NAME; -/** - * The mobile carrier country code. - * - * @deprecated Use ATTR_NETWORK_CARRIER_MCC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_NET_HOST_CARRIER_MCC = TMP_NET_HOST_CARRIER_MCC; -/** - * The mobile carrier network code. - * - * @deprecated Use ATTR_NETWORK_CARRIER_MNC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_NET_HOST_CARRIER_MNC = TMP_NET_HOST_CARRIER_MNC; -/** - * The ISO 3166-1 alpha-2 2-character country code associated with the mobile carrier network. - * - * @deprecated Use ATTR_NETWORK_CARRIER_ICC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_NET_HOST_CARRIER_ICC = TMP_NET_HOST_CARRIER_ICC; -/** - * The [`service.name`](../../resource/semantic_conventions/README.md#service) of the remote service. SHOULD be equal to the actual `service.name` resource attribute of the remote service if any. - * - * @deprecated Use ATTR_PEER_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_PEER_SERVICE = TMP_PEER_SERVICE; -/** - * Username or client_id extracted from the access token or [Authorization](https://tools.ietf.org/html/rfc7235#section-4.2) header in the inbound request from outside the system. - * - * @deprecated Use ATTR_ENDUSER_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_ENDUSER_ID = TMP_ENDUSER_ID; -/** - * Actual/assumed role the client is making the request under extracted from token or application security context. - * - * @deprecated Use ATTR_ENDUSER_ROLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_ENDUSER_ROLE = TMP_ENDUSER_ROLE; -/** - * Scopes or granted authorities the client currently possesses extracted from token or application security context. The value would come from the scope associated with an [OAuth 2.0 Access Token](https://tools.ietf.org/html/rfc6749#section-3.3) or an attribute value in a [SAML 2.0 Assertion](http://docs.oasis-open.org/security/saml/Post2.0/sstc-saml-tech-overview-2.0.html). - * - * @deprecated Use ATTR_ENDUSER_SCOPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_ENDUSER_SCOPE = TMP_ENDUSER_SCOPE; -/** - * Current "managed" thread ID (as opposed to OS thread ID). - * - * @deprecated Use ATTR_THREAD_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_THREAD_ID = TMP_THREAD_ID; -/** - * Current thread name. - * - * @deprecated Use ATTR_THREAD_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_THREAD_NAME = TMP_THREAD_NAME; -/** - * The method or function name, or equivalent (usually rightmost part of the code unit's name). - * - * @deprecated Use ATTR_CODE_FUNCTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_CODE_FUNCTION = TMP_CODE_FUNCTION; -/** - * The "namespace" within which `code.function` is defined. Usually the qualified class or module name, such that `code.namespace` + some separator + `code.function` form a unique identifier for the code unit. - * - * @deprecated Use ATTR_CODE_NAMESPACE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_CODE_NAMESPACE = TMP_CODE_NAMESPACE; -/** - * The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path). - * - * @deprecated Use ATTR_CODE_FILEPATH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_CODE_FILEPATH = TMP_CODE_FILEPATH; -/** - * The line number in `code.filepath` best representing the operation. It SHOULD point within the code unit named in `code.function`. - * - * @deprecated Use ATTR_CODE_LINENO in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_CODE_LINENO = TMP_CODE_LINENO; -/** - * HTTP request method. - * - * @deprecated Use ATTR_HTTP_METHOD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_HTTP_METHOD = TMP_HTTP_METHOD; -/** - * Full HTTP request URL in the form `scheme://host[:port]/path?query[#fragment]`. Usually the fragment is not transmitted over HTTP, but if it is known, it should be included nevertheless. - * - * Note: `http.url` MUST NOT contain credentials passed via URL in form of `https://username:password@www.example.com/`. In such case the attribute's value should be `https://www.example.com/`. - * - * @deprecated Use ATTR_HTTP_URL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_HTTP_URL = TMP_HTTP_URL; -/** - * The full request target as passed in a HTTP request line or equivalent. - * - * @deprecated Use ATTR_HTTP_TARGET in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_HTTP_TARGET = TMP_HTTP_TARGET; -/** - * The value of the [HTTP host header](https://tools.ietf.org/html/rfc7230#section-5.4). An empty Host header should also be reported, see note. - * - * Note: When the header is present but empty the attribute SHOULD be set to the empty string. Note that this is a valid situation that is expected in certain cases, according the aforementioned [section of RFC 7230](https://tools.ietf.org/html/rfc7230#section-5.4). When the header is not set the attribute MUST NOT be set. - * - * @deprecated Use ATTR_HTTP_HOST in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_HTTP_HOST = TMP_HTTP_HOST; -/** - * The URI scheme identifying the used protocol. - * - * @deprecated Use ATTR_HTTP_SCHEME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_HTTP_SCHEME = TMP_HTTP_SCHEME; -/** - * [HTTP response status code](https://tools.ietf.org/html/rfc7231#section-6). - * - * @deprecated Use ATTR_HTTP_STATUS_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_HTTP_STATUS_CODE = TMP_HTTP_STATUS_CODE; -/** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use ATTR_HTTP_FLAVOR in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_HTTP_FLAVOR = TMP_HTTP_FLAVOR; -/** - * Value of the [HTTP User-Agent](https://tools.ietf.org/html/rfc7231#section-5.5.3) header sent by the client. - * - * @deprecated Use ATTR_HTTP_USER_AGENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_HTTP_USER_AGENT = TMP_HTTP_USER_AGENT; -/** - * The size of the request payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size. - * - * @deprecated Use ATTR_HTTP_REQUEST_CONTENT_LENGTH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH = TMP_HTTP_REQUEST_CONTENT_LENGTH; -/** - * The size of the uncompressed request payload body after transport decoding. Not set if transport encoding not used. - * - * @deprecated Use ATTR_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED; -/** - * The size of the response payload body in bytes. This is the number of bytes transferred excluding headers and is often, but not always, present as the [Content-Length](https://tools.ietf.org/html/rfc7230#section-3.3.2) header. For requests using transport encoding, this should be the compressed size. - * - * @deprecated Use ATTR_HTTP_RESPONSE_CONTENT_LENGTH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH = TMP_HTTP_RESPONSE_CONTENT_LENGTH; -/** - * The size of the uncompressed response payload body after transport decoding. Not set if transport encoding not used. - * - * @deprecated Use ATTR_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED = TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED; -/** - * The primary server name of the matched virtual host. This should be obtained via configuration. If no such configuration can be obtained, this attribute MUST NOT be set ( `net.host.name` should be used instead). - * - * Note: `http.url` is usually not readily available on the server side but would have to be assembled in a cumbersome and sometimes lossy process from other information (see e.g. open-telemetry/opentelemetry-python/pull/148). It is thus preferred to supply the raw data that is available. - * - * @deprecated Use ATTR_HTTP_SERVER_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_HTTP_SERVER_NAME = TMP_HTTP_SERVER_NAME; -/** - * The matched route (path template). - * - * @deprecated Use ATTR_HTTP_ROUTE. - */ -exports.SEMATTRS_HTTP_ROUTE = TMP_HTTP_ROUTE; -/** -* The IP address of the original client behind all proxies, if known (e.g. from [X-Forwarded-For](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For)). -* -* Note: This is not necessarily the same as `net.peer.ip`, which would -identify the network-level peer, which may be a proxy. - -This attribute should be set when a source of information different -from the one used for `net.peer.ip`, is available even if that other -source just confirms the same value as `net.peer.ip`. -Rationale: For `net.peer.ip`, one typically does not know if it -comes from a proxy, reverse proxy, or the actual client. Setting -`http.client_ip` when it's the same as `net.peer.ip` means that -one is at least somewhat confident that the address is not that of -the closest proxy. -* -* @deprecated Use ATTR_HTTP_CLIENT_IP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). -*/ -exports.SEMATTRS_HTTP_CLIENT_IP = TMP_HTTP_CLIENT_IP; -/** - * The keys in the `RequestItems` object field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_TABLE_NAMES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_TABLE_NAMES = TMP_AWS_DYNAMODB_TABLE_NAMES; -/** - * The JSON-serialized value of each item in the `ConsumedCapacity` response field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_CONSUMED_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_CONSUMED_CAPACITY = TMP_AWS_DYNAMODB_CONSUMED_CAPACITY; -/** - * The JSON-serialized value of the `ItemCollectionMetrics` response field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_ITEM_COLLECTION_METRICS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_ITEM_COLLECTION_METRICS = TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS; -/** - * The value of the `ProvisionedThroughput.ReadCapacityUnits` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY; -/** - * The value of the `ProvisionedThroughput.WriteCapacityUnits` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY = TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY; -/** - * The value of the `ConsistentRead` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_CONSISTENT_READ in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_CONSISTENT_READ = TMP_AWS_DYNAMODB_CONSISTENT_READ; -/** - * The value of the `ProjectionExpression` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_PROJECTION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_PROJECTION = TMP_AWS_DYNAMODB_PROJECTION; -/** - * The value of the `Limit` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_LIMIT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_LIMIT = TMP_AWS_DYNAMODB_LIMIT; -/** - * The value of the `AttributesToGet` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_ATTRIBUTES_TO_GET in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTES_TO_GET = TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET; -/** - * The value of the `IndexName` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_INDEX_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_INDEX_NAME = TMP_AWS_DYNAMODB_INDEX_NAME; -/** - * The value of the `Select` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_SELECT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_SELECT = TMP_AWS_DYNAMODB_SELECT; -/** - * The JSON-serialized value of each item of the `GlobalSecondaryIndexes` request field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES; -/** - * The JSON-serialized value of each item of the `LocalSecondaryIndexes` request field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES = TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES; -/** - * The value of the `ExclusiveStartTableName` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_EXCLUSIVE_START_TABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_EXCLUSIVE_START_TABLE = TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE; -/** - * The the number of items in the `TableNames` response parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_TABLE_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_TABLE_COUNT = TMP_AWS_DYNAMODB_TABLE_COUNT; -/** - * The value of the `ScanIndexForward` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_SCAN_FORWARD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_SCAN_FORWARD = TMP_AWS_DYNAMODB_SCAN_FORWARD; -/** - * The value of the `Segment` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_SEGMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_SEGMENT = TMP_AWS_DYNAMODB_SEGMENT; -/** - * The value of the `TotalSegments` request parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_TOTAL_SEGMENTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_TOTAL_SEGMENTS = TMP_AWS_DYNAMODB_TOTAL_SEGMENTS; -/** - * The value of the `Count` response parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_COUNT = TMP_AWS_DYNAMODB_COUNT; -/** - * The value of the `ScannedCount` response parameter. - * - * @deprecated Use ATTR_AWS_DYNAMODB_SCANNED_COUNT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_SCANNED_COUNT = TMP_AWS_DYNAMODB_SCANNED_COUNT; -/** - * The JSON-serialized value of each item in the `AttributeDefinitions` request field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS = TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS; -/** - * The JSON-serialized value of each item in the the `GlobalSecondaryIndexUpdates` request field. - * - * @deprecated Use ATTR_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES = TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES; -/** - * A string identifying the messaging system. - * - * @deprecated Use ATTR_MESSAGING_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_MESSAGING_SYSTEM = TMP_MESSAGING_SYSTEM; -/** - * The message destination name. This might be equal to the span name but is required nevertheless. - * - * @deprecated Use ATTR_MESSAGING_DESTINATION_NAME in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_MESSAGING_DESTINATION = TMP_MESSAGING_DESTINATION; -/** - * The kind of message destination. - * - * @deprecated Removed in semconv v1.20.0. - */ -exports.SEMATTRS_MESSAGING_DESTINATION_KIND = TMP_MESSAGING_DESTINATION_KIND; -/** - * A boolean that is true if the message destination is temporary. - * - * @deprecated Use ATTR_MESSAGING_DESTINATION_TEMPORARY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_MESSAGING_TEMP_DESTINATION = TMP_MESSAGING_TEMP_DESTINATION; -/** - * The name of the transport protocol. - * - * @deprecated Use ATTR_NETWORK_PROTOCOL_NAME. - */ -exports.SEMATTRS_MESSAGING_PROTOCOL = TMP_MESSAGING_PROTOCOL; -/** - * The version of the transport protocol. - * - * @deprecated Use ATTR_NETWORK_PROTOCOL_VERSION. - */ -exports.SEMATTRS_MESSAGING_PROTOCOL_VERSION = TMP_MESSAGING_PROTOCOL_VERSION; -/** - * Connection string. - * - * @deprecated Removed in semconv v1.17.0. - */ -exports.SEMATTRS_MESSAGING_URL = TMP_MESSAGING_URL; -/** - * A value used by the messaging system as an identifier for the message, represented as a string. - * - * @deprecated Use ATTR_MESSAGING_MESSAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_MESSAGING_MESSAGE_ID = TMP_MESSAGING_MESSAGE_ID; -/** - * The [conversation ID](#conversations) identifying the conversation to which the message belongs, represented as a string. Sometimes called "Correlation ID". - * - * @deprecated Use ATTR_MESSAGING_MESSAGE_CONVERSATION_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_MESSAGING_CONVERSATION_ID = TMP_MESSAGING_CONVERSATION_ID; -/** - * The (uncompressed) size of the message payload in bytes. Also use this attribute if it is unknown whether the compressed or uncompressed payload size is reported. - * - * @deprecated Use ATTR_MESSAGING_MESSAGE_BODY_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES; -/** - * The compressed size of the message payload in bytes. - * - * @deprecated Removed in semconv v1.22.0. - */ -exports.SEMATTRS_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES = TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES; -/** - * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. - * - * @deprecated Use ATTR_MESSAGING_OPERATION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_MESSAGING_OPERATION = TMP_MESSAGING_OPERATION; -/** - * The identifier for the consumer receiving a message. For Kafka, set it to `{messaging.kafka.consumer_group} - {messaging.kafka.client_id}`, if both are present, or only `messaging.kafka.consumer_group`. For brokers, such as RabbitMQ and Artemis, set it to the `client_id` of the client consuming the message. - * - * @deprecated Removed in semconv v1.21.0. - */ -exports.SEMATTRS_MESSAGING_CONSUMER_ID = TMP_MESSAGING_CONSUMER_ID; -/** - * RabbitMQ message routing key. - * - * @deprecated Use ATTR_MESSAGING_RABBITMQ_DESTINATION_ROUTING_KEY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_MESSAGING_RABBITMQ_ROUTING_KEY = TMP_MESSAGING_RABBITMQ_ROUTING_KEY; -/** - * Message keys in Kafka are used for grouping alike messages to ensure they're processed on the same partition. They differ from `messaging.message_id` in that they're not unique. If the key is `null`, the attribute MUST NOT be set. - * - * Note: If the key type is not string, it's string representation has to be supplied for the attribute. If the key has no unambiguous, canonical string form, don't include its value. - * - * @deprecated Use ATTR_MESSAGING_KAFKA_MESSAGE_KEY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_MESSAGING_KAFKA_MESSAGE_KEY = TMP_MESSAGING_KAFKA_MESSAGE_KEY; -/** - * Name of the Kafka Consumer Group that is handling the message. Only applies to consumers, not producers. - * - * @deprecated Use ATTR_MESSAGING_KAFKA_CONSUMER_GROUP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_MESSAGING_KAFKA_CONSUMER_GROUP = TMP_MESSAGING_KAFKA_CONSUMER_GROUP; -/** - * Client Id for the Consumer or Producer that is handling the message. - * - * @deprecated Use ATTR_MESSAGING_CLIENT_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_MESSAGING_KAFKA_CLIENT_ID = TMP_MESSAGING_KAFKA_CLIENT_ID; -/** - * Partition the message is sent to. - * - * @deprecated Use ATTR_MESSAGING_KAFKA_DESTINATION_PARTITION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_MESSAGING_KAFKA_PARTITION = TMP_MESSAGING_KAFKA_PARTITION; -/** - * A boolean that is true if the message is a tombstone. - * - * @deprecated Use ATTR_MESSAGING_KAFKA_MESSAGE_TOMBSTONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_MESSAGING_KAFKA_TOMBSTONE = TMP_MESSAGING_KAFKA_TOMBSTONE; -/** - * A string identifying the remoting system. - * - * @deprecated Use ATTR_RPC_SYSTEM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_RPC_SYSTEM = TMP_RPC_SYSTEM; -/** - * The full (logical) name of the service being called, including its package name, if applicable. - * - * Note: This is the logical name of the service from the RPC interface perspective, which can be different from the name of any implementing class. The `code.namespace` attribute may be used to store the latter (despite the attribute name, it may include a class name; e.g., class with method actually executing the call on the server side, RPC client stub class on the client side). - * - * @deprecated Use ATTR_RPC_SERVICE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_RPC_SERVICE = TMP_RPC_SERVICE; -/** - * The name of the (logical) method being called, must be equal to the $method part in the span name. - * - * Note: This is the logical name of the method from the RPC interface perspective, which can be different from the name of any implementing method/function. The `code.function` attribute may be used to store the latter (e.g., method actually executing the call on the server side, RPC client stub method on the client side). - * - * @deprecated Use ATTR_RPC_METHOD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_RPC_METHOD = TMP_RPC_METHOD; -/** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use ATTR_RPC_GRPC_STATUS_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_RPC_GRPC_STATUS_CODE = TMP_RPC_GRPC_STATUS_CODE; -/** - * Protocol version as in `jsonrpc` property of request/response. Since JSON-RPC 1.0 does not specify this, the value can be omitted. - * - * @deprecated Use ATTR_RPC_JSONRPC_VERSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_RPC_JSONRPC_VERSION = TMP_RPC_JSONRPC_VERSION; -/** - * `id` property of request or response. Since protocol allows id to be int, string, `null` or missing (for notifications), value is expected to be cast to string for simplicity. Use empty string in case of `null` value. Omit entirely if this is a notification. - * - * @deprecated Use ATTR_RPC_JSONRPC_REQUEST_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_RPC_JSONRPC_REQUEST_ID = TMP_RPC_JSONRPC_REQUEST_ID; -/** - * `error.code` property of response if it is an error response. - * - * @deprecated Use ATTR_RPC_JSONRPC_ERROR_CODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_RPC_JSONRPC_ERROR_CODE = TMP_RPC_JSONRPC_ERROR_CODE; -/** - * `error.message` property of response if it is an error response. - * - * @deprecated Use ATTR_RPC_JSONRPC_ERROR_MESSAGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_RPC_JSONRPC_ERROR_MESSAGE = TMP_RPC_JSONRPC_ERROR_MESSAGE; -/** - * Whether this is a received or sent message. - * - * @deprecated Use ATTR_MESSAGE_TYPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_MESSAGE_TYPE = TMP_MESSAGE_TYPE; -/** - * MUST be calculated as two different counters starting from `1` one for sent messages and one for received message. - * - * Note: This way we guarantee that the values will be consistent between different implementations. - * - * @deprecated Use ATTR_MESSAGE_ID in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_MESSAGE_ID = TMP_MESSAGE_ID; -/** - * Compressed size of the message in bytes. - * - * @deprecated Use ATTR_MESSAGE_COMPRESSED_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_MESSAGE_COMPRESSED_SIZE = TMP_MESSAGE_COMPRESSED_SIZE; -/** - * Uncompressed size of the message in bytes. - * - * @deprecated Use ATTR_MESSAGE_UNCOMPRESSED_SIZE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.SEMATTRS_MESSAGE_UNCOMPRESSED_SIZE = TMP_MESSAGE_UNCOMPRESSED_SIZE; -/** - * Create exported Value Map for SemanticAttributes values - * @deprecated Use the SEMATTRS_XXXXX constants rather than the SemanticAttributes.XXXXX for bundle minification - */ -exports.SemanticAttributes = -/*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_AWS_LAMBDA_INVOKED_ARN, - TMP_DB_SYSTEM, - TMP_DB_CONNECTION_STRING, - TMP_DB_USER, - TMP_DB_JDBC_DRIVER_CLASSNAME, - TMP_DB_NAME, - TMP_DB_STATEMENT, - TMP_DB_OPERATION, - TMP_DB_MSSQL_INSTANCE_NAME, - TMP_DB_CASSANDRA_KEYSPACE, - TMP_DB_CASSANDRA_PAGE_SIZE, - TMP_DB_CASSANDRA_CONSISTENCY_LEVEL, - TMP_DB_CASSANDRA_TABLE, - TMP_DB_CASSANDRA_IDEMPOTENCE, - TMP_DB_CASSANDRA_SPECULATIVE_EXECUTION_COUNT, - TMP_DB_CASSANDRA_COORDINATOR_ID, - TMP_DB_CASSANDRA_COORDINATOR_DC, - TMP_DB_HBASE_NAMESPACE, - TMP_DB_REDIS_DATABASE_INDEX, - TMP_DB_MONGODB_COLLECTION, - TMP_DB_SQL_TABLE, - TMP_EXCEPTION_TYPE, - TMP_EXCEPTION_MESSAGE, - TMP_EXCEPTION_STACKTRACE, - TMP_EXCEPTION_ESCAPED, - TMP_FAAS_TRIGGER, - TMP_FAAS_EXECUTION, - TMP_FAAS_DOCUMENT_COLLECTION, - TMP_FAAS_DOCUMENT_OPERATION, - TMP_FAAS_DOCUMENT_TIME, - TMP_FAAS_DOCUMENT_NAME, - TMP_FAAS_TIME, - TMP_FAAS_CRON, - TMP_FAAS_COLDSTART, - TMP_FAAS_INVOKED_NAME, - TMP_FAAS_INVOKED_PROVIDER, - TMP_FAAS_INVOKED_REGION, - TMP_NET_TRANSPORT, - TMP_NET_PEER_IP, - TMP_NET_PEER_PORT, - TMP_NET_PEER_NAME, - TMP_NET_HOST_IP, - TMP_NET_HOST_PORT, - TMP_NET_HOST_NAME, - TMP_NET_HOST_CONNECTION_TYPE, - TMP_NET_HOST_CONNECTION_SUBTYPE, - TMP_NET_HOST_CARRIER_NAME, - TMP_NET_HOST_CARRIER_MCC, - TMP_NET_HOST_CARRIER_MNC, - TMP_NET_HOST_CARRIER_ICC, - TMP_PEER_SERVICE, - TMP_ENDUSER_ID, - TMP_ENDUSER_ROLE, - TMP_ENDUSER_SCOPE, - TMP_THREAD_ID, - TMP_THREAD_NAME, - TMP_CODE_FUNCTION, - TMP_CODE_NAMESPACE, - TMP_CODE_FILEPATH, - TMP_CODE_LINENO, - TMP_HTTP_METHOD, - TMP_HTTP_URL, - TMP_HTTP_TARGET, - TMP_HTTP_HOST, - TMP_HTTP_SCHEME, - TMP_HTTP_STATUS_CODE, - TMP_HTTP_FLAVOR, - TMP_HTTP_USER_AGENT, - TMP_HTTP_REQUEST_CONTENT_LENGTH, - TMP_HTTP_REQUEST_CONTENT_LENGTH_UNCOMPRESSED, - TMP_HTTP_RESPONSE_CONTENT_LENGTH, - TMP_HTTP_RESPONSE_CONTENT_LENGTH_UNCOMPRESSED, - TMP_HTTP_SERVER_NAME, - TMP_HTTP_ROUTE, - TMP_HTTP_CLIENT_IP, - TMP_AWS_DYNAMODB_TABLE_NAMES, - TMP_AWS_DYNAMODB_CONSUMED_CAPACITY, - TMP_AWS_DYNAMODB_ITEM_COLLECTION_METRICS, - TMP_AWS_DYNAMODB_PROVISIONED_READ_CAPACITY, - TMP_AWS_DYNAMODB_PROVISIONED_WRITE_CAPACITY, - TMP_AWS_DYNAMODB_CONSISTENT_READ, - TMP_AWS_DYNAMODB_PROJECTION, - TMP_AWS_DYNAMODB_LIMIT, - TMP_AWS_DYNAMODB_ATTRIBUTES_TO_GET, - TMP_AWS_DYNAMODB_INDEX_NAME, - TMP_AWS_DYNAMODB_SELECT, - TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEXES, - TMP_AWS_DYNAMODB_LOCAL_SECONDARY_INDEXES, - TMP_AWS_DYNAMODB_EXCLUSIVE_START_TABLE, - TMP_AWS_DYNAMODB_TABLE_COUNT, - TMP_AWS_DYNAMODB_SCAN_FORWARD, - TMP_AWS_DYNAMODB_SEGMENT, - TMP_AWS_DYNAMODB_TOTAL_SEGMENTS, - TMP_AWS_DYNAMODB_COUNT, - TMP_AWS_DYNAMODB_SCANNED_COUNT, - TMP_AWS_DYNAMODB_ATTRIBUTE_DEFINITIONS, - TMP_AWS_DYNAMODB_GLOBAL_SECONDARY_INDEX_UPDATES, - TMP_MESSAGING_SYSTEM, - TMP_MESSAGING_DESTINATION, - TMP_MESSAGING_DESTINATION_KIND, - TMP_MESSAGING_TEMP_DESTINATION, - TMP_MESSAGING_PROTOCOL, - TMP_MESSAGING_PROTOCOL_VERSION, - TMP_MESSAGING_URL, - TMP_MESSAGING_MESSAGE_ID, - TMP_MESSAGING_CONVERSATION_ID, - TMP_MESSAGING_MESSAGE_PAYLOAD_SIZE_BYTES, - TMP_MESSAGING_MESSAGE_PAYLOAD_COMPRESSED_SIZE_BYTES, - TMP_MESSAGING_OPERATION, - TMP_MESSAGING_CONSUMER_ID, - TMP_MESSAGING_RABBITMQ_ROUTING_KEY, - TMP_MESSAGING_KAFKA_MESSAGE_KEY, - TMP_MESSAGING_KAFKA_CONSUMER_GROUP, - TMP_MESSAGING_KAFKA_CLIENT_ID, - TMP_MESSAGING_KAFKA_PARTITION, - TMP_MESSAGING_KAFKA_TOMBSTONE, - TMP_RPC_SYSTEM, - TMP_RPC_SERVICE, - TMP_RPC_METHOD, - TMP_RPC_GRPC_STATUS_CODE, - TMP_RPC_JSONRPC_VERSION, - TMP_RPC_JSONRPC_REQUEST_ID, - TMP_RPC_JSONRPC_ERROR_CODE, - TMP_RPC_JSONRPC_ERROR_MESSAGE, - TMP_MESSAGE_TYPE, - TMP_MESSAGE_ID, - TMP_MESSAGE_COMPRESSED_SIZE, - TMP_MESSAGE_UNCOMPRESSED_SIZE, -]); -/* ---------------------------------------------------------------------------------------------------------- - * Constant values for DbSystemValues enum definition - * - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * ---------------------------------------------------------------------------------------------------------- */ -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_DBSYSTEMVALUES_OTHER_SQL = 'other_sql'; -const TMP_DBSYSTEMVALUES_MSSQL = 'mssql'; -const TMP_DBSYSTEMVALUES_MYSQL = 'mysql'; -const TMP_DBSYSTEMVALUES_ORACLE = 'oracle'; -const TMP_DBSYSTEMVALUES_DB2 = 'db2'; -const TMP_DBSYSTEMVALUES_POSTGRESQL = 'postgresql'; -const TMP_DBSYSTEMVALUES_REDSHIFT = 'redshift'; -const TMP_DBSYSTEMVALUES_HIVE = 'hive'; -const TMP_DBSYSTEMVALUES_CLOUDSCAPE = 'cloudscape'; -const TMP_DBSYSTEMVALUES_HSQLDB = 'hsqldb'; -const TMP_DBSYSTEMVALUES_PROGRESS = 'progress'; -const TMP_DBSYSTEMVALUES_MAXDB = 'maxdb'; -const TMP_DBSYSTEMVALUES_HANADB = 'hanadb'; -const TMP_DBSYSTEMVALUES_INGRES = 'ingres'; -const TMP_DBSYSTEMVALUES_FIRSTSQL = 'firstsql'; -const TMP_DBSYSTEMVALUES_EDB = 'edb'; -const TMP_DBSYSTEMVALUES_CACHE = 'cache'; -const TMP_DBSYSTEMVALUES_ADABAS = 'adabas'; -const TMP_DBSYSTEMVALUES_FIREBIRD = 'firebird'; -const TMP_DBSYSTEMVALUES_DERBY = 'derby'; -const TMP_DBSYSTEMVALUES_FILEMAKER = 'filemaker'; -const TMP_DBSYSTEMVALUES_INFORMIX = 'informix'; -const TMP_DBSYSTEMVALUES_INSTANTDB = 'instantdb'; -const TMP_DBSYSTEMVALUES_INTERBASE = 'interbase'; -const TMP_DBSYSTEMVALUES_MARIADB = 'mariadb'; -const TMP_DBSYSTEMVALUES_NETEZZA = 'netezza'; -const TMP_DBSYSTEMVALUES_PERVASIVE = 'pervasive'; -const TMP_DBSYSTEMVALUES_POINTBASE = 'pointbase'; -const TMP_DBSYSTEMVALUES_SQLITE = 'sqlite'; -const TMP_DBSYSTEMVALUES_SYBASE = 'sybase'; -const TMP_DBSYSTEMVALUES_TERADATA = 'teradata'; -const TMP_DBSYSTEMVALUES_VERTICA = 'vertica'; -const TMP_DBSYSTEMVALUES_H2 = 'h2'; -const TMP_DBSYSTEMVALUES_COLDFUSION = 'coldfusion'; -const TMP_DBSYSTEMVALUES_CASSANDRA = 'cassandra'; -const TMP_DBSYSTEMVALUES_HBASE = 'hbase'; -const TMP_DBSYSTEMVALUES_MONGODB = 'mongodb'; -const TMP_DBSYSTEMVALUES_REDIS = 'redis'; -const TMP_DBSYSTEMVALUES_COUCHBASE = 'couchbase'; -const TMP_DBSYSTEMVALUES_COUCHDB = 'couchdb'; -const TMP_DBSYSTEMVALUES_COSMOSDB = 'cosmosdb'; -const TMP_DBSYSTEMVALUES_DYNAMODB = 'dynamodb'; -const TMP_DBSYSTEMVALUES_NEO4J = 'neo4j'; -const TMP_DBSYSTEMVALUES_GEODE = 'geode'; -const TMP_DBSYSTEMVALUES_ELASTICSEARCH = 'elasticsearch'; -const TMP_DBSYSTEMVALUES_MEMCACHED = 'memcached'; -const TMP_DBSYSTEMVALUES_COCKROACHDB = 'cockroachdb'; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_OTHER_SQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_OTHER_SQL = TMP_DBSYSTEMVALUES_OTHER_SQL; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MSSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_MSSQL = TMP_DBSYSTEMVALUES_MSSQL; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MYSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_MYSQL = TMP_DBSYSTEMVALUES_MYSQL; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_ORACLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_ORACLE = TMP_DBSYSTEMVALUES_ORACLE; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_DB2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_DB2 = TMP_DBSYSTEMVALUES_DB2; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_POSTGRESQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_POSTGRESQL = TMP_DBSYSTEMVALUES_POSTGRESQL; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_REDSHIFT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_REDSHIFT = TMP_DBSYSTEMVALUES_REDSHIFT; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_HIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_HIVE = TMP_DBSYSTEMVALUES_HIVE; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_CLOUDSCAPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_CLOUDSCAPE = TMP_DBSYSTEMVALUES_CLOUDSCAPE; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_HSQLDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_HSQLDB = TMP_DBSYSTEMVALUES_HSQLDB; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_PROGRESS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_PROGRESS = TMP_DBSYSTEMVALUES_PROGRESS; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MAXDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_MAXDB = TMP_DBSYSTEMVALUES_MAXDB; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_HANADB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_HANADB = TMP_DBSYSTEMVALUES_HANADB; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_INGRES in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_INGRES = TMP_DBSYSTEMVALUES_INGRES; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_FIRSTSQL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_FIRSTSQL = TMP_DBSYSTEMVALUES_FIRSTSQL; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_EDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_EDB = TMP_DBSYSTEMVALUES_EDB; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_CACHE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_CACHE = TMP_DBSYSTEMVALUES_CACHE; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_ADABAS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_ADABAS = TMP_DBSYSTEMVALUES_ADABAS; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_FIREBIRD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_FIREBIRD = TMP_DBSYSTEMVALUES_FIREBIRD; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_DERBY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_DERBY = TMP_DBSYSTEMVALUES_DERBY; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_FILEMAKER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_FILEMAKER = TMP_DBSYSTEMVALUES_FILEMAKER; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_INFORMIX in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_INFORMIX = TMP_DBSYSTEMVALUES_INFORMIX; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_INSTANTDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_INSTANTDB = TMP_DBSYSTEMVALUES_INSTANTDB; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_INTERBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_INTERBASE = TMP_DBSYSTEMVALUES_INTERBASE; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MARIADB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_MARIADB = TMP_DBSYSTEMVALUES_MARIADB; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_NETEZZA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_NETEZZA = TMP_DBSYSTEMVALUES_NETEZZA; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_PERVASIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_PERVASIVE = TMP_DBSYSTEMVALUES_PERVASIVE; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_POINTBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_POINTBASE = TMP_DBSYSTEMVALUES_POINTBASE; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_SQLITE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_SQLITE = TMP_DBSYSTEMVALUES_SQLITE; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_SYBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_SYBASE = TMP_DBSYSTEMVALUES_SYBASE; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_TERADATA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_TERADATA = TMP_DBSYSTEMVALUES_TERADATA; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_VERTICA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_VERTICA = TMP_DBSYSTEMVALUES_VERTICA; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_H2 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_H2 = TMP_DBSYSTEMVALUES_H2; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_COLDFUSION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_COLDFUSION = TMP_DBSYSTEMVALUES_COLDFUSION; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_CASSANDRA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_CASSANDRA = TMP_DBSYSTEMVALUES_CASSANDRA; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_HBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_HBASE = TMP_DBSYSTEMVALUES_HBASE; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MONGODB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_MONGODB = TMP_DBSYSTEMVALUES_MONGODB; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_REDIS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_REDIS = TMP_DBSYSTEMVALUES_REDIS; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_COUCHBASE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_COUCHBASE = TMP_DBSYSTEMVALUES_COUCHBASE; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_COUCHDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_COUCHDB = TMP_DBSYSTEMVALUES_COUCHDB; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_COSMOSDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_COSMOSDB = TMP_DBSYSTEMVALUES_COSMOSDB; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_DYNAMODB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_DYNAMODB = TMP_DBSYSTEMVALUES_DYNAMODB; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_NEO4J in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_NEO4J = TMP_DBSYSTEMVALUES_NEO4J; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_GEODE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_GEODE = TMP_DBSYSTEMVALUES_GEODE; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_ELASTICSEARCH in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_ELASTICSEARCH = TMP_DBSYSTEMVALUES_ELASTICSEARCH; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_MEMCACHED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_MEMCACHED = TMP_DBSYSTEMVALUES_MEMCACHED; -/** - * An identifier for the database management system (DBMS) product being used. See below for a list of well-known identifiers. - * - * @deprecated Use DB_SYSTEM_VALUE_COCKROACHDB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBSYSTEMVALUES_COCKROACHDB = TMP_DBSYSTEMVALUES_COCKROACHDB; -/** - * The constant map of values for DbSystemValues. - * @deprecated Use the DBSYSTEMVALUES_XXXXX constants rather than the DbSystemValues.XXXXX for bundle minification. - */ -exports.DbSystemValues = -/*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_DBSYSTEMVALUES_OTHER_SQL, - TMP_DBSYSTEMVALUES_MSSQL, - TMP_DBSYSTEMVALUES_MYSQL, - TMP_DBSYSTEMVALUES_ORACLE, - TMP_DBSYSTEMVALUES_DB2, - TMP_DBSYSTEMVALUES_POSTGRESQL, - TMP_DBSYSTEMVALUES_REDSHIFT, - TMP_DBSYSTEMVALUES_HIVE, - TMP_DBSYSTEMVALUES_CLOUDSCAPE, - TMP_DBSYSTEMVALUES_HSQLDB, - TMP_DBSYSTEMVALUES_PROGRESS, - TMP_DBSYSTEMVALUES_MAXDB, - TMP_DBSYSTEMVALUES_HANADB, - TMP_DBSYSTEMVALUES_INGRES, - TMP_DBSYSTEMVALUES_FIRSTSQL, - TMP_DBSYSTEMVALUES_EDB, - TMP_DBSYSTEMVALUES_CACHE, - TMP_DBSYSTEMVALUES_ADABAS, - TMP_DBSYSTEMVALUES_FIREBIRD, - TMP_DBSYSTEMVALUES_DERBY, - TMP_DBSYSTEMVALUES_FILEMAKER, - TMP_DBSYSTEMVALUES_INFORMIX, - TMP_DBSYSTEMVALUES_INSTANTDB, - TMP_DBSYSTEMVALUES_INTERBASE, - TMP_DBSYSTEMVALUES_MARIADB, - TMP_DBSYSTEMVALUES_NETEZZA, - TMP_DBSYSTEMVALUES_PERVASIVE, - TMP_DBSYSTEMVALUES_POINTBASE, - TMP_DBSYSTEMVALUES_SQLITE, - TMP_DBSYSTEMVALUES_SYBASE, - TMP_DBSYSTEMVALUES_TERADATA, - TMP_DBSYSTEMVALUES_VERTICA, - TMP_DBSYSTEMVALUES_H2, - TMP_DBSYSTEMVALUES_COLDFUSION, - TMP_DBSYSTEMVALUES_CASSANDRA, - TMP_DBSYSTEMVALUES_HBASE, - TMP_DBSYSTEMVALUES_MONGODB, - TMP_DBSYSTEMVALUES_REDIS, - TMP_DBSYSTEMVALUES_COUCHBASE, - TMP_DBSYSTEMVALUES_COUCHDB, - TMP_DBSYSTEMVALUES_COSMOSDB, - TMP_DBSYSTEMVALUES_DYNAMODB, - TMP_DBSYSTEMVALUES_NEO4J, - TMP_DBSYSTEMVALUES_GEODE, - TMP_DBSYSTEMVALUES_ELASTICSEARCH, - TMP_DBSYSTEMVALUES_MEMCACHED, - TMP_DBSYSTEMVALUES_COCKROACHDB, -]); -/* ---------------------------------------------------------------------------------------------------------- - * Constant values for DbCassandraConsistencyLevelValues enum definition - * - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * ---------------------------------------------------------------------------------------------------------- */ -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL = 'all'; -const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = 'each_quorum'; -const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = 'quorum'; -const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = 'local_quorum'; -const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE = 'one'; -const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO = 'two'; -const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE = 'three'; -const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = 'local_one'; -const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY = 'any'; -const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = 'serial'; -const TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = 'local_serial'; -/** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ALL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBCASSANDRACONSISTENCYLEVELVALUES_ALL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL; -/** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_EACH_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM; -/** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM; -/** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_QUORUM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM; -/** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBCASSANDRACONSISTENCYLEVELVALUES_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE; -/** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_TWO in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBCASSANDRACONSISTENCYLEVELVALUES_TWO = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO; -/** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_THREE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBCASSANDRACONSISTENCYLEVELVALUES_THREE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE; -/** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_ONE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE; -/** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_ANY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBCASSANDRACONSISTENCYLEVELVALUES_ANY = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY; -/** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_SERIAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL; -/** - * The consistency level of the query. Based on consistency values from [CQL](https://docs.datastax.com/en/cassandra-oss/3.0/cassandra/dml/dmlConfigConsistency.html). - * - * @deprecated Use DB_CASSANDRA_CONSISTENCY_LEVEL_VALUE_LOCAL_SERIAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL = TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL; -/** - * The constant map of values for DbCassandraConsistencyLevelValues. - * @deprecated Use the DBCASSANDRACONSISTENCYLEVELVALUES_XXXXX constants rather than the DbCassandraConsistencyLevelValues.XXXXX for bundle minification. - */ -exports.DbCassandraConsistencyLevelValues = -/*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ALL, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_EACH_QUORUM, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_QUORUM, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_QUORUM, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ONE, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_TWO, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_THREE, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_ONE, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_ANY, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_SERIAL, - TMP_DBCASSANDRACONSISTENCYLEVELVALUES_LOCAL_SERIAL, -]); -/* ---------------------------------------------------------------------------------------------------------- - * Constant values for FaasTriggerValues enum definition - * - * Type of the trigger on which the function is executed. - * ---------------------------------------------------------------------------------------------------------- */ -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_FAASTRIGGERVALUES_DATASOURCE = 'datasource'; -const TMP_FAASTRIGGERVALUES_HTTP = 'http'; -const TMP_FAASTRIGGERVALUES_PUBSUB = 'pubsub'; -const TMP_FAASTRIGGERVALUES_TIMER = 'timer'; -const TMP_FAASTRIGGERVALUES_OTHER = 'other'; -/** - * Type of the trigger on which the function is executed. - * - * @deprecated Use FAAS_TRIGGER_VALUE_DATASOURCE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.FAASTRIGGERVALUES_DATASOURCE = TMP_FAASTRIGGERVALUES_DATASOURCE; -/** - * Type of the trigger on which the function is executed. - * - * @deprecated Use FAAS_TRIGGER_VALUE_HTTP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.FAASTRIGGERVALUES_HTTP = TMP_FAASTRIGGERVALUES_HTTP; -/** - * Type of the trigger on which the function is executed. - * - * @deprecated Use FAAS_TRIGGER_VALUE_PUBSUB in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.FAASTRIGGERVALUES_PUBSUB = TMP_FAASTRIGGERVALUES_PUBSUB; -/** - * Type of the trigger on which the function is executed. - * - * @deprecated Use FAAS_TRIGGER_VALUE_TIMER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.FAASTRIGGERVALUES_TIMER = TMP_FAASTRIGGERVALUES_TIMER; -/** - * Type of the trigger on which the function is executed. - * - * @deprecated Use FAAS_TRIGGER_VALUE_OTHER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.FAASTRIGGERVALUES_OTHER = TMP_FAASTRIGGERVALUES_OTHER; -/** - * The constant map of values for FaasTriggerValues. - * @deprecated Use the FAASTRIGGERVALUES_XXXXX constants rather than the FaasTriggerValues.XXXXX for bundle minification. - */ -exports.FaasTriggerValues = -/*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_FAASTRIGGERVALUES_DATASOURCE, - TMP_FAASTRIGGERVALUES_HTTP, - TMP_FAASTRIGGERVALUES_PUBSUB, - TMP_FAASTRIGGERVALUES_TIMER, - TMP_FAASTRIGGERVALUES_OTHER, -]); -/* ---------------------------------------------------------------------------------------------------------- - * Constant values for FaasDocumentOperationValues enum definition - * - * Describes the type of the operation that was performed on the data. - * ---------------------------------------------------------------------------------------------------------- */ -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_FAASDOCUMENTOPERATIONVALUES_INSERT = 'insert'; -const TMP_FAASDOCUMENTOPERATIONVALUES_EDIT = 'edit'; -const TMP_FAASDOCUMENTOPERATIONVALUES_DELETE = 'delete'; -/** - * Describes the type of the operation that was performed on the data. - * - * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_INSERT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.FAASDOCUMENTOPERATIONVALUES_INSERT = TMP_FAASDOCUMENTOPERATIONVALUES_INSERT; -/** - * Describes the type of the operation that was performed on the data. - * - * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_EDIT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.FAASDOCUMENTOPERATIONVALUES_EDIT = TMP_FAASDOCUMENTOPERATIONVALUES_EDIT; -/** - * Describes the type of the operation that was performed on the data. - * - * @deprecated Use FAAS_DOCUMENT_OPERATION_VALUE_DELETE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.FAASDOCUMENTOPERATIONVALUES_DELETE = TMP_FAASDOCUMENTOPERATIONVALUES_DELETE; -/** - * The constant map of values for FaasDocumentOperationValues. - * @deprecated Use the FAASDOCUMENTOPERATIONVALUES_XXXXX constants rather than the FaasDocumentOperationValues.XXXXX for bundle minification. - */ -exports.FaasDocumentOperationValues = -/*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_FAASDOCUMENTOPERATIONVALUES_INSERT, - TMP_FAASDOCUMENTOPERATIONVALUES_EDIT, - TMP_FAASDOCUMENTOPERATIONVALUES_DELETE, -]); -/* ---------------------------------------------------------------------------------------------------------- - * Constant values for FaasInvokedProviderValues enum definition - * - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * ---------------------------------------------------------------------------------------------------------- */ -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = 'alibaba_cloud'; -const TMP_FAASINVOKEDPROVIDERVALUES_AWS = 'aws'; -const TMP_FAASINVOKEDPROVIDERVALUES_AZURE = 'azure'; -const TMP_FAASINVOKEDPROVIDERVALUES_GCP = 'gcp'; -/** - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * - * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_ALIBABA_CLOUD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD = TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD; -/** - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * - * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_AWS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.FAASINVOKEDPROVIDERVALUES_AWS = TMP_FAASINVOKEDPROVIDERVALUES_AWS; -/** - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * - * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_AZURE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.FAASINVOKEDPROVIDERVALUES_AZURE = TMP_FAASINVOKEDPROVIDERVALUES_AZURE; -/** - * The cloud provider of the invoked function. - * - * Note: SHOULD be equal to the `cloud.provider` resource attribute of the invoked function. - * - * @deprecated Use FAAS_INVOKED_PROVIDER_VALUE_GCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.FAASINVOKEDPROVIDERVALUES_GCP = TMP_FAASINVOKEDPROVIDERVALUES_GCP; -/** - * The constant map of values for FaasInvokedProviderValues. - * @deprecated Use the FAASINVOKEDPROVIDERVALUES_XXXXX constants rather than the FaasInvokedProviderValues.XXXXX for bundle minification. - */ -exports.FaasInvokedProviderValues = -/*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_FAASINVOKEDPROVIDERVALUES_ALIBABA_CLOUD, - TMP_FAASINVOKEDPROVIDERVALUES_AWS, - TMP_FAASINVOKEDPROVIDERVALUES_AZURE, - TMP_FAASINVOKEDPROVIDERVALUES_GCP, -]); -/* ---------------------------------------------------------------------------------------------------------- - * Constant values for NetTransportValues enum definition - * - * Transport protocol used. See note below. - * ---------------------------------------------------------------------------------------------------------- */ -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_NETTRANSPORTVALUES_IP_TCP = 'ip_tcp'; -const TMP_NETTRANSPORTVALUES_IP_UDP = 'ip_udp'; -const TMP_NETTRANSPORTVALUES_IP = 'ip'; -const TMP_NETTRANSPORTVALUES_UNIX = 'unix'; -const TMP_NETTRANSPORTVALUES_PIPE = 'pipe'; -const TMP_NETTRANSPORTVALUES_INPROC = 'inproc'; -const TMP_NETTRANSPORTVALUES_OTHER = 'other'; -/** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_IP_TCP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETTRANSPORTVALUES_IP_TCP = TMP_NETTRANSPORTVALUES_IP_TCP; -/** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_IP_UDP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETTRANSPORTVALUES_IP_UDP = TMP_NETTRANSPORTVALUES_IP_UDP; -/** - * Transport protocol used. See note below. - * - * @deprecated Removed in v1.21.0. - */ -exports.NETTRANSPORTVALUES_IP = TMP_NETTRANSPORTVALUES_IP; -/** - * Transport protocol used. See note below. - * - * @deprecated Removed in v1.21.0. - */ -exports.NETTRANSPORTVALUES_UNIX = TMP_NETTRANSPORTVALUES_UNIX; -/** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_PIPE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETTRANSPORTVALUES_PIPE = TMP_NETTRANSPORTVALUES_PIPE; -/** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_INPROC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETTRANSPORTVALUES_INPROC = TMP_NETTRANSPORTVALUES_INPROC; -/** - * Transport protocol used. See note below. - * - * @deprecated Use NET_TRANSPORT_VALUE_OTHER in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETTRANSPORTVALUES_OTHER = TMP_NETTRANSPORTVALUES_OTHER; -/** - * The constant map of values for NetTransportValues. - * @deprecated Use the NETTRANSPORTVALUES_XXXXX constants rather than the NetTransportValues.XXXXX for bundle minification. - */ -exports.NetTransportValues = -/*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_NETTRANSPORTVALUES_IP_TCP, - TMP_NETTRANSPORTVALUES_IP_UDP, - TMP_NETTRANSPORTVALUES_IP, - TMP_NETTRANSPORTVALUES_UNIX, - TMP_NETTRANSPORTVALUES_PIPE, - TMP_NETTRANSPORTVALUES_INPROC, - TMP_NETTRANSPORTVALUES_OTHER, -]); -/* ---------------------------------------------------------------------------------------------------------- - * Constant values for NetHostConnectionTypeValues enum definition - * - * The internet connection type currently being used by the host. - * ---------------------------------------------------------------------------------------------------------- */ -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI = 'wifi'; -const TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED = 'wired'; -const TMP_NETHOSTCONNECTIONTYPEVALUES_CELL = 'cell'; -const TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = 'unavailable'; -const TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = 'unknown'; -/** - * The internet connection type currently being used by the host. - * - * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_WIFI in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONTYPEVALUES_WIFI = TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI; -/** - * The internet connection type currently being used by the host. - * - * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_WIRED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONTYPEVALUES_WIRED = TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED; -/** - * The internet connection type currently being used by the host. - * - * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_CELL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONTYPEVALUES_CELL = TMP_NETHOSTCONNECTIONTYPEVALUES_CELL; -/** - * The internet connection type currently being used by the host. - * - * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_UNAVAILABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE = TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE; -/** - * The internet connection type currently being used by the host. - * - * @deprecated Use NETWORK_CONNECTION_TYPE_VALUE_UNKNOWN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONTYPEVALUES_UNKNOWN = TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN; -/** - * The constant map of values for NetHostConnectionTypeValues. - * @deprecated Use the NETHOSTCONNECTIONTYPEVALUES_XXXXX constants rather than the NetHostConnectionTypeValues.XXXXX for bundle minification. - */ -exports.NetHostConnectionTypeValues = -/*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_NETHOSTCONNECTIONTYPEVALUES_WIFI, - TMP_NETHOSTCONNECTIONTYPEVALUES_WIRED, - TMP_NETHOSTCONNECTIONTYPEVALUES_CELL, - TMP_NETHOSTCONNECTIONTYPEVALUES_UNAVAILABLE, - TMP_NETHOSTCONNECTIONTYPEVALUES_UNKNOWN, -]); -/* ---------------------------------------------------------------------------------------------------------- - * Constant values for NetHostConnectionSubtypeValues enum definition - * - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * ---------------------------------------------------------------------------------------------------------- */ -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = 'gprs'; -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = 'edge'; -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = 'umts'; -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = 'cdma'; -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = 'evdo_0'; -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = 'evdo_a'; -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = 'cdma2000_1xrtt'; -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = 'hsdpa'; -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = 'hsupa'; -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = 'hspa'; -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = 'iden'; -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = 'evdo_b'; -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE = 'lte'; -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = 'ehrpd'; -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = 'hspap'; -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM = 'gsm'; -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = 'td_scdma'; -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = 'iwlan'; -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR = 'nr'; -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = 'nrnsa'; -const TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = 'lte_ca'; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_GPRS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_GPRS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EDGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_EDGE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_UMTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_UMTS = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_CDMA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0 = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_A in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_CDMA2000_1XRTT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSDPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSUPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSPA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_IDEN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_IDEN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EVDO_B in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_LTE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_EHRPD in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_HSPAP in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_GSM in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_GSM = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_TD_SCDMA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_IWLAN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_NR in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_NR = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_NRNSA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA; -/** - * This describes more details regarding the connection.type. It may be the type of cell technology connection, but it could be used for describing details about a wifi connection. - * - * @deprecated Use NETWORK_CONNECTION_SUBTYPE_VALUE_LTE_CA in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA = TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA; -/** - * The constant map of values for NetHostConnectionSubtypeValues. - * @deprecated Use the NETHOSTCONNECTIONSUBTYPEVALUES_XXXXX constants rather than the NetHostConnectionSubtypeValues.XXXXX for bundle minification. - */ -exports.NetHostConnectionSubtypeValues = -/*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GPRS, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EDGE, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_UMTS, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_0, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_A, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_CDMA2000_1XRTT, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSDPA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSUPA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IDEN, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EVDO_B, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_EHRPD, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_HSPAP, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_GSM, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_TD_SCDMA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_IWLAN, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NR, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_NRNSA, - TMP_NETHOSTCONNECTIONSUBTYPEVALUES_LTE_CA, -]); -/* ---------------------------------------------------------------------------------------------------------- - * Constant values for HttpFlavorValues enum definition - * - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * ---------------------------------------------------------------------------------------------------------- */ -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_HTTPFLAVORVALUES_HTTP_1_0 = '1.0'; -const TMP_HTTPFLAVORVALUES_HTTP_1_1 = '1.1'; -const TMP_HTTPFLAVORVALUES_HTTP_2_0 = '2.0'; -const TMP_HTTPFLAVORVALUES_SPDY = 'SPDY'; -const TMP_HTTPFLAVORVALUES_QUIC = 'QUIC'; -/** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_1_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.HTTPFLAVORVALUES_HTTP_1_0 = TMP_HTTPFLAVORVALUES_HTTP_1_0; -/** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_1_1 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.HTTPFLAVORVALUES_HTTP_1_1 = TMP_HTTPFLAVORVALUES_HTTP_1_1; -/** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use HTTP_FLAVOR_VALUE_HTTP_2_0 in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.HTTPFLAVORVALUES_HTTP_2_0 = TMP_HTTPFLAVORVALUES_HTTP_2_0; -/** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use HTTP_FLAVOR_VALUE_SPDY in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.HTTPFLAVORVALUES_SPDY = TMP_HTTPFLAVORVALUES_SPDY; -/** - * Kind of HTTP protocol used. - * - * Note: If `net.transport` is not specified, it can be assumed to be `IP.TCP` except if `http.flavor` is `QUIC`, in which case `IP.UDP` is assumed. - * - * @deprecated Use HTTP_FLAVOR_VALUE_QUIC in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.HTTPFLAVORVALUES_QUIC = TMP_HTTPFLAVORVALUES_QUIC; -/** - * The constant map of values for HttpFlavorValues. - * @deprecated Use the HTTPFLAVORVALUES_XXXXX constants rather than the HttpFlavorValues.XXXXX for bundle minification. - */ -exports.HttpFlavorValues = { - HTTP_1_0: TMP_HTTPFLAVORVALUES_HTTP_1_0, - HTTP_1_1: TMP_HTTPFLAVORVALUES_HTTP_1_1, - HTTP_2_0: TMP_HTTPFLAVORVALUES_HTTP_2_0, - SPDY: TMP_HTTPFLAVORVALUES_SPDY, - QUIC: TMP_HTTPFLAVORVALUES_QUIC, -}; -/* ---------------------------------------------------------------------------------------------------------- - * Constant values for MessagingDestinationKindValues enum definition - * - * The kind of message destination. - * ---------------------------------------------------------------------------------------------------------- */ -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE = 'queue'; -const TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC = 'topic'; -/** - * The kind of message destination. - * - * @deprecated Removed in semconv v1.20.0. - */ -exports.MESSAGINGDESTINATIONKINDVALUES_QUEUE = TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE; -/** - * The kind of message destination. - * - * @deprecated Removed in semconv v1.20.0. - */ -exports.MESSAGINGDESTINATIONKINDVALUES_TOPIC = TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC; -/** - * The constant map of values for MessagingDestinationKindValues. - * @deprecated Use the MESSAGINGDESTINATIONKINDVALUES_XXXXX constants rather than the MessagingDestinationKindValues.XXXXX for bundle minification. - */ -exports.MessagingDestinationKindValues = -/*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_MESSAGINGDESTINATIONKINDVALUES_QUEUE, - TMP_MESSAGINGDESTINATIONKINDVALUES_TOPIC, -]); -/* ---------------------------------------------------------------------------------------------------------- - * Constant values for MessagingOperationValues enum definition - * - * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. - * ---------------------------------------------------------------------------------------------------------- */ -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_MESSAGINGOPERATIONVALUES_RECEIVE = 'receive'; -const TMP_MESSAGINGOPERATIONVALUES_PROCESS = 'process'; -/** - * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. - * - * @deprecated Use MESSAGING_OPERATION_TYPE_VALUE_RECEIVE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.MESSAGINGOPERATIONVALUES_RECEIVE = TMP_MESSAGINGOPERATIONVALUES_RECEIVE; -/** - * A string identifying the kind of message consumption as defined in the [Operation names](#operation-names) section above. If the operation is "send", this attribute MUST NOT be set, since the operation can be inferred from the span kind in that case. - * - * @deprecated Use MESSAGING_OPERATION_TYPE_VALUE_PROCESS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.MESSAGINGOPERATIONVALUES_PROCESS = TMP_MESSAGINGOPERATIONVALUES_PROCESS; -/** - * The constant map of values for MessagingOperationValues. - * @deprecated Use the MESSAGINGOPERATIONVALUES_XXXXX constants rather than the MessagingOperationValues.XXXXX for bundle minification. - */ -exports.MessagingOperationValues = -/*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_MESSAGINGOPERATIONVALUES_RECEIVE, - TMP_MESSAGINGOPERATIONVALUES_PROCESS, -]); -/* ---------------------------------------------------------------------------------------------------------- - * Constant values for RpcGrpcStatusCodeValues enum definition - * - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * ---------------------------------------------------------------------------------------------------------- */ -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_RPCGRPCSTATUSCODEVALUES_OK = 0; -const TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED = 1; -const TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN = 2; -const TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = 3; -const TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = 4; -const TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND = 5; -const TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = 6; -const TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = 7; -const TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = 8; -const TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = 9; -const TMP_RPCGRPCSTATUSCODEVALUES_ABORTED = 10; -const TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = 11; -const TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = 12; -const TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL = 13; -const TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = 14; -const TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS = 15; -const TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = 16; -/** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_OK in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.RPCGRPCSTATUSCODEVALUES_OK = TMP_RPCGRPCSTATUSCODEVALUES_OK; -/** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_CANCELLED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.RPCGRPCSTATUSCODEVALUES_CANCELLED = TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED; -/** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNKNOWN in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.RPCGRPCSTATUSCODEVALUES_UNKNOWN = TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN; -/** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_INVALID_ARGUMENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT = TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT; -/** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_DEADLINE_EXCEEDED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED = TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED; -/** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_NOT_FOUND in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.RPCGRPCSTATUSCODEVALUES_NOT_FOUND = TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND; -/** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_ALREADY_EXISTS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS = TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS; -/** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_PERMISSION_DENIED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED = TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED; -/** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_RESOURCE_EXHAUSTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED = TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED; -/** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_FAILED_PRECONDITION in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION = TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION; -/** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_ABORTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.RPCGRPCSTATUSCODEVALUES_ABORTED = TMP_RPCGRPCSTATUSCODEVALUES_ABORTED; -/** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_OUT_OF_RANGE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE = TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE; -/** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNIMPLEMENTED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED = TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED; -/** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_INTERNAL in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.RPCGRPCSTATUSCODEVALUES_INTERNAL = TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL; -/** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNAVAILABLE in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.RPCGRPCSTATUSCODEVALUES_UNAVAILABLE = TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE; -/** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_DATA_LOSS in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.RPCGRPCSTATUSCODEVALUES_DATA_LOSS = TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS; -/** - * The [numeric status code](https://github.com/grpc/grpc/blob/v1.33.2/doc/statuscodes.md) of the gRPC request. - * - * @deprecated Use RPC_GRPC_STATUS_CODE_VALUE_UNAUTHENTICATED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED = TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED; -/** - * The constant map of values for RpcGrpcStatusCodeValues. - * @deprecated Use the RPCGRPCSTATUSCODEVALUES_XXXXX constants rather than the RpcGrpcStatusCodeValues.XXXXX for bundle minification. - */ -exports.RpcGrpcStatusCodeValues = { - OK: TMP_RPCGRPCSTATUSCODEVALUES_OK, - CANCELLED: TMP_RPCGRPCSTATUSCODEVALUES_CANCELLED, - UNKNOWN: TMP_RPCGRPCSTATUSCODEVALUES_UNKNOWN, - INVALID_ARGUMENT: TMP_RPCGRPCSTATUSCODEVALUES_INVALID_ARGUMENT, - DEADLINE_EXCEEDED: TMP_RPCGRPCSTATUSCODEVALUES_DEADLINE_EXCEEDED, - NOT_FOUND: TMP_RPCGRPCSTATUSCODEVALUES_NOT_FOUND, - ALREADY_EXISTS: TMP_RPCGRPCSTATUSCODEVALUES_ALREADY_EXISTS, - PERMISSION_DENIED: TMP_RPCGRPCSTATUSCODEVALUES_PERMISSION_DENIED, - RESOURCE_EXHAUSTED: TMP_RPCGRPCSTATUSCODEVALUES_RESOURCE_EXHAUSTED, - FAILED_PRECONDITION: TMP_RPCGRPCSTATUSCODEVALUES_FAILED_PRECONDITION, - ABORTED: TMP_RPCGRPCSTATUSCODEVALUES_ABORTED, - OUT_OF_RANGE: TMP_RPCGRPCSTATUSCODEVALUES_OUT_OF_RANGE, - UNIMPLEMENTED: TMP_RPCGRPCSTATUSCODEVALUES_UNIMPLEMENTED, - INTERNAL: TMP_RPCGRPCSTATUSCODEVALUES_INTERNAL, - UNAVAILABLE: TMP_RPCGRPCSTATUSCODEVALUES_UNAVAILABLE, - DATA_LOSS: TMP_RPCGRPCSTATUSCODEVALUES_DATA_LOSS, - UNAUTHENTICATED: TMP_RPCGRPCSTATUSCODEVALUES_UNAUTHENTICATED, -}; -/* ---------------------------------------------------------------------------------------------------------- - * Constant values for MessageTypeValues enum definition - * - * Whether this is a received or sent message. - * ---------------------------------------------------------------------------------------------------------- */ -// Temporary local constants to assign to the individual exports and the namespaced version -// Required to avoid the namespace exports using the unminifiable export names for some package types -const TMP_MESSAGETYPEVALUES_SENT = 'SENT'; -const TMP_MESSAGETYPEVALUES_RECEIVED = 'RECEIVED'; -/** - * Whether this is a received or sent message. - * - * @deprecated Use MESSAGE_TYPE_VALUE_SENT in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.MESSAGETYPEVALUES_SENT = TMP_MESSAGETYPEVALUES_SENT; -/** - * Whether this is a received or sent message. - * - * @deprecated Use MESSAGE_TYPE_VALUE_RECEIVED in [incubating entry-point]({@link https://github.com/open-telemetry/opentelemetry-js/blob/main/semantic-conventions/README.md#unstable-semconv}). - */ -exports.MESSAGETYPEVALUES_RECEIVED = TMP_MESSAGETYPEVALUES_RECEIVED; -/** - * The constant map of values for MessageTypeValues. - * @deprecated Use the MESSAGETYPEVALUES_XXXXX constants rather than the MessageTypeValues.XXXXX for bundle minification. - */ -exports.MessageTypeValues = -/*#__PURE__*/ (0, utils_1.createConstMap)([ - TMP_MESSAGETYPEVALUES_SENT, - TMP_MESSAGETYPEVALUES_RECEIVED, -]); -//# sourceMappingURL=SemanticAttributes.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/trace/index.js b/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/trace/index.js deleted file mode 100644 index 19370d56..00000000 --- a/claude-code-source/node_modules/@opentelemetry/semantic-conventions/build/src/trace/index.js +++ /dev/null @@ -1,37 +0,0 @@ -"use strict"; -/* - * Copyright The OpenTelemetry Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -/* eslint-disable no-restricted-syntax -- - * These re-exports are only of constants, only one-level deep at this point, - * and should not cause problems for tree-shakers. - */ -__exportStar(require("./SemanticAttributes"), exports); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@pondwader/socks5-server/dist/index.js b/claude-code-source/node_modules/@pondwader/socks5-server/dist/index.js deleted file mode 100644 index 51696e58..00000000 --- a/claude-code-source/node_modules/@pondwader/socks5-server/dist/index.js +++ /dev/null @@ -1,346 +0,0 @@ -"use strict"; -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - Socks5Server: () => Socks5Server, - createServer: () => createServer, - defaultConnectionHandler: () => connectionHandler_default -}); -module.exports = __toCommonJS(src_exports); - -// src/Server.ts -var import_net2 = __toESM(require("net")); - -// src/types.ts -var Socks5ConnectionCommand = /* @__PURE__ */ ((Socks5ConnectionCommand2) => { - Socks5ConnectionCommand2[Socks5ConnectionCommand2["connect"] = 1] = "connect"; - Socks5ConnectionCommand2[Socks5ConnectionCommand2["bind"] = 2] = "bind"; - Socks5ConnectionCommand2[Socks5ConnectionCommand2["udp"] = 3] = "udp"; - return Socks5ConnectionCommand2; -})(Socks5ConnectionCommand || {}); -var Socks5ConnectionStatus = /* @__PURE__ */ ((Socks5ConnectionStatus2) => { - Socks5ConnectionStatus2[Socks5ConnectionStatus2["REQUEST_GRANTED"] = 0] = "REQUEST_GRANTED"; - Socks5ConnectionStatus2[Socks5ConnectionStatus2["GENERAL_FAILURE"] = 1] = "GENERAL_FAILURE"; - Socks5ConnectionStatus2[Socks5ConnectionStatus2["CONNECTION_NOT_ALLOWED"] = 2] = "CONNECTION_NOT_ALLOWED"; - Socks5ConnectionStatus2[Socks5ConnectionStatus2["NETWORK_UNREACHABLE"] = 3] = "NETWORK_UNREACHABLE"; - Socks5ConnectionStatus2[Socks5ConnectionStatus2["HOST_UNREACHABLE"] = 4] = "HOST_UNREACHABLE"; - Socks5ConnectionStatus2[Socks5ConnectionStatus2["CONNECTION_REFUSED"] = 5] = "CONNECTION_REFUSED"; - Socks5ConnectionStatus2[Socks5ConnectionStatus2["TTL_EXPIRED"] = 6] = "TTL_EXPIRED"; - Socks5ConnectionStatus2[Socks5ConnectionStatus2["COMMAND_NOT_SUPPORTED"] = 7] = "COMMAND_NOT_SUPPORTED"; - Socks5ConnectionStatus2[Socks5ConnectionStatus2["ADDRESS_TYPE_NOT_SUPPORTED"] = 8] = "ADDRESS_TYPE_NOT_SUPPORTED"; - return Socks5ConnectionStatus2; -})(Socks5ConnectionStatus || {}); - -// src/Connection.ts -var Socks5Connection = class { - constructor(server, socket) { - this.errorHandler = () => { - }; - this.metadata = {}; - this.socket = socket; - this.server = server; - socket.on("error", this.errorHandler); - socket.pause(); - this.handleGreeting(); - } - readBytes(len) { - return new Promise((resolve) => { - let buf = Buffer.allocUnsafe(len); - let offset = 0; - const dataListener = (chunk) => { - const readAmount = Math.min(chunk.length, len - offset); - chunk.copy(buf, offset, 0, readAmount); - offset += readAmount; - if (offset < len) return; - this.socket.removeListener("data", dataListener); - this.socket.push(chunk.subarray(readAmount)); - resolve(buf); - this.socket.pause(); - }; - this.socket.on("data", dataListener); - this.socket.resume(); - }); - } - async handleGreeting() { - const ver = (await this.readBytes(1)).readUInt8(); - if (ver !== 5) return this.socket.destroy(); - const authMethodsAmount = (await this.readBytes(1)).readUInt8(); - if (authMethodsAmount > 128 || authMethodsAmount === 0) return this.socket.destroy(); - const authMethods = await this.readBytes(authMethodsAmount); - const authMethodByteCode = this.server.authHandler ? 2 : 0; - if (!authMethods.includes(authMethodByteCode)) { - this.socket.write(Buffer.from([ - 5, - // Version 5 - Socks5 - 255 - // no acceptable auth modes were offered - ])); - return this.socket.destroy(); - } - this.socket.write(Buffer.from([ - 5, - // Version 5 - Socks5 - authMethodByteCode - // The chosen auth method, 0x00 for no auth, 0x02 for user-pass - ])); - if (this.server.authHandler) this.handleUserPassword(); - else this.handleConnectionRequest(); - } - async handleUserPassword() { - await this.readBytes(1); - const usernameLength = (await this.readBytes(1)).readUint8(); - const username = (await this.readBytes(usernameLength)).toString(); - const passwordLength = (await this.readBytes(1)).readUint8(); - const password = (await this.readBytes(passwordLength)).toString(); - this.username = username; - this.password = password; - let calledBack = false; - const acceptCallback = () => { - if (calledBack) return; - calledBack = true; - this.socket.write(Buffer.from([ - 1, - // User pass auth version - 0 - // Success - ])); - this.handleConnectionRequest(); - }; - const denyCallback = () => { - if (calledBack) return; - calledBack = true; - this.socket.write(Buffer.from([ - 1, - // User pass auth version - 1 - // Failure - ])); - this.socket.destroy(); - }; - const resp = await this.server.authHandler(this, acceptCallback, denyCallback); - if (resp === true) acceptCallback(); - else if (resp === false) denyCallback(); - } - async handleConnectionRequest() { - await this.readBytes(1); - const commandByte = (await this.readBytes(1))[0]; - const command = Socks5ConnectionCommand[commandByte]; - if (!command) return this.socket.destroy(); - this.command = command; - await this.readBytes(1); - const addrType = (await this.readBytes(1)).readUInt8(); - let address = ""; - switch (addrType) { - case 1: - address = (await this.readBytes(4)).join("."); - break; - case 3: - const hostLength = (await this.readBytes(1)).readUInt8(); - address = (await this.readBytes(hostLength)).toString(); - break; - case 4: - const bytes = await this.readBytes(16); - for (let i = 0; i < 16; i++) { - if (i % 2 === 0 && i > 0) address += ":"; - address += `${bytes[i] < 16 ? "0" : ""}${bytes[i].toString(16)}`; - } - break; - default: - this.socket.destroy(); - return; - } - const port = (await this.readBytes(2)).readUInt16BE(); - if (!this.server.supportedCommands.has(command)) { - this.socket.write(Buffer.from([5, 7 /* COMMAND_NOT_SUPPORTED */])); - return this.socket.destroy(); - } - this.destAddress = address; - this.destPort = port; - let calledBack = false; - const acceptCallback = () => { - if (calledBack) return; - calledBack = true; - this.connect(); - }; - if (!this.server.rulesetValidator) return acceptCallback(); - const denyCallback = () => { - if (calledBack) return; - calledBack = true; - this.socket.write(Buffer.from([ - 5, - 2, - // connection not allowed by ruleset - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 0 - ])); - this.socket.destroy(); - }; - const resp = await this.server.rulesetValidator(this, acceptCallback, denyCallback); - if (resp === true) acceptCallback(); - else if (resp === false) denyCallback(); - } - connect() { - this.socket.removeListener("error", this.errorHandler); - this.server.connectionHandler(this, (status) => { - if (Socks5ConnectionStatus[status] === void 0) throw new Error(`"${status}" is not a valid status.`); - this.socket.write(Buffer.from([ - 5, - Socks5ConnectionStatus[status], - 0, - 1, - 0, - 0, - 0, - 0, - 0, - 0 - ])); - if (status !== "REQUEST_GRANTED") { - this.socket.destroy(); - } - }); - this.socket.resume(); - } -}; - -// src/connectionHandler.ts -var import_net = __toESM(require("net")); -function connectionHandler_default(connection, sendStatus) { - if (connection.command !== "connect") return sendStatus("COMMAND_NOT_SUPPORTED"); - connection.socket.on("error", () => { - }); - const stream = import_net.default.createConnection({ - host: connection.destAddress, - port: connection.destPort - }); - stream.setNoDelay(); - let streamOpened = false; - stream.on("error", (err) => { - if (!streamOpened) { - switch (err.code) { - case "EINVAL": - case "ENOENT": - case "ENOTFOUND": - case "ETIMEDOUT": - case "EADDRNOTAVAIL": - case "EHOSTUNREACH": - sendStatus("HOST_UNREACHABLE"); - break; - case "ENETUNREACH": - sendStatus("NETWORK_UNREACHABLE"); - break; - case "ECONNREFUSED": - sendStatus("CONNECTION_REFUSED"); - break; - default: - sendStatus("GENERAL_FAILURE"); - } - } - }); - stream.on("ready", () => { - streamOpened = true; - sendStatus("REQUEST_GRANTED"); - connection.socket.pipe(stream).pipe(connection.socket); - }); - connection.socket.on("close", () => stream.destroy()); - return stream; -} - -// src/Server.ts -var Socks5Server = class { - constructor() { - this.supportedCommands = /* @__PURE__ */ new Set(["connect"]); - this.connectionHandler = connectionHandler_default; - this.server = import_net2.default.createServer((socket) => { - socket.setNoDelay(); - this._handleConnection(socket); - }); - } - listen(...args) { - this.server.listen(...args); - return this; - } - close(callback) { - this.server.close(callback); - return this; - } - setAuthHandler(handler) { - this.authHandler = handler; - return this; - } - disableAuthHandler() { - this.authHandler = void 0; - return this; - } - setRulesetValidator(handler) { - this.rulesetValidator = handler; - return this; - } - disableRulesetValidator() { - this.rulesetValidator = void 0; - return this; - } - setConnectionHandler(handler) { - this.connectionHandler = handler; - return this; - } - useDefaultConnectionHandler() { - this.connectionHandler = connectionHandler_default; - return this; - } - // Not private because someone may want to inject a duplex stream to be handled as a connection - _handleConnection(socket) { - new Socks5Connection(this, socket); - return this; - } -}; - -// src/index.ts -function createServer(opts) { - const server = new Socks5Server(); - if (opts?.auth) server.setAuthHandler((conn) => { - return conn.username === opts.auth.username && conn.password === opts.auth.password; - }); - if (opts?.port) server.listen(opts.port, opts.hostname); - return server; -} -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - Socks5Server, - createServer, - defaultConnectionHandler -}); diff --git a/claude-code-source/node_modules/@protobufjs/aspromise/index.js b/claude-code-source/node_modules/@protobufjs/aspromise/index.js deleted file mode 100644 index b10f8267..00000000 --- a/claude-code-source/node_modules/@protobufjs/aspromise/index.js +++ /dev/null @@ -1,52 +0,0 @@ -"use strict"; -module.exports = asPromise; - -/** - * Callback as used by {@link util.asPromise}. - * @typedef asPromiseCallback - * @type {function} - * @param {Error|null} error Error, if any - * @param {...*} params Additional arguments - * @returns {undefined} - */ - -/** - * Returns a promise from a node-style callback function. - * @memberof util - * @param {asPromiseCallback} fn Function to call - * @param {*} ctx Function context - * @param {...*} params Function arguments - * @returns {Promise<*>} Promisified function - */ -function asPromise(fn, ctx/*, varargs */) { - var params = new Array(arguments.length - 1), - offset = 0, - index = 2, - pending = true; - while (index < arguments.length) - params[offset++] = arguments[index++]; - return new Promise(function executor(resolve, reject) { - params[offset] = function callback(err/*, varargs */) { - if (pending) { - pending = false; - if (err) - reject(err); - else { - var params = new Array(arguments.length - 1), - offset = 0; - while (offset < params.length) - params[offset++] = arguments[offset]; - resolve.apply(null, params); - } - } - }; - try { - fn.apply(ctx || null, params); - } catch (err) { - if (pending) { - pending = false; - reject(err); - } - } - }); -} diff --git a/claude-code-source/node_modules/@protobufjs/base64/index.js b/claude-code-source/node_modules/@protobufjs/base64/index.js deleted file mode 100644 index 26d54433..00000000 --- a/claude-code-source/node_modules/@protobufjs/base64/index.js +++ /dev/null @@ -1,139 +0,0 @@ -"use strict"; - -/** - * A minimal base64 implementation for number arrays. - * @memberof util - * @namespace - */ -var base64 = exports; - -/** - * Calculates the byte length of a base64 encoded string. - * @param {string} string Base64 encoded string - * @returns {number} Byte length - */ -base64.length = function length(string) { - var p = string.length; - if (!p) - return 0; - var n = 0; - while (--p % 4 > 1 && string.charAt(p) === "=") - ++n; - return Math.ceil(string.length * 3) / 4 - n; -}; - -// Base64 encoding table -var b64 = new Array(64); - -// Base64 decoding table -var s64 = new Array(123); - -// 65..90, 97..122, 48..57, 43, 47 -for (var i = 0; i < 64;) - s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; - -/** - * Encodes a buffer to a base64 encoded string. - * @param {Uint8Array} buffer Source buffer - * @param {number} start Source start - * @param {number} end Source end - * @returns {string} Base64 encoded string - */ -base64.encode = function encode(buffer, start, end) { - var parts = null, - chunk = []; - var i = 0, // output index - j = 0, // goto index - t; // temporary - while (start < end) { - var b = buffer[start++]; - switch (j) { - case 0: - chunk[i++] = b64[b >> 2]; - t = (b & 3) << 4; - j = 1; - break; - case 1: - chunk[i++] = b64[t | b >> 4]; - t = (b & 15) << 2; - j = 2; - break; - case 2: - chunk[i++] = b64[t | b >> 6]; - chunk[i++] = b64[b & 63]; - j = 0; - break; - } - if (i > 8191) { - (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); - i = 0; - } - } - if (j) { - chunk[i++] = b64[t]; - chunk[i++] = 61; - if (j === 1) - chunk[i++] = 61; - } - if (parts) { - if (i) - parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); - return parts.join(""); - } - return String.fromCharCode.apply(String, chunk.slice(0, i)); -}; - -var invalidEncoding = "invalid encoding"; - -/** - * Decodes a base64 encoded string to a buffer. - * @param {string} string Source string - * @param {Uint8Array} buffer Destination buffer - * @param {number} offset Destination offset - * @returns {number} Number of bytes written - * @throws {Error} If encoding is invalid - */ -base64.decode = function decode(string, buffer, offset) { - var start = offset; - var j = 0, // goto index - t; // temporary - for (var i = 0; i < string.length;) { - var c = string.charCodeAt(i++); - if (c === 61 && j > 1) - break; - if ((c = s64[c]) === undefined) - throw Error(invalidEncoding); - switch (j) { - case 0: - t = c; - j = 1; - break; - case 1: - buffer[offset++] = t << 2 | (c & 48) >> 4; - t = c; - j = 2; - break; - case 2: - buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; - t = c; - j = 3; - break; - case 3: - buffer[offset++] = (t & 3) << 6 | c; - j = 0; - break; - } - } - if (j === 1) - throw Error(invalidEncoding); - return offset - start; -}; - -/** - * Tests if the specified string appears to be base64 encoded. - * @param {string} string String to test - * @returns {boolean} `true` if probably base64 encoded, otherwise false - */ -base64.test = function test(string) { - return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string); -}; diff --git a/claude-code-source/node_modules/@protobufjs/codegen/index.js b/claude-code-source/node_modules/@protobufjs/codegen/index.js deleted file mode 100644 index de73f80b..00000000 --- a/claude-code-source/node_modules/@protobufjs/codegen/index.js +++ /dev/null @@ -1,99 +0,0 @@ -"use strict"; -module.exports = codegen; - -/** - * Begins generating a function. - * @memberof util - * @param {string[]} functionParams Function parameter names - * @param {string} [functionName] Function name if not anonymous - * @returns {Codegen} Appender that appends code to the function's body - */ -function codegen(functionParams, functionName) { - - /* istanbul ignore if */ - if (typeof functionParams === "string") { - functionName = functionParams; - functionParams = undefined; - } - - var body = []; - - /** - * Appends code to the function's body or finishes generation. - * @typedef Codegen - * @type {function} - * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any - * @param {...*} [formatParams] Format parameters - * @returns {Codegen|Function} Itself or the generated function if finished - * @throws {Error} If format parameter counts do not match - */ - - function Codegen(formatStringOrScope) { - // note that explicit array handling below makes this ~50% faster - - // finish the function - if (typeof formatStringOrScope !== "string") { - var source = toString(); - if (codegen.verbose) - console.log("codegen: " + source); // eslint-disable-line no-console - source = "return " + source; - if (formatStringOrScope) { - var scopeKeys = Object.keys(formatStringOrScope), - scopeParams = new Array(scopeKeys.length + 1), - scopeValues = new Array(scopeKeys.length), - scopeOffset = 0; - while (scopeOffset < scopeKeys.length) { - scopeParams[scopeOffset] = scopeKeys[scopeOffset]; - scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]]; - } - scopeParams[scopeOffset] = source; - return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func - } - return Function(source)(); // eslint-disable-line no-new-func - } - - // otherwise append to body - var formatParams = new Array(arguments.length - 1), - formatOffset = 0; - while (formatOffset < formatParams.length) - formatParams[formatOffset] = arguments[++formatOffset]; - formatOffset = 0; - formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) { - var value = formatParams[formatOffset++]; - switch ($1) { - case "d": case "f": return String(Number(value)); - case "i": return String(Math.floor(value)); - case "j": return JSON.stringify(value); - case "s": return String(value); - } - return "%"; - }); - if (formatOffset !== formatParams.length) - throw Error("parameter count mismatch"); - body.push(formatStringOrScope); - return Codegen; - } - - function toString(functionNameOverride) { - return "function " + (functionNameOverride || functionName || "") + "(" + (functionParams && functionParams.join(",") || "") + "){\n " + body.join("\n ") + "\n}"; - } - - Codegen.toString = toString; - return Codegen; -} - -/** - * Begins generating a function. - * @memberof util - * @function codegen - * @param {string} [functionName] Function name if not anonymous - * @returns {Codegen} Appender that appends code to the function's body - * @variation 2 - */ - -/** - * When set to `true`, codegen will log generated code to console. Useful for debugging. - * @name util.codegen.verbose - * @type {boolean} - */ -codegen.verbose = false; diff --git a/claude-code-source/node_modules/@protobufjs/eventemitter/index.js b/claude-code-source/node_modules/@protobufjs/eventemitter/index.js deleted file mode 100644 index 76ce9385..00000000 --- a/claude-code-source/node_modules/@protobufjs/eventemitter/index.js +++ /dev/null @@ -1,76 +0,0 @@ -"use strict"; -module.exports = EventEmitter; - -/** - * Constructs a new event emitter instance. - * @classdesc A minimal event emitter. - * @memberof util - * @constructor - */ -function EventEmitter() { - - /** - * Registered listeners. - * @type {Object.} - * @private - */ - this._listeners = {}; -} - -/** - * Registers an event listener. - * @param {string} evt Event name - * @param {function} fn Listener - * @param {*} [ctx] Listener context - * @returns {util.EventEmitter} `this` - */ -EventEmitter.prototype.on = function on(evt, fn, ctx) { - (this._listeners[evt] || (this._listeners[evt] = [])).push({ - fn : fn, - ctx : ctx || this - }); - return this; -}; - -/** - * Removes an event listener or any matching listeners if arguments are omitted. - * @param {string} [evt] Event name. Removes all listeners if omitted. - * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted. - * @returns {util.EventEmitter} `this` - */ -EventEmitter.prototype.off = function off(evt, fn) { - if (evt === undefined) - this._listeners = {}; - else { - if (fn === undefined) - this._listeners[evt] = []; - else { - var listeners = this._listeners[evt]; - for (var i = 0; i < listeners.length;) - if (listeners[i].fn === fn) - listeners.splice(i, 1); - else - ++i; - } - } - return this; -}; - -/** - * Emits an event by calling its listeners with the specified arguments. - * @param {string} evt Event name - * @param {...*} args Arguments - * @returns {util.EventEmitter} `this` - */ -EventEmitter.prototype.emit = function emit(evt) { - var listeners = this._listeners[evt]; - if (listeners) { - var args = [], - i = 1; - for (; i < arguments.length;) - args.push(arguments[i++]); - for (i = 0; i < listeners.length;) - listeners[i].fn.apply(listeners[i++].ctx, args); - } - return this; -}; diff --git a/claude-code-source/node_modules/@protobufjs/fetch/index.js b/claude-code-source/node_modules/@protobufjs/fetch/index.js deleted file mode 100644 index f2766f54..00000000 --- a/claude-code-source/node_modules/@protobufjs/fetch/index.js +++ /dev/null @@ -1,115 +0,0 @@ -"use strict"; -module.exports = fetch; - -var asPromise = require("@protobufjs/aspromise"), - inquire = require("@protobufjs/inquire"); - -var fs = inquire("fs"); - -/** - * Node-style callback as used by {@link util.fetch}. - * @typedef FetchCallback - * @type {function} - * @param {?Error} error Error, if any, otherwise `null` - * @param {string} [contents] File contents, if there hasn't been an error - * @returns {undefined} - */ - -/** - * Options as used by {@link util.fetch}. - * @typedef FetchOptions - * @type {Object} - * @property {boolean} [binary=false] Whether expecting a binary response - * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest - */ - -/** - * Fetches the contents of a file. - * @memberof util - * @param {string} filename File path or url - * @param {FetchOptions} options Fetch options - * @param {FetchCallback} callback Callback function - * @returns {undefined} - */ -function fetch(filename, options, callback) { - if (typeof options === "function") { - callback = options; - options = {}; - } else if (!options) - options = {}; - - if (!callback) - return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this - - // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found. - if (!options.xhr && fs && fs.readFile) - return fs.readFile(filename, function fetchReadFileCallback(err, contents) { - return err && typeof XMLHttpRequest !== "undefined" - ? fetch.xhr(filename, options, callback) - : err - ? callback(err) - : callback(null, options.binary ? contents : contents.toString("utf8")); - }); - - // use the XHR version otherwise. - return fetch.xhr(filename, options, callback); -} - -/** - * Fetches the contents of a file. - * @name util.fetch - * @function - * @param {string} path File path or url - * @param {FetchCallback} callback Callback function - * @returns {undefined} - * @variation 2 - */ - -/** - * Fetches the contents of a file. - * @name util.fetch - * @function - * @param {string} path File path or url - * @param {FetchOptions} [options] Fetch options - * @returns {Promise} Promise - * @variation 3 - */ - -/**/ -fetch.xhr = function fetch_xhr(filename, options, callback) { - var xhr = new XMLHttpRequest(); - xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() { - - if (xhr.readyState !== 4) - return undefined; - - // local cors security errors return status 0 / empty string, too. afaik this cannot be - // reliably distinguished from an actually empty file for security reasons. feel free - // to send a pull request if you are aware of a solution. - if (xhr.status !== 0 && xhr.status !== 200) - return callback(Error("status " + xhr.status)); - - // if binary data is expected, make sure that some sort of array is returned, even if - // ArrayBuffers are not supported. the binary string fallback, however, is unsafe. - if (options.binary) { - var buffer = xhr.response; - if (!buffer) { - buffer = []; - for (var i = 0; i < xhr.responseText.length; ++i) - buffer.push(xhr.responseText.charCodeAt(i) & 255); - } - return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer); - } - return callback(null, xhr.responseText); - }; - - if (options.binary) { - // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers - if ("overrideMimeType" in xhr) - xhr.overrideMimeType("text/plain; charset=x-user-defined"); - xhr.responseType = "arraybuffer"; - } - - xhr.open("GET", filename); - xhr.send(); -}; diff --git a/claude-code-source/node_modules/@protobufjs/float/index.js b/claude-code-source/node_modules/@protobufjs/float/index.js deleted file mode 100644 index 706d0963..00000000 --- a/claude-code-source/node_modules/@protobufjs/float/index.js +++ /dev/null @@ -1,335 +0,0 @@ -"use strict"; - -module.exports = factory(factory); - -/** - * Reads / writes floats / doubles from / to buffers. - * @name util.float - * @namespace - */ - -/** - * Writes a 32 bit float to a buffer using little endian byte order. - * @name util.float.writeFloatLE - * @function - * @param {number} val Value to write - * @param {Uint8Array} buf Target buffer - * @param {number} pos Target buffer offset - * @returns {undefined} - */ - -/** - * Writes a 32 bit float to a buffer using big endian byte order. - * @name util.float.writeFloatBE - * @function - * @param {number} val Value to write - * @param {Uint8Array} buf Target buffer - * @param {number} pos Target buffer offset - * @returns {undefined} - */ - -/** - * Reads a 32 bit float from a buffer using little endian byte order. - * @name util.float.readFloatLE - * @function - * @param {Uint8Array} buf Source buffer - * @param {number} pos Source buffer offset - * @returns {number} Value read - */ - -/** - * Reads a 32 bit float from a buffer using big endian byte order. - * @name util.float.readFloatBE - * @function - * @param {Uint8Array} buf Source buffer - * @param {number} pos Source buffer offset - * @returns {number} Value read - */ - -/** - * Writes a 64 bit double to a buffer using little endian byte order. - * @name util.float.writeDoubleLE - * @function - * @param {number} val Value to write - * @param {Uint8Array} buf Target buffer - * @param {number} pos Target buffer offset - * @returns {undefined} - */ - -/** - * Writes a 64 bit double to a buffer using big endian byte order. - * @name util.float.writeDoubleBE - * @function - * @param {number} val Value to write - * @param {Uint8Array} buf Target buffer - * @param {number} pos Target buffer offset - * @returns {undefined} - */ - -/** - * Reads a 64 bit double from a buffer using little endian byte order. - * @name util.float.readDoubleLE - * @function - * @param {Uint8Array} buf Source buffer - * @param {number} pos Source buffer offset - * @returns {number} Value read - */ - -/** - * Reads a 64 bit double from a buffer using big endian byte order. - * @name util.float.readDoubleBE - * @function - * @param {Uint8Array} buf Source buffer - * @param {number} pos Source buffer offset - * @returns {number} Value read - */ - -// Factory function for the purpose of node-based testing in modified global environments -function factory(exports) { - - // float: typed array - if (typeof Float32Array !== "undefined") (function() { - - var f32 = new Float32Array([ -0 ]), - f8b = new Uint8Array(f32.buffer), - le = f8b[3] === 128; - - function writeFloat_f32_cpy(val, buf, pos) { - f32[0] = val; - buf[pos ] = f8b[0]; - buf[pos + 1] = f8b[1]; - buf[pos + 2] = f8b[2]; - buf[pos + 3] = f8b[3]; - } - - function writeFloat_f32_rev(val, buf, pos) { - f32[0] = val; - buf[pos ] = f8b[3]; - buf[pos + 1] = f8b[2]; - buf[pos + 2] = f8b[1]; - buf[pos + 3] = f8b[0]; - } - - /* istanbul ignore next */ - exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; - /* istanbul ignore next */ - exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; - - function readFloat_f32_cpy(buf, pos) { - f8b[0] = buf[pos ]; - f8b[1] = buf[pos + 1]; - f8b[2] = buf[pos + 2]; - f8b[3] = buf[pos + 3]; - return f32[0]; - } - - function readFloat_f32_rev(buf, pos) { - f8b[3] = buf[pos ]; - f8b[2] = buf[pos + 1]; - f8b[1] = buf[pos + 2]; - f8b[0] = buf[pos + 3]; - return f32[0]; - } - - /* istanbul ignore next */ - exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; - /* istanbul ignore next */ - exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; - - // float: ieee754 - })(); else (function() { - - function writeFloat_ieee754(writeUint, val, buf, pos) { - var sign = val < 0 ? 1 : 0; - if (sign) - val = -val; - if (val === 0) - writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos); - else if (isNaN(val)) - writeUint(2143289344, buf, pos); - else if (val > 3.4028234663852886e+38) // +-Infinity - writeUint((sign << 31 | 2139095040) >>> 0, buf, pos); - else if (val < 1.1754943508222875e-38) // denormal - writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos); - else { - var exponent = Math.floor(Math.log(val) / Math.LN2), - mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; - writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); - } - } - - exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); - exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); - - function readFloat_ieee754(readUint, buf, pos) { - var uint = readUint(buf, pos), - sign = (uint >> 31) * 2 + 1, - exponent = uint >>> 23 & 255, - mantissa = uint & 8388607; - return exponent === 255 - ? mantissa - ? NaN - : sign * Infinity - : exponent === 0 // denormal - ? sign * 1.401298464324817e-45 * mantissa - : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); - } - - exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE); - exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE); - - })(); - - // double: typed array - if (typeof Float64Array !== "undefined") (function() { - - var f64 = new Float64Array([-0]), - f8b = new Uint8Array(f64.buffer), - le = f8b[7] === 128; - - function writeDouble_f64_cpy(val, buf, pos) { - f64[0] = val; - buf[pos ] = f8b[0]; - buf[pos + 1] = f8b[1]; - buf[pos + 2] = f8b[2]; - buf[pos + 3] = f8b[3]; - buf[pos + 4] = f8b[4]; - buf[pos + 5] = f8b[5]; - buf[pos + 6] = f8b[6]; - buf[pos + 7] = f8b[7]; - } - - function writeDouble_f64_rev(val, buf, pos) { - f64[0] = val; - buf[pos ] = f8b[7]; - buf[pos + 1] = f8b[6]; - buf[pos + 2] = f8b[5]; - buf[pos + 3] = f8b[4]; - buf[pos + 4] = f8b[3]; - buf[pos + 5] = f8b[2]; - buf[pos + 6] = f8b[1]; - buf[pos + 7] = f8b[0]; - } - - /* istanbul ignore next */ - exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; - /* istanbul ignore next */ - exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; - - function readDouble_f64_cpy(buf, pos) { - f8b[0] = buf[pos ]; - f8b[1] = buf[pos + 1]; - f8b[2] = buf[pos + 2]; - f8b[3] = buf[pos + 3]; - f8b[4] = buf[pos + 4]; - f8b[5] = buf[pos + 5]; - f8b[6] = buf[pos + 6]; - f8b[7] = buf[pos + 7]; - return f64[0]; - } - - function readDouble_f64_rev(buf, pos) { - f8b[7] = buf[pos ]; - f8b[6] = buf[pos + 1]; - f8b[5] = buf[pos + 2]; - f8b[4] = buf[pos + 3]; - f8b[3] = buf[pos + 4]; - f8b[2] = buf[pos + 5]; - f8b[1] = buf[pos + 6]; - f8b[0] = buf[pos + 7]; - return f64[0]; - } - - /* istanbul ignore next */ - exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; - /* istanbul ignore next */ - exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; - - // double: ieee754 - })(); else (function() { - - function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { - var sign = val < 0 ? 1 : 0; - if (sign) - val = -val; - if (val === 0) { - writeUint(0, buf, pos + off0); - writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1); - } else if (isNaN(val)) { - writeUint(0, buf, pos + off0); - writeUint(2146959360, buf, pos + off1); - } else if (val > 1.7976931348623157e+308) { // +-Infinity - writeUint(0, buf, pos + off0); - writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1); - } else { - var mantissa; - if (val < 2.2250738585072014e-308) { // denormal - mantissa = val / 5e-324; - writeUint(mantissa >>> 0, buf, pos + off0); - writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); - } else { - var exponent = Math.floor(Math.log(val) / Math.LN2); - if (exponent === 1024) - exponent = 1023; - mantissa = val * Math.pow(2, -exponent); - writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); - writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); - } - } - } - - exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); - exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); - - function readDouble_ieee754(readUint, off0, off1, buf, pos) { - var lo = readUint(buf, pos + off0), - hi = readUint(buf, pos + off1); - var sign = (hi >> 31) * 2 + 1, - exponent = hi >>> 20 & 2047, - mantissa = 4294967296 * (hi & 1048575) + lo; - return exponent === 2047 - ? mantissa - ? NaN - : sign * Infinity - : exponent === 0 // denormal - ? sign * 5e-324 * mantissa - : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); - } - - exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); - exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); - - })(); - - return exports; -} - -// uint helpers - -function writeUintLE(val, buf, pos) { - buf[pos ] = val & 255; - buf[pos + 1] = val >>> 8 & 255; - buf[pos + 2] = val >>> 16 & 255; - buf[pos + 3] = val >>> 24; -} - -function writeUintBE(val, buf, pos) { - buf[pos ] = val >>> 24; - buf[pos + 1] = val >>> 16 & 255; - buf[pos + 2] = val >>> 8 & 255; - buf[pos + 3] = val & 255; -} - -function readUintLE(buf, pos) { - return (buf[pos ] - | buf[pos + 1] << 8 - | buf[pos + 2] << 16 - | buf[pos + 3] << 24) >>> 0; -} - -function readUintBE(buf, pos) { - return (buf[pos ] << 24 - | buf[pos + 1] << 16 - | buf[pos + 2] << 8 - | buf[pos + 3]) >>> 0; -} diff --git a/claude-code-source/node_modules/@protobufjs/inquire/index.js b/claude-code-source/node_modules/@protobufjs/inquire/index.js deleted file mode 100644 index 0a6d443b..00000000 --- a/claude-code-source/node_modules/@protobufjs/inquire/index.js +++ /dev/null @@ -1,18 +0,0 @@ -"use strict"; -module.exports = inquire; - -/** - * Requires a module only if available. - * @memberof util - * @param {string} moduleName Module to require - * @returns {?Object} Required module if available and not empty, otherwise `null` - */ -function inquire(moduleName) { - try { - // Use string literals so bundlers can statically analyze the requires - var mod = moduleName === "long" ? require("long") : moduleName === "buffer" ? require("buffer") : moduleName === "fs" ? require("fs") : eval("quire".replace(/^/,"re"))(moduleName); - if (mod && (mod.length || Object.keys(mod).length)) - return mod; - } catch (e) {} // eslint-disable-line no-empty - return null; -} diff --git a/claude-code-source/node_modules/@protobufjs/path/index.js b/claude-code-source/node_modules/@protobufjs/path/index.js deleted file mode 100644 index 1ea7b174..00000000 --- a/claude-code-source/node_modules/@protobufjs/path/index.js +++ /dev/null @@ -1,65 +0,0 @@ -"use strict"; - -/** - * A minimal path module to resolve Unix, Windows and URL paths alike. - * @memberof util - * @namespace - */ -var path = exports; - -var isAbsolute = -/** - * Tests if the specified path is absolute. - * @param {string} path Path to test - * @returns {boolean} `true` if path is absolute - */ -path.isAbsolute = function isAbsolute(path) { - return /^(?:\/|\w+:)/.test(path); -}; - -var normalize = -/** - * Normalizes the specified path. - * @param {string} path Path to normalize - * @returns {string} Normalized path - */ -path.normalize = function normalize(path) { - path = path.replace(/\\/g, "/") - .replace(/\/{2,}/g, "/"); - var parts = path.split("/"), - absolute = isAbsolute(path), - prefix = ""; - if (absolute) - prefix = parts.shift() + "/"; - for (var i = 0; i < parts.length;) { - if (parts[i] === "..") { - if (i > 0 && parts[i - 1] !== "..") - parts.splice(--i, 2); - else if (absolute) - parts.splice(i, 1); - else - ++i; - } else if (parts[i] === ".") - parts.splice(i, 1); - else - ++i; - } - return prefix + parts.join("/"); -}; - -/** - * Resolves the specified include path against the specified origin path. - * @param {string} originPath Path to the origin file - * @param {string} includePath Include path relative to origin path - * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized - * @returns {string} Path to the include file - */ -path.resolve = function resolve(originPath, includePath, alreadyNormalized) { - if (!alreadyNormalized) - includePath = normalize(includePath); - if (isAbsolute(includePath)) - return includePath; - if (!alreadyNormalized) - originPath = normalize(originPath); - return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath; -}; diff --git a/claude-code-source/node_modules/@protobufjs/pool/index.js b/claude-code-source/node_modules/@protobufjs/pool/index.js deleted file mode 100644 index 9556f5a4..00000000 --- a/claude-code-source/node_modules/@protobufjs/pool/index.js +++ /dev/null @@ -1,48 +0,0 @@ -"use strict"; -module.exports = pool; - -/** - * An allocator as used by {@link util.pool}. - * @typedef PoolAllocator - * @type {function} - * @param {number} size Buffer size - * @returns {Uint8Array} Buffer - */ - -/** - * A slicer as used by {@link util.pool}. - * @typedef PoolSlicer - * @type {function} - * @param {number} start Start offset - * @param {number} end End offset - * @returns {Uint8Array} Buffer slice - * @this {Uint8Array} - */ - -/** - * A general purpose buffer pool. - * @memberof util - * @function - * @param {PoolAllocator} alloc Allocator - * @param {PoolSlicer} slice Slicer - * @param {number} [size=8192] Slab size - * @returns {PoolAllocator} Pooled allocator - */ -function pool(alloc, slice, size) { - var SIZE = size || 8192; - var MAX = SIZE >>> 1; - var slab = null; - var offset = SIZE; - return function pool_alloc(size) { - if (size < 1 || size > MAX) - return alloc(size); - if (offset + size > SIZE) { - slab = alloc(SIZE); - offset = 0; - } - var buf = slice.call(slab, offset, offset += size); - if (offset & 7) // align to 32 bit - offset = (offset | 7) + 1; - return buf; - }; -} diff --git a/claude-code-source/node_modules/@protobufjs/utf8/index.js b/claude-code-source/node_modules/@protobufjs/utf8/index.js deleted file mode 100644 index e4ff8df9..00000000 --- a/claude-code-source/node_modules/@protobufjs/utf8/index.js +++ /dev/null @@ -1,105 +0,0 @@ -"use strict"; - -/** - * A minimal UTF8 implementation for number arrays. - * @memberof util - * @namespace - */ -var utf8 = exports; - -/** - * Calculates the UTF8 byte length of a string. - * @param {string} string String - * @returns {number} Byte length - */ -utf8.length = function utf8_length(string) { - var len = 0, - c = 0; - for (var i = 0; i < string.length; ++i) { - c = string.charCodeAt(i); - if (c < 128) - len += 1; - else if (c < 2048) - len += 2; - else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) { - ++i; - len += 4; - } else - len += 3; - } - return len; -}; - -/** - * Reads UTF8 bytes as a string. - * @param {Uint8Array} buffer Source buffer - * @param {number} start Source start - * @param {number} end Source end - * @returns {string} String read - */ -utf8.read = function utf8_read(buffer, start, end) { - var len = end - start; - if (len < 1) - return ""; - var parts = null, - chunk = [], - i = 0, // char offset - t; // temporary - while (start < end) { - t = buffer[start++]; - if (t < 128) - chunk[i++] = t; - else if (t > 191 && t < 224) - chunk[i++] = (t & 31) << 6 | buffer[start++] & 63; - else if (t > 239 && t < 365) { - t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000; - chunk[i++] = 0xD800 + (t >> 10); - chunk[i++] = 0xDC00 + (t & 1023); - } else - chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; - if (i > 8191) { - (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); - i = 0; - } - } - if (parts) { - if (i) - parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); - return parts.join(""); - } - return String.fromCharCode.apply(String, chunk.slice(0, i)); -}; - -/** - * Writes a string as UTF8 bytes. - * @param {string} string Source string - * @param {Uint8Array} buffer Destination buffer - * @param {number} offset Destination offset - * @returns {number} Bytes written - */ -utf8.write = function utf8_write(string, buffer, offset) { - var start = offset, - c1, // character 1 - c2; // character 2 - for (var i = 0; i < string.length; ++i) { - c1 = string.charCodeAt(i); - if (c1 < 128) { - buffer[offset++] = c1; - } else if (c1 < 2048) { - buffer[offset++] = c1 >> 6 | 192; - buffer[offset++] = c1 & 63 | 128; - } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) { - c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF); - ++i; - buffer[offset++] = c1 >> 18 | 240; - buffer[offset++] = c1 >> 12 & 63 | 128; - buffer[offset++] = c1 >> 6 & 63 | 128; - buffer[offset++] = c1 & 63 | 128; - } else { - buffer[offset++] = c1 >> 12 | 224; - buffer[offset++] = c1 >> 6 & 63 | 128; - buffer[offset++] = c1 & 63 | 128; - } - } - return offset - start; -}; diff --git a/claude-code-source/node_modules/@smithy/config-resolver/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/config-resolver/dist-cjs/index.js deleted file mode 100644 index 4703cff7..00000000 --- a/claude-code-source/node_modules/@smithy/config-resolver/dist-cjs/index.js +++ /dev/null @@ -1,186 +0,0 @@ -'use strict'; - -var utilConfigProvider = require('@smithy/util-config-provider'); -var utilMiddleware = require('@smithy/util-middleware'); -var utilEndpoints = require('@smithy/util-endpoints'); - -const ENV_USE_DUALSTACK_ENDPOINT = "AWS_USE_DUALSTACK_ENDPOINT"; -const CONFIG_USE_DUALSTACK_ENDPOINT = "use_dualstack_endpoint"; -const DEFAULT_USE_DUALSTACK_ENDPOINT = false; -const NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => utilConfigProvider.booleanSelector(env, ENV_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.ENV), - configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, CONFIG_USE_DUALSTACK_ENDPOINT, utilConfigProvider.SelectorType.CONFIG), - default: false, -}; - -const ENV_USE_FIPS_ENDPOINT = "AWS_USE_FIPS_ENDPOINT"; -const CONFIG_USE_FIPS_ENDPOINT = "use_fips_endpoint"; -const DEFAULT_USE_FIPS_ENDPOINT = false; -const NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => utilConfigProvider.booleanSelector(env, ENV_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.ENV), - configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, CONFIG_USE_FIPS_ENDPOINT, utilConfigProvider.SelectorType.CONFIG), - default: false, -}; - -const resolveCustomEndpointsConfig = (input) => { - const { tls, endpoint, urlParser, useDualstackEndpoint } = input; - return Object.assign(input, { - tls: tls ?? true, - endpoint: utilMiddleware.normalizeProvider(typeof endpoint === "string" ? urlParser(endpoint) : endpoint), - isCustomEndpoint: true, - useDualstackEndpoint: utilMiddleware.normalizeProvider(useDualstackEndpoint ?? false), - }); -}; - -const getEndpointFromRegion = async (input) => { - const { tls = true } = input; - const region = await input.region(); - const dnsHostRegex = new RegExp(/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])$/); - if (!dnsHostRegex.test(region)) { - throw new Error("Invalid region in client config"); - } - const useDualstackEndpoint = await input.useDualstackEndpoint(); - const useFipsEndpoint = await input.useFipsEndpoint(); - const { hostname } = (await input.regionInfoProvider(region, { useDualstackEndpoint, useFipsEndpoint })) ?? {}; - if (!hostname) { - throw new Error("Cannot resolve hostname from client config"); - } - return input.urlParser(`${tls ? "https:" : "http:"}//${hostname}`); -}; - -const resolveEndpointsConfig = (input) => { - const useDualstackEndpoint = utilMiddleware.normalizeProvider(input.useDualstackEndpoint ?? false); - const { endpoint, useFipsEndpoint, urlParser, tls } = input; - return Object.assign(input, { - tls: tls ?? true, - endpoint: endpoint - ? utilMiddleware.normalizeProvider(typeof endpoint === "string" ? urlParser(endpoint) : endpoint) - : () => getEndpointFromRegion({ ...input, useDualstackEndpoint, useFipsEndpoint }), - isCustomEndpoint: !!endpoint, - useDualstackEndpoint, - }); -}; - -const REGION_ENV_NAME = "AWS_REGION"; -const REGION_INI_NAME = "region"; -const NODE_REGION_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => env[REGION_ENV_NAME], - configFileSelector: (profile) => profile[REGION_INI_NAME], - default: () => { - throw new Error("Region is missing"); - }, -}; -const NODE_REGION_CONFIG_FILE_OPTIONS = { - preferredFile: "credentials", -}; - -const validRegions = new Set(); -const checkRegion = (region, check = utilEndpoints.isValidHostLabel) => { - if (!validRegions.has(region) && !check(region)) { - if (region === "*") { - console.warn(`@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.`); - } - else { - throw new Error(`Region not accepted: region="${region}" is not a valid hostname component.`); - } - } - else { - validRegions.add(region); - } -}; - -const isFipsRegion = (region) => typeof region === "string" && (region.startsWith("fips-") || region.endsWith("-fips")); - -const getRealRegion = (region) => isFipsRegion(region) - ? ["fips-aws-global", "aws-fips"].includes(region) - ? "us-east-1" - : region.replace(/fips-(dkr-|prod-)?|-fips/, "") - : region; - -const resolveRegionConfig = (input) => { - const { region, useFipsEndpoint } = input; - if (!region) { - throw new Error("Region is missing"); - } - return Object.assign(input, { - region: async () => { - const providedRegion = typeof region === "function" ? await region() : region; - const realRegion = getRealRegion(providedRegion); - checkRegion(realRegion); - return realRegion; - }, - useFipsEndpoint: async () => { - const providedRegion = typeof region === "string" ? region : await region(); - if (isFipsRegion(providedRegion)) { - return true; - } - return typeof useFipsEndpoint !== "function" ? Promise.resolve(!!useFipsEndpoint) : useFipsEndpoint(); - }, - }); -}; - -const getHostnameFromVariants = (variants = [], { useFipsEndpoint, useDualstackEndpoint }) => variants.find(({ tags }) => useFipsEndpoint === tags.includes("fips") && useDualstackEndpoint === tags.includes("dualstack"))?.hostname; - -const getResolvedHostname = (resolvedRegion, { regionHostname, partitionHostname }) => regionHostname - ? regionHostname - : partitionHostname - ? partitionHostname.replace("{region}", resolvedRegion) - : undefined; - -const getResolvedPartition = (region, { partitionHash }) => Object.keys(partitionHash || {}).find((key) => partitionHash[key].regions.includes(region)) ?? "aws"; - -const getResolvedSigningRegion = (hostname, { signingRegion, regionRegex, useFipsEndpoint }) => { - if (signingRegion) { - return signingRegion; - } - else if (useFipsEndpoint) { - const regionRegexJs = regionRegex.replace("\\\\", "\\").replace(/^\^/g, "\\.").replace(/\$$/g, "\\."); - const regionRegexmatchArray = hostname.match(regionRegexJs); - if (regionRegexmatchArray) { - return regionRegexmatchArray[0].slice(1, -1); - } - } -}; - -const getRegionInfo = (region, { useFipsEndpoint = false, useDualstackEndpoint = false, signingService, regionHash, partitionHash, }) => { - const partition = getResolvedPartition(region, { partitionHash }); - const resolvedRegion = region in regionHash ? region : partitionHash[partition]?.endpoint ?? region; - const hostnameOptions = { useFipsEndpoint, useDualstackEndpoint }; - const regionHostname = getHostnameFromVariants(regionHash[resolvedRegion]?.variants, hostnameOptions); - const partitionHostname = getHostnameFromVariants(partitionHash[partition]?.variants, hostnameOptions); - const hostname = getResolvedHostname(resolvedRegion, { regionHostname, partitionHostname }); - if (hostname === undefined) { - throw new Error(`Endpoint resolution failed for: ${{ resolvedRegion, useFipsEndpoint, useDualstackEndpoint }}`); - } - const signingRegion = getResolvedSigningRegion(hostname, { - signingRegion: regionHash[resolvedRegion]?.signingRegion, - regionRegex: partitionHash[partition].regionRegex, - useFipsEndpoint, - }); - return { - partition, - signingService, - hostname, - ...(signingRegion && { signingRegion }), - ...(regionHash[resolvedRegion]?.signingService && { - signingService: regionHash[resolvedRegion].signingService, - }), - }; -}; - -exports.CONFIG_USE_DUALSTACK_ENDPOINT = CONFIG_USE_DUALSTACK_ENDPOINT; -exports.CONFIG_USE_FIPS_ENDPOINT = CONFIG_USE_FIPS_ENDPOINT; -exports.DEFAULT_USE_DUALSTACK_ENDPOINT = DEFAULT_USE_DUALSTACK_ENDPOINT; -exports.DEFAULT_USE_FIPS_ENDPOINT = DEFAULT_USE_FIPS_ENDPOINT; -exports.ENV_USE_DUALSTACK_ENDPOINT = ENV_USE_DUALSTACK_ENDPOINT; -exports.ENV_USE_FIPS_ENDPOINT = ENV_USE_FIPS_ENDPOINT; -exports.NODE_REGION_CONFIG_FILE_OPTIONS = NODE_REGION_CONFIG_FILE_OPTIONS; -exports.NODE_REGION_CONFIG_OPTIONS = NODE_REGION_CONFIG_OPTIONS; -exports.NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS = NODE_USE_DUALSTACK_ENDPOINT_CONFIG_OPTIONS; -exports.NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS = NODE_USE_FIPS_ENDPOINT_CONFIG_OPTIONS; -exports.REGION_ENV_NAME = REGION_ENV_NAME; -exports.REGION_INI_NAME = REGION_INI_NAME; -exports.getRegionInfo = getRegionInfo; -exports.resolveCustomEndpointsConfig = resolveCustomEndpointsConfig; -exports.resolveEndpointsConfig = resolveEndpointsConfig; -exports.resolveRegionConfig = resolveRegionConfig; diff --git a/claude-code-source/node_modules/@smithy/core/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/core/dist-cjs/index.js deleted file mode 100644 index 86a61447..00000000 --- a/claude-code-source/node_modules/@smithy/core/dist-cjs/index.js +++ /dev/null @@ -1,349 +0,0 @@ -'use strict'; - -var types = require('@smithy/types'); -var utilMiddleware = require('@smithy/util-middleware'); -var middlewareSerde = require('@smithy/middleware-serde'); -var protocolHttp = require('@smithy/protocol-http'); -var protocols = require('@smithy/core/protocols'); - -const getSmithyContext = (context) => context[types.SMITHY_CONTEXT_KEY] || (context[types.SMITHY_CONTEXT_KEY] = {}); - -const resolveAuthOptions = (candidateAuthOptions, authSchemePreference) => { - if (!authSchemePreference || authSchemePreference.length === 0) { - return candidateAuthOptions; - } - const preferredAuthOptions = []; - for (const preferredSchemeName of authSchemePreference) { - for (const candidateAuthOption of candidateAuthOptions) { - const candidateAuthSchemeName = candidateAuthOption.schemeId.split("#")[1]; - if (candidateAuthSchemeName === preferredSchemeName) { - preferredAuthOptions.push(candidateAuthOption); - } - } - } - for (const candidateAuthOption of candidateAuthOptions) { - if (!preferredAuthOptions.find(({ schemeId }) => schemeId === candidateAuthOption.schemeId)) { - preferredAuthOptions.push(candidateAuthOption); - } - } - return preferredAuthOptions; -}; - -function convertHttpAuthSchemesToMap(httpAuthSchemes) { - const map = new Map(); - for (const scheme of httpAuthSchemes) { - map.set(scheme.schemeId, scheme); - } - return map; -} -const httpAuthSchemeMiddleware = (config, mwOptions) => (next, context) => async (args) => { - const options = config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config, context, args.input)); - const authSchemePreference = config.authSchemePreference ? await config.authSchemePreference() : []; - const resolvedOptions = resolveAuthOptions(options, authSchemePreference); - const authSchemes = convertHttpAuthSchemesToMap(config.httpAuthSchemes); - const smithyContext = utilMiddleware.getSmithyContext(context); - const failureReasons = []; - for (const option of resolvedOptions) { - const scheme = authSchemes.get(option.schemeId); - if (!scheme) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`); - continue; - } - const identityProvider = scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config)); - if (!identityProvider) { - failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`); - continue; - } - const { identityProperties = {}, signingProperties = {} } = option.propertiesExtractor?.(config, context) || {}; - option.identityProperties = Object.assign(option.identityProperties || {}, identityProperties); - option.signingProperties = Object.assign(option.signingProperties || {}, signingProperties); - smithyContext.selectedHttpAuthScheme = { - httpAuthOption: option, - identity: await identityProvider(option.identityProperties), - signer: scheme.signer, - }; - break; - } - if (!smithyContext.selectedHttpAuthScheme) { - throw new Error(failureReasons.join("\n")); - } - return next(args); -}; - -const httpAuthSchemeEndpointRuleSetMiddlewareOptions = { - step: "serialize", - tags: ["HTTP_AUTH_SCHEME"], - name: "httpAuthSchemeMiddleware", - override: true, - relation: "before", - toMiddleware: "endpointV2Middleware", -}; -const getHttpAuthSchemeEndpointRuleSetPlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider, }) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider, - }), httpAuthSchemeEndpointRuleSetMiddlewareOptions); - }, -}); - -const httpAuthSchemeMiddlewareOptions = { - step: "serialize", - tags: ["HTTP_AUTH_SCHEME"], - name: "httpAuthSchemeMiddleware", - override: true, - relation: "before", - toMiddleware: middlewareSerde.serializerMiddlewareOption.name, -}; -const getHttpAuthSchemePlugin = (config, { httpAuthSchemeParametersProvider, identityProviderConfigProvider, }) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo(httpAuthSchemeMiddleware(config, { - httpAuthSchemeParametersProvider, - identityProviderConfigProvider, - }), httpAuthSchemeMiddlewareOptions); - }, -}); - -const defaultErrorHandler = (signingProperties) => (error) => { - throw error; -}; -const defaultSuccessHandler = (httpResponse, signingProperties) => { }; -const httpSigningMiddleware = (config) => (next, context) => async (args) => { - if (!protocolHttp.HttpRequest.isInstance(args.request)) { - return next(args); - } - const smithyContext = utilMiddleware.getSmithyContext(context); - const scheme = smithyContext.selectedHttpAuthScheme; - if (!scheme) { - throw new Error(`No HttpAuthScheme was selected: unable to sign request`); - } - const { httpAuthOption: { signingProperties = {} }, identity, signer, } = scheme; - const output = await next({ - ...args, - request: await signer.sign(args.request, identity, signingProperties), - }).catch((signer.errorHandler || defaultErrorHandler)(signingProperties)); - (signer.successHandler || defaultSuccessHandler)(output.response, signingProperties); - return output; -}; - -const httpSigningMiddlewareOptions = { - step: "finalizeRequest", - tags: ["HTTP_SIGNING"], - name: "httpSigningMiddleware", - aliases: ["apiKeyMiddleware", "tokenMiddleware", "awsAuthMiddleware"], - override: true, - relation: "after", - toMiddleware: "retryMiddleware", -}; -const getHttpSigningPlugin = (config) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo(httpSigningMiddleware(), httpSigningMiddlewareOptions); - }, -}); - -const normalizeProvider = (input) => { - if (typeof input === "function") - return input; - const promisified = Promise.resolve(input); - return () => promisified; -}; - -const makePagedClientRequest = async (CommandCtor, client, input, withCommand = (_) => _, ...args) => { - let command = new CommandCtor(input); - command = withCommand(command) ?? command; - return await client.send(command, ...args); -}; -function createPaginator(ClientCtor, CommandCtor, inputTokenName, outputTokenName, pageSizeTokenName) { - return async function* paginateOperation(config, input, ...additionalArguments) { - const _input = input; - let token = config.startingToken ?? _input[inputTokenName]; - let hasNext = true; - let page; - while (hasNext) { - _input[inputTokenName] = token; - if (pageSizeTokenName) { - _input[pageSizeTokenName] = _input[pageSizeTokenName] ?? config.pageSize; - } - if (config.client instanceof ClientCtor) { - page = await makePagedClientRequest(CommandCtor, config.client, input, config.withCommand, ...additionalArguments); - } - else { - throw new Error(`Invalid client, expected instance of ${ClientCtor.name}`); - } - yield page; - const prevToken = token; - token = get(page, outputTokenName); - hasNext = !!(token && (!config.stopOnSameToken || token !== prevToken)); - } - return undefined; - }; -} -const get = (fromObject, path) => { - let cursor = fromObject; - const pathComponents = path.split("."); - for (const step of pathComponents) { - if (!cursor || typeof cursor !== "object") { - return undefined; - } - cursor = cursor[step]; - } - return cursor; -}; - -function setFeature(context, feature, value) { - if (!context.__smithy_context) { - context.__smithy_context = { - features: {}, - }; - } - else if (!context.__smithy_context.features) { - context.__smithy_context.features = {}; - } - context.__smithy_context.features[feature] = value; -} - -class DefaultIdentityProviderConfig { - authSchemes = new Map(); - constructor(config) { - for (const [key, value] of Object.entries(config)) { - if (value !== undefined) { - this.authSchemes.set(key, value); - } - } - } - getIdentityProvider(schemeId) { - return this.authSchemes.get(schemeId); - } -} - -class HttpApiKeyAuthSigner { - async sign(httpRequest, identity, signingProperties) { - if (!signingProperties) { - throw new Error("request could not be signed with `apiKey` since the `name` and `in` signer properties are missing"); - } - if (!signingProperties.name) { - throw new Error("request could not be signed with `apiKey` since the `name` signer property is missing"); - } - if (!signingProperties.in) { - throw new Error("request could not be signed with `apiKey` since the `in` signer property is missing"); - } - if (!identity.apiKey) { - throw new Error("request could not be signed with `apiKey` since the `apiKey` is not defined"); - } - const clonedRequest = protocolHttp.HttpRequest.clone(httpRequest); - if (signingProperties.in === types.HttpApiKeyAuthLocation.QUERY) { - clonedRequest.query[signingProperties.name] = identity.apiKey; - } - else if (signingProperties.in === types.HttpApiKeyAuthLocation.HEADER) { - clonedRequest.headers[signingProperties.name] = signingProperties.scheme - ? `${signingProperties.scheme} ${identity.apiKey}` - : identity.apiKey; - } - else { - throw new Error("request can only be signed with `apiKey` locations `query` or `header`, " + - "but found: `" + - signingProperties.in + - "`"); - } - return clonedRequest; - } -} - -class HttpBearerAuthSigner { - async sign(httpRequest, identity, signingProperties) { - const clonedRequest = protocolHttp.HttpRequest.clone(httpRequest); - if (!identity.token) { - throw new Error("request could not be signed with `token` since the `token` is not defined"); - } - clonedRequest.headers["Authorization"] = `Bearer ${identity.token}`; - return clonedRequest; - } -} - -class NoAuthSigner { - async sign(httpRequest, identity, signingProperties) { - return httpRequest; - } -} - -const createIsIdentityExpiredFunction = (expirationMs) => function isIdentityExpired(identity) { - return doesIdentityRequireRefresh(identity) && identity.expiration.getTime() - Date.now() < expirationMs; -}; -const EXPIRATION_MS = 300_000; -const isIdentityExpired = createIsIdentityExpiredFunction(EXPIRATION_MS); -const doesIdentityRequireRefresh = (identity) => identity.expiration !== undefined; -const memoizeIdentityProvider = (provider, isExpired, requiresRefresh) => { - if (provider === undefined) { - return undefined; - } - const normalizedProvider = typeof provider !== "function" ? async () => Promise.resolve(provider) : provider; - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = async (options) => { - if (!pending) { - pending = normalizedProvider(options); - } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } - finally { - pending = undefined; - } - return resolved; - }; - if (isExpired === undefined) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(options); - } - return resolved; - }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(options); - } - if (isConstant) { - return resolved; - } - if (!requiresRefresh(resolved)) { - isConstant = true; - return resolved; - } - if (isExpired(resolved)) { - await coalesceProvider(options); - return resolved; - } - return resolved; - }; -}; - -Object.defineProperty(exports, "requestBuilder", { - enumerable: true, - get: function () { return protocols.requestBuilder; } -}); -exports.DefaultIdentityProviderConfig = DefaultIdentityProviderConfig; -exports.EXPIRATION_MS = EXPIRATION_MS; -exports.HttpApiKeyAuthSigner = HttpApiKeyAuthSigner; -exports.HttpBearerAuthSigner = HttpBearerAuthSigner; -exports.NoAuthSigner = NoAuthSigner; -exports.createIsIdentityExpiredFunction = createIsIdentityExpiredFunction; -exports.createPaginator = createPaginator; -exports.doesIdentityRequireRefresh = doesIdentityRequireRefresh; -exports.getHttpAuthSchemeEndpointRuleSetPlugin = getHttpAuthSchemeEndpointRuleSetPlugin; -exports.getHttpAuthSchemePlugin = getHttpAuthSchemePlugin; -exports.getHttpSigningPlugin = getHttpSigningPlugin; -exports.getSmithyContext = getSmithyContext; -exports.httpAuthSchemeEndpointRuleSetMiddlewareOptions = httpAuthSchemeEndpointRuleSetMiddlewareOptions; -exports.httpAuthSchemeMiddleware = httpAuthSchemeMiddleware; -exports.httpAuthSchemeMiddlewareOptions = httpAuthSchemeMiddlewareOptions; -exports.httpSigningMiddleware = httpSigningMiddleware; -exports.httpSigningMiddlewareOptions = httpSigningMiddlewareOptions; -exports.isIdentityExpired = isIdentityExpired; -exports.memoizeIdentityProvider = memoizeIdentityProvider; -exports.normalizeProvider = normalizeProvider; -exports.setFeature = setFeature; diff --git a/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/cbor/index.js b/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/cbor/index.js deleted file mode 100644 index 9fc40e38..00000000 --- a/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/cbor/index.js +++ /dev/null @@ -1,1050 +0,0 @@ -'use strict'; - -var serde = require('@smithy/core/serde'); -var utilUtf8 = require('@smithy/util-utf8'); -var protocols = require('@smithy/core/protocols'); -var protocolHttp = require('@smithy/protocol-http'); -var utilBodyLengthBrowser = require('@smithy/util-body-length-browser'); -var schema = require('@smithy/core/schema'); -var utilMiddleware = require('@smithy/util-middleware'); -var utilBase64 = require('@smithy/util-base64'); - -const majorUint64 = 0; -const majorNegativeInt64 = 1; -const majorUnstructuredByteString = 2; -const majorUtf8String = 3; -const majorList = 4; -const majorMap = 5; -const majorTag = 6; -const majorSpecial = 7; -const specialFalse = 20; -const specialTrue = 21; -const specialNull = 22; -const specialUndefined = 23; -const extendedOneByte = 24; -const extendedFloat16 = 25; -const extendedFloat32 = 26; -const extendedFloat64 = 27; -const minorIndefinite = 31; -function alloc(size) { - return typeof Buffer !== "undefined" ? Buffer.alloc(size) : new Uint8Array(size); -} -const tagSymbol = Symbol("@smithy/core/cbor::tagSymbol"); -function tag(data) { - data[tagSymbol] = true; - return data; -} - -const USE_TEXT_DECODER = typeof TextDecoder !== "undefined"; -const USE_BUFFER$1 = typeof Buffer !== "undefined"; -let payload = alloc(0); -let dataView$1 = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); -const textDecoder = USE_TEXT_DECODER ? new TextDecoder() : null; -let _offset = 0; -function setPayload(bytes) { - payload = bytes; - dataView$1 = new DataView(payload.buffer, payload.byteOffset, payload.byteLength); -} -function decode(at, to) { - if (at >= to) { - throw new Error("unexpected end of (decode) payload."); - } - const major = (payload[at] & 0b1110_0000) >> 5; - const minor = payload[at] & 0b0001_1111; - switch (major) { - case majorUint64: - case majorNegativeInt64: - case majorTag: - let unsignedInt; - let offset; - if (minor < 24) { - unsignedInt = minor; - offset = 1; - } - else { - switch (minor) { - case extendedOneByte: - case extendedFloat16: - case extendedFloat32: - case extendedFloat64: - const countLength = minorValueToArgumentLength[minor]; - const countOffset = (countLength + 1); - offset = countOffset; - if (to - at < countOffset) { - throw new Error(`countLength ${countLength} greater than remaining buf len.`); - } - const countIndex = at + 1; - if (countLength === 1) { - unsignedInt = payload[countIndex]; - } - else if (countLength === 2) { - unsignedInt = dataView$1.getUint16(countIndex); - } - else if (countLength === 4) { - unsignedInt = dataView$1.getUint32(countIndex); - } - else { - unsignedInt = dataView$1.getBigUint64(countIndex); - } - break; - default: - throw new Error(`unexpected minor value ${minor}.`); - } - } - if (major === majorUint64) { - _offset = offset; - return castBigInt(unsignedInt); - } - else if (major === majorNegativeInt64) { - let negativeInt; - if (typeof unsignedInt === "bigint") { - negativeInt = BigInt(-1) - unsignedInt; - } - else { - negativeInt = -1 - unsignedInt; - } - _offset = offset; - return castBigInt(negativeInt); - } - else { - if (minor === 2 || minor === 3) { - const length = decodeCount(at + offset, to); - let b = BigInt(0); - const start = at + offset + _offset; - for (let i = start; i < start + length; ++i) { - b = (b << BigInt(8)) | BigInt(payload[i]); - } - _offset = offset + _offset + length; - return minor === 3 ? -b - BigInt(1) : b; - } - else if (minor === 4) { - const decimalFraction = decode(at + offset, to); - const [exponent, mantissa] = decimalFraction; - const normalizer = mantissa < 0 ? -1 : 1; - const mantissaStr = "0".repeat(Math.abs(exponent) + 1) + String(BigInt(normalizer) * BigInt(mantissa)); - let numericString; - const sign = mantissa < 0 ? "-" : ""; - numericString = - exponent === 0 - ? mantissaStr - : mantissaStr.slice(0, mantissaStr.length + exponent) + "." + mantissaStr.slice(exponent); - numericString = numericString.replace(/^0+/g, ""); - if (numericString === "") { - numericString = "0"; - } - if (numericString[0] === ".") { - numericString = "0" + numericString; - } - numericString = sign + numericString; - _offset = offset + _offset; - return serde.nv(numericString); - } - else { - const value = decode(at + offset, to); - const valueOffset = _offset; - _offset = offset + valueOffset; - return tag({ tag: castBigInt(unsignedInt), value }); - } - } - case majorUtf8String: - case majorMap: - case majorList: - case majorUnstructuredByteString: - if (minor === minorIndefinite) { - switch (major) { - case majorUtf8String: - return decodeUtf8StringIndefinite(at, to); - case majorMap: - return decodeMapIndefinite(at, to); - case majorList: - return decodeListIndefinite(at, to); - case majorUnstructuredByteString: - return decodeUnstructuredByteStringIndefinite(at, to); - } - } - else { - switch (major) { - case majorUtf8String: - return decodeUtf8String(at, to); - case majorMap: - return decodeMap(at, to); - case majorList: - return decodeList(at, to); - case majorUnstructuredByteString: - return decodeUnstructuredByteString(at, to); - } - } - default: - return decodeSpecial(at, to); - } -} -function bytesToUtf8(bytes, at, to) { - if (USE_BUFFER$1 && bytes.constructor?.name === "Buffer") { - return bytes.toString("utf-8", at, to); - } - if (textDecoder) { - return textDecoder.decode(bytes.subarray(at, to)); - } - return utilUtf8.toUtf8(bytes.subarray(at, to)); -} -function demote(bigInteger) { - const num = Number(bigInteger); - if (num < Number.MIN_SAFE_INTEGER || Number.MAX_SAFE_INTEGER < num) { - console.warn(new Error(`@smithy/core/cbor - truncating BigInt(${bigInteger}) to ${num} with loss of precision.`)); - } - return num; -} -const minorValueToArgumentLength = { - [extendedOneByte]: 1, - [extendedFloat16]: 2, - [extendedFloat32]: 4, - [extendedFloat64]: 8, -}; -function bytesToFloat16(a, b) { - const sign = a >> 7; - const exponent = (a & 0b0111_1100) >> 2; - const fraction = ((a & 0b0000_0011) << 8) | b; - const scalar = sign === 0 ? 1 : -1; - let exponentComponent; - let summation; - if (exponent === 0b00000) { - if (fraction === 0b00000_00000) { - return 0; - } - else { - exponentComponent = Math.pow(2, 1 - 15); - summation = 0; - } - } - else if (exponent === 0b11111) { - if (fraction === 0b00000_00000) { - return scalar * Infinity; - } - else { - return NaN; - } - } - else { - exponentComponent = Math.pow(2, exponent - 15); - summation = 1; - } - summation += fraction / 1024; - return scalar * (exponentComponent * summation); -} -function decodeCount(at, to) { - const minor = payload[at] & 0b0001_1111; - if (minor < 24) { - _offset = 1; - return minor; - } - if (minor === extendedOneByte || - minor === extendedFloat16 || - minor === extendedFloat32 || - minor === extendedFloat64) { - const countLength = minorValueToArgumentLength[minor]; - _offset = (countLength + 1); - if (to - at < _offset) { - throw new Error(`countLength ${countLength} greater than remaining buf len.`); - } - const countIndex = at + 1; - if (countLength === 1) { - return payload[countIndex]; - } - else if (countLength === 2) { - return dataView$1.getUint16(countIndex); - } - else if (countLength === 4) { - return dataView$1.getUint32(countIndex); - } - return demote(dataView$1.getBigUint64(countIndex)); - } - throw new Error(`unexpected minor value ${minor}.`); -} -function decodeUtf8String(at, to) { - const length = decodeCount(at, to); - const offset = _offset; - at += offset; - if (to - at < length) { - throw new Error(`string len ${length} greater than remaining buf len.`); - } - const value = bytesToUtf8(payload, at, at + length); - _offset = offset + length; - return value; -} -function decodeUtf8StringIndefinite(at, to) { - at += 1; - const vector = []; - for (const base = at; at < to;) { - if (payload[at] === 0b1111_1111) { - const data = alloc(vector.length); - data.set(vector, 0); - _offset = at - base + 2; - return bytesToUtf8(data, 0, data.length); - } - const major = (payload[at] & 0b1110_0000) >> 5; - const minor = payload[at] & 0b0001_1111; - if (major !== majorUtf8String) { - throw new Error(`unexpected major type ${major} in indefinite string.`); - } - if (minor === minorIndefinite) { - throw new Error("nested indefinite string."); - } - const bytes = decodeUnstructuredByteString(at, to); - const length = _offset; - at += length; - for (let i = 0; i < bytes.length; ++i) { - vector.push(bytes[i]); - } - } - throw new Error("expected break marker."); -} -function decodeUnstructuredByteString(at, to) { - const length = decodeCount(at, to); - const offset = _offset; - at += offset; - if (to - at < length) { - throw new Error(`unstructured byte string len ${length} greater than remaining buf len.`); - } - const value = payload.subarray(at, at + length); - _offset = offset + length; - return value; -} -function decodeUnstructuredByteStringIndefinite(at, to) { - at += 1; - const vector = []; - for (const base = at; at < to;) { - if (payload[at] === 0b1111_1111) { - const data = alloc(vector.length); - data.set(vector, 0); - _offset = at - base + 2; - return data; - } - const major = (payload[at] & 0b1110_0000) >> 5; - const minor = payload[at] & 0b0001_1111; - if (major !== majorUnstructuredByteString) { - throw new Error(`unexpected major type ${major} in indefinite string.`); - } - if (minor === minorIndefinite) { - throw new Error("nested indefinite string."); - } - const bytes = decodeUnstructuredByteString(at, to); - const length = _offset; - at += length; - for (let i = 0; i < bytes.length; ++i) { - vector.push(bytes[i]); - } - } - throw new Error("expected break marker."); -} -function decodeList(at, to) { - const listDataLength = decodeCount(at, to); - const offset = _offset; - at += offset; - const base = at; - const list = Array(listDataLength); - for (let i = 0; i < listDataLength; ++i) { - const item = decode(at, to); - const itemOffset = _offset; - list[i] = item; - at += itemOffset; - } - _offset = offset + (at - base); - return list; -} -function decodeListIndefinite(at, to) { - at += 1; - const list = []; - for (const base = at; at < to;) { - if (payload[at] === 0b1111_1111) { - _offset = at - base + 2; - return list; - } - const item = decode(at, to); - const n = _offset; - at += n; - list.push(item); - } - throw new Error("expected break marker."); -} -function decodeMap(at, to) { - const mapDataLength = decodeCount(at, to); - const offset = _offset; - at += offset; - const base = at; - const map = {}; - for (let i = 0; i < mapDataLength; ++i) { - if (at >= to) { - throw new Error("unexpected end of map payload."); - } - const major = (payload[at] & 0b1110_0000) >> 5; - if (major !== majorUtf8String) { - throw new Error(`unexpected major type ${major} for map key at index ${at}.`); - } - const key = decode(at, to); - at += _offset; - const value = decode(at, to); - at += _offset; - map[key] = value; - } - _offset = offset + (at - base); - return map; -} -function decodeMapIndefinite(at, to) { - at += 1; - const base = at; - const map = {}; - for (; at < to;) { - if (at >= to) { - throw new Error("unexpected end of map payload."); - } - if (payload[at] === 0b1111_1111) { - _offset = at - base + 2; - return map; - } - const major = (payload[at] & 0b1110_0000) >> 5; - if (major !== majorUtf8String) { - throw new Error(`unexpected major type ${major} for map key.`); - } - const key = decode(at, to); - at += _offset; - const value = decode(at, to); - at += _offset; - map[key] = value; - } - throw new Error("expected break marker."); -} -function decodeSpecial(at, to) { - const minor = payload[at] & 0b0001_1111; - switch (minor) { - case specialTrue: - case specialFalse: - _offset = 1; - return minor === specialTrue; - case specialNull: - _offset = 1; - return null; - case specialUndefined: - _offset = 1; - return null; - case extendedFloat16: - if (to - at < 3) { - throw new Error("incomplete float16 at end of buf."); - } - _offset = 3; - return bytesToFloat16(payload[at + 1], payload[at + 2]); - case extendedFloat32: - if (to - at < 5) { - throw new Error("incomplete float32 at end of buf."); - } - _offset = 5; - return dataView$1.getFloat32(at + 1); - case extendedFloat64: - if (to - at < 9) { - throw new Error("incomplete float64 at end of buf."); - } - _offset = 9; - return dataView$1.getFloat64(at + 1); - default: - throw new Error(`unexpected minor value ${minor}.`); - } -} -function castBigInt(bigInt) { - if (typeof bigInt === "number") { - return bigInt; - } - const num = Number(bigInt); - if (Number.MIN_SAFE_INTEGER <= num && num <= Number.MAX_SAFE_INTEGER) { - return num; - } - return bigInt; -} - -const USE_BUFFER = typeof Buffer !== "undefined"; -const initialSize = 2048; -let data = alloc(initialSize); -let dataView = new DataView(data.buffer, data.byteOffset, data.byteLength); -let cursor = 0; -function ensureSpace(bytes) { - const remaining = data.byteLength - cursor; - if (remaining < bytes) { - if (cursor < 16_000_000) { - resize(Math.max(data.byteLength * 4, data.byteLength + bytes)); - } - else { - resize(data.byteLength + bytes + 16_000_000); - } - } -} -function toUint8Array() { - const out = alloc(cursor); - out.set(data.subarray(0, cursor), 0); - cursor = 0; - return out; -} -function resize(size) { - const old = data; - data = alloc(size); - if (old) { - if (old.copy) { - old.copy(data, 0, 0, old.byteLength); - } - else { - data.set(old, 0); - } - } - dataView = new DataView(data.buffer, data.byteOffset, data.byteLength); -} -function encodeHeader(major, value) { - if (value < 24) { - data[cursor++] = (major << 5) | value; - } - else if (value < 1 << 8) { - data[cursor++] = (major << 5) | 24; - data[cursor++] = value; - } - else if (value < 1 << 16) { - data[cursor++] = (major << 5) | extendedFloat16; - dataView.setUint16(cursor, value); - cursor += 2; - } - else if (value < 2 ** 32) { - data[cursor++] = (major << 5) | extendedFloat32; - dataView.setUint32(cursor, value); - cursor += 4; - } - else { - data[cursor++] = (major << 5) | extendedFloat64; - dataView.setBigUint64(cursor, typeof value === "bigint" ? value : BigInt(value)); - cursor += 8; - } -} -function encode(_input) { - const encodeStack = [_input]; - while (encodeStack.length) { - const input = encodeStack.pop(); - ensureSpace(typeof input === "string" ? input.length * 4 : 64); - if (typeof input === "string") { - if (USE_BUFFER) { - encodeHeader(majorUtf8String, Buffer.byteLength(input)); - cursor += data.write(input, cursor); - } - else { - const bytes = utilUtf8.fromUtf8(input); - encodeHeader(majorUtf8String, bytes.byteLength); - data.set(bytes, cursor); - cursor += bytes.byteLength; - } - continue; - } - else if (typeof input === "number") { - if (Number.isInteger(input)) { - const nonNegative = input >= 0; - const major = nonNegative ? majorUint64 : majorNegativeInt64; - const value = nonNegative ? input : -input - 1; - if (value < 24) { - data[cursor++] = (major << 5) | value; - } - else if (value < 256) { - data[cursor++] = (major << 5) | 24; - data[cursor++] = value; - } - else if (value < 65536) { - data[cursor++] = (major << 5) | extendedFloat16; - data[cursor++] = value >> 8; - data[cursor++] = value; - } - else if (value < 4294967296) { - data[cursor++] = (major << 5) | extendedFloat32; - dataView.setUint32(cursor, value); - cursor += 4; - } - else { - data[cursor++] = (major << 5) | extendedFloat64; - dataView.setBigUint64(cursor, BigInt(value)); - cursor += 8; - } - continue; - } - data[cursor++] = (majorSpecial << 5) | extendedFloat64; - dataView.setFloat64(cursor, input); - cursor += 8; - continue; - } - else if (typeof input === "bigint") { - const nonNegative = input >= 0; - const major = nonNegative ? majorUint64 : majorNegativeInt64; - const value = nonNegative ? input : -input - BigInt(1); - const n = Number(value); - if (n < 24) { - data[cursor++] = (major << 5) | n; - } - else if (n < 256) { - data[cursor++] = (major << 5) | 24; - data[cursor++] = n; - } - else if (n < 65536) { - data[cursor++] = (major << 5) | extendedFloat16; - data[cursor++] = n >> 8; - data[cursor++] = n & 0b1111_1111; - } - else if (n < 4294967296) { - data[cursor++] = (major << 5) | extendedFloat32; - dataView.setUint32(cursor, n); - cursor += 4; - } - else if (value < BigInt("18446744073709551616")) { - data[cursor++] = (major << 5) | extendedFloat64; - dataView.setBigUint64(cursor, value); - cursor += 8; - } - else { - const binaryBigInt = value.toString(2); - const bigIntBytes = new Uint8Array(Math.ceil(binaryBigInt.length / 8)); - let b = value; - let i = 0; - while (bigIntBytes.byteLength - ++i >= 0) { - bigIntBytes[bigIntBytes.byteLength - i] = Number(b & BigInt(255)); - b >>= BigInt(8); - } - ensureSpace(bigIntBytes.byteLength * 2); - data[cursor++] = nonNegative ? 0b110_00010 : 0b110_00011; - if (USE_BUFFER) { - encodeHeader(majorUnstructuredByteString, Buffer.byteLength(bigIntBytes)); - } - else { - encodeHeader(majorUnstructuredByteString, bigIntBytes.byteLength); - } - data.set(bigIntBytes, cursor); - cursor += bigIntBytes.byteLength; - } - continue; - } - else if (input === null) { - data[cursor++] = (majorSpecial << 5) | specialNull; - continue; - } - else if (typeof input === "boolean") { - data[cursor++] = (majorSpecial << 5) | (input ? specialTrue : specialFalse); - continue; - } - else if (typeof input === "undefined") { - throw new Error("@smithy/core/cbor: client may not serialize undefined value."); - } - else if (Array.isArray(input)) { - for (let i = input.length - 1; i >= 0; --i) { - encodeStack.push(input[i]); - } - encodeHeader(majorList, input.length); - continue; - } - else if (typeof input.byteLength === "number") { - ensureSpace(input.length * 2); - encodeHeader(majorUnstructuredByteString, input.length); - data.set(input, cursor); - cursor += input.byteLength; - continue; - } - else if (typeof input === "object") { - if (input instanceof serde.NumericValue) { - const decimalIndex = input.string.indexOf("."); - const exponent = decimalIndex === -1 ? 0 : decimalIndex - input.string.length + 1; - const mantissa = BigInt(input.string.replace(".", "")); - data[cursor++] = 0b110_00100; - encodeStack.push(mantissa); - encodeStack.push(exponent); - encodeHeader(majorList, 2); - continue; - } - if (input[tagSymbol]) { - if ("tag" in input && "value" in input) { - encodeStack.push(input.value); - encodeHeader(majorTag, input.tag); - continue; - } - else { - throw new Error("tag encountered with missing fields, need 'tag' and 'value', found: " + JSON.stringify(input)); - } - } - const keys = Object.keys(input); - for (let i = keys.length - 1; i >= 0; --i) { - const key = keys[i]; - encodeStack.push(input[key]); - encodeStack.push(key); - } - encodeHeader(majorMap, keys.length); - continue; - } - throw new Error(`data type ${input?.constructor?.name ?? typeof input} not compatible for encoding.`); - } -} - -const cbor = { - deserialize(payload) { - setPayload(payload); - return decode(0, payload.length); - }, - serialize(input) { - try { - encode(input); - return toUint8Array(); - } - catch (e) { - toUint8Array(); - throw e; - } - }, - resizeEncodingBuffer(size) { - resize(size); - }, -}; - -const parseCborBody = (streamBody, context) => { - return protocols.collectBody(streamBody, context).then(async (bytes) => { - if (bytes.length) { - try { - return cbor.deserialize(bytes); - } - catch (e) { - Object.defineProperty(e, "$responseBodyText", { - value: context.utf8Encoder(bytes), - }); - throw e; - } - } - return {}; - }); -}; -const dateToTag = (date) => { - return tag({ - tag: 1, - value: date.getTime() / 1000, - }); -}; -const parseCborErrorBody = async (errorBody, context) => { - const value = await parseCborBody(errorBody, context); - value.message = value.message ?? value.Message; - return value; -}; -const loadSmithyRpcV2CborErrorCode = (output, data) => { - const sanitizeErrorCode = (rawValue) => { - let cleanValue = rawValue; - if (typeof cleanValue === "number") { - cleanValue = cleanValue.toString(); - } - if (cleanValue.indexOf(",") >= 0) { - cleanValue = cleanValue.split(",")[0]; - } - if (cleanValue.indexOf(":") >= 0) { - cleanValue = cleanValue.split(":")[0]; - } - if (cleanValue.indexOf("#") >= 0) { - cleanValue = cleanValue.split("#")[1]; - } - return cleanValue; - }; - if (data["__type"] !== undefined) { - return sanitizeErrorCode(data["__type"]); - } - const codeKey = Object.keys(data).find((key) => key.toLowerCase() === "code"); - if (codeKey && data[codeKey] !== undefined) { - return sanitizeErrorCode(data[codeKey]); - } -}; -const checkCborResponse = (response) => { - if (String(response.headers["smithy-protocol"]).toLowerCase() !== "rpc-v2-cbor") { - throw new Error("Malformed RPCv2 CBOR response, status: " + response.statusCode); - } -}; -const buildHttpRpcRequest = async (context, headers, path, resolvedHostname, body) => { - const { hostname, protocol = "https", port, path: basePath } = await context.endpoint(); - const contents = { - protocol, - hostname, - port, - method: "POST", - path: basePath.endsWith("/") ? basePath.slice(0, -1) + path : basePath + path, - headers: { - ...headers, - }, - }; - if (resolvedHostname !== undefined) { - contents.hostname = resolvedHostname; - } - if (body !== undefined) { - contents.body = body; - try { - contents.headers["content-length"] = String(utilBodyLengthBrowser.calculateBodyLength(body)); - } - catch (e) { } - } - return new protocolHttp.HttpRequest(contents); -}; - -class CborCodec extends protocols.SerdeContext { - createSerializer() { - const serializer = new CborShapeSerializer(); - serializer.setSerdeContext(this.serdeContext); - return serializer; - } - createDeserializer() { - const deserializer = new CborShapeDeserializer(); - deserializer.setSerdeContext(this.serdeContext); - return deserializer; - } -} -class CborShapeSerializer extends protocols.SerdeContext { - value; - write(schema, value) { - this.value = this.serialize(schema, value); - } - serialize(schema$1, source) { - const ns = schema.NormalizedSchema.of(schema$1); - if (source == null) { - if (ns.isIdempotencyToken()) { - return serde.generateIdempotencyToken(); - } - return source; - } - if (ns.isBlobSchema()) { - if (typeof source === "string") { - return (this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(source); - } - return source; - } - if (ns.isTimestampSchema()) { - if (typeof source === "number" || typeof source === "bigint") { - return dateToTag(new Date((Number(source) / 1000) | 0)); - } - return dateToTag(source); - } - if (typeof source === "function" || typeof source === "object") { - const sourceObject = source; - if (ns.isListSchema() && Array.isArray(sourceObject)) { - const sparse = !!ns.getMergedTraits().sparse; - const newArray = []; - let i = 0; - for (const item of sourceObject) { - const value = this.serialize(ns.getValueSchema(), item); - if (value != null || sparse) { - newArray[i++] = value; - } - } - return newArray; - } - if (sourceObject instanceof Date) { - return dateToTag(sourceObject); - } - const newObject = {}; - if (ns.isMapSchema()) { - const sparse = !!ns.getMergedTraits().sparse; - for (const key of Object.keys(sourceObject)) { - const value = this.serialize(ns.getValueSchema(), sourceObject[key]); - if (value != null || sparse) { - newObject[key] = value; - } - } - } - else if (ns.isStructSchema()) { - for (const [key, memberSchema] of ns.structIterator()) { - const value = this.serialize(memberSchema, sourceObject[key]); - if (value != null) { - newObject[key] = value; - } - } - } - else if (ns.isDocumentSchema()) { - for (const key of Object.keys(sourceObject)) { - newObject[key] = this.serialize(ns.getValueSchema(), sourceObject[key]); - } - } - return newObject; - } - return source; - } - flush() { - const buffer = cbor.serialize(this.value); - this.value = undefined; - return buffer; - } -} -class CborShapeDeserializer extends protocols.SerdeContext { - read(schema, bytes) { - const data = cbor.deserialize(bytes); - return this.readValue(schema, data); - } - readValue(_schema, value) { - const ns = schema.NormalizedSchema.of(_schema); - if (ns.isTimestampSchema() && typeof value === "number") { - return serde._parseEpochTimestamp(value); - } - if (ns.isBlobSchema()) { - if (typeof value === "string") { - return (this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(value); - } - return value; - } - if (typeof value === "undefined" || - typeof value === "boolean" || - typeof value === "number" || - typeof value === "string" || - typeof value === "bigint" || - typeof value === "symbol") { - return value; - } - else if (typeof value === "function" || typeof value === "object") { - if (value === null) { - return null; - } - if ("byteLength" in value) { - return value; - } - if (value instanceof Date) { - return value; - } - if (ns.isDocumentSchema()) { - return value; - } - if (ns.isListSchema()) { - const newArray = []; - const memberSchema = ns.getValueSchema(); - const sparse = !!ns.getMergedTraits().sparse; - for (const item of value) { - const itemValue = this.readValue(memberSchema, item); - if (itemValue != null || sparse) { - newArray.push(itemValue); - } - } - return newArray; - } - const newObject = {}; - if (ns.isMapSchema()) { - const sparse = !!ns.getMergedTraits().sparse; - const targetSchema = ns.getValueSchema(); - for (const key of Object.keys(value)) { - const itemValue = this.readValue(targetSchema, value[key]); - if (itemValue != null || sparse) { - newObject[key] = itemValue; - } - } - } - else if (ns.isStructSchema()) { - for (const [key, memberSchema] of ns.structIterator()) { - const v = this.readValue(memberSchema, value[key]); - if (v != null) { - newObject[key] = v; - } - } - } - return newObject; - } - else { - return value; - } - } -} - -class SmithyRpcV2CborProtocol extends protocols.RpcProtocol { - codec = new CborCodec(); - serializer = this.codec.createSerializer(); - deserializer = this.codec.createDeserializer(); - constructor({ defaultNamespace }) { - super({ defaultNamespace }); - } - getShapeId() { - return "smithy.protocols#rpcv2Cbor"; - } - getPayloadCodec() { - return this.codec; - } - async serializeRequest(operationSchema, input, context) { - const request = await super.serializeRequest(operationSchema, input, context); - Object.assign(request.headers, { - "content-type": this.getDefaultContentType(), - "smithy-protocol": "rpc-v2-cbor", - accept: this.getDefaultContentType(), - }); - if (schema.deref(operationSchema.input) === "unit") { - delete request.body; - delete request.headers["content-type"]; - } - else { - if (!request.body) { - this.serializer.write(15, {}); - request.body = this.serializer.flush(); - } - try { - request.headers["content-length"] = String(request.body.byteLength); - } - catch (e) { } - } - const { service, operation } = utilMiddleware.getSmithyContext(context); - const path = `/service/${service}/operation/${operation}`; - if (request.path.endsWith("/")) { - request.path += path.slice(1); - } - else { - request.path += path; - } - return request; - } - async deserializeResponse(operationSchema, context, response) { - return super.deserializeResponse(operationSchema, context, response); - } - async handleError(operationSchema, context, response, dataObject, metadata) { - const errorName = loadSmithyRpcV2CborErrorCode(response, dataObject) ?? "Unknown"; - let namespace = this.options.defaultNamespace; - if (errorName.includes("#")) { - [namespace] = errorName.split("#"); - } - const errorMetadata = { - $metadata: metadata, - $fault: response.statusCode <= 500 ? "client" : "server", - }; - const registry = schema.TypeRegistry.for(namespace); - let errorSchema; - try { - errorSchema = registry.getSchema(errorName); - } - catch (e) { - if (dataObject.Message) { - dataObject.message = dataObject.Message; - } - const synthetic = schema.TypeRegistry.for("smithy.ts.sdk.synthetic." + namespace); - const baseExceptionSchema = synthetic.getBaseException(); - if (baseExceptionSchema) { - const ErrorCtor = synthetic.getErrorCtor(baseExceptionSchema); - throw Object.assign(new ErrorCtor({ name: errorName }), errorMetadata, dataObject); - } - throw Object.assign(new Error(errorName), errorMetadata, dataObject); - } - const ns = schema.NormalizedSchema.of(errorSchema); - const ErrorCtor = registry.getErrorCtor(errorSchema); - const message = dataObject.message ?? dataObject.Message ?? "Unknown"; - const exception = new ErrorCtor(message); - const output = {}; - for (const [name, member] of ns.structIterator()) { - output[name] = this.deserializer.readValue(member, dataObject[name]); - } - throw Object.assign(exception, errorMetadata, { - $fault: ns.getMergedTraits().error, - message, - }, output); - } - getDefaultContentType() { - return "application/cbor"; - } -} - -exports.CborCodec = CborCodec; -exports.CborShapeDeserializer = CborShapeDeserializer; -exports.CborShapeSerializer = CborShapeSerializer; -exports.SmithyRpcV2CborProtocol = SmithyRpcV2CborProtocol; -exports.buildHttpRpcRequest = buildHttpRpcRequest; -exports.cbor = cbor; -exports.checkCborResponse = checkCborResponse; -exports.dateToTag = dateToTag; -exports.loadSmithyRpcV2CborErrorCode = loadSmithyRpcV2CborErrorCode; -exports.parseCborBody = parseCborBody; -exports.parseCborErrorBody = parseCborErrorBody; -exports.tag = tag; -exports.tagSymbol = tagSymbol; diff --git a/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/event-streams/index.js b/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/event-streams/index.js deleted file mode 100644 index 163917b9..00000000 --- a/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/event-streams/index.js +++ /dev/null @@ -1,252 +0,0 @@ -'use strict'; - -var utilUtf8 = require('@smithy/util-utf8'); - -class EventStreamSerde { - marshaller; - serializer; - deserializer; - serdeContext; - defaultContentType; - constructor({ marshaller, serializer, deserializer, serdeContext, defaultContentType, }) { - this.marshaller = marshaller; - this.serializer = serializer; - this.deserializer = deserializer; - this.serdeContext = serdeContext; - this.defaultContentType = defaultContentType; - } - async serializeEventStream({ eventStream, requestSchema, initialRequest, }) { - const marshaller = this.marshaller; - const eventStreamMember = requestSchema.getEventStreamMember(); - const unionSchema = requestSchema.getMemberSchema(eventStreamMember); - const serializer = this.serializer; - const defaultContentType = this.defaultContentType; - const initialRequestMarker = Symbol("initialRequestMarker"); - const eventStreamIterable = { - async *[Symbol.asyncIterator]() { - if (initialRequest) { - const headers = { - ":event-type": { type: "string", value: "initial-request" }, - ":message-type": { type: "string", value: "event" }, - ":content-type": { type: "string", value: defaultContentType }, - }; - serializer.write(requestSchema, initialRequest); - const body = serializer.flush(); - yield { - [initialRequestMarker]: true, - headers, - body, - }; - } - for await (const page of eventStream) { - yield page; - } - }, - }; - return marshaller.serialize(eventStreamIterable, (event) => { - if (event[initialRequestMarker]) { - return { - headers: event.headers, - body: event.body, - }; - } - const unionMember = Object.keys(event).find((key) => { - return key !== "__type"; - }) ?? ""; - const { additionalHeaders, body, eventType, explicitPayloadContentType } = this.writeEventBody(unionMember, unionSchema, event); - const headers = { - ":event-type": { type: "string", value: eventType }, - ":message-type": { type: "string", value: "event" }, - ":content-type": { type: "string", value: explicitPayloadContentType ?? defaultContentType }, - ...additionalHeaders, - }; - return { - headers, - body, - }; - }); - } - async deserializeEventStream({ response, responseSchema, initialResponseContainer, }) { - const marshaller = this.marshaller; - const eventStreamMember = responseSchema.getEventStreamMember(); - const unionSchema = responseSchema.getMemberSchema(eventStreamMember); - const memberSchemas = unionSchema.getMemberSchemas(); - const initialResponseMarker = Symbol("initialResponseMarker"); - const asyncIterable = marshaller.deserialize(response.body, async (event) => { - const unionMember = Object.keys(event).find((key) => { - return key !== "__type"; - }) ?? ""; - const body = event[unionMember].body; - if (unionMember === "initial-response") { - const dataObject = await this.deserializer.read(responseSchema, body); - delete dataObject[eventStreamMember]; - return { - [initialResponseMarker]: true, - ...dataObject, - }; - } - else if (unionMember in memberSchemas) { - const eventStreamSchema = memberSchemas[unionMember]; - if (eventStreamSchema.isStructSchema()) { - const out = {}; - let hasBindings = false; - for (const [name, member] of eventStreamSchema.structIterator()) { - const { eventHeader, eventPayload } = member.getMergedTraits(); - hasBindings = hasBindings || Boolean(eventHeader || eventPayload); - if (eventPayload) { - if (member.isBlobSchema()) { - out[name] = body; - } - else if (member.isStringSchema()) { - out[name] = (this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8)(body); - } - else if (member.isStructSchema()) { - out[name] = await this.deserializer.read(member, body); - } - } - else if (eventHeader) { - const value = event[unionMember].headers[name]?.value; - if (value != null) { - if (member.isNumericSchema()) { - if (value && typeof value === "object" && "bytes" in value) { - out[name] = BigInt(value.toString()); - } - else { - out[name] = Number(value); - } - } - else { - out[name] = value; - } - } - } - } - if (hasBindings) { - return { - [unionMember]: out, - }; - } - } - return { - [unionMember]: await this.deserializer.read(eventStreamSchema, body), - }; - } - else { - return { - $unknown: event, - }; - } - }); - const asyncIterator = asyncIterable[Symbol.asyncIterator](); - const firstEvent = await asyncIterator.next(); - if (firstEvent.done) { - return asyncIterable; - } - if (firstEvent.value?.[initialResponseMarker]) { - if (!responseSchema) { - throw new Error("@smithy::core/protocols - initial-response event encountered in event stream but no response schema given."); - } - for (const [key, value] of Object.entries(firstEvent.value)) { - initialResponseContainer[key] = value; - } - } - return { - async *[Symbol.asyncIterator]() { - if (!firstEvent?.value?.[initialResponseMarker]) { - yield firstEvent.value; - } - while (true) { - const { done, value } = await asyncIterator.next(); - if (done) { - break; - } - yield value; - } - }, - }; - } - writeEventBody(unionMember, unionSchema, event) { - const serializer = this.serializer; - let eventType = unionMember; - let explicitPayloadMember = null; - let explicitPayloadContentType; - const isKnownSchema = (() => { - const struct = unionSchema.getSchema(); - return struct[4].includes(unionMember); - })(); - const additionalHeaders = {}; - if (!isKnownSchema) { - const [type, value] = event[unionMember]; - eventType = type; - serializer.write(15, value); - } - else { - const eventSchema = unionSchema.getMemberSchema(unionMember); - if (eventSchema.isStructSchema()) { - for (const [memberName, memberSchema] of eventSchema.structIterator()) { - const { eventHeader, eventPayload } = memberSchema.getMergedTraits(); - if (eventPayload) { - explicitPayloadMember = memberName; - break; - } - else if (eventHeader) { - const value = event[unionMember][memberName]; - let type = "binary"; - if (memberSchema.isNumericSchema()) { - if ((-2) ** 31 <= value && value <= 2 ** 31 - 1) { - type = "integer"; - } - else { - type = "long"; - } - } - else if (memberSchema.isTimestampSchema()) { - type = "timestamp"; - } - else if (memberSchema.isStringSchema()) { - type = "string"; - } - else if (memberSchema.isBooleanSchema()) { - type = "boolean"; - } - if (value != null) { - additionalHeaders[memberName] = { - type, - value, - }; - delete event[unionMember][memberName]; - } - } - } - if (explicitPayloadMember !== null) { - const payloadSchema = eventSchema.getMemberSchema(explicitPayloadMember); - if (payloadSchema.isBlobSchema()) { - explicitPayloadContentType = "application/octet-stream"; - } - else if (payloadSchema.isStringSchema()) { - explicitPayloadContentType = "text/plain"; - } - serializer.write(payloadSchema, event[unionMember][explicitPayloadMember]); - } - else { - serializer.write(eventSchema, event[unionMember]); - } - } - else { - throw new Error("@smithy/core/event-streams - non-struct member not supported in event stream union."); - } - } - const messageSerialization = serializer.flush(); - const body = typeof messageSerialization === "string" - ? (this.serdeContext?.utf8Decoder ?? utilUtf8.fromUtf8)(messageSerialization) - : messageSerialization; - return { - body, - eventType, - explicitPayloadContentType, - additionalHeaders, - }; - } -} - -exports.EventStreamSerde = EventStreamSerde; diff --git a/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/protocols/index.js b/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/protocols/index.js deleted file mode 100644 index cb367dd7..00000000 --- a/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/protocols/index.js +++ /dev/null @@ -1,839 +0,0 @@ -'use strict'; - -var utilStream = require('@smithy/util-stream'); -var schema = require('@smithy/core/schema'); -var serde = require('@smithy/core/serde'); -var protocolHttp = require('@smithy/protocol-http'); -var utilBase64 = require('@smithy/util-base64'); -var utilUtf8 = require('@smithy/util-utf8'); - -const collectBody = async (streamBody = new Uint8Array(), context) => { - if (streamBody instanceof Uint8Array) { - return utilStream.Uint8ArrayBlobAdapter.mutate(streamBody); - } - if (!streamBody) { - return utilStream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); - } - const fromContext = context.streamCollector(streamBody); - return utilStream.Uint8ArrayBlobAdapter.mutate(await fromContext); -}; - -function extendedEncodeURIComponent(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} - -class SerdeContext { - serdeContext; - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - } -} - -class HttpProtocol extends SerdeContext { - options; - constructor(options) { - super(); - this.options = options; - } - getRequestType() { - return protocolHttp.HttpRequest; - } - getResponseType() { - return protocolHttp.HttpResponse; - } - setSerdeContext(serdeContext) { - this.serdeContext = serdeContext; - this.serializer.setSerdeContext(serdeContext); - this.deserializer.setSerdeContext(serdeContext); - if (this.getPayloadCodec()) { - this.getPayloadCodec().setSerdeContext(serdeContext); - } - } - updateServiceEndpoint(request, endpoint) { - if ("url" in endpoint) { - request.protocol = endpoint.url.protocol; - request.hostname = endpoint.url.hostname; - request.port = endpoint.url.port ? Number(endpoint.url.port) : undefined; - request.path = endpoint.url.pathname; - request.fragment = endpoint.url.hash || void 0; - request.username = endpoint.url.username || void 0; - request.password = endpoint.url.password || void 0; - if (!request.query) { - request.query = {}; - } - for (const [k, v] of endpoint.url.searchParams.entries()) { - request.query[k] = v; - } - return request; - } - else { - request.protocol = endpoint.protocol; - request.hostname = endpoint.hostname; - request.port = endpoint.port ? Number(endpoint.port) : undefined; - request.path = endpoint.path; - request.query = { - ...endpoint.query, - }; - return request; - } - } - setHostPrefix(request, operationSchema, input) { - const inputNs = schema.NormalizedSchema.of(operationSchema.input); - const opTraits = schema.translateTraits(operationSchema.traits ?? {}); - if (opTraits.endpoint) { - let hostPrefix = opTraits.endpoint?.[0]; - if (typeof hostPrefix === "string") { - const hostLabelInputs = [...inputNs.structIterator()].filter(([, member]) => member.getMergedTraits().hostLabel); - for (const [name] of hostLabelInputs) { - const replacement = input[name]; - if (typeof replacement !== "string") { - throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`); - } - hostPrefix = hostPrefix.replace(`{${name}}`, replacement); - } - request.hostname = hostPrefix + request.hostname; - } - } - } - deserializeMetadata(output) { - return { - 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"], - }; - } - async serializeEventStream({ eventStream, requestSchema, initialRequest, }) { - const eventStreamSerde = await this.loadEventStreamCapability(); - return eventStreamSerde.serializeEventStream({ - eventStream, - requestSchema, - initialRequest, - }); - } - async deserializeEventStream({ response, responseSchema, initialResponseContainer, }) { - const eventStreamSerde = await this.loadEventStreamCapability(); - return eventStreamSerde.deserializeEventStream({ - response, - responseSchema, - initialResponseContainer, - }); - } - async loadEventStreamCapability() { - const { EventStreamSerde } = await import('@smithy/core/event-streams'); - return new EventStreamSerde({ - marshaller: this.getEventStreamMarshaller(), - serializer: this.serializer, - deserializer: this.deserializer, - serdeContext: this.serdeContext, - defaultContentType: this.getDefaultContentType(), - }); - } - getDefaultContentType() { - throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`); - } - async deserializeHttpMessage(schema, context, response, arg4, arg5) { - return []; - } - getEventStreamMarshaller() { - const context = this.serdeContext; - if (!context.eventStreamMarshaller) { - throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext."); - } - return context.eventStreamMarshaller; - } -} - -class HttpBindingProtocol extends HttpProtocol { - async serializeRequest(operationSchema, _input, context) { - const input = { - ...(_input ?? {}), - }; - const serializer = this.serializer; - const query = {}; - const headers = {}; - const endpoint = await context.endpoint(); - const ns = schema.NormalizedSchema.of(operationSchema?.input); - const schema$1 = ns.getSchema(); - let hasNonHttpBindingMember = false; - let payload; - const request = new protocolHttp.HttpRequest({ - protocol: "", - hostname: "", - port: undefined, - path: "", - fragment: undefined, - query: query, - headers: headers, - body: undefined, - }); - if (endpoint) { - this.updateServiceEndpoint(request, endpoint); - this.setHostPrefix(request, operationSchema, input); - const opTraits = schema.translateTraits(operationSchema.traits); - if (opTraits.http) { - request.method = opTraits.http[0]; - const [path, search] = opTraits.http[1].split("?"); - if (request.path == "/") { - request.path = path; - } - else { - request.path += path; - } - const traitSearchParams = new URLSearchParams(search ?? ""); - Object.assign(query, Object.fromEntries(traitSearchParams)); - } - } - for (const [memberName, memberNs] of ns.structIterator()) { - const memberTraits = memberNs.getMergedTraits() ?? {}; - const inputMemberValue = input[memberName]; - if (inputMemberValue == null && !memberNs.isIdempotencyToken()) { - continue; - } - if (memberTraits.httpPayload) { - const isStreaming = memberNs.isStreaming(); - if (isStreaming) { - const isEventStream = memberNs.isStructSchema(); - if (isEventStream) { - if (input[memberName]) { - payload = await this.serializeEventStream({ - eventStream: input[memberName], - requestSchema: ns, - }); - } - } - else { - payload = inputMemberValue; - } - } - else { - serializer.write(memberNs, inputMemberValue); - payload = serializer.flush(); - } - delete input[memberName]; - } - else if (memberTraits.httpLabel) { - serializer.write(memberNs, inputMemberValue); - const replacement = serializer.flush(); - if (request.path.includes(`{${memberName}+}`)) { - request.path = request.path.replace(`{${memberName}+}`, replacement.split("/").map(extendedEncodeURIComponent).join("/")); - } - else if (request.path.includes(`{${memberName}}`)) { - request.path = request.path.replace(`{${memberName}}`, extendedEncodeURIComponent(replacement)); - } - delete input[memberName]; - } - else if (memberTraits.httpHeader) { - serializer.write(memberNs, inputMemberValue); - headers[memberTraits.httpHeader.toLowerCase()] = String(serializer.flush()); - delete input[memberName]; - } - else if (typeof memberTraits.httpPrefixHeaders === "string") { - for (const [key, val] of Object.entries(inputMemberValue)) { - const amalgam = memberTraits.httpPrefixHeaders + key; - serializer.write([memberNs.getValueSchema(), { httpHeader: amalgam }], val); - headers[amalgam.toLowerCase()] = serializer.flush(); - } - delete input[memberName]; - } - else if (memberTraits.httpQuery || memberTraits.httpQueryParams) { - this.serializeQuery(memberNs, inputMemberValue, query); - delete input[memberName]; - } - else { - hasNonHttpBindingMember = true; - } - } - if (hasNonHttpBindingMember && input) { - serializer.write(schema$1, input); - payload = serializer.flush(); - } - request.headers = headers; - request.query = query; - request.body = payload; - return request; - } - serializeQuery(ns, data, query) { - const serializer = this.serializer; - const traits = ns.getMergedTraits(); - if (traits.httpQueryParams) { - for (const [key, val] of Object.entries(data)) { - if (!(key in query)) { - const valueSchema = ns.getValueSchema(); - Object.assign(valueSchema.getMergedTraits(), { - ...traits, - httpQuery: key, - httpQueryParams: undefined, - }); - this.serializeQuery(valueSchema, val, query); - } - } - return; - } - if (ns.isListSchema()) { - const sparse = !!ns.getMergedTraits().sparse; - const buffer = []; - for (const item of data) { - serializer.write([ns.getValueSchema(), traits], item); - const serializable = serializer.flush(); - if (sparse || serializable !== undefined) { - buffer.push(serializable); - } - } - query[traits.httpQuery] = buffer; - } - else { - serializer.write([ns, traits], data); - query[traits.httpQuery] = serializer.flush(); - } - } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = schema.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(15, bytes)); - } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw."); - } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; - } - const nonHttpBindingMembers = await this.deserializeHttpMessage(ns, context, response, dataObject); - if (nonHttpBindingMembers.length) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - const dataFromBody = await deserializer.read(ns, bytes); - for (const member of nonHttpBindingMembers) { - dataObject[member] = dataFromBody[member]; - } - } - } - else if (nonHttpBindingMembers.discardResponseBody) { - await collectBody(response.body, context); - } - dataObject.$metadata = this.deserializeMetadata(response); - return dataObject; - } - async deserializeHttpMessage(schema$1, context, response, arg4, arg5) { - let dataObject; - if (arg4 instanceof Set) { - dataObject = arg5; - } - else { - dataObject = arg4; - } - let discardResponseBody = true; - const deserializer = this.deserializer; - const ns = schema.NormalizedSchema.of(schema$1); - const nonHttpBindingMembers = []; - for (const [memberName, memberSchema] of ns.structIterator()) { - const memberTraits = memberSchema.getMemberTraits(); - if (memberTraits.httpPayload) { - discardResponseBody = false; - const isStreaming = memberSchema.isStreaming(); - if (isStreaming) { - const isEventStream = memberSchema.isStructSchema(); - if (isEventStream) { - dataObject[memberName] = await this.deserializeEventStream({ - response, - responseSchema: ns, - }); - } - else { - dataObject[memberName] = utilStream.sdkStreamMixin(response.body); - } - } - else if (response.body) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - dataObject[memberName] = await deserializer.read(memberSchema, bytes); - } - } - } - else if (memberTraits.httpHeader) { - const key = String(memberTraits.httpHeader).toLowerCase(); - const value = response.headers[key]; - if (null != value) { - if (memberSchema.isListSchema()) { - const headerListValueSchema = memberSchema.getValueSchema(); - headerListValueSchema.getMergedTraits().httpHeader = key; - let sections; - if (headerListValueSchema.isTimestampSchema() && - headerListValueSchema.getSchema() === 4) { - sections = serde.splitEvery(value, ",", 2); - } - else { - sections = serde.splitHeader(value); - } - const list = []; - for (const section of sections) { - list.push(await deserializer.read(headerListValueSchema, section.trim())); - } - dataObject[memberName] = list; - } - else { - dataObject[memberName] = await deserializer.read(memberSchema, value); - } - } - } - else if (memberTraits.httpPrefixHeaders !== undefined) { - dataObject[memberName] = {}; - for (const [header, value] of Object.entries(response.headers)) { - if (header.startsWith(memberTraits.httpPrefixHeaders)) { - const valueSchema = memberSchema.getValueSchema(); - valueSchema.getMergedTraits().httpHeader = header; - dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)] = await deserializer.read(valueSchema, value); - } - } - } - else if (memberTraits.httpResponseCode) { - dataObject[memberName] = response.statusCode; - } - else { - nonHttpBindingMembers.push(memberName); - } - } - nonHttpBindingMembers.discardResponseBody = discardResponseBody; - return nonHttpBindingMembers; - } -} - -class RpcProtocol extends HttpProtocol { - async serializeRequest(operationSchema, input, context) { - const serializer = this.serializer; - const query = {}; - const headers = {}; - const endpoint = await context.endpoint(); - const ns = schema.NormalizedSchema.of(operationSchema?.input); - const schema$1 = ns.getSchema(); - let payload; - const request = new protocolHttp.HttpRequest({ - protocol: "", - hostname: "", - port: undefined, - path: "/", - fragment: undefined, - query: query, - headers: headers, - body: undefined, - }); - if (endpoint) { - this.updateServiceEndpoint(request, endpoint); - this.setHostPrefix(request, operationSchema, input); - } - const _input = { - ...input, - }; - if (input) { - const eventStreamMember = ns.getEventStreamMember(); - if (eventStreamMember) { - if (_input[eventStreamMember]) { - const initialRequest = {}; - for (const [memberName, memberSchema] of ns.structIterator()) { - if (memberName !== eventStreamMember && _input[memberName]) { - serializer.write(memberSchema, _input[memberName]); - initialRequest[memberName] = serializer.flush(); - } - } - payload = await this.serializeEventStream({ - eventStream: _input[eventStreamMember], - requestSchema: ns, - initialRequest, - }); - } - } - else { - serializer.write(schema$1, _input); - payload = serializer.flush(); - } - } - request.headers = headers; - request.query = query; - request.body = payload; - request.method = "POST"; - return request; - } - async deserializeResponse(operationSchema, context, response) { - const deserializer = this.deserializer; - const ns = schema.NormalizedSchema.of(operationSchema.output); - const dataObject = {}; - if (response.statusCode >= 300) { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(15, bytes)); - } - await this.handleError(operationSchema, context, response, dataObject, this.deserializeMetadata(response)); - throw new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw."); - } - for (const header in response.headers) { - const value = response.headers[header]; - delete response.headers[header]; - response.headers[header.toLowerCase()] = value; - } - const eventStreamMember = ns.getEventStreamMember(); - if (eventStreamMember) { - dataObject[eventStreamMember] = await this.deserializeEventStream({ - response, - responseSchema: ns, - initialResponseContainer: dataObject, - }); - } - else { - const bytes = await collectBody(response.body, context); - if (bytes.byteLength > 0) { - Object.assign(dataObject, await deserializer.read(ns, bytes)); - } - } - dataObject.$metadata = this.deserializeMetadata(response); - return dataObject; - } -} - -const resolvedPath = (resolvedPath, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { - if (input != null && input[memberName] !== undefined) { - const labelValue = labelValueProvider(); - if (labelValue.length <= 0) { - throw new Error("Empty value provided for input HTTP label: " + memberName + "."); - } - resolvedPath = resolvedPath.replace(uriLabel, isGreedyLabel - ? labelValue - .split("/") - .map((segment) => extendedEncodeURIComponent(segment)) - .join("/") - : extendedEncodeURIComponent(labelValue)); - } - else { - throw new Error("No value provided for input HTTP label: " + memberName + "."); - } - return resolvedPath; -}; - -function requestBuilder(input, context) { - return new RequestBuilder(input, context); -} -class RequestBuilder { - input; - context; - query = {}; - method = ""; - headers = {}; - path = ""; - body = null; - hostname = ""; - resolvePathStack = []; - constructor(input, context) { - this.input = input; - this.context = context; - } - async build() { - const { hostname, protocol = "https", port, path: basePath } = await this.context.endpoint(); - this.path = basePath; - for (const resolvePath of this.resolvePathStack) { - resolvePath(this.path); - } - return new protocolHttp.HttpRequest({ - protocol, - hostname: this.hostname || hostname, - port, - method: this.method, - path: this.path, - query: this.query, - body: this.body, - headers: this.headers, - }); - } - hn(hostname) { - this.hostname = hostname; - return this; - } - bp(uriLabel) { - this.resolvePathStack.push((basePath) => { - this.path = `${basePath?.endsWith("/") ? basePath.slice(0, -1) : basePath || ""}` + uriLabel; - }); - return this; - } - p(memberName, labelValueProvider, uriLabel, isGreedyLabel) { - this.resolvePathStack.push((path) => { - this.path = resolvedPath(path, this.input, memberName, labelValueProvider, uriLabel, isGreedyLabel); - }); - return this; - } - h(headers) { - this.headers = headers; - return this; - } - q(query) { - this.query = query; - return this; - } - b(body) { - this.body = body; - return this; - } - m(method) { - this.method = method; - return this; - } -} - -function determineTimestampFormat(ns, settings) { - if (settings.timestampFormat.useTrait) { - if (ns.isTimestampSchema() && - (ns.getSchema() === 5 || - ns.getSchema() === 6 || - ns.getSchema() === 7)) { - return ns.getSchema(); - } - } - const { httpLabel, httpPrefixHeaders, httpHeader, httpQuery } = ns.getMergedTraits(); - const bindingFormat = settings.httpBindings - ? typeof httpPrefixHeaders === "string" || Boolean(httpHeader) - ? 6 - : Boolean(httpQuery) || Boolean(httpLabel) - ? 5 - : undefined - : undefined; - return bindingFormat ?? settings.timestampFormat.default; -} - -class FromStringShapeDeserializer extends SerdeContext { - settings; - constructor(settings) { - super(); - this.settings = settings; - } - read(_schema, data) { - const ns = schema.NormalizedSchema.of(_schema); - if (ns.isListSchema()) { - return serde.splitHeader(data).map((item) => this.read(ns.getValueSchema(), item)); - } - if (ns.isBlobSchema()) { - return (this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(data); - } - if (ns.isTimestampSchema()) { - const format = determineTimestampFormat(ns, this.settings); - switch (format) { - case 5: - return serde._parseRfc3339DateTimeWithOffset(data); - case 6: - return serde._parseRfc7231DateTime(data); - case 7: - return serde._parseEpochTimestamp(data); - default: - console.warn("Missing timestamp format, parsing value with Date constructor:", data); - return new Date(data); - } - } - if (ns.isStringSchema()) { - const mediaType = ns.getMergedTraits().mediaType; - let intermediateValue = data; - if (mediaType) { - if (ns.getMergedTraits().httpHeader) { - intermediateValue = this.base64ToUtf8(intermediateValue); - } - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - intermediateValue = serde.LazyJsonString.from(intermediateValue); - } - return intermediateValue; - } - } - if (ns.isNumericSchema()) { - return Number(data); - } - if (ns.isBigIntegerSchema()) { - return BigInt(data); - } - if (ns.isBigDecimalSchema()) { - return new serde.NumericValue(data, "bigDecimal"); - } - if (ns.isBooleanSchema()) { - return String(data).toLowerCase() === "true"; - } - return data; - } - base64ToUtf8(base64String) { - return (this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8)((this.serdeContext?.base64Decoder ?? utilBase64.fromBase64)(base64String)); - } -} - -class HttpInterceptingShapeDeserializer extends SerdeContext { - codecDeserializer; - stringDeserializer; - constructor(codecDeserializer, codecSettings) { - super(); - this.codecDeserializer = codecDeserializer; - this.stringDeserializer = new FromStringShapeDeserializer(codecSettings); - } - setSerdeContext(serdeContext) { - this.stringDeserializer.setSerdeContext(serdeContext); - this.codecDeserializer.setSerdeContext(serdeContext); - this.serdeContext = serdeContext; - } - read(schema$1, data) { - const ns = schema.NormalizedSchema.of(schema$1); - const traits = ns.getMergedTraits(); - const toString = this.serdeContext?.utf8Encoder ?? utilUtf8.toUtf8; - if (traits.httpHeader || traits.httpResponseCode) { - return this.stringDeserializer.read(ns, toString(data)); - } - if (traits.httpPayload) { - if (ns.isBlobSchema()) { - const toBytes = this.serdeContext?.utf8Decoder ?? utilUtf8.fromUtf8; - if (typeof data === "string") { - return toBytes(data); - } - return data; - } - else if (ns.isStringSchema()) { - if ("byteLength" in data) { - return toString(data); - } - return data; - } - } - return this.codecDeserializer.read(ns, data); - } -} - -class ToStringShapeSerializer extends SerdeContext { - settings; - stringBuffer = ""; - constructor(settings) { - super(); - this.settings = settings; - } - write(schema$1, value) { - const ns = schema.NormalizedSchema.of(schema$1); - switch (typeof value) { - case "object": - if (value === null) { - this.stringBuffer = "null"; - return; - } - if (ns.isTimestampSchema()) { - if (!(value instanceof Date)) { - throw new Error(`@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName(true)}`); - } - const format = determineTimestampFormat(ns, this.settings); - switch (format) { - case 5: - this.stringBuffer = value.toISOString().replace(".000Z", "Z"); - break; - case 6: - this.stringBuffer = serde.dateToUtcString(value); - break; - case 7: - this.stringBuffer = String(value.getTime() / 1000); - break; - default: - console.warn("Missing timestamp format, using epoch seconds", value); - this.stringBuffer = String(value.getTime() / 1000); - } - return; - } - if (ns.isBlobSchema() && "byteLength" in value) { - this.stringBuffer = (this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(value); - return; - } - if (ns.isListSchema() && Array.isArray(value)) { - let buffer = ""; - for (const item of value) { - this.write([ns.getValueSchema(), ns.getMergedTraits()], item); - const headerItem = this.flush(); - const serialized = ns.getValueSchema().isTimestampSchema() ? headerItem : serde.quoteHeader(headerItem); - if (buffer !== "") { - buffer += ", "; - } - buffer += serialized; - } - this.stringBuffer = buffer; - return; - } - this.stringBuffer = JSON.stringify(value, null, 2); - break; - case "string": - const mediaType = ns.getMergedTraits().mediaType; - let intermediateValue = value; - if (mediaType) { - const isJson = mediaType === "application/json" || mediaType.endsWith("+json"); - if (isJson) { - intermediateValue = serde.LazyJsonString.from(intermediateValue); - } - if (ns.getMergedTraits().httpHeader) { - this.stringBuffer = (this.serdeContext?.base64Encoder ?? utilBase64.toBase64)(intermediateValue.toString()); - return; - } - } - this.stringBuffer = value; - break; - default: - if (ns.isIdempotencyToken()) { - this.stringBuffer = serde.generateIdempotencyToken(); - } - else { - this.stringBuffer = String(value); - } - } - } - flush() { - const buffer = this.stringBuffer; - this.stringBuffer = ""; - return buffer; - } -} - -class HttpInterceptingShapeSerializer { - codecSerializer; - stringSerializer; - buffer; - constructor(codecSerializer, codecSettings, stringSerializer = new ToStringShapeSerializer(codecSettings)) { - this.codecSerializer = codecSerializer; - this.stringSerializer = stringSerializer; - } - setSerdeContext(serdeContext) { - this.codecSerializer.setSerdeContext(serdeContext); - this.stringSerializer.setSerdeContext(serdeContext); - } - write(schema$1, value) { - const ns = schema.NormalizedSchema.of(schema$1); - const traits = ns.getMergedTraits(); - if (traits.httpHeader || traits.httpLabel || traits.httpQuery) { - this.stringSerializer.write(ns, value); - this.buffer = this.stringSerializer.flush(); - return; - } - return this.codecSerializer.write(ns, value); - } - flush() { - if (this.buffer !== undefined) { - const buffer = this.buffer; - this.buffer = undefined; - return buffer; - } - return this.codecSerializer.flush(); - } -} - -exports.FromStringShapeDeserializer = FromStringShapeDeserializer; -exports.HttpBindingProtocol = HttpBindingProtocol; -exports.HttpInterceptingShapeDeserializer = HttpInterceptingShapeDeserializer; -exports.HttpInterceptingShapeSerializer = HttpInterceptingShapeSerializer; -exports.HttpProtocol = HttpProtocol; -exports.RequestBuilder = RequestBuilder; -exports.RpcProtocol = RpcProtocol; -exports.SerdeContext = SerdeContext; -exports.ToStringShapeSerializer = ToStringShapeSerializer; -exports.collectBody = collectBody; -exports.determineTimestampFormat = determineTimestampFormat; -exports.extendedEncodeURIComponent = extendedEncodeURIComponent; -exports.requestBuilder = requestBuilder; -exports.resolvedPath = resolvedPath; diff --git a/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/schema/index.js b/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/schema/index.js deleted file mode 100644 index a5173e01..00000000 --- a/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/schema/index.js +++ /dev/null @@ -1,620 +0,0 @@ -'use strict'; - -var protocolHttp = require('@smithy/protocol-http'); -var utilMiddleware = require('@smithy/util-middleware'); - -const deref = (schemaRef) => { - if (typeof schemaRef === "function") { - return schemaRef(); - } - return schemaRef; -}; - -const operation = (namespace, name, traits, input, output) => ({ - name, - namespace, - traits, - input, - output, -}); - -const schemaDeserializationMiddleware = (config) => (next, context) => async (args) => { - const { response } = await next(args); - const { operationSchema } = utilMiddleware.getSmithyContext(context); - const [, ns, n, t, i, o] = operationSchema ?? []; - try { - const parsed = await config.protocol.deserializeResponse(operation(ns, n, t, i, o), { - ...config, - ...context, - }, response); - return { - response, - output: parsed, - }; - } - catch (error) { - Object.defineProperty(error, "$response", { - value: response, - enumerable: false, - writable: false, - configurable: false, - }); - if (!("$metadata" in error)) { - const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; - try { - error.message += "\n " + hint; - } - catch (e) { - if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { - console.warn(hint); - } - else { - context.logger?.warn?.(hint); - } - } - if (typeof error.$responseBodyText !== "undefined") { - if (error.$response) { - error.$response.body = error.$responseBodyText; - } - } - try { - if (protocolHttp.HttpResponse.isInstance(response)) { - const { headers = {} } = response; - const headerEntries = Object.entries(headers); - error.$metadata = { - httpStatusCode: response.statusCode, - requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), - extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), - cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries), - }; - } - } - catch (e) { - } - } - throw error; - } -}; -const findHeader = (pattern, headers) => { - return (headers.find(([k]) => { - return k.match(pattern); - }) || [void 0, void 0])[1]; -}; - -const schemaSerializationMiddleware = (config) => (next, context) => async (args) => { - const { operationSchema } = utilMiddleware.getSmithyContext(context); - const [, ns, n, t, i, o] = operationSchema ?? []; - const endpoint = context.endpointV2?.url && config.urlParser - ? async () => config.urlParser(context.endpointV2.url) - : config.endpoint; - const request = await config.protocol.serializeRequest(operation(ns, n, t, i, o), args.input, { - ...config, - ...context, - endpoint, - }); - return next({ - ...args, - request, - }); -}; - -const deserializerMiddlewareOption = { - name: "deserializerMiddleware", - step: "deserialize", - tags: ["DESERIALIZER"], - override: true, -}; -const serializerMiddlewareOption = { - name: "serializerMiddleware", - step: "serialize", - tags: ["SERIALIZER"], - override: true, -}; -function getSchemaSerdePlugin(config) { - return { - applyToStack: (commandStack) => { - commandStack.add(schemaSerializationMiddleware(config), serializerMiddlewareOption); - commandStack.add(schemaDeserializationMiddleware(config), deserializerMiddlewareOption); - config.protocol.setSerdeContext(config); - }, - }; -} - -class Schema { - name; - namespace; - traits; - static assign(instance, values) { - const schema = Object.assign(instance, values); - return schema; - } - static [Symbol.hasInstance](lhs) { - const isPrototype = this.prototype.isPrototypeOf(lhs); - if (!isPrototype && typeof lhs === "object" && lhs !== null) { - const list = lhs; - return list.symbol === this.symbol; - } - return isPrototype; - } - getName() { - return this.namespace + "#" + this.name; - } -} - -class ListSchema extends Schema { - static symbol = Symbol.for("@smithy/lis"); - name; - traits; - valueSchema; - symbol = ListSchema.symbol; -} -const list = (namespace, name, traits, valueSchema) => Schema.assign(new ListSchema(), { - name, - namespace, - traits, - valueSchema, -}); - -class MapSchema extends Schema { - static symbol = Symbol.for("@smithy/map"); - name; - traits; - keySchema; - valueSchema; - symbol = MapSchema.symbol; -} -const map = (namespace, name, traits, keySchema, valueSchema) => Schema.assign(new MapSchema(), { - name, - namespace, - traits, - keySchema, - valueSchema, -}); - -class OperationSchema extends Schema { - static symbol = Symbol.for("@smithy/ope"); - name; - traits; - input; - output; - symbol = OperationSchema.symbol; -} -const op = (namespace, name, traits, input, output) => Schema.assign(new OperationSchema(), { - name, - namespace, - traits, - input, - output, -}); - -class StructureSchema extends Schema { - static symbol = Symbol.for("@smithy/str"); - name; - traits; - memberNames; - memberList; - symbol = StructureSchema.symbol; -} -const struct = (namespace, name, traits, memberNames, memberList) => Schema.assign(new StructureSchema(), { - name, - namespace, - traits, - memberNames, - memberList, -}); - -class ErrorSchema extends StructureSchema { - static symbol = Symbol.for("@smithy/err"); - ctor; - symbol = ErrorSchema.symbol; -} -const error = (namespace, name, traits, memberNames, memberList, ctor) => Schema.assign(new ErrorSchema(), { - name, - namespace, - traits, - memberNames, - memberList, - ctor: null, -}); - -function translateTraits(indicator) { - if (typeof indicator === "object") { - return indicator; - } - indicator = indicator | 0; - const traits = {}; - let i = 0; - for (const trait of [ - "httpLabel", - "idempotent", - "idempotencyToken", - "sensitive", - "httpPayload", - "httpResponseCode", - "httpQueryParams", - ]) { - if (((indicator >> i++) & 1) === 1) { - traits[trait] = 1; - } - } - return traits; -} - -class NormalizedSchema { - ref; - memberName; - static symbol = Symbol.for("@smithy/nor"); - symbol = NormalizedSchema.symbol; - name; - schema; - _isMemberSchema; - traits; - memberTraits; - normalizedTraits; - constructor(ref, memberName) { - this.ref = ref; - this.memberName = memberName; - const traitStack = []; - let _ref = ref; - let schema = ref; - this._isMemberSchema = false; - while (isMemberSchema(_ref)) { - traitStack.push(_ref[1]); - _ref = _ref[0]; - schema = deref(_ref); - this._isMemberSchema = true; - } - if (traitStack.length > 0) { - this.memberTraits = {}; - for (let i = traitStack.length - 1; i >= 0; --i) { - const traitSet = traitStack[i]; - Object.assign(this.memberTraits, translateTraits(traitSet)); - } - } - else { - this.memberTraits = 0; - } - if (schema instanceof NormalizedSchema) { - const computedMemberTraits = this.memberTraits; - Object.assign(this, schema); - this.memberTraits = Object.assign({}, computedMemberTraits, schema.getMemberTraits(), this.getMemberTraits()); - this.normalizedTraits = void 0; - this.memberName = memberName ?? schema.memberName; - return; - } - this.schema = deref(schema); - if (isStaticSchema(this.schema)) { - this.name = `${this.schema[1]}#${this.schema[2]}`; - this.traits = this.schema[3]; - } - else { - this.name = this.memberName ?? String(schema); - this.traits = 0; - } - if (this._isMemberSchema && !memberName) { - throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(true)} missing member name.`); - } - } - static [Symbol.hasInstance](lhs) { - const isPrototype = this.prototype.isPrototypeOf(lhs); - if (!isPrototype && typeof lhs === "object" && lhs !== null) { - const ns = lhs; - return ns.symbol === this.symbol; - } - return isPrototype; - } - static of(ref) { - const sc = deref(ref); - if (sc instanceof NormalizedSchema) { - return sc; - } - if (isMemberSchema(sc)) { - const [ns, traits] = sc; - if (ns instanceof NormalizedSchema) { - Object.assign(ns.getMergedTraits(), translateTraits(traits)); - return ns; - } - throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref, null, 2)}.`); - } - return new NormalizedSchema(sc); - } - getSchema() { - const sc = this.schema; - if (sc[0] === 0) { - return sc[4]; - } - return sc; - } - getName(withNamespace = false) { - const { name } = this; - const short = !withNamespace && name && name.includes("#"); - return short ? name.split("#")[1] : name || undefined; - } - getMemberName() { - return this.memberName; - } - isMemberSchema() { - return this._isMemberSchema; - } - isListSchema() { - const sc = this.getSchema(); - return typeof sc === "number" - ? sc >= 64 && sc < 128 - : sc[0] === 1; - } - isMapSchema() { - const sc = this.getSchema(); - return typeof sc === "number" - ? sc >= 128 && sc <= 0b1111_1111 - : sc[0] === 2; - } - isStructSchema() { - const sc = this.getSchema(); - return (sc[0] === 3 || - sc[0] === -3); - } - isBlobSchema() { - const sc = this.getSchema(); - return sc === 21 || sc === 42; - } - isTimestampSchema() { - const sc = this.getSchema(); - return (typeof sc === "number" && - sc >= 4 && - sc <= 7); - } - isUnitSchema() { - return this.getSchema() === "unit"; - } - isDocumentSchema() { - return this.getSchema() === 15; - } - isStringSchema() { - return this.getSchema() === 0; - } - isBooleanSchema() { - return this.getSchema() === 2; - } - isNumericSchema() { - return this.getSchema() === 1; - } - isBigIntegerSchema() { - return this.getSchema() === 17; - } - isBigDecimalSchema() { - return this.getSchema() === 19; - } - isStreaming() { - const { streaming } = this.getMergedTraits(); - return !!streaming || this.getSchema() === 42; - } - isIdempotencyToken() { - const match = (traits) => (traits & 0b0100) === 0b0100 || - !!traits?.idempotencyToken; - const { normalizedTraits, traits, memberTraits } = this; - return match(normalizedTraits) || match(traits) || match(memberTraits); - } - getMergedTraits() { - return (this.normalizedTraits ?? - (this.normalizedTraits = { - ...this.getOwnTraits(), - ...this.getMemberTraits(), - })); - } - getMemberTraits() { - return translateTraits(this.memberTraits); - } - getOwnTraits() { - return translateTraits(this.traits); - } - getKeySchema() { - const [isDoc, isMap] = [this.isDocumentSchema(), this.isMapSchema()]; - if (!isDoc && !isMap) { - throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(true)}`); - } - const schema = this.getSchema(); - const memberSchema = isDoc - ? 15 - : schema[4] ?? 0; - return member([memberSchema, 0], "key"); - } - getValueSchema() { - const sc = this.getSchema(); - const [isDoc, isMap, isList] = [this.isDocumentSchema(), this.isMapSchema(), this.isListSchema()]; - const memberSchema = typeof sc === "number" - ? 0b0011_1111 & sc - : sc && typeof sc === "object" && (isMap || isList) - ? sc[3 + sc[0]] - : isDoc - ? 15 - : void 0; - if (memberSchema != null) { - return member([memberSchema, 0], isMap ? "value" : "member"); - } - throw new Error(`@smithy/core/schema - ${this.getName(true)} has no value member.`); - } - getMemberSchema(memberName) { - const struct = this.getSchema(); - if (this.isStructSchema() && struct[4].includes(memberName)) { - const i = struct[4].indexOf(memberName); - const memberSchema = struct[5][i]; - return member(isMemberSchema(memberSchema) ? memberSchema : [memberSchema, 0], memberName); - } - if (this.isDocumentSchema()) { - return member([15, 0], memberName); - } - throw new Error(`@smithy/core/schema - ${this.getName(true)} has no no member=${memberName}.`); - } - getMemberSchemas() { - const buffer = {}; - try { - for (const [k, v] of this.structIterator()) { - buffer[k] = v; - } - } - catch (ignored) { } - return buffer; - } - getEventStreamMember() { - if (this.isStructSchema()) { - for (const [memberName, memberSchema] of this.structIterator()) { - if (memberSchema.isStreaming() && memberSchema.isStructSchema()) { - return memberName; - } - } - } - return ""; - } - *structIterator() { - if (this.isUnitSchema()) { - return; - } - if (!this.isStructSchema()) { - throw new Error("@smithy/core/schema - cannot iterate non-struct schema."); - } - const struct = this.getSchema(); - for (let i = 0; i < struct[4].length; ++i) { - yield [struct[4][i], member([struct[5][i], 0], struct[4][i])]; - } - } -} -function member(memberSchema, memberName) { - if (memberSchema instanceof NormalizedSchema) { - return Object.assign(memberSchema, { - memberName, - _isMemberSchema: true, - }); - } - const internalCtorAccess = NormalizedSchema; - return new internalCtorAccess(memberSchema, memberName); -} -const isMemberSchema = (sc) => Array.isArray(sc) && sc.length === 2; -const isStaticSchema = (sc) => Array.isArray(sc) && sc.length >= 5; - -class SimpleSchema extends Schema { - static symbol = Symbol.for("@smithy/sim"); - name; - schemaRef; - traits; - symbol = SimpleSchema.symbol; -} -const sim = (namespace, name, schemaRef, traits) => Schema.assign(new SimpleSchema(), { - name, - namespace, - traits, - schemaRef, -}); -const simAdapter = (namespace, name, traits, schemaRef) => Schema.assign(new SimpleSchema(), { - name, - namespace, - traits, - schemaRef, -}); - -const SCHEMA = { - BLOB: 0b0001_0101, - STREAMING_BLOB: 0b0010_1010, - BOOLEAN: 0b0000_0010, - STRING: 0b0000_0000, - NUMERIC: 0b0000_0001, - BIG_INTEGER: 0b0001_0001, - BIG_DECIMAL: 0b0001_0011, - DOCUMENT: 0b0000_1111, - TIMESTAMP_DEFAULT: 0b0000_0100, - TIMESTAMP_DATE_TIME: 0b0000_0101, - TIMESTAMP_HTTP_DATE: 0b0000_0110, - TIMESTAMP_EPOCH_SECONDS: 0b0000_0111, - LIST_MODIFIER: 0b0100_0000, - MAP_MODIFIER: 0b1000_0000, -}; - -class TypeRegistry { - namespace; - schemas; - exceptions; - static registries = new Map(); - constructor(namespace, schemas = new Map(), exceptions = new Map()) { - this.namespace = namespace; - this.schemas = schemas; - this.exceptions = exceptions; - } - static for(namespace) { - if (!TypeRegistry.registries.has(namespace)) { - TypeRegistry.registries.set(namespace, new TypeRegistry(namespace)); - } - return TypeRegistry.registries.get(namespace); - } - register(shapeId, schema) { - const qualifiedName = this.normalizeShapeId(shapeId); - const registry = TypeRegistry.for(qualifiedName.split("#")[0]); - registry.schemas.set(qualifiedName, schema); - } - getSchema(shapeId) { - const id = this.normalizeShapeId(shapeId); - if (!this.schemas.has(id)) { - throw new Error(`@smithy/core/schema - schema not found for ${id}`); - } - return this.schemas.get(id); - } - registerError(es, ctor) { - const $error = es; - const registry = TypeRegistry.for($error[1]); - registry.schemas.set($error[1] + "#" + $error[2], $error); - registry.exceptions.set($error, ctor); - } - getErrorCtor(es) { - const $error = es; - const registry = TypeRegistry.for($error[1]); - return registry.exceptions.get($error); - } - getBaseException() { - for (const exceptionKey of this.exceptions.keys()) { - if (Array.isArray(exceptionKey)) { - const [, ns, name] = exceptionKey; - const id = ns + "#" + name; - if (id.startsWith("smithy.ts.sdk.synthetic.") && id.endsWith("ServiceException")) { - return exceptionKey; - } - } - } - return undefined; - } - find(predicate) { - return [...this.schemas.values()].find(predicate); - } - clear() { - this.schemas.clear(); - this.exceptions.clear(); - } - normalizeShapeId(shapeId) { - if (shapeId.includes("#")) { - return shapeId; - } - return this.namespace + "#" + shapeId; - } -} - -exports.ErrorSchema = ErrorSchema; -exports.ListSchema = ListSchema; -exports.MapSchema = MapSchema; -exports.NormalizedSchema = NormalizedSchema; -exports.OperationSchema = OperationSchema; -exports.SCHEMA = SCHEMA; -exports.Schema = Schema; -exports.SimpleSchema = SimpleSchema; -exports.StructureSchema = StructureSchema; -exports.TypeRegistry = TypeRegistry; -exports.deref = deref; -exports.deserializerMiddlewareOption = deserializerMiddlewareOption; -exports.error = error; -exports.getSchemaSerdePlugin = getSchemaSerdePlugin; -exports.isStaticSchema = isStaticSchema; -exports.list = list; -exports.map = map; -exports.op = op; -exports.operation = operation; -exports.serializerMiddlewareOption = serializerMiddlewareOption; -exports.sim = sim; -exports.simAdapter = simAdapter; -exports.struct = struct; -exports.translateTraits = translateTraits; diff --git a/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/serde/index.js b/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/serde/index.js deleted file mode 100644 index 7c4740cf..00000000 --- a/claude-code-source/node_modules/@smithy/core/dist-cjs/submodules/serde/index.js +++ /dev/null @@ -1,697 +0,0 @@ -'use strict'; - -var uuid = require('@smithy/uuid'); - -const copyDocumentWithTransform = (source, schemaRef, transform = (_) => _) => source; - -const parseBoolean = (value) => { - switch (value) { - case "true": - return true; - case "false": - return false; - default: - throw new Error(`Unable to parse boolean value "${value}"`); - } -}; -const expectBoolean = (value) => { - if (value === null || value === undefined) { - return undefined; - } - if (typeof value === "number") { - if (value === 0 || value === 1) { - logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); - } - if (value === 0) { - return false; - } - if (value === 1) { - return true; - } - } - if (typeof value === "string") { - const lower = value.toLowerCase(); - if (lower === "false" || lower === "true") { - logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); - } - if (lower === "false") { - return false; - } - if (lower === "true") { - return true; - } - } - if (typeof value === "boolean") { - return value; - } - throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); -}; -const expectNumber = (value) => { - if (value === null || value === undefined) { - return undefined; - } - if (typeof value === "string") { - const parsed = parseFloat(value); - if (!Number.isNaN(parsed)) { - if (String(parsed) !== String(value)) { - logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); - } - return parsed; - } - } - if (typeof value === "number") { - return value; - } - throw new TypeError(`Expected number, got ${typeof value}: ${value}`); -}; -const MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); -const expectFloat32 = (value) => { - const expected = expectNumber(value); - if (expected !== undefined && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { - if (Math.abs(expected) > MAX_FLOAT) { - throw new TypeError(`Expected 32-bit float, got ${value}`); - } - } - return expected; -}; -const expectLong = (value) => { - if (value === null || value === undefined) { - return undefined; - } - if (Number.isInteger(value) && !Number.isNaN(value)) { - return value; - } - throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); -}; -const expectInt = expectLong; -const expectInt32 = (value) => expectSizedInt(value, 32); -const expectShort = (value) => expectSizedInt(value, 16); -const expectByte = (value) => expectSizedInt(value, 8); -const expectSizedInt = (value, size) => { - const expected = expectLong(value); - if (expected !== undefined && castInt(expected, size) !== expected) { - throw new TypeError(`Expected ${size}-bit integer, got ${value}`); - } - return expected; -}; -const castInt = (value, size) => { - switch (size) { - case 32: - return Int32Array.of(value)[0]; - case 16: - return Int16Array.of(value)[0]; - case 8: - return Int8Array.of(value)[0]; - } -}; -const expectNonNull = (value, location) => { - if (value === null || value === undefined) { - if (location) { - throw new TypeError(`Expected a non-null value for ${location}`); - } - throw new TypeError("Expected a non-null value"); - } - return value; -}; -const expectObject = (value) => { - if (value === null || value === undefined) { - return undefined; - } - if (typeof value === "object" && !Array.isArray(value)) { - return value; - } - const receivedType = Array.isArray(value) ? "array" : typeof value; - throw new TypeError(`Expected object, got ${receivedType}: ${value}`); -}; -const expectString = (value) => { - if (value === null || value === undefined) { - return undefined; - } - if (typeof value === "string") { - return value; - } - if (["boolean", "number", "bigint"].includes(typeof value)) { - logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); - return String(value); - } - throw new TypeError(`Expected string, got ${typeof value}: ${value}`); -}; -const expectUnion = (value) => { - if (value === null || value === undefined) { - return undefined; - } - const asObject = expectObject(value); - const setKeys = Object.entries(asObject) - .filter(([, v]) => v != null) - .map(([k]) => k); - if (setKeys.length === 0) { - throw new TypeError(`Unions must have exactly one non-null member. None were found.`); - } - if (setKeys.length > 1) { - throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); - } - return asObject; -}; -const strictParseDouble = (value) => { - if (typeof value == "string") { - return expectNumber(parseNumber(value)); - } - return expectNumber(value); -}; -const strictParseFloat = strictParseDouble; -const strictParseFloat32 = (value) => { - if (typeof value == "string") { - return expectFloat32(parseNumber(value)); - } - return expectFloat32(value); -}; -const NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; -const parseNumber = (value) => { - const matches = value.match(NUMBER_REGEX); - if (matches === null || matches[0].length !== value.length) { - throw new TypeError(`Expected real number, got implicit NaN`); - } - return parseFloat(value); -}; -const limitedParseDouble = (value) => { - if (typeof value == "string") { - return parseFloatString(value); - } - return expectNumber(value); -}; -const handleFloat = limitedParseDouble; -const limitedParseFloat = limitedParseDouble; -const limitedParseFloat32 = (value) => { - if (typeof value == "string") { - return parseFloatString(value); - } - return expectFloat32(value); -}; -const parseFloatString = (value) => { - switch (value) { - case "NaN": - return NaN; - case "Infinity": - return Infinity; - case "-Infinity": - return -Infinity; - default: - throw new Error(`Unable to parse float value: ${value}`); - } -}; -const strictParseLong = (value) => { - if (typeof value === "string") { - return expectLong(parseNumber(value)); - } - return expectLong(value); -}; -const strictParseInt = strictParseLong; -const strictParseInt32 = (value) => { - if (typeof value === "string") { - return expectInt32(parseNumber(value)); - } - return expectInt32(value); -}; -const strictParseShort = (value) => { - if (typeof value === "string") { - return expectShort(parseNumber(value)); - } - return expectShort(value); -}; -const strictParseByte = (value) => { - if (typeof value === "string") { - return expectByte(parseNumber(value)); - } - return expectByte(value); -}; -const stackTraceWarning = (message) => { - return String(new TypeError(message).stack || message) - .split("\n") - .slice(0, 5) - .filter((s) => !s.includes("stackTraceWarning")) - .join("\n"); -}; -const logger = { - warn: console.warn, -}; - -const DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; -const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; -function dateToUtcString(date) { - const year = date.getUTCFullYear(); - const month = date.getUTCMonth(); - const dayOfWeek = date.getUTCDay(); - const dayOfMonthInt = date.getUTCDate(); - const hoursInt = date.getUTCHours(); - const minutesInt = date.getUTCMinutes(); - const secondsInt = date.getUTCSeconds(); - const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; - const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; - const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; - const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; - return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; -} -const RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); -const parseRfc3339DateTime = (value) => { - if (value === null || value === undefined) { - return undefined; - } - if (typeof value !== "string") { - throw new TypeError("RFC-3339 date-times must be expressed as strings"); - } - const match = RFC3339.exec(value); - if (!match) { - throw new TypeError("Invalid RFC-3339 date-time value"); - } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; - const year = strictParseShort(stripLeadingZeroes(yearStr)); - const month = parseDateValue(monthStr, "month", 1, 12); - const day = parseDateValue(dayStr, "day", 1, 31); - return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); -}; -const RFC3339_WITH_OFFSET$1 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/); -const parseRfc3339DateTimeWithOffset = (value) => { - if (value === null || value === undefined) { - return undefined; - } - if (typeof value !== "string") { - throw new TypeError("RFC-3339 date-times must be expressed as strings"); - } - const match = RFC3339_WITH_OFFSET$1.exec(value); - if (!match) { - throw new TypeError("Invalid RFC-3339 date-time value"); - } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; - const year = strictParseShort(stripLeadingZeroes(yearStr)); - const month = parseDateValue(monthStr, "month", 1, 12); - const day = parseDateValue(dayStr, "day", 1, 31); - const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); - if (offsetStr.toUpperCase() != "Z") { - date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); - } - return date; -}; -const IMF_FIXDATE$1 = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); -const RFC_850_DATE$1 = new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/); -const ASC_TIME$1 = new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/); -const parseRfc7231DateTime = (value) => { - if (value === null || value === undefined) { - return undefined; - } - if (typeof value !== "string") { - throw new TypeError("RFC-7231 date-times must be expressed as strings"); - } - let match = IMF_FIXDATE$1.exec(value); - if (match) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; - return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); - } - match = RFC_850_DATE$1.exec(value); - if (match) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; - return adjustRfc850Year(buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { - hours, - minutes, - seconds, - fractionalMilliseconds, - })); - } - match = ASC_TIME$1.exec(value); - if (match) { - const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; - return buildDate(strictParseShort(stripLeadingZeroes(yearStr)), parseMonthByShortName(monthStr), parseDateValue(dayStr.trimLeft(), "day", 1, 31), { hours, minutes, seconds, fractionalMilliseconds }); - } - throw new TypeError("Invalid RFC-7231 date-time value"); -}; -const parseEpochTimestamp = (value) => { - if (value === null || value === undefined) { - return undefined; - } - let valueAsDouble; - if (typeof value === "number") { - valueAsDouble = value; - } - else if (typeof value === "string") { - valueAsDouble = strictParseDouble(value); - } - else if (typeof value === "object" && value.tag === 1) { - valueAsDouble = value.value; - } - else { - throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); - } - if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { - throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); - } - return new Date(Math.round(valueAsDouble * 1000)); -}; -const buildDate = (year, month, day, time) => { - const adjustedMonth = month - 1; - validateDayOfMonth(year, adjustedMonth, day); - return new Date(Date.UTC(year, adjustedMonth, day, parseDateValue(time.hours, "hour", 0, 23), parseDateValue(time.minutes, "minute", 0, 59), parseDateValue(time.seconds, "seconds", 0, 60), parseMilliseconds(time.fractionalMilliseconds))); -}; -const parseTwoDigitYear = (value) => { - const thisYear = new Date().getUTCFullYear(); - const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); - if (valueInThisCentury < thisYear) { - return valueInThisCentury + 100; - } - return valueInThisCentury; -}; -const FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1000; -const adjustRfc850Year = (input) => { - if (input.getTime() - new Date().getTime() > FIFTY_YEARS_IN_MILLIS) { - return new Date(Date.UTC(input.getUTCFullYear() - 100, input.getUTCMonth(), input.getUTCDate(), input.getUTCHours(), input.getUTCMinutes(), input.getUTCSeconds(), input.getUTCMilliseconds())); - } - return input; -}; -const parseMonthByShortName = (value) => { - const monthIdx = MONTHS.indexOf(value); - if (monthIdx < 0) { - throw new TypeError(`Invalid month: ${value}`); - } - return monthIdx + 1; -}; -const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; -const validateDayOfMonth = (year, month, day) => { - let maxDays = DAYS_IN_MONTH[month]; - if (month === 1 && isLeapYear(year)) { - maxDays = 29; - } - if (day > maxDays) { - throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); - } -}; -const isLeapYear = (year) => { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); -}; -const parseDateValue = (value, type, lower, upper) => { - const dateVal = strictParseByte(stripLeadingZeroes(value)); - if (dateVal < lower || dateVal > upper) { - throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); - } - return dateVal; -}; -const parseMilliseconds = (value) => { - if (value === null || value === undefined) { - return 0; - } - return strictParseFloat32("0." + value) * 1000; -}; -const parseOffsetToMilliseconds = (value) => { - const directionStr = value[0]; - let direction = 1; - if (directionStr == "+") { - direction = 1; - } - else if (directionStr == "-") { - direction = -1; - } - else { - throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); - } - const hour = Number(value.substring(1, 3)); - const minute = Number(value.substring(4, 6)); - return direction * (hour * 60 + minute) * 60 * 1000; -}; -const stripLeadingZeroes = (value) => { - let idx = 0; - while (idx < value.length - 1 && value.charAt(idx) === "0") { - idx++; - } - if (idx === 0) { - return value; - } - return value.slice(idx); -}; - -const LazyJsonString = function LazyJsonString(val) { - const str = Object.assign(new String(val), { - deserializeJSON() { - return JSON.parse(String(val)); - }, - toString() { - return String(val); - }, - toJSON() { - return String(val); - }, - }); - return str; -}; -LazyJsonString.from = (object) => { - if (object && typeof object === "object" && (object instanceof LazyJsonString || "deserializeJSON" in object)) { - return object; - } - else if (typeof object === "string" || Object.getPrototypeOf(object) === String.prototype) { - return LazyJsonString(String(object)); - } - return LazyJsonString(JSON.stringify(object)); -}; -LazyJsonString.fromObject = LazyJsonString.from; - -function quoteHeader(part) { - if (part.includes(",") || part.includes('"')) { - part = `"${part.replace(/"/g, '\\"')}"`; - } - return part; -} - -const ddd = `(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?`; -const mmm = `(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)`; -const time = `(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?`; -const date = `(\\d?\\d)`; -const year = `(\\d{4})`; -const RFC3339_WITH_OFFSET = new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/); -const IMF_FIXDATE = new RegExp(`^${ddd}, ${date} ${mmm} ${year} ${time} GMT$`); -const RFC_850_DATE = new RegExp(`^${ddd}, ${date}-${mmm}-(\\d\\d) ${time} GMT$`); -const ASC_TIME = new RegExp(`^${ddd} ${mmm} ( [1-9]|\\d\\d) ${time} ${year}$`); -const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; -const _parseEpochTimestamp = (value) => { - if (value == null) { - return void 0; - } - let num = NaN; - if (typeof value === "number") { - num = value; - } - else if (typeof value === "string") { - if (!/^-?\d*\.?\d+$/.test(value)) { - throw new TypeError(`parseEpochTimestamp - numeric string invalid.`); - } - num = Number.parseFloat(value); - } - else if (typeof value === "object" && value.tag === 1) { - num = value.value; - } - if (isNaN(num) || Math.abs(num) === Infinity) { - throw new TypeError("Epoch timestamps must be valid finite numbers."); - } - return new Date(Math.round(num * 1000)); -}; -const _parseRfc3339DateTimeWithOffset = (value) => { - if (value == null) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC3339 timestamps must be strings"); - } - const matches = RFC3339_WITH_OFFSET.exec(value); - if (!matches) { - throw new TypeError(`Invalid RFC3339 timestamp format ${value}`); - } - const [, yearStr, monthStr, dayStr, hours, minutes, seconds, , ms, offsetStr] = matches; - range(monthStr, 1, 12); - range(dayStr, 1, 31); - range(hours, 0, 23); - range(minutes, 0, 59); - range(seconds, 0, 60); - const date = new Date(Date.UTC(Number(yearStr), Number(monthStr) - 1, Number(dayStr), Number(hours), Number(minutes), Number(seconds), Number(ms) ? Math.round(parseFloat(`0.${ms}`) * 1000) : 0)); - date.setUTCFullYear(Number(yearStr)); - if (offsetStr.toUpperCase() != "Z") { - const [, sign, offsetH, offsetM] = /([+-])(\d\d):(\d\d)/.exec(offsetStr) || [void 0, "+", 0, 0]; - const scalar = sign === "-" ? 1 : -1; - date.setTime(date.getTime() + scalar * (Number(offsetH) * 60 * 60 * 1000 + Number(offsetM) * 60 * 1000)); - } - return date; -}; -const _parseRfc7231DateTime = (value) => { - if (value == null) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC7231 timestamps must be strings."); - } - let day; - let month; - let year; - let hour; - let minute; - let second; - let fraction; - let matches; - if ((matches = IMF_FIXDATE.exec(value))) { - [, day, month, year, hour, minute, second, fraction] = matches; - } - else if ((matches = RFC_850_DATE.exec(value))) { - [, day, month, year, hour, minute, second, fraction] = matches; - year = (Number(year) + 1900).toString(); - } - else if ((matches = ASC_TIME.exec(value))) { - [, month, day, hour, minute, second, fraction, year] = matches; - } - if (year && second) { - const timestamp = Date.UTC(Number(year), months.indexOf(month), Number(day), Number(hour), Number(minute), Number(second), fraction ? Math.round(parseFloat(`0.${fraction}`) * 1000) : 0); - range(day, 1, 31); - range(hour, 0, 23); - range(minute, 0, 59); - range(second, 0, 60); - const date = new Date(timestamp); - date.setUTCFullYear(Number(year)); - return date; - } - throw new TypeError(`Invalid RFC7231 date-time value ${value}.`); -}; -function range(v, min, max) { - const _v = Number(v); - if (_v < min || _v > max) { - throw new Error(`Value ${_v} out of range [${min}, ${max}]`); - } -} - -function splitEvery(value, delimiter, numDelimiters) { - if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { - throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); - } - const segments = value.split(delimiter); - if (numDelimiters === 1) { - return segments; - } - const compoundSegments = []; - let currentSegment = ""; - for (let i = 0; i < segments.length; i++) { - if (currentSegment === "") { - currentSegment = segments[i]; - } - else { - currentSegment += delimiter + segments[i]; - } - if ((i + 1) % numDelimiters === 0) { - compoundSegments.push(currentSegment); - currentSegment = ""; - } - } - if (currentSegment !== "") { - compoundSegments.push(currentSegment); - } - return compoundSegments; -} - -const splitHeader = (value) => { - const z = value.length; - const values = []; - let withinQuotes = false; - let prevChar = undefined; - let anchor = 0; - for (let i = 0; i < z; ++i) { - const char = value[i]; - switch (char) { - case `"`: - if (prevChar !== "\\") { - withinQuotes = !withinQuotes; - } - break; - case ",": - if (!withinQuotes) { - values.push(value.slice(anchor, i)); - anchor = i + 1; - } - break; - } - prevChar = char; - } - values.push(value.slice(anchor)); - return values.map((v) => { - v = v.trim(); - const z = v.length; - if (z < 2) { - return v; - } - if (v[0] === `"` && v[z - 1] === `"`) { - v = v.slice(1, z - 1); - } - return v.replace(/\\"/g, '"'); - }); -}; - -const format = /^-?\d*(\.\d+)?$/; -class NumericValue { - string; - type; - constructor(string, type) { - this.string = string; - this.type = type; - if (!format.test(string)) { - throw new Error(`@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".`); - } - } - toString() { - return this.string; - } - static [Symbol.hasInstance](object) { - if (!object || typeof object !== "object") { - return false; - } - const _nv = object; - return NumericValue.prototype.isPrototypeOf(object) || (_nv.type === "bigDecimal" && format.test(_nv.string)); - } -} -function nv(input) { - return new NumericValue(String(input), "bigDecimal"); -} - -Object.defineProperty(exports, "generateIdempotencyToken", { - enumerable: true, - get: function () { return uuid.v4; } -}); -exports.LazyJsonString = LazyJsonString; -exports.NumericValue = NumericValue; -exports._parseEpochTimestamp = _parseEpochTimestamp; -exports._parseRfc3339DateTimeWithOffset = _parseRfc3339DateTimeWithOffset; -exports._parseRfc7231DateTime = _parseRfc7231DateTime; -exports.copyDocumentWithTransform = copyDocumentWithTransform; -exports.dateToUtcString = dateToUtcString; -exports.expectBoolean = expectBoolean; -exports.expectByte = expectByte; -exports.expectFloat32 = expectFloat32; -exports.expectInt = expectInt; -exports.expectInt32 = expectInt32; -exports.expectLong = expectLong; -exports.expectNonNull = expectNonNull; -exports.expectNumber = expectNumber; -exports.expectObject = expectObject; -exports.expectShort = expectShort; -exports.expectString = expectString; -exports.expectUnion = expectUnion; -exports.handleFloat = handleFloat; -exports.limitedParseDouble = limitedParseDouble; -exports.limitedParseFloat = limitedParseFloat; -exports.limitedParseFloat32 = limitedParseFloat32; -exports.logger = logger; -exports.nv = nv; -exports.parseBoolean = parseBoolean; -exports.parseEpochTimestamp = parseEpochTimestamp; -exports.parseRfc3339DateTime = parseRfc3339DateTime; -exports.parseRfc3339DateTimeWithOffset = parseRfc3339DateTimeWithOffset; -exports.parseRfc7231DateTime = parseRfc7231DateTime; -exports.quoteHeader = quoteHeader; -exports.splitEvery = splitEvery; -exports.splitHeader = splitHeader; -exports.strictParseByte = strictParseByte; -exports.strictParseDouble = strictParseDouble; -exports.strictParseFloat = strictParseFloat; -exports.strictParseFloat32 = strictParseFloat32; -exports.strictParseInt = strictParseInt; -exports.strictParseInt32 = strictParseInt32; -exports.strictParseLong = strictParseLong; -exports.strictParseShort = strictParseShort; diff --git a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 52303c3b..00000000 --- a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,169 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js deleted file mode 100644 index b06a7b87..00000000 --- a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js +++ /dev/null @@ -1,16 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/index.js deleted file mode 100644 index c095e288..00000000 --- a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/index.js +++ /dev/null @@ -1,19 +0,0 @@ -'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]; } - }); -}); diff --git a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/toBase64.js deleted file mode 100644 index 0590ce3f..00000000 --- a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/dist-cjs/toBase64.js +++ /dev/null @@ -1,19 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js deleted file mode 100644 index b577c9ca..00000000 --- a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js +++ /dev/null @@ -1,20 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js deleted file mode 100644 index 3238bb77..00000000 --- a/claude-code-source/node_modules/@smithy/core/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || - Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; - -exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@smithy/credential-provider-imds/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/credential-provider-imds/dist-cjs/index.js deleted file mode 100644 index 8de0d3f1..00000000 --- a/claude-code-source/node_modules/@smithy/credential-provider-imds/dist-cjs/index.js +++ /dev/null @@ -1,372 +0,0 @@ -'use strict'; - -var propertyProvider = require('@smithy/property-provider'); -var url = require('url'); -var buffer = require('buffer'); -var http = require('http'); -var nodeConfigProvider = require('@smithy/node-config-provider'); -var urlParser = require('@smithy/url-parser'); - -function httpRequest(options) { - return new Promise((resolve, reject) => { - const req = http.request({ - method: "GET", - ...options, - hostname: options.hostname?.replace(/^\[(.+)\]$/, "$1"), - }); - req.on("error", (err) => { - reject(Object.assign(new propertyProvider.ProviderError("Unable to connect to instance metadata service"), err)); - req.destroy(); - }); - req.on("timeout", () => { - reject(new propertyProvider.ProviderError("TimeoutError from instance metadata service")); - req.destroy(); - }); - req.on("response", (res) => { - const { statusCode = 400 } = res; - if (statusCode < 200 || 300 <= statusCode) { - reject(Object.assign(new propertyProvider.ProviderError("Error response received from instance metadata service"), { statusCode })); - req.destroy(); - } - const chunks = []; - res.on("data", (chunk) => { - chunks.push(chunk); - }); - res.on("end", () => { - resolve(buffer.Buffer.concat(chunks)); - req.destroy(); - }); - }); - req.end(); - }); -} - -const isImdsCredentials = (arg) => Boolean(arg) && - typeof arg === "object" && - typeof arg.AccessKeyId === "string" && - typeof arg.SecretAccessKey === "string" && - typeof arg.Token === "string" && - typeof arg.Expiration === "string"; -const fromImdsCredentials = (creds) => ({ - accessKeyId: creds.AccessKeyId, - secretAccessKey: creds.SecretAccessKey, - sessionToken: creds.Token, - expiration: new Date(creds.Expiration), - ...(creds.AccountId && { accountId: creds.AccountId }), -}); - -const DEFAULT_TIMEOUT = 1000; -const DEFAULT_MAX_RETRIES = 0; -const providerConfigFromInit = ({ maxRetries = DEFAULT_MAX_RETRIES, timeout = DEFAULT_TIMEOUT, }) => ({ maxRetries, timeout }); - -const retry = (toRetry, maxRetries) => { - let promise = toRetry(); - for (let i = 0; i < maxRetries; i++) { - promise = promise.catch(toRetry); - } - return promise; -}; - -const ENV_CMDS_FULL_URI = "AWS_CONTAINER_CREDENTIALS_FULL_URI"; -const ENV_CMDS_RELATIVE_URI = "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI"; -const ENV_CMDS_AUTH_TOKEN = "AWS_CONTAINER_AUTHORIZATION_TOKEN"; -const fromContainerMetadata = (init = {}) => { - const { timeout, maxRetries } = providerConfigFromInit(init); - return () => retry(async () => { - const requestOptions = await getCmdsUri({ logger: init.logger }); - const credsResponse = JSON.parse(await requestFromEcsImds(timeout, requestOptions)); - if (!isImdsCredentials(credsResponse)) { - throw new propertyProvider.CredentialsProviderError("Invalid response received from instance metadata service.", { - logger: init.logger, - }); - } - return fromImdsCredentials(credsResponse); - }, maxRetries); -}; -const requestFromEcsImds = async (timeout, options) => { - if (process.env[ENV_CMDS_AUTH_TOKEN]) { - options.headers = { - ...options.headers, - Authorization: process.env[ENV_CMDS_AUTH_TOKEN], - }; - } - const buffer = await httpRequest({ - ...options, - timeout, - }); - return buffer.toString(); -}; -const CMDS_IP = "169.254.170.2"; -const GREENGRASS_HOSTS = { - localhost: true, - "127.0.0.1": true, -}; -const GREENGRASS_PROTOCOLS = { - "http:": true, - "https:": true, -}; -const getCmdsUri = async ({ logger }) => { - if (process.env[ENV_CMDS_RELATIVE_URI]) { - return { - hostname: CMDS_IP, - path: process.env[ENV_CMDS_RELATIVE_URI], - }; - } - if (process.env[ENV_CMDS_FULL_URI]) { - const parsed = url.parse(process.env[ENV_CMDS_FULL_URI]); - if (!parsed.hostname || !(parsed.hostname in GREENGRASS_HOSTS)) { - throw new propertyProvider.CredentialsProviderError(`${parsed.hostname} is not a valid container metadata service hostname`, { - tryNextLink: false, - logger, - }); - } - if (!parsed.protocol || !(parsed.protocol in GREENGRASS_PROTOCOLS)) { - throw new propertyProvider.CredentialsProviderError(`${parsed.protocol} is not a valid container metadata service protocol`, { - tryNextLink: false, - logger, - }); - } - return { - ...parsed, - port: parsed.port ? parseInt(parsed.port, 10) : undefined, - }; - } - throw new propertyProvider.CredentialsProviderError("The container metadata credential provider cannot be used unless" + - ` the ${ENV_CMDS_RELATIVE_URI} or ${ENV_CMDS_FULL_URI} environment` + - " variable is set", { - tryNextLink: false, - logger, - }); -}; - -class InstanceMetadataV1FallbackError extends propertyProvider.CredentialsProviderError { - tryNextLink; - name = "InstanceMetadataV1FallbackError"; - constructor(message, tryNextLink = true) { - super(message, tryNextLink); - this.tryNextLink = tryNextLink; - Object.setPrototypeOf(this, InstanceMetadataV1FallbackError.prototype); - } -} - -exports.Endpoint = void 0; -(function (Endpoint) { - Endpoint["IPv4"] = "http://169.254.169.254"; - Endpoint["IPv6"] = "http://[fd00:ec2::254]"; -})(exports.Endpoint || (exports.Endpoint = {})); - -const ENV_ENDPOINT_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT"; -const CONFIG_ENDPOINT_NAME = "ec2_metadata_service_endpoint"; -const ENDPOINT_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => env[ENV_ENDPOINT_NAME], - configFileSelector: (profile) => profile[CONFIG_ENDPOINT_NAME], - default: undefined, -}; - -var EndpointMode; -(function (EndpointMode) { - EndpointMode["IPv4"] = "IPv4"; - EndpointMode["IPv6"] = "IPv6"; -})(EndpointMode || (EndpointMode = {})); - -const ENV_ENDPOINT_MODE_NAME = "AWS_EC2_METADATA_SERVICE_ENDPOINT_MODE"; -const CONFIG_ENDPOINT_MODE_NAME = "ec2_metadata_service_endpoint_mode"; -const ENDPOINT_MODE_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => env[ENV_ENDPOINT_MODE_NAME], - configFileSelector: (profile) => profile[CONFIG_ENDPOINT_MODE_NAME], - default: EndpointMode.IPv4, -}; - -const getInstanceMetadataEndpoint = async () => urlParser.parseUrl((await getFromEndpointConfig()) || (await getFromEndpointModeConfig())); -const getFromEndpointConfig = async () => nodeConfigProvider.loadConfig(ENDPOINT_CONFIG_OPTIONS)(); -const getFromEndpointModeConfig = async () => { - const endpointMode = await nodeConfigProvider.loadConfig(ENDPOINT_MODE_CONFIG_OPTIONS)(); - switch (endpointMode) { - case EndpointMode.IPv4: - return exports.Endpoint.IPv4; - case EndpointMode.IPv6: - return exports.Endpoint.IPv6; - default: - throw new Error(`Unsupported endpoint mode: ${endpointMode}.` + ` Select from ${Object.values(EndpointMode)}`); - } -}; - -const STATIC_STABILITY_REFRESH_INTERVAL_SECONDS = 5 * 60; -const STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS = 5 * 60; -const STATIC_STABILITY_DOC_URL = "https://docs.aws.amazon.com/sdkref/latest/guide/feature-static-credentials.html"; -const getExtendedInstanceMetadataCredentials = (credentials, logger) => { - const refreshInterval = STATIC_STABILITY_REFRESH_INTERVAL_SECONDS + - Math.floor(Math.random() * STATIC_STABILITY_REFRESH_INTERVAL_JITTER_WINDOW_SECONDS); - const newExpiration = new Date(Date.now() + refreshInterval * 1000); - logger.warn("Attempting credential expiration extension due to a credential service availability issue. A refresh of these " + - `credentials will be attempted after ${new Date(newExpiration)}.\nFor more information, please visit: ` + - STATIC_STABILITY_DOC_URL); - const originalExpiration = credentials.originalExpiration ?? credentials.expiration; - return { - ...credentials, - ...(originalExpiration ? { originalExpiration } : {}), - expiration: newExpiration, - }; -}; - -const staticStabilityProvider = (provider, options = {}) => { - const logger = options?.logger || console; - let pastCredentials; - return async () => { - let credentials; - try { - credentials = await provider(); - if (credentials.expiration && credentials.expiration.getTime() < Date.now()) { - credentials = getExtendedInstanceMetadataCredentials(credentials, logger); - } - } - catch (e) { - if (pastCredentials) { - logger.warn("Credential renew failed: ", e); - credentials = getExtendedInstanceMetadataCredentials(pastCredentials, logger); - } - else { - throw e; - } - } - pastCredentials = credentials; - return credentials; - }; -}; - -const IMDS_PATH = "/latest/meta-data/iam/security-credentials/"; -const IMDS_TOKEN_PATH = "/latest/api/token"; -const AWS_EC2_METADATA_V1_DISABLED = "AWS_EC2_METADATA_V1_DISABLED"; -const PROFILE_AWS_EC2_METADATA_V1_DISABLED = "ec2_metadata_v1_disabled"; -const X_AWS_EC2_METADATA_TOKEN = "x-aws-ec2-metadata-token"; -const fromInstanceMetadata = (init = {}) => staticStabilityProvider(getInstanceMetadataProvider(init), { logger: init.logger }); -const getInstanceMetadataProvider = (init = {}) => { - let disableFetchToken = false; - const { logger, profile } = init; - const { timeout, maxRetries } = providerConfigFromInit(init); - const getCredentials = async (maxRetries, options) => { - const isImdsV1Fallback = disableFetchToken || options.headers?.[X_AWS_EC2_METADATA_TOKEN] == null; - if (isImdsV1Fallback) { - let fallbackBlockedFromProfile = false; - let fallbackBlockedFromProcessEnv = false; - const configValue = await nodeConfigProvider.loadConfig({ - environmentVariableSelector: (env) => { - const envValue = env[AWS_EC2_METADATA_V1_DISABLED]; - fallbackBlockedFromProcessEnv = !!envValue && envValue !== "false"; - if (envValue === undefined) { - throw new propertyProvider.CredentialsProviderError(`${AWS_EC2_METADATA_V1_DISABLED} not set in env, checking config file next.`, { logger: init.logger }); - } - return fallbackBlockedFromProcessEnv; - }, - configFileSelector: (profile) => { - const profileValue = profile[PROFILE_AWS_EC2_METADATA_V1_DISABLED]; - fallbackBlockedFromProfile = !!profileValue && profileValue !== "false"; - return fallbackBlockedFromProfile; - }, - default: false, - }, { - profile, - })(); - if (init.ec2MetadataV1Disabled || configValue) { - const causes = []; - if (init.ec2MetadataV1Disabled) - causes.push("credential provider initialization (runtime option ec2MetadataV1Disabled)"); - if (fallbackBlockedFromProfile) - causes.push(`config file profile (${PROFILE_AWS_EC2_METADATA_V1_DISABLED})`); - if (fallbackBlockedFromProcessEnv) - causes.push(`process environment variable (${AWS_EC2_METADATA_V1_DISABLED})`); - throw new InstanceMetadataV1FallbackError(`AWS EC2 Metadata v1 fallback has been blocked by AWS SDK configuration in the following: [${causes.join(", ")}].`); - } - } - const imdsProfile = (await retry(async () => { - let profile; - try { - profile = await getProfile(options); - } - catch (err) { - if (err.statusCode === 401) { - disableFetchToken = false; - } - throw err; - } - return profile; - }, maxRetries)).trim(); - return retry(async () => { - let creds; - try { - creds = await getCredentialsFromProfile(imdsProfile, options, init); - } - catch (err) { - if (err.statusCode === 401) { - disableFetchToken = false; - } - throw err; - } - return creds; - }, maxRetries); - }; - return async () => { - const endpoint = await getInstanceMetadataEndpoint(); - if (disableFetchToken) { - logger?.debug("AWS SDK Instance Metadata", "using v1 fallback (no token fetch)"); - return getCredentials(maxRetries, { ...endpoint, timeout }); - } - else { - let token; - try { - token = (await getMetadataToken({ ...endpoint, timeout })).toString(); - } - catch (error) { - if (error?.statusCode === 400) { - throw Object.assign(error, { - message: "EC2 Metadata token request returned error", - }); - } - else if (error.message === "TimeoutError" || [403, 404, 405].includes(error.statusCode)) { - disableFetchToken = true; - } - logger?.debug("AWS SDK Instance Metadata", "using v1 fallback (initial)"); - return getCredentials(maxRetries, { ...endpoint, timeout }); - } - return getCredentials(maxRetries, { - ...endpoint, - headers: { - [X_AWS_EC2_METADATA_TOKEN]: token, - }, - timeout, - }); - } - }; -}; -const getMetadataToken = async (options) => httpRequest({ - ...options, - path: IMDS_TOKEN_PATH, - method: "PUT", - headers: { - "x-aws-ec2-metadata-token-ttl-seconds": "21600", - }, -}); -const getProfile = async (options) => (await httpRequest({ ...options, path: IMDS_PATH })).toString(); -const getCredentialsFromProfile = async (profile, options, init) => { - const credentialsResponse = JSON.parse((await httpRequest({ - ...options, - path: IMDS_PATH + profile, - })).toString()); - if (!isImdsCredentials(credentialsResponse)) { - throw new propertyProvider.CredentialsProviderError("Invalid response received from instance metadata service.", { - logger: init.logger, - }); - } - return fromImdsCredentials(credentialsResponse); -}; - -exports.DEFAULT_MAX_RETRIES = DEFAULT_MAX_RETRIES; -exports.DEFAULT_TIMEOUT = DEFAULT_TIMEOUT; -exports.ENV_CMDS_AUTH_TOKEN = ENV_CMDS_AUTH_TOKEN; -exports.ENV_CMDS_FULL_URI = ENV_CMDS_FULL_URI; -exports.ENV_CMDS_RELATIVE_URI = ENV_CMDS_RELATIVE_URI; -exports.fromContainerMetadata = fromContainerMetadata; -exports.fromInstanceMetadata = fromInstanceMetadata; -exports.getInstanceMetadataEndpoint = getInstanceMetadataEndpoint; -exports.httpRequest = httpRequest; -exports.providerConfigFromInit = providerConfigFromInit; diff --git a/claude-code-source/node_modules/@smithy/eventstream-codec/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/eventstream-codec/dist-cjs/index.js deleted file mode 100644 index a17fea8d..00000000 --- a/claude-code-source/node_modules/@smithy/eventstream-codec/dist-cjs/index.js +++ /dev/null @@ -1,388 +0,0 @@ -'use strict'; - -var crc32 = require('@aws-crypto/crc32'); -var utilHexEncoding = require('@smithy/util-hex-encoding'); - -class Int64 { - bytes; - constructor(bytes) { - this.bytes = bytes; - if (bytes.byteLength !== 8) { - throw new Error("Int64 buffers must be exactly 8 bytes"); - } - } - static fromNumber(number) { - if (number > 9_223_372_036_854_775_807 || number < -9223372036854776e3) { - throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); - } - const bytes = new Uint8Array(8); - for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { - bytes[i] = remaining; - } - if (number < 0) { - negate(bytes); - } - return new Int64(bytes); - } - valueOf() { - const bytes = this.bytes.slice(0); - const negative = bytes[0] & 0b10000000; - if (negative) { - negate(bytes); - } - return parseInt(utilHexEncoding.toHex(bytes), 16) * (negative ? -1 : 1); - } - toString() { - return String(this.valueOf()); - } -} -function negate(bytes) { - for (let i = 0; i < 8; i++) { - bytes[i] ^= 0xff; - } - for (let i = 7; i > -1; i--) { - bytes[i]++; - if (bytes[i] !== 0) - break; - } -} - -class HeaderMarshaller { - toUtf8; - fromUtf8; - constructor(toUtf8, fromUtf8) { - this.toUtf8 = toUtf8; - this.fromUtf8 = fromUtf8; - } - format(headers) { - const chunks = []; - for (const headerName of Object.keys(headers)) { - const bytes = this.fromUtf8(headerName); - chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); - } - const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); - let position = 0; - for (const chunk of chunks) { - out.set(chunk, position); - position += chunk.byteLength; - } - return out; - } - formatHeaderValue(header) { - switch (header.type) { - case "boolean": - return Uint8Array.from([header.value ? 0 : 1]); - case "byte": - return Uint8Array.from([2, header.value]); - case "short": - const shortView = new DataView(new ArrayBuffer(3)); - shortView.setUint8(0, 3); - shortView.setInt16(1, header.value, false); - return new Uint8Array(shortView.buffer); - case "integer": - const intView = new DataView(new ArrayBuffer(5)); - intView.setUint8(0, 4); - intView.setInt32(1, header.value, false); - return new Uint8Array(intView.buffer); - case "long": - const longBytes = new Uint8Array(9); - longBytes[0] = 5; - longBytes.set(header.value.bytes, 1); - return longBytes; - case "binary": - const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); - binView.setUint8(0, 6); - binView.setUint16(1, header.value.byteLength, false); - const binBytes = new Uint8Array(binView.buffer); - binBytes.set(header.value, 3); - return binBytes; - case "string": - const utf8Bytes = this.fromUtf8(header.value); - const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); - strView.setUint8(0, 7); - strView.setUint16(1, utf8Bytes.byteLength, false); - const strBytes = new Uint8Array(strView.buffer); - strBytes.set(utf8Bytes, 3); - return strBytes; - case "timestamp": - const tsBytes = new Uint8Array(9); - tsBytes[0] = 8; - tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); - return tsBytes; - case "uuid": - if (!UUID_PATTERN.test(header.value)) { - throw new Error(`Invalid UUID received: ${header.value}`); - } - const uuidBytes = new Uint8Array(17); - uuidBytes[0] = 9; - uuidBytes.set(utilHexEncoding.fromHex(header.value.replace(/\-/g, "")), 1); - return uuidBytes; - } - } - parse(headers) { - const out = {}; - let position = 0; - while (position < headers.byteLength) { - const nameLength = headers.getUint8(position++); - const name = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, nameLength)); - position += nameLength; - switch (headers.getUint8(position++)) { - case 0: - out[name] = { - type: BOOLEAN_TAG, - value: true, - }; - break; - case 1: - out[name] = { - type: BOOLEAN_TAG, - value: false, - }; - break; - case 2: - out[name] = { - type: BYTE_TAG, - value: headers.getInt8(position++), - }; - break; - case 3: - out[name] = { - type: SHORT_TAG, - value: headers.getInt16(position, false), - }; - position += 2; - break; - case 4: - out[name] = { - type: INT_TAG, - value: headers.getInt32(position, false), - }; - position += 4; - break; - case 5: - out[name] = { - type: LONG_TAG, - value: new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)), - }; - position += 8; - break; - case 6: - const binaryLength = headers.getUint16(position, false); - position += 2; - out[name] = { - type: BINARY_TAG, - value: new Uint8Array(headers.buffer, headers.byteOffset + position, binaryLength), - }; - position += binaryLength; - break; - case 7: - const stringLength = headers.getUint16(position, false); - position += 2; - out[name] = { - type: STRING_TAG, - value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, stringLength)), - }; - position += stringLength; - break; - case 8: - out[name] = { - type: TIMESTAMP_TAG, - value: new Date(new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)).valueOf()), - }; - position += 8; - break; - case 9: - const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position, 16); - position += 16; - out[name] = { - type: UUID_TAG, - value: `${utilHexEncoding.toHex(uuidBytes.subarray(0, 4))}-${utilHexEncoding.toHex(uuidBytes.subarray(4, 6))}-${utilHexEncoding.toHex(uuidBytes.subarray(6, 8))}-${utilHexEncoding.toHex(uuidBytes.subarray(8, 10))}-${utilHexEncoding.toHex(uuidBytes.subarray(10))}`, - }; - break; - default: - throw new Error(`Unrecognized header type tag`); - } - } - return out; - } -} -const BOOLEAN_TAG = "boolean"; -const BYTE_TAG = "byte"; -const SHORT_TAG = "short"; -const INT_TAG = "integer"; -const LONG_TAG = "long"; -const BINARY_TAG = "binary"; -const STRING_TAG = "string"; -const TIMESTAMP_TAG = "timestamp"; -const UUID_TAG = "uuid"; -const UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; - -const PRELUDE_MEMBER_LENGTH = 4; -const PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2; -const CHECKSUM_LENGTH = 4; -const MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + CHECKSUM_LENGTH * 2; -function splitMessage({ byteLength, byteOffset, buffer }) { - if (byteLength < MINIMUM_MESSAGE_LENGTH) { - throw new Error("Provided message too short to accommodate event stream message overhead"); - } - const view = new DataView(buffer, byteOffset, byteLength); - const messageLength = view.getUint32(0, false); - if (byteLength !== messageLength) { - throw new Error("Reported message length does not match received message length"); - } - const headerLength = view.getUint32(PRELUDE_MEMBER_LENGTH, false); - const expectedPreludeChecksum = view.getUint32(PRELUDE_LENGTH, false); - const expectedMessageChecksum = view.getUint32(byteLength - CHECKSUM_LENGTH, false); - const checksummer = new crc32.Crc32().update(new Uint8Array(buffer, byteOffset, PRELUDE_LENGTH)); - if (expectedPreludeChecksum !== checksummer.digest()) { - throw new Error(`The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})`); - } - checksummer.update(new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH, byteLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH))); - if (expectedMessageChecksum !== checksummer.digest()) { - throw new Error(`The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}`); - } - return { - headers: new DataView(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH, headerLength), - body: new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH + headerLength, messageLength - headerLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH + CHECKSUM_LENGTH)), - }; -} - -class EventStreamCodec { - headerMarshaller; - messageBuffer; - isEndOfStream; - constructor(toUtf8, fromUtf8) { - this.headerMarshaller = new HeaderMarshaller(toUtf8, fromUtf8); - this.messageBuffer = []; - this.isEndOfStream = false; - } - feed(message) { - this.messageBuffer.push(this.decode(message)); - } - endOfStream() { - this.isEndOfStream = true; - } - getMessage() { - const message = this.messageBuffer.pop(); - const isEndOfStream = this.isEndOfStream; - return { - getMessage() { - return message; - }, - isEndOfStream() { - return isEndOfStream; - }, - }; - } - getAvailableMessages() { - const messages = this.messageBuffer; - this.messageBuffer = []; - const isEndOfStream = this.isEndOfStream; - return { - getMessages() { - return messages; - }, - isEndOfStream() { - return isEndOfStream; - }, - }; - } - encode({ headers: rawHeaders, body }) { - const headers = this.headerMarshaller.format(rawHeaders); - const length = headers.byteLength + body.byteLength + 16; - const out = new Uint8Array(length); - const view = new DataView(out.buffer, out.byteOffset, out.byteLength); - const checksum = new crc32.Crc32(); - view.setUint32(0, length, false); - view.setUint32(4, headers.byteLength, false); - view.setUint32(8, checksum.update(out.subarray(0, 8)).digest(), false); - out.set(headers, 12); - out.set(body, headers.byteLength + 12); - view.setUint32(length - 4, checksum.update(out.subarray(8, length - 4)).digest(), false); - return out; - } - decode(message) { - const { headers, body } = splitMessage(message); - return { headers: this.headerMarshaller.parse(headers), body }; - } - formatHeaders(rawHeaders) { - return this.headerMarshaller.format(rawHeaders); - } -} - -class MessageDecoderStream { - options; - constructor(options) { - this.options = options; - } - [Symbol.asyncIterator]() { - return this.asyncIterator(); - } - async *asyncIterator() { - for await (const bytes of this.options.inputStream) { - const decoded = this.options.decoder.decode(bytes); - yield decoded; - } - } -} - -class MessageEncoderStream { - options; - constructor(options) { - this.options = options; - } - [Symbol.asyncIterator]() { - return this.asyncIterator(); - } - async *asyncIterator() { - for await (const msg of this.options.messageStream) { - const encoded = this.options.encoder.encode(msg); - yield encoded; - } - if (this.options.includeEndFrame) { - yield new Uint8Array(0); - } - } -} - -class SmithyMessageDecoderStream { - options; - constructor(options) { - this.options = options; - } - [Symbol.asyncIterator]() { - return this.asyncIterator(); - } - async *asyncIterator() { - for await (const message of this.options.messageStream) { - const deserialized = await this.options.deserializer(message); - if (deserialized === undefined) - continue; - yield deserialized; - } - } -} - -class SmithyMessageEncoderStream { - options; - constructor(options) { - this.options = options; - } - [Symbol.asyncIterator]() { - return this.asyncIterator(); - } - async *asyncIterator() { - for await (const chunk of this.options.inputStream) { - const payloadBuf = this.options.serializer(chunk); - yield payloadBuf; - } - } -} - -exports.EventStreamCodec = EventStreamCodec; -exports.HeaderMarshaller = HeaderMarshaller; -exports.Int64 = Int64; -exports.MessageDecoderStream = MessageDecoderStream; -exports.MessageEncoderStream = MessageEncoderStream; -exports.SmithyMessageDecoderStream = SmithyMessageDecoderStream; -exports.SmithyMessageEncoderStream = SmithyMessageEncoderStream; diff --git a/claude-code-source/node_modules/@smithy/eventstream-codec/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/eventstream-codec/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js deleted file mode 100644 index 6d1eb2d1..00000000 --- a/claude-code-source/node_modules/@smithy/eventstream-codec/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -const SHORT_TO_HEX = {}; -const HEX_TO_SHORT = {}; -for (let i = 0; i < 256; i++) { - let encodedByte = i.toString(16).toLowerCase(); - if (encodedByte.length === 1) { - encodedByte = `0${encodedByte}`; - } - SHORT_TO_HEX[i] = encodedByte; - HEX_TO_SHORT[encodedByte] = i; -} -function fromHex(encoded) { - if (encoded.length % 2 !== 0) { - throw new Error("Hex encoded strings must have an even number length"); - } - const out = new Uint8Array(encoded.length / 2); - for (let i = 0; i < encoded.length; i += 2) { - const encodedByte = encoded.slice(i, i + 2).toLowerCase(); - if (encodedByte in HEX_TO_SHORT) { - out[i / 2] = HEX_TO_SHORT[encodedByte]; - } - else { - throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); - } - } - return out; -} -function toHex(bytes) { - let out = ""; - for (let i = 0; i < bytes.byteLength; i++) { - out += SHORT_TO_HEX[bytes[i]]; - } - return out; -} - -exports.fromHex = fromHex; -exports.toHex = toHex; diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-browser/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/eventstream-serde-browser/dist-cjs/index.js deleted file mode 100644 index b3f5190d..00000000 --- a/claude-code-source/node_modules/@smithy/eventstream-serde-browser/dist-cjs/index.js +++ /dev/null @@ -1,58 +0,0 @@ -'use strict'; - -var eventstreamSerdeUniversal = require('@smithy/eventstream-serde-universal'); - -const readableStreamtoIterable = (readableStream) => ({ - [Symbol.asyncIterator]: async function* () { - const reader = readableStream.getReader(); - try { - while (true) { - const { done, value } = await reader.read(); - if (done) - return; - yield value; - } - } - finally { - reader.releaseLock(); - } - }, -}); -const iterableToReadableStream = (asyncIterable) => { - const iterator = asyncIterable[Symbol.asyncIterator](); - return new ReadableStream({ - async pull(controller) { - const { done, value } = await iterator.next(); - if (done) { - return controller.close(); - } - controller.enqueue(value); - }, - }); -}; - -class EventStreamMarshaller { - universalMarshaller; - constructor({ utf8Encoder, utf8Decoder }) { - this.universalMarshaller = new eventstreamSerdeUniversal.EventStreamMarshaller({ - utf8Decoder, - utf8Encoder, - }); - } - deserialize(body, deserializer) { - const bodyIterable = isReadableStream(body) ? readableStreamtoIterable(body) : body; - return this.universalMarshaller.deserialize(bodyIterable, deserializer); - } - serialize(input, serializer) { - const serialziedIterable = this.universalMarshaller.serialize(input, serializer); - return typeof ReadableStream === "function" ? iterableToReadableStream(serialziedIterable) : serialziedIterable; - } -} -const isReadableStream = (body) => typeof ReadableStream === "function" && body instanceof ReadableStream; - -const eventStreamSerdeProvider = (options) => new EventStreamMarshaller(options); - -exports.EventStreamMarshaller = EventStreamMarshaller; -exports.eventStreamSerdeProvider = eventStreamSerdeProvider; -exports.iterableToReadableStream = iterableToReadableStream; -exports.readableStreamtoIterable = readableStreamtoIterable; diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-browser/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/eventstream-serde-browser/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js deleted file mode 100644 index cd84e7bd..00000000 --- a/claude-code-source/node_modules/@smithy/eventstream-serde-browser/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js +++ /dev/null @@ -1,132 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-config-resolver/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/eventstream-serde-config-resolver/dist-cjs/index.js deleted file mode 100644 index ea364463..00000000 --- a/claude-code-source/node_modules/@smithy/eventstream-serde-config-resolver/dist-cjs/index.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict'; - -const resolveEventStreamSerdeConfig = (input) => Object.assign(input, { - eventStreamMarshaller: input.eventStreamSerdeProvider(input), -}); - -exports.resolveEventStreamSerdeConfig = resolveEventStreamSerdeConfig; diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js deleted file mode 100644 index 63ca94de..00000000 --- a/claude-code-source/node_modules/@smithy/eventstream-serde-node/dist-cjs/index.js +++ /dev/null @@ -1,88 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - EventStreamMarshaller: () => EventStreamMarshaller, - eventStreamSerdeProvider: () => eventStreamSerdeProvider -}); -module.exports = __toCommonJS(src_exports); - -// src/EventStreamMarshaller.ts -var import_eventstream_serde_universal = require("@smithy/eventstream-serde-universal"); -var import_stream = require("stream"); - -// src/utils.ts -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; - } -} -__name(readabletoIterable, "readabletoIterable"); - -// src/EventStreamMarshaller.ts -var _EventStreamMarshaller = class _EventStreamMarshaller { - constructor({ utf8Encoder, utf8Decoder }) { - this.universalMarshaller = new import_eventstream_serde_universal.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 import_stream.Readable.from(this.universalMarshaller.serialize(input, serializer)); - } -}; -__name(_EventStreamMarshaller, "EventStreamMarshaller"); -var EventStreamMarshaller = _EventStreamMarshaller; - -// src/provider.ts -var eventStreamSerdeProvider = /* @__PURE__ */ __name((options) => new EventStreamMarshaller(options), "eventStreamSerdeProvider"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - EventStreamMarshaller, - eventStreamSerdeProvider -}); - diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js deleted file mode 100644 index 00eda6f2..00000000 --- a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/dist-cjs/index.js +++ /dev/null @@ -1,182 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - EventStreamMarshaller: () => EventStreamMarshaller, - eventStreamSerdeProvider: () => eventStreamSerdeProvider -}); -module.exports = __toCommonJS(src_exports); - -// src/EventStreamMarshaller.ts -var import_eventstream_codec = require("@smithy/eventstream-codec"); - -// src/getChunkedStream.ts -function getChunkedStream(source) { - let currentMessageTotalLength = 0; - let currentMessagePendingLength = 0; - let currentMessage = null; - let messageLengthBuffer = null; - const allocateMessage = /* @__PURE__ */ __name((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); - }, "allocateMessage"); - const iterator = /* @__PURE__ */ __name(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, - // remaining bytes to fill the messageLengthBuffer - bytesRemaining - // bytes left in chunk - ); - messageLengthBuffer.set( - // @ts-ignore error TS2532: Object is possibly 'undefined' for value - 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, - // number of bytes left to complete message - chunkLength - currentOffset - // number of bytes left in the original chunk - ); - currentMessage.set( - // @ts-ignore error TS2532: Object is possibly 'undefined' for value - value.slice(currentOffset, currentOffset + numBytesToWrite), - currentMessagePendingLength - ); - currentMessagePendingLength += numBytesToWrite; - currentOffset += numBytesToWrite; - if (currentMessageTotalLength && currentMessageTotalLength === currentMessagePendingLength) { - yield currentMessage; - currentMessage = null; - currentMessageTotalLength = 0; - currentMessagePendingLength = 0; - } - } - } - }, "iterator"); - return { - [Symbol.asyncIterator]: iterator - }; -} -__name(getChunkedStream, "getChunkedStream"); - -// src/getUnmarshalledStream.ts -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}`); - } - }; -} -__name(getMessageUnmarshaller, "getMessageUnmarshaller"); - -// src/EventStreamMarshaller.ts -var _EventStreamMarshaller = class _EventStreamMarshaller { - constructor({ utf8Encoder, utf8Decoder }) { - this.eventStreamCodec = new import_eventstream_codec.EventStreamCodec(utf8Encoder, utf8Decoder); - this.utfEncoder = utf8Encoder; - } - deserialize(body, deserializer) { - const inputStream = getChunkedStream(body); - return new import_eventstream_codec.SmithyMessageDecoderStream({ - messageStream: new import_eventstream_codec.MessageDecoderStream({ inputStream, decoder: this.eventStreamCodec }), - // @ts-expect-error Type 'T' is not assignable to type 'Record' - deserializer: getMessageUnmarshaller(deserializer, this.utfEncoder) - }); - } - serialize(inputStream, serializer) { - return new import_eventstream_codec.MessageEncoderStream({ - messageStream: new import_eventstream_codec.SmithyMessageEncoderStream({ inputStream, serializer }), - encoder: this.eventStreamCodec, - includeEndFrame: true - }); - } -}; -__name(_EventStreamMarshaller, "EventStreamMarshaller"); -var EventStreamMarshaller = _EventStreamMarshaller; - -// src/provider.ts -var eventStreamSerdeProvider = /* @__PURE__ */ __name((options) => new EventStreamMarshaller(options), "eventStreamSerdeProvider"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - EventStreamMarshaller, - eventStreamSerdeProvider -}); - diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/dist-cjs/index.js deleted file mode 100644 index fac5c933..00000000 --- a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/dist-cjs/index.js +++ /dev/null @@ -1,468 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - EventStreamCodec: () => EventStreamCodec, - HeaderMarshaller: () => HeaderMarshaller, - Int64: () => Int64, - MessageDecoderStream: () => MessageDecoderStream, - MessageEncoderStream: () => MessageEncoderStream, - SmithyMessageDecoderStream: () => SmithyMessageDecoderStream, - SmithyMessageEncoderStream: () => SmithyMessageEncoderStream -}); -module.exports = __toCommonJS(src_exports); - -// src/EventStreamCodec.ts -var import_crc322 = require("@aws-crypto/crc32"); - -// src/HeaderMarshaller.ts - - -// src/Int64.ts -var import_util_hex_encoding = require("@smithy/util-hex-encoding"); -var _Int64 = class _Int64 { - constructor(bytes) { - this.bytes = bytes; - if (bytes.byteLength !== 8) { - throw new Error("Int64 buffers must be exactly 8 bytes"); - } - } - static fromNumber(number) { - if (number > 9223372036854776e3 || number < -9223372036854776e3) { - throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); - } - const bytes = new Uint8Array(8); - for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { - bytes[i] = remaining; - } - if (number < 0) { - negate(bytes); - } - return new _Int64(bytes); - } - /** - * Called implicitly by infix arithmetic operators. - */ - valueOf() { - const bytes = this.bytes.slice(0); - const negative = bytes[0] & 128; - if (negative) { - negate(bytes); - } - return parseInt((0, import_util_hex_encoding.toHex)(bytes), 16) * (negative ? -1 : 1); - } - toString() { - return String(this.valueOf()); - } -}; -__name(_Int64, "Int64"); -var Int64 = _Int64; -function negate(bytes) { - for (let i = 0; i < 8; i++) { - bytes[i] ^= 255; - } - for (let i = 7; i > -1; i--) { - bytes[i]++; - if (bytes[i] !== 0) - break; - } -} -__name(negate, "negate"); - -// src/HeaderMarshaller.ts -var _HeaderMarshaller = class _HeaderMarshaller { - constructor(toUtf8, fromUtf8) { - this.toUtf8 = toUtf8; - this.fromUtf8 = fromUtf8; - } - format(headers) { - const chunks = []; - for (const headerName of Object.keys(headers)) { - const bytes = this.fromUtf8(headerName); - chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); - } - const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); - let position = 0; - for (const chunk of chunks) { - out.set(chunk, position); - position += chunk.byteLength; - } - return out; - } - formatHeaderValue(header) { - switch (header.type) { - case "boolean": - return Uint8Array.from([header.value ? 0 /* boolTrue */ : 1 /* boolFalse */]); - case "byte": - return Uint8Array.from([2 /* byte */, header.value]); - case "short": - const shortView = new DataView(new ArrayBuffer(3)); - shortView.setUint8(0, 3 /* short */); - shortView.setInt16(1, header.value, false); - return new Uint8Array(shortView.buffer); - case "integer": - const intView = new DataView(new ArrayBuffer(5)); - intView.setUint8(0, 4 /* integer */); - intView.setInt32(1, header.value, false); - return new Uint8Array(intView.buffer); - case "long": - const longBytes = new Uint8Array(9); - longBytes[0] = 5 /* long */; - longBytes.set(header.value.bytes, 1); - return longBytes; - case "binary": - const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); - binView.setUint8(0, 6 /* byteArray */); - binView.setUint16(1, header.value.byteLength, false); - const binBytes = new Uint8Array(binView.buffer); - binBytes.set(header.value, 3); - return binBytes; - case "string": - const utf8Bytes = this.fromUtf8(header.value); - const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); - strView.setUint8(0, 7 /* string */); - strView.setUint16(1, utf8Bytes.byteLength, false); - const strBytes = new Uint8Array(strView.buffer); - strBytes.set(utf8Bytes, 3); - return strBytes; - case "timestamp": - const tsBytes = new Uint8Array(9); - tsBytes[0] = 8 /* timestamp */; - tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); - return tsBytes; - case "uuid": - if (!UUID_PATTERN.test(header.value)) { - throw new Error(`Invalid UUID received: ${header.value}`); - } - const uuidBytes = new Uint8Array(17); - uuidBytes[0] = 9 /* uuid */; - uuidBytes.set((0, import_util_hex_encoding.fromHex)(header.value.replace(/\-/g, "")), 1); - return uuidBytes; - } - } - parse(headers) { - const out = {}; - let position = 0; - while (position < headers.byteLength) { - const nameLength = headers.getUint8(position++); - const name = this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, nameLength)); - position += nameLength; - switch (headers.getUint8(position++)) { - case 0 /* boolTrue */: - out[name] = { - type: BOOLEAN_TAG, - value: true - }; - break; - case 1 /* boolFalse */: - out[name] = { - type: BOOLEAN_TAG, - value: false - }; - break; - case 2 /* byte */: - out[name] = { - type: BYTE_TAG, - value: headers.getInt8(position++) - }; - break; - case 3 /* short */: - out[name] = { - type: SHORT_TAG, - value: headers.getInt16(position, false) - }; - position += 2; - break; - case 4 /* integer */: - out[name] = { - type: INT_TAG, - value: headers.getInt32(position, false) - }; - position += 4; - break; - case 5 /* long */: - out[name] = { - type: LONG_TAG, - value: new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)) - }; - position += 8; - break; - case 6 /* byteArray */: - const binaryLength = headers.getUint16(position, false); - position += 2; - out[name] = { - type: BINARY_TAG, - value: new Uint8Array(headers.buffer, headers.byteOffset + position, binaryLength) - }; - position += binaryLength; - break; - case 7 /* string */: - const stringLength = headers.getUint16(position, false); - position += 2; - out[name] = { - type: STRING_TAG, - value: this.toUtf8(new Uint8Array(headers.buffer, headers.byteOffset + position, stringLength)) - }; - position += stringLength; - break; - case 8 /* timestamp */: - out[name] = { - type: TIMESTAMP_TAG, - value: new Date(new Int64(new Uint8Array(headers.buffer, headers.byteOffset + position, 8)).valueOf()) - }; - position += 8; - break; - case 9 /* uuid */: - const uuidBytes = new Uint8Array(headers.buffer, headers.byteOffset + position, 16); - position += 16; - out[name] = { - type: UUID_TAG, - value: `${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(0, 4))}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(4, 6))}-${(0, import_util_hex_encoding.toHex)( - uuidBytes.subarray(6, 8) - )}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(8, 10))}-${(0, import_util_hex_encoding.toHex)(uuidBytes.subarray(10))}` - }; - break; - default: - throw new Error(`Unrecognized header type tag`); - } - } - return out; - } -}; -__name(_HeaderMarshaller, "HeaderMarshaller"); -var HeaderMarshaller = _HeaderMarshaller; -var BOOLEAN_TAG = "boolean"; -var BYTE_TAG = "byte"; -var SHORT_TAG = "short"; -var INT_TAG = "integer"; -var LONG_TAG = "long"; -var BINARY_TAG = "binary"; -var STRING_TAG = "string"; -var TIMESTAMP_TAG = "timestamp"; -var UUID_TAG = "uuid"; -var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; - -// src/splitMessage.ts -var import_crc32 = require("@aws-crypto/crc32"); -var PRELUDE_MEMBER_LENGTH = 4; -var PRELUDE_LENGTH = PRELUDE_MEMBER_LENGTH * 2; -var CHECKSUM_LENGTH = 4; -var MINIMUM_MESSAGE_LENGTH = PRELUDE_LENGTH + CHECKSUM_LENGTH * 2; -function splitMessage({ byteLength, byteOffset, buffer }) { - if (byteLength < MINIMUM_MESSAGE_LENGTH) { - throw new Error("Provided message too short to accommodate event stream message overhead"); - } - const view = new DataView(buffer, byteOffset, byteLength); - const messageLength = view.getUint32(0, false); - if (byteLength !== messageLength) { - throw new Error("Reported message length does not match received message length"); - } - const headerLength = view.getUint32(PRELUDE_MEMBER_LENGTH, false); - const expectedPreludeChecksum = view.getUint32(PRELUDE_LENGTH, false); - const expectedMessageChecksum = view.getUint32(byteLength - CHECKSUM_LENGTH, false); - const checksummer = new import_crc32.Crc32().update(new Uint8Array(buffer, byteOffset, PRELUDE_LENGTH)); - if (expectedPreludeChecksum !== checksummer.digest()) { - throw new Error( - `The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})` - ); - } - checksummer.update( - new Uint8Array(buffer, byteOffset + PRELUDE_LENGTH, byteLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH)) - ); - if (expectedMessageChecksum !== checksummer.digest()) { - throw new Error( - `The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}` - ); - } - return { - headers: new DataView(buffer, byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH, headerLength), - body: new Uint8Array( - buffer, - byteOffset + PRELUDE_LENGTH + CHECKSUM_LENGTH + headerLength, - messageLength - headerLength - (PRELUDE_LENGTH + CHECKSUM_LENGTH + CHECKSUM_LENGTH) - ) - }; -} -__name(splitMessage, "splitMessage"); - -// src/EventStreamCodec.ts -var _EventStreamCodec = class _EventStreamCodec { - constructor(toUtf8, fromUtf8) { - this.headerMarshaller = new HeaderMarshaller(toUtf8, fromUtf8); - this.messageBuffer = []; - this.isEndOfStream = false; - } - feed(message) { - this.messageBuffer.push(this.decode(message)); - } - endOfStream() { - this.isEndOfStream = true; - } - getMessage() { - const message = this.messageBuffer.pop(); - const isEndOfStream = this.isEndOfStream; - return { - getMessage() { - return message; - }, - isEndOfStream() { - return isEndOfStream; - } - }; - } - getAvailableMessages() { - const messages = this.messageBuffer; - this.messageBuffer = []; - const isEndOfStream = this.isEndOfStream; - return { - getMessages() { - return messages; - }, - isEndOfStream() { - return isEndOfStream; - } - }; - } - /** - * Convert a structured JavaScript object with tagged headers into a binary - * event stream message. - */ - encode({ headers: rawHeaders, body }) { - const headers = this.headerMarshaller.format(rawHeaders); - const length = headers.byteLength + body.byteLength + 16; - const out = new Uint8Array(length); - const view = new DataView(out.buffer, out.byteOffset, out.byteLength); - const checksum = new import_crc322.Crc32(); - view.setUint32(0, length, false); - view.setUint32(4, headers.byteLength, false); - view.setUint32(8, checksum.update(out.subarray(0, 8)).digest(), false); - out.set(headers, 12); - out.set(body, headers.byteLength + 12); - view.setUint32(length - 4, checksum.update(out.subarray(8, length - 4)).digest(), false); - return out; - } - /** - * Convert a binary event stream message into a JavaScript object with an - * opaque, binary body and tagged, parsed headers. - */ - decode(message) { - const { headers, body } = splitMessage(message); - return { headers: this.headerMarshaller.parse(headers), body }; - } - /** - * Convert a structured JavaScript object with tagged headers into a binary - * event stream message header. - */ - formatHeaders(rawHeaders) { - return this.headerMarshaller.format(rawHeaders); - } -}; -__name(_EventStreamCodec, "EventStreamCodec"); -var EventStreamCodec = _EventStreamCodec; - -// src/MessageDecoderStream.ts -var _MessageDecoderStream = class _MessageDecoderStream { - constructor(options) { - this.options = options; - } - [Symbol.asyncIterator]() { - return this.asyncIterator(); - } - async *asyncIterator() { - for await (const bytes of this.options.inputStream) { - const decoded = this.options.decoder.decode(bytes); - yield decoded; - } - } -}; -__name(_MessageDecoderStream, "MessageDecoderStream"); -var MessageDecoderStream = _MessageDecoderStream; - -// src/MessageEncoderStream.ts -var _MessageEncoderStream = class _MessageEncoderStream { - constructor(options) { - this.options = options; - } - [Symbol.asyncIterator]() { - return this.asyncIterator(); - } - async *asyncIterator() { - for await (const msg of this.options.messageStream) { - const encoded = this.options.encoder.encode(msg); - yield encoded; - } - if (this.options.includeEndFrame) { - yield new Uint8Array(0); - } - } -}; -__name(_MessageEncoderStream, "MessageEncoderStream"); -var MessageEncoderStream = _MessageEncoderStream; - -// src/SmithyMessageDecoderStream.ts -var _SmithyMessageDecoderStream = class _SmithyMessageDecoderStream { - constructor(options) { - this.options = options; - } - [Symbol.asyncIterator]() { - return this.asyncIterator(); - } - async *asyncIterator() { - for await (const message of this.options.messageStream) { - const deserialized = await this.options.deserializer(message); - if (deserialized === void 0) - continue; - yield deserialized; - } - } -}; -__name(_SmithyMessageDecoderStream, "SmithyMessageDecoderStream"); -var SmithyMessageDecoderStream = _SmithyMessageDecoderStream; - -// src/SmithyMessageEncoderStream.ts -var _SmithyMessageEncoderStream = class _SmithyMessageEncoderStream { - constructor(options) { - this.options = options; - } - [Symbol.asyncIterator]() { - return this.asyncIterator(); - } - async *asyncIterator() { - for await (const chunk of this.options.inputStream) { - const payloadBuf = this.options.serializer(chunk); - yield payloadBuf; - } - } -}; -__name(_SmithyMessageEncoderStream, "SmithyMessageEncoderStream"); -var SmithyMessageEncoderStream = _SmithyMessageEncoderStream; -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - EventStreamCodec, - HeaderMarshaller, - Int64, - MessageDecoderStream, - MessageEncoderStream, - SmithyMessageDecoderStream, - SmithyMessageEncoderStream -}); - diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/build/aws_crc32.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/build/aws_crc32.js deleted file mode 100644 index 09c304cd..00000000 --- a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/build/aws_crc32.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AwsCrc32 = void 0; -var tslib_1 = require("tslib"); -var util_1 = require("@aws-crypto/util"); -var index_1 = require("./index"); -var AwsCrc32 = /** @class */ (function () { - function AwsCrc32() { - this.crc32 = new index_1.Crc32(); - } - AwsCrc32.prototype.update = function (toHash) { - if ((0, util_1.isEmptyData)(toHash)) - return; - this.crc32.update((0, util_1.convertToBuffer)(toHash)); - }; - AwsCrc32.prototype.digest = function () { - return tslib_1.__awaiter(this, void 0, void 0, function () { - return tslib_1.__generator(this, function (_a) { - return [2 /*return*/, (0, util_1.numToUint8)(this.crc32.digest())]; - }); - }); - }; - AwsCrc32.prototype.reset = function () { - this.crc32 = new index_1.Crc32(); - }; - return AwsCrc32; -}()); -exports.AwsCrc32 = AwsCrc32; -//# sourceMappingURL=aws_crc32.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/build/index.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/build/index.js deleted file mode 100644 index fa789688..00000000 --- a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/build/index.js +++ /dev/null @@ -1,108 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AwsCrc32 = exports.Crc32 = exports.crc32 = void 0; -var tslib_1 = require("tslib"); -var util_1 = require("@aws-crypto/util"); -function crc32(data) { - return new Crc32().update(data).digest(); -} -exports.crc32 = crc32; -var Crc32 = /** @class */ (function () { - function Crc32() { - this.checksum = 0xffffffff; - } - Crc32.prototype.update = function (data) { - var e_1, _a; - try { - for (var data_1 = tslib_1.__values(data), data_1_1 = data_1.next(); !data_1_1.done; data_1_1 = data_1.next()) { - var byte = data_1_1.value; - this.checksum = - (this.checksum >>> 8) ^ lookupTable[(this.checksum ^ byte) & 0xff]; - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (data_1_1 && !data_1_1.done && (_a = data_1.return)) _a.call(data_1); - } - finally { if (e_1) throw e_1.error; } - } - return this; - }; - Crc32.prototype.digest = function () { - return (this.checksum ^ 0xffffffff) >>> 0; - }; - return Crc32; -}()); -exports.Crc32 = Crc32; -// prettier-ignore -var a_lookUpTable = [ - 0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, - 0x076DC419, 0x706AF48F, 0xE963A535, 0x9E6495A3, - 0x0EDB8832, 0x79DCB8A4, 0xE0D5E91E, 0x97D2D988, - 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07, 0x90BF1D91, - 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE, - 0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, - 0x136C9856, 0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, - 0x14015C4F, 0x63066CD9, 0xFA0F3D63, 0x8D080DF5, - 0x3B6E20C8, 0x4C69105E, 0xD56041E4, 0xA2677172, - 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B, - 0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, - 0x32D86CE3, 0x45DF5C75, 0xDCD60DCF, 0xABD13D59, - 0x26D930AC, 0x51DE003A, 0xC8D75180, 0xBFD06116, - 0x21B4F4B5, 0x56B3C423, 0xCFBA9599, 0xB8BDA50F, - 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924, - 0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, - 0x76DC4190, 0x01DB7106, 0x98D220BC, 0xEFD5102A, - 0x71B18589, 0x06B6B51F, 0x9FBFE4A5, 0xE8B8D433, - 0x7807C9A2, 0x0F00F934, 0x9609A88E, 0xE10E9818, - 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01, - 0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, - 0x6C0695ED, 0x1B01A57B, 0x8208F4C1, 0xF50FC457, - 0x65B0D9C6, 0x12B7E950, 0x8BBEB8EA, 0xFCB9887C, - 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3, 0xFBD44C65, - 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2, - 0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, - 0x4369E96A, 0x346ED9FC, 0xAD678846, 0xDA60B8D0, - 0x44042D73, 0x33031DE5, 0xAA0A4C5F, 0xDD0D7CC9, - 0x5005713C, 0x270241AA, 0xBE0B1010, 0xC90C2086, - 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F, - 0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, - 0x59B33D17, 0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, - 0xEDB88320, 0x9ABFB3B6, 0x03B6E20C, 0x74B1D29A, - 0xEAD54739, 0x9DD277AF, 0x04DB2615, 0x73DC1683, - 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8, - 0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, - 0xF00F9344, 0x8708A3D2, 0x1E01F268, 0x6906C2FE, - 0xF762575D, 0x806567CB, 0x196C3671, 0x6E6B06E7, - 0xFED41B76, 0x89D32BE0, 0x10DA7A5A, 0x67DD4ACC, - 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5, - 0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, - 0xD1BB67F1, 0xA6BC5767, 0x3FB506DD, 0x48B2364B, - 0xD80D2BDA, 0xAF0A1B4C, 0x36034AF6, 0x41047A60, - 0xDF60EFC3, 0xA867DF55, 0x316E8EEF, 0x4669BE79, - 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236, - 0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, - 0xC5BA3BBE, 0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, - 0xC2D7FFA7, 0xB5D0CF31, 0x2CD99E8B, 0x5BDEAE1D, - 0x9B64C2B0, 0xEC63F226, 0x756AA39C, 0x026D930A, - 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713, - 0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, - 0x92D28E9B, 0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, - 0x86D3D2D4, 0xF1D4E242, 0x68DDB3F8, 0x1FDA836E, - 0x81BE16CD, 0xF6B9265B, 0x6FB077E1, 0x18B74777, - 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C, - 0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, - 0xA00AE278, 0xD70DD2EE, 0x4E048354, 0x3903B3C2, - 0xA7672661, 0xD06016F7, 0x4969474D, 0x3E6E77DB, - 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66, 0x37D83BF0, - 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9, - 0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, - 0xBAD03605, 0xCDD70693, 0x54DE5729, 0x23D967BF, - 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, - 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D, -]; -var lookupTable = (0, util_1.uint32ArrayFrom)(a_lookUpTable); -var aws_crc32_1 = require("./aws_crc32"); -Object.defineProperty(exports, "AwsCrc32", { enumerable: true, get: function () { return aws_crc32_1.AwsCrc32; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/convertToBuffer.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/convertToBuffer.js deleted file mode 100644 index 6cc8bcfe..00000000 --- a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/convertToBuffer.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -Object.defineProperty(exports, "__esModule", { value: true }); -exports.convertToBuffer = void 0; -var util_utf8_browser_1 = require("@aws-sdk/util-utf8-browser"); -// Quick polyfill -var fromUtf8 = typeof Buffer !== "undefined" && Buffer.from - ? function (input) { return Buffer.from(input, "utf8"); } - : util_utf8_browser_1.fromUtf8; -function convertToBuffer(data) { - // Already a Uint8, do nothing - if (data instanceof Uint8Array) - return data; - if (typeof data === "string") { - return fromUtf8(data); - } - if (ArrayBuffer.isView(data)) { - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); - } - return new Uint8Array(data); -} -exports.convertToBuffer = convertToBuffer; -//# sourceMappingURL=convertToBuffer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/index.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/index.js deleted file mode 100644 index 94e1ca90..00000000 --- a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/index.js +++ /dev/null @@ -1,14 +0,0 @@ -"use strict"; -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -Object.defineProperty(exports, "__esModule", { value: true }); -exports.uint32ArrayFrom = exports.numToUint8 = exports.isEmptyData = exports.convertToBuffer = void 0; -var convertToBuffer_1 = require("./convertToBuffer"); -Object.defineProperty(exports, "convertToBuffer", { enumerable: true, get: function () { return convertToBuffer_1.convertToBuffer; } }); -var isEmptyData_1 = require("./isEmptyData"); -Object.defineProperty(exports, "isEmptyData", { enumerable: true, get: function () { return isEmptyData_1.isEmptyData; } }); -var numToUint8_1 = require("./numToUint8"); -Object.defineProperty(exports, "numToUint8", { enumerable: true, get: function () { return numToUint8_1.numToUint8; } }); -var uint32ArrayFrom_1 = require("./uint32ArrayFrom"); -Object.defineProperty(exports, "uint32ArrayFrom", { enumerable: true, get: function () { return uint32ArrayFrom_1.uint32ArrayFrom; } }); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/isEmptyData.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/isEmptyData.js deleted file mode 100644 index 6af1e89e..00000000 --- a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/isEmptyData.js +++ /dev/null @@ -1,13 +0,0 @@ -"use strict"; -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isEmptyData = void 0; -function isEmptyData(data) { - if (typeof data === "string") { - return data.length === 0; - } - return data.byteLength === 0; -} -exports.isEmptyData = isEmptyData; -//# sourceMappingURL=isEmptyData.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/numToUint8.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/numToUint8.js deleted file mode 100644 index 2f070e10..00000000 --- a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/numToUint8.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -Object.defineProperty(exports, "__esModule", { value: true }); -exports.numToUint8 = void 0; -function numToUint8(num) { - return new Uint8Array([ - (num & 0xff000000) >> 24, - (num & 0x00ff0000) >> 16, - (num & 0x0000ff00) >> 8, - num & 0x000000ff, - ]); -} -exports.numToUint8 = numToUint8; -//# sourceMappingURL=numToUint8.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/uint32ArrayFrom.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/uint32ArrayFrom.js deleted file mode 100644 index 226cdc3d..00000000 --- a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/@aws-crypto/util/build/uint32ArrayFrom.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; -// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved. -// SPDX-License-Identifier: Apache-2.0 -Object.defineProperty(exports, "__esModule", { value: true }); -exports.uint32ArrayFrom = void 0; -// IE 11 does not support Array.from, so we do it manually -function uint32ArrayFrom(a_lookUpTable) { - if (!Uint32Array.from) { - var return_array = new Uint32Array(a_lookUpTable.length); - var a_index = 0; - while (a_index < a_lookUpTable.length) { - return_array[a_index] = a_lookUpTable[a_index]; - a_index += 1; - } - return return_array; - } - return Uint32Array.from(a_lookUpTable); -} -exports.uint32ArrayFrom = uint32ArrayFrom; -//# sourceMappingURL=uint32ArrayFrom.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/tslib/tslib.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/tslib/tslib.js deleted file mode 100644 index e5b7c9b8..00000000 --- a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@aws-crypto/crc32/node_modules/tslib/tslib.js +++ /dev/null @@ -1,284 +0,0 @@ -/*! ***************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ - -/* global global, define, System, Reflect, Promise */ -var __extends; -var __assign; -var __rest; -var __decorate; -var __param; -var __metadata; -var __awaiter; -var __generator; -var __exportStar; -var __values; -var __read; -var __spread; -var __spreadArrays; -var __await; -var __asyncGenerator; -var __asyncDelegator; -var __asyncValues; -var __makeTemplateObject; -var __importStar; -var __importDefault; -var __classPrivateFieldGet; -var __classPrivateFieldSet; -var __createBinding; -(function (factory) { - var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; - if (typeof define === "function" && define.amd) { - define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); - } - else if (typeof module === "object" && typeof module.exports === "object") { - factory(createExporter(root, createExporter(module.exports))); - } - else { - factory(createExporter(root)); - } - function createExporter(exports, previous) { - if (exports !== root) { - if (typeof Object.create === "function") { - Object.defineProperty(exports, "__esModule", { value: true }); - } - else { - exports.__esModule = true; - } - } - return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; - } -}) -(function (exporter) { - var extendStatics = Object.setPrototypeOf || - ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || - function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; - - __extends = function (d, b) { - extendStatics(d, b); - function __() { this.constructor = d; } - d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); - }; - - __assign = Object.assign || function (t) { - for (var s, i = 1, n = arguments.length; i < n; i++) { - s = arguments[i]; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; - } - return t; - }; - - __rest = function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; - }; - - __decorate = function (decorators, target, key, desc) { - var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; - if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); - else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; - return c > 3 && r && Object.defineProperty(target, key, r), r; - }; - - __param = function (paramIndex, decorator) { - return function (target, key) { decorator(target, key, paramIndex); } - }; - - __metadata = function (metadataKey, metadataValue) { - if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); - }; - - __awaiter = function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); - }; - - __generator = function (thisArg, body) { - var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; - return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; - function verb(n) { return function (v) { return step([n, v]); }; } - function step(op) { - if (f) throw new TypeError("Generator is already executing."); - while (_) try { - if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; - if (y = 0, t) op = [op[0] & 2, t.value]; - switch (op[0]) { - case 0: case 1: t = op; break; - case 4: _.label++; return { value: op[1], done: false }; - case 5: _.label++; y = op[1]; op = [0]; continue; - case 7: op = _.ops.pop(); _.trys.pop(); continue; - default: - if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } - if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } - if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } - if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } - if (t[2]) _.ops.pop(); - _.trys.pop(); continue; - } - op = body.call(thisArg, _); - } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } - if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; - } - }; - - __createBinding = function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; - }; - - __exportStar = function (m, exports) { - for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) exports[p] = m[p]; - }; - - __values = function (o) { - var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; - if (m) return m.call(o); - if (o && typeof o.length === "number") return { - next: function () { - if (o && i >= o.length) o = void 0; - return { value: o && o[i++], done: !o }; - } - }; - throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); - }; - - __read = function (o, n) { - var m = typeof Symbol === "function" && o[Symbol.iterator]; - if (!m) return o; - var i = m.call(o), r, ar = [], e; - try { - while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); - } - catch (error) { e = { error: error }; } - finally { - try { - if (r && !r.done && (m = i["return"])) m.call(i); - } - finally { if (e) throw e.error; } - } - return ar; - }; - - __spread = function () { - for (var ar = [], i = 0; i < arguments.length; i++) - ar = ar.concat(__read(arguments[i])); - return ar; - }; - - __spreadArrays = function () { - for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; - for (var r = Array(s), k = 0, i = 0; i < il; i++) - for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) - r[k] = a[j]; - return r; - }; - - __await = function (v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); - }; - - __asyncGenerator = function (thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } - }; - - __asyncDelegator = function (o) { - var i, p; - return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; - function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; } - }; - - __asyncValues = function (o) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var m = o[Symbol.asyncIterator], i; - return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); - function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } - function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } - }; - - __makeTemplateObject = function (cooked, raw) { - if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } - return cooked; - }; - - __importStar = function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; - result["default"] = mod; - return result; - }; - - __importDefault = function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; - }; - - __classPrivateFieldGet = function (receiver, privateMap) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to get private field on non-instance"); - } - return privateMap.get(receiver); - }; - - __classPrivateFieldSet = function (receiver, privateMap, value) { - if (!privateMap.has(receiver)) { - throw new TypeError("attempted to set private field on non-instance"); - } - privateMap.set(receiver, value); - return value; - }; - - exporter("__extends", __extends); - exporter("__assign", __assign); - exporter("__rest", __rest); - exporter("__decorate", __decorate); - exporter("__param", __param); - exporter("__metadata", __metadata); - exporter("__awaiter", __awaiter); - exporter("__generator", __generator); - exporter("__exportStar", __exportStar); - exporter("__createBinding", __createBinding); - exporter("__values", __values); - exporter("__read", __read); - exporter("__spread", __spread); - exporter("__spreadArrays", __spreadArrays); - exporter("__await", __await); - exporter("__asyncGenerator", __asyncGenerator); - exporter("__asyncDelegator", __asyncDelegator); - exporter("__asyncValues", __asyncValues); - exporter("__makeTemplateObject", __makeTemplateObject); - exporter("__importStar", __importStar); - exporter("__importDefault", __importDefault); - exporter("__classPrivateFieldGet", __classPrivateFieldGet); - exporter("__classPrivateFieldSet", __classPrivateFieldSet); -}); diff --git a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js deleted file mode 100644 index 78a59ea8..00000000 --- a/claude-code-source/node_modules/@smithy/eventstream-serde-universal/node_modules/@smithy/eventstream-codec/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js +++ /dev/null @@ -1,67 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - fromHex: () => fromHex, - toHex: () => toHex -}); -module.exports = __toCommonJS(src_exports); -var SHORT_TO_HEX = {}; -var HEX_TO_SHORT = {}; -for (let i = 0; i < 256; i++) { - let encodedByte = i.toString(16).toLowerCase(); - if (encodedByte.length === 1) { - encodedByte = `0${encodedByte}`; - } - SHORT_TO_HEX[i] = encodedByte; - HEX_TO_SHORT[encodedByte] = i; -} -function fromHex(encoded) { - if (encoded.length % 2 !== 0) { - throw new Error("Hex encoded strings must have an even number length"); - } - const out = new Uint8Array(encoded.length / 2); - for (let i = 0; i < encoded.length; i += 2) { - const encodedByte = encoded.slice(i, i + 2).toLowerCase(); - if (encodedByte in HEX_TO_SHORT) { - out[i / 2] = HEX_TO_SHORT[encodedByte]; - } else { - throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); - } - } - return out; -} -__name(fromHex, "fromHex"); -function toHex(bytes) { - let out = ""; - for (let i = 0; i < bytes.byteLength; i++) { - out += SHORT_TO_HEX[bytes[i]]; - } - return out; -} -__name(toHex, "toHex"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - fromHex, - toHex -}); - diff --git a/claude-code-source/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js deleted file mode 100644 index 9c9c44b9..00000000 --- a/claude-code-source/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js +++ /dev/null @@ -1,264 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - FetchHttpHandler: () => FetchHttpHandler, - keepAliveSupport: () => keepAliveSupport, - streamCollector: () => streamCollector -}); -module.exports = __toCommonJS(src_exports); - -// src/fetch-http-handler.ts -var import_protocol_http = require("@smithy/protocol-http"); -var import_querystring_builder = require("@smithy/querystring-builder"); - -// src/create-request.ts -function createRequest(url, requestOptions) { - return new Request(url, requestOptions); -} -__name(createRequest, "createRequest"); - -// src/request-timeout.ts -function requestTimeout(timeoutInMs = 0) { - return new Promise((resolve, reject) => { - if (timeoutInMs) { - setTimeout(() => { - const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); - timeoutError.name = "TimeoutError"; - reject(timeoutError); - }, timeoutInMs); - } - }); -} -__name(requestTimeout, "requestTimeout"); - -// src/fetch-http-handler.ts -var keepAliveSupport = { - supported: void 0 -}; -var FetchHttpHandler = class _FetchHttpHandler { - static { - __name(this, "FetchHttpHandler"); - } - /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. - */ - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new _FetchHttpHandler(instanceOrOptions); - } - constructor(options) { - if (typeof options === "function") { - this.configProvider = options().then((opts) => opts || {}); - } else { - this.config = options ?? {}; - this.configProvider = Promise.resolve(this.config); - } - if (keepAliveSupport.supported === void 0) { - keepAliveSupport.supported = Boolean( - typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]") - ); - } - } - destroy() { - } - async handle(request, { abortSignal } = {}) { - if (!this.config) { - this.config = await this.configProvider; - } - const requestTimeoutInMs = this.config.requestTimeout; - const keepAlive = this.config.keepAlive === true; - const credentials = this.config.credentials; - if (abortSignal?.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - return Promise.reject(abortError); - } - let path = request.path; - const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const { port, method } = request; - const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; - const body = method === "GET" || method === "HEAD" ? void 0 : request.body; - const requestOptions = { - body, - headers: new Headers(request.headers), - method, - credentials - }; - if (this.config?.cache) { - requestOptions.cache = this.config.cache; - } - if (body) { - requestOptions.duplex = "half"; - } - if (typeof AbortController !== "undefined") { - requestOptions.signal = abortSignal; - } - if (keepAliveSupport.supported) { - requestOptions.keepalive = keepAlive; - } - if (typeof this.config.requestInit === "function") { - Object.assign(requestOptions, this.config.requestInit(request)); - } - let removeSignalEventListener = /* @__PURE__ */ __name(() => { - }, "removeSignalEventListener"); - const fetchRequest = createRequest(url, requestOptions); - const raceOfPromises = [ - fetch(fetchRequest).then((response) => { - const fetchHeaders = response.headers; - const transformedHeaders = {}; - for (const pair of fetchHeaders.entries()) { - transformedHeaders[pair[0]] = pair[1]; - } - const hasReadableStream = response.body != void 0; - if (!hasReadableStream) { - return response.blob().then((body2) => ({ - response: new import_protocol_http.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: body2 - }) - })); - } - return { - response: new import_protocol_http.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: response.body - }) - }; - }), - requestTimeout(requestTimeoutInMs) - ]; - if (abortSignal) { - raceOfPromises.push( - new Promise((resolve, reject) => { - const onAbort = /* @__PURE__ */ __name(() => { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }, "onAbort"); - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - removeSignalEventListener = /* @__PURE__ */ __name(() => signal.removeEventListener("abort", onAbort), "removeSignalEventListener"); - } else { - abortSignal.onabort = onAbort; - } - }) - ); - } - return Promise.race(raceOfPromises).finally(removeSignalEventListener); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - config[key] = value; - return config; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } -}; - -// src/stream-collector.ts -var import_util_base64 = require("@smithy/util-base64"); -var streamCollector = /* @__PURE__ */ __name(async (stream) => { - if (typeof Blob === "function" && stream instanceof Blob || stream.constructor?.name === "Blob") { - if (Blob.prototype.arrayBuffer !== void 0) { - return new Uint8Array(await stream.arrayBuffer()); - } - return collectBlob(stream); - } - return collectStream(stream); -}, "streamCollector"); -async function collectBlob(blob) { - const base64 = await readToBase64(blob); - const arrayBuffer = (0, import_util_base64.fromBase64)(base64); - return new Uint8Array(arrayBuffer); -} -__name(collectBlob, "collectBlob"); -async function collectStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; - } - isDone = done; - } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; - } - return collected; -} -__name(collectStream, "collectStream"); -function readToBase64(blob) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onloadend = () => { - if (reader.readyState !== 2) { - return reject(new Error("Reader aborted too early")); - } - const result = reader.result ?? ""; - const commaIndex = result.indexOf(","); - const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; - resolve(result.substring(dataOffset)); - }; - reader.onabort = () => reject(new Error("Read aborted")); - reader.onerror = () => reject(reader.error); - reader.readAsDataURL(blob); - }); -} -__name(readToBase64, "readToBase64"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - keepAliveSupport, - FetchHttpHandler, - streamCollector -}); - diff --git a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index df371090..00000000 --- a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,262 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - Field: () => Field, - Fields: () => Fields, - HttpRequest: () => HttpRequest, - HttpResponse: () => HttpResponse, - IHttpRequest: () => import_types.HttpRequest, - getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, - isValidHostname: () => isValidHostname, - resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig -}); -module.exports = __toCommonJS(src_exports); - -// src/extensions/httpExtensionConfiguration.ts -var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - setHttpHandler(handler) { - runtimeConfig.httpHandler = handler; - }, - httpHandler() { - return runtimeConfig.httpHandler; - }, - updateHttpClientConfig(key, value) { - runtimeConfig.httpHandler?.updateHttpClientConfig(key, value); - }, - httpHandlerConfigs() { - return runtimeConfig.httpHandler.httpHandlerConfigs(); - } - }; -}, "getHttpHandlerExtensionConfiguration"); -var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { - return { - httpHandler: httpHandlerExtensionConfiguration.httpHandler() - }; -}, "resolveHttpHandlerRuntimeConfig"); - -// src/Field.ts -var import_types = require("@smithy/types"); -var Field = class { - static { - __name(this, "Field"); - } - constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { - this.name = name; - this.kind = kind; - this.values = values; - } - /** - * Appends a value to the field. - * - * @param value The value to append. - */ - add(value) { - this.values.push(value); - } - /** - * Overwrite existing field values. - * - * @param values The new field values. - */ - set(values) { - this.values = values; - } - /** - * Remove all matching entries from list. - * - * @param value Value to remove. - */ - remove(value) { - this.values = this.values.filter((v) => v !== value); - } - /** - * Get comma-delimited string. - * - * @returns String representation of {@link Field}. - */ - toString() { - return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); - } - /** - * Get string values as a list - * - * @returns Values in {@link Field} as a list. - */ - get() { - return this.values; - } -}; - -// src/Fields.ts -var Fields = class { - constructor({ fields = [], encoding = "utf-8" }) { - this.entries = {}; - fields.forEach(this.setField.bind(this)); - this.encoding = encoding; - } - static { - __name(this, "Fields"); - } - /** - * Set entry for a {@link Field} name. The `name` - * attribute will be used to key the collection. - * - * @param field The {@link Field} to set. - */ - setField(field) { - this.entries[field.name.toLowerCase()] = field; - } - /** - * Retrieve {@link Field} entry by name. - * - * @param name The name of the {@link Field} entry - * to retrieve - * @returns The {@link Field} if it exists. - */ - getField(name) { - return this.entries[name.toLowerCase()]; - } - /** - * Delete entry from collection. - * - * @param name Name of the entry to delete. - */ - removeField(name) { - delete this.entries[name.toLowerCase()]; - } - /** - * Helper function for retrieving specific types of fields. - * Used to grab all headers or all trailers. - * - * @param kind {@link FieldPosition} of entries to retrieve. - * @returns The {@link Field} entries with the specified - * {@link FieldPosition}. - */ - getByType(kind) { - return Object.values(this.entries).filter((field) => field.kind === kind); - } -}; - -// src/httpRequest.ts - -var HttpRequest = class _HttpRequest { - static { - __name(this, "HttpRequest"); - } - 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; - } - /** - * Note: this does not deep-clone the body. - */ - static clone(request) { - const cloned = new _HttpRequest({ - ...request, - headers: { ...request.headers } - }); - if (cloned.query) { - cloned.query = cloneQuery(cloned.query); - } - return cloned; - } - /** - * This method only actually asserts that request is the interface {@link IHttpRequest}, - * and not necessarily this concrete class. Left in place for API stability. - * - * Do not call instance methods on the input of this function, and - * do not assume it has the HttpRequest prototype. - */ - 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"; - } - /** - * @deprecated use static HttpRequest.clone(request) instead. It's not safe to call - * this method because {@link HttpRequest.isInstance} incorrectly - * asserts that IHttpRequest (interface) objects are of type HttpRequest (class). - */ - 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 - }; - }, {}); -} -__name(cloneQuery, "cloneQuery"); - -// src/httpResponse.ts -var HttpResponse = class { - static { - __name(this, "HttpResponse"); - } - 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"; - } -}; - -// src/isValidHostname.ts -function isValidHostname(hostname) { - const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; - return hostPattern.test(hostname); -} -__name(isValidHostname, "isValidHostname"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - getHttpHandlerExtensionConfiguration, - resolveHttpHandlerRuntimeConfig, - Field, - Fields, - HttpRequest, - HttpResponse, - isValidHostname -}); - diff --git a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index 0849f2b4..00000000 --- a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,144 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig -}); -module.exports = __toCommonJS(src_exports); - -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); - -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); - -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); - -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: () => "sha256" /* SHA256 */, - checksumConstructor: () => runtimeConfig.sha256 - }); - } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: () => "md5" /* MD5 */, - checksumConstructor: () => runtimeConfig.md5 - }); - } - return { - addChecksumAlgorithm(algo) { - checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return checksumAlgorithms; - } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); - -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return getChecksumConfiguration(runtimeConfig); -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return resolveChecksumRuntimeConfig(config); -}, "resolveDefaultRuntimeConfig"); - -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); - -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; - -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); - -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - HttpAuthLocation, - HttpApiKeyAuthLocation, - EndpointURLScheme, - AlgorithmId, - getDefaultClientConfiguration, - resolveDefaultRuntimeConfig, - FieldPosition, - SMITHY_CONTEXT_KEY, - IniSectionType, - RequestHandlerProtocol -}); - diff --git a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js deleted file mode 100644 index b06a7b87..00000000 --- a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js +++ /dev/null @@ -1,16 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/index.js deleted file mode 100644 index 02848d02..00000000 --- a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/index.js +++ /dev/null @@ -1,27 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -module.exports = __toCommonJS(src_exports); -__reExport(src_exports, require("././fromBase64"), module.exports); -__reExport(src_exports, require("././toBase64"), module.exports); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - fromBase64, - toBase64 -}); - diff --git a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/toBase64.js deleted file mode 100644 index 0590ce3f..00000000 --- a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/dist-cjs/toBase64.js +++ /dev/null @@ -1,19 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js deleted file mode 100644 index b577c9ca..00000000 --- a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/dist-cjs/index.js +++ /dev/null @@ -1,20 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js deleted file mode 100644 index 3238bb77..00000000 --- a/claude-code-source/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/util-base64/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || - Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; - -exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@smithy/hash-node/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/hash-node/dist-cjs/index.js deleted file mode 100644 index 9038b5fe..00000000 --- a/claude-code-source/node_modules/@smithy/hash-node/dist-cjs/index.js +++ /dev/null @@ -1,42 +0,0 @@ -'use strict'; - -var utilBufferFrom = require('@smithy/util-buffer-from'); -var utilUtf8 = require('@smithy/util-utf8'); -var buffer = require('buffer'); -var crypto = require('crypto'); - -class Hash { - algorithmIdentifier; - secret; - hash; - constructor(algorithmIdentifier, secret) { - this.algorithmIdentifier = algorithmIdentifier; - this.secret = secret; - this.reset(); - } - update(toHash, encoding) { - this.hash.update(utilUtf8.toUint8Array(castSourceData(toHash, encoding))); - } - digest() { - return Promise.resolve(this.hash.digest()); - } - reset() { - this.hash = this.secret - ? crypto.createHmac(this.algorithmIdentifier, castSourceData(this.secret)) - : crypto.createHash(this.algorithmIdentifier); - } -} -function castSourceData(toCast, encoding) { - if (buffer.Buffer.isBuffer(toCast)) { - return toCast; - } - if (typeof toCast === "string") { - return utilBufferFrom.fromString(toCast, encoding); - } - if (ArrayBuffer.isView(toCast)) { - return utilBufferFrom.fromArrayBuffer(toCast.buffer, toCast.byteOffset, toCast.byteLength); - } - return utilBufferFrom.fromArrayBuffer(toCast); -} - -exports.Hash = Hash; diff --git a/claude-code-source/node_modules/@smithy/hash-node/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/hash-node/node_modules/@smithy/util-buffer-from/dist-cjs/index.js deleted file mode 100644 index b577c9ca..00000000 --- a/claude-code-source/node_modules/@smithy/hash-node/node_modules/@smithy/util-buffer-from/dist-cjs/index.js +++ /dev/null @@ -1,20 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/hash-node/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/hash-node/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js deleted file mode 100644 index 3238bb77..00000000 --- a/claude-code-source/node_modules/@smithy/hash-node/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || - Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; - -exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/is-array-buffer/dist-cjs/index.js deleted file mode 100644 index 5d792e71..00000000 --- a/claude-code-source/node_modules/@smithy/is-array-buffer/dist-cjs/index.js +++ /dev/null @@ -1,32 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - isArrayBuffer: () => isArrayBuffer -}); -module.exports = __toCommonJS(src_exports); -var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - isArrayBuffer -}); - diff --git a/claude-code-source/node_modules/@smithy/middleware-content-length/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-content-length/dist-cjs/index.js deleted file mode 100644 index e957f196..00000000 --- a/claude-code-source/node_modules/@smithy/middleware-content-length/dist-cjs/index.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict'; - -var protocolHttp = require('@smithy/protocol-http'); - -const CONTENT_LENGTH_HEADER = "content-length"; -function contentLengthMiddleware(bodyLengthChecker) { - return (next) => async (args) => { - const request = args.request; - if (protocolHttp.HttpRequest.isInstance(request)) { - const { body, headers } = request; - if (body && - Object.keys(headers) - .map((str) => str.toLowerCase()) - .indexOf(CONTENT_LENGTH_HEADER) === -1) { - try { - const length = bodyLengthChecker(body); - request.headers = { - ...request.headers, - [CONTENT_LENGTH_HEADER]: String(length), - }; - } - catch (error) { - } - } - } - return next({ - ...args, - request, - }); - }; -} -const contentLengthMiddlewareOptions = { - step: "build", - tags: ["SET_CONTENT_LENGTH", "CONTENT_LENGTH"], - name: "contentLengthMiddleware", - override: true, -}; -const getContentLengthPlugin = (options) => ({ - applyToStack: (clientStack) => { - clientStack.add(contentLengthMiddleware(options.bodyLengthChecker), contentLengthMiddlewareOptions); - }, -}); - -exports.contentLengthMiddleware = contentLengthMiddleware; -exports.contentLengthMiddlewareOptions = contentLengthMiddlewareOptions; -exports.getContentLengthPlugin = getContentLengthPlugin; diff --git a/claude-code-source/node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 52303c3b..00000000 --- a/claude-code-source/node_modules/@smithy/middleware-content-length/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,169 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/middleware-content-length/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-content-length/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@smithy/middleware-content-length/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointFromConfig.js b/claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointFromConfig.js deleted file mode 100644 index 262b45be..00000000 --- a/claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointFromConfig.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getEndpointFromConfig = void 0; -const node_config_provider_1 = require("@smithy/node-config-provider"); -const getEndpointUrlConfig_1 = require("./getEndpointUrlConfig"); -const getEndpointFromConfig = async (serviceId) => (0, node_config_provider_1.loadConfig)((0, getEndpointUrlConfig_1.getEndpointUrlConfig)(serviceId ?? ""))(); -exports.getEndpointFromConfig = getEndpointFromConfig; diff --git a/claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointUrlConfig.js b/claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointUrlConfig.js deleted file mode 100644 index fe5c010a..00000000 --- a/claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/adaptors/getEndpointUrlConfig.js +++ /dev/null @@ -1,35 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getEndpointUrlConfig = void 0; -const shared_ini_file_loader_1 = require("@smithy/shared-ini-file-loader"); -const ENV_ENDPOINT_URL = "AWS_ENDPOINT_URL"; -const CONFIG_ENDPOINT_URL = "endpoint_url"; -const getEndpointUrlConfig = (serviceId) => ({ - environmentVariableSelector: (env) => { - const serviceSuffixParts = serviceId.split(" ").map((w) => w.toUpperCase()); - const serviceEndpointUrl = env[[ENV_ENDPOINT_URL, ...serviceSuffixParts].join("_")]; - if (serviceEndpointUrl) - return serviceEndpointUrl; - const endpointUrl = env[ENV_ENDPOINT_URL]; - if (endpointUrl) - return endpointUrl; - return undefined; - }, - configFileSelector: (profile, config) => { - if (config && profile.services) { - const servicesSection = config[["services", profile.services].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; - if (servicesSection) { - const servicePrefixParts = serviceId.split(" ").map((w) => w.toLowerCase()); - const endpointUrl = servicesSection[[servicePrefixParts.join("_"), CONFIG_ENDPOINT_URL].join(shared_ini_file_loader_1.CONFIG_PREFIX_SEPARATOR)]; - if (endpointUrl) - return endpointUrl; - } - } - const endpointUrl = profile[CONFIG_ENDPOINT_URL]; - if (endpointUrl) - return endpointUrl; - return undefined; - }, - default: undefined, -}); -exports.getEndpointUrlConfig = getEndpointUrlConfig; diff --git a/claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/index.js deleted file mode 100644 index 82a7e58e..00000000 --- a/claude-code-source/node_modules/@smithy/middleware-endpoint/dist-cjs/index.js +++ /dev/null @@ -1,240 +0,0 @@ -'use strict'; - -var getEndpointFromConfig = require('./adaptors/getEndpointFromConfig'); -var urlParser = require('@smithy/url-parser'); -var core = require('@smithy/core'); -var utilMiddleware = require('@smithy/util-middleware'); -var middlewareSerde = require('@smithy/middleware-serde'); - -const resolveParamsForS3 = async (endpointParams) => { - const bucket = endpointParams?.Bucket || ""; - if (typeof endpointParams.Bucket === "string") { - endpointParams.Bucket = bucket.replace(/#/g, encodeURIComponent("#")).replace(/\?/g, encodeURIComponent("?")); - } - if (isArnBucketName(bucket)) { - if (endpointParams.ForcePathStyle === true) { - throw new Error("Path-style addressing cannot be used with ARN buckets"); - } - } - else if (!isDnsCompatibleBucketName(bucket) || - (bucket.indexOf(".") !== -1 && !String(endpointParams.Endpoint).startsWith("http:")) || - bucket.toLowerCase() !== bucket || - bucket.length < 3) { - endpointParams.ForcePathStyle = true; - } - if (endpointParams.DisableMultiRegionAccessPoints) { - endpointParams.disableMultiRegionAccessPoints = true; - endpointParams.DisableMRAP = true; - } - return endpointParams; -}; -const DOMAIN_PATTERN = /^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/; -const IP_ADDRESS_PATTERN = /(\d+\.){3}\d+/; -const DOTS_PATTERN = /\.\./; -const isDnsCompatibleBucketName = (bucketName) => DOMAIN_PATTERN.test(bucketName) && !IP_ADDRESS_PATTERN.test(bucketName) && !DOTS_PATTERN.test(bucketName); -const isArnBucketName = (bucketName) => { - const [arn, partition, service, , , bucket] = bucketName.split(":"); - const isArn = arn === "arn" && bucketName.split(":").length >= 6; - const isValidArn = Boolean(isArn && partition && service && bucket); - if (isArn && !isValidArn) { - throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`); - } - return isValidArn; -}; - -const createConfigValueProvider = (configKey, canonicalEndpointParamKey, config) => { - const configProvider = async () => { - const configValue = config[configKey] ?? config[canonicalEndpointParamKey]; - if (typeof configValue === "function") { - return configValue(); - } - return configValue; - }; - if (configKey === "credentialScope" || canonicalEndpointParamKey === "CredentialScope") { - return async () => { - const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; - const configValue = credentials?.credentialScope ?? credentials?.CredentialScope; - return configValue; - }; - } - if (configKey === "accountId" || canonicalEndpointParamKey === "AccountId") { - return async () => { - const credentials = typeof config.credentials === "function" ? await config.credentials() : config.credentials; - const configValue = credentials?.accountId ?? credentials?.AccountId; - return configValue; - }; - } - if (configKey === "endpoint" || canonicalEndpointParamKey === "endpoint") { - return async () => { - if (config.isCustomEndpoint === false) { - return undefined; - } - const endpoint = await configProvider(); - if (endpoint && typeof endpoint === "object") { - if ("url" in endpoint) { - return endpoint.url.href; - } - if ("hostname" in endpoint) { - const { protocol, hostname, port, path } = endpoint; - return `${protocol}//${hostname}${port ? ":" + port : ""}${path}`; - } - } - return endpoint; - }; - } - return configProvider; -}; - -const toEndpointV1 = (endpoint) => { - if (typeof endpoint === "object") { - if ("url" in endpoint) { - return urlParser.parseUrl(endpoint.url); - } - return endpoint; - } - return urlParser.parseUrl(endpoint); -}; - -const getEndpointFromInstructions = async (commandInput, instructionsSupplier, clientConfig, context) => { - if (!clientConfig.isCustomEndpoint) { - let endpointFromConfig; - if (clientConfig.serviceConfiguredEndpoint) { - endpointFromConfig = await clientConfig.serviceConfiguredEndpoint(); - } - else { - endpointFromConfig = await getEndpointFromConfig.getEndpointFromConfig(clientConfig.serviceId); - } - if (endpointFromConfig) { - clientConfig.endpoint = () => Promise.resolve(toEndpointV1(endpointFromConfig)); - clientConfig.isCustomEndpoint = true; - } - } - const endpointParams = await resolveParams(commandInput, instructionsSupplier, clientConfig); - if (typeof clientConfig.endpointProvider !== "function") { - throw new Error("config.endpointProvider is not set."); - } - const endpoint = clientConfig.endpointProvider(endpointParams, context); - return endpoint; -}; -const resolveParams = async (commandInput, instructionsSupplier, clientConfig) => { - const endpointParams = {}; - const instructions = instructionsSupplier?.getEndpointParameterInstructions?.() || {}; - for (const [name, instruction] of Object.entries(instructions)) { - switch (instruction.type) { - case "staticContextParams": - endpointParams[name] = instruction.value; - break; - case "contextParams": - endpointParams[name] = commandInput[instruction.name]; - break; - case "clientContextParams": - case "builtInParams": - endpointParams[name] = await createConfigValueProvider(instruction.name, name, clientConfig)(); - break; - case "operationContextParams": - endpointParams[name] = instruction.get(commandInput); - break; - default: - throw new Error("Unrecognized endpoint parameter instruction: " + JSON.stringify(instruction)); - } - } - if (Object.keys(instructions).length === 0) { - Object.assign(endpointParams, clientConfig); - } - if (String(clientConfig.serviceId).toLowerCase() === "s3") { - await resolveParamsForS3(endpointParams); - } - return endpointParams; -}; - -const endpointMiddleware = ({ config, instructions, }) => { - return (next, context) => async (args) => { - if (config.isCustomEndpoint) { - core.setFeature(context, "ENDPOINT_OVERRIDE", "N"); - } - const endpoint = await getEndpointFromInstructions(args.input, { - getEndpointParameterInstructions() { - return instructions; - }, - }, { ...config }, context); - context.endpointV2 = endpoint; - context.authSchemes = endpoint.properties?.authSchemes; - const authScheme = context.authSchemes?.[0]; - if (authScheme) { - context["signing_region"] = authScheme.signingRegion; - context["signing_service"] = authScheme.signingName; - const smithyContext = utilMiddleware.getSmithyContext(context); - const httpAuthOption = smithyContext?.selectedHttpAuthScheme?.httpAuthOption; - if (httpAuthOption) { - httpAuthOption.signingProperties = Object.assign(httpAuthOption.signingProperties || {}, { - signing_region: authScheme.signingRegion, - signingRegion: authScheme.signingRegion, - signing_service: authScheme.signingName, - signingName: authScheme.signingName, - signingRegionSet: authScheme.signingRegionSet, - }, authScheme.properties); - } - } - return next({ - ...args, - }); - }; -}; - -const endpointMiddlewareOptions = { - step: "serialize", - tags: ["ENDPOINT_PARAMETERS", "ENDPOINT_V2", "ENDPOINT"], - name: "endpointV2Middleware", - override: true, - relation: "before", - toMiddleware: middlewareSerde.serializerMiddlewareOption.name, -}; -const getEndpointPlugin = (config, instructions) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo(endpointMiddleware({ - config, - instructions, - }), endpointMiddlewareOptions); - }, -}); - -const resolveEndpointConfig = (input) => { - const tls = input.tls ?? true; - const { endpoint, useDualstackEndpoint, useFipsEndpoint } = input; - const customEndpointProvider = endpoint != null ? async () => toEndpointV1(await utilMiddleware.normalizeProvider(endpoint)()) : undefined; - const isCustomEndpoint = !!endpoint; - const resolvedConfig = Object.assign(input, { - endpoint: customEndpointProvider, - tls, - isCustomEndpoint, - useDualstackEndpoint: utilMiddleware.normalizeProvider(useDualstackEndpoint ?? false), - useFipsEndpoint: utilMiddleware.normalizeProvider(useFipsEndpoint ?? false), - }); - let configuredEndpointPromise = undefined; - resolvedConfig.serviceConfiguredEndpoint = async () => { - if (input.serviceId && !configuredEndpointPromise) { - configuredEndpointPromise = getEndpointFromConfig.getEndpointFromConfig(input.serviceId); - } - return configuredEndpointPromise; - }; - return resolvedConfig; -}; - -const resolveEndpointRequiredConfig = (input) => { - const { endpoint } = input; - if (endpoint === undefined) { - input.endpoint = async () => { - throw new Error("@smithy/middleware-endpoint: (default endpointRuleSet) endpoint is not set - you must configure an endpoint."); - }; - } - return input; -}; - -exports.endpointMiddleware = endpointMiddleware; -exports.endpointMiddlewareOptions = endpointMiddlewareOptions; -exports.getEndpointFromInstructions = getEndpointFromInstructions; -exports.getEndpointPlugin = getEndpointPlugin; -exports.resolveEndpointConfig = resolveEndpointConfig; -exports.resolveEndpointRequiredConfig = resolveEndpointRequiredConfig; -exports.resolveParams = resolveParams; -exports.toEndpointV1 = toEndpointV1; diff --git a/claude-code-source/node_modules/@smithy/middleware-retry/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-retry/dist-cjs/index.js deleted file mode 100644 index 3da6fd72..00000000 --- a/claude-code-source/node_modules/@smithy/middleware-retry/dist-cjs/index.js +++ /dev/null @@ -1,358 +0,0 @@ -'use strict'; - -var utilRetry = require('@smithy/util-retry'); -var protocolHttp = require('@smithy/protocol-http'); -var serviceErrorClassification = require('@smithy/service-error-classification'); -var uuid = require('@smithy/uuid'); -var utilMiddleware = require('@smithy/util-middleware'); -var smithyClient = require('@smithy/smithy-client'); -var isStreamingPayload = require('./isStreamingPayload/isStreamingPayload'); - -const getDefaultRetryQuota = (initialRetryTokens, options) => { - const MAX_CAPACITY = initialRetryTokens; - const noRetryIncrement = utilRetry.NO_RETRY_INCREMENT; - const retryCost = utilRetry.RETRY_COST; - const timeoutRetryCost = utilRetry.TIMEOUT_RETRY_COST; - let availableCapacity = initialRetryTokens; - const getCapacityAmount = (error) => (error.name === "TimeoutError" ? timeoutRetryCost : retryCost); - const hasRetryTokens = (error) => getCapacityAmount(error) <= availableCapacity; - const retrieveRetryTokens = (error) => { - if (!hasRetryTokens(error)) { - throw new Error("No retry token available"); - } - const capacityAmount = getCapacityAmount(error); - availableCapacity -= capacityAmount; - return capacityAmount; - }; - const releaseRetryTokens = (capacityReleaseAmount) => { - availableCapacity += capacityReleaseAmount ?? noRetryIncrement; - availableCapacity = Math.min(availableCapacity, MAX_CAPACITY); - }; - return Object.freeze({ - hasRetryTokens, - retrieveRetryTokens, - releaseRetryTokens, - }); -}; - -const defaultDelayDecider = (delayBase, attempts) => Math.floor(Math.min(utilRetry.MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)); - -const defaultRetryDecider = (error) => { - if (!error) { - return false; - } - return serviceErrorClassification.isRetryableByTrait(error) || serviceErrorClassification.isClockSkewError(error) || serviceErrorClassification.isThrottlingError(error) || serviceErrorClassification.isTransientError(error); -}; - -const asSdkError = (error) => { - if (error instanceof Error) - return error; - if (error instanceof Object) - return Object.assign(new Error(), error); - if (typeof error === "string") - return new Error(error); - return new Error(`AWS SDK error wrapper for ${error}`); -}; - -class StandardRetryStrategy { - maxAttemptsProvider; - retryDecider; - delayDecider; - retryQuota; - mode = utilRetry.RETRY_MODES.STANDARD; - constructor(maxAttemptsProvider, options) { - this.maxAttemptsProvider = maxAttemptsProvider; - this.retryDecider = options?.retryDecider ?? defaultRetryDecider; - this.delayDecider = options?.delayDecider ?? defaultDelayDecider; - this.retryQuota = options?.retryQuota ?? getDefaultRetryQuota(utilRetry.INITIAL_RETRY_TOKENS); - } - shouldRetry(error, attempts, maxAttempts) { - return attempts < maxAttempts && this.retryDecider(error) && this.retryQuota.hasRetryTokens(error); - } - async getMaxAttempts() { - let maxAttempts; - try { - maxAttempts = await this.maxAttemptsProvider(); - } - catch (error) { - maxAttempts = utilRetry.DEFAULT_MAX_ATTEMPTS; - } - return maxAttempts; - } - async retry(next, args, options) { - let retryTokenAmount; - let attempts = 0; - let totalDelay = 0; - const maxAttempts = await this.getMaxAttempts(); - const { request } = args; - if (protocolHttp.HttpRequest.isInstance(request)) { - request.headers[utilRetry.INVOCATION_ID_HEADER] = uuid.v4(); - } - while (true) { - try { - if (protocolHttp.HttpRequest.isInstance(request)) { - request.headers[utilRetry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; - } - if (options?.beforeRequest) { - await options.beforeRequest(); - } - const { response, output } = await next(args); - if (options?.afterRequest) { - options.afterRequest(response); - } - this.retryQuota.releaseRetryTokens(retryTokenAmount); - output.$metadata.attempts = attempts + 1; - output.$metadata.totalRetryDelay = totalDelay; - return { response, output }; - } - catch (e) { - const err = asSdkError(e); - attempts++; - if (this.shouldRetry(err, attempts, maxAttempts)) { - retryTokenAmount = this.retryQuota.retrieveRetryTokens(err); - const delayFromDecider = this.delayDecider(serviceErrorClassification.isThrottlingError(err) ? utilRetry.THROTTLING_RETRY_DELAY_BASE : utilRetry.DEFAULT_RETRY_DELAY_BASE, attempts); - const delayFromResponse = getDelayFromRetryAfterHeader(err.$response); - const delay = Math.max(delayFromResponse || 0, delayFromDecider); - totalDelay += delay; - await new Promise((resolve) => setTimeout(resolve, delay)); - continue; - } - if (!err.$metadata) { - err.$metadata = {}; - } - err.$metadata.attempts = attempts; - err.$metadata.totalRetryDelay = totalDelay; - throw err; - } - } - } -} -const getDelayFromRetryAfterHeader = (response) => { - if (!protocolHttp.HttpResponse.isInstance(response)) - return; - const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); - if (!retryAfterHeaderName) - return; - const retryAfter = response.headers[retryAfterHeaderName]; - const retryAfterSeconds = Number(retryAfter); - if (!Number.isNaN(retryAfterSeconds)) - return retryAfterSeconds * 1000; - const retryAfterDate = new Date(retryAfter); - return retryAfterDate.getTime() - Date.now(); -}; - -class AdaptiveRetryStrategy extends StandardRetryStrategy { - rateLimiter; - constructor(maxAttemptsProvider, options) { - const { rateLimiter, ...superOptions } = options ?? {}; - super(maxAttemptsProvider, superOptions); - this.rateLimiter = rateLimiter ?? new utilRetry.DefaultRateLimiter(); - this.mode = utilRetry.RETRY_MODES.ADAPTIVE; - } - async retry(next, args) { - return super.retry(next, args, { - beforeRequest: async () => { - return this.rateLimiter.getSendToken(); - }, - afterRequest: (response) => { - this.rateLimiter.updateClientSendingRate(response); - }, - }); - } -} - -const ENV_MAX_ATTEMPTS = "AWS_MAX_ATTEMPTS"; -const CONFIG_MAX_ATTEMPTS = "max_attempts"; -const NODE_MAX_ATTEMPT_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => { - const value = env[ENV_MAX_ATTEMPTS]; - if (!value) - return undefined; - const maxAttempt = parseInt(value); - if (Number.isNaN(maxAttempt)) { - throw new Error(`Environment variable ${ENV_MAX_ATTEMPTS} mast be a number, got "${value}"`); - } - return maxAttempt; - }, - configFileSelector: (profile) => { - const value = profile[CONFIG_MAX_ATTEMPTS]; - if (!value) - return undefined; - const maxAttempt = parseInt(value); - if (Number.isNaN(maxAttempt)) { - throw new Error(`Shared config file entry ${CONFIG_MAX_ATTEMPTS} mast be a number, got "${value}"`); - } - return maxAttempt; - }, - default: utilRetry.DEFAULT_MAX_ATTEMPTS, -}; -const resolveRetryConfig = (input) => { - const { retryStrategy, retryMode: _retryMode, maxAttempts: _maxAttempts } = input; - const maxAttempts = utilMiddleware.normalizeProvider(_maxAttempts ?? utilRetry.DEFAULT_MAX_ATTEMPTS); - return Object.assign(input, { - maxAttempts, - retryStrategy: async () => { - if (retryStrategy) { - return retryStrategy; - } - const retryMode = await utilMiddleware.normalizeProvider(_retryMode)(); - if (retryMode === utilRetry.RETRY_MODES.ADAPTIVE) { - return new utilRetry.AdaptiveRetryStrategy(maxAttempts); - } - return new utilRetry.StandardRetryStrategy(maxAttempts); - }, - }); -}; -const ENV_RETRY_MODE = "AWS_RETRY_MODE"; -const CONFIG_RETRY_MODE = "retry_mode"; -const NODE_RETRY_MODE_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => env[ENV_RETRY_MODE], - configFileSelector: (profile) => profile[CONFIG_RETRY_MODE], - default: utilRetry.DEFAULT_RETRY_MODE, -}; - -const omitRetryHeadersMiddleware = () => (next) => async (args) => { - const { request } = args; - if (protocolHttp.HttpRequest.isInstance(request)) { - delete request.headers[utilRetry.INVOCATION_ID_HEADER]; - delete request.headers[utilRetry.REQUEST_HEADER]; - } - return next(args); -}; -const omitRetryHeadersMiddlewareOptions = { - name: "omitRetryHeadersMiddleware", - tags: ["RETRY", "HEADERS", "OMIT_RETRY_HEADERS"], - relation: "before", - toMiddleware: "awsAuthMiddleware", - override: true, -}; -const getOmitRetryHeadersPlugin = (options) => ({ - applyToStack: (clientStack) => { - clientStack.addRelativeTo(omitRetryHeadersMiddleware(), omitRetryHeadersMiddlewareOptions); - }, -}); - -const retryMiddleware = (options) => (next, context) => async (args) => { - let retryStrategy = await options.retryStrategy(); - const maxAttempts = await options.maxAttempts(); - if (isRetryStrategyV2(retryStrategy)) { - retryStrategy = retryStrategy; - let retryToken = await retryStrategy.acquireInitialRetryToken(context["partition_id"]); - let lastError = new Error(); - let attempts = 0; - let totalRetryDelay = 0; - const { request } = args; - const isRequest = protocolHttp.HttpRequest.isInstance(request); - if (isRequest) { - request.headers[utilRetry.INVOCATION_ID_HEADER] = uuid.v4(); - } - while (true) { - try { - if (isRequest) { - request.headers[utilRetry.REQUEST_HEADER] = `attempt=${attempts + 1}; max=${maxAttempts}`; - } - const { response, output } = await next(args); - retryStrategy.recordSuccess(retryToken); - output.$metadata.attempts = attempts + 1; - output.$metadata.totalRetryDelay = totalRetryDelay; - return { response, output }; - } - catch (e) { - const retryErrorInfo = getRetryErrorInfo(e); - lastError = asSdkError(e); - if (isRequest && isStreamingPayload.isStreamingPayload(request)) { - (context.logger instanceof smithyClient.NoOpLogger ? console : context.logger)?.warn("An error was encountered in a non-retryable streaming request."); - throw lastError; - } - try { - retryToken = await retryStrategy.refreshRetryTokenForRetry(retryToken, retryErrorInfo); - } - catch (refreshError) { - if (!lastError.$metadata) { - lastError.$metadata = {}; - } - lastError.$metadata.attempts = attempts + 1; - lastError.$metadata.totalRetryDelay = totalRetryDelay; - throw lastError; - } - attempts = retryToken.getRetryCount(); - const delay = retryToken.getRetryDelay(); - totalRetryDelay += delay; - await new Promise((resolve) => setTimeout(resolve, delay)); - } - } - } - else { - retryStrategy = retryStrategy; - if (retryStrategy?.mode) - context.userAgent = [...(context.userAgent || []), ["cfg/retry-mode", retryStrategy.mode]]; - return retryStrategy.retry(next, args); - } -}; -const isRetryStrategyV2 = (retryStrategy) => typeof retryStrategy.acquireInitialRetryToken !== "undefined" && - typeof retryStrategy.refreshRetryTokenForRetry !== "undefined" && - typeof retryStrategy.recordSuccess !== "undefined"; -const getRetryErrorInfo = (error) => { - const errorInfo = { - error, - errorType: getRetryErrorType(error), - }; - const retryAfterHint = getRetryAfterHint(error.$response); - if (retryAfterHint) { - errorInfo.retryAfterHint = retryAfterHint; - } - return errorInfo; -}; -const getRetryErrorType = (error) => { - if (serviceErrorClassification.isThrottlingError(error)) - return "THROTTLING"; - if (serviceErrorClassification.isTransientError(error)) - return "TRANSIENT"; - if (serviceErrorClassification.isServerError(error)) - return "SERVER_ERROR"; - return "CLIENT_ERROR"; -}; -const retryMiddlewareOptions = { - name: "retryMiddleware", - tags: ["RETRY"], - step: "finalizeRequest", - priority: "high", - override: true, -}; -const getRetryPlugin = (options) => ({ - applyToStack: (clientStack) => { - clientStack.add(retryMiddleware(options), retryMiddlewareOptions); - }, -}); -const getRetryAfterHint = (response) => { - if (!protocolHttp.HttpResponse.isInstance(response)) - return; - const retryAfterHeaderName = Object.keys(response.headers).find((key) => key.toLowerCase() === "retry-after"); - if (!retryAfterHeaderName) - return; - const retryAfter = response.headers[retryAfterHeaderName]; - const retryAfterSeconds = Number(retryAfter); - if (!Number.isNaN(retryAfterSeconds)) - return new Date(retryAfterSeconds * 1000); - const retryAfterDate = new Date(retryAfter); - return retryAfterDate; -}; - -exports.AdaptiveRetryStrategy = AdaptiveRetryStrategy; -exports.CONFIG_MAX_ATTEMPTS = CONFIG_MAX_ATTEMPTS; -exports.CONFIG_RETRY_MODE = CONFIG_RETRY_MODE; -exports.ENV_MAX_ATTEMPTS = ENV_MAX_ATTEMPTS; -exports.ENV_RETRY_MODE = ENV_RETRY_MODE; -exports.NODE_MAX_ATTEMPT_CONFIG_OPTIONS = NODE_MAX_ATTEMPT_CONFIG_OPTIONS; -exports.NODE_RETRY_MODE_CONFIG_OPTIONS = NODE_RETRY_MODE_CONFIG_OPTIONS; -exports.StandardRetryStrategy = StandardRetryStrategy; -exports.defaultDelayDecider = defaultDelayDecider; -exports.defaultRetryDecider = defaultRetryDecider; -exports.getOmitRetryHeadersPlugin = getOmitRetryHeadersPlugin; -exports.getRetryAfterHint = getRetryAfterHint; -exports.getRetryPlugin = getRetryPlugin; -exports.omitRetryHeadersMiddleware = omitRetryHeadersMiddleware; -exports.omitRetryHeadersMiddlewareOptions = omitRetryHeadersMiddlewareOptions; -exports.resolveRetryConfig = resolveRetryConfig; -exports.retryMiddleware = retryMiddleware; -exports.retryMiddlewareOptions = retryMiddlewareOptions; diff --git a/claude-code-source/node_modules/@smithy/middleware-retry/dist-cjs/isStreamingPayload/isStreamingPayload.js b/claude-code-source/node_modules/@smithy/middleware-retry/dist-cjs/isStreamingPayload/isStreamingPayload.js deleted file mode 100644 index 6d66c791..00000000 --- a/claude-code-source/node_modules/@smithy/middleware-retry/dist-cjs/isStreamingPayload/isStreamingPayload.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isStreamingPayload = void 0; -const stream_1 = require("stream"); -const isStreamingPayload = (request) => request?.body instanceof stream_1.Readable || - (typeof ReadableStream !== "undefined" && request?.body instanceof ReadableStream); -exports.isStreamingPayload = isStreamingPayload; diff --git a/claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 52303c3b..00000000 --- a/claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,169 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/smithy-client/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/smithy-client/dist-cjs/index.js deleted file mode 100644 index 9f589873..00000000 --- a/claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/smithy-client/dist-cjs/index.js +++ /dev/null @@ -1,589 +0,0 @@ -'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]; } - }); -}); diff --git a/claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@smithy/middleware-retry/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/middleware-serde/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-serde/dist-cjs/index.js deleted file mode 100644 index b0712b8d..00000000 --- a/claude-code-source/node_modules/@smithy/middleware-serde/dist-cjs/index.js +++ /dev/null @@ -1,103 +0,0 @@ -'use strict'; - -var protocolHttp = require('@smithy/protocol-http'); - -const deserializerMiddleware = (options, deserializer) => (next, context) => async (args) => { - const { response } = await next(args); - try { - const parsed = await deserializer(response, options); - return { - response, - output: parsed, - }; - } - catch (error) { - Object.defineProperty(error, "$response", { - value: response, - enumerable: false, - writable: false, - configurable: false, - }); - if (!("$metadata" in error)) { - const hint = `Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.`; - try { - error.message += "\n " + hint; - } - catch (e) { - if (!context.logger || context.logger?.constructor?.name === "NoOpLogger") { - console.warn(hint); - } - else { - context.logger?.warn?.(hint); - } - } - if (typeof error.$responseBodyText !== "undefined") { - if (error.$response) { - error.$response.body = error.$responseBodyText; - } - } - try { - if (protocolHttp.HttpResponse.isInstance(response)) { - const { headers = {} } = response; - const headerEntries = Object.entries(headers); - error.$metadata = { - httpStatusCode: response.statusCode, - requestId: findHeader(/^x-[\w-]+-request-?id$/, headerEntries), - extendedRequestId: findHeader(/^x-[\w-]+-id-2$/, headerEntries), - cfId: findHeader(/^x-[\w-]+-cf-id$/, headerEntries), - }; - } - } - catch (e) { - } - } - throw error; - } -}; -const findHeader = (pattern, headers) => { - return (headers.find(([k]) => { - return k.match(pattern); - }) || [void 0, void 0])[1]; -}; - -const serializerMiddleware = (options, serializer) => (next, context) => async (args) => { - const endpointConfig = options; - const endpoint = context.endpointV2?.url && endpointConfig.urlParser - ? async () => endpointConfig.urlParser(context.endpointV2.url) - : endpointConfig.endpoint; - if (!endpoint) { - throw new Error("No valid endpoint provider available."); - } - const request = await serializer(args.input, { ...options, endpoint }); - return next({ - ...args, - request, - }); -}; - -const deserializerMiddlewareOption = { - name: "deserializerMiddleware", - step: "deserialize", - tags: ["DESERIALIZER"], - override: true, -}; -const serializerMiddlewareOption = { - name: "serializerMiddleware", - step: "serialize", - tags: ["SERIALIZER"], - override: true, -}; -function getSerdePlugin(config, serializer, deserializer) { - return { - applyToStack: (commandStack) => { - commandStack.add(deserializerMiddleware(config, deserializer), deserializerMiddlewareOption); - commandStack.add(serializerMiddleware(config, serializer), serializerMiddlewareOption); - }, - }; -} - -exports.deserializerMiddleware = deserializerMiddleware; -exports.deserializerMiddlewareOption = deserializerMiddlewareOption; -exports.getSerdePlugin = getSerdePlugin; -exports.serializerMiddleware = serializerMiddleware; -exports.serializerMiddlewareOption = serializerMiddlewareOption; diff --git a/claude-code-source/node_modules/@smithy/middleware-serde/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-serde/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 52303c3b..00000000 --- a/claude-code-source/node_modules/@smithy/middleware-serde/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,169 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/middleware-serde/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-serde/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@smithy/middleware-serde/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/middleware-stack/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/middleware-stack/dist-cjs/index.js deleted file mode 100644 index b83cef58..00000000 --- a/claude-code-source/node_modules/@smithy/middleware-stack/dist-cjs/index.js +++ /dev/null @@ -1,285 +0,0 @@ -'use strict'; - -const getAllAliases = (name, aliases) => { - const _aliases = []; - if (name) { - _aliases.push(name); - } - if (aliases) { - for (const alias of aliases) { - _aliases.push(alias); - } - } - return _aliases; -}; -const getMiddlewareNameWithAliases = (name, aliases) => { - return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`; -}; -const constructStack = () => { - let absoluteEntries = []; - let relativeEntries = []; - let identifyOnResolve = false; - const entriesNameSet = new Set(); - const sort = (entries) => entries.sort((a, b) => stepWeights[b.step] - stepWeights[a.step] || - priorityWeights[b.priority || "normal"] - priorityWeights[a.priority || "normal"]); - const removeByName = (toRemove) => { - let isRemoved = false; - const filterCb = (entry) => { - const aliases = getAllAliases(entry.name, entry.aliases); - if (aliases.includes(toRemove)) { - isRemoved = true; - for (const alias of aliases) { - entriesNameSet.delete(alias); - } - return false; - } - return true; - }; - absoluteEntries = absoluteEntries.filter(filterCb); - relativeEntries = relativeEntries.filter(filterCb); - return isRemoved; - }; - const removeByReference = (toRemove) => { - let isRemoved = false; - const filterCb = (entry) => { - if (entry.middleware === toRemove) { - isRemoved = true; - for (const alias of getAllAliases(entry.name, entry.aliases)) { - entriesNameSet.delete(alias); - } - return false; - } - return true; - }; - absoluteEntries = absoluteEntries.filter(filterCb); - relativeEntries = relativeEntries.filter(filterCb); - return isRemoved; - }; - const cloneTo = (toStack) => { - absoluteEntries.forEach((entry) => { - toStack.add(entry.middleware, { ...entry }); - }); - relativeEntries.forEach((entry) => { - toStack.addRelativeTo(entry.middleware, { ...entry }); - }); - toStack.identifyOnResolve?.(stack.identifyOnResolve()); - return toStack; - }; - const expandRelativeMiddlewareList = (from) => { - const expandedMiddlewareList = []; - from.before.forEach((entry) => { - if (entry.before.length === 0 && entry.after.length === 0) { - expandedMiddlewareList.push(entry); - } - else { - expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); - } - }); - expandedMiddlewareList.push(from); - from.after.reverse().forEach((entry) => { - if (entry.before.length === 0 && entry.after.length === 0) { - expandedMiddlewareList.push(entry); - } - else { - expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); - } - }); - return expandedMiddlewareList; - }; - const getMiddlewareList = (debug = false) => { - const normalizedAbsoluteEntries = []; - const normalizedRelativeEntries = []; - const normalizedEntriesNameMap = {}; - absoluteEntries.forEach((entry) => { - const normalizedEntry = { - ...entry, - before: [], - after: [], - }; - for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { - normalizedEntriesNameMap[alias] = normalizedEntry; - } - normalizedAbsoluteEntries.push(normalizedEntry); - }); - relativeEntries.forEach((entry) => { - const normalizedEntry = { - ...entry, - before: [], - after: [], - }; - for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { - normalizedEntriesNameMap[alias] = normalizedEntry; - } - normalizedRelativeEntries.push(normalizedEntry); - }); - normalizedRelativeEntries.forEach((entry) => { - if (entry.toMiddleware) { - const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware]; - if (toMiddleware === undefined) { - if (debug) { - return; - } - throw new Error(`${entry.toMiddleware} is not found when adding ` + - `${getMiddlewareNameWithAliases(entry.name, entry.aliases)} ` + - `middleware ${entry.relation} ${entry.toMiddleware}`); - } - if (entry.relation === "after") { - toMiddleware.after.push(entry); - } - if (entry.relation === "before") { - toMiddleware.before.push(entry); - } - } - }); - const mainChain = sort(normalizedAbsoluteEntries) - .map(expandRelativeMiddlewareList) - .reduce((wholeList, expandedMiddlewareList) => { - wholeList.push(...expandedMiddlewareList); - return wholeList; - }, []); - return mainChain; - }; - const stack = { - add: (middleware, options = {}) => { - const { name, override, aliases: _aliases } = options; - const entry = { - step: "initialize", - priority: "normal", - middleware, - ...options, - }; - const aliases = getAllAliases(name, _aliases); - if (aliases.length > 0) { - if (aliases.some((alias) => entriesNameSet.has(alias))) { - if (!override) - throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); - for (const alias of aliases) { - const toOverrideIndex = absoluteEntries.findIndex((entry) => entry.name === alias || entry.aliases?.some((a) => a === alias)); - if (toOverrideIndex === -1) { - continue; - } - const toOverride = absoluteEntries[toOverrideIndex]; - if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) { - throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ` + - `${toOverride.priority} priority in ${toOverride.step} step cannot ` + - `be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ` + - `${entry.priority} priority in ${entry.step} step.`); - } - absoluteEntries.splice(toOverrideIndex, 1); - } - } - for (const alias of aliases) { - entriesNameSet.add(alias); - } - } - absoluteEntries.push(entry); - }, - addRelativeTo: (middleware, options) => { - const { name, override, aliases: _aliases } = options; - const entry = { - middleware, - ...options, - }; - const aliases = getAllAliases(name, _aliases); - if (aliases.length > 0) { - if (aliases.some((alias) => entriesNameSet.has(alias))) { - if (!override) - throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); - for (const alias of aliases) { - const toOverrideIndex = relativeEntries.findIndex((entry) => entry.name === alias || entry.aliases?.some((a) => a === alias)); - if (toOverrideIndex === -1) { - continue; - } - const toOverride = relativeEntries[toOverrideIndex]; - if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) { - throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ` + - `${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden ` + - `by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} ` + - `"${entry.toMiddleware}" middleware.`); - } - relativeEntries.splice(toOverrideIndex, 1); - } - } - for (const alias of aliases) { - entriesNameSet.add(alias); - } - } - relativeEntries.push(entry); - }, - clone: () => cloneTo(constructStack()), - use: (plugin) => { - plugin.applyToStack(stack); - }, - remove: (toRemove) => { - if (typeof toRemove === "string") - return removeByName(toRemove); - else - return removeByReference(toRemove); - }, - removeByTag: (toRemove) => { - let isRemoved = false; - const filterCb = (entry) => { - const { tags, name, aliases: _aliases } = entry; - if (tags && tags.includes(toRemove)) { - const aliases = getAllAliases(name, _aliases); - for (const alias of aliases) { - entriesNameSet.delete(alias); - } - isRemoved = true; - return false; - } - return true; - }; - absoluteEntries = absoluteEntries.filter(filterCb); - relativeEntries = relativeEntries.filter(filterCb); - return isRemoved; - }, - concat: (from) => { - const cloned = cloneTo(constructStack()); - cloned.use(from); - cloned.identifyOnResolve(identifyOnResolve || cloned.identifyOnResolve() || (from.identifyOnResolve?.() ?? false)); - return cloned; - }, - applyToStack: cloneTo, - identify: () => { - return getMiddlewareList(true).map((mw) => { - const step = mw.step ?? - mw.relation + - " " + - mw.toMiddleware; - return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step; - }); - }, - identifyOnResolve(toggle) { - if (typeof toggle === "boolean") - identifyOnResolve = toggle; - return identifyOnResolve; - }, - resolve: (handler, context) => { - for (const middleware of getMiddlewareList() - .map((entry) => entry.middleware) - .reverse()) { - handler = middleware(handler, context); - } - if (identifyOnResolve) { - console.log(stack.identify()); - } - return handler; - }, - }; - return stack; -}; -const stepWeights = { - initialize: 5, - serialize: 4, - build: 3, - finalizeRequest: 2, - deserialize: 1, -}; -const priorityWeights = { - high: 3, - normal: 2, - low: 1, -}; - -exports.constructStack = constructStack; diff --git a/claude-code-source/node_modules/@smithy/node-config-provider/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/node-config-provider/dist-cjs/index.js deleted file mode 100644 index b68e5434..00000000 --- a/claude-code-source/node_modules/@smithy/node-config-provider/dist-cjs/index.js +++ /dev/null @@ -1,62 +0,0 @@ -'use strict'; - -var propertyProvider = require('@smithy/property-provider'); -var sharedIniFileLoader = require('@smithy/shared-ini-file-loader'); - -function getSelectorName(functionString) { - try { - const constants = new Set(Array.from(functionString.match(/([A-Z_]){3,}/g) ?? [])); - constants.delete("CONFIG"); - constants.delete("CONFIG_PREFIX_SEPARATOR"); - constants.delete("ENV"); - return [...constants].join(", "); - } - catch (e) { - return functionString; - } -} - -const fromEnv = (envVarSelector, options) => async () => { - try { - const config = envVarSelector(process.env, options); - if (config === undefined) { - throw new Error(); - } - return config; - } - catch (e) { - throw new propertyProvider.CredentialsProviderError(e.message || `Not found in ENV: ${getSelectorName(envVarSelector.toString())}`, { logger: options?.logger }); - } -}; - -const fromSharedConfigFiles = (configSelector, { preferredFile = "config", ...init } = {}) => async () => { - const profile = sharedIniFileLoader.getProfileName(init); - const { configFile, credentialsFile } = await sharedIniFileLoader.loadSharedConfigFiles(init); - const profileFromCredentials = credentialsFile[profile] || {}; - const profileFromConfig = configFile[profile] || {}; - const mergedProfile = preferredFile === "config" - ? { ...profileFromCredentials, ...profileFromConfig } - : { ...profileFromConfig, ...profileFromCredentials }; - try { - const cfgFile = preferredFile === "config" ? configFile : credentialsFile; - const configValue = configSelector(mergedProfile, cfgFile); - if (configValue === undefined) { - throw new Error(); - } - return configValue; - } - catch (e) { - throw new propertyProvider.CredentialsProviderError(e.message || `Not found in config files w/ profile [${profile}]: ${getSelectorName(configSelector.toString())}`, { logger: init.logger }); - } -}; - -const isFunction = (func) => typeof func === "function"; -const fromStatic = (defaultValue) => isFunction(defaultValue) ? async () => await defaultValue() : propertyProvider.fromStatic(defaultValue); - -const loadConfig = ({ environmentVariableSelector, configFileSelector, default: defaultValue }, configuration = {}) => { - const { signingName, logger } = configuration; - const envOptions = { signingName, logger }; - return propertyProvider.memoize(propertyProvider.chain(fromEnv(environmentVariableSelector, envOptions), fromSharedConfigFiles(configFileSelector, configuration), fromStatic(defaultValue))); -}; - -exports.loadConfig = loadConfig; diff --git a/claude-code-source/node_modules/@smithy/node-http-handler/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/node-http-handler/dist-cjs/index.js deleted file mode 100644 index bdc797c6..00000000 --- a/claude-code-source/node_modules/@smithy/node-http-handler/dist-cjs/index.js +++ /dev/null @@ -1,732 +0,0 @@ -'use strict'; - -var protocolHttp = require('@smithy/protocol-http'); -var querystringBuilder = require('@smithy/querystring-builder'); -var http = require('http'); -var https = require('https'); -var stream = require('stream'); -var http2 = require('http2'); - -const NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; - -const getTransformedHeaders = (headers) => { - const transformedHeaders = {}; - for (const name of Object.keys(headers)) { - const headerValues = headers[name]; - transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; - } - return transformedHeaders; -}; - -const timing = { - setTimeout: (cb, ms) => setTimeout(cb, ms), - clearTimeout: (timeoutId) => clearTimeout(timeoutId), -}; - -const DEFER_EVENT_LISTENER_TIME$2 = 1000; -const setConnectionTimeout = (request, reject, timeoutInMs = 0) => { - if (!timeoutInMs) { - return -1; - } - const registerTimeout = (offset) => { - const timeoutId = timing.setTimeout(() => { - request.destroy(); - reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket did not establish a connection with the server within the configured timeout of ${timeoutInMs} ms.`), { - name: "TimeoutError", - })); - }, timeoutInMs - offset); - const doWithSocket = (socket) => { - if (socket?.connecting) { - socket.on("connect", () => { - timing.clearTimeout(timeoutId); - }); - } - else { - timing.clearTimeout(timeoutId); - } - }; - if (request.socket) { - doWithSocket(request.socket); - } - else { - request.on("socket", doWithSocket); - } - }; - if (timeoutInMs < 2000) { - registerTimeout(0); - return 0; - } - return timing.setTimeout(registerTimeout.bind(null, DEFER_EVENT_LISTENER_TIME$2), DEFER_EVENT_LISTENER_TIME$2); -}; - -const setRequestTimeout = (req, reject, timeoutInMs = 0, throwOnRequestTimeout, logger) => { - if (timeoutInMs) { - return timing.setTimeout(() => { - let msg = `@smithy/node-http-handler - [${throwOnRequestTimeout ? "ERROR" : "WARN"}] a request has exceeded the configured ${timeoutInMs} ms requestTimeout.`; - if (throwOnRequestTimeout) { - const error = Object.assign(new Error(msg), { - name: "TimeoutError", - code: "ETIMEDOUT", - }); - req.destroy(error); - reject(error); - } - else { - msg += ` Init client requestHandler with throwOnRequestTimeout=true to turn this into an error.`; - logger?.warn?.(msg); - } - }, timeoutInMs); - } - return -1; -}; - -const DEFER_EVENT_LISTENER_TIME$1 = 3000; -const setSocketKeepAlive = (request, { keepAlive, keepAliveMsecs }, deferTimeMs = DEFER_EVENT_LISTENER_TIME$1) => { - if (keepAlive !== true) { - return -1; - } - const registerListener = () => { - if (request.socket) { - request.socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - } - else { - request.on("socket", (socket) => { - socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - }); - } - }; - if (deferTimeMs === 0) { - registerListener(); - return 0; - } - return timing.setTimeout(registerListener, deferTimeMs); -}; - -const DEFER_EVENT_LISTENER_TIME = 3000; -const setSocketTimeout = (request, reject, timeoutInMs = 0) => { - const registerTimeout = (offset) => { - const timeout = timeoutInMs - offset; - const onTimeout = () => { - request.destroy(); - reject(Object.assign(new Error(`@smithy/node-http-handler - the request socket timed out after ${timeoutInMs} ms of inactivity (configured by client requestHandler).`), { name: "TimeoutError" })); - }; - if (request.socket) { - request.socket.setTimeout(timeout, onTimeout); - request.on("close", () => request.socket?.removeListener("timeout", onTimeout)); - } - else { - request.setTimeout(timeout, onTimeout); - } - }; - if (0 < timeoutInMs && timeoutInMs < 6000) { - registerTimeout(0); - return 0; - } - return timing.setTimeout(registerTimeout.bind(null, timeoutInMs === 0 ? 0 : DEFER_EVENT_LISTENER_TIME), DEFER_EVENT_LISTENER_TIME); -}; - -const MIN_WAIT_TIME = 6_000; -async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME, externalAgent = false) { - const headers = request.headers ?? {}; - const expect = headers.Expect || headers.expect; - let timeoutId = -1; - let sendBody = true; - if (!externalAgent && expect === "100-continue") { - sendBody = await Promise.race([ - new Promise((resolve) => { - timeoutId = Number(timing.setTimeout(() => resolve(true), Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); - }), - new Promise((resolve) => { - httpRequest.on("continue", () => { - timing.clearTimeout(timeoutId); - resolve(true); - }); - httpRequest.on("response", () => { - timing.clearTimeout(timeoutId); - resolve(false); - }); - httpRequest.on("error", () => { - timing.clearTimeout(timeoutId); - resolve(false); - }); - }), - ]); - } - if (sendBody) { - writeBody(httpRequest, request.body); - } -} -function writeBody(httpRequest, body) { - if (body instanceof stream.Readable) { - body.pipe(httpRequest); - return; - } - if (body) { - if (Buffer.isBuffer(body) || typeof body === "string") { - httpRequest.end(body); - return; - } - const uint8 = body; - if (typeof uint8 === "object" && - uint8.buffer && - typeof uint8.byteOffset === "number" && - typeof uint8.byteLength === "number") { - httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); - return; - } - httpRequest.end(Buffer.from(body)); - return; - } - httpRequest.end(); -} - -const DEFAULT_REQUEST_TIMEOUT = 0; -class NodeHttpHandler { - config; - configProvider; - socketWarningTimestamp = 0; - externalAgent = false; - metadata = { handlerProtocol: "http/1.1" }; - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new NodeHttpHandler(instanceOrOptions); - } - static checkSocketUsage(agent, socketWarningTimestamp, logger = console) { - const { sockets, requests, maxSockets } = agent; - if (typeof maxSockets !== "number" || maxSockets === Infinity) { - return socketWarningTimestamp; - } - const interval = 15_000; - if (Date.now() - interval < socketWarningTimestamp) { - return socketWarningTimestamp; - } - if (sockets && requests) { - for (const origin in sockets) { - const socketsInUse = sockets[origin]?.length ?? 0; - const requestsEnqueued = requests[origin]?.length ?? 0; - if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { - logger?.warn?.(`@smithy/node-http-handler:WARN - socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued. -See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html -or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config.`); - return Date.now(); - } - } - } - return socketWarningTimestamp; - } - constructor(options) { - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options() - .then((_options) => { - resolve(this.resolveDefaultConfig(_options)); - }) - .catch(reject); - } - else { - resolve(this.resolveDefaultConfig(options)); - } - }); - } - resolveDefaultConfig(options) { - const { requestTimeout, connectionTimeout, socketTimeout, socketAcquisitionWarningTimeout, httpAgent, httpsAgent, throwOnRequestTimeout, } = options || {}; - const keepAlive = true; - const maxSockets = 50; - return { - connectionTimeout, - requestTimeout, - socketTimeout, - socketAcquisitionWarningTimeout, - throwOnRequestTimeout, - httpAgent: (() => { - if (httpAgent instanceof http.Agent || typeof httpAgent?.destroy === "function") { - this.externalAgent = true; - return httpAgent; - } - return new http.Agent({ keepAlive, maxSockets, ...httpAgent }); - })(), - httpsAgent: (() => { - if (httpsAgent instanceof https.Agent || typeof httpsAgent?.destroy === "function") { - this.externalAgent = true; - return httpsAgent; - } - return new https.Agent({ keepAlive, maxSockets, ...httpsAgent }); - })(), - logger: console, - }; - } - destroy() { - this.config?.httpAgent?.destroy(); - this.config?.httpsAgent?.destroy(); - } - async handle(request, { abortSignal, requestTimeout } = {}) { - if (!this.config) { - this.config = await this.configProvider; - } - return new Promise((_resolve, _reject) => { - const config = this.config; - let writeRequestBodyPromise = undefined; - const timeouts = []; - const resolve = async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _resolve(arg); - }; - const reject = async (arg) => { - await writeRequestBodyPromise; - timeouts.forEach(timing.clearTimeout); - _reject(arg); - }; - if (abortSignal?.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - return; - } - const isSSL = request.protocol === "https:"; - const headers = request.headers ?? {}; - const expectContinue = (headers.Expect ?? headers.expect) === "100-continue"; - let agent = isSSL ? config.httpsAgent : config.httpAgent; - if (expectContinue && !this.externalAgent) { - agent = new (isSSL ? https.Agent : http.Agent)({ - keepAlive: false, - maxSockets: Infinity, - }); - } - timeouts.push(timing.setTimeout(() => { - this.socketWarningTimestamp = NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp, config.logger); - }, config.socketAcquisitionWarningTimeout ?? (config.requestTimeout ?? 2000) + (config.connectionTimeout ?? 1000))); - const queryString = querystringBuilder.buildQueryString(request.query || {}); - let auth = undefined; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}`; - } - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - let hostname = request.hostname ?? ""; - if (hostname[0] === "[" && hostname.endsWith("]")) { - hostname = request.hostname.slice(1, -1); - } - else { - hostname = request.hostname; - } - const nodeHttpsOptions = { - headers: request.headers, - host: hostname, - method: request.method, - path, - port: request.port, - agent, - auth, - }; - const requestFunc = isSSL ? https.request : http.request; - const req = requestFunc(nodeHttpsOptions, (res) => { - const httpResponse = new protocolHttp.HttpResponse({ - statusCode: res.statusCode || -1, - reason: res.statusMessage, - headers: getTransformedHeaders(res.headers), - body: res, - }); - resolve({ response: httpResponse }); - }); - req.on("error", (err) => { - if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { - reject(Object.assign(err, { name: "TimeoutError" })); - } - else { - reject(err); - } - }); - if (abortSignal) { - const onAbort = () => { - req.destroy(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }; - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } - else { - abortSignal.onabort = onAbort; - } - } - const effectiveRequestTimeout = requestTimeout ?? config.requestTimeout; - timeouts.push(setConnectionTimeout(req, reject, config.connectionTimeout)); - timeouts.push(setRequestTimeout(req, reject, effectiveRequestTimeout, config.throwOnRequestTimeout, config.logger ?? console)); - timeouts.push(setSocketTimeout(req, reject, config.socketTimeout)); - const httpAgent = nodeHttpsOptions.agent; - if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { - timeouts.push(setSocketKeepAlive(req, { - keepAlive: httpAgent.keepAlive, - keepAliveMsecs: httpAgent.keepAliveMsecs, - })); - } - writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout, this.externalAgent).catch((e) => { - timeouts.forEach(timing.clearTimeout); - return _reject(e); - }); - }); - } - updateHttpClientConfig(key, value) { - this.config = undefined; - this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value, - }; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } -} - -class NodeHttp2ConnectionPool { - sessions = []; - constructor(sessions) { - this.sessions = sessions ?? []; - } - poll() { - if (this.sessions.length > 0) { - return this.sessions.shift(); - } - } - offerLast(session) { - this.sessions.push(session); - } - contains(session) { - return this.sessions.includes(session); - } - remove(session) { - this.sessions = this.sessions.filter((s) => s !== session); - } - [Symbol.iterator]() { - return this.sessions[Symbol.iterator](); - } - destroy(connection) { - for (const session of this.sessions) { - if (session === connection) { - if (!session.destroyed) { - session.destroy(); - } - } - } - } -} - -class NodeHttp2ConnectionManager { - constructor(config) { - this.config = config; - if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { - throw new RangeError("maxConcurrency must be greater than zero."); - } - } - config; - sessionCache = new Map(); - lease(requestContext, connectionConfiguration) { - const url = this.getUrlString(requestContext); - const existingPool = this.sessionCache.get(url); - if (existingPool) { - const existingSession = existingPool.poll(); - if (existingSession && !this.config.disableConcurrency) { - return existingSession; - } - } - const session = http2.connect(url); - if (this.config.maxConcurrency) { - session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { - if (err) { - throw new Error("Fail to set maxConcurrentStreams to " + - this.config.maxConcurrency + - "when creating new session for " + - requestContext.destination.toString()); - } - }); - } - session.unref(); - const destroySessionCb = () => { - session.destroy(); - this.deleteSession(url, session); - }; - session.on("goaway", destroySessionCb); - session.on("error", destroySessionCb); - session.on("frameError", destroySessionCb); - session.on("close", () => this.deleteSession(url, session)); - if (connectionConfiguration.requestTimeout) { - session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); - } - const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); - connectionPool.offerLast(session); - this.sessionCache.set(url, connectionPool); - return session; - } - deleteSession(authority, session) { - const existingConnectionPool = this.sessionCache.get(authority); - if (!existingConnectionPool) { - return; - } - if (!existingConnectionPool.contains(session)) { - return; - } - existingConnectionPool.remove(session); - this.sessionCache.set(authority, existingConnectionPool); - } - release(requestContext, session) { - const cacheKey = this.getUrlString(requestContext); - this.sessionCache.get(cacheKey)?.offerLast(session); - } - destroy() { - for (const [key, connectionPool] of this.sessionCache) { - for (const session of connectionPool) { - if (!session.destroyed) { - session.destroy(); - } - connectionPool.remove(session); - } - this.sessionCache.delete(key); - } - } - setMaxConcurrentStreams(maxConcurrentStreams) { - if (maxConcurrentStreams && maxConcurrentStreams <= 0) { - throw new RangeError("maxConcurrentStreams must be greater than zero."); - } - this.config.maxConcurrency = maxConcurrentStreams; - } - setDisableConcurrentStreams(disableConcurrentStreams) { - this.config.disableConcurrency = disableConcurrentStreams; - } - getUrlString(request) { - return request.destination.toString(); - } -} - -class NodeHttp2Handler { - config; - configProvider; - metadata = { handlerProtocol: "h2" }; - connectionManager = new NodeHttp2ConnectionManager({}); - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new NodeHttp2Handler(instanceOrOptions); - } - constructor(options) { - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options() - .then((opts) => { - resolve(opts || {}); - }) - .catch(reject); - } - else { - resolve(options || {}); - } - }); - } - destroy() { - this.connectionManager.destroy(); - } - async handle(request, { abortSignal, requestTimeout } = {}) { - if (!this.config) { - this.config = await this.configProvider; - this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); - if (this.config.maxConcurrentStreams) { - this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); - } - } - const { requestTimeout: configRequestTimeout, disableConcurrentStreams } = this.config; - const effectiveRequestTimeout = requestTimeout ?? configRequestTimeout; - return new Promise((_resolve, _reject) => { - let fulfilled = false; - let writeRequestBodyPromise = undefined; - const resolve = async (arg) => { - await writeRequestBodyPromise; - _resolve(arg); - }; - const reject = async (arg) => { - await writeRequestBodyPromise; - _reject(arg); - }; - if (abortSignal?.aborted) { - fulfilled = true; - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - return; - } - const { hostname, method, port, protocol, query } = request; - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; - const requestContext = { destination: new URL(authority) }; - const session = this.connectionManager.lease(requestContext, { - requestTimeout: this.config?.sessionTimeout, - disableConcurrentStreams: disableConcurrentStreams || false, - }); - const rejectWithDestroy = (err) => { - if (disableConcurrentStreams) { - this.destroySession(session); - } - fulfilled = true; - reject(err); - }; - const queryString = querystringBuilder.buildQueryString(query || {}); - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - const req = session.request({ - ...request.headers, - [http2.constants.HTTP2_HEADER_PATH]: path, - [http2.constants.HTTP2_HEADER_METHOD]: method, - }); - session.ref(); - req.on("response", (headers) => { - const httpResponse = new protocolHttp.HttpResponse({ - statusCode: headers[":status"] || -1, - headers: getTransformedHeaders(headers), - body: req, - }); - fulfilled = true; - resolve({ response: httpResponse }); - if (disableConcurrentStreams) { - session.close(); - this.connectionManager.deleteSession(authority, session); - } - }); - if (effectiveRequestTimeout) { - req.setTimeout(effectiveRequestTimeout, () => { - req.close(); - const timeoutError = new Error(`Stream timed out because of no activity for ${effectiveRequestTimeout} ms`); - timeoutError.name = "TimeoutError"; - rejectWithDestroy(timeoutError); - }); - } - if (abortSignal) { - const onAbort = () => { - req.close(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - rejectWithDestroy(abortError); - }; - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - req.once("close", () => signal.removeEventListener("abort", onAbort)); - } - else { - abortSignal.onabort = onAbort; - } - } - req.on("frameError", (type, code, id) => { - rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); - }); - req.on("error", rejectWithDestroy); - req.on("aborted", () => { - rejectWithDestroy(new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`)); - }); - req.on("close", () => { - session.unref(); - if (disableConcurrentStreams) { - session.destroy(); - } - if (!fulfilled) { - rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); - } - }); - writeRequestBodyPromise = writeRequestBody(req, request, effectiveRequestTimeout); - }); - } - updateHttpClientConfig(key, value) { - this.config = undefined; - this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value, - }; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } - destroySession(session) { - if (!session.destroyed) { - session.destroy(); - } - } -} - -class Collector extends stream.Writable { - bufferedBytes = []; - _write(chunk, encoding, callback) { - this.bufferedBytes.push(chunk); - callback(); - } -} - -const streamCollector = (stream) => { - if (isReadableStreamInstance(stream)) { - return collectReadableStream(stream); - } - return new Promise((resolve, reject) => { - const collector = new Collector(); - stream.pipe(collector); - stream.on("error", (err) => { - collector.end(); - reject(err); - }); - collector.on("error", reject); - collector.on("finish", function () { - const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); - resolve(bytes); - }); - }); -}; -const isReadableStreamInstance = (stream) => typeof ReadableStream === "function" && stream instanceof ReadableStream; -async function collectReadableStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; - } - isDone = done; - } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; - } - return collected; -} - -exports.DEFAULT_REQUEST_TIMEOUT = DEFAULT_REQUEST_TIMEOUT; -exports.NodeHttp2Handler = NodeHttp2Handler; -exports.NodeHttpHandler = NodeHttpHandler; -exports.streamCollector = streamCollector; diff --git a/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 52303c3b..00000000 --- a/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,169 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js deleted file mode 100644 index f245489f..00000000 --- a/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -var utilUriEscape = require('@smithy/util-uri-escape'); - -function buildQueryString(query) { - const parts = []; - for (let key of Object.keys(query).sort()) { - const value = query[key]; - key = utilUriEscape.escapeUri(key); - if (Array.isArray(value)) { - for (let i = 0, iLen = value.length; i < iLen; i++) { - parts.push(`${key}=${utilUriEscape.escapeUri(value[i])}`); - } - } - else { - let qsEntry = key; - if (value || typeof value === "string") { - qsEntry += `=${utilUriEscape.escapeUri(value)}`; - } - parts.push(qsEntry); - } - } - return parts.join("&"); -} - -exports.buildQueryString = buildQueryString; diff --git a/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js deleted file mode 100644 index 11f942c3..00000000 --- a/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -const escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode); -const hexEncode = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`; - -const escapeUriPath = (uri) => uri.split("/").map(escapeUri).join("/"); - -exports.escapeUri = escapeUri; -exports.escapeUriPath = escapeUriPath; diff --git a/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@smithy/node-http-handler/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/property-provider/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/property-provider/dist-cjs/index.js deleted file mode 100644 index a419560c..00000000 --- a/claude-code-source/node_modules/@smithy/property-provider/dist-cjs/index.js +++ /dev/null @@ -1,117 +0,0 @@ -'use strict'; - -class ProviderError extends Error { - name = "ProviderError"; - tryNextLink; - constructor(message, options = true) { - let logger; - let tryNextLink = true; - if (typeof options === "boolean") { - logger = undefined; - tryNextLink = options; - } - else if (options != null && typeof options === "object") { - logger = options.logger; - tryNextLink = options.tryNextLink ?? true; - } - super(message); - this.tryNextLink = tryNextLink; - Object.setPrototypeOf(this, ProviderError.prototype); - logger?.debug?.(`@smithy/property-provider ${tryNextLink ? "->" : "(!)"} ${message}`); - } - static from(error, options = true) { - return Object.assign(new this(error.message, options), error); - } -} - -class CredentialsProviderError extends ProviderError { - name = "CredentialsProviderError"; - constructor(message, options = true) { - super(message, options); - Object.setPrototypeOf(this, CredentialsProviderError.prototype); - } -} - -class TokenProviderError extends ProviderError { - name = "TokenProviderError"; - constructor(message, options = true) { - super(message, options); - Object.setPrototypeOf(this, TokenProviderError.prototype); - } -} - -const chain = (...providers) => async () => { - if (providers.length === 0) { - throw new ProviderError("No providers in chain"); - } - let lastProviderError; - for (const provider of providers) { - try { - const credentials = await provider(); - return credentials; - } - catch (err) { - lastProviderError = err; - if (err?.tryNextLink) { - continue; - } - throw err; - } - } - throw lastProviderError; -}; - -const fromStatic = (staticValue) => () => Promise.resolve(staticValue); - -const memoize = (provider, isExpired, requiresRefresh) => { - let resolved; - let pending; - let hasResult; - let isConstant = false; - const coalesceProvider = async () => { - if (!pending) { - pending = provider(); - } - try { - resolved = await pending; - hasResult = true; - isConstant = false; - } - finally { - pending = undefined; - } - return resolved; - }; - if (isExpired === undefined) { - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - return resolved; - }; - } - return async (options) => { - if (!hasResult || options?.forceRefresh) { - resolved = await coalesceProvider(); - } - if (isConstant) { - return resolved; - } - if (requiresRefresh && !requiresRefresh(resolved)) { - isConstant = true; - return resolved; - } - if (isExpired(resolved)) { - await coalesceProvider(); - return resolved; - } - return resolved; - }; -}; - -exports.CredentialsProviderError = CredentialsProviderError; -exports.ProviderError = ProviderError; -exports.TokenProviderError = TokenProviderError; -exports.chain = chain; -exports.fromStatic = fromStatic; -exports.memoize = memoize; diff --git a/claude-code-source/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 182663fb..00000000 --- a/claude-code-source/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,237 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - Field: () => Field, - Fields: () => Fields, - HttpRequest: () => HttpRequest, - HttpResponse: () => HttpResponse, - getHttpHandlerExtensionConfiguration: () => getHttpHandlerExtensionConfiguration, - isValidHostname: () => isValidHostname, - resolveHttpHandlerRuntimeConfig: () => resolveHttpHandlerRuntimeConfig -}); -module.exports = __toCommonJS(src_exports); - -// src/extensions/httpExtensionConfiguration.ts -var getHttpHandlerExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - let httpHandler = runtimeConfig.httpHandler; - return { - setHttpHandler(handler) { - httpHandler = handler; - }, - httpHandler() { - return httpHandler; - }, - updateHttpClientConfig(key, value) { - httpHandler.updateHttpClientConfig(key, value); - }, - httpHandlerConfigs() { - return httpHandler.httpHandlerConfigs(); - } - }; -}, "getHttpHandlerExtensionConfiguration"); -var resolveHttpHandlerRuntimeConfig = /* @__PURE__ */ __name((httpHandlerExtensionConfiguration) => { - return { - httpHandler: httpHandlerExtensionConfiguration.httpHandler() - }; -}, "resolveHttpHandlerRuntimeConfig"); - -// src/Field.ts -var import_types = require("@smithy/types"); -var _Field = class _Field { - constructor({ name, kind = import_types.FieldPosition.HEADER, values = [] }) { - this.name = name; - this.kind = kind; - this.values = values; - } - /** - * Appends a value to the field. - * - * @param value The value to append. - */ - add(value) { - this.values.push(value); - } - /** - * Overwrite existing field values. - * - * @param values The new field values. - */ - set(values) { - this.values = values; - } - /** - * Remove all matching entries from list. - * - * @param value Value to remove. - */ - remove(value) { - this.values = this.values.filter((v) => v !== value); - } - /** - * Get comma-delimited string. - * - * @returns String representation of {@link Field}. - */ - toString() { - return this.values.map((v) => v.includes(",") || v.includes(" ") ? `"${v}"` : v).join(", "); - } - /** - * Get string values as a list - * - * @returns Values in {@link Field} as a list. - */ - get() { - return this.values; - } -}; -__name(_Field, "Field"); -var Field = _Field; - -// src/Fields.ts -var _Fields = class _Fields { - constructor({ fields = [], encoding = "utf-8" }) { - this.entries = {}; - fields.forEach(this.setField.bind(this)); - this.encoding = encoding; - } - /** - * Set entry for a {@link Field} name. The `name` - * attribute will be used to key the collection. - * - * @param field The {@link Field} to set. - */ - setField(field) { - this.entries[field.name.toLowerCase()] = field; - } - /** - * Retrieve {@link Field} entry by name. - * - * @param name The name of the {@link Field} entry - * to retrieve - * @returns The {@link Field} if it exists. - */ - getField(name) { - return this.entries[name.toLowerCase()]; - } - /** - * Delete entry from collection. - * - * @param name Name of the entry to delete. - */ - removeField(name) { - delete this.entries[name.toLowerCase()]; - } - /** - * Helper function for retrieving specific types of fields. - * Used to grab all headers or all trailers. - * - * @param kind {@link FieldPosition} of entries to retrieve. - * @returns The {@link Field} entries with the specified - * {@link FieldPosition}. - */ - getByType(kind) { - return Object.values(this.entries).filter((field) => field.kind === kind); - } -}; -__name(_Fields, "Fields"); -var Fields = _Fields; - -// src/httpRequest.ts -var _HttpRequest = class _HttpRequest { - 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 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() { - const cloned = new _HttpRequest({ - ...this, - headers: { ...this.headers } - }); - if (cloned.query) - cloned.query = cloneQuery(cloned.query); - return cloned; - } -}; -__name(_HttpRequest, "HttpRequest"); -var HttpRequest = _HttpRequest; -function cloneQuery(query) { - return Object.keys(query).reduce((carry, paramName) => { - const param = query[paramName]; - return { - ...carry, - [paramName]: Array.isArray(param) ? [...param] : param - }; - }, {}); -} -__name(cloneQuery, "cloneQuery"); - -// src/httpResponse.ts -var _HttpResponse = class _HttpResponse { - 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"; - } -}; -__name(_HttpResponse, "HttpResponse"); -var HttpResponse = _HttpResponse; - -// src/isValidHostname.ts -function isValidHostname(hostname) { - const hostPattern = /^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/; - return hostPattern.test(hostname); -} -__name(isValidHostname, "isValidHostname"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - getHttpHandlerExtensionConfiguration, - resolveHttpHandlerRuntimeConfig, - Field, - Fields, - HttpRequest, - HttpResponse, - isValidHostname -}); - diff --git a/claude-code-source/node_modules/@smithy/querystring-builder/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/querystring-builder/dist-cjs/index.js deleted file mode 100644 index 70302425..00000000 --- a/claude-code-source/node_modules/@smithy/querystring-builder/dist-cjs/index.js +++ /dev/null @@ -1,52 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - buildQueryString: () => buildQueryString -}); -module.exports = __toCommonJS(src_exports); -var import_util_uri_escape = require("@smithy/util-uri-escape"); -function buildQueryString(query) { - const parts = []; - for (let key of Object.keys(query).sort()) { - const value = query[key]; - key = (0, import_util_uri_escape.escapeUri)(key); - if (Array.isArray(value)) { - for (let i = 0, iLen = value.length; i < iLen; i++) { - parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); - } - } else { - let qsEntry = key; - if (value || typeof value === "string") { - qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; - } - parts.push(qsEntry); - } - } - return parts.join("&"); -} -__name(buildQueryString, "buildQueryString"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - buildQueryString -}); - diff --git a/claude-code-source/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js deleted file mode 100644 index 51001efe..00000000 --- a/claude-code-source/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js +++ /dev/null @@ -1,43 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - escapeUri: () => escapeUri, - escapeUriPath: () => escapeUriPath -}); -module.exports = __toCommonJS(src_exports); - -// src/escape-uri.ts -var escapeUri = /* @__PURE__ */ __name((uri) => ( - // AWS percent-encodes some extra non-standard characters in a URI - encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) -), "escapeUri"); -var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); - -// src/escape-uri-path.ts -var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - escapeUri, - escapeUriPath -}); - diff --git a/claude-code-source/node_modules/@smithy/querystring-parser/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/querystring-parser/dist-cjs/index.js deleted file mode 100644 index d1efbf7a..00000000 --- a/claude-code-source/node_modules/@smithy/querystring-parser/dist-cjs/index.js +++ /dev/null @@ -1,27 +0,0 @@ -'use strict'; - -function parseQueryString(querystring) { - const query = {}; - querystring = querystring.replace(/^\?/, ""); - if (querystring) { - for (const pair of querystring.split("&")) { - let [key, value = null] = pair.split("="); - key = decodeURIComponent(key); - if (value) { - value = decodeURIComponent(value); - } - if (!(key in query)) { - query[key] = value; - } - else if (Array.isArray(query[key])) { - query[key].push(value); - } - else { - query[key] = [query[key], value]; - } - } - } - return query; -} - -exports.parseQueryString = parseQueryString; diff --git a/claude-code-source/node_modules/@smithy/service-error-classification/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/service-error-classification/dist-cjs/index.js deleted file mode 100644 index 03f20230..00000000 --- a/claude-code-source/node_modules/@smithy/service-error-classification/dist-cjs/index.js +++ /dev/null @@ -1,77 +0,0 @@ -'use strict'; - -const CLOCK_SKEW_ERROR_CODES = [ - "AuthFailure", - "InvalidSignatureException", - "RequestExpired", - "RequestInTheFuture", - "RequestTimeTooSkewed", - "SignatureDoesNotMatch", -]; -const THROTTLING_ERROR_CODES = [ - "BandwidthLimitExceeded", - "EC2ThrottledException", - "LimitExceededException", - "PriorRequestNotComplete", - "ProvisionedThroughputExceededException", - "RequestLimitExceeded", - "RequestThrottled", - "RequestThrottledException", - "SlowDown", - "ThrottledException", - "Throttling", - "ThrottlingException", - "TooManyRequestsException", - "TransactionInProgressException", -]; -const TRANSIENT_ERROR_CODES = ["TimeoutError", "RequestTimeout", "RequestTimeoutException"]; -const TRANSIENT_ERROR_STATUS_CODES = [500, 502, 503, 504]; -const NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "ECONNREFUSED", "EPIPE", "ETIMEDOUT"]; -const NODEJS_NETWORK_ERROR_CODES = ["EHOSTUNREACH", "ENETUNREACH", "ENOTFOUND"]; - -const isRetryableByTrait = (error) => error?.$retryable !== undefined; -const isClockSkewError = (error) => CLOCK_SKEW_ERROR_CODES.includes(error.name); -const isClockSkewCorrectedError = (error) => error.$metadata?.clockSkewCorrected; -const isBrowserNetworkError = (error) => { - const errorMessages = new Set([ - "Failed to fetch", - "NetworkError when attempting to fetch resource", - "The Internet connection appears to be offline", - "Load failed", - "Network request failed", - ]); - const isValid = error && error instanceof TypeError; - if (!isValid) { - return false; - } - return errorMessages.has(error.message); -}; -const isThrottlingError = (error) => error.$metadata?.httpStatusCode === 429 || - THROTTLING_ERROR_CODES.includes(error.name) || - error.$retryable?.throttling == true; -const isTransientError = (error, depth = 0) => isRetryableByTrait(error) || - isClockSkewCorrectedError(error) || - TRANSIENT_ERROR_CODES.includes(error.name) || - NODEJS_TIMEOUT_ERROR_CODES.includes(error?.code || "") || - NODEJS_NETWORK_ERROR_CODES.includes(error?.code || "") || - TRANSIENT_ERROR_STATUS_CODES.includes(error.$metadata?.httpStatusCode || 0) || - isBrowserNetworkError(error) || - (error.cause !== undefined && depth <= 10 && isTransientError(error.cause, depth + 1)); -const isServerError = (error) => { - if (error.$metadata?.httpStatusCode !== undefined) { - const statusCode = error.$metadata.httpStatusCode; - if (500 <= statusCode && statusCode <= 599 && !isTransientError(error)) { - return true; - } - return false; - } - return false; -}; - -exports.isBrowserNetworkError = isBrowserNetworkError; -exports.isClockSkewCorrectedError = isClockSkewCorrectedError; -exports.isClockSkewError = isClockSkewError; -exports.isRetryableByTrait = isRetryableByTrait; -exports.isServerError = isServerError; -exports.isThrottlingError = isThrottlingError; -exports.isTransientError = isTransientError; diff --git a/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getHomeDir.js b/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getHomeDir.js deleted file mode 100644 index 2a4f7375..00000000 --- a/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getHomeDir.js +++ /dev/null @@ -1,26 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getHomeDir = void 0; -const os_1 = require("os"); -const path_1 = require("path"); -const homeDirCache = {}; -const getHomeDirCacheKey = () => { - if (process && process.geteuid) { - return `${process.geteuid()}`; - } - return "DEFAULT"; -}; -const getHomeDir = () => { - const { HOME, USERPROFILE, HOMEPATH, HOMEDRIVE = `C:${path_1.sep}` } = process.env; - if (HOME) - return HOME; - if (USERPROFILE) - return USERPROFILE; - if (HOMEPATH) - return `${HOMEDRIVE}${HOMEPATH}`; - const homeDirCacheKey = getHomeDirCacheKey(); - if (!homeDirCache[homeDirCacheKey]) - homeDirCache[homeDirCacheKey] = (0, os_1.homedir)(); - return homeDirCache[homeDirCacheKey]; -}; -exports.getHomeDir = getHomeDir; diff --git a/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFilepath.js b/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFilepath.js deleted file mode 100644 index 30d97b3d..00000000 --- a/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFilepath.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getSSOTokenFilepath = void 0; -const crypto_1 = require("crypto"); -const path_1 = require("path"); -const getHomeDir_1 = require("./getHomeDir"); -const getSSOTokenFilepath = (id) => { - const hasher = (0, crypto_1.createHash)("sha1"); - const cacheName = hasher.update(id).digest("hex"); - return (0, path_1.join)((0, getHomeDir_1.getHomeDir)(), ".aws", "sso", "cache", `${cacheName}.json`); -}; -exports.getSSOTokenFilepath = getSSOTokenFilepath; diff --git a/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFromFile.js b/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFromFile.js deleted file mode 100644 index 955e1121..00000000 --- a/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/getSSOTokenFromFile.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getSSOTokenFromFile = exports.tokenIntercept = void 0; -const promises_1 = require("fs/promises"); -const getSSOTokenFilepath_1 = require("./getSSOTokenFilepath"); -exports.tokenIntercept = {}; -const getSSOTokenFromFile = async (id) => { - if (exports.tokenIntercept[id]) { - return exports.tokenIntercept[id]; - } - const ssoTokenFilepath = (0, getSSOTokenFilepath_1.getSSOTokenFilepath)(id); - const ssoTokenText = await (0, promises_1.readFile)(ssoTokenFilepath, "utf8"); - return JSON.parse(ssoTokenText); -}; -exports.getSSOTokenFromFile = getSSOTokenFromFile; diff --git a/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/index.js deleted file mode 100644 index 75693847..00000000 --- a/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/index.js +++ /dev/null @@ -1,194 +0,0 @@ -'use strict'; - -var getHomeDir = require('./getHomeDir'); -var getSSOTokenFilepath = require('./getSSOTokenFilepath'); -var getSSOTokenFromFile = require('./getSSOTokenFromFile'); -var path = require('path'); -var types = require('@smithy/types'); -var readFile = require('./readFile'); - -const ENV_PROFILE = "AWS_PROFILE"; -const DEFAULT_PROFILE = "default"; -const getProfileName = (init) => init.profile || process.env[ENV_PROFILE] || DEFAULT_PROFILE; - -const CONFIG_PREFIX_SEPARATOR = "."; - -const getConfigData = (data) => Object.entries(data) - .filter(([key]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - if (indexOfSeparator === -1) { - return false; - } - return Object.values(types.IniSectionType).includes(key.substring(0, indexOfSeparator)); -}) - .reduce((acc, [key, value]) => { - const indexOfSeparator = key.indexOf(CONFIG_PREFIX_SEPARATOR); - const updatedKey = key.substring(0, indexOfSeparator) === types.IniSectionType.PROFILE ? key.substring(indexOfSeparator + 1) : key; - acc[updatedKey] = value; - return acc; -}, { - ...(data.default && { default: data.default }), -}); - -const ENV_CONFIG_PATH = "AWS_CONFIG_FILE"; -const getConfigFilepath = () => process.env[ENV_CONFIG_PATH] || path.join(getHomeDir.getHomeDir(), ".aws", "config"); - -const ENV_CREDENTIALS_PATH = "AWS_SHARED_CREDENTIALS_FILE"; -const getCredentialsFilepath = () => process.env[ENV_CREDENTIALS_PATH] || path.join(getHomeDir.getHomeDir(), ".aws", "credentials"); - -const prefixKeyRegex = /^([\w-]+)\s(["'])?([\w-@\+\.%:/]+)\2$/; -const profileNameBlockList = ["__proto__", "profile __proto__"]; -const parseIni = (iniData) => { - const map = {}; - let currentSection; - let currentSubSection; - for (const iniLine of iniData.split(/\r?\n/)) { - const trimmedLine = iniLine.split(/(^|\s)[;#]/)[0].trim(); - const isSection = trimmedLine[0] === "[" && trimmedLine[trimmedLine.length - 1] === "]"; - if (isSection) { - currentSection = undefined; - currentSubSection = undefined; - const sectionName = trimmedLine.substring(1, trimmedLine.length - 1); - const matches = prefixKeyRegex.exec(sectionName); - if (matches) { - const [, prefix, , name] = matches; - if (Object.values(types.IniSectionType).includes(prefix)) { - currentSection = [prefix, name].join(CONFIG_PREFIX_SEPARATOR); - } - } - else { - currentSection = sectionName; - } - if (profileNameBlockList.includes(sectionName)) { - throw new Error(`Found invalid profile name "${sectionName}"`); - } - } - else if (currentSection) { - const indexOfEqualsSign = trimmedLine.indexOf("="); - if (![0, -1].includes(indexOfEqualsSign)) { - const [name, value] = [ - trimmedLine.substring(0, indexOfEqualsSign).trim(), - trimmedLine.substring(indexOfEqualsSign + 1).trim(), - ]; - if (value === "") { - currentSubSection = name; - } - else { - if (currentSubSection && iniLine.trimStart() === iniLine) { - currentSubSection = undefined; - } - map[currentSection] = map[currentSection] || {}; - const key = currentSubSection ? [currentSubSection, name].join(CONFIG_PREFIX_SEPARATOR) : name; - map[currentSection][key] = value; - } - } - } - } - return map; -}; - -const swallowError$1 = () => ({}); -const loadSharedConfigFiles = async (init = {}) => { - const { filepath = getCredentialsFilepath(), configFilepath = getConfigFilepath() } = init; - const homeDir = getHomeDir.getHomeDir(); - const relativeHomeDirPrefix = "~/"; - let resolvedFilepath = filepath; - if (filepath.startsWith(relativeHomeDirPrefix)) { - resolvedFilepath = path.join(homeDir, filepath.slice(2)); - } - let resolvedConfigFilepath = configFilepath; - if (configFilepath.startsWith(relativeHomeDirPrefix)) { - resolvedConfigFilepath = path.join(homeDir, configFilepath.slice(2)); - } - const parsedFiles = await Promise.all([ - readFile.readFile(resolvedConfigFilepath, { - ignoreCache: init.ignoreCache, - }) - .then(parseIni) - .then(getConfigData) - .catch(swallowError$1), - readFile.readFile(resolvedFilepath, { - ignoreCache: init.ignoreCache, - }) - .then(parseIni) - .catch(swallowError$1), - ]); - return { - configFile: parsedFiles[0], - credentialsFile: parsedFiles[1], - }; -}; - -const getSsoSessionData = (data) => Object.entries(data) - .filter(([key]) => key.startsWith(types.IniSectionType.SSO_SESSION + CONFIG_PREFIX_SEPARATOR)) - .reduce((acc, [key, value]) => ({ ...acc, [key.substring(key.indexOf(CONFIG_PREFIX_SEPARATOR) + 1)]: value }), {}); - -const swallowError = () => ({}); -const loadSsoSessionData = async (init = {}) => readFile.readFile(init.configFilepath ?? getConfigFilepath()) - .then(parseIni) - .then(getSsoSessionData) - .catch(swallowError); - -const mergeConfigFiles = (...files) => { - const merged = {}; - for (const file of files) { - for (const [key, values] of Object.entries(file)) { - if (merged[key] !== undefined) { - Object.assign(merged[key], values); - } - else { - merged[key] = values; - } - } - } - return merged; -}; - -const parseKnownFiles = async (init) => { - const parsedFiles = await loadSharedConfigFiles(init); - return mergeConfigFiles(parsedFiles.configFile, parsedFiles.credentialsFile); -}; - -const externalDataInterceptor = { - getFileRecord() { - return readFile.fileIntercept; - }, - interceptFile(path, contents) { - readFile.fileIntercept[path] = Promise.resolve(contents); - }, - getTokenRecord() { - return getSSOTokenFromFile.tokenIntercept; - }, - interceptToken(id, contents) { - getSSOTokenFromFile.tokenIntercept[id] = contents; - }, -}; - -Object.defineProperty(exports, "getSSOTokenFromFile", { - enumerable: true, - get: function () { return getSSOTokenFromFile.getSSOTokenFromFile; } -}); -Object.defineProperty(exports, "readFile", { - enumerable: true, - get: function () { return readFile.readFile; } -}); -exports.CONFIG_PREFIX_SEPARATOR = CONFIG_PREFIX_SEPARATOR; -exports.DEFAULT_PROFILE = DEFAULT_PROFILE; -exports.ENV_PROFILE = ENV_PROFILE; -exports.externalDataInterceptor = externalDataInterceptor; -exports.getProfileName = getProfileName; -exports.loadSharedConfigFiles = loadSharedConfigFiles; -exports.loadSsoSessionData = loadSsoSessionData; -exports.parseKnownFiles = parseKnownFiles; -Object.keys(getHomeDir).forEach(function (k) { - if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { - enumerable: true, - get: function () { return getHomeDir[k]; } - }); -}); -Object.keys(getSSOTokenFilepath).forEach(function (k) { - if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { - enumerable: true, - get: function () { return getSSOTokenFilepath[k]; } - }); -}); diff --git a/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/readFile.js b/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/readFile.js deleted file mode 100644 index e2a492fd..00000000 --- a/claude-code-source/node_modules/@smithy/shared-ini-file-loader/dist-cjs/readFile.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.readFile = exports.fileIntercept = exports.filePromises = void 0; -const promises_1 = require("node:fs/promises"); -exports.filePromises = {}; -exports.fileIntercept = {}; -const readFile = (path, options) => { - if (exports.fileIntercept[path] !== undefined) { - return exports.fileIntercept[path]; - } - if (!exports.filePromises[path] || options?.ignoreCache) { - exports.filePromises[path] = (0, promises_1.readFile)(path, "utf8"); - } - return exports.filePromises[path]; -}; -exports.readFile = readFile; diff --git a/claude-code-source/node_modules/@smithy/shared-ini-file-loader/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/shared-ini-file-loader/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@smithy/shared-ini-file-loader/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/signature-v4/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/signature-v4/dist-cjs/index.js deleted file mode 100644 index fc678618..00000000 --- a/claude-code-source/node_modules/@smithy/signature-v4/dist-cjs/index.js +++ /dev/null @@ -1,589 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - SignatureV4: () => SignatureV4, - clearCredentialCache: () => clearCredentialCache, - createScope: () => createScope, - getCanonicalHeaders: () => getCanonicalHeaders, - getCanonicalQuery: () => getCanonicalQuery, - getPayloadHash: () => getPayloadHash, - getSigningKey: () => getSigningKey, - moveHeadersToQuery: () => moveHeadersToQuery, - prepareRequest: () => prepareRequest -}); -module.exports = __toCommonJS(src_exports); - -// src/SignatureV4.ts - -var import_util_middleware = require("@smithy/util-middleware"); - -var import_util_utf84 = require("@smithy/util-utf8"); - -// src/constants.ts -var ALGORITHM_QUERY_PARAM = "X-Amz-Algorithm"; -var CREDENTIAL_QUERY_PARAM = "X-Amz-Credential"; -var AMZ_DATE_QUERY_PARAM = "X-Amz-Date"; -var SIGNED_HEADERS_QUERY_PARAM = "X-Amz-SignedHeaders"; -var EXPIRES_QUERY_PARAM = "X-Amz-Expires"; -var SIGNATURE_QUERY_PARAM = "X-Amz-Signature"; -var TOKEN_QUERY_PARAM = "X-Amz-Security-Token"; -var AUTH_HEADER = "authorization"; -var AMZ_DATE_HEADER = AMZ_DATE_QUERY_PARAM.toLowerCase(); -var DATE_HEADER = "date"; -var GENERATED_HEADERS = [AUTH_HEADER, AMZ_DATE_HEADER, DATE_HEADER]; -var SIGNATURE_HEADER = SIGNATURE_QUERY_PARAM.toLowerCase(); -var SHA256_HEADER = "x-amz-content-sha256"; -var TOKEN_HEADER = TOKEN_QUERY_PARAM.toLowerCase(); -var ALWAYS_UNSIGNABLE_HEADERS = { - authorization: true, - "cache-control": true, - connection: true, - expect: true, - from: true, - "keep-alive": true, - "max-forwards": true, - pragma: true, - referer: true, - te: true, - trailer: true, - "transfer-encoding": true, - upgrade: true, - "user-agent": true, - "x-amzn-trace-id": true -}; -var PROXY_HEADER_PATTERN = /^proxy-/; -var SEC_HEADER_PATTERN = /^sec-/; -var ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256"; -var EVENT_ALGORITHM_IDENTIFIER = "AWS4-HMAC-SHA256-PAYLOAD"; -var UNSIGNED_PAYLOAD = "UNSIGNED-PAYLOAD"; -var MAX_CACHE_SIZE = 50; -var KEY_TYPE_IDENTIFIER = "aws4_request"; -var MAX_PRESIGNED_TTL = 60 * 60 * 24 * 7; - -// src/credentialDerivation.ts -var import_util_hex_encoding = require("@smithy/util-hex-encoding"); -var import_util_utf8 = require("@smithy/util-utf8"); -var signingKeyCache = {}; -var cacheQueue = []; -var createScope = /* @__PURE__ */ __name((shortDate, region, service) => `${shortDate}/${region}/${service}/${KEY_TYPE_IDENTIFIER}`, "createScope"); -var getSigningKey = /* @__PURE__ */ __name(async (sha256Constructor, credentials, shortDate, region, service) => { - const credsHash = await hmac(sha256Constructor, credentials.secretAccessKey, credentials.accessKeyId); - const cacheKey = `${shortDate}:${region}:${service}:${(0, import_util_hex_encoding.toHex)(credsHash)}:${credentials.sessionToken}`; - if (cacheKey in signingKeyCache) { - return signingKeyCache[cacheKey]; - } - cacheQueue.push(cacheKey); - while (cacheQueue.length > MAX_CACHE_SIZE) { - delete signingKeyCache[cacheQueue.shift()]; - } - let key = `AWS4${credentials.secretAccessKey}`; - for (const signable of [shortDate, region, service, KEY_TYPE_IDENTIFIER]) { - key = await hmac(sha256Constructor, key, signable); - } - return signingKeyCache[cacheKey] = key; -}, "getSigningKey"); -var clearCredentialCache = /* @__PURE__ */ __name(() => { - cacheQueue.length = 0; - Object.keys(signingKeyCache).forEach((cacheKey) => { - delete signingKeyCache[cacheKey]; - }); -}, "clearCredentialCache"); -var hmac = /* @__PURE__ */ __name((ctor, secret, data) => { - const hash = new ctor(secret); - hash.update((0, import_util_utf8.toUint8Array)(data)); - return hash.digest(); -}, "hmac"); - -// src/getCanonicalHeaders.ts -var getCanonicalHeaders = /* @__PURE__ */ __name(({ headers }, unsignableHeaders, signableHeaders) => { - const canonical = {}; - for (const headerName of Object.keys(headers).sort()) { - if (headers[headerName] == void 0) { - continue; - } - const canonicalHeaderName = headerName.toLowerCase(); - if (canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS || (unsignableHeaders == null ? void 0 : unsignableHeaders.has(canonicalHeaderName)) || PROXY_HEADER_PATTERN.test(canonicalHeaderName) || SEC_HEADER_PATTERN.test(canonicalHeaderName)) { - if (!signableHeaders || signableHeaders && !signableHeaders.has(canonicalHeaderName)) { - continue; - } - } - canonical[canonicalHeaderName] = headers[headerName].trim().replace(/\s+/g, " "); - } - return canonical; -}, "getCanonicalHeaders"); - -// src/getCanonicalQuery.ts -var import_util_uri_escape = require("@smithy/util-uri-escape"); -var getCanonicalQuery = /* @__PURE__ */ __name(({ query = {} }) => { - const keys = []; - const serialized = {}; - for (const key of Object.keys(query).sort()) { - if (key.toLowerCase() === SIGNATURE_HEADER) { - continue; - } - keys.push(key); - const value = query[key]; - if (typeof value === "string") { - serialized[key] = `${(0, import_util_uri_escape.escapeUri)(key)}=${(0, import_util_uri_escape.escapeUri)(value)}`; - } else if (Array.isArray(value)) { - serialized[key] = value.slice(0).reduce( - (encoded, value2) => encoded.concat([`${(0, import_util_uri_escape.escapeUri)(key)}=${(0, import_util_uri_escape.escapeUri)(value2)}`]), - [] - ).sort().join("&"); - } - } - return keys.map((key) => serialized[key]).filter((serialized2) => serialized2).join("&"); -}, "getCanonicalQuery"); - -// src/getPayloadHash.ts -var import_is_array_buffer = require("@smithy/is-array-buffer"); - -var import_util_utf82 = require("@smithy/util-utf8"); -var getPayloadHash = /* @__PURE__ */ __name(async ({ headers, body }, hashConstructor) => { - for (const headerName of Object.keys(headers)) { - if (headerName.toLowerCase() === SHA256_HEADER) { - return headers[headerName]; - } - } - if (body == void 0) { - return "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"; - } else if (typeof body === "string" || ArrayBuffer.isView(body) || (0, import_is_array_buffer.isArrayBuffer)(body)) { - const hashCtor = new hashConstructor(); - hashCtor.update((0, import_util_utf82.toUint8Array)(body)); - return (0, import_util_hex_encoding.toHex)(await hashCtor.digest()); - } - return UNSIGNED_PAYLOAD; -}, "getPayloadHash"); - -// src/HeaderFormatter.ts - -var import_util_utf83 = require("@smithy/util-utf8"); -var _HeaderFormatter = class _HeaderFormatter { - format(headers) { - const chunks = []; - for (const headerName of Object.keys(headers)) { - const bytes = (0, import_util_utf83.fromUtf8)(headerName); - chunks.push(Uint8Array.from([bytes.byteLength]), bytes, this.formatHeaderValue(headers[headerName])); - } - const out = new Uint8Array(chunks.reduce((carry, bytes) => carry + bytes.byteLength, 0)); - let position = 0; - for (const chunk of chunks) { - out.set(chunk, position); - position += chunk.byteLength; - } - return out; - } - formatHeaderValue(header) { - switch (header.type) { - case "boolean": - return Uint8Array.from([header.value ? 0 /* boolTrue */ : 1 /* boolFalse */]); - case "byte": - return Uint8Array.from([2 /* byte */, header.value]); - case "short": - const shortView = new DataView(new ArrayBuffer(3)); - shortView.setUint8(0, 3 /* short */); - shortView.setInt16(1, header.value, false); - return new Uint8Array(shortView.buffer); - case "integer": - const intView = new DataView(new ArrayBuffer(5)); - intView.setUint8(0, 4 /* integer */); - intView.setInt32(1, header.value, false); - return new Uint8Array(intView.buffer); - case "long": - const longBytes = new Uint8Array(9); - longBytes[0] = 5 /* long */; - longBytes.set(header.value.bytes, 1); - return longBytes; - case "binary": - const binView = new DataView(new ArrayBuffer(3 + header.value.byteLength)); - binView.setUint8(0, 6 /* byteArray */); - binView.setUint16(1, header.value.byteLength, false); - const binBytes = new Uint8Array(binView.buffer); - binBytes.set(header.value, 3); - return binBytes; - case "string": - const utf8Bytes = (0, import_util_utf83.fromUtf8)(header.value); - const strView = new DataView(new ArrayBuffer(3 + utf8Bytes.byteLength)); - strView.setUint8(0, 7 /* string */); - strView.setUint16(1, utf8Bytes.byteLength, false); - const strBytes = new Uint8Array(strView.buffer); - strBytes.set(utf8Bytes, 3); - return strBytes; - case "timestamp": - const tsBytes = new Uint8Array(9); - tsBytes[0] = 8 /* timestamp */; - tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes, 1); - return tsBytes; - case "uuid": - if (!UUID_PATTERN.test(header.value)) { - throw new Error(`Invalid UUID received: ${header.value}`); - } - const uuidBytes = new Uint8Array(17); - uuidBytes[0] = 9 /* uuid */; - uuidBytes.set((0, import_util_hex_encoding.fromHex)(header.value.replace(/\-/g, "")), 1); - return uuidBytes; - } - } -}; -__name(_HeaderFormatter, "HeaderFormatter"); -var HeaderFormatter = _HeaderFormatter; -var UUID_PATTERN = /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/; -var _Int64 = class _Int64 { - constructor(bytes) { - this.bytes = bytes; - if (bytes.byteLength !== 8) { - throw new Error("Int64 buffers must be exactly 8 bytes"); - } - } - static fromNumber(number) { - if (number > 9223372036854776e3 || number < -9223372036854776e3) { - throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`); - } - const bytes = new Uint8Array(8); - for (let i = 7, remaining = Math.abs(Math.round(number)); i > -1 && remaining > 0; i--, remaining /= 256) { - bytes[i] = remaining; - } - if (number < 0) { - negate(bytes); - } - return new _Int64(bytes); - } - /** - * Called implicitly by infix arithmetic operators. - */ - valueOf() { - const bytes = this.bytes.slice(0); - const negative = bytes[0] & 128; - if (negative) { - negate(bytes); - } - return parseInt((0, import_util_hex_encoding.toHex)(bytes), 16) * (negative ? -1 : 1); - } - toString() { - return String(this.valueOf()); - } -}; -__name(_Int64, "Int64"); -var Int64 = _Int64; -function negate(bytes) { - for (let i = 0; i < 8; i++) { - bytes[i] ^= 255; - } - for (let i = 7; i > -1; i--) { - bytes[i]++; - if (bytes[i] !== 0) - break; - } -} -__name(negate, "negate"); - -// src/headerUtil.ts -var hasHeader = /* @__PURE__ */ __name((soughtHeader, headers) => { - soughtHeader = soughtHeader.toLowerCase(); - for (const headerName of Object.keys(headers)) { - if (soughtHeader === headerName.toLowerCase()) { - return true; - } - } - return false; -}, "hasHeader"); - -// src/cloneRequest.ts -var cloneRequest = /* @__PURE__ */ __name(({ headers, query, ...rest }) => ({ - ...rest, - headers: { ...headers }, - query: query ? cloneQuery(query) : void 0 -}), "cloneRequest"); -var cloneQuery = /* @__PURE__ */ __name((query) => Object.keys(query).reduce((carry, paramName) => { - const param = query[paramName]; - return { - ...carry, - [paramName]: Array.isArray(param) ? [...param] : param - }; -}, {}), "cloneQuery"); - -// src/moveHeadersToQuery.ts -var moveHeadersToQuery = /* @__PURE__ */ __name((request, options = {}) => { - var _a; - const { headers, query = {} } = typeof request.clone === "function" ? request.clone() : cloneRequest(request); - for (const name of Object.keys(headers)) { - const lname = name.toLowerCase(); - if (lname.slice(0, 6) === "x-amz-" && !((_a = options.unhoistableHeaders) == null ? void 0 : _a.has(lname))) { - query[name] = headers[name]; - delete headers[name]; - } - } - return { - ...request, - headers, - query - }; -}, "moveHeadersToQuery"); - -// src/prepareRequest.ts -var prepareRequest = /* @__PURE__ */ __name((request) => { - request = typeof request.clone === "function" ? request.clone() : cloneRequest(request); - for (const headerName of Object.keys(request.headers)) { - if (GENERATED_HEADERS.indexOf(headerName.toLowerCase()) > -1) { - delete request.headers[headerName]; - } - } - return request; -}, "prepareRequest"); - -// src/utilDate.ts -var iso8601 = /* @__PURE__ */ __name((time) => toDate(time).toISOString().replace(/\.\d{3}Z$/, "Z"), "iso8601"); -var toDate = /* @__PURE__ */ __name((time) => { - if (typeof time === "number") { - return new Date(time * 1e3); - } - if (typeof time === "string") { - if (Number(time)) { - return new Date(Number(time) * 1e3); - } - return new Date(time); - } - return time; -}, "toDate"); - -// src/SignatureV4.ts -var _SignatureV4 = class _SignatureV4 { - constructor({ - applyChecksum, - credentials, - region, - service, - sha256, - uriEscapePath = true - }) { - this.headerFormatter = new HeaderFormatter(); - this.service = service; - this.sha256 = sha256; - this.uriEscapePath = uriEscapePath; - this.applyChecksum = typeof applyChecksum === "boolean" ? applyChecksum : true; - this.regionProvider = (0, import_util_middleware.normalizeProvider)(region); - this.credentialProvider = (0, import_util_middleware.normalizeProvider)(credentials); - } - async presign(originalRequest, options = {}) { - const { - signingDate = /* @__PURE__ */ new Date(), - expiresIn = 3600, - unsignableHeaders, - unhoistableHeaders, - signableHeaders, - signingRegion, - signingService - } = options; - const credentials = await this.credentialProvider(); - this.validateResolvedCredentials(credentials); - const region = signingRegion ?? await this.regionProvider(); - const { longDate, shortDate } = formatDate(signingDate); - if (expiresIn > MAX_PRESIGNED_TTL) { - return Promise.reject( - "Signature version 4 presigned URLs must have an expiration date less than one week in the future" - ); - } - const scope = createScope(shortDate, region, signingService ?? this.service); - const request = moveHeadersToQuery(prepareRequest(originalRequest), { unhoistableHeaders }); - if (credentials.sessionToken) { - request.query[TOKEN_QUERY_PARAM] = credentials.sessionToken; - } - request.query[ALGORITHM_QUERY_PARAM] = ALGORITHM_IDENTIFIER; - request.query[CREDENTIAL_QUERY_PARAM] = `${credentials.accessKeyId}/${scope}`; - request.query[AMZ_DATE_QUERY_PARAM] = longDate; - request.query[EXPIRES_QUERY_PARAM] = expiresIn.toString(10); - const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); - request.query[SIGNED_HEADERS_QUERY_PARAM] = getCanonicalHeaderList(canonicalHeaders); - request.query[SIGNATURE_QUERY_PARAM] = await this.getSignature( - longDate, - scope, - this.getSigningKey(credentials, region, shortDate, signingService), - this.createCanonicalRequest(request, canonicalHeaders, await getPayloadHash(originalRequest, this.sha256)) - ); - return request; - } - async sign(toSign, options) { - if (typeof toSign === "string") { - return this.signString(toSign, options); - } else if (toSign.headers && toSign.payload) { - return this.signEvent(toSign, options); - } else if (toSign.message) { - return this.signMessage(toSign, options); - } else { - return this.signRequest(toSign, options); - } - } - async signEvent({ headers, payload }, { signingDate = /* @__PURE__ */ new Date(), priorSignature, signingRegion, signingService }) { - const region = signingRegion ?? await this.regionProvider(); - const { shortDate, longDate } = formatDate(signingDate); - const scope = createScope(shortDate, region, signingService ?? this.service); - const hashedPayload = await getPayloadHash({ headers: {}, body: payload }, this.sha256); - const hash = new this.sha256(); - hash.update(headers); - const hashedHeaders = (0, import_util_hex_encoding.toHex)(await hash.digest()); - const stringToSign = [ - EVENT_ALGORITHM_IDENTIFIER, - longDate, - scope, - priorSignature, - hashedHeaders, - hashedPayload - ].join("\n"); - return this.signString(stringToSign, { signingDate, signingRegion: region, signingService }); - } - async signMessage(signableMessage, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService }) { - const promise = this.signEvent( - { - headers: this.headerFormatter.format(signableMessage.message.headers), - payload: signableMessage.message.body - }, - { - signingDate, - signingRegion, - signingService, - priorSignature: signableMessage.priorSignature - } - ); - return promise.then((signature) => { - return { message: signableMessage.message, signature }; - }); - } - async signString(stringToSign, { signingDate = /* @__PURE__ */ new Date(), signingRegion, signingService } = {}) { - const credentials = await this.credentialProvider(); - this.validateResolvedCredentials(credentials); - const region = signingRegion ?? await this.regionProvider(); - const { shortDate } = formatDate(signingDate); - const hash = new this.sha256(await this.getSigningKey(credentials, region, shortDate, signingService)); - hash.update((0, import_util_utf84.toUint8Array)(stringToSign)); - return (0, import_util_hex_encoding.toHex)(await hash.digest()); - } - async signRequest(requestToSign, { - signingDate = /* @__PURE__ */ new Date(), - signableHeaders, - unsignableHeaders, - signingRegion, - signingService - } = {}) { - const credentials = await this.credentialProvider(); - this.validateResolvedCredentials(credentials); - const region = signingRegion ?? await this.regionProvider(); - const request = prepareRequest(requestToSign); - const { longDate, shortDate } = formatDate(signingDate); - const scope = createScope(shortDate, region, signingService ?? this.service); - request.headers[AMZ_DATE_HEADER] = longDate; - if (credentials.sessionToken) { - request.headers[TOKEN_HEADER] = credentials.sessionToken; - } - const payloadHash = await getPayloadHash(request, this.sha256); - if (!hasHeader(SHA256_HEADER, request.headers) && this.applyChecksum) { - request.headers[SHA256_HEADER] = payloadHash; - } - const canonicalHeaders = getCanonicalHeaders(request, unsignableHeaders, signableHeaders); - const signature = await this.getSignature( - longDate, - scope, - this.getSigningKey(credentials, region, shortDate, signingService), - this.createCanonicalRequest(request, canonicalHeaders, payloadHash) - ); - request.headers[AUTH_HEADER] = `${ALGORITHM_IDENTIFIER} Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`; - return request; - } - createCanonicalRequest(request, canonicalHeaders, payloadHash) { - const sortedHeaders = Object.keys(canonicalHeaders).sort(); - return `${request.method} -${this.getCanonicalPath(request)} -${getCanonicalQuery(request)} -${sortedHeaders.map((name) => `${name}:${canonicalHeaders[name]}`).join("\n")} - -${sortedHeaders.join(";")} -${payloadHash}`; - } - async createStringToSign(longDate, credentialScope, canonicalRequest) { - const hash = new this.sha256(); - hash.update((0, import_util_utf84.toUint8Array)(canonicalRequest)); - const hashedRequest = await hash.digest(); - return `${ALGORITHM_IDENTIFIER} -${longDate} -${credentialScope} -${(0, import_util_hex_encoding.toHex)(hashedRequest)}`; - } - getCanonicalPath({ path }) { - if (this.uriEscapePath) { - const normalizedPathSegments = []; - for (const pathSegment of path.split("/")) { - if ((pathSegment == null ? void 0 : pathSegment.length) === 0) - continue; - if (pathSegment === ".") - continue; - if (pathSegment === "..") { - normalizedPathSegments.pop(); - } else { - normalizedPathSegments.push(pathSegment); - } - } - const normalizedPath = `${(path == null ? void 0 : path.startsWith("/")) ? "/" : ""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length > 0 && (path == null ? void 0 : path.endsWith("/")) ? "/" : ""}`; - const doubleEncoded = (0, import_util_uri_escape.escapeUri)(normalizedPath); - return doubleEncoded.replace(/%2F/g, "/"); - } - return path; - } - async getSignature(longDate, credentialScope, keyPromise, canonicalRequest) { - const stringToSign = await this.createStringToSign(longDate, credentialScope, canonicalRequest); - const hash = new this.sha256(await keyPromise); - hash.update((0, import_util_utf84.toUint8Array)(stringToSign)); - return (0, import_util_hex_encoding.toHex)(await hash.digest()); - } - getSigningKey(credentials, region, shortDate, service) { - return getSigningKey(this.sha256, credentials, shortDate, region, service || this.service); - } - validateResolvedCredentials(credentials) { - if (typeof credentials !== "object" || // @ts-expect-error: Property 'accessKeyId' does not exist on type 'object'.ts(2339) - typeof credentials.accessKeyId !== "string" || // @ts-expect-error: Property 'secretAccessKey' does not exist on type 'object'.ts(2339) - typeof credentials.secretAccessKey !== "string") { - throw new Error("Resolved credential object is not valid"); - } - } -}; -__name(_SignatureV4, "SignatureV4"); -var SignatureV4 = _SignatureV4; -var formatDate = /* @__PURE__ */ __name((now) => { - const longDate = iso8601(now).replace(/[\-:]/g, ""); - return { - longDate, - shortDate: longDate.slice(0, 8) - }; -}, "formatDate"); -var getCanonicalHeaderList = /* @__PURE__ */ __name((headers) => Object.keys(headers).sort().join(";"), "getCanonicalHeaderList"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - getCanonicalHeaders, - getCanonicalQuery, - getPayloadHash, - moveHeadersToQuery, - prepareRequest, - SignatureV4, - createScope, - getSigningKey, - clearCredentialCache -}); - diff --git a/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index b22a90a6..00000000 --- a/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,149 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig -}); -module.exports = __toCommonJS(src_exports); - -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); - -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); - -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); - -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: () => "sha256" /* SHA256 */, - checksumConstructor: () => runtimeConfig.sha256 - }); - } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: () => "md5" /* MD5 */, - checksumConstructor: () => runtimeConfig.md5 - }); - } - return { - _checksumAlgorithms: checksumAlgorithms, - addChecksumAlgorithm(algo) { - this._checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return this._checksumAlgorithms; - } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); - -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - ...getChecksumConfiguration(runtimeConfig) - }; -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return { - ...resolveChecksumRuntimeConfig(config) - }; -}, "resolveDefaultRuntimeConfig"); - -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); - -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; - -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); - -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - HttpAuthLocation, - HttpApiKeyAuthLocation, - EndpointURLScheme, - AlgorithmId, - getDefaultClientConfiguration, - resolveDefaultRuntimeConfig, - FieldPosition, - SMITHY_CONTEXT_KEY, - IniSectionType, - RequestHandlerProtocol -}); - diff --git a/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-middleware/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-middleware/dist-cjs/index.js deleted file mode 100644 index dfccf176..00000000 --- a/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-middleware/dist-cjs/index.js +++ /dev/null @@ -1,45 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - getSmithyContext: () => getSmithyContext, - normalizeProvider: () => normalizeProvider -}); -module.exports = __toCommonJS(src_exports); - -// src/getSmithyContext.ts -var import_types = require("@smithy/types"); -var getSmithyContext = /* @__PURE__ */ __name((context) => context[import_types.SMITHY_CONTEXT_KEY] || (context[import_types.SMITHY_CONTEXT_KEY] = {}), "getSmithyContext"); - -// src/normalizeProvider.ts -var normalizeProvider = /* @__PURE__ */ __name((input) => { - if (typeof input === "function") - return input; - const promisified = Promise.resolve(input); - return () => promisified; -}, "normalizeProvider"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - getSmithyContext, - normalizeProvider -}); - diff --git a/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8/dist-cjs/index.js deleted file mode 100644 index 0b22680a..00000000 --- a/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8/dist-cjs/index.js +++ /dev/null @@ -1,65 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - fromUtf8: () => fromUtf8, - toUint8Array: () => toUint8Array, - toUtf8: () => toUtf8 -}); -module.exports = __toCommonJS(src_exports); - -// src/fromUtf8.ts -var import_util_buffer_from = require("@smithy/util-buffer-from"); -var fromUtf8 = /* @__PURE__ */ __name((input) => { - const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); -}, "fromUtf8"); - -// src/toUint8Array.ts -var toUint8Array = /* @__PURE__ */ __name((data) => { - if (typeof data === "string") { - return fromUtf8(data); - } - if (ArrayBuffer.isView(data)) { - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); - } - return new Uint8Array(data); -}, "toUint8Array"); - -// src/toUtf8.ts - -var toUtf8 = /* @__PURE__ */ __name((input) => { - if (typeof input === "string") { - return input; - } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); - } - return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); -}, "toUtf8"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - fromUtf8, - toUint8Array, - toUtf8 -}); - diff --git a/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/dist-cjs/index.js deleted file mode 100644 index c6738d94..00000000 --- a/claude-code-source/node_modules/@smithy/signature-v4/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/dist-cjs/index.js +++ /dev/null @@ -1,47 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - fromArrayBuffer: () => fromArrayBuffer, - fromString: () => fromString -}); -module.exports = __toCommonJS(src_exports); -var import_is_array_buffer = require("@smithy/is-array-buffer"); -var import_buffer = require("buffer"); -var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { - if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { - throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); - } - return import_buffer.Buffer.from(input, offset, length); -}, "fromArrayBuffer"); -var fromString = /* @__PURE__ */ __name((input, encoding) => { - if (typeof input !== "string") { - throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); - } - return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); -}, "fromString"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - fromArrayBuffer, - fromString -}); - diff --git a/claude-code-source/node_modules/@smithy/smithy-client/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/smithy-client/dist-cjs/index.js deleted file mode 100644 index 6d1e298c..00000000 --- a/claude-code-source/node_modules/@smithy/smithy-client/dist-cjs/index.js +++ /dev/null @@ -1,1256 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - Client: () => Client, - Command: () => Command, - LazyJsonString: () => LazyJsonString, - NoOpLogger: () => NoOpLogger, - SENSITIVE_STRING: () => SENSITIVE_STRING, - ServiceException: () => ServiceException, - StringWrapper: () => StringWrapper, - _json: () => _json, - collectBody: () => collectBody, - convertMap: () => convertMap, - createAggregatedClient: () => createAggregatedClient, - dateToUtcString: () => dateToUtcString, - decorateServiceException: () => decorateServiceException, - emitWarningIfUnsupportedVersion: () => emitWarningIfUnsupportedVersion, - expectBoolean: () => expectBoolean, - expectByte: () => expectByte, - expectFloat32: () => expectFloat32, - expectInt: () => expectInt, - expectInt32: () => expectInt32, - expectLong: () => expectLong, - expectNonNull: () => expectNonNull, - expectNumber: () => expectNumber, - expectObject: () => expectObject, - expectShort: () => expectShort, - expectString: () => expectString, - expectUnion: () => expectUnion, - extendedEncodeURIComponent: () => extendedEncodeURIComponent, - getArrayIfSingleItem: () => getArrayIfSingleItem, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - getDefaultExtensionConfiguration: () => getDefaultExtensionConfiguration, - getValueFromTextNode: () => getValueFromTextNode, - handleFloat: () => handleFloat, - limitedParseDouble: () => limitedParseDouble, - limitedParseFloat: () => limitedParseFloat, - limitedParseFloat32: () => limitedParseFloat32, - loadConfigsForDefaultMode: () => loadConfigsForDefaultMode, - logger: () => logger, - map: () => map, - parseBoolean: () => parseBoolean, - parseEpochTimestamp: () => parseEpochTimestamp, - parseRfc3339DateTime: () => parseRfc3339DateTime, - parseRfc3339DateTimeWithOffset: () => parseRfc3339DateTimeWithOffset, - parseRfc7231DateTime: () => parseRfc7231DateTime, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig, - resolvedPath: () => resolvedPath, - serializeFloat: () => serializeFloat, - splitEvery: () => splitEvery, - strictParseByte: () => strictParseByte, - strictParseDouble: () => strictParseDouble, - strictParseFloat: () => strictParseFloat, - strictParseFloat32: () => strictParseFloat32, - strictParseInt: () => strictParseInt, - strictParseInt32: () => strictParseInt32, - strictParseLong: () => strictParseLong, - strictParseShort: () => strictParseShort, - take: () => take, - throwDefaultError: () => throwDefaultError, - withBaseException: () => withBaseException -}); -module.exports = __toCommonJS(src_exports); - -// src/NoOpLogger.ts -var _NoOpLogger = class _NoOpLogger { - trace() { - } - debug() { - } - info() { - } - warn() { - } - error() { - } -}; -__name(_NoOpLogger, "NoOpLogger"); -var NoOpLogger = _NoOpLogger; - -// src/client.ts -var import_middleware_stack = require("@smithy/middleware-stack"); -var _Client = class _Client { - constructor(config) { - this.middlewareStack = (0, import_middleware_stack.constructStack)(); - this.config = config; - } - send(command, optionsOrCb, cb) { - const options = typeof optionsOrCb !== "function" ? optionsOrCb : void 0; - const callback = typeof optionsOrCb === "function" ? optionsOrCb : cb; - const handler = command.resolveMiddleware(this.middlewareStack, this.config, options); - if (callback) { - handler(command).then( - (result) => callback(null, result.output), - (err) => callback(err) - ).catch( - // prevent any errors thrown in the callback from triggering an - // unhandled promise rejection - () => { - } - ); - } else { - return handler(command).then((result) => result.output); - } - } - destroy() { - if (this.config.requestHandler.destroy) - this.config.requestHandler.destroy(); - } -}; -__name(_Client, "Client"); -var Client = _Client; - -// src/collect-stream-body.ts -var import_util_stream = require("@smithy/util-stream"); -var collectBody = /* @__PURE__ */ __name(async (streamBody = new Uint8Array(), context) => { - if (streamBody instanceof Uint8Array) { - return import_util_stream.Uint8ArrayBlobAdapter.mutate(streamBody); - } - if (!streamBody) { - return import_util_stream.Uint8ArrayBlobAdapter.mutate(new Uint8Array()); - } - const fromContext = context.streamCollector(streamBody); - return import_util_stream.Uint8ArrayBlobAdapter.mutate(await fromContext); -}, "collectBody"); - -// src/command.ts - -var import_types = require("@smithy/types"); -var _Command = class _Command { - constructor() { - this.middlewareStack = (0, import_middleware_stack.constructStack)(); - } - /** - * Factory for Command ClassBuilder. - * @internal - */ - static classBuilder() { - return new ClassBuilder(); - } - /** - * @internal - */ - 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: logger2 } = configuration; - const handlerExecutionContext = { - logger: logger2, - clientName, - commandName, - inputFilterSensitiveLog, - outputFilterSensitiveLog, - [import_types.SMITHY_CONTEXT_KEY]: { - ...smithyContext - }, - ...additionalContext - }; - const { requestHandler } = configuration; - return stack.resolve( - (request) => requestHandler.handle(request.request, options || {}), - handlerExecutionContext - ); - } -}; -__name(_Command, "Command"); -var Command = _Command; -var _ClassBuilder = class _ClassBuilder { - constructor() { - this._init = () => { - }; - this._ep = {}; - this._middlewareFn = () => []; - this._commandName = ""; - this._clientName = ""; - this._additionalContext = {}; - this._smithyContext = {}; - this._inputFilterSensitiveLog = (_) => _; - this._outputFilterSensitiveLog = (_) => _; - this._serializer = null; - this._deserializer = null; - } - /** - * Optional init callback. - */ - init(cb) { - this._init = cb; - } - /** - * Set the endpoint parameter instructions. - */ - ep(endpointParameterInstructions) { - this._ep = endpointParameterInstructions; - return this; - } - /** - * Add any number of middleware. - */ - m(middlewareSupplier) { - this._middlewareFn = middlewareSupplier; - return this; - } - /** - * Set the initial handler execution context Smithy field. - */ - s(service, operation, smithyContext = {}) { - this._smithyContext = { - service, - operation, - ...smithyContext - }; - return this; - } - /** - * Set the initial handler execution context. - */ - c(additionalContext = {}) { - this._additionalContext = additionalContext; - return this; - } - /** - * Set constant string identifiers for the operation. - */ - n(clientName, commandName) { - this._clientName = clientName; - this._commandName = commandName; - return this; - } - /** - * Set the input and output sensistive log filters. - */ - f(inputFilter = (_) => _, outputFilter = (_) => _) { - this._inputFilterSensitiveLog = inputFilter; - this._outputFilterSensitiveLog = outputFilter; - return this; - } - /** - * Sets the serializer. - */ - ser(serializer) { - this._serializer = serializer; - return this; - } - /** - * Sets the deserializer. - */ - de(deserializer) { - this._deserializer = deserializer; - return this; - } - /** - * @returns a Command class with the classBuilder properties. - */ - build() { - var _a; - const closure = this; - let CommandRef; - return CommandRef = (_a = class extends Command { - /** - * @public - */ - constructor(...[input]) { - super(); - /** - * @internal - */ - // @ts-ignore used in middlewareFn closure. - this.serialize = closure._serializer; - /** - * @internal - */ - // @ts-ignore used in middlewareFn closure. - this.deserialize = closure._deserializer; - this.input = input ?? {}; - closure._init(this); - } - /** - * @public - */ - static getEndpointParameterInstructions() { - return closure._ep; - } - /** - * @internal - */ - resolveMiddleware(stack, configuration, options) { - return this.resolveMiddlewareWithContext(stack, configuration, options, { - CommandCtor: CommandRef, - middlewareFn: closure._middlewareFn, - clientName: closure._clientName, - commandName: closure._commandName, - inputFilterSensitiveLog: closure._inputFilterSensitiveLog, - outputFilterSensitiveLog: closure._outputFilterSensitiveLog, - smithyContext: closure._smithyContext, - additionalContext: closure._additionalContext - }); - } - }, __name(_a, "CommandRef"), _a); - } -}; -__name(_ClassBuilder, "ClassBuilder"); -var ClassBuilder = _ClassBuilder; - -// src/constants.ts -var SENSITIVE_STRING = "***SensitiveInformation***"; - -// src/create-aggregated-client.ts -var createAggregatedClient = /* @__PURE__ */ __name((commands, Client2) => { - for (const command of Object.keys(commands)) { - const CommandCtor = commands[command]; - const methodImpl = /* @__PURE__ */ __name(async function(args, optionsOrCb, cb) { - const command2 = new CommandCtor(args); - if (typeof optionsOrCb === "function") { - this.send(command2, optionsOrCb); - } else if (typeof cb === "function") { - if (typeof optionsOrCb !== "object") - throw new Error(`Expected http options but got ${typeof optionsOrCb}`); - this.send(command2, optionsOrCb || {}, cb); - } else { - return this.send(command2, optionsOrCb); - } - }, "methodImpl"); - const methodName = (command[0].toLowerCase() + command.slice(1)).replace(/Command$/, ""); - Client2.prototype[methodName] = methodImpl; - } -}, "createAggregatedClient"); - -// src/parse-utils.ts -var parseBoolean = /* @__PURE__ */ __name((value) => { - switch (value) { - case "true": - return true; - case "false": - return false; - default: - throw new Error(`Unable to parse boolean value "${value}"`); - } -}, "parseBoolean"); -var expectBoolean = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "number") { - if (value === 0 || value === 1) { - logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); - } - if (value === 0) { - return false; - } - if (value === 1) { - return true; - } - } - if (typeof value === "string") { - const lower = value.toLowerCase(); - if (lower === "false" || lower === "true") { - logger.warn(stackTraceWarning(`Expected boolean, got ${typeof value}: ${value}`)); - } - if (lower === "false") { - return false; - } - if (lower === "true") { - return true; - } - } - if (typeof value === "boolean") { - return value; - } - throw new TypeError(`Expected boolean, got ${typeof value}: ${value}`); -}, "expectBoolean"); -var expectNumber = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "string") { - const parsed = parseFloat(value); - if (!Number.isNaN(parsed)) { - if (String(parsed) !== String(value)) { - logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`)); - } - return parsed; - } - } - if (typeof value === "number") { - return value; - } - throw new TypeError(`Expected number, got ${typeof value}: ${value}`); -}, "expectNumber"); -var MAX_FLOAT = Math.ceil(2 ** 127 * (2 - 2 ** -23)); -var expectFloat32 = /* @__PURE__ */ __name((value) => { - const expected = expectNumber(value); - if (expected !== void 0 && !Number.isNaN(expected) && expected !== Infinity && expected !== -Infinity) { - if (Math.abs(expected) > MAX_FLOAT) { - throw new TypeError(`Expected 32-bit float, got ${value}`); - } - } - return expected; -}, "expectFloat32"); -var expectLong = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return void 0; - } - if (Number.isInteger(value) && !Number.isNaN(value)) { - return value; - } - throw new TypeError(`Expected integer, got ${typeof value}: ${value}`); -}, "expectLong"); -var expectInt = expectLong; -var expectInt32 = /* @__PURE__ */ __name((value) => expectSizedInt(value, 32), "expectInt32"); -var expectShort = /* @__PURE__ */ __name((value) => expectSizedInt(value, 16), "expectShort"); -var expectByte = /* @__PURE__ */ __name((value) => expectSizedInt(value, 8), "expectByte"); -var expectSizedInt = /* @__PURE__ */ __name((value, size) => { - const expected = expectLong(value); - if (expected !== void 0 && castInt(expected, size) !== expected) { - throw new TypeError(`Expected ${size}-bit integer, got ${value}`); - } - return expected; -}, "expectSizedInt"); -var castInt = /* @__PURE__ */ __name((value, size) => { - switch (size) { - case 32: - return Int32Array.of(value)[0]; - case 16: - return Int16Array.of(value)[0]; - case 8: - return Int8Array.of(value)[0]; - } -}, "castInt"); -var expectNonNull = /* @__PURE__ */ __name((value, location) => { - if (value === null || value === void 0) { - if (location) { - throw new TypeError(`Expected a non-null value for ${location}`); - } - throw new TypeError("Expected a non-null value"); - } - return value; -}, "expectNonNull"); -var expectObject = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "object" && !Array.isArray(value)) { - return value; - } - const receivedType = Array.isArray(value) ? "array" : typeof value; - throw new TypeError(`Expected object, got ${receivedType}: ${value}`); -}, "expectObject"); -var expectString = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value === "string") { - return value; - } - if (["boolean", "number", "bigint"].includes(typeof value)) { - logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`)); - return String(value); - } - throw new TypeError(`Expected string, got ${typeof value}: ${value}`); -}, "expectString"); -var expectUnion = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return void 0; - } - const asObject = expectObject(value); - const setKeys = Object.entries(asObject).filter(([, v]) => v != null).map(([k]) => k); - if (setKeys.length === 0) { - throw new TypeError(`Unions must have exactly one non-null member. None were found.`); - } - if (setKeys.length > 1) { - throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`); - } - return asObject; -}, "expectUnion"); -var strictParseDouble = /* @__PURE__ */ __name((value) => { - if (typeof value == "string") { - return expectNumber(parseNumber(value)); - } - return expectNumber(value); -}, "strictParseDouble"); -var strictParseFloat = strictParseDouble; -var strictParseFloat32 = /* @__PURE__ */ __name((value) => { - if (typeof value == "string") { - return expectFloat32(parseNumber(value)); - } - return expectFloat32(value); -}, "strictParseFloat32"); -var NUMBER_REGEX = /(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g; -var parseNumber = /* @__PURE__ */ __name((value) => { - const matches = value.match(NUMBER_REGEX); - if (matches === null || matches[0].length !== value.length) { - throw new TypeError(`Expected real number, got implicit NaN`); - } - return parseFloat(value); -}, "parseNumber"); -var limitedParseDouble = /* @__PURE__ */ __name((value) => { - if (typeof value == "string") { - return parseFloatString(value); - } - return expectNumber(value); -}, "limitedParseDouble"); -var handleFloat = limitedParseDouble; -var limitedParseFloat = limitedParseDouble; -var limitedParseFloat32 = /* @__PURE__ */ __name((value) => { - if (typeof value == "string") { - return parseFloatString(value); - } - return expectFloat32(value); -}, "limitedParseFloat32"); -var parseFloatString = /* @__PURE__ */ __name((value) => { - switch (value) { - case "NaN": - return NaN; - case "Infinity": - return Infinity; - case "-Infinity": - return -Infinity; - default: - throw new Error(`Unable to parse float value: ${value}`); - } -}, "parseFloatString"); -var strictParseLong = /* @__PURE__ */ __name((value) => { - if (typeof value === "string") { - return expectLong(parseNumber(value)); - } - return expectLong(value); -}, "strictParseLong"); -var strictParseInt = strictParseLong; -var strictParseInt32 = /* @__PURE__ */ __name((value) => { - if (typeof value === "string") { - return expectInt32(parseNumber(value)); - } - return expectInt32(value); -}, "strictParseInt32"); -var strictParseShort = /* @__PURE__ */ __name((value) => { - if (typeof value === "string") { - return expectShort(parseNumber(value)); - } - return expectShort(value); -}, "strictParseShort"); -var strictParseByte = /* @__PURE__ */ __name((value) => { - if (typeof value === "string") { - return expectByte(parseNumber(value)); - } - return expectByte(value); -}, "strictParseByte"); -var stackTraceWarning = /* @__PURE__ */ __name((message) => { - return String(new TypeError(message).stack || message).split("\n").slice(0, 5).filter((s) => !s.includes("stackTraceWarning")).join("\n"); -}, "stackTraceWarning"); -var logger = { - warn: console.warn -}; - -// src/date-utils.ts -var DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; -var MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; -function dateToUtcString(date) { - const year = date.getUTCFullYear(); - const month = date.getUTCMonth(); - const dayOfWeek = date.getUTCDay(); - const dayOfMonthInt = date.getUTCDate(); - const hoursInt = date.getUTCHours(); - const minutesInt = date.getUTCMinutes(); - const secondsInt = date.getUTCSeconds(); - const dayOfMonthString = dayOfMonthInt < 10 ? `0${dayOfMonthInt}` : `${dayOfMonthInt}`; - const hoursString = hoursInt < 10 ? `0${hoursInt}` : `${hoursInt}`; - const minutesString = minutesInt < 10 ? `0${minutesInt}` : `${minutesInt}`; - const secondsString = secondsInt < 10 ? `0${secondsInt}` : `${secondsInt}`; - return `${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`; -} -__name(dateToUtcString, "dateToUtcString"); -var RFC3339 = new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/); -var parseRfc3339DateTime = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-3339 date-times must be expressed as strings"); - } - const match = RFC3339.exec(value); - if (!match) { - throw new TypeError("Invalid RFC-3339 date-time value"); - } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds] = match; - const year = strictParseShort(stripLeadingZeroes(yearStr)); - const month = parseDateValue(monthStr, "month", 1, 12); - const day = parseDateValue(dayStr, "day", 1, 31); - return buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); -}, "parseRfc3339DateTime"); -var RFC3339_WITH_OFFSET = new RegExp( - /^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/ -); -var parseRfc3339DateTimeWithOffset = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-3339 date-times must be expressed as strings"); - } - const match = RFC3339_WITH_OFFSET.exec(value); - if (!match) { - throw new TypeError("Invalid RFC-3339 date-time value"); - } - const [_, yearStr, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, offsetStr] = match; - const year = strictParseShort(stripLeadingZeroes(yearStr)); - const month = parseDateValue(monthStr, "month", 1, 12); - const day = parseDateValue(dayStr, "day", 1, 31); - const date = buildDate(year, month, day, { hours, minutes, seconds, fractionalMilliseconds }); - if (offsetStr.toUpperCase() != "Z") { - date.setTime(date.getTime() - parseOffsetToMilliseconds(offsetStr)); - } - return date; -}, "parseRfc3339DateTimeWithOffset"); -var IMF_FIXDATE = new RegExp( - /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ -); -var RFC_850_DATE = new RegExp( - /^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/ -); -var ASC_TIME = new RegExp( - /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/ -); -var parseRfc7231DateTime = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return void 0; - } - if (typeof value !== "string") { - throw new TypeError("RFC-7231 date-times must be expressed as strings"); - } - let match = IMF_FIXDATE.exec(value); - if (match) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; - return buildDate( - strictParseShort(stripLeadingZeroes(yearStr)), - parseMonthByShortName(monthStr), - parseDateValue(dayStr, "day", 1, 31), - { hours, minutes, seconds, fractionalMilliseconds } - ); - } - match = RFC_850_DATE.exec(value); - if (match) { - const [_, dayStr, monthStr, yearStr, hours, minutes, seconds, fractionalMilliseconds] = match; - return adjustRfc850Year( - buildDate(parseTwoDigitYear(yearStr), parseMonthByShortName(monthStr), parseDateValue(dayStr, "day", 1, 31), { - hours, - minutes, - seconds, - fractionalMilliseconds - }) - ); - } - match = ASC_TIME.exec(value); - if (match) { - const [_, monthStr, dayStr, hours, minutes, seconds, fractionalMilliseconds, yearStr] = match; - return buildDate( - strictParseShort(stripLeadingZeroes(yearStr)), - parseMonthByShortName(monthStr), - parseDateValue(dayStr.trimLeft(), "day", 1, 31), - { hours, minutes, seconds, fractionalMilliseconds } - ); - } - throw new TypeError("Invalid RFC-7231 date-time value"); -}, "parseRfc7231DateTime"); -var parseEpochTimestamp = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return void 0; - } - let valueAsDouble; - if (typeof value === "number") { - valueAsDouble = value; - } else if (typeof value === "string") { - valueAsDouble = strictParseDouble(value); - } else { - throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation"); - } - if (Number.isNaN(valueAsDouble) || valueAsDouble === Infinity || valueAsDouble === -Infinity) { - throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics"); - } - return new Date(Math.round(valueAsDouble * 1e3)); -}, "parseEpochTimestamp"); -var buildDate = /* @__PURE__ */ __name((year, month, day, time) => { - const adjustedMonth = month - 1; - validateDayOfMonth(year, adjustedMonth, day); - return new Date( - Date.UTC( - year, - adjustedMonth, - day, - parseDateValue(time.hours, "hour", 0, 23), - parseDateValue(time.minutes, "minute", 0, 59), - // seconds can go up to 60 for leap seconds - parseDateValue(time.seconds, "seconds", 0, 60), - parseMilliseconds(time.fractionalMilliseconds) - ) - ); -}, "buildDate"); -var parseTwoDigitYear = /* @__PURE__ */ __name((value) => { - const thisYear = (/* @__PURE__ */ new Date()).getUTCFullYear(); - const valueInThisCentury = Math.floor(thisYear / 100) * 100 + strictParseShort(stripLeadingZeroes(value)); - if (valueInThisCentury < thisYear) { - return valueInThisCentury + 100; - } - return valueInThisCentury; -}, "parseTwoDigitYear"); -var FIFTY_YEARS_IN_MILLIS = 50 * 365 * 24 * 60 * 60 * 1e3; -var adjustRfc850Year = /* @__PURE__ */ __name((input) => { - if (input.getTime() - (/* @__PURE__ */ new Date()).getTime() > FIFTY_YEARS_IN_MILLIS) { - return new Date( - Date.UTC( - input.getUTCFullYear() - 100, - input.getUTCMonth(), - input.getUTCDate(), - input.getUTCHours(), - input.getUTCMinutes(), - input.getUTCSeconds(), - input.getUTCMilliseconds() - ) - ); - } - return input; -}, "adjustRfc850Year"); -var parseMonthByShortName = /* @__PURE__ */ __name((value) => { - const monthIdx = MONTHS.indexOf(value); - if (monthIdx < 0) { - throw new TypeError(`Invalid month: ${value}`); - } - return monthIdx + 1; -}, "parseMonthByShortName"); -var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; -var validateDayOfMonth = /* @__PURE__ */ __name((year, month, day) => { - let maxDays = DAYS_IN_MONTH[month]; - if (month === 1 && isLeapYear(year)) { - maxDays = 29; - } - if (day > maxDays) { - throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`); - } -}, "validateDayOfMonth"); -var isLeapYear = /* @__PURE__ */ __name((year) => { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); -}, "isLeapYear"); -var parseDateValue = /* @__PURE__ */ __name((value, type, lower, upper) => { - const dateVal = strictParseByte(stripLeadingZeroes(value)); - if (dateVal < lower || dateVal > upper) { - throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`); - } - return dateVal; -}, "parseDateValue"); -var parseMilliseconds = /* @__PURE__ */ __name((value) => { - if (value === null || value === void 0) { - return 0; - } - return strictParseFloat32("0." + value) * 1e3; -}, "parseMilliseconds"); -var parseOffsetToMilliseconds = /* @__PURE__ */ __name((value) => { - const directionStr = value[0]; - let direction = 1; - if (directionStr == "+") { - direction = 1; - } else if (directionStr == "-") { - direction = -1; - } else { - throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`); - } - const hour = Number(value.substring(1, 3)); - const minute = Number(value.substring(4, 6)); - return direction * (hour * 60 + minute) * 60 * 1e3; -}, "parseOffsetToMilliseconds"); -var stripLeadingZeroes = /* @__PURE__ */ __name((value) => { - let idx = 0; - while (idx < value.length - 1 && value.charAt(idx) === "0") { - idx++; - } - if (idx === 0) { - return value; - } - return value.slice(idx); -}, "stripLeadingZeroes"); - -// src/exceptions.ts -var _ServiceException = class _ServiceException extends Error { - constructor(options) { - super(options.message); - Object.setPrototypeOf(this, _ServiceException.prototype); - this.name = options.name; - this.$fault = options.$fault; - this.$metadata = options.$metadata; - } -}; -__name(_ServiceException, "ServiceException"); -var ServiceException = _ServiceException; -var decorateServiceException = /* @__PURE__ */ __name((exception, additions = {}) => { - Object.entries(additions).filter(([, v]) => v !== void 0).forEach(([k, v]) => { - if (exception[k] == void 0 || exception[k] === "") { - exception[k] = v; - } - }); - const message = exception.message || exception.Message || "UnknownError"; - exception.message = message; - delete exception.Message; - return exception; -}, "decorateServiceException"); - -// src/default-error-handler.ts -var throwDefaultError = /* @__PURE__ */ __name(({ output, parsedBody, exceptionCtor, errorCode }) => { - const $metadata = deserializeMetadata(output); - const statusCode = $metadata.httpStatusCode ? $metadata.httpStatusCode + "" : void 0; - const response = new exceptionCtor({ - name: (parsedBody == null ? void 0 : parsedBody.code) || (parsedBody == null ? void 0 : parsedBody.Code) || errorCode || statusCode || "UnknownError", - $fault: "client", - $metadata - }); - throw decorateServiceException(response, parsedBody); -}, "throwDefaultError"); -var withBaseException = /* @__PURE__ */ __name((ExceptionCtor) => { - return ({ output, parsedBody, errorCode }) => { - throwDefaultError({ output, parsedBody, exceptionCtor: ExceptionCtor, errorCode }); - }; -}, "withBaseException"); -var deserializeMetadata = /* @__PURE__ */ __name((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"] -}), "deserializeMetadata"); - -// src/defaults-mode.ts -var loadConfigsForDefaultMode = /* @__PURE__ */ __name((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: 3e4 - }; - default: - return {}; - } -}, "loadConfigsForDefaultMode"); - -// src/emitWarningIfUnsupportedVersion.ts -var warningEmitted = false; -var emitWarningIfUnsupportedVersion = /* @__PURE__ */ __name((version) => { - if (version && !warningEmitted && parseInt(version.substring(1, version.indexOf("."))) < 14) { - warningEmitted = true; - } -}, "emitWarningIfUnsupportedVersion"); - -// src/extensions/checksum.ts - -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - for (const id in import_types.AlgorithmId) { - const algorithmId = import_types.AlgorithmId[id]; - if (runtimeConfig[algorithmId] === void 0) { - continue; - } - checksumAlgorithms.push({ - algorithmId: () => algorithmId, - checksumConstructor: () => runtimeConfig[algorithmId] - }); - } - return { - _checksumAlgorithms: checksumAlgorithms, - addChecksumAlgorithm(algo) { - this._checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return this._checksumAlgorithms; - } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); - -// src/extensions/retry.ts -var getRetryConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - let _retryStrategy = runtimeConfig.retryStrategy; - return { - setRetryStrategy(retryStrategy) { - _retryStrategy = retryStrategy; - }, - retryStrategy() { - return _retryStrategy; - } - }; -}, "getRetryConfiguration"); -var resolveRetryRuntimeConfig = /* @__PURE__ */ __name((retryStrategyConfiguration) => { - const runtimeConfig = {}; - runtimeConfig.retryStrategy = retryStrategyConfiguration.retryStrategy(); - return runtimeConfig; -}, "resolveRetryRuntimeConfig"); - -// src/extensions/defaultExtensionConfiguration.ts -var getDefaultExtensionConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - ...getChecksumConfiguration(runtimeConfig), - ...getRetryConfiguration(runtimeConfig) - }; -}, "getDefaultExtensionConfiguration"); -var getDefaultClientConfiguration = getDefaultExtensionConfiguration; -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return { - ...resolveChecksumRuntimeConfig(config), - ...resolveRetryRuntimeConfig(config) - }; -}, "resolveDefaultRuntimeConfig"); - -// src/extended-encode-uri-component.ts -function extendedEncodeURIComponent(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} -__name(extendedEncodeURIComponent, "extendedEncodeURIComponent"); - -// src/get-array-if-single-item.ts -var getArrayIfSingleItem = /* @__PURE__ */ __name((mayBeArray) => Array.isArray(mayBeArray) ? mayBeArray : [mayBeArray], "getArrayIfSingleItem"); - -// src/get-value-from-text-node.ts -var getValueFromTextNode = /* @__PURE__ */ __name((obj) => { - const textNodeName = "#text"; - for (const key in obj) { - if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== void 0) { - obj[key] = obj[key][textNodeName]; - } else if (typeof obj[key] === "object" && obj[key] !== null) { - obj[key] = getValueFromTextNode(obj[key]); - } - } - return obj; -}, "getValueFromTextNode"); - -// src/lazy-json.ts -var StringWrapper = /* @__PURE__ */ __name(function() { - const Class = Object.getPrototypeOf(this).constructor; - const Constructor = Function.bind.apply(String, [null, ...arguments]); - const instance = new Constructor(); - Object.setPrototypeOf(instance, Class.prototype); - return instance; -}, "StringWrapper"); -StringWrapper.prototype = Object.create(String.prototype, { - constructor: { - value: StringWrapper, - enumerable: false, - writable: true, - configurable: true - } -}); -Object.setPrototypeOf(StringWrapper, String); -var _LazyJsonString = class _LazyJsonString extends StringWrapper { - deserializeJSON() { - return JSON.parse(super.toString()); - } - toJSON() { - return super.toString(); - } - static fromObject(object) { - if (object instanceof _LazyJsonString) { - return object; - } else if (object instanceof String || typeof object === "string") { - return new _LazyJsonString(object); - } - return new _LazyJsonString(JSON.stringify(object)); - } -}; -__name(_LazyJsonString, "LazyJsonString"); -var LazyJsonString = _LazyJsonString; - -// src/object-mapping.ts -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; -} -__name(map, "map"); -var convertMap = /* @__PURE__ */ __name((target) => { - const output = {}; - for (const [k, v] of Object.entries(target || {})) { - output[k] = [, v]; - } - return output; -}, "convertMap"); -var take = /* @__PURE__ */ __name((source, instructions) => { - const out = {}; - for (const key in instructions) { - applyInstruction(out, source, instructions, key); - } - return out; -}, "take"); -var mapWithFilter = /* @__PURE__ */ __name((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; - }, - {} - ) - ); -}, "mapWithFilter"); -var applyInstruction = /* @__PURE__ */ __name((target, source, instructions, targetKey) => { - if (source !== null) { - let instruction = instructions[targetKey]; - if (typeof instruction === "function") { - instruction = [, instruction]; - } - const [filter2 = nonNullish, valueFn = pass, sourceKey = targetKey] = instruction; - if (typeof filter2 === "function" && filter2(source[sourceKey]) || typeof filter2 !== "function" && !!filter2) { - target[targetKey] = valueFn(source[sourceKey]); - } - return; - } - let [filter, value] = instructions[targetKey]; - if (typeof value === "function") { - let _value; - const defaultFilterPassed = filter === void 0 && (_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 === void 0 && value != null; - const customFilterPassed = typeof filter === "function" && !!filter(value) || typeof filter !== "function" && !!filter; - if (defaultFilterPassed || customFilterPassed) { - target[targetKey] = value; - } - } -}, "applyInstruction"); -var nonNullish = /* @__PURE__ */ __name((_) => _ != null, "nonNullish"); -var pass = /* @__PURE__ */ __name((_) => _, "pass"); - -// src/resolve-path.ts -var resolvedPath = /* @__PURE__ */ __name((resolvedPath2, input, memberName, labelValueProvider, uriLabel, isGreedyLabel) => { - if (input != null && input[memberName] !== void 0) { - const labelValue = labelValueProvider(); - if (labelValue.length <= 0) { - throw new Error("Empty value provided for input HTTP label: " + memberName + "."); - } - resolvedPath2 = resolvedPath2.replace( - uriLabel, - isGreedyLabel ? labelValue.split("/").map((segment) => extendedEncodeURIComponent(segment)).join("/") : extendedEncodeURIComponent(labelValue) - ); - } else { - throw new Error("No value provided for input HTTP label: " + memberName + "."); - } - return resolvedPath2; -}, "resolvedPath"); - -// src/ser-utils.ts -var serializeFloat = /* @__PURE__ */ __name((value) => { - if (value !== value) { - return "NaN"; - } - switch (value) { - case Infinity: - return "Infinity"; - case -Infinity: - return "-Infinity"; - default: - return value; - } -}, "serializeFloat"); - -// src/serde-json.ts -var _json = /* @__PURE__ */ __name((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; -}, "_json"); - -// src/split-every.ts -function splitEvery(value, delimiter, numDelimiters) { - if (numDelimiters <= 0 || !Number.isInteger(numDelimiters)) { - throw new Error("Invalid number of delimiters (" + numDelimiters + ") for splitEvery."); - } - const segments = value.split(delimiter); - if (numDelimiters === 1) { - return segments; - } - const compoundSegments = []; - let currentSegment = ""; - for (let i = 0; i < segments.length; i++) { - if (currentSegment === "") { - currentSegment = segments[i]; - } else { - currentSegment += delimiter + segments[i]; - } - if ((i + 1) % numDelimiters === 0) { - compoundSegments.push(currentSegment); - currentSegment = ""; - } - } - if (currentSegment !== "") { - compoundSegments.push(currentSegment); - } - return compoundSegments; -} -__name(splitEvery, "splitEvery"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - NoOpLogger, - Client, - collectBody, - Command, - SENSITIVE_STRING, - createAggregatedClient, - dateToUtcString, - parseRfc3339DateTime, - parseRfc3339DateTimeWithOffset, - parseRfc7231DateTime, - parseEpochTimestamp, - throwDefaultError, - withBaseException, - loadConfigsForDefaultMode, - emitWarningIfUnsupportedVersion, - getDefaultExtensionConfiguration, - getDefaultClientConfiguration, - resolveDefaultRuntimeConfig, - ServiceException, - decorateServiceException, - extendedEncodeURIComponent, - getArrayIfSingleItem, - getValueFromTextNode, - StringWrapper, - LazyJsonString, - map, - convertMap, - take, - parseBoolean, - expectBoolean, - expectNumber, - expectFloat32, - expectLong, - expectInt, - expectInt32, - expectShort, - expectByte, - expectNonNull, - expectObject, - expectString, - expectUnion, - strictParseDouble, - strictParseFloat, - strictParseFloat32, - limitedParseDouble, - handleFloat, - limitedParseFloat, - limitedParseFloat32, - strictParseLong, - strictParseInt, - strictParseInt32, - strictParseShort, - strictParseByte, - logger, - resolvedPath, - serializeFloat, - _json, - splitEvery -}); - diff --git a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/middleware-stack/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/middleware-stack/dist-cjs/index.js deleted file mode 100644 index 18329dd6..00000000 --- a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/middleware-stack/dist-cjs/index.js +++ /dev/null @@ -1,318 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - constructStack: () => constructStack -}); -module.exports = __toCommonJS(src_exports); - -// src/MiddlewareStack.ts -var getAllAliases = /* @__PURE__ */ __name((name, aliases) => { - const _aliases = []; - if (name) { - _aliases.push(name); - } - if (aliases) { - for (const alias of aliases) { - _aliases.push(alias); - } - } - return _aliases; -}, "getAllAliases"); -var getMiddlewareNameWithAliases = /* @__PURE__ */ __name((name, aliases) => { - return `${name || "anonymous"}${aliases && aliases.length > 0 ? ` (a.k.a. ${aliases.join(",")})` : ""}`; -}, "getMiddlewareNameWithAliases"); -var constructStack = /* @__PURE__ */ __name(() => { - let absoluteEntries = []; - let relativeEntries = []; - let identifyOnResolve = false; - const entriesNameSet = /* @__PURE__ */ new Set(); - const sort = /* @__PURE__ */ __name((entries) => entries.sort( - (a, b) => stepWeights[b.step] - stepWeights[a.step] || priorityWeights[b.priority || "normal"] - priorityWeights[a.priority || "normal"] - ), "sort"); - const removeByName = /* @__PURE__ */ __name((toRemove) => { - let isRemoved = false; - const filterCb = /* @__PURE__ */ __name((entry) => { - const aliases = getAllAliases(entry.name, entry.aliases); - if (aliases.includes(toRemove)) { - isRemoved = true; - for (const alias of aliases) { - entriesNameSet.delete(alias); - } - return false; - } - return true; - }, "filterCb"); - absoluteEntries = absoluteEntries.filter(filterCb); - relativeEntries = relativeEntries.filter(filterCb); - return isRemoved; - }, "removeByName"); - const removeByReference = /* @__PURE__ */ __name((toRemove) => { - let isRemoved = false; - const filterCb = /* @__PURE__ */ __name((entry) => { - if (entry.middleware === toRemove) { - isRemoved = true; - for (const alias of getAllAliases(entry.name, entry.aliases)) { - entriesNameSet.delete(alias); - } - return false; - } - return true; - }, "filterCb"); - absoluteEntries = absoluteEntries.filter(filterCb); - relativeEntries = relativeEntries.filter(filterCb); - return isRemoved; - }, "removeByReference"); - const cloneTo = /* @__PURE__ */ __name((toStack) => { - var _a; - absoluteEntries.forEach((entry) => { - toStack.add(entry.middleware, { ...entry }); - }); - relativeEntries.forEach((entry) => { - toStack.addRelativeTo(entry.middleware, { ...entry }); - }); - (_a = toStack.identifyOnResolve) == null ? void 0 : _a.call(toStack, stack.identifyOnResolve()); - return toStack; - }, "cloneTo"); - const expandRelativeMiddlewareList = /* @__PURE__ */ __name((from) => { - const expandedMiddlewareList = []; - from.before.forEach((entry) => { - if (entry.before.length === 0 && entry.after.length === 0) { - expandedMiddlewareList.push(entry); - } else { - expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); - } - }); - expandedMiddlewareList.push(from); - from.after.reverse().forEach((entry) => { - if (entry.before.length === 0 && entry.after.length === 0) { - expandedMiddlewareList.push(entry); - } else { - expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry)); - } - }); - return expandedMiddlewareList; - }, "expandRelativeMiddlewareList"); - const getMiddlewareList = /* @__PURE__ */ __name((debug = false) => { - const normalizedAbsoluteEntries = []; - const normalizedRelativeEntries = []; - const normalizedEntriesNameMap = {}; - absoluteEntries.forEach((entry) => { - const normalizedEntry = { - ...entry, - before: [], - after: [] - }; - for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { - normalizedEntriesNameMap[alias] = normalizedEntry; - } - normalizedAbsoluteEntries.push(normalizedEntry); - }); - relativeEntries.forEach((entry) => { - const normalizedEntry = { - ...entry, - before: [], - after: [] - }; - for (const alias of getAllAliases(normalizedEntry.name, normalizedEntry.aliases)) { - normalizedEntriesNameMap[alias] = normalizedEntry; - } - normalizedRelativeEntries.push(normalizedEntry); - }); - normalizedRelativeEntries.forEach((entry) => { - if (entry.toMiddleware) { - const toMiddleware = normalizedEntriesNameMap[entry.toMiddleware]; - if (toMiddleware === void 0) { - if (debug) { - return; - } - throw new Error( - `${entry.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry.name, entry.aliases)} middleware ${entry.relation} ${entry.toMiddleware}` - ); - } - if (entry.relation === "after") { - toMiddleware.after.push(entry); - } - if (entry.relation === "before") { - toMiddleware.before.push(entry); - } - } - }); - const mainChain = sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce((wholeList, expandedMiddlewareList) => { - wholeList.push(...expandedMiddlewareList); - return wholeList; - }, []); - return mainChain; - }, "getMiddlewareList"); - const stack = { - add: (middleware, options = {}) => { - const { name, override, aliases: _aliases } = options; - const entry = { - step: "initialize", - priority: "normal", - middleware, - ...options - }; - const aliases = getAllAliases(name, _aliases); - if (aliases.length > 0) { - if (aliases.some((alias) => entriesNameSet.has(alias))) { - if (!override) - throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); - for (const alias of aliases) { - const toOverrideIndex = absoluteEntries.findIndex( - (entry2) => { - var _a; - return entry2.name === alias || ((_a = entry2.aliases) == null ? void 0 : _a.some((a) => a === alias)); - } - ); - if (toOverrideIndex === -1) { - continue; - } - const toOverride = absoluteEntries[toOverrideIndex]; - if (toOverride.step !== entry.step || entry.priority !== toOverride.priority) { - throw new Error( - `"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware with ${entry.priority} priority in ${entry.step} step.` - ); - } - absoluteEntries.splice(toOverrideIndex, 1); - } - } - for (const alias of aliases) { - entriesNameSet.add(alias); - } - } - absoluteEntries.push(entry); - }, - addRelativeTo: (middleware, options) => { - const { name, override, aliases: _aliases } = options; - const entry = { - middleware, - ...options - }; - const aliases = getAllAliases(name, _aliases); - if (aliases.length > 0) { - if (aliases.some((alias) => entriesNameSet.has(alias))) { - if (!override) - throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name, _aliases)}'`); - for (const alias of aliases) { - const toOverrideIndex = relativeEntries.findIndex( - (entry2) => { - var _a; - return entry2.name === alias || ((_a = entry2.aliases) == null ? void 0 : _a.some((a) => a === alias)); - } - ); - if (toOverrideIndex === -1) { - continue; - } - const toOverride = relativeEntries[toOverrideIndex]; - if (toOverride.toMiddleware !== entry.toMiddleware || toOverride.relation !== entry.relation) { - throw new Error( - `"${getMiddlewareNameWithAliases(toOverride.name, toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name, _aliases)}" middleware ${entry.relation} "${entry.toMiddleware}" middleware.` - ); - } - relativeEntries.splice(toOverrideIndex, 1); - } - } - for (const alias of aliases) { - entriesNameSet.add(alias); - } - } - relativeEntries.push(entry); - }, - clone: () => cloneTo(constructStack()), - use: (plugin) => { - plugin.applyToStack(stack); - }, - remove: (toRemove) => { - if (typeof toRemove === "string") - return removeByName(toRemove); - else - return removeByReference(toRemove); - }, - removeByTag: (toRemove) => { - let isRemoved = false; - const filterCb = /* @__PURE__ */ __name((entry) => { - const { tags, name, aliases: _aliases } = entry; - if (tags && tags.includes(toRemove)) { - const aliases = getAllAliases(name, _aliases); - for (const alias of aliases) { - entriesNameSet.delete(alias); - } - isRemoved = true; - return false; - } - return true; - }, "filterCb"); - absoluteEntries = absoluteEntries.filter(filterCb); - relativeEntries = relativeEntries.filter(filterCb); - return isRemoved; - }, - concat: (from) => { - var _a; - const cloned = cloneTo(constructStack()); - cloned.use(from); - cloned.identifyOnResolve( - identifyOnResolve || cloned.identifyOnResolve() || (((_a = from.identifyOnResolve) == null ? void 0 : _a.call(from)) ?? false) - ); - return cloned; - }, - applyToStack: cloneTo, - identify: () => { - return getMiddlewareList(true).map((mw) => { - const step = mw.step ?? mw.relation + " " + mw.toMiddleware; - return getMiddlewareNameWithAliases(mw.name, mw.aliases) + " - " + step; - }); - }, - identifyOnResolve(toggle) { - if (typeof toggle === "boolean") - identifyOnResolve = toggle; - return identifyOnResolve; - }, - resolve: (handler, context) => { - for (const middleware of getMiddlewareList().map((entry) => entry.middleware).reverse()) { - handler = middleware(handler, context); - } - if (identifyOnResolve) { - console.log(stack.identify()); - } - return handler; - } - }; - return stack; -}, "constructStack"); -var stepWeights = { - initialize: 5, - serialize: 4, - build: 3, - finalizeRequest: 2, - deserialize: 1 -}; -var priorityWeights = { - high: 3, - normal: 2, - low: 1 -}; -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - constructStack -}); - diff --git a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js deleted file mode 100644 index 4f3f9e73..00000000 --- a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js +++ /dev/null @@ -1,30 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getAwsChunkedEncodingStream = void 0; -const stream_1 = require("stream"); -const getAwsChunkedEncodingStream = (readableStream, options) => { - const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; - const checksumRequired = base64Encoder !== undefined && - checksumAlgorithmFn !== undefined && - checksumLocationName !== undefined && - streamHasher !== undefined; - const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; - const awsChunkedEncodingStream = new stream_1.Readable({ read: () => { } }); - readableStream.on("data", (data) => { - const length = bodyLengthChecker(data) || 0; - awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); - awsChunkedEncodingStream.push(data); - awsChunkedEncodingStream.push("\r\n"); - }); - readableStream.on("end", async () => { - awsChunkedEncodingStream.push(`0\r\n`); - if (checksumRequired) { - const checksum = base64Encoder(await digest); - awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); - awsChunkedEncodingStream.push(`\r\n`); - } - awsChunkedEncodingStream.push(null); - }); - return awsChunkedEncodingStream; -}; -exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; diff --git a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/index.js deleted file mode 100644 index 4031941e..00000000 --- a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/index.js +++ /dev/null @@ -1,89 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - Uint8ArrayBlobAdapter: () => Uint8ArrayBlobAdapter -}); -module.exports = __toCommonJS(src_exports); - -// src/blob/transforms.ts -var import_util_base64 = require("@smithy/util-base64"); -var import_util_utf8 = require("@smithy/util-utf8"); -function transformToString(payload, encoding = "utf-8") { - if (encoding === "base64") { - return (0, import_util_base64.toBase64)(payload); - } - return (0, import_util_utf8.toUtf8)(payload); -} -__name(transformToString, "transformToString"); -function transformFromString(str, encoding) { - if (encoding === "base64") { - return Uint8ArrayBlobAdapter.mutate((0, import_util_base64.fromBase64)(str)); - } - return Uint8ArrayBlobAdapter.mutate((0, import_util_utf8.fromUtf8)(str)); -} -__name(transformFromString, "transformFromString"); - -// src/blob/Uint8ArrayBlobAdapter.ts -var _Uint8ArrayBlobAdapter = class _Uint8ArrayBlobAdapter extends Uint8Array { - /** - * @param source - such as a string or Stream. - * @returns a new Uint8ArrayBlobAdapter extending Uint8Array. - */ - static fromString(source, encoding = "utf-8") { - switch (typeof source) { - case "string": - return transformFromString(source, encoding); - default: - throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); - } - } - /** - * @param source - Uint8Array to be mutated. - * @returns the same Uint8Array but with prototype switched to Uint8ArrayBlobAdapter. - */ - static mutate(source) { - Object.setPrototypeOf(source, _Uint8ArrayBlobAdapter.prototype); - return source; - } - /** - * @param encoding - default 'utf-8'. - * @returns the blob as string. - */ - transformToString(encoding = "utf-8") { - return transformToString(this, encoding); - } -}; -__name(_Uint8ArrayBlobAdapter, "Uint8ArrayBlobAdapter"); -var Uint8ArrayBlobAdapter = _Uint8ArrayBlobAdapter; - -// src/index.ts -__reExport(src_exports, require("././getAwsChunkedEncodingStream"), module.exports); -__reExport(src_exports, require("././sdk-stream-mixin"), module.exports); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - Uint8ArrayBlobAdapter, - getAwsChunkedEncodingStream, - sdkStreamMixin -}); - diff --git a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js deleted file mode 100644 index c2af3441..00000000 --- a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js +++ /dev/null @@ -1,50 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.sdkStreamMixin = void 0; -const node_http_handler_1 = require("@smithy/node-http-handler"); -const util_buffer_from_1 = require("@smithy/util-buffer-from"); -const stream_1 = require("stream"); -const util_1 = require("util"); -const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; -const sdkStreamMixin = (stream) => { - var _a, _b; - if (!(stream instanceof stream_1.Readable)) { - const name = ((_b = (_a = stream === null || stream === void 0 ? void 0 : stream.__proto__) === null || _a === void 0 ? void 0 : _a.constructor) === null || _b === void 0 ? void 0 : _b.name) || stream; - throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); - } - let transformed = false; - const transformToByteArray = async () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - return await (0, node_http_handler_1.streamCollector)(stream); - }; - return Object.assign(stream, { - transformToByteArray, - transformToString: async (encoding) => { - const buf = await transformToByteArray(); - if (encoding === undefined || Buffer.isEncoding(encoding)) { - return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); - } - else { - const decoder = new util_1.TextDecoder(encoding); - return decoder.decode(buf); - } - }, - transformToWebStream: () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - if (stream.readableFlowing !== null) { - throw new Error("The stream has been consumed by other callbacks."); - } - if (typeof stream_1.Readable.toWeb !== "function") { - throw new Error("Readable.toWeb() is not supported. Please make sure you are using Node.js >= 17.0.0, or polyfill is available."); - } - transformed = true; - return stream_1.Readable.toWeb(stream); - }, - }); -}; -exports.sdkStreamMixin = sdkStreamMixin; diff --git a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/dist-cjs/index.js deleted file mode 100644 index 33f84613..00000000 --- a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/dist-cjs/index.js +++ /dev/null @@ -1,687 +0,0 @@ -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - DEFAULT_REQUEST_TIMEOUT: () => DEFAULT_REQUEST_TIMEOUT, - NodeHttp2Handler: () => NodeHttp2Handler, - NodeHttpHandler: () => NodeHttpHandler, - streamCollector: () => streamCollector -}); -module.exports = __toCommonJS(src_exports); - -// src/node-http-handler.ts -var import_protocol_http = require("@smithy/protocol-http"); -var import_querystring_builder = require("@smithy/querystring-builder"); -var import_http = require("http"); -var import_https = require("https"); - -// src/constants.ts -var NODEJS_TIMEOUT_ERROR_CODES = ["ECONNRESET", "EPIPE", "ETIMEDOUT"]; - -// src/get-transformed-headers.ts -var getTransformedHeaders = /* @__PURE__ */ __name((headers) => { - const transformedHeaders = {}; - for (const name of Object.keys(headers)) { - const headerValues = headers[name]; - transformedHeaders[name] = Array.isArray(headerValues) ? headerValues.join(",") : headerValues; - } - return transformedHeaders; -}, "getTransformedHeaders"); - -// src/set-connection-timeout.ts -var setConnectionTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { - if (!timeoutInMs) { - return; - } - const timeoutId = setTimeout(() => { - request.destroy(); - reject( - Object.assign(new Error(`Socket timed out without establishing a connection within ${timeoutInMs} ms`), { - name: "TimeoutError" - }) - ); - }, timeoutInMs); - request.on("socket", (socket) => { - if (socket.connecting) { - socket.on("connect", () => { - clearTimeout(timeoutId); - }); - } else { - clearTimeout(timeoutId); - } - }); -}, "setConnectionTimeout"); - -// src/set-socket-keep-alive.ts -var setSocketKeepAlive = /* @__PURE__ */ __name((request, { keepAlive, keepAliveMsecs }) => { - if (keepAlive !== true) { - return; - } - request.on("socket", (socket) => { - socket.setKeepAlive(keepAlive, keepAliveMsecs || 0); - }); -}, "setSocketKeepAlive"); - -// src/set-socket-timeout.ts -var setSocketTimeout = /* @__PURE__ */ __name((request, reject, timeoutInMs = 0) => { - request.setTimeout(timeoutInMs, () => { - request.destroy(); - reject(Object.assign(new Error(`Connection timed out after ${timeoutInMs} ms`), { name: "TimeoutError" })); - }); -}, "setSocketTimeout"); - -// src/write-request-body.ts -var import_stream = require("stream"); -var MIN_WAIT_TIME = 1e3; -async function writeRequestBody(httpRequest, request, maxContinueTimeoutMs = MIN_WAIT_TIME) { - const headers = request.headers ?? {}; - const expect = headers["Expect"] || headers["expect"]; - let timeoutId = -1; - let hasError = false; - if (expect === "100-continue") { - await Promise.race([ - new Promise((resolve) => { - timeoutId = Number(setTimeout(resolve, Math.max(MIN_WAIT_TIME, maxContinueTimeoutMs))); - }), - new Promise((resolve) => { - httpRequest.on("continue", () => { - clearTimeout(timeoutId); - resolve(); - }); - httpRequest.on("error", () => { - hasError = true; - clearTimeout(timeoutId); - resolve(); - }); - }) - ]); - } - if (!hasError) { - writeBody(httpRequest, request.body); - } -} -__name(writeRequestBody, "writeRequestBody"); -function writeBody(httpRequest, body) { - if (body instanceof import_stream.Readable) { - body.pipe(httpRequest); - return; - } - if (body) { - if (Buffer.isBuffer(body) || typeof body === "string") { - httpRequest.end(body); - return; - } - const uint8 = body; - if (typeof uint8 === "object" && uint8.buffer && typeof uint8.byteOffset === "number" && typeof uint8.byteLength === "number") { - httpRequest.end(Buffer.from(uint8.buffer, uint8.byteOffset, uint8.byteLength)); - return; - } - httpRequest.end(Buffer.from(body)); - return; - } - httpRequest.end(); -} -__name(writeBody, "writeBody"); - -// src/node-http-handler.ts -var DEFAULT_REQUEST_TIMEOUT = 0; -var _NodeHttpHandler = class _NodeHttpHandler { - constructor(options) { - this.socketWarningTimestamp = 0; - // Node http handler is hard-coded to http/1.1: https://github.com/nodejs/node/blob/ff5664b83b89c55e4ab5d5f60068fb457f1f5872/lib/_http_server.js#L286 - this.metadata = { handlerProtocol: "http/1.1" }; - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options().then((_options) => { - resolve(this.resolveDefaultConfig(_options)); - }).catch(reject); - } else { - resolve(this.resolveDefaultConfig(options)); - } - }); - } - /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. - */ - static create(instanceOrOptions) { - if (typeof (instanceOrOptions == null ? void 0 : instanceOrOptions.handle) === "function") { - return instanceOrOptions; - } - return new _NodeHttpHandler(instanceOrOptions); - } - /** - * @internal - * - * @param agent - http(s) agent in use by the NodeHttpHandler instance. - * @returns timestamp of last emitted warning. - */ - static checkSocketUsage(agent, socketWarningTimestamp) { - var _a, _b; - const { sockets, requests, maxSockets } = agent; - if (typeof maxSockets !== "number" || maxSockets === Infinity) { - return socketWarningTimestamp; - } - const interval = 15e3; - if (Date.now() - interval < socketWarningTimestamp) { - return socketWarningTimestamp; - } - if (sockets && requests) { - for (const origin in sockets) { - const socketsInUse = ((_a = sockets[origin]) == null ? void 0 : _a.length) ?? 0; - const requestsEnqueued = ((_b = requests[origin]) == null ? void 0 : _b.length) ?? 0; - if (socketsInUse >= maxSockets && requestsEnqueued >= 2 * maxSockets) { - console.warn( - "@smithy/node-http-handler:WARN", - `socket usage at capacity=${socketsInUse} and ${requestsEnqueued} additional requests are enqueued.`, - "See https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html", - "or increase socketAcquisitionWarningTimeout=(millis) in the NodeHttpHandler config." - ); - return Date.now(); - } - } - } - return socketWarningTimestamp; - } - resolveDefaultConfig(options) { - const { requestTimeout, connectionTimeout, socketTimeout, httpAgent, httpsAgent } = options || {}; - const keepAlive = true; - const maxSockets = 50; - return { - connectionTimeout, - requestTimeout: requestTimeout ?? socketTimeout, - httpAgent: (() => { - if (httpAgent instanceof import_http.Agent || typeof (httpAgent == null ? void 0 : httpAgent.destroy) === "function") { - return httpAgent; - } - return new import_http.Agent({ keepAlive, maxSockets, ...httpAgent }); - })(), - httpsAgent: (() => { - if (httpsAgent instanceof import_https.Agent || typeof (httpsAgent == null ? void 0 : httpsAgent.destroy) === "function") { - return httpsAgent; - } - return new import_https.Agent({ keepAlive, maxSockets, ...httpsAgent }); - })() - }; - } - destroy() { - var _a, _b, _c, _d; - (_b = (_a = this.config) == null ? void 0 : _a.httpAgent) == null ? void 0 : _b.destroy(); - (_d = (_c = this.config) == null ? void 0 : _c.httpsAgent) == null ? void 0 : _d.destroy(); - } - async handle(request, { abortSignal } = {}) { - if (!this.config) { - this.config = await this.configProvider; - } - let socketCheckTimeoutId; - return new Promise((_resolve, _reject) => { - let writeRequestBodyPromise = void 0; - const resolve = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - clearTimeout(socketCheckTimeoutId); - _resolve(arg); - }, "resolve"); - const reject = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _reject(arg); - }, "reject"); - if (!this.config) { - throw new Error("Node HTTP request handler config is not resolved"); - } - if (abortSignal == null ? void 0 : abortSignal.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - return; - } - const isSSL = request.protocol === "https:"; - const agent = isSSL ? this.config.httpsAgent : this.config.httpAgent; - socketCheckTimeoutId = setTimeout(() => { - this.socketWarningTimestamp = _NodeHttpHandler.checkSocketUsage(agent, this.socketWarningTimestamp); - }, this.config.socketAcquisitionWarningTimeout ?? (this.config.requestTimeout ?? 2e3) + (this.config.connectionTimeout ?? 1e3)); - const queryString = (0, import_querystring_builder.buildQueryString)(request.query || {}); - let auth = void 0; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}`; - } - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - const nodeHttpsOptions = { - headers: request.headers, - host: request.hostname, - method: request.method, - path, - port: request.port, - agent, - auth - }; - const requestFunc = isSSL ? import_https.request : import_http.request; - const req = requestFunc(nodeHttpsOptions, (res) => { - const httpResponse = new import_protocol_http.HttpResponse({ - statusCode: res.statusCode || -1, - reason: res.statusMessage, - headers: getTransformedHeaders(res.headers), - body: res - }); - resolve({ response: httpResponse }); - }); - req.on("error", (err) => { - if (NODEJS_TIMEOUT_ERROR_CODES.includes(err.code)) { - reject(Object.assign(err, { name: "TimeoutError" })); - } else { - reject(err); - } - }); - setConnectionTimeout(req, reject, this.config.connectionTimeout); - setSocketTimeout(req, reject, this.config.requestTimeout); - if (abortSignal) { - abortSignal.onabort = () => { - req.abort(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }; - } - const httpAgent = nodeHttpsOptions.agent; - if (typeof httpAgent === "object" && "keepAlive" in httpAgent) { - setSocketKeepAlive(req, { - // @ts-expect-error keepAlive is not public on httpAgent. - keepAlive: httpAgent.keepAlive, - // @ts-expect-error keepAliveMsecs is not public on httpAgent. - keepAliveMsecs: httpAgent.keepAliveMsecs - }); - } - writeRequestBodyPromise = writeRequestBody(req, request, this.config.requestTimeout).catch(_reject); - }); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value - }; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } -}; -__name(_NodeHttpHandler, "NodeHttpHandler"); -var NodeHttpHandler = _NodeHttpHandler; - -// src/node-http2-handler.ts - - -var import_http22 = require("http2"); - -// src/node-http2-connection-manager.ts -var import_http2 = __toESM(require("http2")); - -// src/node-http2-connection-pool.ts -var _NodeHttp2ConnectionPool = class _NodeHttp2ConnectionPool { - constructor(sessions) { - this.sessions = []; - this.sessions = sessions ?? []; - } - poll() { - if (this.sessions.length > 0) { - return this.sessions.shift(); - } - } - offerLast(session) { - this.sessions.push(session); - } - contains(session) { - return this.sessions.includes(session); - } - remove(session) { - this.sessions = this.sessions.filter((s) => s !== session); - } - [Symbol.iterator]() { - return this.sessions[Symbol.iterator](); - } - destroy(connection) { - for (const session of this.sessions) { - if (session === connection) { - if (!session.destroyed) { - session.destroy(); - } - } - } - } -}; -__name(_NodeHttp2ConnectionPool, "NodeHttp2ConnectionPool"); -var NodeHttp2ConnectionPool = _NodeHttp2ConnectionPool; - -// src/node-http2-connection-manager.ts -var _NodeHttp2ConnectionManager = class _NodeHttp2ConnectionManager { - constructor(config) { - this.sessionCache = /* @__PURE__ */ new Map(); - this.config = config; - if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { - throw new RangeError("maxConcurrency must be greater than zero."); - } - } - lease(requestContext, connectionConfiguration) { - const url = this.getUrlString(requestContext); - const existingPool = this.sessionCache.get(url); - if (existingPool) { - const existingSession = existingPool.poll(); - if (existingSession && !this.config.disableConcurrency) { - return existingSession; - } - } - const session = import_http2.default.connect(url); - if (this.config.maxConcurrency) { - session.settings({ maxConcurrentStreams: this.config.maxConcurrency }, (err) => { - if (err) { - throw new Error( - "Fail to set maxConcurrentStreams to " + this.config.maxConcurrency + "when creating new session for " + requestContext.destination.toString() - ); - } - }); - } - session.unref(); - const destroySessionCb = /* @__PURE__ */ __name(() => { - session.destroy(); - this.deleteSession(url, session); - }, "destroySessionCb"); - session.on("goaway", destroySessionCb); - session.on("error", destroySessionCb); - session.on("frameError", destroySessionCb); - session.on("close", () => this.deleteSession(url, session)); - if (connectionConfiguration.requestTimeout) { - session.setTimeout(connectionConfiguration.requestTimeout, destroySessionCb); - } - const connectionPool = this.sessionCache.get(url) || new NodeHttp2ConnectionPool(); - connectionPool.offerLast(session); - this.sessionCache.set(url, connectionPool); - return session; - } - /** - * Delete a session from the connection pool. - * @param authority The authority of the session to delete. - * @param session The session to delete. - */ - deleteSession(authority, session) { - const existingConnectionPool = this.sessionCache.get(authority); - if (!existingConnectionPool) { - return; - } - if (!existingConnectionPool.contains(session)) { - return; - } - existingConnectionPool.remove(session); - this.sessionCache.set(authority, existingConnectionPool); - } - release(requestContext, session) { - var _a; - const cacheKey = this.getUrlString(requestContext); - (_a = this.sessionCache.get(cacheKey)) == null ? void 0 : _a.offerLast(session); - } - destroy() { - for (const [key, connectionPool] of this.sessionCache) { - for (const session of connectionPool) { - if (!session.destroyed) { - session.destroy(); - } - connectionPool.remove(session); - } - this.sessionCache.delete(key); - } - } - setMaxConcurrentStreams(maxConcurrentStreams) { - if (this.config.maxConcurrency && this.config.maxConcurrency <= 0) { - throw new RangeError("maxConcurrentStreams must be greater than zero."); - } - this.config.maxConcurrency = maxConcurrentStreams; - } - setDisableConcurrentStreams(disableConcurrentStreams) { - this.config.disableConcurrency = disableConcurrentStreams; - } - getUrlString(request) { - return request.destination.toString(); - } -}; -__name(_NodeHttp2ConnectionManager, "NodeHttp2ConnectionManager"); -var NodeHttp2ConnectionManager = _NodeHttp2ConnectionManager; - -// src/node-http2-handler.ts -var _NodeHttp2Handler = class _NodeHttp2Handler { - constructor(options) { - this.metadata = { handlerProtocol: "h2" }; - this.connectionManager = new NodeHttp2ConnectionManager({}); - this.configProvider = new Promise((resolve, reject) => { - if (typeof options === "function") { - options().then((opts) => { - resolve(opts || {}); - }).catch(reject); - } else { - resolve(options || {}); - } - }); - } - /** - * @returns the input if it is an HttpHandler of any class, - * or instantiates a new instance of this handler. - */ - static create(instanceOrOptions) { - if (typeof (instanceOrOptions == null ? void 0 : instanceOrOptions.handle) === "function") { - return instanceOrOptions; - } - return new _NodeHttp2Handler(instanceOrOptions); - } - destroy() { - this.connectionManager.destroy(); - } - async handle(request, { abortSignal } = {}) { - if (!this.config) { - this.config = await this.configProvider; - this.connectionManager.setDisableConcurrentStreams(this.config.disableConcurrentStreams || false); - if (this.config.maxConcurrentStreams) { - this.connectionManager.setMaxConcurrentStreams(this.config.maxConcurrentStreams); - } - } - const { requestTimeout, disableConcurrentStreams } = this.config; - return new Promise((_resolve, _reject) => { - var _a; - let fulfilled = false; - let writeRequestBodyPromise = void 0; - const resolve = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _resolve(arg); - }, "resolve"); - const reject = /* @__PURE__ */ __name(async (arg) => { - await writeRequestBodyPromise; - _reject(arg); - }, "reject"); - if (abortSignal == null ? void 0 : abortSignal.aborted) { - fulfilled = true; - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - return; - } - const { hostname, method, port, protocol, query } = request; - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const authority = `${protocol}//${auth}${hostname}${port ? `:${port}` : ""}`; - const requestContext = { destination: new URL(authority) }; - const session = this.connectionManager.lease(requestContext, { - requestTimeout: (_a = this.config) == null ? void 0 : _a.sessionTimeout, - disableConcurrentStreams: disableConcurrentStreams || false - }); - const rejectWithDestroy = /* @__PURE__ */ __name((err) => { - if (disableConcurrentStreams) { - this.destroySession(session); - } - fulfilled = true; - reject(err); - }, "rejectWithDestroy"); - const queryString = (0, import_querystring_builder.buildQueryString)(query || {}); - let path = request.path; - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - const req = session.request({ - ...request.headers, - [import_http22.constants.HTTP2_HEADER_PATH]: path, - [import_http22.constants.HTTP2_HEADER_METHOD]: method - }); - session.ref(); - req.on("response", (headers) => { - const httpResponse = new import_protocol_http.HttpResponse({ - statusCode: headers[":status"] || -1, - headers: getTransformedHeaders(headers), - body: req - }); - fulfilled = true; - resolve({ response: httpResponse }); - if (disableConcurrentStreams) { - session.close(); - this.connectionManager.deleteSession(authority, session); - } - }); - if (requestTimeout) { - req.setTimeout(requestTimeout, () => { - req.close(); - const timeoutError = new Error(`Stream timed out because of no activity for ${requestTimeout} ms`); - timeoutError.name = "TimeoutError"; - rejectWithDestroy(timeoutError); - }); - } - if (abortSignal) { - abortSignal.onabort = () => { - req.close(); - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - rejectWithDestroy(abortError); - }; - } - req.on("frameError", (type, code, id) => { - rejectWithDestroy(new Error(`Frame type id ${type} in stream id ${id} has failed with code ${code}.`)); - }); - req.on("error", rejectWithDestroy); - req.on("aborted", () => { - rejectWithDestroy( - new Error(`HTTP/2 stream is abnormally aborted in mid-communication with result code ${req.rstCode}.`) - ); - }); - req.on("close", () => { - session.unref(); - if (disableConcurrentStreams) { - session.destroy(); - } - if (!fulfilled) { - rejectWithDestroy(new Error("Unexpected error: http2 request did not get a response")); - } - }); - writeRequestBodyPromise = writeRequestBody(req, request, requestTimeout); - }); - } - updateHttpClientConfig(key, value) { - this.config = void 0; - this.configProvider = this.configProvider.then((config) => { - return { - ...config, - [key]: value - }; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } - /** - * Destroys a session. - * @param session The session to destroy. - */ - destroySession(session) { - if (!session.destroyed) { - session.destroy(); - } - } -}; -__name(_NodeHttp2Handler, "NodeHttp2Handler"); -var NodeHttp2Handler = _NodeHttp2Handler; - -// src/stream-collector/collector.ts - -var _Collector = class _Collector extends import_stream.Writable { - constructor() { - super(...arguments); - this.bufferedBytes = []; - } - _write(chunk, encoding, callback) { - this.bufferedBytes.push(chunk); - callback(); - } -}; -__name(_Collector, "Collector"); -var Collector = _Collector; - -// src/stream-collector/index.ts -var streamCollector = /* @__PURE__ */ __name((stream) => new Promise((resolve, reject) => { - const collector = new Collector(); - stream.pipe(collector); - stream.on("error", (err) => { - collector.end(); - reject(err); - }); - collector.on("error", reject); - collector.on("finish", function() { - const bytes = new Uint8Array(Buffer.concat(this.bufferedBytes)); - resolve(bytes); - }); -}), "streamCollector"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - DEFAULT_REQUEST_TIMEOUT, - NodeHttpHandler, - NodeHttp2Handler, - streamCollector -}); - diff --git a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js deleted file mode 100644 index 70302425..00000000 --- a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js +++ /dev/null @@ -1,52 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - buildQueryString: () => buildQueryString -}); -module.exports = __toCommonJS(src_exports); -var import_util_uri_escape = require("@smithy/util-uri-escape"); -function buildQueryString(query) { - const parts = []; - for (let key of Object.keys(query).sort()) { - const value = query[key]; - key = (0, import_util_uri_escape.escapeUri)(key); - if (Array.isArray(value)) { - for (let i = 0, iLen = value.length; i < iLen; i++) { - parts.push(`${key}=${(0, import_util_uri_escape.escapeUri)(value[i])}`); - } - } else { - let qsEntry = key; - if (value || typeof value === "string") { - qsEntry += `=${(0, import_util_uri_escape.escapeUri)(value)}`; - } - parts.push(qsEntry); - } - } - return parts.join("&"); -} -__name(buildQueryString, "buildQueryString"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - buildQueryString -}); - diff --git a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js deleted file mode 100644 index 51001efe..00000000 --- a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/node-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js +++ /dev/null @@ -1,43 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - escapeUri: () => escapeUri, - escapeUriPath: () => escapeUriPath -}); -module.exports = __toCommonJS(src_exports); - -// src/escape-uri.ts -var escapeUri = /* @__PURE__ */ __name((uri) => ( - // AWS percent-encodes some extra non-standard characters in a URI - encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) -), "escapeUri"); -var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); - -// src/escape-uri-path.ts -var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - escapeUri, - escapeUriPath -}); - diff --git a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/util-utf8/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/util-utf8/dist-cjs/index.js deleted file mode 100644 index 0b22680a..00000000 --- a/claude-code-source/node_modules/@smithy/smithy-client/node_modules/@smithy/util-stream/node_modules/@smithy/util-utf8/dist-cjs/index.js +++ /dev/null @@ -1,65 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - fromUtf8: () => fromUtf8, - toUint8Array: () => toUint8Array, - toUtf8: () => toUtf8 -}); -module.exports = __toCommonJS(src_exports); - -// src/fromUtf8.ts -var import_util_buffer_from = require("@smithy/util-buffer-from"); -var fromUtf8 = /* @__PURE__ */ __name((input) => { - const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); -}, "fromUtf8"); - -// src/toUint8Array.ts -var toUint8Array = /* @__PURE__ */ __name((data) => { - if (typeof data === "string") { - return fromUtf8(data); - } - if (ArrayBuffer.isView(data)) { - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); - } - return new Uint8Array(data); -}, "toUint8Array"); - -// src/toUtf8.ts - -var toUtf8 = /* @__PURE__ */ __name((input) => { - if (typeof input === "string") { - return input; - } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); - } - return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); -}, "toUtf8"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - fromUtf8, - toUint8Array, - toUtf8 -}); - diff --git a/claude-code-source/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index b22a90a6..00000000 --- a/claude-code-source/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,149 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - AlgorithmId: () => AlgorithmId, - EndpointURLScheme: () => EndpointURLScheme, - FieldPosition: () => FieldPosition, - HttpApiKeyAuthLocation: () => HttpApiKeyAuthLocation, - HttpAuthLocation: () => HttpAuthLocation, - IniSectionType: () => IniSectionType, - RequestHandlerProtocol: () => RequestHandlerProtocol, - SMITHY_CONTEXT_KEY: () => SMITHY_CONTEXT_KEY, - getDefaultClientConfiguration: () => getDefaultClientConfiguration, - resolveDefaultRuntimeConfig: () => resolveDefaultRuntimeConfig -}); -module.exports = __toCommonJS(src_exports); - -// src/auth/auth.ts -var HttpAuthLocation = /* @__PURE__ */ ((HttpAuthLocation2) => { - HttpAuthLocation2["HEADER"] = "header"; - HttpAuthLocation2["QUERY"] = "query"; - return HttpAuthLocation2; -})(HttpAuthLocation || {}); - -// src/auth/HttpApiKeyAuth.ts -var HttpApiKeyAuthLocation = /* @__PURE__ */ ((HttpApiKeyAuthLocation2) => { - HttpApiKeyAuthLocation2["HEADER"] = "header"; - HttpApiKeyAuthLocation2["QUERY"] = "query"; - return HttpApiKeyAuthLocation2; -})(HttpApiKeyAuthLocation || {}); - -// src/endpoint.ts -var EndpointURLScheme = /* @__PURE__ */ ((EndpointURLScheme2) => { - EndpointURLScheme2["HTTP"] = "http"; - EndpointURLScheme2["HTTPS"] = "https"; - return EndpointURLScheme2; -})(EndpointURLScheme || {}); - -// src/extensions/checksum.ts -var AlgorithmId = /* @__PURE__ */ ((AlgorithmId2) => { - AlgorithmId2["MD5"] = "md5"; - AlgorithmId2["CRC32"] = "crc32"; - AlgorithmId2["CRC32C"] = "crc32c"; - AlgorithmId2["SHA1"] = "sha1"; - AlgorithmId2["SHA256"] = "sha256"; - return AlgorithmId2; -})(AlgorithmId || {}); -var getChecksumConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - const checksumAlgorithms = []; - if (runtimeConfig.sha256 !== void 0) { - checksumAlgorithms.push({ - algorithmId: () => "sha256" /* SHA256 */, - checksumConstructor: () => runtimeConfig.sha256 - }); - } - if (runtimeConfig.md5 != void 0) { - checksumAlgorithms.push({ - algorithmId: () => "md5" /* MD5 */, - checksumConstructor: () => runtimeConfig.md5 - }); - } - return { - _checksumAlgorithms: checksumAlgorithms, - addChecksumAlgorithm(algo) { - this._checksumAlgorithms.push(algo); - }, - checksumAlgorithms() { - return this._checksumAlgorithms; - } - }; -}, "getChecksumConfiguration"); -var resolveChecksumRuntimeConfig = /* @__PURE__ */ __name((clientConfig) => { - const runtimeConfig = {}; - clientConfig.checksumAlgorithms().forEach((checksumAlgorithm) => { - runtimeConfig[checksumAlgorithm.algorithmId()] = checksumAlgorithm.checksumConstructor(); - }); - return runtimeConfig; -}, "resolveChecksumRuntimeConfig"); - -// src/extensions/defaultClientConfiguration.ts -var getDefaultClientConfiguration = /* @__PURE__ */ __name((runtimeConfig) => { - return { - ...getChecksumConfiguration(runtimeConfig) - }; -}, "getDefaultClientConfiguration"); -var resolveDefaultRuntimeConfig = /* @__PURE__ */ __name((config) => { - return { - ...resolveChecksumRuntimeConfig(config) - }; -}, "resolveDefaultRuntimeConfig"); - -// src/http.ts -var FieldPosition = /* @__PURE__ */ ((FieldPosition2) => { - FieldPosition2[FieldPosition2["HEADER"] = 0] = "HEADER"; - FieldPosition2[FieldPosition2["TRAILER"] = 1] = "TRAILER"; - return FieldPosition2; -})(FieldPosition || {}); - -// src/middleware.ts -var SMITHY_CONTEXT_KEY = "__smithy_context"; - -// src/profile.ts -var IniSectionType = /* @__PURE__ */ ((IniSectionType2) => { - IniSectionType2["PROFILE"] = "profile"; - IniSectionType2["SSO_SESSION"] = "sso-session"; - IniSectionType2["SERVICES"] = "services"; - return IniSectionType2; -})(IniSectionType || {}); - -// src/transfer.ts -var RequestHandlerProtocol = /* @__PURE__ */ ((RequestHandlerProtocol2) => { - RequestHandlerProtocol2["HTTP_0_9"] = "http/0.9"; - RequestHandlerProtocol2["HTTP_1_0"] = "http/1.0"; - RequestHandlerProtocol2["TDS_8_0"] = "tds/8.0"; - return RequestHandlerProtocol2; -})(RequestHandlerProtocol || {}); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - HttpAuthLocation, - HttpApiKeyAuthLocation, - EndpointURLScheme, - AlgorithmId, - getDefaultClientConfiguration, - resolveDefaultRuntimeConfig, - FieldPosition, - SMITHY_CONTEXT_KEY, - IniSectionType, - RequestHandlerProtocol -}); - diff --git a/claude-code-source/node_modules/@smithy/url-parser/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/url-parser/dist-cjs/index.js deleted file mode 100644 index ddc21b01..00000000 --- a/claude-code-source/node_modules/@smithy/url-parser/dist-cjs/index.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -var querystringParser = require('@smithy/querystring-parser'); - -const parseUrl = (url) => { - if (typeof url === "string") { - return parseUrl(new URL(url)); - } - const { hostname, pathname, port, protocol, search } = url; - let query; - if (search) { - query = querystringParser.parseQueryString(search); - } - return { - hostname, - port: port ? parseInt(port) : undefined, - protocol, - path: pathname, - query, - }; -}; - -exports.parseUrl = parseUrl; diff --git a/claude-code-source/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js deleted file mode 100644 index b06a7b87..00000000 --- a/claude-code-source/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js +++ /dev/null @@ -1,16 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-base64/dist-cjs/index.js deleted file mode 100644 index 02848d02..00000000 --- a/claude-code-source/node_modules/@smithy/util-base64/dist-cjs/index.js +++ /dev/null @@ -1,27 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -module.exports = __toCommonJS(src_exports); -__reExport(src_exports, require("././fromBase64"), module.exports); -__reExport(src_exports, require("././toBase64"), module.exports); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - fromBase64, - toBase64 -}); - diff --git a/claude-code-source/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@smithy/util-base64/dist-cjs/toBase64.js deleted file mode 100644 index 0590ce3f..00000000 --- a/claude-code-source/node_modules/@smithy/util-base64/dist-cjs/toBase64.js +++ /dev/null @@ -1,19 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@smithy/util-base64/node_modules/@smithy/util-utf8/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-base64/node_modules/@smithy/util-utf8/dist-cjs/index.js deleted file mode 100644 index 0b22680a..00000000 --- a/claude-code-source/node_modules/@smithy/util-base64/node_modules/@smithy/util-utf8/dist-cjs/index.js +++ /dev/null @@ -1,65 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - fromUtf8: () => fromUtf8, - toUint8Array: () => toUint8Array, - toUtf8: () => toUtf8 -}); -module.exports = __toCommonJS(src_exports); - -// src/fromUtf8.ts -var import_util_buffer_from = require("@smithy/util-buffer-from"); -var fromUtf8 = /* @__PURE__ */ __name((input) => { - const buf = (0, import_util_buffer_from.fromString)(input, "utf8"); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); -}, "fromUtf8"); - -// src/toUint8Array.ts -var toUint8Array = /* @__PURE__ */ __name((data) => { - if (typeof data === "string") { - return fromUtf8(data); - } - if (ArrayBuffer.isView(data)) { - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); - } - return new Uint8Array(data); -}, "toUint8Array"); - -// src/toUtf8.ts - -var toUtf8 = /* @__PURE__ */ __name((input) => { - if (typeof input === "string") { - return input; - } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); - } - return (0, import_util_buffer_from.fromArrayBuffer)(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); -}, "toUtf8"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - fromUtf8, - toUint8Array, - toUtf8 -}); - diff --git a/claude-code-source/node_modules/@smithy/util-body-length-browser/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-body-length-browser/dist-cjs/index.js deleted file mode 100644 index 5cf421cb..00000000 --- a/claude-code-source/node_modules/@smithy/util-body-length-browser/dist-cjs/index.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -const TEXT_ENCODER = typeof TextEncoder == "function" ? new TextEncoder() : null; -const calculateBodyLength = (body) => { - if (typeof body === "string") { - if (TEXT_ENCODER) { - return TEXT_ENCODER.encode(body).byteLength; - } - let len = body.length; - for (let i = len - 1; i >= 0; i--) { - const code = body.charCodeAt(i); - if (code > 0x7f && code <= 0x7ff) - len++; - else if (code > 0x7ff && code <= 0xffff) - len += 2; - if (code >= 0xdc00 && code <= 0xdfff) - i--; - } - return len; - } - else if (typeof body.byteLength === "number") { - return body.byteLength; - } - else if (typeof body.size === "number") { - return body.size; - } - throw new Error(`Body Length computation failed for ${body}`); -}; - -exports.calculateBodyLength = calculateBodyLength; diff --git a/claude-code-source/node_modules/@smithy/util-body-length-node/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-body-length-node/dist-cjs/index.js deleted file mode 100644 index a388e288..00000000 --- a/claude-code-source/node_modules/@smithy/util-body-length-node/dist-cjs/index.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -var node_fs = require('node:fs'); - -const calculateBodyLength = (body) => { - if (!body) { - return 0; - } - if (typeof body === "string") { - return Buffer.byteLength(body); - } - else if (typeof body.byteLength === "number") { - return body.byteLength; - } - else if (typeof body.size === "number") { - return body.size; - } - else if (typeof body.start === "number" && typeof body.end === "number") { - return body.end + 1 - body.start; - } - else if (body instanceof node_fs.ReadStream) { - if (body.path != null) { - return node_fs.lstatSync(body.path).size; - } - else if (typeof body.fd === "number") { - return node_fs.fstatSync(body.fd).size; - } - } - throw new Error(`Body Length computation failed for ${body}`); -}; - -exports.calculateBodyLength = calculateBodyLength; diff --git a/claude-code-source/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-buffer-from/dist-cjs/index.js deleted file mode 100644 index c6738d94..00000000 --- a/claude-code-source/node_modules/@smithy/util-buffer-from/dist-cjs/index.js +++ /dev/null @@ -1,47 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - fromArrayBuffer: () => fromArrayBuffer, - fromString: () => fromString -}); -module.exports = __toCommonJS(src_exports); -var import_is_array_buffer = require("@smithy/is-array-buffer"); -var import_buffer = require("buffer"); -var fromArrayBuffer = /* @__PURE__ */ __name((input, offset = 0, length = input.byteLength - offset) => { - if (!(0, import_is_array_buffer.isArrayBuffer)(input)) { - throw new TypeError(`The "input" argument must be ArrayBuffer. Received type ${typeof input} (${input})`); - } - return import_buffer.Buffer.from(input, offset, length); -}, "fromArrayBuffer"); -var fromString = /* @__PURE__ */ __name((input, encoding) => { - if (typeof input !== "string") { - throw new TypeError(`The "input" argument must be of type string. Received type ${typeof input} (${input})`); - } - return encoding ? import_buffer.Buffer.from(input, encoding) : import_buffer.Buffer.from(input); -}, "fromString"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - fromArrayBuffer, - fromString -}); - diff --git a/claude-code-source/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js deleted file mode 100644 index 5d792e71..00000000 --- a/claude-code-source/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js +++ /dev/null @@ -1,32 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - isArrayBuffer: () => isArrayBuffer -}); -module.exports = __toCommonJS(src_exports); -var isArrayBuffer = /* @__PURE__ */ __name((arg) => typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer || Object.prototype.toString.call(arg) === "[object ArrayBuffer]", "isArrayBuffer"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - isArrayBuffer -}); - diff --git a/claude-code-source/node_modules/@smithy/util-config-provider/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-config-provider/dist-cjs/index.js deleted file mode 100644 index 52d176d5..00000000 --- a/claude-code-source/node_modules/@smithy/util-config-provider/dist-cjs/index.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -const booleanSelector = (obj, key, type) => { - if (!(key in obj)) - return undefined; - if (obj[key] === "true") - return true; - if (obj[key] === "false") - return false; - throw new Error(`Cannot load ${type} "${key}". Expected "true" or "false", got ${obj[key]}.`); -}; - -const numberSelector = (obj, key, type) => { - if (!(key in obj)) - return undefined; - const numberValue = parseInt(obj[key], 10); - if (Number.isNaN(numberValue)) { - throw new TypeError(`Cannot load ${type} '${key}'. Expected number, got '${obj[key]}'.`); - } - return numberValue; -}; - -exports.SelectorType = void 0; -(function (SelectorType) { - SelectorType["ENV"] = "env"; - SelectorType["CONFIG"] = "shared config entry"; -})(exports.SelectorType || (exports.SelectorType = {})); - -exports.booleanSelector = booleanSelector; -exports.numberSelector = numberSelector; diff --git a/claude-code-source/node_modules/@smithy/util-defaults-mode-node/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-defaults-mode-node/dist-cjs/index.js deleted file mode 100644 index 9fae1b10..00000000 --- a/claude-code-source/node_modules/@smithy/util-defaults-mode-node/dist-cjs/index.js +++ /dev/null @@ -1,74 +0,0 @@ -'use strict'; - -var configResolver = require('@smithy/config-resolver'); -var nodeConfigProvider = require('@smithy/node-config-provider'); -var propertyProvider = require('@smithy/property-provider'); - -const AWS_EXECUTION_ENV = "AWS_EXECUTION_ENV"; -const AWS_REGION_ENV = "AWS_REGION"; -const AWS_DEFAULT_REGION_ENV = "AWS_DEFAULT_REGION"; -const ENV_IMDS_DISABLED = "AWS_EC2_METADATA_DISABLED"; -const DEFAULTS_MODE_OPTIONS = ["in-region", "cross-region", "mobile", "standard", "legacy"]; -const IMDS_REGION_PATH = "/latest/meta-data/placement/region"; - -const AWS_DEFAULTS_MODE_ENV = "AWS_DEFAULTS_MODE"; -const AWS_DEFAULTS_MODE_CONFIG = "defaults_mode"; -const NODE_DEFAULTS_MODE_CONFIG_OPTIONS = { - environmentVariableSelector: (env) => { - return env[AWS_DEFAULTS_MODE_ENV]; - }, - configFileSelector: (profile) => { - return profile[AWS_DEFAULTS_MODE_CONFIG]; - }, - default: "legacy", -}; - -const resolveDefaultsModeConfig = ({ region = nodeConfigProvider.loadConfig(configResolver.NODE_REGION_CONFIG_OPTIONS), defaultsMode = nodeConfigProvider.loadConfig(NODE_DEFAULTS_MODE_CONFIG_OPTIONS), } = {}) => propertyProvider.memoize(async () => { - const mode = typeof defaultsMode === "function" ? await defaultsMode() : defaultsMode; - switch (mode?.toLowerCase()) { - case "auto": - return resolveNodeDefaultsModeAuto(region); - case "in-region": - case "cross-region": - case "mobile": - case "standard": - case "legacy": - return Promise.resolve(mode?.toLocaleLowerCase()); - case undefined: - return Promise.resolve("legacy"); - default: - throw new Error(`Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`); - } -}); -const resolveNodeDefaultsModeAuto = async (clientRegion) => { - if (clientRegion) { - const resolvedRegion = typeof clientRegion === "function" ? await clientRegion() : clientRegion; - const inferredRegion = await inferPhysicalRegion(); - if (!inferredRegion) { - return "standard"; - } - if (resolvedRegion === inferredRegion) { - return "in-region"; - } - else { - return "cross-region"; - } - } - return "standard"; -}; -const inferPhysicalRegion = async () => { - if (process.env[AWS_EXECUTION_ENV] && (process.env[AWS_REGION_ENV] || process.env[AWS_DEFAULT_REGION_ENV])) { - return process.env[AWS_REGION_ENV] ?? process.env[AWS_DEFAULT_REGION_ENV]; - } - if (!process.env[ENV_IMDS_DISABLED]) { - try { - const { getInstanceMetadataEndpoint, httpRequest } = await import('@smithy/credential-provider-imds'); - const endpoint = await getInstanceMetadataEndpoint(); - return (await httpRequest({ ...endpoint, path: IMDS_REGION_PATH })).toString(); - } - catch (e) { - } - } -}; - -exports.resolveDefaultsModeConfig = resolveDefaultsModeConfig; diff --git a/claude-code-source/node_modules/@smithy/util-endpoints/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-endpoints/dist-cjs/index.js deleted file mode 100644 index e3a02c6f..00000000 --- a/claude-code-source/node_modules/@smithy/util-endpoints/dist-cjs/index.js +++ /dev/null @@ -1,472 +0,0 @@ -'use strict'; - -var types = require('@smithy/types'); - -class EndpointCache { - capacity; - data = new Map(); - parameters = []; - constructor({ size, params }) { - this.capacity = size ?? 50; - if (params) { - this.parameters = params; - } - } - get(endpointParams, resolver) { - const key = this.hash(endpointParams); - if (key === false) { - return resolver(); - } - if (!this.data.has(key)) { - if (this.data.size > this.capacity + 10) { - const keys = this.data.keys(); - let i = 0; - while (true) { - const { value, done } = keys.next(); - this.data.delete(value); - if (done || ++i > 10) { - break; - } - } - } - this.data.set(key, resolver()); - } - return this.data.get(key); - } - size() { - return this.data.size; - } - hash(endpointParams) { - let buffer = ""; - const { parameters } = this; - if (parameters.length === 0) { - return false; - } - for (const param of parameters) { - const val = String(endpointParams[param] ?? ""); - if (val.includes("|;")) { - return false; - } - buffer += val + "|;"; - } - return buffer; - } -} - -const IP_V4_REGEX = new RegExp(`^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$`); -const isIpAddress = (value) => IP_V4_REGEX.test(value) || (value.startsWith("[") && value.endsWith("]")); - -const VALID_HOST_LABEL_REGEX = new RegExp(`^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$`); -const isValidHostLabel = (value, allowSubDomains = false) => { - if (!allowSubDomains) { - return VALID_HOST_LABEL_REGEX.test(value); - } - const labels = value.split("."); - for (const label of labels) { - if (!isValidHostLabel(label)) { - return false; - } - } - return true; -}; - -const customEndpointFunctions = {}; - -const debugId = "endpoints"; - -function toDebugString(input) { - if (typeof input !== "object" || input == null) { - return input; - } - if ("ref" in input) { - return `$${toDebugString(input.ref)}`; - } - if ("fn" in input) { - return `${input.fn}(${(input.argv || []).map(toDebugString).join(", ")})`; - } - return JSON.stringify(input, null, 2); -} - -class EndpointError extends Error { - constructor(message) { - super(message); - this.name = "EndpointError"; - } -} - -const booleanEquals = (value1, value2) => value1 === value2; - -const getAttrPathList = (path) => { - const parts = path.split("."); - const pathList = []; - for (const part of parts) { - const squareBracketIndex = part.indexOf("["); - if (squareBracketIndex !== -1) { - if (part.indexOf("]") !== part.length - 1) { - throw new EndpointError(`Path: '${path}' does not end with ']'`); - } - const arrayIndex = part.slice(squareBracketIndex + 1, -1); - if (Number.isNaN(parseInt(arrayIndex))) { - throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path}'`); - } - if (squareBracketIndex !== 0) { - pathList.push(part.slice(0, squareBracketIndex)); - } - pathList.push(arrayIndex); - } - else { - pathList.push(part); - } - } - return pathList; -}; - -const getAttr = (value, path) => getAttrPathList(path).reduce((acc, index) => { - if (typeof acc !== "object") { - throw new EndpointError(`Index '${index}' in '${path}' not found in '${JSON.stringify(value)}'`); - } - else if (Array.isArray(acc)) { - return acc[parseInt(index)]; - } - return acc[index]; -}, value); - -const isSet = (value) => value != null; - -const not = (value) => !value; - -const DEFAULT_PORTS = { - [types.EndpointURLScheme.HTTP]: 80, - [types.EndpointURLScheme.HTTPS]: 443, -}; -const parseURL = (value) => { - const whatwgURL = (() => { - try { - if (value instanceof URL) { - return value; - } - if (typeof value === "object" && "hostname" in value) { - const { hostname, port, protocol = "", path = "", query = {} } = value; - const url = new URL(`${protocol}//${hostname}${port ? `:${port}` : ""}${path}`); - url.search = Object.entries(query) - .map(([k, v]) => `${k}=${v}`) - .join("&"); - return url; - } - return new URL(value); - } - catch (error) { - return null; - } - })(); - if (!whatwgURL) { - console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`); - return null; - } - const urlString = whatwgURL.href; - const { host, hostname, pathname, protocol, search } = whatwgURL; - if (search) { - return null; - } - const scheme = protocol.slice(0, -1); - if (!Object.values(types.EndpointURLScheme).includes(scheme)) { - return null; - } - const isIp = isIpAddress(hostname); - const inputContainsDefaultPort = urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`) || - (typeof value === "string" && value.includes(`${host}:${DEFAULT_PORTS[scheme]}`)); - const authority = `${host}${inputContainsDefaultPort ? `:${DEFAULT_PORTS[scheme]}` : ``}`; - return { - scheme, - authority, - path: pathname, - normalizedPath: pathname.endsWith("/") ? pathname : `${pathname}/`, - isIp, - }; -}; - -const stringEquals = (value1, value2) => value1 === value2; - -const substring = (input, start, stop, reverse) => { - if (start >= stop || input.length < stop) { - return null; - } - if (!reverse) { - return input.substring(start, stop); - } - return input.substring(input.length - stop, input.length - start); -}; - -const uriEncode = (value) => encodeURIComponent(value).replace(/[!*'()]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); - -const endpointFunctions = { - booleanEquals, - getAttr, - isSet, - isValidHostLabel, - not, - parseURL, - stringEquals, - substring, - uriEncode, -}; - -const evaluateTemplate = (template, options) => { - const evaluatedTemplateArr = []; - const templateContext = { - ...options.endpointParams, - ...options.referenceRecord, - }; - let currentIndex = 0; - while (currentIndex < template.length) { - const openingBraceIndex = template.indexOf("{", currentIndex); - if (openingBraceIndex === -1) { - evaluatedTemplateArr.push(template.slice(currentIndex)); - break; - } - evaluatedTemplateArr.push(template.slice(currentIndex, openingBraceIndex)); - const closingBraceIndex = template.indexOf("}", openingBraceIndex); - if (closingBraceIndex === -1) { - evaluatedTemplateArr.push(template.slice(openingBraceIndex)); - break; - } - if (template[openingBraceIndex + 1] === "{" && template[closingBraceIndex + 1] === "}") { - evaluatedTemplateArr.push(template.slice(openingBraceIndex + 1, closingBraceIndex)); - currentIndex = closingBraceIndex + 2; - } - const parameterName = template.substring(openingBraceIndex + 1, closingBraceIndex); - if (parameterName.includes("#")) { - const [refName, attrName] = parameterName.split("#"); - evaluatedTemplateArr.push(getAttr(templateContext[refName], attrName)); - } - else { - evaluatedTemplateArr.push(templateContext[parameterName]); - } - currentIndex = closingBraceIndex + 1; - } - return evaluatedTemplateArr.join(""); -}; - -const getReferenceValue = ({ ref }, options) => { - const referenceRecord = { - ...options.endpointParams, - ...options.referenceRecord, - }; - return referenceRecord[ref]; -}; - -const evaluateExpression = (obj, keyName, options) => { - if (typeof obj === "string") { - return evaluateTemplate(obj, options); - } - else if (obj["fn"]) { - return group$2.callFunction(obj, options); - } - else if (obj["ref"]) { - return getReferenceValue(obj, options); - } - throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`); -}; -const callFunction = ({ fn, argv }, options) => { - const evaluatedArgs = argv.map((arg) => ["boolean", "number"].includes(typeof arg) ? arg : group$2.evaluateExpression(arg, "arg", options)); - const fnSegments = fn.split("."); - if (fnSegments[0] in customEndpointFunctions && fnSegments[1] != null) { - return customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs); - } - return endpointFunctions[fn](...evaluatedArgs); -}; -const group$2 = { - evaluateExpression, - callFunction, -}; - -const evaluateCondition = ({ assign, ...fnArgs }, options) => { - if (assign && assign in options.referenceRecord) { - throw new EndpointError(`'${assign}' is already defined in Reference Record.`); - } - const value = callFunction(fnArgs, options); - options.logger?.debug?.(`${debugId} evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`); - return { - result: value === "" ? true : !!value, - ...(assign != null && { toAssign: { name: assign, value } }), - }; -}; - -const evaluateConditions = (conditions = [], options) => { - const conditionsReferenceRecord = {}; - for (const condition of conditions) { - const { result, toAssign } = evaluateCondition(condition, { - ...options, - referenceRecord: { - ...options.referenceRecord, - ...conditionsReferenceRecord, - }, - }); - if (!result) { - return { result }; - } - if (toAssign) { - conditionsReferenceRecord[toAssign.name] = toAssign.value; - options.logger?.debug?.(`${debugId} assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`); - } - } - return { result: true, referenceRecord: conditionsReferenceRecord }; -}; - -const getEndpointHeaders = (headers, options) => Object.entries(headers).reduce((acc, [headerKey, headerVal]) => ({ - ...acc, - [headerKey]: headerVal.map((headerValEntry) => { - const processedExpr = evaluateExpression(headerValEntry, "Header value entry", options); - if (typeof processedExpr !== "string") { - throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`); - } - return processedExpr; - }), -}), {}); - -const getEndpointProperties = (properties, options) => Object.entries(properties).reduce((acc, [propertyKey, propertyVal]) => ({ - ...acc, - [propertyKey]: group$1.getEndpointProperty(propertyVal, options), -}), {}); -const getEndpointProperty = (property, options) => { - if (Array.isArray(property)) { - return property.map((propertyEntry) => getEndpointProperty(propertyEntry, options)); - } - switch (typeof property) { - case "string": - return evaluateTemplate(property, options); - case "object": - if (property === null) { - throw new EndpointError(`Unexpected endpoint property: ${property}`); - } - return group$1.getEndpointProperties(property, options); - case "boolean": - return property; - default: - throw new EndpointError(`Unexpected endpoint property type: ${typeof property}`); - } -}; -const group$1 = { - getEndpointProperty, - getEndpointProperties, -}; - -const getEndpointUrl = (endpointUrl, options) => { - const expression = evaluateExpression(endpointUrl, "Endpoint URL", options); - if (typeof expression === "string") { - try { - return new URL(expression); - } - catch (error) { - console.error(`Failed to construct URL with ${expression}`, error); - throw error; - } - } - throw new EndpointError(`Endpoint URL must be a string, got ${typeof expression}`); -}; - -const evaluateEndpointRule = (endpointRule, options) => { - const { conditions, endpoint } = endpointRule; - const { result, referenceRecord } = evaluateConditions(conditions, options); - if (!result) { - return; - } - const endpointRuleOptions = { - ...options, - referenceRecord: { ...options.referenceRecord, ...referenceRecord }, - }; - const { url, properties, headers } = endpoint; - options.logger?.debug?.(`${debugId} Resolving endpoint from template: ${toDebugString(endpoint)}`); - return { - ...(headers != undefined && { - headers: getEndpointHeaders(headers, endpointRuleOptions), - }), - ...(properties != undefined && { - properties: getEndpointProperties(properties, endpointRuleOptions), - }), - url: getEndpointUrl(url, endpointRuleOptions), - }; -}; - -const evaluateErrorRule = (errorRule, options) => { - const { conditions, error } = errorRule; - const { result, referenceRecord } = evaluateConditions(conditions, options); - if (!result) { - return; - } - throw new EndpointError(evaluateExpression(error, "Error", { - ...options, - referenceRecord: { ...options.referenceRecord, ...referenceRecord }, - })); -}; - -const evaluateRules = (rules, options) => { - for (const rule of rules) { - if (rule.type === "endpoint") { - const endpointOrUndefined = evaluateEndpointRule(rule, options); - if (endpointOrUndefined) { - return endpointOrUndefined; - } - } - else if (rule.type === "error") { - evaluateErrorRule(rule, options); - } - else if (rule.type === "tree") { - const endpointOrUndefined = group.evaluateTreeRule(rule, options); - if (endpointOrUndefined) { - return endpointOrUndefined; - } - } - else { - throw new EndpointError(`Unknown endpoint rule: ${rule}`); - } - } - throw new EndpointError(`Rules evaluation failed`); -}; -const evaluateTreeRule = (treeRule, options) => { - const { conditions, rules } = treeRule; - const { result, referenceRecord } = evaluateConditions(conditions, options); - if (!result) { - return; - } - return group.evaluateRules(rules, { - ...options, - referenceRecord: { ...options.referenceRecord, ...referenceRecord }, - }); -}; -const group = { - evaluateRules, - evaluateTreeRule, -}; - -const resolveEndpoint = (ruleSetObject, options) => { - const { endpointParams, logger } = options; - const { parameters, rules } = ruleSetObject; - options.logger?.debug?.(`${debugId} Initial EndpointParams: ${toDebugString(endpointParams)}`); - const paramsWithDefault = Object.entries(parameters) - .filter(([, v]) => v.default != null) - .map(([k, v]) => [k, v.default]); - if (paramsWithDefault.length > 0) { - for (const [paramKey, paramDefaultValue] of paramsWithDefault) { - endpointParams[paramKey] = endpointParams[paramKey] ?? paramDefaultValue; - } - } - const requiredParams = Object.entries(parameters) - .filter(([, v]) => v.required) - .map(([k]) => k); - for (const requiredParam of requiredParams) { - if (endpointParams[requiredParam] == null) { - throw new EndpointError(`Missing required parameter: '${requiredParam}'`); - } - } - const endpoint = evaluateRules(rules, { endpointParams, logger, referenceRecord: {} }); - options.logger?.debug?.(`${debugId} Resolved endpoint: ${toDebugString(endpoint)}`); - return endpoint; -}; - -exports.EndpointCache = EndpointCache; -exports.EndpointError = EndpointError; -exports.customEndpointFunctions = customEndpointFunctions; -exports.isIpAddress = isIpAddress; -exports.isValidHostLabel = isValidHostLabel; -exports.resolveEndpoint = resolveEndpoint; diff --git a/claude-code-source/node_modules/@smithy/util-endpoints/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-endpoints/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@smithy/util-endpoints/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js deleted file mode 100644 index 78a59ea8..00000000 --- a/claude-code-source/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js +++ /dev/null @@ -1,67 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - fromHex: () => fromHex, - toHex: () => toHex -}); -module.exports = __toCommonJS(src_exports); -var SHORT_TO_HEX = {}; -var HEX_TO_SHORT = {}; -for (let i = 0; i < 256; i++) { - let encodedByte = i.toString(16).toLowerCase(); - if (encodedByte.length === 1) { - encodedByte = `0${encodedByte}`; - } - SHORT_TO_HEX[i] = encodedByte; - HEX_TO_SHORT[encodedByte] = i; -} -function fromHex(encoded) { - if (encoded.length % 2 !== 0) { - throw new Error("Hex encoded strings must have an even number length"); - } - const out = new Uint8Array(encoded.length / 2); - for (let i = 0; i < encoded.length; i += 2) { - const encodedByte = encoded.slice(i, i + 2).toLowerCase(); - if (encodedByte in HEX_TO_SHORT) { - out[i / 2] = HEX_TO_SHORT[encodedByte]; - } else { - throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); - } - } - return out; -} -__name(fromHex, "fromHex"); -function toHex(bytes) { - let out = ""; - for (let i = 0; i < bytes.byteLength; i++) { - out += SHORT_TO_HEX[bytes[i]]; - } - return out; -} -__name(toHex, "toHex"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - fromHex, - toHex -}); - diff --git a/claude-code-source/node_modules/@smithy/util-middleware/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-middleware/dist-cjs/index.js deleted file mode 100644 index 2b9af753..00000000 --- a/claude-code-source/node_modules/@smithy/util-middleware/dist-cjs/index.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var types = require('@smithy/types'); - -const getSmithyContext = (context) => context[types.SMITHY_CONTEXT_KEY] || (context[types.SMITHY_CONTEXT_KEY] = {}); - -const normalizeProvider = (input) => { - if (typeof input === "function") - return input; - const promisified = Promise.resolve(input); - return () => promisified; -}; - -exports.getSmithyContext = getSmithyContext; -exports.normalizeProvider = normalizeProvider; diff --git a/claude-code-source/node_modules/@smithy/util-middleware/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-middleware/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@smithy/util-middleware/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/util-retry/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-retry/dist-cjs/index.js deleted file mode 100644 index a56d37c9..00000000 --- a/claude-code-source/node_modules/@smithy/util-retry/dist-cjs/index.js +++ /dev/null @@ -1,278 +0,0 @@ -'use strict'; - -var serviceErrorClassification = require('@smithy/service-error-classification'); - -exports.RETRY_MODES = void 0; -(function (RETRY_MODES) { - RETRY_MODES["STANDARD"] = "standard"; - RETRY_MODES["ADAPTIVE"] = "adaptive"; -})(exports.RETRY_MODES || (exports.RETRY_MODES = {})); -const DEFAULT_MAX_ATTEMPTS = 3; -const DEFAULT_RETRY_MODE = exports.RETRY_MODES.STANDARD; - -class DefaultRateLimiter { - static setTimeoutFn = setTimeout; - beta; - minCapacity; - minFillRate; - scaleConstant; - smooth; - currentCapacity = 0; - enabled = false; - lastMaxRate = 0; - measuredTxRate = 0; - requestCount = 0; - fillRate; - lastThrottleTime; - lastTimestamp = 0; - lastTxRateBucket; - maxCapacity; - timeWindow = 0; - constructor(options) { - this.beta = options?.beta ?? 0.7; - this.minCapacity = options?.minCapacity ?? 1; - this.minFillRate = options?.minFillRate ?? 0.5; - this.scaleConstant = options?.scaleConstant ?? 0.4; - this.smooth = options?.smooth ?? 0.8; - const currentTimeInSeconds = this.getCurrentTimeInSeconds(); - this.lastThrottleTime = currentTimeInSeconds; - this.lastTxRateBucket = Math.floor(this.getCurrentTimeInSeconds()); - this.fillRate = this.minFillRate; - this.maxCapacity = this.minCapacity; - } - getCurrentTimeInSeconds() { - return Date.now() / 1000; - } - async getSendToken() { - return this.acquireTokenBucket(1); - } - async acquireTokenBucket(amount) { - if (!this.enabled) { - return; - } - this.refillTokenBucket(); - if (amount > this.currentCapacity) { - const delay = ((amount - this.currentCapacity) / this.fillRate) * 1000; - await new Promise((resolve) => DefaultRateLimiter.setTimeoutFn(resolve, delay)); - } - this.currentCapacity = this.currentCapacity - amount; - } - refillTokenBucket() { - const timestamp = this.getCurrentTimeInSeconds(); - if (!this.lastTimestamp) { - this.lastTimestamp = timestamp; - return; - } - const fillAmount = (timestamp - this.lastTimestamp) * this.fillRate; - this.currentCapacity = Math.min(this.maxCapacity, this.currentCapacity + fillAmount); - this.lastTimestamp = timestamp; - } - updateClientSendingRate(response) { - let calculatedRate; - this.updateMeasuredRate(); - if (serviceErrorClassification.isThrottlingError(response)) { - const rateToUse = !this.enabled ? this.measuredTxRate : Math.min(this.measuredTxRate, this.fillRate); - this.lastMaxRate = rateToUse; - this.calculateTimeWindow(); - this.lastThrottleTime = this.getCurrentTimeInSeconds(); - calculatedRate = this.cubicThrottle(rateToUse); - this.enableTokenBucket(); - } - else { - this.calculateTimeWindow(); - calculatedRate = this.cubicSuccess(this.getCurrentTimeInSeconds()); - } - const newRate = Math.min(calculatedRate, 2 * this.measuredTxRate); - this.updateTokenBucketRate(newRate); - } - calculateTimeWindow() { - this.timeWindow = this.getPrecise(Math.pow((this.lastMaxRate * (1 - this.beta)) / this.scaleConstant, 1 / 3)); - } - cubicThrottle(rateToUse) { - return this.getPrecise(rateToUse * this.beta); - } - cubicSuccess(timestamp) { - return this.getPrecise(this.scaleConstant * Math.pow(timestamp - this.lastThrottleTime - this.timeWindow, 3) + this.lastMaxRate); - } - enableTokenBucket() { - this.enabled = true; - } - updateTokenBucketRate(newRate) { - this.refillTokenBucket(); - this.fillRate = Math.max(newRate, this.minFillRate); - this.maxCapacity = Math.max(newRate, this.minCapacity); - this.currentCapacity = Math.min(this.currentCapacity, this.maxCapacity); - } - updateMeasuredRate() { - const t = this.getCurrentTimeInSeconds(); - const timeBucket = Math.floor(t * 2) / 2; - this.requestCount++; - if (timeBucket > this.lastTxRateBucket) { - const currentRate = this.requestCount / (timeBucket - this.lastTxRateBucket); - this.measuredTxRate = this.getPrecise(currentRate * this.smooth + this.measuredTxRate * (1 - this.smooth)); - this.requestCount = 0; - this.lastTxRateBucket = timeBucket; - } - } - getPrecise(num) { - return parseFloat(num.toFixed(8)); - } -} - -const DEFAULT_RETRY_DELAY_BASE = 100; -const MAXIMUM_RETRY_DELAY = 20 * 1000; -const THROTTLING_RETRY_DELAY_BASE = 500; -const INITIAL_RETRY_TOKENS = 500; -const RETRY_COST = 5; -const TIMEOUT_RETRY_COST = 10; -const NO_RETRY_INCREMENT = 1; -const INVOCATION_ID_HEADER = "amz-sdk-invocation-id"; -const REQUEST_HEADER = "amz-sdk-request"; - -const getDefaultRetryBackoffStrategy = () => { - let delayBase = DEFAULT_RETRY_DELAY_BASE; - const computeNextBackoffDelay = (attempts) => { - return Math.floor(Math.min(MAXIMUM_RETRY_DELAY, Math.random() * 2 ** attempts * delayBase)); - }; - const setDelayBase = (delay) => { - delayBase = delay; - }; - return { - computeNextBackoffDelay, - setDelayBase, - }; -}; - -const createDefaultRetryToken = ({ retryDelay, retryCount, retryCost, }) => { - const getRetryCount = () => retryCount; - const getRetryDelay = () => Math.min(MAXIMUM_RETRY_DELAY, retryDelay); - const getRetryCost = () => retryCost; - return { - getRetryCount, - getRetryDelay, - getRetryCost, - }; -}; - -class StandardRetryStrategy { - maxAttempts; - mode = exports.RETRY_MODES.STANDARD; - capacity = INITIAL_RETRY_TOKENS; - retryBackoffStrategy = getDefaultRetryBackoffStrategy(); - maxAttemptsProvider; - constructor(maxAttempts) { - this.maxAttempts = maxAttempts; - this.maxAttemptsProvider = typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts; - } - async acquireInitialRetryToken(retryTokenScope) { - return createDefaultRetryToken({ - retryDelay: DEFAULT_RETRY_DELAY_BASE, - retryCount: 0, - }); - } - async refreshRetryTokenForRetry(token, errorInfo) { - const maxAttempts = await this.getMaxAttempts(); - if (this.shouldRetry(token, errorInfo, maxAttempts)) { - const errorType = errorInfo.errorType; - this.retryBackoffStrategy.setDelayBase(errorType === "THROTTLING" ? THROTTLING_RETRY_DELAY_BASE : DEFAULT_RETRY_DELAY_BASE); - const delayFromErrorType = this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount()); - const retryDelay = errorInfo.retryAfterHint - ? Math.max(errorInfo.retryAfterHint.getTime() - Date.now() || 0, delayFromErrorType) - : delayFromErrorType; - const capacityCost = this.getCapacityCost(errorType); - this.capacity -= capacityCost; - return createDefaultRetryToken({ - retryDelay, - retryCount: token.getRetryCount() + 1, - retryCost: capacityCost, - }); - } - throw new Error("No retry token available"); - } - recordSuccess(token) { - this.capacity = Math.max(INITIAL_RETRY_TOKENS, this.capacity + (token.getRetryCost() ?? NO_RETRY_INCREMENT)); - } - getCapacity() { - return this.capacity; - } - async getMaxAttempts() { - try { - return await this.maxAttemptsProvider(); - } - catch (error) { - console.warn(`Max attempts provider could not resolve. Using default of ${DEFAULT_MAX_ATTEMPTS}`); - return DEFAULT_MAX_ATTEMPTS; - } - } - shouldRetry(tokenToRenew, errorInfo, maxAttempts) { - const attempts = tokenToRenew.getRetryCount() + 1; - return (attempts < maxAttempts && - this.capacity >= this.getCapacityCost(errorInfo.errorType) && - this.isRetryableError(errorInfo.errorType)); - } - getCapacityCost(errorType) { - return errorType === "TRANSIENT" ? TIMEOUT_RETRY_COST : RETRY_COST; - } - isRetryableError(errorType) { - return errorType === "THROTTLING" || errorType === "TRANSIENT"; - } -} - -class AdaptiveRetryStrategy { - maxAttemptsProvider; - rateLimiter; - standardRetryStrategy; - mode = exports.RETRY_MODES.ADAPTIVE; - constructor(maxAttemptsProvider, options) { - this.maxAttemptsProvider = maxAttemptsProvider; - const { rateLimiter } = options ?? {}; - this.rateLimiter = rateLimiter ?? new DefaultRateLimiter(); - this.standardRetryStrategy = new StandardRetryStrategy(maxAttemptsProvider); - } - async acquireInitialRetryToken(retryTokenScope) { - await this.rateLimiter.getSendToken(); - return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope); - } - async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { - this.rateLimiter.updateClientSendingRate(errorInfo); - return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew, errorInfo); - } - recordSuccess(token) { - this.rateLimiter.updateClientSendingRate({}); - this.standardRetryStrategy.recordSuccess(token); - } -} - -class ConfiguredRetryStrategy extends StandardRetryStrategy { - computeNextBackoffDelay; - constructor(maxAttempts, computeNextBackoffDelay = DEFAULT_RETRY_DELAY_BASE) { - super(typeof maxAttempts === "function" ? maxAttempts : async () => maxAttempts); - if (typeof computeNextBackoffDelay === "number") { - this.computeNextBackoffDelay = () => computeNextBackoffDelay; - } - else { - this.computeNextBackoffDelay = computeNextBackoffDelay; - } - } - async refreshRetryTokenForRetry(tokenToRenew, errorInfo) { - const token = await super.refreshRetryTokenForRetry(tokenToRenew, errorInfo); - token.getRetryDelay = () => this.computeNextBackoffDelay(token.getRetryCount()); - return token; - } -} - -exports.AdaptiveRetryStrategy = AdaptiveRetryStrategy; -exports.ConfiguredRetryStrategy = ConfiguredRetryStrategy; -exports.DEFAULT_MAX_ATTEMPTS = DEFAULT_MAX_ATTEMPTS; -exports.DEFAULT_RETRY_DELAY_BASE = DEFAULT_RETRY_DELAY_BASE; -exports.DEFAULT_RETRY_MODE = DEFAULT_RETRY_MODE; -exports.DefaultRateLimiter = DefaultRateLimiter; -exports.INITIAL_RETRY_TOKENS = INITIAL_RETRY_TOKENS; -exports.INVOCATION_ID_HEADER = INVOCATION_ID_HEADER; -exports.MAXIMUM_RETRY_DELAY = MAXIMUM_RETRY_DELAY; -exports.NO_RETRY_INCREMENT = NO_RETRY_INCREMENT; -exports.REQUEST_HEADER = REQUEST_HEADER; -exports.RETRY_COST = RETRY_COST; -exports.StandardRetryStrategy = StandardRetryStrategy; -exports.THROTTLING_RETRY_DELAY_BASE = THROTTLING_RETRY_DELAY_BASE; -exports.TIMEOUT_RETRY_COST = TIMEOUT_RETRY_COST; diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/ByteArrayCollector.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/ByteArrayCollector.js deleted file mode 100644 index f056f826..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/ByteArrayCollector.js +++ /dev/null @@ -1,36 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ByteArrayCollector = void 0; -class ByteArrayCollector { - allocByteArray; - byteLength = 0; - byteArrays = []; - constructor(allocByteArray) { - this.allocByteArray = allocByteArray; - } - push(byteArray) { - this.byteArrays.push(byteArray); - this.byteLength += byteArray.byteLength; - } - flush() { - if (this.byteArrays.length === 1) { - const bytes = this.byteArrays[0]; - this.reset(); - return bytes; - } - const aggregation = this.allocByteArray(this.byteLength); - let cursor = 0; - for (let i = 0; i < this.byteArrays.length; ++i) { - const bytes = this.byteArrays[i]; - aggregation.set(bytes, cursor); - cursor += bytes.byteLength; - } - this.reset(); - return aggregation; - } - reset() { - this.byteArrays = []; - this.byteLength = 0; - } -} -exports.ByteArrayCollector = ByteArrayCollector; diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.browser.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.browser.js deleted file mode 100644 index b73363a5..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.browser.js +++ /dev/null @@ -1,7 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ChecksumStream = void 0; -const ReadableStreamRef = typeof ReadableStream === "function" ? ReadableStream : function () { }; -class ChecksumStream extends ReadableStreamRef { -} -exports.ChecksumStream = ChecksumStream; diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.js deleted file mode 100644 index f1624ec2..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/ChecksumStream.js +++ /dev/null @@ -1,53 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ChecksumStream = void 0; -const util_base64_1 = require("@smithy/util-base64"); -const stream_1 = require("stream"); -class ChecksumStream extends stream_1.Duplex { - expectedChecksum; - checksumSourceLocation; - checksum; - source; - base64Encoder; - constructor({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) { - super(); - if (typeof source.pipe === "function") { - this.source = source; - } - else { - throw new Error(`@smithy/util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`); - } - this.base64Encoder = base64Encoder ?? util_base64_1.toBase64; - this.expectedChecksum = expectedChecksum; - this.checksum = checksum; - this.checksumSourceLocation = checksumSourceLocation; - this.source.pipe(this); - } - _read(size) { } - _write(chunk, encoding, callback) { - try { - this.checksum.update(chunk); - this.push(chunk); - } - catch (e) { - return callback(e); - } - return callback(); - } - async _final(callback) { - try { - const digest = await this.checksum.digest(); - const received = this.base64Encoder(digest); - if (this.expectedChecksum !== received) { - return callback(new Error(`Checksum mismatch: expected "${this.expectedChecksum}" but received "${received}"` + - ` in response header "${this.checksumSourceLocation}".`)); - } - } - catch (e) { - return callback(e); - } - this.push(null); - return callback(); - } -} -exports.ChecksumStream = ChecksumStream; diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.browser.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.browser.js deleted file mode 100644 index 2bbe76e5..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.browser.js +++ /dev/null @@ -1,39 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createChecksumStream = void 0; -const util_base64_1 = require("@smithy/util-base64"); -const stream_type_check_1 = require("../stream-type-check"); -const ChecksumStream_browser_1 = require("./ChecksumStream.browser"); -const createChecksumStream = ({ expectedChecksum, checksum, source, checksumSourceLocation, base64Encoder, }) => { - if (!(0, stream_type_check_1.isReadableStream)(source)) { - throw new Error(`@smithy/util-stream: unsupported source type ${source?.constructor?.name ?? source} in ChecksumStream.`); - } - const encoder = base64Encoder ?? util_base64_1.toBase64; - if (typeof TransformStream !== "function") { - throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream."); - } - const transform = new TransformStream({ - start() { }, - async transform(chunk, controller) { - checksum.update(chunk); - controller.enqueue(chunk); - }, - async flush(controller) { - const digest = await checksum.digest(); - const received = encoder(digest); - if (expectedChecksum !== received) { - const error = new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}"` + - ` in response header "${checksumSourceLocation}".`); - controller.error(error); - } - else { - controller.terminate(); - } - }, - }); - source.pipeThrough(transform); - const readable = transform.readable; - Object.setPrototypeOf(readable, ChecksumStream_browser_1.ChecksumStream.prototype); - return readable; -}; -exports.createChecksumStream = createChecksumStream; diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.js deleted file mode 100644 index 9638f020..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/checksum/createChecksumStream.js +++ /dev/null @@ -1,12 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createChecksumStream = createChecksumStream; -const stream_type_check_1 = require("../stream-type-check"); -const ChecksumStream_1 = require("./ChecksumStream"); -const createChecksumStream_browser_1 = require("./createChecksumStream.browser"); -function createChecksumStream(init) { - if (typeof ReadableStream === "function" && (0, stream_type_check_1.isReadableStream)(init.source)) { - return (0, createChecksumStream_browser_1.createChecksumStream)(init); - } - return new ChecksumStream_1.ChecksumStream(init); -} diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadable.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadable.js deleted file mode 100644 index b3b47a26..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadable.js +++ /dev/null @@ -1,60 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createBufferedReadable = createBufferedReadable; -const node_stream_1 = require("node:stream"); -const ByteArrayCollector_1 = require("./ByteArrayCollector"); -const createBufferedReadableStream_1 = require("./createBufferedReadableStream"); -const stream_type_check_1 = require("./stream-type-check"); -function createBufferedReadable(upstream, size, logger) { - if ((0, stream_type_check_1.isReadableStream)(upstream)) { - return (0, createBufferedReadableStream_1.createBufferedReadableStream)(upstream, size, logger); - } - const downstream = new node_stream_1.Readable({ read() { } }); - let streamBufferingLoggedWarning = false; - let bytesSeen = 0; - const buffers = [ - "", - new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size)), - new ByteArrayCollector_1.ByteArrayCollector((size) => Buffer.from(new Uint8Array(size))), - ]; - let mode = -1; - upstream.on("data", (chunk) => { - const chunkMode = (0, createBufferedReadableStream_1.modeOf)(chunk, true); - if (mode !== chunkMode) { - if (mode >= 0) { - downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); - } - mode = chunkMode; - } - if (mode === -1) { - downstream.push(chunk); - return; - } - const chunkSize = (0, createBufferedReadableStream_1.sizeOf)(chunk); - bytesSeen += chunkSize; - const bufferSize = (0, createBufferedReadableStream_1.sizeOf)(buffers[mode]); - if (chunkSize >= size && bufferSize === 0) { - downstream.push(chunk); - } - else { - const newSize = (0, createBufferedReadableStream_1.merge)(buffers, mode, chunk); - if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { - streamBufferingLoggedWarning = true; - logger?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); - } - if (newSize >= size) { - downstream.push((0, createBufferedReadableStream_1.flush)(buffers, mode)); - } - } - }); - upstream.on("end", () => { - if (mode !== -1) { - const remainder = (0, createBufferedReadableStream_1.flush)(buffers, mode); - if ((0, createBufferedReadableStream_1.sizeOf)(remainder) > 0) { - downstream.push(remainder); - } - } - downstream.push(null); - }); - return downstream; -} diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadableStream.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadableStream.js deleted file mode 100644 index 1b7d8c38..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/createBufferedReadableStream.js +++ /dev/null @@ -1,103 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createBufferedReadable = void 0; -exports.createBufferedReadableStream = createBufferedReadableStream; -exports.merge = merge; -exports.flush = flush; -exports.sizeOf = sizeOf; -exports.modeOf = modeOf; -const ByteArrayCollector_1 = require("./ByteArrayCollector"); -function createBufferedReadableStream(upstream, size, logger) { - const reader = upstream.getReader(); - let streamBufferingLoggedWarning = false; - let bytesSeen = 0; - const buffers = ["", new ByteArrayCollector_1.ByteArrayCollector((size) => new Uint8Array(size))]; - let mode = -1; - const pull = async (controller) => { - const { value, done } = await reader.read(); - const chunk = value; - if (done) { - if (mode !== -1) { - const remainder = flush(buffers, mode); - if (sizeOf(remainder) > 0) { - controller.enqueue(remainder); - } - } - controller.close(); - } - else { - const chunkMode = modeOf(chunk, false); - if (mode !== chunkMode) { - if (mode >= 0) { - controller.enqueue(flush(buffers, mode)); - } - mode = chunkMode; - } - if (mode === -1) { - controller.enqueue(chunk); - return; - } - const chunkSize = sizeOf(chunk); - bytesSeen += chunkSize; - const bufferSize = sizeOf(buffers[mode]); - if (chunkSize >= size && bufferSize === 0) { - controller.enqueue(chunk); - } - else { - const newSize = merge(buffers, mode, chunk); - if (!streamBufferingLoggedWarning && bytesSeen > size * 2) { - streamBufferingLoggedWarning = true; - logger?.warn(`@smithy/util-stream - stream chunk size ${chunkSize} is below threshold of ${size}, automatically buffering.`); - } - if (newSize >= size) { - controller.enqueue(flush(buffers, mode)); - } - else { - await pull(controller); - } - } - } - }; - return new ReadableStream({ - pull, - }); -} -exports.createBufferedReadable = createBufferedReadableStream; -function merge(buffers, mode, chunk) { - switch (mode) { - case 0: - buffers[0] += chunk; - return sizeOf(buffers[0]); - case 1: - case 2: - buffers[mode].push(chunk); - return sizeOf(buffers[mode]); - } -} -function flush(buffers, mode) { - switch (mode) { - case 0: - const s = buffers[0]; - buffers[0] = ""; - return s; - case 1: - case 2: - return buffers[mode].flush(); - } - throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`); -} -function sizeOf(chunk) { - return chunk?.byteLength ?? chunk?.length ?? 0; -} -function modeOf(chunk, allowBuffer = true) { - if (allowBuffer && typeof Buffer !== "undefined" && chunk instanceof Buffer) { - return 2; - } - if (chunk instanceof Uint8Array) { - return 1; - } - if (typeof chunk === "string") { - return 0; - } - return -1; -} diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js deleted file mode 100644 index 4f3f9e73..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/getAwsChunkedEncodingStream.js +++ /dev/null @@ -1,30 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getAwsChunkedEncodingStream = void 0; -const stream_1 = require("stream"); -const getAwsChunkedEncodingStream = (readableStream, options) => { - const { base64Encoder, bodyLengthChecker, checksumAlgorithmFn, checksumLocationName, streamHasher } = options; - const checksumRequired = base64Encoder !== undefined && - checksumAlgorithmFn !== undefined && - checksumLocationName !== undefined && - streamHasher !== undefined; - const digest = checksumRequired ? streamHasher(checksumAlgorithmFn, readableStream) : undefined; - const awsChunkedEncodingStream = new stream_1.Readable({ read: () => { } }); - readableStream.on("data", (data) => { - const length = bodyLengthChecker(data) || 0; - awsChunkedEncodingStream.push(`${length.toString(16)}\r\n`); - awsChunkedEncodingStream.push(data); - awsChunkedEncodingStream.push("\r\n"); - }); - readableStream.on("end", async () => { - awsChunkedEncodingStream.push(`0\r\n`); - if (checksumRequired) { - const checksum = base64Encoder(await digest); - awsChunkedEncodingStream.push(`${checksumLocationName}:${checksum}\r\n`); - awsChunkedEncodingStream.push(`\r\n`); - } - awsChunkedEncodingStream.push(null); - }); - return awsChunkedEncodingStream; -}; -exports.getAwsChunkedEncodingStream = getAwsChunkedEncodingStream; diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/headStream.browser.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/headStream.browser.js deleted file mode 100644 index e8413f2c..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/headStream.browser.js +++ /dev/null @@ -1,34 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.headStream = headStream; -async function headStream(stream, bytes) { - let byteLengthCounter = 0; - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - byteLengthCounter += value?.byteLength ?? 0; - } - if (byteLengthCounter >= bytes) { - break; - } - isDone = done; - } - reader.releaseLock(); - const collected = new Uint8Array(Math.min(bytes, byteLengthCounter)); - let offset = 0; - for (const chunk of chunks) { - if (chunk.byteLength > collected.byteLength - offset) { - collected.set(chunk.subarray(0, collected.byteLength - offset), offset); - break; - } - else { - collected.set(chunk, offset); - } - offset += chunk.length; - } - return collected; -} diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/headStream.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/headStream.js deleted file mode 100644 index 4e766334..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/headStream.js +++ /dev/null @@ -1,42 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.headStream = void 0; -const stream_1 = require("stream"); -const headStream_browser_1 = require("./headStream.browser"); -const stream_type_check_1 = require("./stream-type-check"); -const headStream = (stream, bytes) => { - if ((0, stream_type_check_1.isReadableStream)(stream)) { - return (0, headStream_browser_1.headStream)(stream, bytes); - } - return new Promise((resolve, reject) => { - const collector = new Collector(); - collector.limit = bytes; - stream.pipe(collector); - stream.on("error", (err) => { - collector.end(); - reject(err); - }); - collector.on("error", reject); - collector.on("finish", function () { - const bytes = new Uint8Array(Buffer.concat(this.buffers)); - resolve(bytes); - }); - }); -}; -exports.headStream = headStream; -class Collector extends stream_1.Writable { - buffers = []; - limit = Infinity; - bytesBuffered = 0; - _write(chunk, encoding, callback) { - this.buffers.push(chunk); - this.bytesBuffered += chunk.byteLength ?? 0; - if (this.bytesBuffered >= this.limit) { - const excess = this.bytesBuffered - this.limit; - const tailBuffer = this.buffers[this.buffers.length - 1]; - this.buffers[this.buffers.length - 1] = tailBuffer.subarray(0, tailBuffer.byteLength - excess); - this.emit("finish"); - } - callback(); - } -} diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/index.js deleted file mode 100644 index a50b4993..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/index.js +++ /dev/null @@ -1,84 +0,0 @@ -'use strict'; - -var utilBase64 = require('@smithy/util-base64'); -var utilUtf8 = require('@smithy/util-utf8'); -var ChecksumStream = require('./checksum/ChecksumStream'); -var createChecksumStream = require('./checksum/createChecksumStream'); -var createBufferedReadable = require('./createBufferedReadable'); -var getAwsChunkedEncodingStream = require('./getAwsChunkedEncodingStream'); -var headStream = require('./headStream'); -var sdkStreamMixin = require('./sdk-stream-mixin'); -var splitStream = require('./splitStream'); -var streamTypeCheck = require('./stream-type-check'); - -class Uint8ArrayBlobAdapter extends Uint8Array { - static fromString(source, encoding = "utf-8") { - if (typeof source === "string") { - if (encoding === "base64") { - return Uint8ArrayBlobAdapter.mutate(utilBase64.fromBase64(source)); - } - return Uint8ArrayBlobAdapter.mutate(utilUtf8.fromUtf8(source)); - } - throw new Error(`Unsupported conversion from ${typeof source} to Uint8ArrayBlobAdapter.`); - } - static mutate(source) { - Object.setPrototypeOf(source, Uint8ArrayBlobAdapter.prototype); - return source; - } - transformToString(encoding = "utf-8") { - if (encoding === "base64") { - return utilBase64.toBase64(this); - } - return utilUtf8.toUtf8(this); - } -} - -exports.Uint8ArrayBlobAdapter = Uint8ArrayBlobAdapter; -Object.keys(ChecksumStream).forEach(function (k) { - if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { - enumerable: true, - get: function () { return ChecksumStream[k]; } - }); -}); -Object.keys(createChecksumStream).forEach(function (k) { - if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { - enumerable: true, - get: function () { return createChecksumStream[k]; } - }); -}); -Object.keys(createBufferedReadable).forEach(function (k) { - if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { - enumerable: true, - get: function () { return createBufferedReadable[k]; } - }); -}); -Object.keys(getAwsChunkedEncodingStream).forEach(function (k) { - if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { - enumerable: true, - get: function () { return getAwsChunkedEncodingStream[k]; } - }); -}); -Object.keys(headStream).forEach(function (k) { - if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { - enumerable: true, - get: function () { return headStream[k]; } - }); -}); -Object.keys(sdkStreamMixin).forEach(function (k) { - if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { - enumerable: true, - get: function () { return sdkStreamMixin[k]; } - }); -}); -Object.keys(splitStream).forEach(function (k) { - if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { - enumerable: true, - get: function () { return splitStream[k]; } - }); -}); -Object.keys(streamTypeCheck).forEach(function (k) { - if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { - enumerable: true, - get: function () { return streamTypeCheck[k]; } - }); -}); diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.browser.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.browser.js deleted file mode 100644 index 222c5f78..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.browser.js +++ /dev/null @@ -1,68 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.sdkStreamMixin = void 0; -const fetch_http_handler_1 = require("@smithy/fetch-http-handler"); -const util_base64_1 = require("@smithy/util-base64"); -const util_hex_encoding_1 = require("@smithy/util-hex-encoding"); -const util_utf8_1 = require("@smithy/util-utf8"); -const stream_type_check_1 = require("./stream-type-check"); -const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; -const sdkStreamMixin = (stream) => { - if (!isBlobInstance(stream) && !(0, stream_type_check_1.isReadableStream)(stream)) { - const name = stream?.__proto__?.constructor?.name || stream; - throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`); - } - let transformed = false; - const transformToByteArray = async () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - return await (0, fetch_http_handler_1.streamCollector)(stream); - }; - const blobToWebStream = (blob) => { - if (typeof blob.stream !== "function") { - throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\n" + - "If you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body"); - } - return blob.stream(); - }; - return Object.assign(stream, { - transformToByteArray: transformToByteArray, - transformToString: async (encoding) => { - const buf = await transformToByteArray(); - if (encoding === "base64") { - return (0, util_base64_1.toBase64)(buf); - } - else if (encoding === "hex") { - return (0, util_hex_encoding_1.toHex)(buf); - } - else if (encoding === undefined || encoding === "utf8" || encoding === "utf-8") { - return (0, util_utf8_1.toUtf8)(buf); - } - else if (typeof TextDecoder === "function") { - return new TextDecoder(encoding).decode(buf); - } - else { - throw new Error("TextDecoder is not available, please make sure polyfill is provided."); - } - }, - transformToWebStream: () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - if (isBlobInstance(stream)) { - return blobToWebStream(stream); - } - else if ((0, stream_type_check_1.isReadableStream)(stream)) { - return stream; - } - else { - throw new Error(`Cannot transform payload to web stream, got ${stream}`); - } - }, - }); -}; -exports.sdkStreamMixin = sdkStreamMixin; -const isBlobInstance = (stream) => typeof Blob === "function" && stream instanceof Blob; diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js deleted file mode 100644 index 31d8da1b..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/sdk-stream-mixin.js +++ /dev/null @@ -1,54 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.sdkStreamMixin = void 0; -const node_http_handler_1 = require("@smithy/node-http-handler"); -const util_buffer_from_1 = require("@smithy/util-buffer-from"); -const stream_1 = require("stream"); -const sdk_stream_mixin_browser_1 = require("./sdk-stream-mixin.browser"); -const ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED = "The stream has already been transformed."; -const sdkStreamMixin = (stream) => { - if (!(stream instanceof stream_1.Readable)) { - try { - return (0, sdk_stream_mixin_browser_1.sdkStreamMixin)(stream); - } - catch (e) { - const name = stream?.__proto__?.constructor?.name || stream; - throw new Error(`Unexpected stream implementation, expect Stream.Readable instance, got ${name}`); - } - } - let transformed = false; - const transformToByteArray = async () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - transformed = true; - return await (0, node_http_handler_1.streamCollector)(stream); - }; - return Object.assign(stream, { - transformToByteArray, - transformToString: async (encoding) => { - const buf = await transformToByteArray(); - if (encoding === undefined || Buffer.isEncoding(encoding)) { - return (0, util_buffer_from_1.fromArrayBuffer)(buf.buffer, buf.byteOffset, buf.byteLength).toString(encoding); - } - else { - const decoder = new TextDecoder(encoding); - return decoder.decode(buf); - } - }, - transformToWebStream: () => { - if (transformed) { - throw new Error(ERR_MSG_STREAM_HAS_BEEN_TRANSFORMED); - } - if (stream.readableFlowing !== null) { - throw new Error("The stream has been consumed by other callbacks."); - } - if (typeof stream_1.Readable.toWeb !== "function") { - throw new Error("Readable.toWeb() is not supported. Please ensure a polyfill is available."); - } - transformed = true; - return stream_1.Readable.toWeb(stream); - }, - }); -}; -exports.sdkStreamMixin = sdkStreamMixin; diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/splitStream.browser.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/splitStream.browser.js deleted file mode 100644 index 1a4cc07b..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/splitStream.browser.js +++ /dev/null @@ -1,10 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.splitStream = splitStream; -async function splitStream(stream) { - if (typeof stream.stream === "function") { - stream = stream.stream(); - } - const readableStream = stream; - return readableStream.tee(); -} diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/splitStream.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/splitStream.js deleted file mode 100644 index a60ffadf..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/splitStream.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.splitStream = splitStream; -const stream_1 = require("stream"); -const splitStream_browser_1 = require("./splitStream.browser"); -const stream_type_check_1 = require("./stream-type-check"); -async function splitStream(stream) { - if ((0, stream_type_check_1.isReadableStream)(stream) || (0, stream_type_check_1.isBlob)(stream)) { - return (0, splitStream_browser_1.splitStream)(stream); - } - const stream1 = new stream_1.PassThrough(); - const stream2 = new stream_1.PassThrough(); - stream.pipe(stream1); - stream.pipe(stream2); - return [stream1, stream2]; -} diff --git a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/stream-type-check.js b/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/stream-type-check.js deleted file mode 100644 index c4648f8d..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/dist-cjs/stream-type-check.js +++ /dev/null @@ -1,10 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.isBlob = exports.isReadableStream = void 0; -const isReadableStream = (stream) => typeof ReadableStream === "function" && - (stream?.constructor?.name === ReadableStream.name || stream instanceof ReadableStream); -exports.isReadableStream = isReadableStream; -const isBlob = (blob) => { - return typeof Blob === "function" && (blob?.constructor?.name === Blob.name || blob instanceof Blob); -}; -exports.isBlob = isBlob; diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js deleted file mode 100644 index e6673dc8..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/dist-cjs/index.js +++ /dev/null @@ -1,216 +0,0 @@ -'use strict'; - -var protocolHttp = require('@smithy/protocol-http'); -var querystringBuilder = require('@smithy/querystring-builder'); -var utilBase64 = require('@smithy/util-base64'); - -function createRequest(url, requestOptions) { - return new Request(url, requestOptions); -} - -function requestTimeout(timeoutInMs = 0) { - return new Promise((resolve, reject) => { - if (timeoutInMs) { - setTimeout(() => { - const timeoutError = new Error(`Request did not complete within ${timeoutInMs} ms`); - timeoutError.name = "TimeoutError"; - reject(timeoutError); - }, timeoutInMs); - } - }); -} - -const keepAliveSupport = { - supported: undefined, -}; -class FetchHttpHandler { - config; - configProvider; - static create(instanceOrOptions) { - if (typeof instanceOrOptions?.handle === "function") { - return instanceOrOptions; - } - return new FetchHttpHandler(instanceOrOptions); - } - constructor(options) { - if (typeof options === "function") { - this.configProvider = options().then((opts) => opts || {}); - } - else { - this.config = options ?? {}; - this.configProvider = Promise.resolve(this.config); - } - if (keepAliveSupport.supported === undefined) { - keepAliveSupport.supported = Boolean(typeof Request !== "undefined" && "keepalive" in createRequest("https://[::1]")); - } - } - destroy() { - } - async handle(request, { abortSignal, requestTimeout: requestTimeout$1 } = {}) { - if (!this.config) { - this.config = await this.configProvider; - } - const requestTimeoutInMs = requestTimeout$1 ?? this.config.requestTimeout; - const keepAlive = this.config.keepAlive === true; - const credentials = this.config.credentials; - if (abortSignal?.aborted) { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - return Promise.reject(abortError); - } - let path = request.path; - const queryString = querystringBuilder.buildQueryString(request.query || {}); - if (queryString) { - path += `?${queryString}`; - } - if (request.fragment) { - path += `#${request.fragment}`; - } - let auth = ""; - if (request.username != null || request.password != null) { - const username = request.username ?? ""; - const password = request.password ?? ""; - auth = `${username}:${password}@`; - } - const { port, method } = request; - const url = `${request.protocol}//${auth}${request.hostname}${port ? `:${port}` : ""}${path}`; - const body = method === "GET" || method === "HEAD" ? undefined : request.body; - const requestOptions = { - body, - headers: new Headers(request.headers), - method: method, - credentials, - }; - if (this.config?.cache) { - requestOptions.cache = this.config.cache; - } - if (body) { - requestOptions.duplex = "half"; - } - if (typeof AbortController !== "undefined") { - requestOptions.signal = abortSignal; - } - if (keepAliveSupport.supported) { - requestOptions.keepalive = keepAlive; - } - if (typeof this.config.requestInit === "function") { - Object.assign(requestOptions, this.config.requestInit(request)); - } - let removeSignalEventListener = () => { }; - const fetchRequest = createRequest(url, requestOptions); - const raceOfPromises = [ - fetch(fetchRequest).then((response) => { - const fetchHeaders = response.headers; - const transformedHeaders = {}; - for (const pair of fetchHeaders.entries()) { - transformedHeaders[pair[0]] = pair[1]; - } - const hasReadableStream = response.body != undefined; - if (!hasReadableStream) { - return response.blob().then((body) => ({ - response: new protocolHttp.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body, - }), - })); - } - return { - response: new protocolHttp.HttpResponse({ - headers: transformedHeaders, - reason: response.statusText, - statusCode: response.status, - body: response.body, - }), - }; - }), - requestTimeout(requestTimeoutInMs), - ]; - if (abortSignal) { - raceOfPromises.push(new Promise((resolve, reject) => { - const onAbort = () => { - const abortError = new Error("Request aborted"); - abortError.name = "AbortError"; - reject(abortError); - }; - if (typeof abortSignal.addEventListener === "function") { - const signal = abortSignal; - signal.addEventListener("abort", onAbort, { once: true }); - removeSignalEventListener = () => signal.removeEventListener("abort", onAbort); - } - else { - abortSignal.onabort = onAbort; - } - })); - } - return Promise.race(raceOfPromises).finally(removeSignalEventListener); - } - updateHttpClientConfig(key, value) { - this.config = undefined; - this.configProvider = this.configProvider.then((config) => { - config[key] = value; - return config; - }); - } - httpHandlerConfigs() { - return this.config ?? {}; - } -} - -const streamCollector = async (stream) => { - if ((typeof Blob === "function" && stream instanceof Blob) || stream.constructor?.name === "Blob") { - if (Blob.prototype.arrayBuffer !== undefined) { - return new Uint8Array(await stream.arrayBuffer()); - } - return collectBlob(stream); - } - return collectStream(stream); -}; -async function collectBlob(blob) { - const base64 = await readToBase64(blob); - const arrayBuffer = utilBase64.fromBase64(base64); - return new Uint8Array(arrayBuffer); -} -async function collectStream(stream) { - const chunks = []; - const reader = stream.getReader(); - let isDone = false; - let length = 0; - while (!isDone) { - const { done, value } = await reader.read(); - if (value) { - chunks.push(value); - length += value.length; - } - isDone = done; - } - const collected = new Uint8Array(length); - let offset = 0; - for (const chunk of chunks) { - collected.set(chunk, offset); - offset += chunk.length; - } - return collected; -} -function readToBase64(blob) { - return new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.onloadend = () => { - if (reader.readyState !== 2) { - return reject(new Error("Reader aborted too early")); - } - const result = (reader.result ?? ""); - const commaIndex = result.indexOf(","); - const dataOffset = commaIndex > -1 ? commaIndex + 1 : result.length; - resolve(result.substring(dataOffset)); - }; - reader.onabort = () => reject(new Error("Read aborted")); - reader.onerror = () => reject(reader.error); - reader.readAsDataURL(blob); - }); -} - -exports.FetchHttpHandler = FetchHttpHandler; -exports.keepAliveSupport = keepAliveSupport; -exports.streamCollector = streamCollector; diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js deleted file mode 100644 index 52303c3b..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/protocol-http/dist-cjs/index.js +++ /dev/null @@ -1,169 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js deleted file mode 100644 index f245489f..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/dist-cjs/index.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict'; - -var utilUriEscape = require('@smithy/util-uri-escape'); - -function buildQueryString(query) { - const parts = []; - for (let key of Object.keys(query).sort()) { - const value = query[key]; - key = utilUriEscape.escapeUri(key); - if (Array.isArray(value)) { - for (let i = 0, iLen = value.length; i < iLen; i++) { - parts.push(`${key}=${utilUriEscape.escapeUri(value[i])}`); - } - } - else { - let qsEntry = key; - if (value || typeof value === "string") { - qsEntry += `=${utilUriEscape.escapeUri(value)}`; - } - parts.push(qsEntry); - } - } - return parts.join("&"); -} - -exports.buildQueryString = buildQueryString; diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js deleted file mode 100644 index 11f942c3..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/fetch-http-handler/node_modules/@smithy/querystring-builder/node_modules/@smithy/util-uri-escape/dist-cjs/index.js +++ /dev/null @@ -1,9 +0,0 @@ -'use strict'; - -const escapeUri = (uri) => encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode); -const hexEncode = (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`; - -const escapeUriPath = (uri) => uri.split("/").map(escapeUri).join("/"); - -exports.escapeUri = escapeUri; -exports.escapeUriPath = escapeUriPath; diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/types/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/types/dist-cjs/index.js deleted file mode 100644 index be6d0e1a..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/types/dist-cjs/index.js +++ /dev/null @@ -1,91 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js deleted file mode 100644 index b06a7b87..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/fromBase64.js +++ /dev/null @@ -1,16 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/index.js deleted file mode 100644 index c095e288..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/index.js +++ /dev/null @@ -1,19 +0,0 @@ -'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]; } - }); -}); diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/toBase64.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/toBase64.js deleted file mode 100644 index 0590ce3f..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-base64/dist-cjs/toBase64.js +++ /dev/null @@ -1,19 +0,0 @@ -"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; diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-buffer-from/dist-cjs/index.js deleted file mode 100644 index b577c9ca..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-buffer-from/dist-cjs/index.js +++ /dev/null @@ -1,20 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js deleted file mode 100644 index 3238bb77..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || - Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; - -exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js deleted file mode 100644 index 6d1eb2d1..00000000 --- a/claude-code-source/node_modules/@smithy/util-stream/node_modules/@smithy/util-hex-encoding/dist-cjs/index.js +++ /dev/null @@ -1,38 +0,0 @@ -'use strict'; - -const SHORT_TO_HEX = {}; -const HEX_TO_SHORT = {}; -for (let i = 0; i < 256; i++) { - let encodedByte = i.toString(16).toLowerCase(); - if (encodedByte.length === 1) { - encodedByte = `0${encodedByte}`; - } - SHORT_TO_HEX[i] = encodedByte; - HEX_TO_SHORT[encodedByte] = i; -} -function fromHex(encoded) { - if (encoded.length % 2 !== 0) { - throw new Error("Hex encoded strings must have an even number length"); - } - const out = new Uint8Array(encoded.length / 2); - for (let i = 0; i < encoded.length; i += 2) { - const encodedByte = encoded.slice(i, i + 2).toLowerCase(); - if (encodedByte in HEX_TO_SHORT) { - out[i / 2] = HEX_TO_SHORT[encodedByte]; - } - else { - throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`); - } - } - return out; -} -function toHex(bytes) { - let out = ""; - for (let i = 0; i < bytes.byteLength; i++) { - out += SHORT_TO_HEX[bytes[i]]; - } - return out; -} - -exports.fromHex = fromHex; -exports.toHex = toHex; diff --git a/claude-code-source/node_modules/@smithy/util-uri-escape/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-uri-escape/dist-cjs/index.js deleted file mode 100644 index 51001efe..00000000 --- a/claude-code-source/node_modules/@smithy/util-uri-escape/dist-cjs/index.js +++ /dev/null @@ -1,43 +0,0 @@ -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - escapeUri: () => escapeUri, - escapeUriPath: () => escapeUriPath -}); -module.exports = __toCommonJS(src_exports); - -// src/escape-uri.ts -var escapeUri = /* @__PURE__ */ __name((uri) => ( - // AWS percent-encodes some extra non-standard characters in a URI - encodeURIComponent(uri).replace(/[!'()*]/g, hexEncode) -), "escapeUri"); -var hexEncode = /* @__PURE__ */ __name((c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`, "hexEncode"); - -// src/escape-uri-path.ts -var escapeUriPath = /* @__PURE__ */ __name((uri) => uri.split("/").map(escapeUri).join("/"), "escapeUriPath"); -// Annotate the CommonJS export names for ESM import in node: - -0 && (module.exports = { - escapeUri, - escapeUriPath -}); - diff --git a/claude-code-source/node_modules/@smithy/util-utf8/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-utf8/dist-cjs/index.js deleted file mode 100644 index 7f945100..00000000 --- a/claude-code-source/node_modules/@smithy/util-utf8/dist-cjs/index.js +++ /dev/null @@ -1,32 +0,0 @@ -'use strict'; - -var utilBufferFrom = require('@smithy/util-buffer-from'); - -const fromUtf8 = (input) => { - const buf = utilBufferFrom.fromString(input, "utf8"); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength / Uint8Array.BYTES_PER_ELEMENT); -}; - -const toUint8Array = (data) => { - if (typeof data === "string") { - return fromUtf8(data); - } - if (ArrayBuffer.isView(data)) { - return new Uint8Array(data.buffer, data.byteOffset, data.byteLength / Uint8Array.BYTES_PER_ELEMENT); - } - return new Uint8Array(data); -}; - -const toUtf8 = (input) => { - if (typeof input === "string") { - return input; - } - if (typeof input !== "object" || typeof input.byteOffset !== "number" || typeof input.byteLength !== "number") { - throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array."); - } - return utilBufferFrom.fromArrayBuffer(input.buffer, input.byteOffset, input.byteLength).toString("utf8"); -}; - -exports.fromUtf8 = fromUtf8; -exports.toUint8Array = toUint8Array; -exports.toUtf8 = toUtf8; diff --git a/claude-code-source/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/dist-cjs/index.js deleted file mode 100644 index b577c9ca..00000000 --- a/claude-code-source/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/dist-cjs/index.js +++ /dev/null @@ -1,20 +0,0 @@ -'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; diff --git a/claude-code-source/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js deleted file mode 100644 index 3238bb77..00000000 --- a/claude-code-source/node_modules/@smithy/util-utf8/node_modules/@smithy/util-buffer-from/node_modules/@smithy/is-array-buffer/dist-cjs/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -const isArrayBuffer = (arg) => (typeof ArrayBuffer === "function" && arg instanceof ArrayBuffer) || - Object.prototype.toString.call(arg) === "[object ArrayBuffer]"; - -exports.isArrayBuffer = isArrayBuffer; diff --git a/claude-code-source/node_modules/@smithy/uuid/dist-cjs/index.js b/claude-code-source/node_modules/@smithy/uuid/dist-cjs/index.js deleted file mode 100644 index e9399c97..00000000 --- a/claude-code-source/node_modules/@smithy/uuid/dist-cjs/index.js +++ /dev/null @@ -1,36 +0,0 @@ -'use strict'; - -var randomUUID = require('./randomUUID'); - -const decimalToHex = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0")); -const v4 = () => { - if (randomUUID.randomUUID) { - return randomUUID.randomUUID(); - } - const rnds = new Uint8Array(16); - crypto.getRandomValues(rnds); - rnds[6] = (rnds[6] & 0x0f) | 0x40; - rnds[8] = (rnds[8] & 0x3f) | 0x80; - return (decimalToHex[rnds[0]] + - decimalToHex[rnds[1]] + - decimalToHex[rnds[2]] + - decimalToHex[rnds[3]] + - "-" + - decimalToHex[rnds[4]] + - decimalToHex[rnds[5]] + - "-" + - decimalToHex[rnds[6]] + - decimalToHex[rnds[7]] + - "-" + - decimalToHex[rnds[8]] + - decimalToHex[rnds[9]] + - "-" + - decimalToHex[rnds[10]] + - decimalToHex[rnds[11]] + - decimalToHex[rnds[12]] + - decimalToHex[rnds[13]] + - decimalToHex[rnds[14]] + - decimalToHex[rnds[15]]); -}; - -exports.v4 = v4; diff --git a/claude-code-source/node_modules/@smithy/uuid/dist-cjs/randomUUID.js b/claude-code-source/node_modules/@smithy/uuid/dist-cjs/randomUUID.js deleted file mode 100644 index a1a97239..00000000 --- a/claude-code-source/node_modules/@smithy/uuid/dist-cjs/randomUUID.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.randomUUID = void 0; -const tslib_1 = require("tslib"); -const crypto_1 = tslib_1.__importDefault(require("crypto")); -exports.randomUUID = crypto_1.default.randomUUID.bind(crypto_1.default); diff --git a/claude-code-source/node_modules/@types/node b/claude-code-source/node_modules/@types/node deleted file mode 120000 index 55649128..00000000 --- a/claude-code-source/node_modules/@types/node +++ /dev/null @@ -1 +0,0 @@ -../.pnpm/@types+node@25.5.0/node_modules/@types/node \ No newline at end of file diff --git a/claude-code-source/node_modules/@types/react b/claude-code-source/node_modules/@types/react deleted file mode 120000 index a92f0bb6..00000000 --- a/claude-code-source/node_modules/@types/react +++ /dev/null @@ -1 +0,0 @@ -../.pnpm/@types+react@19.2.14/node_modules/@types/react \ No newline at end of file diff --git a/claude-code-source/node_modules/@types/ws b/claude-code-source/node_modules/@types/ws deleted file mode 120000 index 73e151dd..00000000 --- a/claude-code-source/node_modules/@types/ws +++ /dev/null @@ -1 +0,0 @@ -../.pnpm/@types+ws@8.18.1/node_modules/@types/ws \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/abort-controller/AbortError.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/abort-controller/AbortError.js deleted file mode 100644 index 4b5139e8..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/abort-controller/AbortError.js +++ /dev/null @@ -1,38 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * This error is thrown when an asynchronous operation has been aborted. - * Check for this error by testing the `name` that the name property of the - * error matches `"AbortError"`. - * - * @example - * ```ts snippet:ReadmeSampleAbortError - * import { AbortError } from "@typespec/ts-http-runtime"; - * - * async function doAsyncWork(options: { abortSignal: AbortSignal }): Promise { - * if (options.abortSignal.aborted) { - * throw new AbortError(); - * } - * - * // do async work - * } - * - * const controller = new AbortController(); - * controller.abort(); - * - * try { - * doAsyncWork({ abortSignal: controller.signal }); - * } catch (e) { - * if (e instanceof Error && e.name === "AbortError") { - * // handle abort error here. - * } - * } - * ``` - */ -export class AbortError extends Error { - constructor(message) { - super(message); - this.name = "AbortError"; - } -} -//# sourceMappingURL=AbortError.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/constants.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/constants.js deleted file mode 100644 index b7e120f4..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/constants.js +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -export const SDK_VERSION = "0.2.3"; -export const DEFAULT_RETRY_POLICY_COUNT = 3; -//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/defaultHttpClient.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/defaultHttpClient.js deleted file mode 100644 index f4b15a92..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/defaultHttpClient.js +++ /dev/null @@ -1,10 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createNodeHttpClient } from "./nodeHttpClient.js"; -/** - * Create the correct HttpClient for the current environment. - */ -export function createDefaultHttpClient() { - return createNodeHttpClient(); -} -//# sourceMappingURL=defaultHttpClient.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/httpHeaders.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/httpHeaders.js deleted file mode 100644 index ba491c7e..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/httpHeaders.js +++ /dev/null @@ -1,89 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -function normalizeName(name) { - return name.toLowerCase(); -} -function* headerIterator(map) { - for (const entry of map.values()) { - yield [entry.name, entry.value]; - } -} -class HttpHeadersImpl { - constructor(rawHeaders) { - this._headersMap = new Map(); - if (rawHeaders) { - for (const headerName of Object.keys(rawHeaders)) { - this.set(headerName, rawHeaders[headerName]); - } - } - } - /** - * Set a header in this collection with the provided name and value. The name is - * case-insensitive. - * @param name - The name of the header to set. This value is case-insensitive. - * @param value - The value of the header to set. - */ - set(name, value) { - this._headersMap.set(normalizeName(name), { name, value: String(value).trim() }); - } - /** - * Get the header value for the provided header name, or undefined if no header exists in this - * collection with the provided name. - * @param name - The name of the header. This value is case-insensitive. - */ - get(name) { - var _a; - return (_a = this._headersMap.get(normalizeName(name))) === null || _a === void 0 ? void 0 : _a.value; - } - /** - * Get whether or not this header collection contains a header entry for the provided header name. - * @param name - The name of the header to set. This value is case-insensitive. - */ - has(name) { - return this._headersMap.has(normalizeName(name)); - } - /** - * Remove the header with the provided headerName. - * @param name - The name of the header to remove. - */ - delete(name) { - this._headersMap.delete(normalizeName(name)); - } - /** - * Get the JSON object representation of this HTTP header collection. - */ - toJSON(options = {}) { - const result = {}; - if (options.preserveCase) { - for (const entry of this._headersMap.values()) { - result[entry.name] = entry.value; - } - } - else { - for (const [normalizedName, entry] of this._headersMap) { - result[normalizedName] = entry.value; - } - } - return result; - } - /** - * Get the string representation of this HTTP header collection. - */ - toString() { - return JSON.stringify(this.toJSON({ preserveCase: true })); - } - /** - * Iterate over tuples of header [name, value] pairs. - */ - [Symbol.iterator]() { - return headerIterator(this._headersMap); - } -} -/** - * Creates an object that satisfies the `HttpHeaders` interface. - * @param rawHeaders - A simple object representing initial headers - */ -export function createHttpHeaders(rawHeaders) { - return new HttpHeadersImpl(rawHeaders); -} -//# sourceMappingURL=httpHeaders.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/index.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/index.js deleted file mode 100644 index 14432ff6..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/index.js +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -export { AbortError } from "./abort-controller/AbortError.js"; -export { createClientLogger, getLogLevel, setLogLevel, TypeSpecRuntimeLogger, } from "./logger/logger.js"; -export { createHttpHeaders } from "./httpHeaders.js"; -export * from "./auth/schemes.js"; -export * from "./auth/oauth2Flows.js"; -export { createPipelineRequest } from "./pipelineRequest.js"; -export { createEmptyPipeline, } from "./pipeline.js"; -export { RestError, isRestError } from "./restError.js"; -export { stringToUint8Array, uint8ArrayToString } from "./util/bytesEncoding.js"; -export { createDefaultHttpClient } from "./defaultHttpClient.js"; -export { getClient } from "./client/getClient.js"; -export { operationOptionsToRequestParameters } from "./client/operationOptionHelpers.js"; -export { createRestError } from "./client/restError.js"; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/log.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/log.js deleted file mode 100644 index 5c452cf7..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/log.js +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createClientLogger } from "./logger/logger.js"; -export const logger = createClientLogger("ts-http-runtime"); -//# sourceMappingURL=log.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/debug.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/debug.js deleted file mode 100644 index 1ca28d6b..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/debug.js +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { log } from "./log.js"; -const debugEnvVariable = (typeof process !== "undefined" && process.env && process.env.DEBUG) || undefined; -let enabledString; -let enabledNamespaces = []; -let skippedNamespaces = []; -const debuggers = []; -if (debugEnvVariable) { - enable(debugEnvVariable); -} -const debugObj = Object.assign((namespace) => { - return createDebugger(namespace); -}, { - enable, - enabled, - disable, - log, -}); -function enable(namespaces) { - enabledString = namespaces; - enabledNamespaces = []; - skippedNamespaces = []; - const wildcard = /\*/g; - const namespaceList = namespaces.split(",").map((ns) => ns.trim().replace(wildcard, ".*?")); - for (const ns of namespaceList) { - if (ns.startsWith("-")) { - skippedNamespaces.push(new RegExp(`^${ns.substr(1)}$`)); - } - else { - enabledNamespaces.push(new RegExp(`^${ns}$`)); - } - } - for (const instance of debuggers) { - instance.enabled = enabled(instance.namespace); - } -} -function enabled(namespace) { - if (namespace.endsWith("*")) { - return true; - } - for (const skipped of skippedNamespaces) { - if (skipped.test(namespace)) { - return false; - } - } - for (const enabledNamespace of enabledNamespaces) { - if (enabledNamespace.test(namespace)) { - return true; - } - } - return false; -} -function disable() { - const result = enabledString || ""; - enable(""); - return result; -} -function createDebugger(namespace) { - const newDebugger = Object.assign(debug, { - enabled: enabled(namespace), - destroy, - log: debugObj.log, - namespace, - extend, - }); - function debug(...args) { - if (!newDebugger.enabled) { - return; - } - if (args.length > 0) { - args[0] = `${namespace} ${args[0]}`; - } - newDebugger.log(...args); - } - debuggers.push(newDebugger); - return newDebugger; -} -function destroy() { - const index = debuggers.indexOf(this); - if (index >= 0) { - debuggers.splice(index, 1); - return true; - } - return false; -} -function extend(namespace) { - const newDebugger = createDebugger(`${this.namespace}:${namespace}`); - newDebugger.log = this.log; - return newDebugger; -} -export default debugObj; -//# sourceMappingURL=debug.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/internal.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/internal.js deleted file mode 100644 index 3e5b5461..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/internal.js +++ /dev/null @@ -1,4 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -export { createLoggerContext, } from "./logger.js"; -//# sourceMappingURL=internal.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/log.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/log.js deleted file mode 100644 index 38323684..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/log.js +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { EOL } from "node:os"; -import util from "node:util"; -import * as process from "node:process"; -export function log(message, ...args) { - process.stderr.write(`${util.format(message, ...args)}${EOL}`); -} -//# sourceMappingURL=log.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/logger.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/logger.js deleted file mode 100644 index 25922d80..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/logger/logger.js +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import debug from "./debug.js"; -const TYPESPEC_RUNTIME_LOG_LEVELS = ["verbose", "info", "warning", "error"]; -const levelMap = { - verbose: 400, - info: 300, - warning: 200, - error: 100, -}; -function patchLogMethod(parent, child) { - child.log = (...args) => { - parent.log(...args); - }; -} -function isTypeSpecRuntimeLogLevel(level) { - return TYPESPEC_RUNTIME_LOG_LEVELS.includes(level); -} -/** - * Creates a logger context base on the provided options. - * @param options - The options for creating a logger context. - * @returns The logger context. - */ -export function createLoggerContext(options) { - const registeredLoggers = new Set(); - const logLevelFromEnv = (typeof process !== "undefined" && process.env && process.env[options.logLevelEnvVarName]) || - undefined; - let logLevel; - const clientLogger = debug(options.namespace); - clientLogger.log = (...args) => { - debug.log(...args); - }; - function contextSetLogLevel(level) { - if (level && !isTypeSpecRuntimeLogLevel(level)) { - throw new Error(`Unknown log level '${level}'. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(",")}`); - } - logLevel = level; - const enabledNamespaces = []; - for (const logger of registeredLoggers) { - if (shouldEnable(logger)) { - enabledNamespaces.push(logger.namespace); - } - } - debug.enable(enabledNamespaces.join(",")); - } - if (logLevelFromEnv) { - // avoid calling setLogLevel because we don't want a mis-set environment variable to crash - if (isTypeSpecRuntimeLogLevel(logLevelFromEnv)) { - contextSetLogLevel(logLevelFromEnv); - } - else { - console.error(`${options.logLevelEnvVarName} set to unknown log level '${logLevelFromEnv}'; logging is not enabled. Acceptable values: ${TYPESPEC_RUNTIME_LOG_LEVELS.join(", ")}.`); - } - } - function shouldEnable(logger) { - return Boolean(logLevel && levelMap[logger.level] <= levelMap[logLevel]); - } - function createLogger(parent, level) { - const logger = Object.assign(parent.extend(level), { - level, - }); - patchLogMethod(parent, logger); - if (shouldEnable(logger)) { - const enabledNamespaces = debug.disable(); - debug.enable(enabledNamespaces + "," + logger.namespace); - } - registeredLoggers.add(logger); - return logger; - } - function contextGetLogLevel() { - return logLevel; - } - function contextCreateClientLogger(namespace) { - const clientRootLogger = clientLogger.extend(namespace); - patchLogMethod(clientLogger, clientRootLogger); - return { - error: createLogger(clientRootLogger, "error"), - warning: createLogger(clientRootLogger, "warning"), - info: createLogger(clientRootLogger, "info"), - verbose: createLogger(clientRootLogger, "verbose"), - }; - } - return { - setLogLevel: contextSetLogLevel, - getLogLevel: contextGetLogLevel, - createClientLogger: contextCreateClientLogger, - logger: clientLogger, - }; -} -const context = createLoggerContext({ - logLevelEnvVarName: "TYPESPEC_RUNTIME_LOG_LEVEL", - namespace: "typeSpecRuntime", -}); -/** - * Immediately enables logging at the specified log level. If no level is specified, logging is disabled. - * @param level - The log level to enable for logging. - * Options from most verbose to least verbose are: - * - verbose - * - info - * - warning - * - error - */ -// eslint-disable-next-line @typescript-eslint/no-redeclare -export const TypeSpecRuntimeLogger = context.logger; -/** - * Retrieves the currently specified log level. - */ -export function setLogLevel(logLevel) { - context.setLogLevel(logLevel); -} -/** - * Retrieves the currently specified log level. - */ -export function getLogLevel() { - return context.getLogLevel(); -} -/** - * Creates a logger for use by the SDKs that inherits from `TypeSpecRuntimeLogger`. - * @param namespace - The name of the SDK package. - * @hidden - */ -export function createClientLogger(namespace) { - return context.createClientLogger(namespace); -} -//# sourceMappingURL=logger.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/nodeHttpClient.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/nodeHttpClient.js deleted file mode 100644 index 41b51289..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/nodeHttpClient.js +++ /dev/null @@ -1,341 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import * as http from "node:http"; -import * as https from "node:https"; -import * as zlib from "node:zlib"; -import { Transform } from "node:stream"; -import { AbortError } from "./abort-controller/AbortError.js"; -import { createHttpHeaders } from "./httpHeaders.js"; -import { RestError } from "./restError.js"; -import { logger } from "./log.js"; -import { Sanitizer } from "./util/sanitizer.js"; -const DEFAULT_TLS_SETTINGS = {}; -function isReadableStream(body) { - return body && typeof body.pipe === "function"; -} -function isStreamComplete(stream) { - if (stream.readable === false) { - return Promise.resolve(); - } - return new Promise((resolve) => { - const handler = () => { - resolve(); - stream.removeListener("close", handler); - stream.removeListener("end", handler); - stream.removeListener("error", handler); - }; - stream.on("close", handler); - stream.on("end", handler); - stream.on("error", handler); - }); -} -function isArrayBuffer(body) { - return body && typeof body.byteLength === "number"; -} -class ReportTransform extends Transform { - // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type - _transform(chunk, _encoding, callback) { - this.push(chunk); - this.loadedBytes += chunk.length; - try { - this.progressCallback({ loadedBytes: this.loadedBytes }); - callback(); - } - catch (e) { - callback(e); - } - } - constructor(progressCallback) { - super(); - this.loadedBytes = 0; - this.progressCallback = progressCallback; - } -} -/** - * A HttpClient implementation that uses Node's "https" module to send HTTPS requests. - * @internal - */ -class NodeHttpClient { - constructor() { - this.cachedHttpsAgents = new WeakMap(); - } - /** - * Makes a request over an underlying transport layer and returns the response. - * @param request - The request to be made. - */ - async sendRequest(request) { - var _a, _b, _c; - const abortController = new AbortController(); - let abortListener; - if (request.abortSignal) { - if (request.abortSignal.aborted) { - throw new AbortError("The operation was aborted. Request has already been canceled."); - } - abortListener = (event) => { - if (event.type === "abort") { - abortController.abort(); - } - }; - request.abortSignal.addEventListener("abort", abortListener); - } - let timeoutId; - if (request.timeout > 0) { - timeoutId = setTimeout(() => { - const sanitizer = new Sanitizer(); - logger.info(`request to '${sanitizer.sanitizeUrl(request.url)}' timed out. canceling...`); - abortController.abort(); - }, request.timeout); - } - const acceptEncoding = request.headers.get("Accept-Encoding"); - const shouldDecompress = (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("gzip")) || (acceptEncoding === null || acceptEncoding === void 0 ? void 0 : acceptEncoding.includes("deflate")); - let body = typeof request.body === "function" ? request.body() : request.body; - if (body && !request.headers.has("Content-Length")) { - const bodyLength = getBodyLength(body); - if (bodyLength !== null) { - request.headers.set("Content-Length", bodyLength); - } - } - let responseStream; - try { - if (body && request.onUploadProgress) { - const onUploadProgress = request.onUploadProgress; - const uploadReportStream = new ReportTransform(onUploadProgress); - uploadReportStream.on("error", (e) => { - logger.error("Error in upload progress", e); - }); - if (isReadableStream(body)) { - body.pipe(uploadReportStream); - } - else { - uploadReportStream.end(body); - } - body = uploadReportStream; - } - const res = await this.makeRequest(request, abortController, body); - if (timeoutId !== undefined) { - clearTimeout(timeoutId); - } - const headers = getResponseHeaders(res); - const status = (_a = res.statusCode) !== null && _a !== void 0 ? _a : 0; - const response = { - status, - headers, - request, - }; - // Responses to HEAD must not have a body. - // If they do return a body, that body must be ignored. - if (request.method === "HEAD") { - // call resume() and not destroy() to avoid closing the socket - // and losing keep alive - res.resume(); - return response; - } - responseStream = shouldDecompress ? getDecodedResponseStream(res, headers) : res; - const onDownloadProgress = request.onDownloadProgress; - if (onDownloadProgress) { - const downloadReportStream = new ReportTransform(onDownloadProgress); - downloadReportStream.on("error", (e) => { - logger.error("Error in download progress", e); - }); - responseStream.pipe(downloadReportStream); - responseStream = downloadReportStream; - } - if ( - // Value of POSITIVE_INFINITY in streamResponseStatusCodes is considered as any status code - ((_b = request.streamResponseStatusCodes) === null || _b === void 0 ? void 0 : _b.has(Number.POSITIVE_INFINITY)) || - ((_c = request.streamResponseStatusCodes) === null || _c === void 0 ? void 0 : _c.has(response.status))) { - response.readableStreamBody = responseStream; - } - else { - response.bodyAsText = await streamToText(responseStream); - } - return response; - } - finally { - // clean up event listener - if (request.abortSignal && abortListener) { - let uploadStreamDone = Promise.resolve(); - if (isReadableStream(body)) { - uploadStreamDone = isStreamComplete(body); - } - let downloadStreamDone = Promise.resolve(); - if (isReadableStream(responseStream)) { - downloadStreamDone = isStreamComplete(responseStream); - } - Promise.all([uploadStreamDone, downloadStreamDone]) - .then(() => { - var _a; - // eslint-disable-next-line promise/always-return - if (abortListener) { - (_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.removeEventListener("abort", abortListener); - } - }) - .catch((e) => { - logger.warning("Error when cleaning up abortListener on httpRequest", e); - }); - } - } - } - makeRequest(request, abortController, body) { - var _a; - const url = new URL(request.url); - const isInsecure = url.protocol !== "https:"; - if (isInsecure && !request.allowInsecureConnection) { - throw new Error(`Cannot connect to ${request.url} while allowInsecureConnection is false.`); - } - const agent = (_a = request.agent) !== null && _a !== void 0 ? _a : this.getOrCreateAgent(request, isInsecure); - const options = Object.assign({ agent, hostname: url.hostname, path: `${url.pathname}${url.search}`, port: url.port, method: request.method, headers: request.headers.toJSON({ preserveCase: true }) }, request.requestOverrides); - return new Promise((resolve, reject) => { - const req = isInsecure ? http.request(options, resolve) : https.request(options, resolve); - req.once("error", (err) => { - var _a; - reject(new RestError(err.message, { code: (_a = err.code) !== null && _a !== void 0 ? _a : RestError.REQUEST_SEND_ERROR, request })); - }); - abortController.signal.addEventListener("abort", () => { - const abortError = new AbortError("The operation was aborted. Rejecting from abort signal callback while making request."); - req.destroy(abortError); - reject(abortError); - }); - if (body && isReadableStream(body)) { - body.pipe(req); - } - else if (body) { - if (typeof body === "string" || Buffer.isBuffer(body)) { - req.end(body); - } - else if (isArrayBuffer(body)) { - req.end(ArrayBuffer.isView(body) ? Buffer.from(body.buffer) : Buffer.from(body)); - } - else { - logger.error("Unrecognized body type", body); - reject(new RestError("Unrecognized body type")); - } - } - else { - // streams don't like "undefined" being passed as data - req.end(); - } - }); - } - getOrCreateAgent(request, isInsecure) { - var _a; - const disableKeepAlive = request.disableKeepAlive; - // Handle Insecure requests first - if (isInsecure) { - if (disableKeepAlive) { - // keepAlive:false is the default so we don't need a custom Agent - return http.globalAgent; - } - if (!this.cachedHttpAgent) { - // If there is no cached agent create a new one and cache it. - this.cachedHttpAgent = new http.Agent({ keepAlive: true }); - } - return this.cachedHttpAgent; - } - else { - if (disableKeepAlive && !request.tlsSettings) { - // When there are no tlsSettings and keepAlive is false - // we don't need a custom agent - return https.globalAgent; - } - // We use the tlsSettings to index cached clients - const tlsSettings = (_a = request.tlsSettings) !== null && _a !== void 0 ? _a : DEFAULT_TLS_SETTINGS; - // Get the cached agent or create a new one with the - // provided values for keepAlive and tlsSettings - let agent = this.cachedHttpsAgents.get(tlsSettings); - if (agent && agent.options.keepAlive === !disableKeepAlive) { - return agent; - } - logger.info("No cached TLS Agent exist, creating a new Agent"); - agent = new https.Agent(Object.assign({ - // keepAlive is true if disableKeepAlive is false. - keepAlive: !disableKeepAlive }, tlsSettings)); - this.cachedHttpsAgents.set(tlsSettings, agent); - return agent; - } - } -} -function getResponseHeaders(res) { - const headers = createHttpHeaders(); - for (const header of Object.keys(res.headers)) { - const value = res.headers[header]; - if (Array.isArray(value)) { - if (value.length > 0) { - headers.set(header, value[0]); - } - } - else if (value) { - headers.set(header, value); - } - } - return headers; -} -function getDecodedResponseStream(stream, headers) { - const contentEncoding = headers.get("Content-Encoding"); - if (contentEncoding === "gzip") { - const unzip = zlib.createGunzip(); - stream.pipe(unzip); - return unzip; - } - else if (contentEncoding === "deflate") { - const inflate = zlib.createInflate(); - stream.pipe(inflate); - return inflate; - } - return stream; -} -function streamToText(stream) { - return new Promise((resolve, reject) => { - const buffer = []; - stream.on("data", (chunk) => { - if (Buffer.isBuffer(chunk)) { - buffer.push(chunk); - } - else { - buffer.push(Buffer.from(chunk)); - } - }); - stream.on("end", () => { - resolve(Buffer.concat(buffer).toString("utf8")); - }); - stream.on("error", (e) => { - if (e && (e === null || e === void 0 ? void 0 : e.name) === "AbortError") { - reject(e); - } - else { - reject(new RestError(`Error reading response as text: ${e.message}`, { - code: RestError.PARSE_ERROR, - })); - } - }); - }); -} -/** @internal */ -export function getBodyLength(body) { - if (!body) { - return 0; - } - else if (Buffer.isBuffer(body)) { - return body.length; - } - else if (isReadableStream(body)) { - return null; - } - else if (isArrayBuffer(body)) { - return body.byteLength; - } - else if (typeof body === "string") { - return Buffer.from(body).length; - } - else { - return null; - } -} -/** - * Create a new HttpClient instance for the NodeJS environment. - * @internal - */ -export function createNodeHttpClient() { - return new NodeHttpClient(); -} -//# sourceMappingURL=nodeHttpClient.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/pipeline.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/pipeline.js deleted file mode 100644 index 637b8962..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/pipeline.js +++ /dev/null @@ -1,262 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -const ValidPhaseNames = new Set(["Deserialize", "Serialize", "Retry", "Sign"]); -/** - * A private implementation of Pipeline. - * Do not export this class from the package. - * @internal - */ -class HttpPipeline { - constructor(policies) { - var _a; - this._policies = []; - this._policies = (_a = policies === null || policies === void 0 ? void 0 : policies.slice(0)) !== null && _a !== void 0 ? _a : []; - this._orderedPolicies = undefined; - } - addPolicy(policy, options = {}) { - if (options.phase && options.afterPhase) { - throw new Error("Policies inside a phase cannot specify afterPhase."); - } - if (options.phase && !ValidPhaseNames.has(options.phase)) { - throw new Error(`Invalid phase name: ${options.phase}`); - } - if (options.afterPhase && !ValidPhaseNames.has(options.afterPhase)) { - throw new Error(`Invalid afterPhase name: ${options.afterPhase}`); - } - this._policies.push({ - policy, - options, - }); - this._orderedPolicies = undefined; - } - removePolicy(options) { - const removedPolicies = []; - this._policies = this._policies.filter((policyDescriptor) => { - if ((options.name && policyDescriptor.policy.name === options.name) || - (options.phase && policyDescriptor.options.phase === options.phase)) { - removedPolicies.push(policyDescriptor.policy); - return false; - } - else { - return true; - } - }); - this._orderedPolicies = undefined; - return removedPolicies; - } - sendRequest(httpClient, request) { - const policies = this.getOrderedPolicies(); - const pipeline = policies.reduceRight((next, policy) => { - return (req) => { - return policy.sendRequest(req, next); - }; - }, (req) => httpClient.sendRequest(req)); - return pipeline(request); - } - getOrderedPolicies() { - if (!this._orderedPolicies) { - this._orderedPolicies = this.orderPolicies(); - } - return this._orderedPolicies; - } - clone() { - return new HttpPipeline(this._policies); - } - static create() { - return new HttpPipeline(); - } - orderPolicies() { - /** - * The goal of this method is to reliably order pipeline policies - * based on their declared requirements when they were added. - * - * Order is first determined by phase: - * - * 1. Serialize Phase - * 2. Policies not in a phase - * 3. Deserialize Phase - * 4. Retry Phase - * 5. Sign Phase - * - * Within each phase, policies are executed in the order - * they were added unless they were specified to execute - * before/after other policies or after a particular phase. - * - * To determine the final order, we will walk the policy list - * in phase order multiple times until all dependencies are - * satisfied. - * - * `afterPolicies` are the set of policies that must be - * executed before a given policy. This requirement is - * considered satisfied when each of the listed policies - * have been scheduled. - * - * `beforePolicies` are the set of policies that must be - * executed after a given policy. Since this dependency - * can be expressed by converting it into a equivalent - * `afterPolicies` declarations, they are normalized - * into that form for simplicity. - * - * An `afterPhase` dependency is considered satisfied when all - * policies in that phase have scheduled. - * - */ - const result = []; - // Track all policies we know about. - const policyMap = new Map(); - function createPhase(name) { - return { - name, - policies: new Set(), - hasRun: false, - hasAfterPolicies: false, - }; - } - // Track policies for each phase. - const serializePhase = createPhase("Serialize"); - const noPhase = createPhase("None"); - const deserializePhase = createPhase("Deserialize"); - const retryPhase = createPhase("Retry"); - const signPhase = createPhase("Sign"); - // a list of phases in order - const orderedPhases = [serializePhase, noPhase, deserializePhase, retryPhase, signPhase]; - // Small helper function to map phase name to each Phase - function getPhase(phase) { - if (phase === "Retry") { - return retryPhase; - } - else if (phase === "Serialize") { - return serializePhase; - } - else if (phase === "Deserialize") { - return deserializePhase; - } - else if (phase === "Sign") { - return signPhase; - } - else { - return noPhase; - } - } - // First walk each policy and create a node to track metadata. - for (const descriptor of this._policies) { - const policy = descriptor.policy; - const options = descriptor.options; - const policyName = policy.name; - if (policyMap.has(policyName)) { - throw new Error("Duplicate policy names not allowed in pipeline"); - } - const node = { - policy, - dependsOn: new Set(), - dependants: new Set(), - }; - if (options.afterPhase) { - node.afterPhase = getPhase(options.afterPhase); - node.afterPhase.hasAfterPolicies = true; - } - policyMap.set(policyName, node); - const phase = getPhase(options.phase); - phase.policies.add(node); - } - // Now that each policy has a node, connect dependency references. - for (const descriptor of this._policies) { - const { policy, options } = descriptor; - const policyName = policy.name; - const node = policyMap.get(policyName); - if (!node) { - throw new Error(`Missing node for policy ${policyName}`); - } - if (options.afterPolicies) { - for (const afterPolicyName of options.afterPolicies) { - const afterNode = policyMap.get(afterPolicyName); - if (afterNode) { - // Linking in both directions helps later - // when we want to notify dependants. - node.dependsOn.add(afterNode); - afterNode.dependants.add(node); - } - } - } - if (options.beforePolicies) { - for (const beforePolicyName of options.beforePolicies) { - const beforeNode = policyMap.get(beforePolicyName); - if (beforeNode) { - // To execute before another node, make it - // depend on the current node. - beforeNode.dependsOn.add(node); - node.dependants.add(beforeNode); - } - } - } - } - function walkPhase(phase) { - phase.hasRun = true; - // Sets iterate in insertion order - for (const node of phase.policies) { - if (node.afterPhase && (!node.afterPhase.hasRun || node.afterPhase.policies.size)) { - // If this node is waiting on a phase to complete, - // we need to skip it for now. - // Even if the phase is empty, we should wait for it - // to be walked to avoid re-ordering policies. - continue; - } - if (node.dependsOn.size === 0) { - // If there's nothing else we're waiting for, we can - // add this policy to the result list. - result.push(node.policy); - // Notify anything that depends on this policy that - // the policy has been scheduled. - for (const dependant of node.dependants) { - dependant.dependsOn.delete(node); - } - policyMap.delete(node.policy.name); - phase.policies.delete(node); - } - } - } - function walkPhases() { - for (const phase of orderedPhases) { - walkPhase(phase); - // if the phase isn't complete - if (phase.policies.size > 0 && phase !== noPhase) { - if (!noPhase.hasRun) { - // Try running noPhase to see if that unblocks this phase next tick. - // This can happen if a phase that happens before noPhase - // is waiting on a noPhase policy to complete. - walkPhase(noPhase); - } - // Don't proceed to the next phase until this phase finishes. - return; - } - if (phase.hasAfterPolicies) { - // Run any policies unblocked by this phase - walkPhase(noPhase); - } - } - } - // Iterate until we've put every node in the result list. - let iteration = 0; - while (policyMap.size > 0) { - iteration++; - const initialResultLength = result.length; - // Keep walking each phase in order until we can order every node. - walkPhases(); - // The result list *should* get at least one larger each time - // after the first full pass. - // Otherwise, we're going to loop forever. - if (result.length <= initialResultLength && iteration > 1) { - throw new Error("Cannot satisfy policy dependencies due to requirements cycle."); - } - } - return result; - } -} -/** - * Creates a totally empty pipeline. - * Useful for testing or creating a custom one. - */ -export function createEmptyPipeline() { - return HttpPipeline.create(); -} -//# sourceMappingURL=pipeline.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/pipelineRequest.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/pipelineRequest.js deleted file mode 100644 index 2a7501a3..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/pipelineRequest.js +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { createHttpHeaders } from "./httpHeaders.js"; -import { randomUUID } from "./util/uuidUtils.js"; -class PipelineRequestImpl { - constructor(options) { - var _a, _b, _c, _d, _e, _f, _g; - this.url = options.url; - this.body = options.body; - this.headers = (_a = options.headers) !== null && _a !== void 0 ? _a : createHttpHeaders(); - this.method = (_b = options.method) !== null && _b !== void 0 ? _b : "GET"; - this.timeout = (_c = options.timeout) !== null && _c !== void 0 ? _c : 0; - this.multipartBody = options.multipartBody; - this.formData = options.formData; - this.disableKeepAlive = (_d = options.disableKeepAlive) !== null && _d !== void 0 ? _d : false; - this.proxySettings = options.proxySettings; - this.streamResponseStatusCodes = options.streamResponseStatusCodes; - this.withCredentials = (_e = options.withCredentials) !== null && _e !== void 0 ? _e : false; - this.abortSignal = options.abortSignal; - this.onUploadProgress = options.onUploadProgress; - this.onDownloadProgress = options.onDownloadProgress; - this.requestId = options.requestId || randomUUID(); - this.allowInsecureConnection = (_f = options.allowInsecureConnection) !== null && _f !== void 0 ? _f : false; - this.enableBrowserStreams = (_g = options.enableBrowserStreams) !== null && _g !== void 0 ? _g : false; - this.requestOverrides = options.requestOverrides; - this.authSchemes = options.authSchemes; - } -} -/** - * Creates a new pipeline request with the given options. - * This method is to allow for the easy setting of default values and not required. - * @param options - The options to create the request with. - */ -export function createPipelineRequest(options) { - return new PipelineRequestImpl(options); -} -//# sourceMappingURL=pipelineRequest.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/agentPolicy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/agentPolicy.js deleted file mode 100644 index 3f770ed6..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/agentPolicy.js +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * Name of the Agent Policy - */ -export const agentPolicyName = "agentPolicy"; -/** - * Gets a pipeline policy that sets http.agent - */ -export function agentPolicy(agent) { - return { - name: agentPolicyName, - sendRequest: async (req, next) => { - // Users may define an agent on the request, honor it over the client level one - if (!req.agent) { - req.agent = agent; - } - return next(req); - }, - }; -} -//# sourceMappingURL=agentPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/decompressResponsePolicy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/decompressResponsePolicy.js deleted file mode 100644 index d687748a..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/decompressResponsePolicy.js +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * The programmatic identifier of the decompressResponsePolicy. - */ -export const decompressResponsePolicyName = "decompressResponsePolicy"; -/** - * A policy to enable response decompression according to Accept-Encoding header - * https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding - */ -export function decompressResponsePolicy() { - return { - name: decompressResponsePolicyName, - async sendRequest(request, next) { - // HEAD requests have no body - if (request.method !== "HEAD") { - request.headers.set("Accept-Encoding", "gzip,deflate"); - } - return next(request); - }, - }; -} -//# sourceMappingURL=decompressResponsePolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/defaultRetryPolicy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/defaultRetryPolicy.js deleted file mode 100644 index 791c0baa..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/defaultRetryPolicy.js +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { exponentialRetryStrategy } from "../retryStrategies/exponentialRetryStrategy.js"; -import { throttlingRetryStrategy } from "../retryStrategies/throttlingRetryStrategy.js"; -import { retryPolicy } from "./retryPolicy.js"; -import { DEFAULT_RETRY_POLICY_COUNT } from "../constants.js"; -/** - * Name of the {@link defaultRetryPolicy} - */ -export const defaultRetryPolicyName = "defaultRetryPolicy"; -/** - * A policy that retries according to three strategies: - * - When the server sends a 429 response with a Retry-After header. - * - When there are errors in the underlying transport layer (e.g. DNS lookup failures). - * - Or otherwise if the outgoing request fails, it will retry with an exponentially increasing delay. - */ -export function defaultRetryPolicy(options = {}) { - var _a; - return { - name: defaultRetryPolicyName, - sendRequest: retryPolicy([throttlingRetryStrategy(), exponentialRetryStrategy(options)], { - maxRetries: (_a = options.maxRetries) !== null && _a !== void 0 ? _a : DEFAULT_RETRY_POLICY_COUNT, - }).sendRequest, - }; -} -//# sourceMappingURL=defaultRetryPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/formDataPolicy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/formDataPolicy.js deleted file mode 100644 index 2c05f02f..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/formDataPolicy.js +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { stringToUint8Array } from "../util/bytesEncoding.js"; -import { isNodeLike } from "../util/checkEnvironment.js"; -import { createHttpHeaders } from "../httpHeaders.js"; -/** - * The programmatic identifier of the formDataPolicy. - */ -export const formDataPolicyName = "formDataPolicy"; -function formDataToFormDataMap(formData) { - var _a; - const formDataMap = {}; - for (const [key, value] of formData.entries()) { - (_a = formDataMap[key]) !== null && _a !== void 0 ? _a : (formDataMap[key] = []); - formDataMap[key].push(value); - } - return formDataMap; -} -/** - * A policy that encodes FormData on the request into the body. - */ -export function formDataPolicy() { - return { - name: formDataPolicyName, - async sendRequest(request, next) { - if (isNodeLike && typeof FormData !== "undefined" && request.body instanceof FormData) { - request.formData = formDataToFormDataMap(request.body); - request.body = undefined; - } - if (request.formData) { - const contentType = request.headers.get("Content-Type"); - if (contentType && contentType.indexOf("application/x-www-form-urlencoded") !== -1) { - request.body = wwwFormUrlEncode(request.formData); - } - else { - await prepareFormData(request.formData, request); - } - request.formData = undefined; - } - return next(request); - }, - }; -} -function wwwFormUrlEncode(formData) { - const urlSearchParams = new URLSearchParams(); - for (const [key, value] of Object.entries(formData)) { - if (Array.isArray(value)) { - for (const subValue of value) { - urlSearchParams.append(key, subValue.toString()); - } - } - else { - urlSearchParams.append(key, value.toString()); - } - } - return urlSearchParams.toString(); -} -async function prepareFormData(formData, request) { - // validate content type (multipart/form-data) - const contentType = request.headers.get("Content-Type"); - if (contentType && !contentType.startsWith("multipart/form-data")) { - // content type is specified and is not multipart/form-data. Exit. - return; - } - request.headers.set("Content-Type", contentType !== null && contentType !== void 0 ? contentType : "multipart/form-data"); - // set body to MultipartRequestBody using content from FormDataMap - const parts = []; - for (const [fieldName, values] of Object.entries(formData)) { - for (const value of Array.isArray(values) ? values : [values]) { - if (typeof value === "string") { - parts.push({ - headers: createHttpHeaders({ - "Content-Disposition": `form-data; name="${fieldName}"`, - }), - body: stringToUint8Array(value, "utf-8"), - }); - } - else if (value === undefined || value === null || typeof value !== "object") { - throw new Error(`Unexpected value for key ${fieldName}: ${value}. Value should be serialized to string first.`); - } - else { - // using || instead of ?? here since if value.name is empty we should create a file name - const fileName = value.name || "blob"; - const headers = createHttpHeaders(); - headers.set("Content-Disposition", `form-data; name="${fieldName}"; filename="${fileName}"`); - // again, || is used since an empty value.type means the content type is unset - headers.set("Content-Type", value.type || "application/octet-stream"); - parts.push({ - headers, - body: value, - }); - } - } - } - request.multipartBody = { parts }; -} -//# sourceMappingURL=formDataPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/internal.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/internal.js deleted file mode 100644 index d2e2522e..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/internal.js +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -export { agentPolicy, agentPolicyName } from "./agentPolicy.js"; -export { decompressResponsePolicy, decompressResponsePolicyName, } from "./decompressResponsePolicy.js"; -export { defaultRetryPolicy, defaultRetryPolicyName, } from "./defaultRetryPolicy.js"; -export { exponentialRetryPolicy, exponentialRetryPolicyName, } from "./exponentialRetryPolicy.js"; -export { retryPolicy } from "./retryPolicy.js"; -export { systemErrorRetryPolicy, systemErrorRetryPolicyName } from "./systemErrorRetryPolicy.js"; -export { throttlingRetryPolicy, throttlingRetryPolicyName } from "./throttlingRetryPolicy.js"; -export { formDataPolicy, formDataPolicyName } from "./formDataPolicy.js"; -export { logPolicy, logPolicyName } from "./logPolicy.js"; -export { multipartPolicy, multipartPolicyName } from "./multipartPolicy.js"; -export { proxyPolicy, proxyPolicyName, getDefaultProxySettings } from "./proxyPolicy.js"; -export { redirectPolicy, redirectPolicyName } from "./redirectPolicy.js"; -export { tlsPolicy, tlsPolicyName } from "./tlsPolicy.js"; -export { userAgentPolicy, userAgentPolicyName } from "./userAgentPolicy.js"; -//# sourceMappingURL=internal.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/logPolicy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/logPolicy.js deleted file mode 100644 index 2d8d94fd..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/logPolicy.js +++ /dev/null @@ -1,34 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { logger as coreLogger } from "../log.js"; -import { Sanitizer } from "../util/sanitizer.js"; -/** - * The programmatic identifier of the logPolicy. - */ -export const logPolicyName = "logPolicy"; -/** - * A policy that logs all requests and responses. - * @param options - Options to configure logPolicy. - */ -export function logPolicy(options = {}) { - var _a; - const logger = (_a = options.logger) !== null && _a !== void 0 ? _a : coreLogger.info; - const sanitizer = new Sanitizer({ - additionalAllowedHeaderNames: options.additionalAllowedHeaderNames, - additionalAllowedQueryParameters: options.additionalAllowedQueryParameters, - }); - return { - name: logPolicyName, - async sendRequest(request, next) { - if (!logger.enabled) { - return next(request); - } - logger(`Request: ${sanitizer.sanitize(request)}`); - const response = await next(request); - logger(`Response status code: ${response.status}`); - logger(`Headers: ${sanitizer.sanitize(response.headers)}`); - return response; - }, - }; -} -//# sourceMappingURL=logPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/multipartPolicy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/multipartPolicy.js deleted file mode 100644 index 269db9a5..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/multipartPolicy.js +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { stringToUint8Array } from "../util/bytesEncoding.js"; -import { isBlob } from "../util/typeGuards.js"; -import { randomUUID } from "../util/uuidUtils.js"; -import { concat } from "../util/concat.js"; -function generateBoundary() { - return `----AzSDKFormBoundary${randomUUID()}`; -} -function encodeHeaders(headers) { - let result = ""; - for (const [key, value] of headers) { - result += `${key}: ${value}\r\n`; - } - return result; -} -function getLength(source) { - if (source instanceof Uint8Array) { - return source.byteLength; - } - else if (isBlob(source)) { - // if was created using createFile then -1 means we have an unknown size - return source.size === -1 ? undefined : source.size; - } - else { - return undefined; - } -} -function getTotalLength(sources) { - let total = 0; - for (const source of sources) { - const partLength = getLength(source); - if (partLength === undefined) { - return undefined; - } - else { - total += partLength; - } - } - return total; -} -async function buildRequestBody(request, parts, boundary) { - const sources = [ - stringToUint8Array(`--${boundary}`, "utf-8"), - ...parts.flatMap((part) => [ - stringToUint8Array("\r\n", "utf-8"), - stringToUint8Array(encodeHeaders(part.headers), "utf-8"), - stringToUint8Array("\r\n", "utf-8"), - part.body, - stringToUint8Array(`\r\n--${boundary}`, "utf-8"), - ]), - stringToUint8Array("--\r\n\r\n", "utf-8"), - ]; - const contentLength = getTotalLength(sources); - if (contentLength) { - request.headers.set("Content-Length", contentLength); - } - request.body = await concat(sources); -} -/** - * Name of multipart policy - */ -export const multipartPolicyName = "multipartPolicy"; -const maxBoundaryLength = 70; -const validBoundaryCharacters = new Set(`abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'()+,-./:=?`); -function assertValidBoundary(boundary) { - if (boundary.length > maxBoundaryLength) { - throw new Error(`Multipart boundary "${boundary}" exceeds maximum length of 70 characters`); - } - if (Array.from(boundary).some((x) => !validBoundaryCharacters.has(x))) { - throw new Error(`Multipart boundary "${boundary}" contains invalid characters`); - } -} -/** - * Pipeline policy for multipart requests - */ -export function multipartPolicy() { - return { - name: multipartPolicyName, - async sendRequest(request, next) { - var _a; - if (!request.multipartBody) { - return next(request); - } - if (request.body) { - throw new Error("multipartBody and regular body cannot be set at the same time"); - } - let boundary = request.multipartBody.boundary; - const contentTypeHeader = (_a = request.headers.get("Content-Type")) !== null && _a !== void 0 ? _a : "multipart/mixed"; - const parsedHeader = contentTypeHeader.match(/^(multipart\/[^ ;]+)(?:; *boundary=(.+))?$/); - if (!parsedHeader) { - throw new Error(`Got multipart request body, but content-type header was not multipart: ${contentTypeHeader}`); - } - const [, contentType, parsedBoundary] = parsedHeader; - if (parsedBoundary && boundary && parsedBoundary !== boundary) { - throw new Error(`Multipart boundary was specified as ${parsedBoundary} in the header, but got ${boundary} in the request body`); - } - boundary !== null && boundary !== void 0 ? boundary : (boundary = parsedBoundary); - if (boundary) { - assertValidBoundary(boundary); - } - else { - boundary = generateBoundary(); - } - request.headers.set("Content-Type", `${contentType}; boundary=${boundary}`); - await buildRequestBody(request, request.multipartBody.parts, boundary); - request.multipartBody = undefined; - return next(request); - }, - }; -} -//# sourceMappingURL=multipartPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/proxyPolicy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/proxyPolicy.js deleted file mode 100644 index a722e3dd..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/proxyPolicy.js +++ /dev/null @@ -1,191 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { HttpsProxyAgent } from "https-proxy-agent"; -import { HttpProxyAgent } from "http-proxy-agent"; -import { logger } from "../log.js"; -const HTTPS_PROXY = "HTTPS_PROXY"; -const HTTP_PROXY = "HTTP_PROXY"; -const ALL_PROXY = "ALL_PROXY"; -const NO_PROXY = "NO_PROXY"; -/** - * The programmatic identifier of the proxyPolicy. - */ -export const proxyPolicyName = "proxyPolicy"; -/** - * Stores the patterns specified in NO_PROXY environment variable. - * @internal - */ -export const globalNoProxyList = []; -let noProxyListLoaded = false; -/** A cache of whether a host should bypass the proxy. */ -const globalBypassedMap = new Map(); -function getEnvironmentValue(name) { - if (process.env[name]) { - return process.env[name]; - } - else if (process.env[name.toLowerCase()]) { - return process.env[name.toLowerCase()]; - } - return undefined; -} -function loadEnvironmentProxyValue() { - if (!process) { - return undefined; - } - const httpsProxy = getEnvironmentValue(HTTPS_PROXY); - const allProxy = getEnvironmentValue(ALL_PROXY); - const httpProxy = getEnvironmentValue(HTTP_PROXY); - return httpsProxy || allProxy || httpProxy; -} -/** - * Check whether the host of a given `uri` matches any pattern in the no proxy list. - * If there's a match, any request sent to the same host shouldn't have the proxy settings set. - * This implementation is a port of https://github.com/Azure/azure-sdk-for-net/blob/8cca811371159e527159c7eb65602477898683e2/sdk/core/Azure.Core/src/Pipeline/Internal/HttpEnvironmentProxy.cs#L210 - */ -function isBypassed(uri, noProxyList, bypassedMap) { - if (noProxyList.length === 0) { - return false; - } - const host = new URL(uri).hostname; - if (bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.has(host)) { - return bypassedMap.get(host); - } - let isBypassedFlag = false; - for (const pattern of noProxyList) { - if (pattern[0] === ".") { - // This should match either domain it self or any subdomain or host - // .foo.com will match foo.com it self or *.foo.com - if (host.endsWith(pattern)) { - isBypassedFlag = true; - } - else { - if (host.length === pattern.length - 1 && host === pattern.slice(1)) { - isBypassedFlag = true; - } - } - } - else { - if (host === pattern) { - isBypassedFlag = true; - } - } - } - bypassedMap === null || bypassedMap === void 0 ? void 0 : bypassedMap.set(host, isBypassedFlag); - return isBypassedFlag; -} -export function loadNoProxy() { - const noProxy = getEnvironmentValue(NO_PROXY); - noProxyListLoaded = true; - if (noProxy) { - return noProxy - .split(",") - .map((item) => item.trim()) - .filter((item) => item.length); - } - return []; -} -/** - * This method converts a proxy url into `ProxySettings` for use with ProxyPolicy. - * If no argument is given, it attempts to parse a proxy URL from the environment - * variables `HTTPS_PROXY` or `HTTP_PROXY`. - * @param proxyUrl - The url of the proxy to use. May contain authentication information. - * @deprecated - Internally this method is no longer necessary when setting proxy information. - */ -export function getDefaultProxySettings(proxyUrl) { - if (!proxyUrl) { - proxyUrl = loadEnvironmentProxyValue(); - if (!proxyUrl) { - return undefined; - } - } - const parsedUrl = new URL(proxyUrl); - const schema = parsedUrl.protocol ? parsedUrl.protocol + "//" : ""; - return { - host: schema + parsedUrl.hostname, - port: Number.parseInt(parsedUrl.port || "80"), - username: parsedUrl.username, - password: parsedUrl.password, - }; -} -/** - * This method attempts to parse a proxy URL from the environment - * variables `HTTPS_PROXY` or `HTTP_PROXY`. - */ -function getDefaultProxySettingsInternal() { - const envProxy = loadEnvironmentProxyValue(); - return envProxy ? new URL(envProxy) : undefined; -} -function getUrlFromProxySettings(settings) { - let parsedProxyUrl; - try { - parsedProxyUrl = new URL(settings.host); - } - catch (_a) { - throw new Error(`Expecting a valid host string in proxy settings, but found "${settings.host}".`); - } - parsedProxyUrl.port = String(settings.port); - if (settings.username) { - parsedProxyUrl.username = settings.username; - } - if (settings.password) { - parsedProxyUrl.password = settings.password; - } - return parsedProxyUrl; -} -function setProxyAgentOnRequest(request, cachedAgents, proxyUrl) { - // Custom Agent should take precedence so if one is present - // we should skip to avoid overwriting it. - if (request.agent) { - return; - } - const url = new URL(request.url); - const isInsecure = url.protocol !== "https:"; - if (request.tlsSettings) { - logger.warning("TLS settings are not supported in combination with custom Proxy, certificates provided to the client will be ignored."); - } - const headers = request.headers.toJSON(); - if (isInsecure) { - if (!cachedAgents.httpProxyAgent) { - cachedAgents.httpProxyAgent = new HttpProxyAgent(proxyUrl, { headers }); - } - request.agent = cachedAgents.httpProxyAgent; - } - else { - if (!cachedAgents.httpsProxyAgent) { - cachedAgents.httpsProxyAgent = new HttpsProxyAgent(proxyUrl, { headers }); - } - request.agent = cachedAgents.httpsProxyAgent; - } -} -/** - * A policy that allows one to apply proxy settings to all requests. - * If not passed static settings, they will be retrieved from the HTTPS_PROXY - * or HTTP_PROXY environment variables. - * @param proxySettings - ProxySettings to use on each request. - * @param options - additional settings, for example, custom NO_PROXY patterns - */ -export function proxyPolicy(proxySettings, options) { - if (!noProxyListLoaded) { - globalNoProxyList.push(...loadNoProxy()); - } - const defaultProxy = proxySettings - ? getUrlFromProxySettings(proxySettings) - : getDefaultProxySettingsInternal(); - const cachedAgents = {}; - return { - name: proxyPolicyName, - async sendRequest(request, next) { - var _a; - if (!request.proxySettings && - defaultProxy && - !isBypassed(request.url, (_a = options === null || options === void 0 ? void 0 : options.customNoProxyList) !== null && _a !== void 0 ? _a : globalNoProxyList, (options === null || options === void 0 ? void 0 : options.customNoProxyList) ? undefined : globalBypassedMap)) { - setProxyAgentOnRequest(request, cachedAgents, defaultProxy); - } - else if (request.proxySettings) { - setProxyAgentOnRequest(request, cachedAgents, getUrlFromProxySettings(request.proxySettings)); - } - return next(request); - }, - }; -} -//# sourceMappingURL=proxyPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/redirectPolicy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/redirectPolicy.js deleted file mode 100644 index 0a67fd8e..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/redirectPolicy.js +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * The programmatic identifier of the redirectPolicy. - */ -export const redirectPolicyName = "redirectPolicy"; -/** - * Methods that are allowed to follow redirects 301 and 302 - */ -const allowedRedirect = ["GET", "HEAD"]; -/** - * A policy to follow Location headers from the server in order - * to support server-side redirection. - * In the browser, this policy is not used. - * @param options - Options to control policy behavior. - */ -export function redirectPolicy(options = {}) { - const { maxRetries = 20 } = options; - return { - name: redirectPolicyName, - async sendRequest(request, next) { - const response = await next(request); - return handleRedirect(next, response, maxRetries); - }, - }; -} -async function handleRedirect(next, response, maxRetries, currentRetries = 0) { - const { request, status, headers } = response; - const locationHeader = headers.get("location"); - if (locationHeader && - (status === 300 || - (status === 301 && allowedRedirect.includes(request.method)) || - (status === 302 && allowedRedirect.includes(request.method)) || - (status === 303 && request.method === "POST") || - status === 307) && - currentRetries < maxRetries) { - const url = new URL(locationHeader, request.url); - request.url = url.toString(); - // POST request with Status code 303 should be converted into a - // redirected GET request if the redirect url is present in the location header - if (status === 303) { - request.method = "GET"; - request.headers.delete("Content-Length"); - delete request.body; - } - request.headers.delete("Authorization"); - const res = await next(request); - return handleRedirect(next, res, maxRetries, currentRetries + 1); - } - return response; -} -//# sourceMappingURL=redirectPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/retryPolicy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/retryPolicy.js deleted file mode 100644 index 802de0d1..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/retryPolicy.js +++ /dev/null @@ -1,105 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { delay } from "../util/helpers.js"; -import { AbortError } from "../abort-controller/AbortError.js"; -import { createClientLogger } from "../logger/logger.js"; -import { DEFAULT_RETRY_POLICY_COUNT } from "../constants.js"; -const retryPolicyLogger = createClientLogger("ts-http-runtime retryPolicy"); -/** - * The programmatic identifier of the retryPolicy. - */ -const retryPolicyName = "retryPolicy"; -/** - * retryPolicy is a generic policy to enable retrying requests when certain conditions are met - */ -export function retryPolicy(strategies, options = { maxRetries: DEFAULT_RETRY_POLICY_COUNT }) { - const logger = options.logger || retryPolicyLogger; - return { - name: retryPolicyName, - async sendRequest(request, next) { - var _a, _b; - let response; - let responseError; - let retryCount = -1; - retryRequest: while (true) { - retryCount += 1; - response = undefined; - responseError = undefined; - try { - logger.info(`Retry ${retryCount}: Attempting to send request`, request.requestId); - response = await next(request); - logger.info(`Retry ${retryCount}: Received a response from request`, request.requestId); - } - catch (e) { - logger.error(`Retry ${retryCount}: Received an error from request`, request.requestId); - // RestErrors are valid targets for the retry strategies. - // If none of the retry strategies can work with them, they will be thrown later in this policy. - // If the received error is not a RestError, it is immediately thrown. - responseError = e; - if (!e || responseError.name !== "RestError") { - throw e; - } - response = responseError.response; - } - if ((_a = request.abortSignal) === null || _a === void 0 ? void 0 : _a.aborted) { - logger.error(`Retry ${retryCount}: Request aborted.`); - const abortError = new AbortError(); - throw abortError; - } - if (retryCount >= ((_b = options.maxRetries) !== null && _b !== void 0 ? _b : DEFAULT_RETRY_POLICY_COUNT)) { - logger.info(`Retry ${retryCount}: Maximum retries reached. Returning the last received response, or throwing the last received error.`); - if (responseError) { - throw responseError; - } - else if (response) { - return response; - } - else { - throw new Error("Maximum retries reached with no response or error to throw"); - } - } - logger.info(`Retry ${retryCount}: Processing ${strategies.length} retry strategies.`); - strategiesLoop: for (const strategy of strategies) { - const strategyLogger = strategy.logger || logger; - strategyLogger.info(`Retry ${retryCount}: Processing retry strategy ${strategy.name}.`); - const modifiers = strategy.retry({ - retryCount, - response, - responseError, - }); - if (modifiers.skipStrategy) { - strategyLogger.info(`Retry ${retryCount}: Skipped.`); - continue strategiesLoop; - } - const { errorToThrow, retryAfterInMs, redirectTo } = modifiers; - if (errorToThrow) { - strategyLogger.error(`Retry ${retryCount}: Retry strategy ${strategy.name} throws error:`, errorToThrow); - throw errorToThrow; - } - if (retryAfterInMs || retryAfterInMs === 0) { - strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} retries after ${retryAfterInMs}`); - await delay(retryAfterInMs, undefined, { abortSignal: request.abortSignal }); - continue retryRequest; - } - if (redirectTo) { - strategyLogger.info(`Retry ${retryCount}: Retry strategy ${strategy.name} redirects to ${redirectTo}`); - request.url = redirectTo; - continue retryRequest; - } - } - if (responseError) { - logger.info(`None of the retry strategies could work with the received error. Throwing it.`); - throw responseError; - } - if (response) { - logger.info(`None of the retry strategies could work with the received response. Returning it.`); - return response; - } - // If all the retries skip and there's no response, - // we're still in the retry loop, so a new request will be sent - // until `maxRetries` is reached. - } - }, - }; -} -//# sourceMappingURL=retryPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/tlsPolicy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/tlsPolicy.js deleted file mode 100644 index d2dd9b2f..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/policies/tlsPolicy.js +++ /dev/null @@ -1,22 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * Name of the TLS Policy - */ -export const tlsPolicyName = "tlsPolicy"; -/** - * Gets a pipeline policy that adds the client certificate to the HttpClient agent for authentication. - */ -export function tlsPolicy(tlsSettings) { - return { - name: tlsPolicyName, - sendRequest: async (req, next) => { - // Users may define a request tlsSettings, honor those over the client level one - if (!req.tlsSettings) { - req.tlsSettings = tlsSettings; - } - return next(req); - }, - }; -} -//# sourceMappingURL=tlsPolicy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/restError.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/restError.js deleted file mode 100644 index 501644dd..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/restError.js +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { isError } from "./util/error.js"; -import { custom } from "./util/inspect.js"; -import { Sanitizer } from "./util/sanitizer.js"; -const errorSanitizer = new Sanitizer(); -/** - * A custom error type for failed pipeline requests. - */ -export class RestError extends Error { - constructor(message, options = {}) { - super(message); - this.name = "RestError"; - this.code = options.code; - this.statusCode = options.statusCode; - // The request and response may contain sensitive information in the headers or body. - // To help prevent this sensitive information being accidentally logged, the request and response - // properties are marked as non-enumerable here. This prevents them showing up in the output of - // JSON.stringify and console.log. - Object.defineProperty(this, "request", { value: options.request, enumerable: false }); - Object.defineProperty(this, "response", { value: options.response, enumerable: false }); - // Logging method for util.inspect in Node - Object.defineProperty(this, custom, { - value: () => { - // Extract non-enumerable properties and add them back. This is OK since in this output the request and - // response get sanitized. - return `RestError: ${this.message} \n ${errorSanitizer.sanitize(Object.assign(Object.assign({}, this), { request: this.request, response: this.response }))}`; - }, - enumerable: false, - }); - Object.setPrototypeOf(this, RestError.prototype); - } -} -/** - * Something went wrong when making the request. - * This means the actual request failed for some reason, - * such as a DNS issue or the connection being lost. - */ -RestError.REQUEST_SEND_ERROR = "REQUEST_SEND_ERROR"; -/** - * This means that parsing the response from the server failed. - * It may have been malformed. - */ -RestError.PARSE_ERROR = "PARSE_ERROR"; -/** - * Typeguard for RestError - * @param e - Something caught by a catch clause. - */ -export function isRestError(e) { - if (e instanceof RestError) { - return true; - } - return isError(e) && e.name === "RestError"; -} -//# sourceMappingURL=restError.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/exponentialRetryStrategy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/exponentialRetryStrategy.js deleted file mode 100644 index 78c19d55..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/exponentialRetryStrategy.js +++ /dev/null @@ -1,64 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { calculateRetryDelay } from "../util/delay.js"; -import { isThrottlingRetryResponse } from "./throttlingRetryStrategy.js"; -// intervals are in milliseconds -const DEFAULT_CLIENT_RETRY_INTERVAL = 1000; -const DEFAULT_CLIENT_MAX_RETRY_INTERVAL = 1000 * 64; -/** - * A retry strategy that retries with an exponentially increasing delay in these two cases: - * - When there are errors in the underlying transport layer (e.g. DNS lookup failures). - * - Or otherwise if the outgoing request fails (408, greater or equal than 500, except for 501 and 505). - */ -export function exponentialRetryStrategy(options = {}) { - var _a, _b; - const retryInterval = (_a = options.retryDelayInMs) !== null && _a !== void 0 ? _a : DEFAULT_CLIENT_RETRY_INTERVAL; - const maxRetryInterval = (_b = options.maxRetryDelayInMs) !== null && _b !== void 0 ? _b : DEFAULT_CLIENT_MAX_RETRY_INTERVAL; - return { - name: "exponentialRetryStrategy", - retry({ retryCount, response, responseError }) { - const matchedSystemError = isSystemError(responseError); - const ignoreSystemErrors = matchedSystemError && options.ignoreSystemErrors; - const isExponential = isExponentialRetryResponse(response); - const ignoreExponentialResponse = isExponential && options.ignoreHttpStatusCodes; - const unknownResponse = response && (isThrottlingRetryResponse(response) || !isExponential); - if (unknownResponse || ignoreExponentialResponse || ignoreSystemErrors) { - return { skipStrategy: true }; - } - if (responseError && !matchedSystemError && !isExponential) { - return { errorToThrow: responseError }; - } - return calculateRetryDelay(retryCount, { - retryDelayInMs: retryInterval, - maxRetryDelayInMs: maxRetryInterval, - }); - }, - }; -} -/** - * A response is a retry response if it has status codes: - * - 408, or - * - Greater or equal than 500, except for 501 and 505. - */ -export function isExponentialRetryResponse(response) { - return Boolean(response && - response.status !== undefined && - (response.status >= 500 || response.status === 408) && - response.status !== 501 && - response.status !== 505); -} -/** - * Determines whether an error from a pipeline response was triggered in the network layer. - */ -export function isSystemError(err) { - if (!err) { - return false; - } - return (err.code === "ETIMEDOUT" || - err.code === "ESOCKETTIMEDOUT" || - err.code === "ECONNREFUSED" || - err.code === "ECONNRESET" || - err.code === "ENOENT" || - err.code === "ENOTFOUND"); -} -//# sourceMappingURL=exponentialRetryStrategy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/throttlingRetryStrategy.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/throttlingRetryStrategy.js deleted file mode 100644 index ccc2f0c6..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/retryStrategies/throttlingRetryStrategy.js +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { parseHeaderValueAsNumber } from "../util/helpers.js"; -/** - * The header that comes back from services representing - * the amount of time (minimum) to wait to retry (in seconds or timestamp after which we can retry). - */ -const RetryAfterHeader = "Retry-After"; -/** - * The headers that come back from services representing - * the amount of time (minimum) to wait to retry. - * - * "retry-after-ms", "x-ms-retry-after-ms" : milliseconds - * "Retry-After" : seconds or timestamp - */ -const AllRetryAfterHeaders = ["retry-after-ms", "x-ms-retry-after-ms", RetryAfterHeader]; -/** - * A response is a throttling retry response if it has a throttling status code (429 or 503), - * as long as one of the [ "Retry-After" or "retry-after-ms" or "x-ms-retry-after-ms" ] headers has a valid value. - * - * Returns the `retryAfterInMs` value if the response is a throttling retry response. - * If not throttling retry response, returns `undefined`. - * - * @internal - */ -function getRetryAfterInMs(response) { - if (!(response && [429, 503].includes(response.status))) - return undefined; - try { - // Headers: "retry-after-ms", "x-ms-retry-after-ms", "Retry-After" - for (const header of AllRetryAfterHeaders) { - const retryAfterValue = parseHeaderValueAsNumber(response, header); - if (retryAfterValue === 0 || retryAfterValue) { - // "Retry-After" header ==> seconds - // "retry-after-ms", "x-ms-retry-after-ms" headers ==> milli-seconds - const multiplyingFactor = header === RetryAfterHeader ? 1000 : 1; - return retryAfterValue * multiplyingFactor; // in milli-seconds - } - } - // RetryAfterHeader ("Retry-After") has a special case where it might be formatted as a date instead of a number of seconds - const retryAfterHeader = response.headers.get(RetryAfterHeader); - if (!retryAfterHeader) - return; - const date = Date.parse(retryAfterHeader); - const diff = date - Date.now(); - // negative diff would mean a date in the past, so retry asap with 0 milliseconds - return Number.isFinite(diff) ? Math.max(0, diff) : undefined; - } - catch (_a) { - return undefined; - } -} -/** - * A response is a retry response if it has a throttling status code (429 or 503), - * as long as one of the [ "Retry-After" or "retry-after-ms" or "x-ms-retry-after-ms" ] headers has a valid value. - */ -export function isThrottlingRetryResponse(response) { - return Number.isFinite(getRetryAfterInMs(response)); -} -export function throttlingRetryStrategy() { - return { - name: "throttlingRetryStrategy", - retry({ response }) { - const retryAfterInMs = getRetryAfterInMs(response); - if (!Number.isFinite(retryAfterInMs)) { - return { skipStrategy: true }; - } - return { - retryAfterInMs, - }; - }, - }; -} -//# sourceMappingURL=throttlingRetryStrategy.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/bytesEncoding.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/bytesEncoding.js deleted file mode 100644 index 432cc94a..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/bytesEncoding.js +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * The helper that transforms bytes with specific character encoding into string - * @param bytes - the uint8array bytes - * @param format - the format we use to encode the byte - * @returns a string of the encoded string - */ -export function uint8ArrayToString(bytes, format) { - return Buffer.from(bytes).toString(format); -} -/** - * The helper that transforms string to specific character encoded bytes array. - * @param value - the string to be converted - * @param format - the format we use to decode the value - * @returns a uint8array - */ -export function stringToUint8Array(value, format) { - return Buffer.from(value, format); -} -//# sourceMappingURL=bytesEncoding.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/checkEnvironment.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/checkEnvironment.js deleted file mode 100644 index 7b38b63a..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/checkEnvironment.js +++ /dev/null @@ -1,42 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -var _a, _b, _c, _d; -/** - * A constant that indicates whether the environment the code is running is a Web Browser. - */ -// eslint-disable-next-line @azure/azure-sdk/ts-no-window -export const isBrowser = typeof window !== "undefined" && typeof window.document !== "undefined"; -/** - * A constant that indicates whether the environment the code is running is a Web Worker. - */ -export const isWebWorker = typeof self === "object" && - typeof (self === null || self === void 0 ? void 0 : self.importScripts) === "function" && - (((_a = self.constructor) === null || _a === void 0 ? void 0 : _a.name) === "DedicatedWorkerGlobalScope" || - ((_b = self.constructor) === null || _b === void 0 ? void 0 : _b.name) === "ServiceWorkerGlobalScope" || - ((_c = self.constructor) === null || _c === void 0 ? void 0 : _c.name) === "SharedWorkerGlobalScope"); -/** - * A constant that indicates whether the environment the code is running is Deno. - */ -export const isDeno = typeof Deno !== "undefined" && - typeof Deno.version !== "undefined" && - typeof Deno.version.deno !== "undefined"; -/** - * A constant that indicates whether the environment the code is running is Bun.sh. - */ -export const isBun = typeof Bun !== "undefined" && typeof Bun.version !== "undefined"; -/** - * A constant that indicates whether the environment the code is running is a Node.js compatible environment. - */ -export const isNodeLike = typeof globalThis.process !== "undefined" && - Boolean(globalThis.process.version) && - Boolean((_d = globalThis.process.versions) === null || _d === void 0 ? void 0 : _d.node); -/** - * A constant that indicates whether the environment the code is running is Node.JS. - */ -export const isNodeRuntime = isNodeLike && !isBun && !isDeno; -/** - * A constant that indicates whether the environment the code is running is in React-Native. - */ -// https://github.com/facebook/react-native/blob/main/packages/react-native/Libraries/Core/setUpNavigator.js -export const isReactNative = typeof navigator !== "undefined" && (navigator === null || navigator === void 0 ? void 0 : navigator.product) === "ReactNative"; -//# sourceMappingURL=checkEnvironment.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/concat.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/concat.js deleted file mode 100644 index 7dc6c6ed..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/concat.js +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { __asyncGenerator, __asyncValues, __await } from "tslib"; -import { Readable } from "stream"; -import { isBlob } from "./typeGuards.js"; -function streamAsyncIterator() { - return __asyncGenerator(this, arguments, function* streamAsyncIterator_1() { - const reader = this.getReader(); - try { - while (true) { - const { done, value } = yield __await(reader.read()); - if (done) { - return yield __await(void 0); - } - yield yield __await(value); - } - } - finally { - reader.releaseLock(); - } - }); -} -function makeAsyncIterable(webStream) { - if (!webStream[Symbol.asyncIterator]) { - webStream[Symbol.asyncIterator] = streamAsyncIterator.bind(webStream); - } - if (!webStream.values) { - webStream.values = streamAsyncIterator.bind(webStream); - } -} -function ensureNodeStream(stream) { - if (stream instanceof ReadableStream) { - makeAsyncIterable(stream); - return Readable.fromWeb(stream); - } - else { - return stream; - } -} -function toStream(source) { - if (source instanceof Uint8Array) { - return Readable.from(Buffer.from(source)); - } - else if (isBlob(source)) { - return ensureNodeStream(source.stream()); - } - else { - return ensureNodeStream(source); - } -} -/** - * Utility function that concatenates a set of binary inputs into one combined output. - * - * @param sources - array of sources for the concatenation - * @returns - in Node, a (() =\> NodeJS.ReadableStream) which, when read, produces a concatenation of all the inputs. - * In browser, returns a `Blob` representing all the concatenated inputs. - * - * @internal - */ -export async function concat(sources) { - return function () { - const streams = sources.map((x) => (typeof x === "function" ? x() : x)).map(toStream); - return Readable.from((function () { - return __asyncGenerator(this, arguments, function* () { - var _a, e_1, _b, _c; - for (const stream of streams) { - try { - for (var _d = true, stream_1 = (e_1 = void 0, __asyncValues(stream)), stream_1_1; stream_1_1 = yield __await(stream_1.next()), _a = stream_1_1.done, !_a; _d = true) { - _c = stream_1_1.value; - _d = false; - const chunk = _c; - yield yield __await(chunk); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (!_d && !_a && (_b = stream_1.return)) yield __await(_b.call(stream_1)); - } - finally { if (e_1) throw e_1.error; } - } - } - }); - })()); - }; -} -//# sourceMappingURL=concat.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/delay.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/delay.js deleted file mode 100644 index b9338b86..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/delay.js +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { getRandomIntegerInclusive } from "./random.js"; -/** - * Calculates the delay interval for retry attempts using exponential delay with jitter. - * @param retryAttempt - The current retry attempt number. - * @param config - The exponential retry configuration. - * @returns An object containing the calculated retry delay. - */ -export function calculateRetryDelay(retryAttempt, config) { - // Exponentially increase the delay each time - const exponentialDelay = config.retryDelayInMs * Math.pow(2, retryAttempt); - // Don't let the delay exceed the maximum - const clampedDelay = Math.min(config.maxRetryDelayInMs, exponentialDelay); - // Allow the final value to have some "jitter" (within 50% of the delay size) so - // that retries across multiple clients don't occur simultaneously. - const retryAfterInMs = clampedDelay / 2 + getRandomIntegerInclusive(0, clampedDelay / 2); - return { retryAfterInMs }; -} -//# sourceMappingURL=delay.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/error.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/error.js deleted file mode 100644 index 204c75cd..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/error.js +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { isObject } from "./object.js"; -/** - * Typeguard for an error object shape (has name and message) - * @param e - Something caught by a catch clause. - */ -export function isError(e) { - if (isObject(e)) { - const hasName = typeof e.name === "string"; - const hasMessage = typeof e.message === "string"; - return hasName && hasMessage; - } - return false; -} -//# sourceMappingURL=error.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/helpers.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/helpers.js deleted file mode 100644 index a5bd15be..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/helpers.js +++ /dev/null @@ -1,58 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { AbortError } from "../abort-controller/AbortError.js"; -const StandardAbortMessage = "The operation was aborted."; -/** - * A wrapper for setTimeout that resolves a promise after delayInMs milliseconds. - * @param delayInMs - The number of milliseconds to be delayed. - * @param value - The value to be resolved with after a timeout of t milliseconds. - * @param options - The options for delay - currently abort options - * - abortSignal - The abortSignal associated with containing operation. - * - abortErrorMsg - The abort error message associated with containing operation. - * @returns Resolved promise - */ -export function delay(delayInMs, value, options) { - return new Promise((resolve, reject) => { - let timer = undefined; - let onAborted = undefined; - const rejectOnAbort = () => { - return reject(new AbortError((options === null || options === void 0 ? void 0 : options.abortErrorMsg) ? options === null || options === void 0 ? void 0 : options.abortErrorMsg : StandardAbortMessage)); - }; - const removeListeners = () => { - if ((options === null || options === void 0 ? void 0 : options.abortSignal) && onAborted) { - options.abortSignal.removeEventListener("abort", onAborted); - } - }; - onAborted = () => { - if (timer) { - clearTimeout(timer); - } - removeListeners(); - return rejectOnAbort(); - }; - if ((options === null || options === void 0 ? void 0 : options.abortSignal) && options.abortSignal.aborted) { - return rejectOnAbort(); - } - timer = setTimeout(() => { - removeListeners(); - resolve(value); - }, delayInMs); - if (options === null || options === void 0 ? void 0 : options.abortSignal) { - options.abortSignal.addEventListener("abort", onAborted); - } - }); -} -/** - * @internal - * @returns the parsed value or undefined if the parsed value is invalid. - */ -export function parseHeaderValueAsNumber(response, headerName) { - const value = response.headers.get(headerName); - if (!value) - return; - const valueAsNum = Number(value); - if (Number.isNaN(valueAsNum)) - return; - return valueAsNum; -} -//# sourceMappingURL=helpers.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/inspect.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/inspect.js deleted file mode 100644 index 4782720f..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/inspect.js +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { inspect } from "node:util"; -export const custom = inspect.custom; -//# sourceMappingURL=inspect.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/internal.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/internal.js deleted file mode 100644 index 3676840f..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/internal.js +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -export { calculateRetryDelay } from "./delay.js"; -export { getRandomIntegerInclusive } from "./random.js"; -export { isObject } from "./object.js"; -export { isError } from "./error.js"; -export { computeSha256Hash, computeSha256Hmac } from "./sha256.js"; -export { randomUUID } from "./uuidUtils.js"; -export { isBrowser, isBun, isNodeLike, isNodeRuntime, isDeno, isReactNative, isWebWorker, } from "./checkEnvironment.js"; -export { stringToUint8Array, uint8ArrayToString } from "./bytesEncoding.js"; -export { Sanitizer } from "./sanitizer.js"; -//# sourceMappingURL=internal.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/object.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/object.js deleted file mode 100644 index f3e9e1d1..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/object.js +++ /dev/null @@ -1,14 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * Helper to determine when an input is a generic JS object. - * @returns true when input is an object type that is not null, Array, RegExp, or Date. - */ -export function isObject(input) { - return (typeof input === "object" && - input !== null && - !Array.isArray(input) && - !(input instanceof RegExp) && - !(input instanceof Date)); -} -//# sourceMappingURL=object.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/random.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/random.js deleted file mode 100644 index 88eee7f7..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/random.js +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -/** - * Returns a random integer value between a lower and upper bound, - * inclusive of both bounds. - * Note that this uses Math.random and isn't secure. If you need to use - * this for any kind of security purpose, find a better source of random. - * @param min - The smallest integer value allowed. - * @param max - The largest integer value allowed. - */ -export function getRandomIntegerInclusive(min, max) { - // Make sure inputs are integers. - min = Math.ceil(min); - max = Math.floor(max); - // Pick a random offset from zero to the size of the range. - // Since Math.random() can never return 1, we have to make the range one larger - // in order to be inclusive of the maximum value after we take the floor. - const offset = Math.floor(Math.random() * (max - min + 1)); - return offset + min; -} -//# sourceMappingURL=random.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/sanitizer.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/sanitizer.js deleted file mode 100644 index 4add75d6..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/sanitizer.js +++ /dev/null @@ -1,149 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -import { isObject } from "./object.js"; -const RedactedString = "REDACTED"; -// Make sure this list is up-to-date with the one under core/logger/Readme#Keyconcepts -const defaultAllowedHeaderNames = [ - "x-ms-client-request-id", - "x-ms-return-client-request-id", - "x-ms-useragent", - "x-ms-correlation-request-id", - "x-ms-request-id", - "client-request-id", - "ms-cv", - "return-client-request-id", - "traceparent", - "Access-Control-Allow-Credentials", - "Access-Control-Allow-Headers", - "Access-Control-Allow-Methods", - "Access-Control-Allow-Origin", - "Access-Control-Expose-Headers", - "Access-Control-Max-Age", - "Access-Control-Request-Headers", - "Access-Control-Request-Method", - "Origin", - "Accept", - "Accept-Encoding", - "Cache-Control", - "Connection", - "Content-Length", - "Content-Type", - "Date", - "ETag", - "Expires", - "If-Match", - "If-Modified-Since", - "If-None-Match", - "If-Unmodified-Since", - "Last-Modified", - "Pragma", - "Request-Id", - "Retry-After", - "Server", - "Transfer-Encoding", - "User-Agent", - "WWW-Authenticate", -]; -const defaultAllowedQueryParameters = ["api-version"]; -/** - * A utility class to sanitize objects for logging. - */ -export class Sanitizer { - constructor({ additionalAllowedHeaderNames: allowedHeaderNames = [], additionalAllowedQueryParameters: allowedQueryParameters = [], } = {}) { - allowedHeaderNames = defaultAllowedHeaderNames.concat(allowedHeaderNames); - allowedQueryParameters = defaultAllowedQueryParameters.concat(allowedQueryParameters); - this.allowedHeaderNames = new Set(allowedHeaderNames.map((n) => n.toLowerCase())); - this.allowedQueryParameters = new Set(allowedQueryParameters.map((p) => p.toLowerCase())); - } - /** - * Sanitizes an object for logging. - * @param obj - The object to sanitize - * @returns - The sanitized object as a string - */ - sanitize(obj) { - const seen = new Set(); - return JSON.stringify(obj, (key, value) => { - // Ensure Errors include their interesting non-enumerable members - if (value instanceof Error) { - return Object.assign(Object.assign({}, value), { name: value.name, message: value.message }); - } - if (key === "headers") { - return this.sanitizeHeaders(value); - } - else if (key === "url") { - return this.sanitizeUrl(value); - } - else if (key === "query") { - return this.sanitizeQuery(value); - } - else if (key === "body") { - // Don't log the request body - return undefined; - } - else if (key === "response") { - // Don't log response again - return undefined; - } - else if (key === "operationSpec") { - // When using sendOperationRequest, the request carries a massive - // field with the autorest spec. No need to log it. - return undefined; - } - else if (Array.isArray(value) || isObject(value)) { - if (seen.has(value)) { - return "[Circular]"; - } - seen.add(value); - } - return value; - }, 2); - } - /** - * Sanitizes a URL for logging. - * @param value - The URL to sanitize - * @returns - The sanitized URL as a string - */ - sanitizeUrl(value) { - if (typeof value !== "string" || value === null || value === "") { - return value; - } - const url = new URL(value); - if (!url.search) { - return value; - } - for (const [key] of url.searchParams) { - if (!this.allowedQueryParameters.has(key.toLowerCase())) { - url.searchParams.set(key, RedactedString); - } - } - return url.toString(); - } - sanitizeHeaders(obj) { - const sanitized = {}; - for (const key of Object.keys(obj)) { - if (this.allowedHeaderNames.has(key.toLowerCase())) { - sanitized[key] = obj[key]; - } - else { - sanitized[key] = RedactedString; - } - } - return sanitized; - } - sanitizeQuery(value) { - if (typeof value !== "object" || value === null) { - return value; - } - const sanitized = {}; - for (const k of Object.keys(value)) { - if (this.allowedQueryParameters.has(k.toLowerCase())) { - sanitized[k] = value[k]; - } - else { - sanitized[k] = RedactedString; - } - } - return sanitized; - } -} -//# sourceMappingURL=sanitizer.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/typeGuards.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/typeGuards.js deleted file mode 100644 index c8e3b812..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/typeGuards.js +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -export function isNodeReadableStream(x) { - return Boolean(x && typeof x["pipe"] === "function"); -} -export function isWebReadableStream(x) { - return Boolean(x && - typeof x.getReader === "function" && - typeof x.tee === "function"); -} -export function isBinaryBody(body) { - return (body !== undefined && - (body instanceof Uint8Array || - isReadableStream(body) || - typeof body === "function" || - body instanceof Blob)); -} -export function isReadableStream(x) { - return isNodeReadableStream(x) || isWebReadableStream(x); -} -export function isBlob(x) { - return typeof x.stream === "function"; -} -//# sourceMappingURL=typeGuards.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/uuidUtils.js b/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/uuidUtils.js deleted file mode 100644 index e50afafc..00000000 --- a/claude-code-source/node_modules/@typespec/ts-http-runtime/dist/esm/util/uuidUtils.js +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright (c) Microsoft Corporation. -// Licensed under the MIT License. -var _a; -import { randomUUID as v4RandomUUID } from "node:crypto"; -// NOTE: This is a workaround until we can use `globalThis.crypto.randomUUID` in Node.js 19+. -const uuidFunction = typeof ((_a = globalThis === null || globalThis === void 0 ? void 0 : globalThis.crypto) === null || _a === void 0 ? void 0 : _a.randomUUID) === "function" - ? globalThis.crypto.randomUUID.bind(globalThis.crypto) - : v4RandomUUID; -/** - * Generated Universally Unique Identifier - * - * @returns RFC4122 v4 UUID. - */ -export function randomUUID() { - return uuidFunction(); -} -//# sourceMappingURL=uuidUtils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/@xmldom/xmldom/lib/conventions.js b/claude-code-source/node_modules/@xmldom/xmldom/lib/conventions.js deleted file mode 100644 index 953f0eff..00000000 --- a/claude-code-source/node_modules/@xmldom/xmldom/lib/conventions.js +++ /dev/null @@ -1,203 +0,0 @@ -'use strict' - -/** - * Ponyfill for `Array.prototype.find` which is only available in ES6 runtimes. - * - * Works with anything that has a `length` property and index access properties, including NodeList. - * - * @template {unknown} T - * @param {Array | ({length:number, [number]: T})} list - * @param {function (item: T, index: number, list:Array | ({length:number, [number]: T})):boolean} predicate - * @param {Partial>?} ac `Array.prototype` by default, - * allows injecting a custom implementation in tests - * @returns {T | undefined} - * - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find - * @see https://tc39.es/ecma262/multipage/indexed-collections.html#sec-array.prototype.find - */ -function find(list, predicate, ac) { - if (ac === undefined) { - ac = Array.prototype; - } - if (list && typeof ac.find === 'function') { - return ac.find.call(list, predicate); - } - for (var i = 0; i < list.length; i++) { - if (Object.prototype.hasOwnProperty.call(list, i)) { - var item = list[i]; - if (predicate.call(undefined, item, i, list)) { - return item; - } - } - } -} - -/** - * "Shallow freezes" an object to render it immutable. - * Uses `Object.freeze` if available, - * otherwise the immutability is only in the type. - * - * Is used to create "enum like" objects. - * - * @template T - * @param {T} object the object to freeze - * @param {Pick = Object} oc `Object` by default, - * allows to inject custom object constructor for tests - * @returns {Readonly} - * - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze - */ -function freeze(object, oc) { - if (oc === undefined) { - oc = Object - } - return oc && typeof oc.freeze === 'function' ? oc.freeze(object) : object -} - -/** - * Since we can not rely on `Object.assign` we provide a simplified version - * that is sufficient for our needs. - * - * @param {Object} target - * @param {Object | null | undefined} source - * - * @returns {Object} target - * @throws TypeError if target is not an object - * - * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign - * @see https://tc39.es/ecma262/multipage/fundamental-objects.html#sec-object.assign - */ -function assign(target, source) { - if (target === null || typeof target !== 'object') { - throw new TypeError('target is not an object') - } - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key] - } - } - return target -} - -/** - * All mime types that are allowed as input to `DOMParser.parseFromString` - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument02 MDN - * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#domparsersupportedtype WHATWG HTML Spec - * @see DOMParser.prototype.parseFromString - */ -var MIME_TYPE = freeze({ - /** - * `text/html`, the only mime type that triggers treating an XML document as HTML. - * - * @see DOMParser.SupportedType.isHTML - * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration - * @see https://en.wikipedia.org/wiki/HTML Wikipedia - * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN - * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring WHATWG HTML Spec - */ - HTML: 'text/html', - - /** - * Helper method to check a mime type if it indicates an HTML document - * - * @param {string} [value] - * @returns {boolean} - * - * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration - * @see https://en.wikipedia.org/wiki/HTML Wikipedia - * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN - * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring */ - isHTML: function (value) { - return value === MIME_TYPE.HTML - }, - - /** - * `application/xml`, the standard mime type for XML documents. - * - * @see https://www.iana.org/assignments/media-types/application/xml IANA MimeType registration - * @see https://tools.ietf.org/html/rfc7303#section-9.1 RFC 7303 - * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia - */ - XML_APPLICATION: 'application/xml', - - /** - * `text/html`, an alias for `application/xml`. - * - * @see https://tools.ietf.org/html/rfc7303#section-9.2 RFC 7303 - * @see https://www.iana.org/assignments/media-types/text/xml IANA MimeType registration - * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia - */ - XML_TEXT: 'text/xml', - - /** - * `application/xhtml+xml`, indicates an XML document that has the default HTML namespace, - * but is parsed as an XML document. - * - * @see https://www.iana.org/assignments/media-types/application/xhtml+xml IANA MimeType registration - * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument WHATWG DOM Spec - * @see https://en.wikipedia.org/wiki/XHTML Wikipedia - */ - XML_XHTML_APPLICATION: 'application/xhtml+xml', - - /** - * `image/svg+xml`, - * - * @see https://www.iana.org/assignments/media-types/image/svg+xml IANA MimeType registration - * @see https://www.w3.org/TR/SVG11/ W3C SVG 1.1 - * @see https://en.wikipedia.org/wiki/Scalable_Vector_Graphics Wikipedia - */ - XML_SVG_IMAGE: 'image/svg+xml', -}) - -/** - * Namespaces that are used in this code base. - * - * @see http://www.w3.org/TR/REC-xml-names - */ -var NAMESPACE = freeze({ - /** - * The XHTML namespace. - * - * @see http://www.w3.org/1999/xhtml - */ - HTML: 'http://www.w3.org/1999/xhtml', - - /** - * Checks if `uri` equals `NAMESPACE.HTML`. - * - * @param {string} [uri] - * - * @see NAMESPACE.HTML - */ - isHTML: function (uri) { - return uri === NAMESPACE.HTML - }, - - /** - * The SVG namespace. - * - * @see http://www.w3.org/2000/svg - */ - SVG: 'http://www.w3.org/2000/svg', - - /** - * The `xml:` namespace. - * - * @see http://www.w3.org/XML/1998/namespace - */ - XML: 'http://www.w3.org/XML/1998/namespace', - - /** - * The `xmlns:` namespace - * - * @see https://www.w3.org/2000/xmlns/ - */ - XMLNS: 'http://www.w3.org/2000/xmlns/', -}) - -exports.assign = assign; -exports.find = find; -exports.freeze = freeze; -exports.MIME_TYPE = MIME_TYPE; -exports.NAMESPACE = NAMESPACE; diff --git a/claude-code-source/node_modules/@xmldom/xmldom/lib/dom-parser.js b/claude-code-source/node_modules/@xmldom/xmldom/lib/dom-parser.js deleted file mode 100644 index 94769a21..00000000 --- a/claude-code-source/node_modules/@xmldom/xmldom/lib/dom-parser.js +++ /dev/null @@ -1,322 +0,0 @@ -var conventions = require("./conventions"); -var dom = require('./dom') -var entities = require('./entities'); -var sax = require('./sax'); - -var DOMImplementation = dom.DOMImplementation; - -var NAMESPACE = conventions.NAMESPACE; - -var ParseError = sax.ParseError; -var XMLReader = sax.XMLReader; - -/** - * Normalizes line ending according to https://www.w3.org/TR/xml11/#sec-line-ends: - * - * > XML parsed entities are often stored in computer files which, - * > for editing convenience, are organized into lines. - * > These lines are typically separated by some combination - * > of the characters CARRIAGE RETURN (#xD) and LINE FEED (#xA). - * > - * > To simplify the tasks of applications, the XML processor must behave - * > as if it normalized all line breaks in external parsed entities (including the document entity) - * > on input, before parsing, by translating all of the following to a single #xA character: - * > - * > 1. the two-character sequence #xD #xA - * > 2. the two-character sequence #xD #x85 - * > 3. the single character #x85 - * > 4. the single character #x2028 - * > 5. any #xD character that is not immediately followed by #xA or #x85. - * - * @param {string} input - * @returns {string} - */ -function normalizeLineEndings(input) { - return input - .replace(/\r[\n\u0085]/g, '\n') - .replace(/[\r\u0085\u2028]/g, '\n') -} - -/** - * @typedef Locator - * @property {number} [columnNumber] - * @property {number} [lineNumber] - */ - -/** - * @typedef DOMParserOptions - * @property {DOMHandler} [domBuilder] - * @property {Function} [errorHandler] - * @property {(string) => string} [normalizeLineEndings] used to replace line endings before parsing - * defaults to `normalizeLineEndings` - * @property {Locator} [locator] - * @property {Record} [xmlns] - * - * @see normalizeLineEndings - */ - -/** - * The DOMParser interface provides the ability to parse XML or HTML source code - * from a string into a DOM `Document`. - * - * _xmldom is different from the spec in that it allows an `options` parameter, - * to override the default behavior._ - * - * @param {DOMParserOptions} [options] - * @constructor - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser - * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-parsing-and-serialization - */ -function DOMParser(options){ - this.options = options ||{locator:{}}; -} - -DOMParser.prototype.parseFromString = function(source,mimeType){ - var options = this.options; - var sax = new XMLReader(); - var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler - var errorHandler = options.errorHandler; - var locator = options.locator; - var defaultNSMap = options.xmlns||{}; - var isHTML = /\/x?html?$/.test(mimeType);//mimeType.toLowerCase().indexOf('html') > -1; - var entityMap = isHTML ? entities.HTML_ENTITIES : entities.XML_ENTITIES; - if(locator){ - domBuilder.setDocumentLocator(locator) - } - - sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator); - sax.domBuilder = options.domBuilder || domBuilder; - if(isHTML){ - defaultNSMap[''] = NAMESPACE.HTML; - } - defaultNSMap.xml = defaultNSMap.xml || NAMESPACE.XML; - var normalize = options.normalizeLineEndings || normalizeLineEndings; - if (source && typeof source === 'string') { - sax.parse( - normalize(source), - defaultNSMap, - entityMap - ) - } else { - sax.errorHandler.error('invalid doc source') - } - return domBuilder.doc; -} -function buildErrorHandler(errorImpl,domBuilder,locator){ - if(!errorImpl){ - if(domBuilder instanceof DOMHandler){ - return domBuilder; - } - errorImpl = domBuilder ; - } - var errorHandler = {} - var isCallback = errorImpl instanceof Function; - locator = locator||{} - function build(key){ - var fn = errorImpl[key]; - if(!fn && isCallback){ - fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl; - } - errorHandler[key] = fn && function(msg){ - fn('[xmldom '+key+']\t'+msg+_locator(locator)); - }||function(){}; - } - build('warning'); - build('error'); - build('fatalError'); - return errorHandler; -} - -//console.log('#\n\n\n\n\n\n\n####') -/** - * +ContentHandler+ErrorHandler - * +LexicalHandler+EntityResolver2 - * -DeclHandler-DTDHandler - * - * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler - * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2 - * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html - */ -function DOMHandler() { - this.cdata = false; -} -function position(locator,node){ - node.lineNumber = locator.lineNumber; - node.columnNumber = locator.columnNumber; -} -/** - * @see org.xml.sax.ContentHandler#startDocument - * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html - */ -DOMHandler.prototype = { - startDocument : function() { - this.doc = new DOMImplementation().createDocument(null, null, null); - if (this.locator) { - this.doc.documentURI = this.locator.systemId; - } - }, - startElement:function(namespaceURI, localName, qName, attrs) { - var doc = this.doc; - var el = doc.createElementNS(namespaceURI, qName||localName); - var len = attrs.length; - appendElement(this, el); - this.currentElement = el; - - this.locator && position(this.locator,el) - for (var i = 0 ; i < len; i++) { - var namespaceURI = attrs.getURI(i); - var value = attrs.getValue(i); - var qName = attrs.getQName(i); - var attr = doc.createAttributeNS(namespaceURI, qName); - this.locator &&position(attrs.getLocator(i),attr); - attr.value = attr.nodeValue = value; - el.setAttributeNode(attr) - } - }, - endElement:function(namespaceURI, localName, qName) { - var current = this.currentElement - var tagName = current.tagName; - this.currentElement = current.parentNode; - }, - startPrefixMapping:function(prefix, uri) { - }, - endPrefixMapping:function(prefix) { - }, - processingInstruction:function(target, data) { - var ins = this.doc.createProcessingInstruction(target, data); - this.locator && position(this.locator,ins) - appendElement(this, ins); - }, - ignorableWhitespace:function(ch, start, length) { - }, - characters:function(chars, start, length) { - chars = _toString.apply(this,arguments) - //console.log(chars) - if(chars){ - if (this.cdata) { - var charNode = this.doc.createCDATASection(chars); - } else { - var charNode = this.doc.createTextNode(chars); - } - if(this.currentElement){ - this.currentElement.appendChild(charNode); - }else if(/^\s*$/.test(chars)){ - this.doc.appendChild(charNode); - //process xml - } - this.locator && position(this.locator,charNode) - } - }, - skippedEntity:function(name) { - }, - endDocument:function() { - this.doc.normalize(); - }, - setDocumentLocator:function (locator) { - if(this.locator = locator){// && !('lineNumber' in locator)){ - locator.lineNumber = 0; - } - }, - //LexicalHandler - comment:function(chars, start, length) { - chars = _toString.apply(this,arguments) - var comm = this.doc.createComment(chars); - this.locator && position(this.locator,comm) - appendElement(this, comm); - }, - - startCDATA:function() { - //used in characters() methods - this.cdata = true; - }, - endCDATA:function() { - this.cdata = false; - }, - - startDTD:function(name, publicId, systemId) { - var impl = this.doc.implementation; - if (impl && impl.createDocumentType) { - var dt = impl.createDocumentType(name, publicId, systemId); - this.locator && position(this.locator,dt) - appendElement(this, dt); - this.doc.doctype = dt; - } - }, - /** - * @see org.xml.sax.ErrorHandler - * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html - */ - warning:function(error) { - console.warn('[xmldom warning]\t'+error,_locator(this.locator)); - }, - error:function(error) { - console.error('[xmldom error]\t'+error,_locator(this.locator)); - }, - fatalError:function(error) { - throw new ParseError(error, this.locator); - } -} -function _locator(l){ - if(l){ - return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']' - } -} -function _toString(chars,start,length){ - if(typeof chars == 'string'){ - return chars.substr(start,length) - }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)") - if(chars.length >= start+length || start){ - return new java.lang.String(chars,start,length)+''; - } - return chars; - } -} - -/* - * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html - * used method of org.xml.sax.ext.LexicalHandler: - * #comment(chars, start, length) - * #startCDATA() - * #endCDATA() - * #startDTD(name, publicId, systemId) - * - * - * IGNORED method of org.xml.sax.ext.LexicalHandler: - * #endDTD() - * #startEntity(name) - * #endEntity(name) - * - * - * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html - * IGNORED method of org.xml.sax.ext.DeclHandler - * #attributeDecl(eName, aName, type, mode, value) - * #elementDecl(name, model) - * #externalEntityDecl(name, publicId, systemId) - * #internalEntityDecl(name, value) - * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html - * IGNORED method of org.xml.sax.EntityResolver2 - * #resolveEntity(String name,String publicId,String baseURI,String systemId) - * #resolveEntity(publicId, systemId) - * #getExternalSubset(name, baseURI) - * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html - * IGNORED method of org.xml.sax.DTDHandler - * #notationDecl(name, publicId, systemId) {}; - * #unparsedEntityDecl(name, publicId, systemId, notationName) {}; - */ -"endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){ - DOMHandler.prototype[key] = function(){return null} -}) - -/* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */ -function appendElement (hander,node) { - if (!hander.currentElement) { - hander.doc.appendChild(node); - } else { - hander.currentElement.appendChild(node); - } -}//appendChild and setAttributeNS are preformance key - -exports.__DOMHandler = DOMHandler; -exports.normalizeLineEndings = normalizeLineEndings; -exports.DOMParser = DOMParser; diff --git a/claude-code-source/node_modules/@xmldom/xmldom/lib/dom.js b/claude-code-source/node_modules/@xmldom/xmldom/lib/dom.js deleted file mode 100644 index aaa745fe..00000000 --- a/claude-code-source/node_modules/@xmldom/xmldom/lib/dom.js +++ /dev/null @@ -1,1840 +0,0 @@ -var conventions = require("./conventions"); - -var find = conventions.find; -var NAMESPACE = conventions.NAMESPACE; - -/** - * A prerequisite for `[].filter`, to drop elements that are empty - * @param {string} input - * @returns {boolean} - */ -function notEmptyString (input) { - return input !== '' -} -/** - * @see https://infra.spec.whatwg.org/#split-on-ascii-whitespace - * @see https://infra.spec.whatwg.org/#ascii-whitespace - * - * @param {string} input - * @returns {string[]} (can be empty) - */ -function splitOnASCIIWhitespace(input) { - // U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, U+0020 SPACE - return input ? input.split(/[\t\n\f\r ]+/).filter(notEmptyString) : [] -} - -/** - * Adds element as a key to current if it is not already present. - * - * @param {Record} current - * @param {string} element - * @returns {Record} - */ -function orderedSetReducer (current, element) { - if (!current.hasOwnProperty(element)) { - current[element] = true; - } - return current; -} - -/** - * @see https://infra.spec.whatwg.org/#ordered-set - * @param {string} input - * @returns {string[]} - */ -function toOrderedSet(input) { - if (!input) return []; - var list = splitOnASCIIWhitespace(input); - return Object.keys(list.reduce(orderedSetReducer, {})) -} - -/** - * Uses `list.indexOf` to implement something like `Array.prototype.includes`, - * which we can not rely on being available. - * - * @param {any[]} list - * @returns {function(any): boolean} - */ -function arrayIncludes (list) { - return function(element) { - return list && list.indexOf(element) !== -1; - } -} - -function copy(src,dest){ - for(var p in src){ - if (Object.prototype.hasOwnProperty.call(src, p)) { - dest[p] = src[p]; - } - } -} - -/** -^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));? -^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));? - */ -function _extends(Class,Super){ - var pt = Class.prototype; - if(!(pt instanceof Super)){ - function t(){}; - t.prototype = Super.prototype; - t = new t(); - copy(pt,t); - Class.prototype = pt = t; - } - if(pt.constructor != Class){ - if(typeof Class != 'function'){ - console.error("unknown Class:"+Class) - } - pt.constructor = Class - } -} - -// Node Types -var NodeType = {} -var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1; -var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2; -var TEXT_NODE = NodeType.TEXT_NODE = 3; -var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4; -var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5; -var ENTITY_NODE = NodeType.ENTITY_NODE = 6; -var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7; -var COMMENT_NODE = NodeType.COMMENT_NODE = 8; -var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9; -var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10; -var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11; -var NOTATION_NODE = NodeType.NOTATION_NODE = 12; - -// ExceptionCode -var ExceptionCode = {} -var ExceptionMessage = {}; -var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1); -var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2); -var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3); -var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4); -var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5); -var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6); -var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7); -var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8); -var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9); -var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10); -//level2 -var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11); -var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12); -var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13); -var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14); -var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15); - -/** - * DOM Level 2 - * Object DOMException - * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html - * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html - */ -function DOMException(code, message) { - if(message instanceof Error){ - var error = message; - }else{ - error = this; - Error.call(this, ExceptionMessage[code]); - this.message = ExceptionMessage[code]; - if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException); - } - error.code = code; - if(message) this.message = this.message + ": " + message; - return error; -}; -DOMException.prototype = Error.prototype; -copy(ExceptionCode,DOMException) - -/** - * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177 - * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live. - * The items in the NodeList are accessible via an integral index, starting from 0. - */ -function NodeList() { -}; -NodeList.prototype = { - /** - * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive. - * @standard level1 - */ - length:0, - /** - * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null. - * @standard level1 - * @param index unsigned long - * Index into the collection. - * @return Node - * The node at the indexth position in the NodeList, or null if that is not a valid index. - */ - item: function(index) { - return index >= 0 && index < this.length ? this[index] : null; - }, - toString:function(isHTML,nodeFilter){ - for(var buf = [], i = 0;i=0){ - var lastIndex = list.length-1 - while(i0 || key == 'xmlns'){ -// return null; -// } - //console.log() - var i = this.length; - while(i--){ - var attr = this[i]; - //console.log(attr.nodeName,key) - if(attr.nodeName == key){ - return attr; - } - } - }, - setNamedItem: function(attr) { - var el = attr.ownerElement; - if(el && el!=this._ownerElement){ - throw new DOMException(INUSE_ATTRIBUTE_ERR); - } - var oldAttr = this.getNamedItem(attr.nodeName); - _addNamedNode(this._ownerElement,this,attr,oldAttr); - return oldAttr; - }, - /* returns Node */ - setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR - var el = attr.ownerElement, oldAttr; - if(el && el!=this._ownerElement){ - throw new DOMException(INUSE_ATTRIBUTE_ERR); - } - oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName); - _addNamedNode(this._ownerElement,this,attr,oldAttr); - return oldAttr; - }, - - /* returns Node */ - removeNamedItem: function(key) { - var attr = this.getNamedItem(key); - _removeNamedNode(this._ownerElement,this,attr); - return attr; - - - },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR - - //for level2 - removeNamedItemNS:function(namespaceURI,localName){ - var attr = this.getNamedItemNS(namespaceURI,localName); - _removeNamedNode(this._ownerElement,this,attr); - return attr; - }, - getNamedItemNS: function(namespaceURI, localName) { - var i = this.length; - while(i--){ - var node = this[i]; - if(node.localName == localName && node.namespaceURI == namespaceURI){ - return node; - } - } - return null; - } -}; - -/** - * The DOMImplementation interface represents an object providing methods - * which are not dependent on any particular document. - * Such an object is returned by the `Document.implementation` property. - * - * __The individual methods describe the differences compared to the specs.__ - * - * @constructor - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation MDN - * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490 DOM Level 1 Core (Initial) - * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-102161490 DOM Level 2 Core - * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-102161490 DOM Level 3 Core - * @see https://dom.spec.whatwg.org/#domimplementation DOM Living Standard - */ -function DOMImplementation() { -} - -DOMImplementation.prototype = { - /** - * The DOMImplementation.hasFeature() method returns a Boolean flag indicating if a given feature is supported. - * The different implementations fairly diverged in what kind of features were reported. - * The latest version of the spec settled to force this method to always return true, where the functionality was accurate and in use. - * - * @deprecated It is deprecated and modern browsers return true in all cases. - * - * @param {string} feature - * @param {string} [version] - * @returns {boolean} always true - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/hasFeature MDN - * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-5CED94D7 DOM Level 1 Core - * @see https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature DOM Living Standard - */ - hasFeature: function(feature, version) { - return true; - }, - /** - * Creates an XML Document object of the specified type with its document element. - * - * __It behaves slightly different from the description in the living standard__: - * - There is no interface/class `XMLDocument`, it returns a `Document` instance. - * - `contentType`, `encoding`, `mode`, `origin`, `url` fields are currently not declared. - * - this implementation is not validating names or qualified names - * (when parsing XML strings, the SAX parser takes care of that) - * - * @param {string|null} namespaceURI - * @param {string} qualifiedName - * @param {DocumentType=null} doctype - * @returns {Document} - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument MDN - * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocument DOM Level 2 Core (initial) - * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument DOM Level 2 Core - * - * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract - * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names - * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names - */ - createDocument: function(namespaceURI, qualifiedName, doctype){ - var doc = new Document(); - doc.implementation = this; - doc.childNodes = new NodeList(); - doc.doctype = doctype || null; - if (doctype){ - doc.appendChild(doctype); - } - if (qualifiedName){ - var root = doc.createElementNS(namespaceURI, qualifiedName); - doc.appendChild(root); - } - return doc; - }, - /** - * Returns a doctype, with the given `qualifiedName`, `publicId`, and `systemId`. - * - * __This behavior is slightly different from the in the specs__: - * - this implementation is not validating names or qualified names - * (when parsing XML strings, the SAX parser takes care of that) - * - * @param {string} qualifiedName - * @param {string} [publicId] - * @param {string} [systemId] - * @returns {DocumentType} which can either be used with `DOMImplementation.createDocument` upon document creation - * or can be put into the document via methods like `Node.insertBefore()` or `Node.replaceChild()` - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocumentType MDN - * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocType DOM Level 2 Core - * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype DOM Living Standard - * - * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract - * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names - * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names - */ - createDocumentType: function(qualifiedName, publicId, systemId){ - var node = new DocumentType(); - node.name = qualifiedName; - node.nodeName = qualifiedName; - node.publicId = publicId || ''; - node.systemId = systemId || ''; - - return node; - } -}; - - -/** - * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247 - */ - -function Node() { -}; - -Node.prototype = { - firstChild : null, - lastChild : null, - previousSibling : null, - nextSibling : null, - attributes : null, - parentNode : null, - childNodes : null, - ownerDocument : null, - nodeValue : null, - namespaceURI : null, - prefix : null, - localName : null, - // Modified in DOM Level 2: - insertBefore:function(newChild, refChild){//raises - return _insertBefore(this,newChild,refChild); - }, - replaceChild:function(newChild, oldChild){//raises - _insertBefore(this, newChild,oldChild, assertPreReplacementValidityInDocument); - if(oldChild){ - this.removeChild(oldChild); - } - }, - removeChild:function(oldChild){ - return _removeChild(this,oldChild); - }, - appendChild:function(newChild){ - return this.insertBefore(newChild,null); - }, - hasChildNodes:function(){ - return this.firstChild != null; - }, - cloneNode:function(deep){ - return cloneNode(this.ownerDocument||this,this,deep); - }, - // Modified in DOM Level 2: - normalize:function(){ - var child = this.firstChild; - while(child){ - var next = child.nextSibling; - if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){ - this.removeChild(next); - child.appendData(next.data); - }else{ - child.normalize(); - child = next; - } - } - }, - // Introduced in DOM Level 2: - isSupported:function(feature, version){ - return this.ownerDocument.implementation.hasFeature(feature,version); - }, - // Introduced in DOM Level 2: - hasAttributes:function(){ - return this.attributes.length>0; - }, - /** - * Look up the prefix associated to the given namespace URI, starting from this node. - * **The default namespace declarations are ignored by this method.** - * See Namespace Prefix Lookup for details on the algorithm used by this method. - * - * _Note: The implementation seems to be incomplete when compared to the algorithm described in the specs._ - * - * @param {string | null} namespaceURI - * @returns {string | null} - * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespacePrefix - * @see https://www.w3.org/TR/DOM-Level-3-Core/namespaces-algorithms.html#lookupNamespacePrefixAlgo - * @see https://dom.spec.whatwg.org/#dom-node-lookupprefix - * @see https://github.com/xmldom/xmldom/issues/322 - */ - lookupPrefix:function(namespaceURI){ - var el = this; - while(el){ - var map = el._nsMap; - //console.dir(map) - if(map){ - for(var n in map){ - if (Object.prototype.hasOwnProperty.call(map, n) && map[n] === namespaceURI) { - return n; - } - } - } - el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode; - } - return null; - }, - // Introduced in DOM Level 3: - lookupNamespaceURI:function(prefix){ - var el = this; - while(el){ - var map = el._nsMap; - //console.dir(map) - if(map){ - if(Object.prototype.hasOwnProperty.call(map, prefix)){ - return map[prefix] ; - } - } - el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode; - } - return null; - }, - // Introduced in DOM Level 3: - isDefaultNamespace:function(namespaceURI){ - var prefix = this.lookupPrefix(namespaceURI); - return prefix == null; - } -}; - - -function _xmlEncoder(c){ - return c == '<' && '<' || - c == '>' && '>' || - c == '&' && '&' || - c == '"' && '"' || - '&#'+c.charCodeAt()+';' -} - - -copy(NodeType,Node); -copy(NodeType,Node.prototype); - -/** - * @param callback return true for continue,false for break - * @return boolean true: break visit; - */ -function _visitNode(node,callback){ - if(callback(node)){ - return true; - } - if(node = node.firstChild){ - do{ - if(_visitNode(node,callback)){return true} - }while(node=node.nextSibling) - } -} - - - -function Document(){ - this.ownerDocument = this; -} - -function _onAddAttribute(doc,el,newAttr){ - doc && doc._inc++; - var ns = newAttr.namespaceURI ; - if(ns === NAMESPACE.XMLNS){ - //update namespace - el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value - } -} - -function _onRemoveAttribute(doc,el,newAttr,remove){ - doc && doc._inc++; - var ns = newAttr.namespaceURI ; - if(ns === NAMESPACE.XMLNS){ - //update namespace - delete el._nsMap[newAttr.prefix?newAttr.localName:''] - } -} - -/** - * Updates `el.childNodes`, updating the indexed items and it's `length`. - * Passing `newChild` means it will be appended. - * Otherwise it's assumed that an item has been removed, - * and `el.firstNode` and it's `.nextSibling` are used - * to walk the current list of child nodes. - * - * @param {Document} doc - * @param {Node} el - * @param {Node} [newChild] - * @private - */ -function _onUpdateChild (doc, el, newChild) { - if(doc && doc._inc){ - doc._inc++; - //update childNodes - var cs = el.childNodes; - if (newChild) { - cs[cs.length++] = newChild; - } else { - var child = el.firstChild; - var i = 0; - while (child) { - cs[i++] = child; - child = child.nextSibling; - } - cs.length = i; - delete cs[cs.length]; - } - } -} - -/** - * Removes the connections between `parentNode` and `child` - * and any existing `child.previousSibling` or `child.nextSibling`. - * - * @see https://github.com/xmldom/xmldom/issues/135 - * @see https://github.com/xmldom/xmldom/issues/145 - * - * @param {Node} parentNode - * @param {Node} child - * @returns {Node} the child that was removed. - * @private - */ -function _removeChild (parentNode, child) { - var previous = child.previousSibling; - var next = child.nextSibling; - if (previous) { - previous.nextSibling = next; - } else { - parentNode.firstChild = next; - } - if (next) { - next.previousSibling = previous; - } else { - parentNode.lastChild = previous; - } - child.parentNode = null; - child.previousSibling = null; - child.nextSibling = null; - _onUpdateChild(parentNode.ownerDocument, parentNode); - return child; -} - -/** - * Returns `true` if `node` can be a parent for insertion. - * @param {Node} node - * @returns {boolean} - */ -function hasValidParentNodeType(node) { - return ( - node && - (node.nodeType === Node.DOCUMENT_NODE || node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || node.nodeType === Node.ELEMENT_NODE) - ); -} - -/** - * Returns `true` if `node` can be inserted according to it's `nodeType`. - * @param {Node} node - * @returns {boolean} - */ -function hasInsertableNodeType(node) { - return ( - node && - (isElementNode(node) || - isTextNode(node) || - isDocTypeNode(node) || - node.nodeType === Node.DOCUMENT_FRAGMENT_NODE || - node.nodeType === Node.COMMENT_NODE || - node.nodeType === Node.PROCESSING_INSTRUCTION_NODE) - ); -} - -/** - * Returns true if `node` is a DOCTYPE node - * @param {Node} node - * @returns {boolean} - */ -function isDocTypeNode(node) { - return node && node.nodeType === Node.DOCUMENT_TYPE_NODE; -} - -/** - * Returns true if the node is an element - * @param {Node} node - * @returns {boolean} - */ -function isElementNode(node) { - return node && node.nodeType === Node.ELEMENT_NODE; -} -/** - * Returns true if `node` is a text node - * @param {Node} node - * @returns {boolean} - */ -function isTextNode(node) { - return node && node.nodeType === Node.TEXT_NODE; -} - -/** - * Check if en element node can be inserted before `child`, or at the end if child is falsy, - * according to the presence and position of a doctype node on the same level. - * - * @param {Document} doc The document node - * @param {Node} child the node that would become the nextSibling if the element would be inserted - * @returns {boolean} `true` if an element can be inserted before child - * @private - * https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity - */ -function isElementInsertionPossible(doc, child) { - var parentChildNodes = doc.childNodes || []; - if (find(parentChildNodes, isElementNode) || isDocTypeNode(child)) { - return false; - } - var docTypeNode = find(parentChildNodes, isDocTypeNode); - return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child)); -} - -/** - * Check if en element node can be inserted before `child`, or at the end if child is falsy, - * according to the presence and position of a doctype node on the same level. - * - * @param {Node} doc The document node - * @param {Node} child the node that would become the nextSibling if the element would be inserted - * @returns {boolean} `true` if an element can be inserted before child - * @private - * https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity - */ -function isElementReplacementPossible(doc, child) { - var parentChildNodes = doc.childNodes || []; - - function hasElementChildThatIsNotChild(node) { - return isElementNode(node) && node !== child; - } - - if (find(parentChildNodes, hasElementChildThatIsNotChild)) { - return false; - } - var docTypeNode = find(parentChildNodes, isDocTypeNode); - return !(child && docTypeNode && parentChildNodes.indexOf(docTypeNode) > parentChildNodes.indexOf(child)); -} - -/** - * @private - * Steps 1-5 of the checks before inserting and before replacing a child are the same. - * - * @param {Node} parent the parent node to insert `node` into - * @param {Node} node the node to insert - * @param {Node=} child the node that should become the `nextSibling` of `node` - * @returns {Node} - * @throws DOMException for several node combinations that would create a DOM that is not well-formed. - * @throws DOMException if `child` is provided but is not a child of `parent`. - * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity - * @see https://dom.spec.whatwg.org/#concept-node-replace - */ -function assertPreInsertionValidity1to5(parent, node, child) { - // 1. If `parent` is not a Document, DocumentFragment, or Element node, then throw a "HierarchyRequestError" DOMException. - if (!hasValidParentNodeType(parent)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'Unexpected parent node type ' + parent.nodeType); - } - // 2. If `node` is a host-including inclusive ancestor of `parent`, then throw a "HierarchyRequestError" DOMException. - // not implemented! - // 3. If `child` is non-null and its parent is not `parent`, then throw a "NotFoundError" DOMException. - if (child && child.parentNode !== parent) { - throw new DOMException(NOT_FOUND_ERR, 'child not in parent'); - } - if ( - // 4. If `node` is not a DocumentFragment, DocumentType, Element, or CharacterData node, then throw a "HierarchyRequestError" DOMException. - !hasInsertableNodeType(node) || - // 5. If either `node` is a Text node and `parent` is a document, - // the sax parser currently adds top level text nodes, this will be fixed in 0.9.0 - // || (node.nodeType === Node.TEXT_NODE && parent.nodeType === Node.DOCUMENT_NODE) - // or `node` is a doctype and `parent` is not a document, then throw a "HierarchyRequestError" DOMException. - (isDocTypeNode(node) && parent.nodeType !== Node.DOCUMENT_NODE) - ) { - throw new DOMException( - HIERARCHY_REQUEST_ERR, - 'Unexpected node type ' + node.nodeType + ' for parent node type ' + parent.nodeType - ); - } -} - -/** - * @private - * Step 6 of the checks before inserting and before replacing a child are different. - * - * @param {Document} parent the parent node to insert `node` into - * @param {Node} node the node to insert - * @param {Node | undefined} child the node that should become the `nextSibling` of `node` - * @returns {Node} - * @throws DOMException for several node combinations that would create a DOM that is not well-formed. - * @throws DOMException if `child` is provided but is not a child of `parent`. - * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity - * @see https://dom.spec.whatwg.org/#concept-node-replace - */ -function assertPreInsertionValidityInDocument(parent, node, child) { - var parentChildNodes = parent.childNodes || []; - var nodeChildNodes = node.childNodes || []; - - // DocumentFragment - if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { - var nodeChildElements = nodeChildNodes.filter(isElementNode); - // If node has more than one element child or has a Text node child. - if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'More than one element or text in fragment'); - } - // Otherwise, if `node` has one element child and either `parent` has an element child, - // `child` is a doctype, or `child` is non-null and a doctype is following `child`. - if (nodeChildElements.length === 1 && !isElementInsertionPossible(parent, child)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'Element in fragment can not be inserted before doctype'); - } - } - // Element - if (isElementNode(node)) { - // `parent` has an element child, `child` is a doctype, - // or `child` is non-null and a doctype is following `child`. - if (!isElementInsertionPossible(parent, child)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one element can be added and only after doctype'); - } - } - // DocumentType - if (isDocTypeNode(node)) { - // `parent` has a doctype child, - if (find(parentChildNodes, isDocTypeNode)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one doctype is allowed'); - } - var parentElementChild = find(parentChildNodes, isElementNode); - // `child` is non-null and an element is preceding `child`, - if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can only be inserted before an element'); - } - // or `child` is null and `parent` has an element child. - if (!child && parentElementChild) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can not be appended since element is present'); - } - } -} - -/** - * @private - * Step 6 of the checks before inserting and before replacing a child are different. - * - * @param {Document} parent the parent node to insert `node` into - * @param {Node} node the node to insert - * @param {Node | undefined} child the node that should become the `nextSibling` of `node` - * @returns {Node} - * @throws DOMException for several node combinations that would create a DOM that is not well-formed. - * @throws DOMException if `child` is provided but is not a child of `parent`. - * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity - * @see https://dom.spec.whatwg.org/#concept-node-replace - */ -function assertPreReplacementValidityInDocument(parent, node, child) { - var parentChildNodes = parent.childNodes || []; - var nodeChildNodes = node.childNodes || []; - - // DocumentFragment - if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { - var nodeChildElements = nodeChildNodes.filter(isElementNode); - // If `node` has more than one element child or has a Text node child. - if (nodeChildElements.length > 1 || find(nodeChildNodes, isTextNode)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'More than one element or text in fragment'); - } - // Otherwise, if `node` has one element child and either `parent` has an element child that is not `child` or a doctype is following `child`. - if (nodeChildElements.length === 1 && !isElementReplacementPossible(parent, child)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'Element in fragment can not be inserted before doctype'); - } - } - // Element - if (isElementNode(node)) { - // `parent` has an element child that is not `child` or a doctype is following `child`. - if (!isElementReplacementPossible(parent, child)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one element can be added and only after doctype'); - } - } - // DocumentType - if (isDocTypeNode(node)) { - function hasDoctypeChildThatIsNotChild(node) { - return isDocTypeNode(node) && node !== child; - } - - // `parent` has a doctype child that is not `child`, - if (find(parentChildNodes, hasDoctypeChildThatIsNotChild)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'Only one doctype is allowed'); - } - var parentElementChild = find(parentChildNodes, isElementNode); - // or an element is preceding `child`. - if (child && parentChildNodes.indexOf(parentElementChild) < parentChildNodes.indexOf(child)) { - throw new DOMException(HIERARCHY_REQUEST_ERR, 'Doctype can only be inserted before an element'); - } - } -} - -/** - * @private - * @param {Node} parent the parent node to insert `node` into - * @param {Node} node the node to insert - * @param {Node=} child the node that should become the `nextSibling` of `node` - * @returns {Node} - * @throws DOMException for several node combinations that would create a DOM that is not well-formed. - * @throws DOMException if `child` is provided but is not a child of `parent`. - * @see https://dom.spec.whatwg.org/#concept-node-ensure-pre-insertion-validity - */ -function _insertBefore(parent, node, child, _inDocumentAssertion) { - // To ensure pre-insertion validity of a node into a parent before a child, run these steps: - assertPreInsertionValidity1to5(parent, node, child); - - // If parent is a document, and any of the statements below, switched on the interface node implements, - // are true, then throw a "HierarchyRequestError" DOMException. - if (parent.nodeType === Node.DOCUMENT_NODE) { - (_inDocumentAssertion || assertPreInsertionValidityInDocument)(parent, node, child); - } - - var cp = node.parentNode; - if(cp){ - cp.removeChild(node);//remove and update - } - if(node.nodeType === DOCUMENT_FRAGMENT_NODE){ - var newFirst = node.firstChild; - if (newFirst == null) { - return node; - } - var newLast = node.lastChild; - }else{ - newFirst = newLast = node; - } - var pre = child ? child.previousSibling : parent.lastChild; - - newFirst.previousSibling = pre; - newLast.nextSibling = child; - - - if(pre){ - pre.nextSibling = newFirst; - }else{ - parent.firstChild = newFirst; - } - if(child == null){ - parent.lastChild = newLast; - }else{ - child.previousSibling = newLast; - } - do{ - newFirst.parentNode = parent; - }while(newFirst !== newLast && (newFirst= newFirst.nextSibling)) - _onUpdateChild(parent.ownerDocument||parent, parent); - //console.log(parent.lastChild.nextSibling == null) - if (node.nodeType == DOCUMENT_FRAGMENT_NODE) { - node.firstChild = node.lastChild = null; - } - return node; -} - -/** - * Appends `newChild` to `parentNode`. - * If `newChild` is already connected to a `parentNode` it is first removed from it. - * - * @see https://github.com/xmldom/xmldom/issues/135 - * @see https://github.com/xmldom/xmldom/issues/145 - * @param {Node} parentNode - * @param {Node} newChild - * @returns {Node} - * @private - */ -function _appendSingleChild (parentNode, newChild) { - if (newChild.parentNode) { - newChild.parentNode.removeChild(newChild); - } - newChild.parentNode = parentNode; - newChild.previousSibling = parentNode.lastChild; - newChild.nextSibling = null; - if (newChild.previousSibling) { - newChild.previousSibling.nextSibling = newChild; - } else { - parentNode.firstChild = newChild; - } - parentNode.lastChild = newChild; - _onUpdateChild(parentNode.ownerDocument, parentNode, newChild); - return newChild; -} - -Document.prototype = { - //implementation : null, - nodeName : '#document', - nodeType : DOCUMENT_NODE, - /** - * The DocumentType node of the document. - * - * @readonly - * @type DocumentType - */ - doctype : null, - documentElement : null, - _inc : 1, - - insertBefore : function(newChild, refChild){//raises - if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){ - var child = newChild.firstChild; - while(child){ - var next = child.nextSibling; - this.insertBefore(child,refChild); - child = next; - } - return newChild; - } - _insertBefore(this, newChild, refChild); - newChild.ownerDocument = this; - if (this.documentElement === null && newChild.nodeType === ELEMENT_NODE) { - this.documentElement = newChild; - } - - return newChild; - }, - removeChild : function(oldChild){ - if(this.documentElement == oldChild){ - this.documentElement = null; - } - return _removeChild(this,oldChild); - }, - replaceChild: function (newChild, oldChild) { - //raises - _insertBefore(this, newChild, oldChild, assertPreReplacementValidityInDocument); - newChild.ownerDocument = this; - if (oldChild) { - this.removeChild(oldChild); - } - if (isElementNode(newChild)) { - this.documentElement = newChild; - } - }, - // Introduced in DOM Level 2: - importNode : function(importedNode,deep){ - return importNode(this,importedNode,deep); - }, - // Introduced in DOM Level 2: - getElementById : function(id){ - var rtv = null; - _visitNode(this.documentElement,function(node){ - if(node.nodeType == ELEMENT_NODE){ - if(node.getAttribute('id') == id){ - rtv = node; - return true; - } - } - }) - return rtv; - }, - - /** - * The `getElementsByClassName` method of `Document` interface returns an array-like object - * of all child elements which have **all** of the given class name(s). - * - * Returns an empty list if `classeNames` is an empty string or only contains HTML white space characters. - * - * - * Warning: This is a live LiveNodeList. - * Changes in the DOM will reflect in the array as the changes occur. - * If an element selected by this array no longer qualifies for the selector, - * it will automatically be removed. Be aware of this for iteration purposes. - * - * @param {string} classNames is a string representing the class name(s) to match; multiple class names are separated by (ASCII-)whitespace - * - * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName - * @see https://dom.spec.whatwg.org/#concept-getelementsbyclassname - */ - getElementsByClassName: function(classNames) { - var classNamesSet = toOrderedSet(classNames) - return new LiveNodeList(this, function(base) { - var ls = []; - if (classNamesSet.length > 0) { - _visitNode(base.documentElement, function(node) { - if(node !== base && node.nodeType === ELEMENT_NODE) { - var nodeClassNames = node.getAttribute('class') - // can be null if the attribute does not exist - if (nodeClassNames) { - // before splitting and iterating just compare them for the most common case - var matches = classNames === nodeClassNames; - if (!matches) { - var nodeClassNamesSet = toOrderedSet(nodeClassNames) - matches = classNamesSet.every(arrayIncludes(nodeClassNamesSet)) - } - if(matches) { - ls.push(node); - } - } - } - }); - } - return ls; - }); - }, - - //document factory method: - createElement : function(tagName){ - var node = new Element(); - node.ownerDocument = this; - node.nodeName = tagName; - node.tagName = tagName; - node.localName = tagName; - node.childNodes = new NodeList(); - var attrs = node.attributes = new NamedNodeMap(); - attrs._ownerElement = node; - return node; - }, - createDocumentFragment : function(){ - var node = new DocumentFragment(); - node.ownerDocument = this; - node.childNodes = new NodeList(); - return node; - }, - createTextNode : function(data){ - var node = new Text(); - node.ownerDocument = this; - node.appendData(data) - return node; - }, - createComment : function(data){ - var node = new Comment(); - node.ownerDocument = this; - node.appendData(data) - return node; - }, - createCDATASection : function(data){ - var node = new CDATASection(); - node.ownerDocument = this; - node.appendData(data) - return node; - }, - createProcessingInstruction : function(target,data){ - var node = new ProcessingInstruction(); - node.ownerDocument = this; - node.tagName = node.nodeName = node.target = target; - node.nodeValue = node.data = data; - return node; - }, - createAttribute : function(name){ - var node = new Attr(); - node.ownerDocument = this; - node.name = name; - node.nodeName = name; - node.localName = name; - node.specified = true; - return node; - }, - createEntityReference : function(name){ - var node = new EntityReference(); - node.ownerDocument = this; - node.nodeName = name; - return node; - }, - // Introduced in DOM Level 2: - createElementNS : function(namespaceURI,qualifiedName){ - var node = new Element(); - var pl = qualifiedName.split(':'); - var attrs = node.attributes = new NamedNodeMap(); - node.childNodes = new NodeList(); - node.ownerDocument = this; - node.nodeName = qualifiedName; - node.tagName = qualifiedName; - node.namespaceURI = namespaceURI; - if(pl.length == 2){ - node.prefix = pl[0]; - node.localName = pl[1]; - }else{ - //el.prefix = null; - node.localName = qualifiedName; - } - attrs._ownerElement = node; - return node; - }, - // Introduced in DOM Level 2: - createAttributeNS : function(namespaceURI,qualifiedName){ - var node = new Attr(); - var pl = qualifiedName.split(':'); - node.ownerDocument = this; - node.nodeName = qualifiedName; - node.name = qualifiedName; - node.namespaceURI = namespaceURI; - node.specified = true; - if(pl.length == 2){ - node.prefix = pl[0]; - node.localName = pl[1]; - }else{ - //el.prefix = null; - node.localName = qualifiedName; - } - return node; - } -}; -_extends(Document,Node); - - -function Element() { - this._nsMap = {}; -}; -Element.prototype = { - nodeType : ELEMENT_NODE, - hasAttribute : function(name){ - return this.getAttributeNode(name)!=null; - }, - getAttribute : function(name){ - var attr = this.getAttributeNode(name); - return attr && attr.value || ''; - }, - getAttributeNode : function(name){ - return this.attributes.getNamedItem(name); - }, - setAttribute : function(name, value){ - var attr = this.ownerDocument.createAttribute(name); - attr.value = attr.nodeValue = "" + value; - this.setAttributeNode(attr) - }, - removeAttribute : function(name){ - var attr = this.getAttributeNode(name) - attr && this.removeAttributeNode(attr); - }, - - //four real opeartion method - appendChild:function(newChild){ - if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){ - return this.insertBefore(newChild,null); - }else{ - return _appendSingleChild(this,newChild); - } - }, - setAttributeNode : function(newAttr){ - return this.attributes.setNamedItem(newAttr); - }, - setAttributeNodeNS : function(newAttr){ - return this.attributes.setNamedItemNS(newAttr); - }, - removeAttributeNode : function(oldAttr){ - //console.log(this == oldAttr.ownerElement) - return this.attributes.removeNamedItem(oldAttr.nodeName); - }, - //get real attribute name,and remove it by removeAttributeNode - removeAttributeNS : function(namespaceURI, localName){ - var old = this.getAttributeNodeNS(namespaceURI, localName); - old && this.removeAttributeNode(old); - }, - - hasAttributeNS : function(namespaceURI, localName){ - return this.getAttributeNodeNS(namespaceURI, localName)!=null; - }, - getAttributeNS : function(namespaceURI, localName){ - var attr = this.getAttributeNodeNS(namespaceURI, localName); - return attr && attr.value || ''; - }, - setAttributeNS : function(namespaceURI, qualifiedName, value){ - var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName); - attr.value = attr.nodeValue = "" + value; - this.setAttributeNode(attr) - }, - getAttributeNodeNS : function(namespaceURI, localName){ - return this.attributes.getNamedItemNS(namespaceURI, localName); - }, - - getElementsByTagName : function(tagName){ - return new LiveNodeList(this,function(base){ - var ls = []; - _visitNode(base,function(node){ - if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){ - ls.push(node); - } - }); - return ls; - }); - }, - getElementsByTagNameNS : function(namespaceURI, localName){ - return new LiveNodeList(this,function(base){ - var ls = []; - _visitNode(base,function(node){ - if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){ - ls.push(node); - } - }); - return ls; - - }); - } -}; -Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName; -Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS; - - -_extends(Element,Node); -function Attr() { -}; -Attr.prototype.nodeType = ATTRIBUTE_NODE; -_extends(Attr,Node); - - -function CharacterData() { -}; -CharacterData.prototype = { - data : '', - substringData : function(offset, count) { - return this.data.substring(offset, offset+count); - }, - appendData: function(text) { - text = this.data+text; - this.nodeValue = this.data = text; - this.length = text.length; - }, - insertData: function(offset,text) { - this.replaceData(offset,0,text); - - }, - appendChild:function(newChild){ - throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR]) - }, - deleteData: function(offset, count) { - this.replaceData(offset,count,""); - }, - replaceData: function(offset, count, text) { - var start = this.data.substring(0,offset); - var end = this.data.substring(offset+count); - text = start + text + end; - this.nodeValue = this.data = text; - this.length = text.length; - } -} -_extends(CharacterData,Node); -function Text() { -}; -Text.prototype = { - nodeName : "#text", - nodeType : TEXT_NODE, - splitText : function(offset) { - var text = this.data; - var newText = text.substring(offset); - text = text.substring(0, offset); - this.data = this.nodeValue = text; - this.length = text.length; - var newNode = this.ownerDocument.createTextNode(newText); - if(this.parentNode){ - this.parentNode.insertBefore(newNode, this.nextSibling); - } - return newNode; - } -} -_extends(Text,CharacterData); -function Comment() { -}; -Comment.prototype = { - nodeName : "#comment", - nodeType : COMMENT_NODE -} -_extends(Comment,CharacterData); - -function CDATASection() { -}; -CDATASection.prototype = { - nodeName : "#cdata-section", - nodeType : CDATA_SECTION_NODE -} -_extends(CDATASection,CharacterData); - - -function DocumentType() { -}; -DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE; -_extends(DocumentType,Node); - -function Notation() { -}; -Notation.prototype.nodeType = NOTATION_NODE; -_extends(Notation,Node); - -function Entity() { -}; -Entity.prototype.nodeType = ENTITY_NODE; -_extends(Entity,Node); - -function EntityReference() { -}; -EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE; -_extends(EntityReference,Node); - -function DocumentFragment() { -}; -DocumentFragment.prototype.nodeName = "#document-fragment"; -DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE; -_extends(DocumentFragment,Node); - - -function ProcessingInstruction() { -} -ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE; -_extends(ProcessingInstruction,Node); -function XMLSerializer(){} -XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){ - return nodeSerializeToString.call(node,isHtml,nodeFilter); -} -Node.prototype.toString = nodeSerializeToString; -function nodeSerializeToString(isHtml,nodeFilter){ - var buf = []; - var refNode = this.nodeType == 9 && this.documentElement || this; - var prefix = refNode.prefix; - var uri = refNode.namespaceURI; - - if(uri && prefix == null){ - //console.log(prefix) - var prefix = refNode.lookupPrefix(uri); - if(prefix == null){ - //isHTML = true; - var visibleNamespaces=[ - {namespace:uri,prefix:null} - //{namespace:uri,prefix:''} - ] - } - } - serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces); - //console.log('###',this.nodeType,uri,prefix,buf.join('')) - return buf.join(''); -} - -function needNamespaceDefine(node, isHTML, visibleNamespaces) { - var prefix = node.prefix || ''; - var uri = node.namespaceURI; - // According to [Namespaces in XML 1.0](https://www.w3.org/TR/REC-xml-names/#ns-using) , - // and more specifically https://www.w3.org/TR/REC-xml-names/#nsc-NoPrefixUndecl : - // > In a namespace declaration for a prefix [...], the attribute value MUST NOT be empty. - // in a similar manner [Namespaces in XML 1.1](https://www.w3.org/TR/xml-names11/#ns-using) - // and more specifically https://www.w3.org/TR/xml-names11/#nsc-NSDeclared : - // > [...] Furthermore, the attribute value [...] must not be an empty string. - // so serializing empty namespace value like xmlns:ds="" would produce an invalid XML document. - if (!uri) { - return false; - } - if (prefix === "xml" && uri === NAMESPACE.XML || uri === NAMESPACE.XMLNS) { - return false; - } - - var i = visibleNamespaces.length - while (i--) { - var ns = visibleNamespaces[i]; - // get namespace prefix - if (ns.prefix === prefix) { - return ns.namespace !== uri; - } - } - return true; -} -/** - * Well-formed constraint: No < in Attribute Values - * > The replacement text of any entity referred to directly or indirectly - * > in an attribute value must not contain a <. - * @see https://www.w3.org/TR/xml11/#CleanAttrVals - * @see https://www.w3.org/TR/xml11/#NT-AttValue - * - * Literal whitespace other than space that appear in attribute values - * are serialized as their entity references, so they will be preserved. - * (In contrast to whitespace literals in the input which are normalized to spaces) - * @see https://www.w3.org/TR/xml11/#AVNormalize - * @see https://w3c.github.io/DOM-Parsing/#serializing-an-element-s-attributes - */ -function addSerializedAttribute(buf, qualifiedName, value) { - buf.push(' ', qualifiedName, '="', value.replace(/[<>&"\t\n\r]/g, _xmlEncoder), '"') -} - -function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){ - if (!visibleNamespaces) { - visibleNamespaces = []; - } - - if(nodeFilter){ - node = nodeFilter(node); - if(node){ - if(typeof node == 'string'){ - buf.push(node); - return; - } - }else{ - return; - } - //buf.sort.apply(attrs, attributeSorter); - } - - switch(node.nodeType){ - case ELEMENT_NODE: - var attrs = node.attributes; - var len = attrs.length; - var child = node.firstChild; - var nodeName = node.tagName; - - isHTML = NAMESPACE.isHTML(node.namespaceURI) || isHTML - - var prefixedNodeName = nodeName - if (!isHTML && !node.prefix && node.namespaceURI) { - var defaultNS - // lookup current default ns from `xmlns` attribute - for (var ai = 0; ai < attrs.length; ai++) { - if (attrs.item(ai).name === 'xmlns') { - defaultNS = attrs.item(ai).value - break - } - } - if (!defaultNS) { - // lookup current default ns in visibleNamespaces - for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) { - var namespace = visibleNamespaces[nsi] - if (namespace.prefix === '' && namespace.namespace === node.namespaceURI) { - defaultNS = namespace.namespace - break - } - } - } - if (defaultNS !== node.namespaceURI) { - for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) { - var namespace = visibleNamespaces[nsi] - if (namespace.namespace === node.namespaceURI) { - if (namespace.prefix) { - prefixedNodeName = namespace.prefix + ':' + nodeName - } - break - } - } - } - } - - buf.push('<', prefixedNodeName); - - for(var i=0;i'); - //if is cdata child node - if(isHTML && /^script$/i.test(nodeName)){ - while(child){ - if(child.data){ - buf.push(child.data); - }else{ - serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice()); - } - child = child.nextSibling; - } - }else - { - while(child){ - serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice()); - child = child.nextSibling; - } - } - buf.push(''); - }else{ - buf.push('/>'); - } - // remove added visible namespaces - //visibleNamespaces.length = startVisibleNamespaces; - return; - case DOCUMENT_NODE: - case DOCUMENT_FRAGMENT_NODE: - var child = node.firstChild; - while(child){ - serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice()); - child = child.nextSibling; - } - return; - case ATTRIBUTE_NODE: - return addSerializedAttribute(buf, node.name, node.value); - case TEXT_NODE: - /** - * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, - * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. - * If they are needed elsewhere, they must be escaped using either numeric character references or the strings - * `&` and `<` respectively. - * The right angle bracket (>) may be represented using the string " > ", and must, for compatibility, - * be escaped using either `>` or a character reference when it appears in the string `]]>` in content, - * when that string is not marking the end of a CDATA section. - * - * In the content of elements, character data is any string of characters - * which does not contain the start-delimiter of any markup - * and does not include the CDATA-section-close delimiter, `]]>`. - * - * @see https://www.w3.org/TR/xml/#NT-CharData - * @see https://w3c.github.io/DOM-Parsing/#xml-serializing-a-text-node - */ - return buf.push(node.data - .replace(/[<&>]/g,_xmlEncoder) - ); - case CDATA_SECTION_NODE: - return buf.push( ''); - case COMMENT_NODE: - return buf.push( ""); - case DOCUMENT_TYPE_NODE: - var pubid = node.publicId; - var sysid = node.systemId; - buf.push(''); - }else if(sysid && sysid!='.'){ - buf.push(' SYSTEM ', sysid, '>'); - }else{ - var sub = node.internalSubset; - if(sub){ - buf.push(" [",sub,"]"); - } - buf.push(">"); - } - return; - case PROCESSING_INSTRUCTION_NODE: - return buf.push( ""); - case ENTITY_REFERENCE_NODE: - return buf.push( '&',node.nodeName,';'); - //case ENTITY_NODE: - //case NOTATION_NODE: - default: - buf.push('??',node.nodeName); - } -} -function importNode(doc,node,deep){ - var node2; - switch (node.nodeType) { - case ELEMENT_NODE: - node2 = node.cloneNode(false); - node2.ownerDocument = doc; - //var attrs = node2.attributes; - //var len = attrs.length; - //for(var i=0;i', - lt: '<', - quot: '"', -}); - -/** - * A map of all entities that are detected in an HTML document. - * They contain all entries from `XML_ENTITIES`. - * - * @see XML_ENTITIES - * @see DOMParser.parseFromString - * @see DOMImplementation.prototype.createHTMLDocument - * @see https://html.spec.whatwg.org/#named-character-references WHATWG HTML(5) Spec - * @see https://html.spec.whatwg.org/entities.json JSON - * @see https://www.w3.org/TR/xml-entity-names/ W3C XML Entity Names - * @see https://www.w3.org/TR/html4/sgml/entities.html W3C HTML4/SGML - * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Character_entity_references_in_HTML Wikipedia (HTML) - * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Entities_representing_special_characters_in_XHTML Wikpedia (XHTML) - */ -exports.HTML_ENTITIES = freeze({ - Aacute: '\u00C1', - aacute: '\u00E1', - Abreve: '\u0102', - abreve: '\u0103', - ac: '\u223E', - acd: '\u223F', - acE: '\u223E\u0333', - Acirc: '\u00C2', - acirc: '\u00E2', - acute: '\u00B4', - Acy: '\u0410', - acy: '\u0430', - AElig: '\u00C6', - aelig: '\u00E6', - af: '\u2061', - Afr: '\uD835\uDD04', - afr: '\uD835\uDD1E', - Agrave: '\u00C0', - agrave: '\u00E0', - alefsym: '\u2135', - aleph: '\u2135', - Alpha: '\u0391', - alpha: '\u03B1', - Amacr: '\u0100', - amacr: '\u0101', - amalg: '\u2A3F', - AMP: '\u0026', - amp: '\u0026', - And: '\u2A53', - and: '\u2227', - andand: '\u2A55', - andd: '\u2A5C', - andslope: '\u2A58', - andv: '\u2A5A', - ang: '\u2220', - ange: '\u29A4', - angle: '\u2220', - angmsd: '\u2221', - angmsdaa: '\u29A8', - angmsdab: '\u29A9', - angmsdac: '\u29AA', - angmsdad: '\u29AB', - angmsdae: '\u29AC', - angmsdaf: '\u29AD', - angmsdag: '\u29AE', - angmsdah: '\u29AF', - angrt: '\u221F', - angrtvb: '\u22BE', - angrtvbd: '\u299D', - angsph: '\u2222', - angst: '\u00C5', - angzarr: '\u237C', - Aogon: '\u0104', - aogon: '\u0105', - Aopf: '\uD835\uDD38', - aopf: '\uD835\uDD52', - ap: '\u2248', - apacir: '\u2A6F', - apE: '\u2A70', - ape: '\u224A', - apid: '\u224B', - apos: '\u0027', - ApplyFunction: '\u2061', - approx: '\u2248', - approxeq: '\u224A', - Aring: '\u00C5', - aring: '\u00E5', - Ascr: '\uD835\uDC9C', - ascr: '\uD835\uDCB6', - Assign: '\u2254', - ast: '\u002A', - asymp: '\u2248', - asympeq: '\u224D', - Atilde: '\u00C3', - atilde: '\u00E3', - Auml: '\u00C4', - auml: '\u00E4', - awconint: '\u2233', - awint: '\u2A11', - backcong: '\u224C', - backepsilon: '\u03F6', - backprime: '\u2035', - backsim: '\u223D', - backsimeq: '\u22CD', - Backslash: '\u2216', - Barv: '\u2AE7', - barvee: '\u22BD', - Barwed: '\u2306', - barwed: '\u2305', - barwedge: '\u2305', - bbrk: '\u23B5', - bbrktbrk: '\u23B6', - bcong: '\u224C', - Bcy: '\u0411', - bcy: '\u0431', - bdquo: '\u201E', - becaus: '\u2235', - Because: '\u2235', - because: '\u2235', - bemptyv: '\u29B0', - bepsi: '\u03F6', - bernou: '\u212C', - Bernoullis: '\u212C', - Beta: '\u0392', - beta: '\u03B2', - beth: '\u2136', - between: '\u226C', - Bfr: '\uD835\uDD05', - bfr: '\uD835\uDD1F', - bigcap: '\u22C2', - bigcirc: '\u25EF', - bigcup: '\u22C3', - bigodot: '\u2A00', - bigoplus: '\u2A01', - bigotimes: '\u2A02', - bigsqcup: '\u2A06', - bigstar: '\u2605', - bigtriangledown: '\u25BD', - bigtriangleup: '\u25B3', - biguplus: '\u2A04', - bigvee: '\u22C1', - bigwedge: '\u22C0', - bkarow: '\u290D', - blacklozenge: '\u29EB', - blacksquare: '\u25AA', - blacktriangle: '\u25B4', - blacktriangledown: '\u25BE', - blacktriangleleft: '\u25C2', - blacktriangleright: '\u25B8', - blank: '\u2423', - blk12: '\u2592', - blk14: '\u2591', - blk34: '\u2593', - block: '\u2588', - bne: '\u003D\u20E5', - bnequiv: '\u2261\u20E5', - bNot: '\u2AED', - bnot: '\u2310', - Bopf: '\uD835\uDD39', - bopf: '\uD835\uDD53', - bot: '\u22A5', - bottom: '\u22A5', - bowtie: '\u22C8', - boxbox: '\u29C9', - boxDL: '\u2557', - boxDl: '\u2556', - boxdL: '\u2555', - boxdl: '\u2510', - boxDR: '\u2554', - boxDr: '\u2553', - boxdR: '\u2552', - boxdr: '\u250C', - boxH: '\u2550', - boxh: '\u2500', - boxHD: '\u2566', - boxHd: '\u2564', - boxhD: '\u2565', - boxhd: '\u252C', - boxHU: '\u2569', - boxHu: '\u2567', - boxhU: '\u2568', - boxhu: '\u2534', - boxminus: '\u229F', - boxplus: '\u229E', - boxtimes: '\u22A0', - boxUL: '\u255D', - boxUl: '\u255C', - boxuL: '\u255B', - boxul: '\u2518', - boxUR: '\u255A', - boxUr: '\u2559', - boxuR: '\u2558', - boxur: '\u2514', - boxV: '\u2551', - boxv: '\u2502', - boxVH: '\u256C', - boxVh: '\u256B', - boxvH: '\u256A', - boxvh: '\u253C', - boxVL: '\u2563', - boxVl: '\u2562', - boxvL: '\u2561', - boxvl: '\u2524', - boxVR: '\u2560', - boxVr: '\u255F', - boxvR: '\u255E', - boxvr: '\u251C', - bprime: '\u2035', - Breve: '\u02D8', - breve: '\u02D8', - brvbar: '\u00A6', - Bscr: '\u212C', - bscr: '\uD835\uDCB7', - bsemi: '\u204F', - bsim: '\u223D', - bsime: '\u22CD', - bsol: '\u005C', - bsolb: '\u29C5', - bsolhsub: '\u27C8', - bull: '\u2022', - bullet: '\u2022', - bump: '\u224E', - bumpE: '\u2AAE', - bumpe: '\u224F', - Bumpeq: '\u224E', - bumpeq: '\u224F', - Cacute: '\u0106', - cacute: '\u0107', - Cap: '\u22D2', - cap: '\u2229', - capand: '\u2A44', - capbrcup: '\u2A49', - capcap: '\u2A4B', - capcup: '\u2A47', - capdot: '\u2A40', - CapitalDifferentialD: '\u2145', - caps: '\u2229\uFE00', - caret: '\u2041', - caron: '\u02C7', - Cayleys: '\u212D', - ccaps: '\u2A4D', - Ccaron: '\u010C', - ccaron: '\u010D', - Ccedil: '\u00C7', - ccedil: '\u00E7', - Ccirc: '\u0108', - ccirc: '\u0109', - Cconint: '\u2230', - ccups: '\u2A4C', - ccupssm: '\u2A50', - Cdot: '\u010A', - cdot: '\u010B', - cedil: '\u00B8', - Cedilla: '\u00B8', - cemptyv: '\u29B2', - cent: '\u00A2', - CenterDot: '\u00B7', - centerdot: '\u00B7', - Cfr: '\u212D', - cfr: '\uD835\uDD20', - CHcy: '\u0427', - chcy: '\u0447', - check: '\u2713', - checkmark: '\u2713', - Chi: '\u03A7', - chi: '\u03C7', - cir: '\u25CB', - circ: '\u02C6', - circeq: '\u2257', - circlearrowleft: '\u21BA', - circlearrowright: '\u21BB', - circledast: '\u229B', - circledcirc: '\u229A', - circleddash: '\u229D', - CircleDot: '\u2299', - circledR: '\u00AE', - circledS: '\u24C8', - CircleMinus: '\u2296', - CirclePlus: '\u2295', - CircleTimes: '\u2297', - cirE: '\u29C3', - cire: '\u2257', - cirfnint: '\u2A10', - cirmid: '\u2AEF', - cirscir: '\u29C2', - ClockwiseContourIntegral: '\u2232', - CloseCurlyDoubleQuote: '\u201D', - CloseCurlyQuote: '\u2019', - clubs: '\u2663', - clubsuit: '\u2663', - Colon: '\u2237', - colon: '\u003A', - Colone: '\u2A74', - colone: '\u2254', - coloneq: '\u2254', - comma: '\u002C', - commat: '\u0040', - comp: '\u2201', - compfn: '\u2218', - complement: '\u2201', - complexes: '\u2102', - cong: '\u2245', - congdot: '\u2A6D', - Congruent: '\u2261', - Conint: '\u222F', - conint: '\u222E', - ContourIntegral: '\u222E', - Copf: '\u2102', - copf: '\uD835\uDD54', - coprod: '\u2210', - Coproduct: '\u2210', - COPY: '\u00A9', - copy: '\u00A9', - copysr: '\u2117', - CounterClockwiseContourIntegral: '\u2233', - crarr: '\u21B5', - Cross: '\u2A2F', - cross: '\u2717', - Cscr: '\uD835\uDC9E', - cscr: '\uD835\uDCB8', - csub: '\u2ACF', - csube: '\u2AD1', - csup: '\u2AD0', - csupe: '\u2AD2', - ctdot: '\u22EF', - cudarrl: '\u2938', - cudarrr: '\u2935', - cuepr: '\u22DE', - cuesc: '\u22DF', - cularr: '\u21B6', - cularrp: '\u293D', - Cup: '\u22D3', - cup: '\u222A', - cupbrcap: '\u2A48', - CupCap: '\u224D', - cupcap: '\u2A46', - cupcup: '\u2A4A', - cupdot: '\u228D', - cupor: '\u2A45', - cups: '\u222A\uFE00', - curarr: '\u21B7', - curarrm: '\u293C', - curlyeqprec: '\u22DE', - curlyeqsucc: '\u22DF', - curlyvee: '\u22CE', - curlywedge: '\u22CF', - curren: '\u00A4', - curvearrowleft: '\u21B6', - curvearrowright: '\u21B7', - cuvee: '\u22CE', - cuwed: '\u22CF', - cwconint: '\u2232', - cwint: '\u2231', - cylcty: '\u232D', - Dagger: '\u2021', - dagger: '\u2020', - daleth: '\u2138', - Darr: '\u21A1', - dArr: '\u21D3', - darr: '\u2193', - dash: '\u2010', - Dashv: '\u2AE4', - dashv: '\u22A3', - dbkarow: '\u290F', - dblac: '\u02DD', - Dcaron: '\u010E', - dcaron: '\u010F', - Dcy: '\u0414', - dcy: '\u0434', - DD: '\u2145', - dd: '\u2146', - ddagger: '\u2021', - ddarr: '\u21CA', - DDotrahd: '\u2911', - ddotseq: '\u2A77', - deg: '\u00B0', - Del: '\u2207', - Delta: '\u0394', - delta: '\u03B4', - demptyv: '\u29B1', - dfisht: '\u297F', - Dfr: '\uD835\uDD07', - dfr: '\uD835\uDD21', - dHar: '\u2965', - dharl: '\u21C3', - dharr: '\u21C2', - DiacriticalAcute: '\u00B4', - DiacriticalDot: '\u02D9', - DiacriticalDoubleAcute: '\u02DD', - DiacriticalGrave: '\u0060', - DiacriticalTilde: '\u02DC', - diam: '\u22C4', - Diamond: '\u22C4', - diamond: '\u22C4', - diamondsuit: '\u2666', - diams: '\u2666', - die: '\u00A8', - DifferentialD: '\u2146', - digamma: '\u03DD', - disin: '\u22F2', - div: '\u00F7', - divide: '\u00F7', - divideontimes: '\u22C7', - divonx: '\u22C7', - DJcy: '\u0402', - djcy: '\u0452', - dlcorn: '\u231E', - dlcrop: '\u230D', - dollar: '\u0024', - Dopf: '\uD835\uDD3B', - dopf: '\uD835\uDD55', - Dot: '\u00A8', - dot: '\u02D9', - DotDot: '\u20DC', - doteq: '\u2250', - doteqdot: '\u2251', - DotEqual: '\u2250', - dotminus: '\u2238', - dotplus: '\u2214', - dotsquare: '\u22A1', - doublebarwedge: '\u2306', - DoubleContourIntegral: '\u222F', - DoubleDot: '\u00A8', - DoubleDownArrow: '\u21D3', - DoubleLeftArrow: '\u21D0', - DoubleLeftRightArrow: '\u21D4', - DoubleLeftTee: '\u2AE4', - DoubleLongLeftArrow: '\u27F8', - DoubleLongLeftRightArrow: '\u27FA', - DoubleLongRightArrow: '\u27F9', - DoubleRightArrow: '\u21D2', - DoubleRightTee: '\u22A8', - DoubleUpArrow: '\u21D1', - DoubleUpDownArrow: '\u21D5', - DoubleVerticalBar: '\u2225', - DownArrow: '\u2193', - Downarrow: '\u21D3', - downarrow: '\u2193', - DownArrowBar: '\u2913', - DownArrowUpArrow: '\u21F5', - DownBreve: '\u0311', - downdownarrows: '\u21CA', - downharpoonleft: '\u21C3', - downharpoonright: '\u21C2', - DownLeftRightVector: '\u2950', - DownLeftTeeVector: '\u295E', - DownLeftVector: '\u21BD', - DownLeftVectorBar: '\u2956', - DownRightTeeVector: '\u295F', - DownRightVector: '\u21C1', - DownRightVectorBar: '\u2957', - DownTee: '\u22A4', - DownTeeArrow: '\u21A7', - drbkarow: '\u2910', - drcorn: '\u231F', - drcrop: '\u230C', - Dscr: '\uD835\uDC9F', - dscr: '\uD835\uDCB9', - DScy: '\u0405', - dscy: '\u0455', - dsol: '\u29F6', - Dstrok: '\u0110', - dstrok: '\u0111', - dtdot: '\u22F1', - dtri: '\u25BF', - dtrif: '\u25BE', - duarr: '\u21F5', - duhar: '\u296F', - dwangle: '\u29A6', - DZcy: '\u040F', - dzcy: '\u045F', - dzigrarr: '\u27FF', - Eacute: '\u00C9', - eacute: '\u00E9', - easter: '\u2A6E', - Ecaron: '\u011A', - ecaron: '\u011B', - ecir: '\u2256', - Ecirc: '\u00CA', - ecirc: '\u00EA', - ecolon: '\u2255', - Ecy: '\u042D', - ecy: '\u044D', - eDDot: '\u2A77', - Edot: '\u0116', - eDot: '\u2251', - edot: '\u0117', - ee: '\u2147', - efDot: '\u2252', - Efr: '\uD835\uDD08', - efr: '\uD835\uDD22', - eg: '\u2A9A', - Egrave: '\u00C8', - egrave: '\u00E8', - egs: '\u2A96', - egsdot: '\u2A98', - el: '\u2A99', - Element: '\u2208', - elinters: '\u23E7', - ell: '\u2113', - els: '\u2A95', - elsdot: '\u2A97', - Emacr: '\u0112', - emacr: '\u0113', - empty: '\u2205', - emptyset: '\u2205', - EmptySmallSquare: '\u25FB', - emptyv: '\u2205', - EmptyVerySmallSquare: '\u25AB', - emsp: '\u2003', - emsp13: '\u2004', - emsp14: '\u2005', - ENG: '\u014A', - eng: '\u014B', - ensp: '\u2002', - Eogon: '\u0118', - eogon: '\u0119', - Eopf: '\uD835\uDD3C', - eopf: '\uD835\uDD56', - epar: '\u22D5', - eparsl: '\u29E3', - eplus: '\u2A71', - epsi: '\u03B5', - Epsilon: '\u0395', - epsilon: '\u03B5', - epsiv: '\u03F5', - eqcirc: '\u2256', - eqcolon: '\u2255', - eqsim: '\u2242', - eqslantgtr: '\u2A96', - eqslantless: '\u2A95', - Equal: '\u2A75', - equals: '\u003D', - EqualTilde: '\u2242', - equest: '\u225F', - Equilibrium: '\u21CC', - equiv: '\u2261', - equivDD: '\u2A78', - eqvparsl: '\u29E5', - erarr: '\u2971', - erDot: '\u2253', - Escr: '\u2130', - escr: '\u212F', - esdot: '\u2250', - Esim: '\u2A73', - esim: '\u2242', - Eta: '\u0397', - eta: '\u03B7', - ETH: '\u00D0', - eth: '\u00F0', - Euml: '\u00CB', - euml: '\u00EB', - euro: '\u20AC', - excl: '\u0021', - exist: '\u2203', - Exists: '\u2203', - expectation: '\u2130', - ExponentialE: '\u2147', - exponentiale: '\u2147', - fallingdotseq: '\u2252', - Fcy: '\u0424', - fcy: '\u0444', - female: '\u2640', - ffilig: '\uFB03', - fflig: '\uFB00', - ffllig: '\uFB04', - Ffr: '\uD835\uDD09', - ffr: '\uD835\uDD23', - filig: '\uFB01', - FilledSmallSquare: '\u25FC', - FilledVerySmallSquare: '\u25AA', - fjlig: '\u0066\u006A', - flat: '\u266D', - fllig: '\uFB02', - fltns: '\u25B1', - fnof: '\u0192', - Fopf: '\uD835\uDD3D', - fopf: '\uD835\uDD57', - ForAll: '\u2200', - forall: '\u2200', - fork: '\u22D4', - forkv: '\u2AD9', - Fouriertrf: '\u2131', - fpartint: '\u2A0D', - frac12: '\u00BD', - frac13: '\u2153', - frac14: '\u00BC', - frac15: '\u2155', - frac16: '\u2159', - frac18: '\u215B', - frac23: '\u2154', - frac25: '\u2156', - frac34: '\u00BE', - frac35: '\u2157', - frac38: '\u215C', - frac45: '\u2158', - frac56: '\u215A', - frac58: '\u215D', - frac78: '\u215E', - frasl: '\u2044', - frown: '\u2322', - Fscr: '\u2131', - fscr: '\uD835\uDCBB', - gacute: '\u01F5', - Gamma: '\u0393', - gamma: '\u03B3', - Gammad: '\u03DC', - gammad: '\u03DD', - gap: '\u2A86', - Gbreve: '\u011E', - gbreve: '\u011F', - Gcedil: '\u0122', - Gcirc: '\u011C', - gcirc: '\u011D', - Gcy: '\u0413', - gcy: '\u0433', - Gdot: '\u0120', - gdot: '\u0121', - gE: '\u2267', - ge: '\u2265', - gEl: '\u2A8C', - gel: '\u22DB', - geq: '\u2265', - geqq: '\u2267', - geqslant: '\u2A7E', - ges: '\u2A7E', - gescc: '\u2AA9', - gesdot: '\u2A80', - gesdoto: '\u2A82', - gesdotol: '\u2A84', - gesl: '\u22DB\uFE00', - gesles: '\u2A94', - Gfr: '\uD835\uDD0A', - gfr: '\uD835\uDD24', - Gg: '\u22D9', - gg: '\u226B', - ggg: '\u22D9', - gimel: '\u2137', - GJcy: '\u0403', - gjcy: '\u0453', - gl: '\u2277', - gla: '\u2AA5', - glE: '\u2A92', - glj: '\u2AA4', - gnap: '\u2A8A', - gnapprox: '\u2A8A', - gnE: '\u2269', - gne: '\u2A88', - gneq: '\u2A88', - gneqq: '\u2269', - gnsim: '\u22E7', - Gopf: '\uD835\uDD3E', - gopf: '\uD835\uDD58', - grave: '\u0060', - GreaterEqual: '\u2265', - GreaterEqualLess: '\u22DB', - GreaterFullEqual: '\u2267', - GreaterGreater: '\u2AA2', - GreaterLess: '\u2277', - GreaterSlantEqual: '\u2A7E', - GreaterTilde: '\u2273', - Gscr: '\uD835\uDCA2', - gscr: '\u210A', - gsim: '\u2273', - gsime: '\u2A8E', - gsiml: '\u2A90', - Gt: '\u226B', - GT: '\u003E', - gt: '\u003E', - gtcc: '\u2AA7', - gtcir: '\u2A7A', - gtdot: '\u22D7', - gtlPar: '\u2995', - gtquest: '\u2A7C', - gtrapprox: '\u2A86', - gtrarr: '\u2978', - gtrdot: '\u22D7', - gtreqless: '\u22DB', - gtreqqless: '\u2A8C', - gtrless: '\u2277', - gtrsim: '\u2273', - gvertneqq: '\u2269\uFE00', - gvnE: '\u2269\uFE00', - Hacek: '\u02C7', - hairsp: '\u200A', - half: '\u00BD', - hamilt: '\u210B', - HARDcy: '\u042A', - hardcy: '\u044A', - hArr: '\u21D4', - harr: '\u2194', - harrcir: '\u2948', - harrw: '\u21AD', - Hat: '\u005E', - hbar: '\u210F', - Hcirc: '\u0124', - hcirc: '\u0125', - hearts: '\u2665', - heartsuit: '\u2665', - hellip: '\u2026', - hercon: '\u22B9', - Hfr: '\u210C', - hfr: '\uD835\uDD25', - HilbertSpace: '\u210B', - hksearow: '\u2925', - hkswarow: '\u2926', - hoarr: '\u21FF', - homtht: '\u223B', - hookleftarrow: '\u21A9', - hookrightarrow: '\u21AA', - Hopf: '\u210D', - hopf: '\uD835\uDD59', - horbar: '\u2015', - HorizontalLine: '\u2500', - Hscr: '\u210B', - hscr: '\uD835\uDCBD', - hslash: '\u210F', - Hstrok: '\u0126', - hstrok: '\u0127', - HumpDownHump: '\u224E', - HumpEqual: '\u224F', - hybull: '\u2043', - hyphen: '\u2010', - Iacute: '\u00CD', - iacute: '\u00ED', - ic: '\u2063', - Icirc: '\u00CE', - icirc: '\u00EE', - Icy: '\u0418', - icy: '\u0438', - Idot: '\u0130', - IEcy: '\u0415', - iecy: '\u0435', - iexcl: '\u00A1', - iff: '\u21D4', - Ifr: '\u2111', - ifr: '\uD835\uDD26', - Igrave: '\u00CC', - igrave: '\u00EC', - ii: '\u2148', - iiiint: '\u2A0C', - iiint: '\u222D', - iinfin: '\u29DC', - iiota: '\u2129', - IJlig: '\u0132', - ijlig: '\u0133', - Im: '\u2111', - Imacr: '\u012A', - imacr: '\u012B', - image: '\u2111', - ImaginaryI: '\u2148', - imagline: '\u2110', - imagpart: '\u2111', - imath: '\u0131', - imof: '\u22B7', - imped: '\u01B5', - Implies: '\u21D2', - in: '\u2208', - incare: '\u2105', - infin: '\u221E', - infintie: '\u29DD', - inodot: '\u0131', - Int: '\u222C', - int: '\u222B', - intcal: '\u22BA', - integers: '\u2124', - Integral: '\u222B', - intercal: '\u22BA', - Intersection: '\u22C2', - intlarhk: '\u2A17', - intprod: '\u2A3C', - InvisibleComma: '\u2063', - InvisibleTimes: '\u2062', - IOcy: '\u0401', - iocy: '\u0451', - Iogon: '\u012E', - iogon: '\u012F', - Iopf: '\uD835\uDD40', - iopf: '\uD835\uDD5A', - Iota: '\u0399', - iota: '\u03B9', - iprod: '\u2A3C', - iquest: '\u00BF', - Iscr: '\u2110', - iscr: '\uD835\uDCBE', - isin: '\u2208', - isindot: '\u22F5', - isinE: '\u22F9', - isins: '\u22F4', - isinsv: '\u22F3', - isinv: '\u2208', - it: '\u2062', - Itilde: '\u0128', - itilde: '\u0129', - Iukcy: '\u0406', - iukcy: '\u0456', - Iuml: '\u00CF', - iuml: '\u00EF', - Jcirc: '\u0134', - jcirc: '\u0135', - Jcy: '\u0419', - jcy: '\u0439', - Jfr: '\uD835\uDD0D', - jfr: '\uD835\uDD27', - jmath: '\u0237', - Jopf: '\uD835\uDD41', - jopf: '\uD835\uDD5B', - Jscr: '\uD835\uDCA5', - jscr: '\uD835\uDCBF', - Jsercy: '\u0408', - jsercy: '\u0458', - Jukcy: '\u0404', - jukcy: '\u0454', - Kappa: '\u039A', - kappa: '\u03BA', - kappav: '\u03F0', - Kcedil: '\u0136', - kcedil: '\u0137', - Kcy: '\u041A', - kcy: '\u043A', - Kfr: '\uD835\uDD0E', - kfr: '\uD835\uDD28', - kgreen: '\u0138', - KHcy: '\u0425', - khcy: '\u0445', - KJcy: '\u040C', - kjcy: '\u045C', - Kopf: '\uD835\uDD42', - kopf: '\uD835\uDD5C', - Kscr: '\uD835\uDCA6', - kscr: '\uD835\uDCC0', - lAarr: '\u21DA', - Lacute: '\u0139', - lacute: '\u013A', - laemptyv: '\u29B4', - lagran: '\u2112', - Lambda: '\u039B', - lambda: '\u03BB', - Lang: '\u27EA', - lang: '\u27E8', - langd: '\u2991', - langle: '\u27E8', - lap: '\u2A85', - Laplacetrf: '\u2112', - laquo: '\u00AB', - Larr: '\u219E', - lArr: '\u21D0', - larr: '\u2190', - larrb: '\u21E4', - larrbfs: '\u291F', - larrfs: '\u291D', - larrhk: '\u21A9', - larrlp: '\u21AB', - larrpl: '\u2939', - larrsim: '\u2973', - larrtl: '\u21A2', - lat: '\u2AAB', - lAtail: '\u291B', - latail: '\u2919', - late: '\u2AAD', - lates: '\u2AAD\uFE00', - lBarr: '\u290E', - lbarr: '\u290C', - lbbrk: '\u2772', - lbrace: '\u007B', - lbrack: '\u005B', - lbrke: '\u298B', - lbrksld: '\u298F', - lbrkslu: '\u298D', - Lcaron: '\u013D', - lcaron: '\u013E', - Lcedil: '\u013B', - lcedil: '\u013C', - lceil: '\u2308', - lcub: '\u007B', - Lcy: '\u041B', - lcy: '\u043B', - ldca: '\u2936', - ldquo: '\u201C', - ldquor: '\u201E', - ldrdhar: '\u2967', - ldrushar: '\u294B', - ldsh: '\u21B2', - lE: '\u2266', - le: '\u2264', - LeftAngleBracket: '\u27E8', - LeftArrow: '\u2190', - Leftarrow: '\u21D0', - leftarrow: '\u2190', - LeftArrowBar: '\u21E4', - LeftArrowRightArrow: '\u21C6', - leftarrowtail: '\u21A2', - LeftCeiling: '\u2308', - LeftDoubleBracket: '\u27E6', - LeftDownTeeVector: '\u2961', - LeftDownVector: '\u21C3', - LeftDownVectorBar: '\u2959', - LeftFloor: '\u230A', - leftharpoondown: '\u21BD', - leftharpoonup: '\u21BC', - leftleftarrows: '\u21C7', - LeftRightArrow: '\u2194', - Leftrightarrow: '\u21D4', - leftrightarrow: '\u2194', - leftrightarrows: '\u21C6', - leftrightharpoons: '\u21CB', - leftrightsquigarrow: '\u21AD', - LeftRightVector: '\u294E', - LeftTee: '\u22A3', - LeftTeeArrow: '\u21A4', - LeftTeeVector: '\u295A', - leftthreetimes: '\u22CB', - LeftTriangle: '\u22B2', - LeftTriangleBar: '\u29CF', - LeftTriangleEqual: '\u22B4', - LeftUpDownVector: '\u2951', - LeftUpTeeVector: '\u2960', - LeftUpVector: '\u21BF', - LeftUpVectorBar: '\u2958', - LeftVector: '\u21BC', - LeftVectorBar: '\u2952', - lEg: '\u2A8B', - leg: '\u22DA', - leq: '\u2264', - leqq: '\u2266', - leqslant: '\u2A7D', - les: '\u2A7D', - lescc: '\u2AA8', - lesdot: '\u2A7F', - lesdoto: '\u2A81', - lesdotor: '\u2A83', - lesg: '\u22DA\uFE00', - lesges: '\u2A93', - lessapprox: '\u2A85', - lessdot: '\u22D6', - lesseqgtr: '\u22DA', - lesseqqgtr: '\u2A8B', - LessEqualGreater: '\u22DA', - LessFullEqual: '\u2266', - LessGreater: '\u2276', - lessgtr: '\u2276', - LessLess: '\u2AA1', - lesssim: '\u2272', - LessSlantEqual: '\u2A7D', - LessTilde: '\u2272', - lfisht: '\u297C', - lfloor: '\u230A', - Lfr: '\uD835\uDD0F', - lfr: '\uD835\uDD29', - lg: '\u2276', - lgE: '\u2A91', - lHar: '\u2962', - lhard: '\u21BD', - lharu: '\u21BC', - lharul: '\u296A', - lhblk: '\u2584', - LJcy: '\u0409', - ljcy: '\u0459', - Ll: '\u22D8', - ll: '\u226A', - llarr: '\u21C7', - llcorner: '\u231E', - Lleftarrow: '\u21DA', - llhard: '\u296B', - lltri: '\u25FA', - Lmidot: '\u013F', - lmidot: '\u0140', - lmoust: '\u23B0', - lmoustache: '\u23B0', - lnap: '\u2A89', - lnapprox: '\u2A89', - lnE: '\u2268', - lne: '\u2A87', - lneq: '\u2A87', - lneqq: '\u2268', - lnsim: '\u22E6', - loang: '\u27EC', - loarr: '\u21FD', - lobrk: '\u27E6', - LongLeftArrow: '\u27F5', - Longleftarrow: '\u27F8', - longleftarrow: '\u27F5', - LongLeftRightArrow: '\u27F7', - Longleftrightarrow: '\u27FA', - longleftrightarrow: '\u27F7', - longmapsto: '\u27FC', - LongRightArrow: '\u27F6', - Longrightarrow: '\u27F9', - longrightarrow: '\u27F6', - looparrowleft: '\u21AB', - looparrowright: '\u21AC', - lopar: '\u2985', - Lopf: '\uD835\uDD43', - lopf: '\uD835\uDD5D', - loplus: '\u2A2D', - lotimes: '\u2A34', - lowast: '\u2217', - lowbar: '\u005F', - LowerLeftArrow: '\u2199', - LowerRightArrow: '\u2198', - loz: '\u25CA', - lozenge: '\u25CA', - lozf: '\u29EB', - lpar: '\u0028', - lparlt: '\u2993', - lrarr: '\u21C6', - lrcorner: '\u231F', - lrhar: '\u21CB', - lrhard: '\u296D', - lrm: '\u200E', - lrtri: '\u22BF', - lsaquo: '\u2039', - Lscr: '\u2112', - lscr: '\uD835\uDCC1', - Lsh: '\u21B0', - lsh: '\u21B0', - lsim: '\u2272', - lsime: '\u2A8D', - lsimg: '\u2A8F', - lsqb: '\u005B', - lsquo: '\u2018', - lsquor: '\u201A', - Lstrok: '\u0141', - lstrok: '\u0142', - Lt: '\u226A', - LT: '\u003C', - lt: '\u003C', - ltcc: '\u2AA6', - ltcir: '\u2A79', - ltdot: '\u22D6', - lthree: '\u22CB', - ltimes: '\u22C9', - ltlarr: '\u2976', - ltquest: '\u2A7B', - ltri: '\u25C3', - ltrie: '\u22B4', - ltrif: '\u25C2', - ltrPar: '\u2996', - lurdshar: '\u294A', - luruhar: '\u2966', - lvertneqq: '\u2268\uFE00', - lvnE: '\u2268\uFE00', - macr: '\u00AF', - male: '\u2642', - malt: '\u2720', - maltese: '\u2720', - Map: '\u2905', - map: '\u21A6', - mapsto: '\u21A6', - mapstodown: '\u21A7', - mapstoleft: '\u21A4', - mapstoup: '\u21A5', - marker: '\u25AE', - mcomma: '\u2A29', - Mcy: '\u041C', - mcy: '\u043C', - mdash: '\u2014', - mDDot: '\u223A', - measuredangle: '\u2221', - MediumSpace: '\u205F', - Mellintrf: '\u2133', - Mfr: '\uD835\uDD10', - mfr: '\uD835\uDD2A', - mho: '\u2127', - micro: '\u00B5', - mid: '\u2223', - midast: '\u002A', - midcir: '\u2AF0', - middot: '\u00B7', - minus: '\u2212', - minusb: '\u229F', - minusd: '\u2238', - minusdu: '\u2A2A', - MinusPlus: '\u2213', - mlcp: '\u2ADB', - mldr: '\u2026', - mnplus: '\u2213', - models: '\u22A7', - Mopf: '\uD835\uDD44', - mopf: '\uD835\uDD5E', - mp: '\u2213', - Mscr: '\u2133', - mscr: '\uD835\uDCC2', - mstpos: '\u223E', - Mu: '\u039C', - mu: '\u03BC', - multimap: '\u22B8', - mumap: '\u22B8', - nabla: '\u2207', - Nacute: '\u0143', - nacute: '\u0144', - nang: '\u2220\u20D2', - nap: '\u2249', - napE: '\u2A70\u0338', - napid: '\u224B\u0338', - napos: '\u0149', - napprox: '\u2249', - natur: '\u266E', - natural: '\u266E', - naturals: '\u2115', - nbsp: '\u00A0', - nbump: '\u224E\u0338', - nbumpe: '\u224F\u0338', - ncap: '\u2A43', - Ncaron: '\u0147', - ncaron: '\u0148', - Ncedil: '\u0145', - ncedil: '\u0146', - ncong: '\u2247', - ncongdot: '\u2A6D\u0338', - ncup: '\u2A42', - Ncy: '\u041D', - ncy: '\u043D', - ndash: '\u2013', - ne: '\u2260', - nearhk: '\u2924', - neArr: '\u21D7', - nearr: '\u2197', - nearrow: '\u2197', - nedot: '\u2250\u0338', - NegativeMediumSpace: '\u200B', - NegativeThickSpace: '\u200B', - NegativeThinSpace: '\u200B', - NegativeVeryThinSpace: '\u200B', - nequiv: '\u2262', - nesear: '\u2928', - nesim: '\u2242\u0338', - NestedGreaterGreater: '\u226B', - NestedLessLess: '\u226A', - NewLine: '\u000A', - nexist: '\u2204', - nexists: '\u2204', - Nfr: '\uD835\uDD11', - nfr: '\uD835\uDD2B', - ngE: '\u2267\u0338', - nge: '\u2271', - ngeq: '\u2271', - ngeqq: '\u2267\u0338', - ngeqslant: '\u2A7E\u0338', - nges: '\u2A7E\u0338', - nGg: '\u22D9\u0338', - ngsim: '\u2275', - nGt: '\u226B\u20D2', - ngt: '\u226F', - ngtr: '\u226F', - nGtv: '\u226B\u0338', - nhArr: '\u21CE', - nharr: '\u21AE', - nhpar: '\u2AF2', - ni: '\u220B', - nis: '\u22FC', - nisd: '\u22FA', - niv: '\u220B', - NJcy: '\u040A', - njcy: '\u045A', - nlArr: '\u21CD', - nlarr: '\u219A', - nldr: '\u2025', - nlE: '\u2266\u0338', - nle: '\u2270', - nLeftarrow: '\u21CD', - nleftarrow: '\u219A', - nLeftrightarrow: '\u21CE', - nleftrightarrow: '\u21AE', - nleq: '\u2270', - nleqq: '\u2266\u0338', - nleqslant: '\u2A7D\u0338', - nles: '\u2A7D\u0338', - nless: '\u226E', - nLl: '\u22D8\u0338', - nlsim: '\u2274', - nLt: '\u226A\u20D2', - nlt: '\u226E', - nltri: '\u22EA', - nltrie: '\u22EC', - nLtv: '\u226A\u0338', - nmid: '\u2224', - NoBreak: '\u2060', - NonBreakingSpace: '\u00A0', - Nopf: '\u2115', - nopf: '\uD835\uDD5F', - Not: '\u2AEC', - not: '\u00AC', - NotCongruent: '\u2262', - NotCupCap: '\u226D', - NotDoubleVerticalBar: '\u2226', - NotElement: '\u2209', - NotEqual: '\u2260', - NotEqualTilde: '\u2242\u0338', - NotExists: '\u2204', - NotGreater: '\u226F', - NotGreaterEqual: '\u2271', - NotGreaterFullEqual: '\u2267\u0338', - NotGreaterGreater: '\u226B\u0338', - NotGreaterLess: '\u2279', - NotGreaterSlantEqual: '\u2A7E\u0338', - NotGreaterTilde: '\u2275', - NotHumpDownHump: '\u224E\u0338', - NotHumpEqual: '\u224F\u0338', - notin: '\u2209', - notindot: '\u22F5\u0338', - notinE: '\u22F9\u0338', - notinva: '\u2209', - notinvb: '\u22F7', - notinvc: '\u22F6', - NotLeftTriangle: '\u22EA', - NotLeftTriangleBar: '\u29CF\u0338', - NotLeftTriangleEqual: '\u22EC', - NotLess: '\u226E', - NotLessEqual: '\u2270', - NotLessGreater: '\u2278', - NotLessLess: '\u226A\u0338', - NotLessSlantEqual: '\u2A7D\u0338', - NotLessTilde: '\u2274', - NotNestedGreaterGreater: '\u2AA2\u0338', - NotNestedLessLess: '\u2AA1\u0338', - notni: '\u220C', - notniva: '\u220C', - notnivb: '\u22FE', - notnivc: '\u22FD', - NotPrecedes: '\u2280', - NotPrecedesEqual: '\u2AAF\u0338', - NotPrecedesSlantEqual: '\u22E0', - NotReverseElement: '\u220C', - NotRightTriangle: '\u22EB', - NotRightTriangleBar: '\u29D0\u0338', - NotRightTriangleEqual: '\u22ED', - NotSquareSubset: '\u228F\u0338', - NotSquareSubsetEqual: '\u22E2', - NotSquareSuperset: '\u2290\u0338', - NotSquareSupersetEqual: '\u22E3', - NotSubset: '\u2282\u20D2', - NotSubsetEqual: '\u2288', - NotSucceeds: '\u2281', - NotSucceedsEqual: '\u2AB0\u0338', - NotSucceedsSlantEqual: '\u22E1', - NotSucceedsTilde: '\u227F\u0338', - NotSuperset: '\u2283\u20D2', - NotSupersetEqual: '\u2289', - NotTilde: '\u2241', - NotTildeEqual: '\u2244', - NotTildeFullEqual: '\u2247', - NotTildeTilde: '\u2249', - NotVerticalBar: '\u2224', - npar: '\u2226', - nparallel: '\u2226', - nparsl: '\u2AFD\u20E5', - npart: '\u2202\u0338', - npolint: '\u2A14', - npr: '\u2280', - nprcue: '\u22E0', - npre: '\u2AAF\u0338', - nprec: '\u2280', - npreceq: '\u2AAF\u0338', - nrArr: '\u21CF', - nrarr: '\u219B', - nrarrc: '\u2933\u0338', - nrarrw: '\u219D\u0338', - nRightarrow: '\u21CF', - nrightarrow: '\u219B', - nrtri: '\u22EB', - nrtrie: '\u22ED', - nsc: '\u2281', - nsccue: '\u22E1', - nsce: '\u2AB0\u0338', - Nscr: '\uD835\uDCA9', - nscr: '\uD835\uDCC3', - nshortmid: '\u2224', - nshortparallel: '\u2226', - nsim: '\u2241', - nsime: '\u2244', - nsimeq: '\u2244', - nsmid: '\u2224', - nspar: '\u2226', - nsqsube: '\u22E2', - nsqsupe: '\u22E3', - nsub: '\u2284', - nsubE: '\u2AC5\u0338', - nsube: '\u2288', - nsubset: '\u2282\u20D2', - nsubseteq: '\u2288', - nsubseteqq: '\u2AC5\u0338', - nsucc: '\u2281', - nsucceq: '\u2AB0\u0338', - nsup: '\u2285', - nsupE: '\u2AC6\u0338', - nsupe: '\u2289', - nsupset: '\u2283\u20D2', - nsupseteq: '\u2289', - nsupseteqq: '\u2AC6\u0338', - ntgl: '\u2279', - Ntilde: '\u00D1', - ntilde: '\u00F1', - ntlg: '\u2278', - ntriangleleft: '\u22EA', - ntrianglelefteq: '\u22EC', - ntriangleright: '\u22EB', - ntrianglerighteq: '\u22ED', - Nu: '\u039D', - nu: '\u03BD', - num: '\u0023', - numero: '\u2116', - numsp: '\u2007', - nvap: '\u224D\u20D2', - nVDash: '\u22AF', - nVdash: '\u22AE', - nvDash: '\u22AD', - nvdash: '\u22AC', - nvge: '\u2265\u20D2', - nvgt: '\u003E\u20D2', - nvHarr: '\u2904', - nvinfin: '\u29DE', - nvlArr: '\u2902', - nvle: '\u2264\u20D2', - nvlt: '\u003C\u20D2', - nvltrie: '\u22B4\u20D2', - nvrArr: '\u2903', - nvrtrie: '\u22B5\u20D2', - nvsim: '\u223C\u20D2', - nwarhk: '\u2923', - nwArr: '\u21D6', - nwarr: '\u2196', - nwarrow: '\u2196', - nwnear: '\u2927', - Oacute: '\u00D3', - oacute: '\u00F3', - oast: '\u229B', - ocir: '\u229A', - Ocirc: '\u00D4', - ocirc: '\u00F4', - Ocy: '\u041E', - ocy: '\u043E', - odash: '\u229D', - Odblac: '\u0150', - odblac: '\u0151', - odiv: '\u2A38', - odot: '\u2299', - odsold: '\u29BC', - OElig: '\u0152', - oelig: '\u0153', - ofcir: '\u29BF', - Ofr: '\uD835\uDD12', - ofr: '\uD835\uDD2C', - ogon: '\u02DB', - Ograve: '\u00D2', - ograve: '\u00F2', - ogt: '\u29C1', - ohbar: '\u29B5', - ohm: '\u03A9', - oint: '\u222E', - olarr: '\u21BA', - olcir: '\u29BE', - olcross: '\u29BB', - oline: '\u203E', - olt: '\u29C0', - Omacr: '\u014C', - omacr: '\u014D', - Omega: '\u03A9', - omega: '\u03C9', - Omicron: '\u039F', - omicron: '\u03BF', - omid: '\u29B6', - ominus: '\u2296', - Oopf: '\uD835\uDD46', - oopf: '\uD835\uDD60', - opar: '\u29B7', - OpenCurlyDoubleQuote: '\u201C', - OpenCurlyQuote: '\u2018', - operp: '\u29B9', - oplus: '\u2295', - Or: '\u2A54', - or: '\u2228', - orarr: '\u21BB', - ord: '\u2A5D', - order: '\u2134', - orderof: '\u2134', - ordf: '\u00AA', - ordm: '\u00BA', - origof: '\u22B6', - oror: '\u2A56', - orslope: '\u2A57', - orv: '\u2A5B', - oS: '\u24C8', - Oscr: '\uD835\uDCAA', - oscr: '\u2134', - Oslash: '\u00D8', - oslash: '\u00F8', - osol: '\u2298', - Otilde: '\u00D5', - otilde: '\u00F5', - Otimes: '\u2A37', - otimes: '\u2297', - otimesas: '\u2A36', - Ouml: '\u00D6', - ouml: '\u00F6', - ovbar: '\u233D', - OverBar: '\u203E', - OverBrace: '\u23DE', - OverBracket: '\u23B4', - OverParenthesis: '\u23DC', - par: '\u2225', - para: '\u00B6', - parallel: '\u2225', - parsim: '\u2AF3', - parsl: '\u2AFD', - part: '\u2202', - PartialD: '\u2202', - Pcy: '\u041F', - pcy: '\u043F', - percnt: '\u0025', - period: '\u002E', - permil: '\u2030', - perp: '\u22A5', - pertenk: '\u2031', - Pfr: '\uD835\uDD13', - pfr: '\uD835\uDD2D', - Phi: '\u03A6', - phi: '\u03C6', - phiv: '\u03D5', - phmmat: '\u2133', - phone: '\u260E', - Pi: '\u03A0', - pi: '\u03C0', - pitchfork: '\u22D4', - piv: '\u03D6', - planck: '\u210F', - planckh: '\u210E', - plankv: '\u210F', - plus: '\u002B', - plusacir: '\u2A23', - plusb: '\u229E', - pluscir: '\u2A22', - plusdo: '\u2214', - plusdu: '\u2A25', - pluse: '\u2A72', - PlusMinus: '\u00B1', - plusmn: '\u00B1', - plussim: '\u2A26', - plustwo: '\u2A27', - pm: '\u00B1', - Poincareplane: '\u210C', - pointint: '\u2A15', - Popf: '\u2119', - popf: '\uD835\uDD61', - pound: '\u00A3', - Pr: '\u2ABB', - pr: '\u227A', - prap: '\u2AB7', - prcue: '\u227C', - prE: '\u2AB3', - pre: '\u2AAF', - prec: '\u227A', - precapprox: '\u2AB7', - preccurlyeq: '\u227C', - Precedes: '\u227A', - PrecedesEqual: '\u2AAF', - PrecedesSlantEqual: '\u227C', - PrecedesTilde: '\u227E', - preceq: '\u2AAF', - precnapprox: '\u2AB9', - precneqq: '\u2AB5', - precnsim: '\u22E8', - precsim: '\u227E', - Prime: '\u2033', - prime: '\u2032', - primes: '\u2119', - prnap: '\u2AB9', - prnE: '\u2AB5', - prnsim: '\u22E8', - prod: '\u220F', - Product: '\u220F', - profalar: '\u232E', - profline: '\u2312', - profsurf: '\u2313', - prop: '\u221D', - Proportion: '\u2237', - Proportional: '\u221D', - propto: '\u221D', - prsim: '\u227E', - prurel: '\u22B0', - Pscr: '\uD835\uDCAB', - pscr: '\uD835\uDCC5', - Psi: '\u03A8', - psi: '\u03C8', - puncsp: '\u2008', - Qfr: '\uD835\uDD14', - qfr: '\uD835\uDD2E', - qint: '\u2A0C', - Qopf: '\u211A', - qopf: '\uD835\uDD62', - qprime: '\u2057', - Qscr: '\uD835\uDCAC', - qscr: '\uD835\uDCC6', - quaternions: '\u210D', - quatint: '\u2A16', - quest: '\u003F', - questeq: '\u225F', - QUOT: '\u0022', - quot: '\u0022', - rAarr: '\u21DB', - race: '\u223D\u0331', - Racute: '\u0154', - racute: '\u0155', - radic: '\u221A', - raemptyv: '\u29B3', - Rang: '\u27EB', - rang: '\u27E9', - rangd: '\u2992', - range: '\u29A5', - rangle: '\u27E9', - raquo: '\u00BB', - Rarr: '\u21A0', - rArr: '\u21D2', - rarr: '\u2192', - rarrap: '\u2975', - rarrb: '\u21E5', - rarrbfs: '\u2920', - rarrc: '\u2933', - rarrfs: '\u291E', - rarrhk: '\u21AA', - rarrlp: '\u21AC', - rarrpl: '\u2945', - rarrsim: '\u2974', - Rarrtl: '\u2916', - rarrtl: '\u21A3', - rarrw: '\u219D', - rAtail: '\u291C', - ratail: '\u291A', - ratio: '\u2236', - rationals: '\u211A', - RBarr: '\u2910', - rBarr: '\u290F', - rbarr: '\u290D', - rbbrk: '\u2773', - rbrace: '\u007D', - rbrack: '\u005D', - rbrke: '\u298C', - rbrksld: '\u298E', - rbrkslu: '\u2990', - Rcaron: '\u0158', - rcaron: '\u0159', - Rcedil: '\u0156', - rcedil: '\u0157', - rceil: '\u2309', - rcub: '\u007D', - Rcy: '\u0420', - rcy: '\u0440', - rdca: '\u2937', - rdldhar: '\u2969', - rdquo: '\u201D', - rdquor: '\u201D', - rdsh: '\u21B3', - Re: '\u211C', - real: '\u211C', - realine: '\u211B', - realpart: '\u211C', - reals: '\u211D', - rect: '\u25AD', - REG: '\u00AE', - reg: '\u00AE', - ReverseElement: '\u220B', - ReverseEquilibrium: '\u21CB', - ReverseUpEquilibrium: '\u296F', - rfisht: '\u297D', - rfloor: '\u230B', - Rfr: '\u211C', - rfr: '\uD835\uDD2F', - rHar: '\u2964', - rhard: '\u21C1', - rharu: '\u21C0', - rharul: '\u296C', - Rho: '\u03A1', - rho: '\u03C1', - rhov: '\u03F1', - RightAngleBracket: '\u27E9', - RightArrow: '\u2192', - Rightarrow: '\u21D2', - rightarrow: '\u2192', - RightArrowBar: '\u21E5', - RightArrowLeftArrow: '\u21C4', - rightarrowtail: '\u21A3', - RightCeiling: '\u2309', - RightDoubleBracket: '\u27E7', - RightDownTeeVector: '\u295D', - RightDownVector: '\u21C2', - RightDownVectorBar: '\u2955', - RightFloor: '\u230B', - rightharpoondown: '\u21C1', - rightharpoonup: '\u21C0', - rightleftarrows: '\u21C4', - rightleftharpoons: '\u21CC', - rightrightarrows: '\u21C9', - rightsquigarrow: '\u219D', - RightTee: '\u22A2', - RightTeeArrow: '\u21A6', - RightTeeVector: '\u295B', - rightthreetimes: '\u22CC', - RightTriangle: '\u22B3', - RightTriangleBar: '\u29D0', - RightTriangleEqual: '\u22B5', - RightUpDownVector: '\u294F', - RightUpTeeVector: '\u295C', - RightUpVector: '\u21BE', - RightUpVectorBar: '\u2954', - RightVector: '\u21C0', - RightVectorBar: '\u2953', - ring: '\u02DA', - risingdotseq: '\u2253', - rlarr: '\u21C4', - rlhar: '\u21CC', - rlm: '\u200F', - rmoust: '\u23B1', - rmoustache: '\u23B1', - rnmid: '\u2AEE', - roang: '\u27ED', - roarr: '\u21FE', - robrk: '\u27E7', - ropar: '\u2986', - Ropf: '\u211D', - ropf: '\uD835\uDD63', - roplus: '\u2A2E', - rotimes: '\u2A35', - RoundImplies: '\u2970', - rpar: '\u0029', - rpargt: '\u2994', - rppolint: '\u2A12', - rrarr: '\u21C9', - Rrightarrow: '\u21DB', - rsaquo: '\u203A', - Rscr: '\u211B', - rscr: '\uD835\uDCC7', - Rsh: '\u21B1', - rsh: '\u21B1', - rsqb: '\u005D', - rsquo: '\u2019', - rsquor: '\u2019', - rthree: '\u22CC', - rtimes: '\u22CA', - rtri: '\u25B9', - rtrie: '\u22B5', - rtrif: '\u25B8', - rtriltri: '\u29CE', - RuleDelayed: '\u29F4', - ruluhar: '\u2968', - rx: '\u211E', - Sacute: '\u015A', - sacute: '\u015B', - sbquo: '\u201A', - Sc: '\u2ABC', - sc: '\u227B', - scap: '\u2AB8', - Scaron: '\u0160', - scaron: '\u0161', - sccue: '\u227D', - scE: '\u2AB4', - sce: '\u2AB0', - Scedil: '\u015E', - scedil: '\u015F', - Scirc: '\u015C', - scirc: '\u015D', - scnap: '\u2ABA', - scnE: '\u2AB6', - scnsim: '\u22E9', - scpolint: '\u2A13', - scsim: '\u227F', - Scy: '\u0421', - scy: '\u0441', - sdot: '\u22C5', - sdotb: '\u22A1', - sdote: '\u2A66', - searhk: '\u2925', - seArr: '\u21D8', - searr: '\u2198', - searrow: '\u2198', - sect: '\u00A7', - semi: '\u003B', - seswar: '\u2929', - setminus: '\u2216', - setmn: '\u2216', - sext: '\u2736', - Sfr: '\uD835\uDD16', - sfr: '\uD835\uDD30', - sfrown: '\u2322', - sharp: '\u266F', - SHCHcy: '\u0429', - shchcy: '\u0449', - SHcy: '\u0428', - shcy: '\u0448', - ShortDownArrow: '\u2193', - ShortLeftArrow: '\u2190', - shortmid: '\u2223', - shortparallel: '\u2225', - ShortRightArrow: '\u2192', - ShortUpArrow: '\u2191', - shy: '\u00AD', - Sigma: '\u03A3', - sigma: '\u03C3', - sigmaf: '\u03C2', - sigmav: '\u03C2', - sim: '\u223C', - simdot: '\u2A6A', - sime: '\u2243', - simeq: '\u2243', - simg: '\u2A9E', - simgE: '\u2AA0', - siml: '\u2A9D', - simlE: '\u2A9F', - simne: '\u2246', - simplus: '\u2A24', - simrarr: '\u2972', - slarr: '\u2190', - SmallCircle: '\u2218', - smallsetminus: '\u2216', - smashp: '\u2A33', - smeparsl: '\u29E4', - smid: '\u2223', - smile: '\u2323', - smt: '\u2AAA', - smte: '\u2AAC', - smtes: '\u2AAC\uFE00', - SOFTcy: '\u042C', - softcy: '\u044C', - sol: '\u002F', - solb: '\u29C4', - solbar: '\u233F', - Sopf: '\uD835\uDD4A', - sopf: '\uD835\uDD64', - spades: '\u2660', - spadesuit: '\u2660', - spar: '\u2225', - sqcap: '\u2293', - sqcaps: '\u2293\uFE00', - sqcup: '\u2294', - sqcups: '\u2294\uFE00', - Sqrt: '\u221A', - sqsub: '\u228F', - sqsube: '\u2291', - sqsubset: '\u228F', - sqsubseteq: '\u2291', - sqsup: '\u2290', - sqsupe: '\u2292', - sqsupset: '\u2290', - sqsupseteq: '\u2292', - squ: '\u25A1', - Square: '\u25A1', - square: '\u25A1', - SquareIntersection: '\u2293', - SquareSubset: '\u228F', - SquareSubsetEqual: '\u2291', - SquareSuperset: '\u2290', - SquareSupersetEqual: '\u2292', - SquareUnion: '\u2294', - squarf: '\u25AA', - squf: '\u25AA', - srarr: '\u2192', - Sscr: '\uD835\uDCAE', - sscr: '\uD835\uDCC8', - ssetmn: '\u2216', - ssmile: '\u2323', - sstarf: '\u22C6', - Star: '\u22C6', - star: '\u2606', - starf: '\u2605', - straightepsilon: '\u03F5', - straightphi: '\u03D5', - strns: '\u00AF', - Sub: '\u22D0', - sub: '\u2282', - subdot: '\u2ABD', - subE: '\u2AC5', - sube: '\u2286', - subedot: '\u2AC3', - submult: '\u2AC1', - subnE: '\u2ACB', - subne: '\u228A', - subplus: '\u2ABF', - subrarr: '\u2979', - Subset: '\u22D0', - subset: '\u2282', - subseteq: '\u2286', - subseteqq: '\u2AC5', - SubsetEqual: '\u2286', - subsetneq: '\u228A', - subsetneqq: '\u2ACB', - subsim: '\u2AC7', - subsub: '\u2AD5', - subsup: '\u2AD3', - succ: '\u227B', - succapprox: '\u2AB8', - succcurlyeq: '\u227D', - Succeeds: '\u227B', - SucceedsEqual: '\u2AB0', - SucceedsSlantEqual: '\u227D', - SucceedsTilde: '\u227F', - succeq: '\u2AB0', - succnapprox: '\u2ABA', - succneqq: '\u2AB6', - succnsim: '\u22E9', - succsim: '\u227F', - SuchThat: '\u220B', - Sum: '\u2211', - sum: '\u2211', - sung: '\u266A', - Sup: '\u22D1', - sup: '\u2283', - sup1: '\u00B9', - sup2: '\u00B2', - sup3: '\u00B3', - supdot: '\u2ABE', - supdsub: '\u2AD8', - supE: '\u2AC6', - supe: '\u2287', - supedot: '\u2AC4', - Superset: '\u2283', - SupersetEqual: '\u2287', - suphsol: '\u27C9', - suphsub: '\u2AD7', - suplarr: '\u297B', - supmult: '\u2AC2', - supnE: '\u2ACC', - supne: '\u228B', - supplus: '\u2AC0', - Supset: '\u22D1', - supset: '\u2283', - supseteq: '\u2287', - supseteqq: '\u2AC6', - supsetneq: '\u228B', - supsetneqq: '\u2ACC', - supsim: '\u2AC8', - supsub: '\u2AD4', - supsup: '\u2AD6', - swarhk: '\u2926', - swArr: '\u21D9', - swarr: '\u2199', - swarrow: '\u2199', - swnwar: '\u292A', - szlig: '\u00DF', - Tab: '\u0009', - target: '\u2316', - Tau: '\u03A4', - tau: '\u03C4', - tbrk: '\u23B4', - Tcaron: '\u0164', - tcaron: '\u0165', - Tcedil: '\u0162', - tcedil: '\u0163', - Tcy: '\u0422', - tcy: '\u0442', - tdot: '\u20DB', - telrec: '\u2315', - Tfr: '\uD835\uDD17', - tfr: '\uD835\uDD31', - there4: '\u2234', - Therefore: '\u2234', - therefore: '\u2234', - Theta: '\u0398', - theta: '\u03B8', - thetasym: '\u03D1', - thetav: '\u03D1', - thickapprox: '\u2248', - thicksim: '\u223C', - ThickSpace: '\u205F\u200A', - thinsp: '\u2009', - ThinSpace: '\u2009', - thkap: '\u2248', - thksim: '\u223C', - THORN: '\u00DE', - thorn: '\u00FE', - Tilde: '\u223C', - tilde: '\u02DC', - TildeEqual: '\u2243', - TildeFullEqual: '\u2245', - TildeTilde: '\u2248', - times: '\u00D7', - timesb: '\u22A0', - timesbar: '\u2A31', - timesd: '\u2A30', - tint: '\u222D', - toea: '\u2928', - top: '\u22A4', - topbot: '\u2336', - topcir: '\u2AF1', - Topf: '\uD835\uDD4B', - topf: '\uD835\uDD65', - topfork: '\u2ADA', - tosa: '\u2929', - tprime: '\u2034', - TRADE: '\u2122', - trade: '\u2122', - triangle: '\u25B5', - triangledown: '\u25BF', - triangleleft: '\u25C3', - trianglelefteq: '\u22B4', - triangleq: '\u225C', - triangleright: '\u25B9', - trianglerighteq: '\u22B5', - tridot: '\u25EC', - trie: '\u225C', - triminus: '\u2A3A', - TripleDot: '\u20DB', - triplus: '\u2A39', - trisb: '\u29CD', - tritime: '\u2A3B', - trpezium: '\u23E2', - Tscr: '\uD835\uDCAF', - tscr: '\uD835\uDCC9', - TScy: '\u0426', - tscy: '\u0446', - TSHcy: '\u040B', - tshcy: '\u045B', - Tstrok: '\u0166', - tstrok: '\u0167', - twixt: '\u226C', - twoheadleftarrow: '\u219E', - twoheadrightarrow: '\u21A0', - Uacute: '\u00DA', - uacute: '\u00FA', - Uarr: '\u219F', - uArr: '\u21D1', - uarr: '\u2191', - Uarrocir: '\u2949', - Ubrcy: '\u040E', - ubrcy: '\u045E', - Ubreve: '\u016C', - ubreve: '\u016D', - Ucirc: '\u00DB', - ucirc: '\u00FB', - Ucy: '\u0423', - ucy: '\u0443', - udarr: '\u21C5', - Udblac: '\u0170', - udblac: '\u0171', - udhar: '\u296E', - ufisht: '\u297E', - Ufr: '\uD835\uDD18', - ufr: '\uD835\uDD32', - Ugrave: '\u00D9', - ugrave: '\u00F9', - uHar: '\u2963', - uharl: '\u21BF', - uharr: '\u21BE', - uhblk: '\u2580', - ulcorn: '\u231C', - ulcorner: '\u231C', - ulcrop: '\u230F', - ultri: '\u25F8', - Umacr: '\u016A', - umacr: '\u016B', - uml: '\u00A8', - UnderBar: '\u005F', - UnderBrace: '\u23DF', - UnderBracket: '\u23B5', - UnderParenthesis: '\u23DD', - Union: '\u22C3', - UnionPlus: '\u228E', - Uogon: '\u0172', - uogon: '\u0173', - Uopf: '\uD835\uDD4C', - uopf: '\uD835\uDD66', - UpArrow: '\u2191', - Uparrow: '\u21D1', - uparrow: '\u2191', - UpArrowBar: '\u2912', - UpArrowDownArrow: '\u21C5', - UpDownArrow: '\u2195', - Updownarrow: '\u21D5', - updownarrow: '\u2195', - UpEquilibrium: '\u296E', - upharpoonleft: '\u21BF', - upharpoonright: '\u21BE', - uplus: '\u228E', - UpperLeftArrow: '\u2196', - UpperRightArrow: '\u2197', - Upsi: '\u03D2', - upsi: '\u03C5', - upsih: '\u03D2', - Upsilon: '\u03A5', - upsilon: '\u03C5', - UpTee: '\u22A5', - UpTeeArrow: '\u21A5', - upuparrows: '\u21C8', - urcorn: '\u231D', - urcorner: '\u231D', - urcrop: '\u230E', - Uring: '\u016E', - uring: '\u016F', - urtri: '\u25F9', - Uscr: '\uD835\uDCB0', - uscr: '\uD835\uDCCA', - utdot: '\u22F0', - Utilde: '\u0168', - utilde: '\u0169', - utri: '\u25B5', - utrif: '\u25B4', - uuarr: '\u21C8', - Uuml: '\u00DC', - uuml: '\u00FC', - uwangle: '\u29A7', - vangrt: '\u299C', - varepsilon: '\u03F5', - varkappa: '\u03F0', - varnothing: '\u2205', - varphi: '\u03D5', - varpi: '\u03D6', - varpropto: '\u221D', - vArr: '\u21D5', - varr: '\u2195', - varrho: '\u03F1', - varsigma: '\u03C2', - varsubsetneq: '\u228A\uFE00', - varsubsetneqq: '\u2ACB\uFE00', - varsupsetneq: '\u228B\uFE00', - varsupsetneqq: '\u2ACC\uFE00', - vartheta: '\u03D1', - vartriangleleft: '\u22B2', - vartriangleright: '\u22B3', - Vbar: '\u2AEB', - vBar: '\u2AE8', - vBarv: '\u2AE9', - Vcy: '\u0412', - vcy: '\u0432', - VDash: '\u22AB', - Vdash: '\u22A9', - vDash: '\u22A8', - vdash: '\u22A2', - Vdashl: '\u2AE6', - Vee: '\u22C1', - vee: '\u2228', - veebar: '\u22BB', - veeeq: '\u225A', - vellip: '\u22EE', - Verbar: '\u2016', - verbar: '\u007C', - Vert: '\u2016', - vert: '\u007C', - VerticalBar: '\u2223', - VerticalLine: '\u007C', - VerticalSeparator: '\u2758', - VerticalTilde: '\u2240', - VeryThinSpace: '\u200A', - Vfr: '\uD835\uDD19', - vfr: '\uD835\uDD33', - vltri: '\u22B2', - vnsub: '\u2282\u20D2', - vnsup: '\u2283\u20D2', - Vopf: '\uD835\uDD4D', - vopf: '\uD835\uDD67', - vprop: '\u221D', - vrtri: '\u22B3', - Vscr: '\uD835\uDCB1', - vscr: '\uD835\uDCCB', - vsubnE: '\u2ACB\uFE00', - vsubne: '\u228A\uFE00', - vsupnE: '\u2ACC\uFE00', - vsupne: '\u228B\uFE00', - Vvdash: '\u22AA', - vzigzag: '\u299A', - Wcirc: '\u0174', - wcirc: '\u0175', - wedbar: '\u2A5F', - Wedge: '\u22C0', - wedge: '\u2227', - wedgeq: '\u2259', - weierp: '\u2118', - Wfr: '\uD835\uDD1A', - wfr: '\uD835\uDD34', - Wopf: '\uD835\uDD4E', - wopf: '\uD835\uDD68', - wp: '\u2118', - wr: '\u2240', - wreath: '\u2240', - Wscr: '\uD835\uDCB2', - wscr: '\uD835\uDCCC', - xcap: '\u22C2', - xcirc: '\u25EF', - xcup: '\u22C3', - xdtri: '\u25BD', - Xfr: '\uD835\uDD1B', - xfr: '\uD835\uDD35', - xhArr: '\u27FA', - xharr: '\u27F7', - Xi: '\u039E', - xi: '\u03BE', - xlArr: '\u27F8', - xlarr: '\u27F5', - xmap: '\u27FC', - xnis: '\u22FB', - xodot: '\u2A00', - Xopf: '\uD835\uDD4F', - xopf: '\uD835\uDD69', - xoplus: '\u2A01', - xotime: '\u2A02', - xrArr: '\u27F9', - xrarr: '\u27F6', - Xscr: '\uD835\uDCB3', - xscr: '\uD835\uDCCD', - xsqcup: '\u2A06', - xuplus: '\u2A04', - xutri: '\u25B3', - xvee: '\u22C1', - xwedge: '\u22C0', - Yacute: '\u00DD', - yacute: '\u00FD', - YAcy: '\u042F', - yacy: '\u044F', - Ycirc: '\u0176', - ycirc: '\u0177', - Ycy: '\u042B', - ycy: '\u044B', - yen: '\u00A5', - Yfr: '\uD835\uDD1C', - yfr: '\uD835\uDD36', - YIcy: '\u0407', - yicy: '\u0457', - Yopf: '\uD835\uDD50', - yopf: '\uD835\uDD6A', - Yscr: '\uD835\uDCB4', - yscr: '\uD835\uDCCE', - YUcy: '\u042E', - yucy: '\u044E', - Yuml: '\u0178', - yuml: '\u00FF', - Zacute: '\u0179', - zacute: '\u017A', - Zcaron: '\u017D', - zcaron: '\u017E', - Zcy: '\u0417', - zcy: '\u0437', - Zdot: '\u017B', - zdot: '\u017C', - zeetrf: '\u2128', - ZeroWidthSpace: '\u200B', - Zeta: '\u0396', - zeta: '\u03B6', - Zfr: '\u2128', - zfr: '\uD835\uDD37', - ZHcy: '\u0416', - zhcy: '\u0436', - zigrarr: '\u21DD', - Zopf: '\u2124', - zopf: '\uD835\uDD6B', - Zscr: '\uD835\uDCB5', - zscr: '\uD835\uDCCF', - zwj: '\u200D', - zwnj: '\u200C', -}); - -/** - * @deprecated use `HTML_ENTITIES` instead - * @see HTML_ENTITIES - */ -exports.entityMap = exports.HTML_ENTITIES; diff --git a/claude-code-source/node_modules/@xmldom/xmldom/lib/index.js b/claude-code-source/node_modules/@xmldom/xmldom/lib/index.js deleted file mode 100644 index df827f6f..00000000 --- a/claude-code-source/node_modules/@xmldom/xmldom/lib/index.js +++ /dev/null @@ -1,4 +0,0 @@ -var dom = require('./dom') -exports.DOMImplementation = dom.DOMImplementation -exports.XMLSerializer = dom.XMLSerializer -exports.DOMParser = require('./dom-parser').DOMParser diff --git a/claude-code-source/node_modules/@xmldom/xmldom/lib/sax.js b/claude-code-source/node_modules/@xmldom/xmldom/lib/sax.js deleted file mode 100644 index 2ec3ea1e..00000000 --- a/claude-code-source/node_modules/@xmldom/xmldom/lib/sax.js +++ /dev/null @@ -1,662 +0,0 @@ -var NAMESPACE = require("./conventions").NAMESPACE; - -//[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF] -//[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040] -//[5] Name ::= NameStartChar (NameChar)* -var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF -var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]"); -var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$'); -//var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/ -//var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',') - -//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE -//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE -var S_TAG = 0;//tag name offerring -var S_ATTR = 1;//attr name offerring -var S_ATTR_SPACE=2;//attr name end and space offer -var S_EQ = 3;//=space? -var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only) -var S_ATTR_END = 5;//attr value end and no space(quot end) -var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer) -var S_TAG_CLOSE = 7;//closed el - -/** - * Creates an error that will not be caught by XMLReader aka the SAX parser. - * - * @param {string} message - * @param {any?} locator Optional, can provide details about the location in the source - * @constructor - */ -function ParseError(message, locator) { - this.message = message - this.locator = locator - if(Error.captureStackTrace) Error.captureStackTrace(this, ParseError); -} -ParseError.prototype = new Error(); -ParseError.prototype.name = ParseError.name - -function XMLReader(){ - -} - -XMLReader.prototype = { - parse:function(source,defaultNSMap,entityMap){ - var domBuilder = this.domBuilder; - domBuilder.startDocument(); - _copy(defaultNSMap ,defaultNSMap = {}) - parse(source,defaultNSMap,entityMap, - domBuilder,this.errorHandler); - domBuilder.endDocument(); - } -} -function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){ - function fixedFromCharCode(code) { - // String.prototype.fromCharCode does not supports - // > 2 bytes unicode chars directly - if (code > 0xffff) { - code -= 0x10000; - var surrogate1 = 0xd800 + (code >> 10) - , surrogate2 = 0xdc00 + (code & 0x3ff); - - return String.fromCharCode(surrogate1, surrogate2); - } else { - return String.fromCharCode(code); - } - } - function entityReplacer(a){ - var k = a.slice(1,-1); - if (Object.hasOwnProperty.call(entityMap, k)) { - return entityMap[k]; - }else if(k.charAt(0) === '#'){ - return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x'))) - }else{ - errorHandler.error('entity not found:'+a); - return a; - } - } - function appendText(end){//has some bugs - if(end>start){ - var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer); - locator&&position(start); - domBuilder.characters(xt,0,end-start); - start = end - } - } - function position(p,m){ - while(p>=lineEnd && (m = linePattern.exec(source))){ - lineStart = m.index; - lineEnd = lineStart + m[0].length; - locator.lineNumber++; - //console.log('line++:',locator,startPos,endPos) - } - locator.columnNumber = p-lineStart+1; - } - var lineStart = 0; - var lineEnd = 0; - var linePattern = /.*(?:\r\n?|\n)|.*$/g - var locator = domBuilder.locator; - - var parseStack = [{currentNSMap:defaultNSMapCopy}] - var closeMap = {}; - var start = 0; - while(true){ - try{ - var tagStart = source.indexOf('<',start); - if(tagStart<0){ - if(!source.substr(start).match(/^\s*$/)){ - var doc = domBuilder.doc; - var text = doc.createTextNode(source.substr(start)); - doc.appendChild(text); - domBuilder.currentElement = text; - } - return; - } - if(tagStart>start){ - appendText(tagStart); - } - switch(source.charAt(tagStart+1)){ - case '/': - var end = source.indexOf('>',tagStart+3); - var tagName = source.substring(tagStart + 2, end).replace(/[ \t\n\r]+$/g, ''); - var config = parseStack.pop(); - if(end<0){ - - tagName = source.substring(tagStart+2).replace(/[\s<].*/,''); - errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName); - end = tagStart+1+tagName.length; - }else if(tagName.match(/\s - locator&&position(tagStart); - end = parseInstruction(source,tagStart,domBuilder); - break; - case '!':// start){ - start = end; - }else{ - //TODO: 这里有可能sax回退,有位置错误风险 - appendText(Math.max(tagStart,start)+1); - } - } -} -function copyLocator(f,t){ - t.lineNumber = f.lineNumber; - t.columnNumber = f.columnNumber; - return t; -} - -/** - * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack); - * @return end of the elementStartPart(end of elementEndPart for selfClosed el) - */ -function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){ - - /** - * @param {string} qname - * @param {string} value - * @param {number} startIndex - */ - function addAttribute(qname, value, startIndex) { - if (el.attributeNames.hasOwnProperty(qname)) { - errorHandler.fatalError('Attribute ' + qname + ' redefined') - } - el.addValue( - qname, - // @see https://www.w3.org/TR/xml/#AVNormalize - // since the xmldom sax parser does not "interpret" DTD the following is not implemented: - // - recursive replacement of (DTD) entity references - // - trimming and collapsing multiple spaces into a single one for attributes that are not of type CDATA - value.replace(/[\t\n\r]/g, ' ').replace(/&#?\w+;/g, entityReplacer), - startIndex - ) - } - var attrName; - var value; - var p = ++start; - var s = S_TAG;//status - while(true){ - var c = source.charAt(p); - switch(c){ - case '=': - if(s === S_ATTR){//attrName - attrName = source.slice(start,p); - s = S_EQ; - }else if(s === S_ATTR_SPACE){ - s = S_EQ; - }else{ - //fatalError: equal must after attrName or space after attrName - throw new Error('attribute equal must after attrName'); // No known test case - } - break; - case '\'': - case '"': - if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE - ){//equal - if(s === S_ATTR){ - errorHandler.warning('attribute value must after "="') - attrName = source.slice(start,p) - } - start = p+1; - p = source.indexOf(c,start) - if(p>0){ - value = source.slice(start, p); - addAttribute(attrName, value, start-1); - s = S_ATTR_END; - }else{ - //fatalError: no end quot match - throw new Error('attribute value no end \''+c+'\' match'); - } - }else if(s == S_ATTR_NOQUOT_VALUE){ - value = source.slice(start, p); - addAttribute(attrName, value, start); - errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!'); - start = p+1; - s = S_ATTR_END - }else{ - //fatalError: no equal before - throw new Error('attribute value must after "="'); // No known test case - } - break; - case '/': - switch(s){ - case S_TAG: - el.setTagName(source.slice(start,p)); - case S_ATTR_END: - case S_TAG_SPACE: - case S_TAG_CLOSE: - s =S_TAG_CLOSE; - el.closed = true; - case S_ATTR_NOQUOT_VALUE: - case S_ATTR: - break; - case S_ATTR_SPACE: - el.closed = true; - break; - //case S_EQ: - default: - throw new Error("attribute invalid close char('/')") // No known test case - } - break; - case ''://end document - errorHandler.error('unexpected end of input'); - if(s == S_TAG){ - el.setTagName(source.slice(start,p)); - } - return p; - case '>': - switch(s){ - case S_TAG: - el.setTagName(source.slice(start,p)); - case S_ATTR_END: - case S_TAG_SPACE: - case S_TAG_CLOSE: - break;//normal - case S_ATTR_NOQUOT_VALUE://Compatible state - case S_ATTR: - value = source.slice(start,p); - if(value.slice(-1) === '/'){ - el.closed = true; - value = value.slice(0,-1) - } - case S_ATTR_SPACE: - if(s === S_ATTR_SPACE){ - value = attrName; - } - if(s == S_ATTR_NOQUOT_VALUE){ - errorHandler.warning('attribute "'+value+'" missed quot(")!'); - addAttribute(attrName, value, start) - }else{ - if(!NAMESPACE.isHTML(currentNSMap['']) || !value.match(/^(?:disabled|checked|selected)$/i)){ - errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!') - } - addAttribute(value, value, start) - } - break; - case S_EQ: - throw new Error('attribute value missed!!'); - } -// console.log(tagName,tagNamePattern,tagNamePattern.test(tagName)) - return p; - /*xml space '\x20' | #x9 | #xD | #xA; */ - case '\u0080': - c = ' '; - default: - if(c<= ' '){//space - switch(s){ - case S_TAG: - el.setTagName(source.slice(start,p));//tagName - s = S_TAG_SPACE; - break; - case S_ATTR: - attrName = source.slice(start,p) - s = S_ATTR_SPACE; - break; - case S_ATTR_NOQUOT_VALUE: - var value = source.slice(start, p); - errorHandler.warning('attribute "'+value+'" missed quot(")!!'); - addAttribute(attrName, value, start) - case S_ATTR_END: - s = S_TAG_SPACE; - break; - //case S_TAG_SPACE: - //case S_EQ: - //case S_ATTR_SPACE: - // void();break; - //case S_TAG_CLOSE: - //ignore warning - } - }else{//not space -//S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE -//S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE - switch(s){ - //case S_TAG:void();break; - //case S_ATTR:void();break; - //case S_ATTR_NOQUOT_VALUE:void();break; - case S_ATTR_SPACE: - var tagName = el.tagName; - if (!NAMESPACE.isHTML(currentNSMap['']) || !attrName.match(/^(?:disabled|checked|selected)$/i)) { - errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!') - } - addAttribute(attrName, attrName, start); - start = p; - s = S_ATTR; - break; - case S_ATTR_END: - errorHandler.warning('attribute space is required"'+attrName+'"!!') - case S_TAG_SPACE: - s = S_ATTR; - start = p; - break; - case S_EQ: - s = S_ATTR_NOQUOT_VALUE; - start = p; - break; - case S_TAG_CLOSE: - throw new Error("elements closed character '/' and '>' must be connected to"); - } - } - }//end outer switch - //console.log('p++',p) - p++; - } -} -/** - * @return true if has new namespace define - */ -function appendElement(el,domBuilder,currentNSMap){ - var tagName = el.tagName; - var localNSMap = null; - //var currentNSMap = parseStack[parseStack.length-1].currentNSMap; - var i = el.length; - while(i--){ - var a = el[i]; - var qName = a.qName; - var value = a.value; - var nsp = qName.indexOf(':'); - if(nsp>0){ - var prefix = a.prefix = qName.slice(0,nsp); - var localName = qName.slice(nsp+1); - var nsPrefix = prefix === 'xmlns' && localName - }else{ - localName = qName; - prefix = null - nsPrefix = qName === 'xmlns' && '' - } - //can not set prefix,because prefix !== '' - a.localName = localName ; - //prefix == null for no ns prefix attribute - if(nsPrefix !== false){//hack!! - if(localNSMap == null){ - localNSMap = {} - //console.log(currentNSMap,0) - _copy(currentNSMap,currentNSMap={}) - //console.log(currentNSMap,1) - } - currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value; - a.uri = NAMESPACE.XMLNS - domBuilder.startPrefixMapping(nsPrefix, value) - } - } - var i = el.length; - while(i--){ - a = el[i]; - var prefix = a.prefix; - if(prefix){//no prefix attribute has no namespace - if(prefix === 'xml'){ - a.uri = NAMESPACE.XML; - }if(prefix !== 'xmlns'){ - a.uri = currentNSMap[prefix || ''] - - //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)} - } - } - } - var nsp = tagName.indexOf(':'); - if(nsp>0){ - prefix = el.prefix = tagName.slice(0,nsp); - localName = el.localName = tagName.slice(nsp+1); - }else{ - prefix = null;//important!! - localName = el.localName = tagName; - } - //no prefix element has default namespace - var ns = el.uri = currentNSMap[prefix || '']; - domBuilder.startElement(ns,localName,tagName,el); - //endPrefixMapping and startPrefixMapping have not any help for dom builder - //localNSMap = null - if(el.closed){ - domBuilder.endElement(ns,localName,tagName); - if(localNSMap){ - for (prefix in localNSMap) { - if (Object.prototype.hasOwnProperty.call(localNSMap, prefix)) { - domBuilder.endPrefixMapping(prefix); - } - } - } - }else{ - el.currentNSMap = currentNSMap; - el.localNSMap = localNSMap; - //parseStack.push(el); - return true; - } -} -function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){ - if(/^(?:script|textarea)$/i.test(tagName)){ - var elEndStart = source.indexOf('',elStartEnd); - var text = source.substring(elStartEnd+1,elEndStart); - if(/[&<]/.test(text)){ - if(/^script$/i.test(tagName)){ - //if(!/\]\]>/.test(text)){ - //lexHandler.startCDATA(); - domBuilder.characters(text,0,text.length); - //lexHandler.endCDATA(); - return elEndStart; - //} - }//}else{//text area - text = text.replace(/&#?\w+;/g,entityReplacer); - domBuilder.characters(text,0,text.length); - return elEndStart; - //} - - } - } - return elStartEnd+1; -} -function fixSelfClosed(source,elStartEnd,tagName,closeMap){ - //if(tagName in closeMap){ - var pos = closeMap[tagName]; - if(pos == null){ - //console.log(tagName) - pos = source.lastIndexOf('') - if(pos',start+4); - //append comment source.substring(4,end)// 0.001 (e-3), so adjust s so the rounding digits - // are indexed correctly. - if (r.e < e) --s; - n = n.slice(s - 3, s + 1); - - // The 4th rounding digit may be in error by -1 so if the 4 rounding digits - // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the - // iteration. - if (n == '9999' || !rep && n == '4999') { - - // On the first iteration only, check to see if rounding up gives the - // exact result as the nines may infinitely repeat. - if (!rep) { - round(t, t.e + DECIMAL_PLACES + 2, 0); - - if (t.times(t).eq(x)) { - r = t; - break; - } - } - - dp += 4; - s += 4; - rep = 1; - } else { - - // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact - // result. If not, then there are further digits and m will be truthy. - if (!+n || !+n.slice(1) && n.charAt(0) == '5') { - - // Truncate to the first rounding digit. - round(r, r.e + DECIMAL_PLACES + 2, 1); - m = !r.times(r).eq(x); - } - - break; - } - } - } - } - - return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); - }; - - - /* - * Return a string representing the value of this BigNumber in exponential notation and - * rounded using ROUNDING_MODE to dp fixed decimal places. - * - * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' - */ - P.toExponential = function (dp, rm) { - if (dp != null) { - intCheck(dp, 0, MAX); - dp++; - } - return format(this, dp, rm, 1); - }; - - - /* - * Return a string representing the value of this BigNumber in fixed-point notation rounding - * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. - * - * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', - * but e.g. (-0.00001).toFixed(0) is '-0'. - * - * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' - */ - P.toFixed = function (dp, rm) { - if (dp != null) { - intCheck(dp, 0, MAX); - dp = dp + this.e + 1; - } - return format(this, dp, rm); - }; - - - /* - * Return a string representing the value of this BigNumber in fixed-point notation rounded - * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties - * of the format or FORMAT object (see BigNumber.set). - * - * The formatting object may contain some or all of the properties shown below. - * - * FORMAT = { - * prefix: '', - * groupSize: 3, - * secondaryGroupSize: 0, - * groupSeparator: ',', - * decimalSeparator: '.', - * fractionGroupSize: 0, - * fractionGroupSeparator: '\xA0', // non-breaking space - * suffix: '' - * }; - * - * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * [format] {object} Formatting options. See FORMAT pbject above. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' - * '[BigNumber Error] Argument not an object: {format}' - */ - P.toFormat = function (dp, rm, format) { - var str, - x = this; - - if (format == null) { - if (dp != null && rm && typeof rm == 'object') { - format = rm; - rm = null; - } else if (dp && typeof dp == 'object') { - format = dp; - dp = rm = null; - } else { - format = FORMAT; - } - } else if (typeof format != 'object') { - throw Error - (bignumberError + 'Argument not an object: ' + format); - } - - str = x.toFixed(dp, rm); - - if (x.c) { - var i, - arr = str.split('.'), - g1 = +format.groupSize, - g2 = +format.secondaryGroupSize, - groupSeparator = format.groupSeparator || '', - intPart = arr[0], - fractionPart = arr[1], - isNeg = x.s < 0, - intDigits = isNeg ? intPart.slice(1) : intPart, - len = intDigits.length; - - if (g2) { - i = g1; - g1 = g2; - g2 = i; - len -= i; - } - - if (g1 > 0 && len > 0) { - i = len % g1 || g1; - intPart = intDigits.substr(0, i); - for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1); - if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); - if (isNeg) intPart = '-' + intPart; - } - - str = fractionPart - ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize) - ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), - '$&' + (format.fractionGroupSeparator || '')) - : fractionPart) - : intPart; - } - - return (format.prefix || '') + str + (format.suffix || ''); - }; - - - /* - * Return an array of two BigNumbers representing the value of this BigNumber as a simple - * fraction with an integer numerator and an integer denominator. - * The denominator will be a positive non-zero value less than or equal to the specified - * maximum denominator. If a maximum denominator is not specified, the denominator will be - * the lowest value necessary to represent the number exactly. - * - * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. - * - * '[BigNumber Error] Argument {not an integer|out of range} : {md}' - */ - P.toFraction = function (md) { - var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s, - x = this, - xc = x.c; - - if (md != null) { - n = new BigNumber(md); - - // Throw if md is less than one or is not an integer, unless it is Infinity. - if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { - throw Error - (bignumberError + 'Argument ' + - (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n)); - } - } - - if (!xc) return new BigNumber(x); - - d = new BigNumber(ONE); - n1 = d0 = new BigNumber(ONE); - d1 = n0 = new BigNumber(ONE); - s = coeffToString(xc); - - // Determine initial denominator. - // d is a power of 10 and the minimum max denominator that specifies the value exactly. - e = d.e = s.length - x.e - 1; - d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; - md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; - - exp = MAX_EXP; - MAX_EXP = 1 / 0; - n = new BigNumber(s); - - // n0 = d1 = 0 - n0.c[0] = 0; - - for (; ;) { - q = div(n, d, 0, 1); - d2 = d0.plus(q.times(d1)); - if (d2.comparedTo(md) == 1) break; - d0 = d1; - d1 = d2; - n1 = n0.plus(q.times(d2 = n1)); - n0 = d2; - d = n.minus(q.times(d2 = d)); - n = d2; - } - - d2 = div(md.minus(d0), d1, 0, 1); - n0 = n0.plus(d2.times(n1)); - d0 = d0.plus(d2.times(d1)); - n0.s = n1.s = x.s; - e = e * 2; - - // Determine which fraction is closer to x, n0/d0 or n1/d1 - r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( - div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0]; - - MAX_EXP = exp; - - return r; - }; - - - /* - * Return the value of this BigNumber converted to a number primitive. - */ - P.toNumber = function () { - return +valueOf(this); - }; - - - /* - * Return a string representing the value of this BigNumber rounded to sd significant digits - * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits - * necessary to represent the integer part of the value in fixed-point notation, then use - * exponential notation. - * - * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. - * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. - * - * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' - */ - P.toPrecision = function (sd, rm) { - if (sd != null) intCheck(sd, 1, MAX); - return format(this, sd, rm, 2); - }; - - - /* - * Return a string representing the value of this BigNumber in base b, or base 10 if b is - * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and - * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent - * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than - * TO_EXP_NEG, return exponential notation. - * - * [b] {number} Integer, 2 to ALPHABET.length inclusive. - * - * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' - */ - P.toString = function (b) { - var str, - n = this, - s = n.s, - e = n.e; - - // Infinity or NaN? - if (e === null) { - if (s) { - str = 'Infinity'; - if (s < 0) str = '-' + str; - } else { - str = 'NaN'; - } - } else { - if (b == null) { - str = e <= TO_EXP_NEG || e >= TO_EXP_POS - ? toExponential(coeffToString(n.c), e) - : toFixedPoint(coeffToString(n.c), e, '0'); - } else if (b === 10 && alphabetHasNormalDecimalDigits) { - n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE); - str = toFixedPoint(coeffToString(n.c), n.e, '0'); - } else { - intCheck(b, 2, ALPHABET.length, 'Base'); - str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true); - } - - if (s < 0 && n.c[0]) str = '-' + str; - } - - return str; - }; - - - /* - * Return as toString, but do not accept a base argument, and include the minus sign for - * negative zero. - */ - P.valueOf = P.toJSON = function () { - return valueOf(this); - }; - - - P._isBigNumber = true; - - if (configObject != null) BigNumber.set(configObject); - - return BigNumber; - } - - - // PRIVATE HELPER FUNCTIONS - - // These functions don't need access to variables, - // e.g. DECIMAL_PLACES, in the scope of the `clone` function above. - - - function bitFloor(n) { - var i = n | 0; - return n > 0 || n === i ? i : i - 1; - } - - - // Return a coefficient array as a string of base 10 digits. - function coeffToString(a) { - var s, z, - i = 1, - j = a.length, - r = a[0] + ''; - - for (; i < j;) { - s = a[i++] + ''; - z = LOG_BASE - s.length; - for (; z--; s = '0' + s); - r += s; - } - - // Determine trailing zeros. - for (j = r.length; r.charCodeAt(--j) === 48;); - - return r.slice(0, j + 1 || 1); - } - - - // Compare the value of BigNumbers x and y. - function compare(x, y) { - var a, b, - xc = x.c, - yc = y.c, - i = x.s, - j = y.s, - k = x.e, - l = y.e; - - // Either NaN? - if (!i || !j) return null; - - a = xc && !xc[0]; - b = yc && !yc[0]; - - // Either zero? - if (a || b) return a ? b ? 0 : -j : i; - - // Signs differ? - if (i != j) return i; - - a = i < 0; - b = k == l; - - // Either Infinity? - if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; - - // Compare exponents. - if (!b) return k > l ^ a ? 1 : -1; - - j = (k = xc.length) < (l = yc.length) ? k : l; - - // Compare digit by digit. - for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; - - // Compare lengths. - return k == l ? 0 : k > l ^ a ? 1 : -1; - } - - - /* - * Check that n is a primitive number, an integer, and in range, otherwise throw. - */ - function intCheck(n, min, max, name) { - if (n < min || n > max || n !== mathfloor(n)) { - throw Error - (bignumberError + (name || 'Argument') + (typeof n == 'number' - ? n < min || n > max ? ' out of range: ' : ' not an integer: ' - : ' not a primitive number: ') + String(n)); - } - } - - - // Assumes finite n. - function isOdd(n) { - var k = n.c.length - 1; - return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; - } - - - function toExponential(str, e) { - return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + - (e < 0 ? 'e' : 'e+') + e; - } - - - function toFixedPoint(str, e, z) { - var len, zs; - - // Negative exponent? - if (e < 0) { - - // Prepend zeros. - for (zs = z + '.'; ++e; zs += z); - str = zs + str; - - // Positive exponent - } else { - len = str.length; - - // Append zeros. - if (++e > len) { - for (zs = z, e -= len; --e; zs += z); - str += zs; - } else if (e < len) { - str = str.slice(0, e) + '.' + str.slice(e); - } - } - - return str; - } - - - // EXPORT - - - BigNumber = clone(); - BigNumber['default'] = BigNumber.BigNumber = BigNumber; - - // AMD. - if (typeof define == 'function' && define.amd) { - define(function () { return BigNumber; }); - - // Node.js and other environments that support module.exports. - } else if (typeof module != 'undefined' && module.exports) { - module.exports = BigNumber; - - // Browser. - } else { - if (!globalObject) { - globalObject = typeof self != 'undefined' && self ? self : window; - } - - globalObject.BigNumber = BigNumber; - } -})(this); diff --git a/claude-code-source/node_modules/buffer-equal-constant-time/index.js b/claude-code-source/node_modules/buffer-equal-constant-time/index.js deleted file mode 100644 index 5462c1f8..00000000 --- a/claude-code-source/node_modules/buffer-equal-constant-time/index.js +++ /dev/null @@ -1,41 +0,0 @@ -/*jshint node:true */ -'use strict'; -var Buffer = require('buffer').Buffer; // browserify -var SlowBuffer = require('buffer').SlowBuffer; - -module.exports = bufferEq; - -function bufferEq(a, b) { - - // shortcutting on type is necessary for correctness - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - return false; - } - - // buffer sizes should be well-known information, so despite this - // shortcutting, it doesn't leak any information about the *contents* of the - // buffers. - if (a.length !== b.length) { - return false; - } - - var c = 0; - for (var i = 0; i < a.length; i++) { - /*jshint bitwise:false */ - c |= a[i] ^ b[i]; // XOR - } - return c === 0; -} - -bufferEq.install = function() { - Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { - return bufferEq(this, that); - }; -}; - -var origBufEqual = Buffer.prototype.equal; -var origSlowBufEqual = SlowBuffer.prototype.equal; -bufferEq.restore = function() { - Buffer.prototype.equal = origBufEqual; - SlowBuffer.prototype.equal = origSlowBufEqual; -}; diff --git a/claude-code-source/node_modules/bun-types b/claude-code-source/node_modules/bun-types deleted file mode 120000 index 13d4287d..00000000 --- a/claude-code-source/node_modules/bun-types +++ /dev/null @@ -1 +0,0 @@ -.pnpm/bun-types@1.3.11/node_modules/bun-types \ No newline at end of file diff --git a/claude-code-source/node_modules/bundle-name/index.js b/claude-code-source/node_modules/bundle-name/index.js deleted file mode 100644 index 994815e6..00000000 --- a/claude-code-source/node_modules/bundle-name/index.js +++ /dev/null @@ -1,5 +0,0 @@ -import {runAppleScript} from 'run-applescript'; - -export default async function bundleName(bundleId) { - return runAppleScript(`tell application "Finder" to set app_path to application file id "${bundleId}" as string\ntell application "System Events" to get value of property list item "CFBundleName" of property list file (app_path & ":Contents:Info.plist")`); -} diff --git a/claude-code-source/node_modules/call-bind-apply-helpers/actualApply.js b/claude-code-source/node_modules/call-bind-apply-helpers/actualApply.js deleted file mode 100644 index ffa51355..00000000 --- a/claude-code-source/node_modules/call-bind-apply-helpers/actualApply.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -var bind = require('function-bind'); - -var $apply = require('./functionApply'); -var $call = require('./functionCall'); -var $reflectApply = require('./reflectApply'); - -/** @type {import('./actualApply')} */ -module.exports = $reflectApply || bind.call($call, $apply); diff --git a/claude-code-source/node_modules/call-bind-apply-helpers/functionApply.js b/claude-code-source/node_modules/call-bind-apply-helpers/functionApply.js deleted file mode 100644 index c71df9c2..00000000 --- a/claude-code-source/node_modules/call-bind-apply-helpers/functionApply.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; - -/** @type {import('./functionApply')} */ -module.exports = Function.prototype.apply; diff --git a/claude-code-source/node_modules/call-bind-apply-helpers/functionCall.js b/claude-code-source/node_modules/call-bind-apply-helpers/functionCall.js deleted file mode 100644 index 7a8d8735..00000000 --- a/claude-code-source/node_modules/call-bind-apply-helpers/functionCall.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; - -/** @type {import('./functionCall')} */ -module.exports = Function.prototype.call; diff --git a/claude-code-source/node_modules/call-bind-apply-helpers/index.js b/claude-code-source/node_modules/call-bind-apply-helpers/index.js deleted file mode 100644 index 2f6dab4c..00000000 --- a/claude-code-source/node_modules/call-bind-apply-helpers/index.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -var bind = require('function-bind'); -var $TypeError = require('es-errors/type'); - -var $call = require('./functionCall'); -var $actualApply = require('./actualApply'); - -/** @type {(args: [Function, thisArg?: unknown, ...args: unknown[]]) => Function} TODO FIXME, find a way to use import('.') */ -module.exports = function callBindBasic(args) { - if (args.length < 1 || typeof args[0] !== 'function') { - throw new $TypeError('a function is required'); - } - return $actualApply(bind, $call, args); -}; diff --git a/claude-code-source/node_modules/call-bind-apply-helpers/reflectApply.js b/claude-code-source/node_modules/call-bind-apply-helpers/reflectApply.js deleted file mode 100644 index 3d03caa6..00000000 --- a/claude-code-source/node_modules/call-bind-apply-helpers/reflectApply.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; - -/** @type {import('./reflectApply')} */ -module.exports = typeof Reflect !== 'undefined' && Reflect && Reflect.apply; diff --git a/claude-code-source/node_modules/chalk/source/index.js b/claude-code-source/node_modules/chalk/source/index.js deleted file mode 100644 index 8bc993da..00000000 --- a/claude-code-source/node_modules/chalk/source/index.js +++ /dev/null @@ -1,225 +0,0 @@ -import ansiStyles from '#ansi-styles'; -import supportsColor from '#supports-color'; -import { // eslint-disable-line import/order - stringReplaceAll, - stringEncaseCRLFWithFirstIndex, -} from './utilities.js'; - -const {stdout: stdoutColor, stderr: stderrColor} = supportsColor; - -const GENERATOR = Symbol('GENERATOR'); -const STYLER = Symbol('STYLER'); -const IS_EMPTY = Symbol('IS_EMPTY'); - -// `supportsColor.level` → `ansiStyles.color[name]` mapping -const levelMapping = [ - 'ansi', - 'ansi', - 'ansi256', - 'ansi16m', -]; - -const styles = Object.create(null); - -const applyOptions = (object, options = {}) => { - if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { - throw new Error('The `level` option should be an integer from 0 to 3'); - } - - // Detect level if not set manually - const colorLevel = stdoutColor ? stdoutColor.level : 0; - object.level = options.level === undefined ? colorLevel : options.level; -}; - -export class Chalk { - constructor(options) { - // eslint-disable-next-line no-constructor-return - return chalkFactory(options); - } -} - -const chalkFactory = options => { - const chalk = (...strings) => strings.join(' '); - applyOptions(chalk, options); - - Object.setPrototypeOf(chalk, createChalk.prototype); - - return chalk; -}; - -function createChalk(options) { - return chalkFactory(options); -} - -Object.setPrototypeOf(createChalk.prototype, Function.prototype); - -for (const [styleName, style] of Object.entries(ansiStyles)) { - styles[styleName] = { - get() { - const builder = createBuilder(this, createStyler(style.open, style.close, this[STYLER]), this[IS_EMPTY]); - Object.defineProperty(this, styleName, {value: builder}); - return builder; - }, - }; -} - -styles.visible = { - get() { - const builder = createBuilder(this, this[STYLER], true); - Object.defineProperty(this, 'visible', {value: builder}); - return builder; - }, -}; - -const getModelAnsi = (model, level, type, ...arguments_) => { - if (model === 'rgb') { - if (level === 'ansi16m') { - return ansiStyles[type].ansi16m(...arguments_); - } - - if (level === 'ansi256') { - return ansiStyles[type].ansi256(ansiStyles.rgbToAnsi256(...arguments_)); - } - - return ansiStyles[type].ansi(ansiStyles.rgbToAnsi(...arguments_)); - } - - if (model === 'hex') { - return getModelAnsi('rgb', level, type, ...ansiStyles.hexToRgb(...arguments_)); - } - - return ansiStyles[type][model](...arguments_); -}; - -const usedModels = ['rgb', 'hex', 'ansi256']; - -for (const model of usedModels) { - styles[model] = { - get() { - const {level} = this; - return function (...arguments_) { - const styler = createStyler(getModelAnsi(model, levelMapping[level], 'color', ...arguments_), ansiStyles.color.close, this[STYLER]); - return createBuilder(this, styler, this[IS_EMPTY]); - }; - }, - }; - - const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); - styles[bgModel] = { - get() { - const {level} = this; - return function (...arguments_) { - const styler = createStyler(getModelAnsi(model, levelMapping[level], 'bgColor', ...arguments_), ansiStyles.bgColor.close, this[STYLER]); - return createBuilder(this, styler, this[IS_EMPTY]); - }; - }, - }; -} - -const proto = Object.defineProperties(() => {}, { - ...styles, - level: { - enumerable: true, - get() { - return this[GENERATOR].level; - }, - set(level) { - this[GENERATOR].level = level; - }, - }, -}); - -const createStyler = (open, close, parent) => { - let openAll; - let closeAll; - if (parent === undefined) { - openAll = open; - closeAll = close; - } else { - openAll = parent.openAll + open; - closeAll = close + parent.closeAll; - } - - return { - open, - close, - openAll, - closeAll, - parent, - }; -}; - -const createBuilder = (self, _styler, _isEmpty) => { - // Single argument is hot path, implicit coercion is faster than anything - // eslint-disable-next-line no-implicit-coercion - const builder = (...arguments_) => applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); - - // We alter the prototype because we must return a function, but there is - // no way to create a function with a different prototype - Object.setPrototypeOf(builder, proto); - - builder[GENERATOR] = self; - builder[STYLER] = _styler; - builder[IS_EMPTY] = _isEmpty; - - return builder; -}; - -const applyStyle = (self, string) => { - if (self.level <= 0 || !string) { - return self[IS_EMPTY] ? '' : string; - } - - let styler = self[STYLER]; - - if (styler === undefined) { - return string; - } - - const {openAll, closeAll} = styler; - if (string.includes('\u001B')) { - while (styler !== undefined) { - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - string = stringReplaceAll(string, styler.close, styler.open); - - styler = styler.parent; - } - } - - // We can move both next actions out of loop, because remaining actions in loop won't have - // any/visible effect on parts we add here. Close the styling before a linebreak and reopen - // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 - const lfIndex = string.indexOf('\n'); - if (lfIndex !== -1) { - string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); - } - - return openAll + string + closeAll; -}; - -Object.defineProperties(createChalk.prototype, styles); - -const chalk = createChalk(); -export const chalkStderr = createChalk({level: stderrColor ? stderrColor.level : 0}); - -export { - modifierNames, - foregroundColorNames, - backgroundColorNames, - colorNames, - - // TODO: Remove these aliases in the next major version - modifierNames as modifiers, - foregroundColorNames as foregroundColors, - backgroundColorNames as backgroundColors, - colorNames as colors, -} from './vendor/ansi-styles/index.js'; - -export { - stdoutColor as supportsColor, - stderrColor as supportsColorStderr, -}; - -export default chalk; diff --git a/claude-code-source/node_modules/chalk/source/utilities.js b/claude-code-source/node_modules/chalk/source/utilities.js deleted file mode 100644 index 4366dee0..00000000 --- a/claude-code-source/node_modules/chalk/source/utilities.js +++ /dev/null @@ -1,33 +0,0 @@ -// TODO: When targeting Node.js 16, use `String.prototype.replaceAll`. -export function stringReplaceAll(string, substring, replacer) { - let index = string.indexOf(substring); - if (index === -1) { - return string; - } - - const substringLength = substring.length; - let endIndex = 0; - let returnValue = ''; - do { - returnValue += string.slice(endIndex, index) + substring + replacer; - endIndex = index + substringLength; - index = string.indexOf(substring, endIndex); - } while (index !== -1); - - returnValue += string.slice(endIndex); - return returnValue; -} - -export function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) { - let endIndex = 0; - let returnValue = ''; - do { - const gotCR = string[index - 1] === '\r'; - returnValue += string.slice(endIndex, (gotCR ? index - 1 : index)) + prefix + (gotCR ? '\r\n' : '\n') + postfix; - endIndex = index + 1; - index = string.indexOf('\n', endIndex); - } while (index !== -1); - - returnValue += string.slice(endIndex); - return returnValue; -} diff --git a/claude-code-source/node_modules/chalk/source/vendor/ansi-styles/index.js b/claude-code-source/node_modules/chalk/source/vendor/ansi-styles/index.js deleted file mode 100644 index eaa7bed6..00000000 --- a/claude-code-source/node_modules/chalk/source/vendor/ansi-styles/index.js +++ /dev/null @@ -1,223 +0,0 @@ -const ANSI_BACKGROUND_OFFSET = 10; - -const wrapAnsi16 = (offset = 0) => code => `\u001B[${code + offset}m`; - -const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; - -const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; - -const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - overline: [53, 55], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29], - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - - // Bright color - blackBright: [90, 39], - gray: [90, 39], // Alias of `blackBright` - grey: [90, 39], // Alias of `blackBright` - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39], - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - - // Bright color - bgBlackBright: [100, 49], - bgGray: [100, 49], // Alias of `bgBlackBright` - bgGrey: [100, 49], // Alias of `bgBlackBright` - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49], - }, -}; - -export const modifierNames = Object.keys(styles.modifier); -export const foregroundColorNames = Object.keys(styles.color); -export const backgroundColorNames = Object.keys(styles.bgColor); -export const colorNames = [...foregroundColorNames, ...backgroundColorNames]; - -function assembleStyles() { - const codes = new Map(); - - for (const [groupName, group] of Object.entries(styles)) { - for (const [styleName, style] of Object.entries(group)) { - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m`, - }; - - group[styleName] = styles[styleName]; - - codes.set(style[0], style[1]); - } - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false, - }); - } - - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false, - }); - - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; - - styles.color.ansi = wrapAnsi16(); - styles.color.ansi256 = wrapAnsi256(); - styles.color.ansi16m = wrapAnsi16m(); - styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET); - styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); - styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); - - // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js - Object.defineProperties(styles, { - rgbToAnsi256: { - value(red, green, blue) { - // We use the extended greyscale palette here, with the exception of - // black and white. normal palette only has 4 greyscale shades. - if (red === green && green === blue) { - if (red < 8) { - return 16; - } - - if (red > 248) { - return 231; - } - - return Math.round(((red - 8) / 247) * 24) + 232; - } - - return 16 - + (36 * Math.round(red / 255 * 5)) - + (6 * Math.round(green / 255 * 5)) - + Math.round(blue / 255 * 5); - }, - enumerable: false, - }, - hexToRgb: { - value(hex) { - const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); - if (!matches) { - return [0, 0, 0]; - } - - let [colorString] = matches; - - if (colorString.length === 3) { - colorString = [...colorString].map(character => character + character).join(''); - } - - const integer = Number.parseInt(colorString, 16); - - return [ - /* eslint-disable no-bitwise */ - (integer >> 16) & 0xFF, - (integer >> 8) & 0xFF, - integer & 0xFF, - /* eslint-enable no-bitwise */ - ]; - }, - enumerable: false, - }, - hexToAnsi256: { - value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), - enumerable: false, - }, - ansi256ToAnsi: { - value(code) { - if (code < 8) { - return 30 + code; - } - - if (code < 16) { - return 90 + (code - 8); - } - - let red; - let green; - let blue; - - if (code >= 232) { - red = (((code - 232) * 10) + 8) / 255; - green = red; - blue = red; - } else { - code -= 16; - - const remainder = code % 36; - - red = Math.floor(code / 36) / 5; - green = Math.floor(remainder / 6) / 5; - blue = (remainder % 6) / 5; - } - - const value = Math.max(red, green, blue) * 2; - - if (value === 0) { - return 30; - } - - // eslint-disable-next-line no-bitwise - let result = 30 + ((Math.round(blue) << 2) | (Math.round(green) << 1) | Math.round(red)); - - if (value === 2) { - result += 60; - } - - return result; - }, - enumerable: false, - }, - rgbToAnsi: { - value: (red, green, blue) => styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)), - enumerable: false, - }, - hexToAnsi: { - value: hex => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)), - enumerable: false, - }, - }); - - return styles; -} - -const ansiStyles = assembleStyles(); - -export default ansiStyles; diff --git a/claude-code-source/node_modules/chalk/source/vendor/supports-color/index.js b/claude-code-source/node_modules/chalk/source/vendor/supports-color/index.js deleted file mode 100644 index 13883726..00000000 --- a/claude-code-source/node_modules/chalk/source/vendor/supports-color/index.js +++ /dev/null @@ -1,182 +0,0 @@ -import process from 'node:process'; -import os from 'node:os'; -import tty from 'node:tty'; - -// From: https://github.com/sindresorhus/has-flag/blob/main/index.js -/// function hasFlag(flag, argv = globalThis.Deno?.args ?? process.argv) { -function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process.argv) { - const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf('--'); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); -} - -const {env} = process; - -let flagForceColor; -if ( - hasFlag('no-color') - || hasFlag('no-colors') - || hasFlag('color=false') - || hasFlag('color=never') -) { - flagForceColor = 0; -} else if ( - hasFlag('color') - || hasFlag('colors') - || hasFlag('color=true') - || hasFlag('color=always') -) { - flagForceColor = 1; -} - -function envForceColor() { - if ('FORCE_COLOR' in env) { - if (env.FORCE_COLOR === 'true') { - return 1; - } - - if (env.FORCE_COLOR === 'false') { - return 0; - } - - return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); - } -} - -function translateLevel(level) { - if (level === 0) { - return false; - } - - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3, - }; -} - -function _supportsColor(haveStream, {streamIsTTY, sniffFlags = true} = {}) { - const noFlagForceColor = envForceColor(); - if (noFlagForceColor !== undefined) { - flagForceColor = noFlagForceColor; - } - - const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; - - if (forceColor === 0) { - return 0; - } - - if (sniffFlags) { - if (hasFlag('color=16m') - || hasFlag('color=full') - || hasFlag('color=truecolor')) { - return 3; - } - - if (hasFlag('color=256')) { - return 2; - } - } - - // Check for Azure DevOps pipelines. - // Has to be above the `!streamIsTTY` check. - if ('TF_BUILD' in env && 'AGENT_NAME' in env) { - return 1; - } - - if (haveStream && !streamIsTTY && forceColor === undefined) { - return 0; - } - - const min = forceColor || 0; - - if (env.TERM === 'dumb') { - return min; - } - - if (process.platform === 'win32') { - // Windows 10 build 10586 is the first Windows release that supports 256 colors. - // Windows 10 build 14931 is the first release that supports 16m/TrueColor. - const osRelease = os.release().split('.'); - if ( - Number(osRelease[0]) >= 10 - && Number(osRelease[2]) >= 10_586 - ) { - return Number(osRelease[2]) >= 14_931 ? 3 : 2; - } - - return 1; - } - - if ('CI' in env) { - if (['GITHUB_ACTIONS', 'GITEA_ACTIONS', 'CIRCLECI'].some(key => key in env)) { - return 3; - } - - if (['TRAVIS', 'APPVEYOR', 'GITLAB_CI', 'BUILDKITE', 'DRONE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; - } - - return min; - } - - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } - - if (env.COLORTERM === 'truecolor') { - return 3; - } - - if (env.TERM === 'xterm-kitty') { - return 3; - } - - if ('TERM_PROGRAM' in env) { - const version = Number.parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - - switch (env.TERM_PROGRAM) { - case 'iTerm.app': { - return version >= 3 ? 3 : 2; - } - - case 'Apple_Terminal': { - return 2; - } - // No default - } - } - - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } - - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } - - if ('COLORTERM' in env) { - return 1; - } - - return min; -} - -export function createSupportsColor(stream, options = {}) { - const level = _supportsColor(stream, { - streamIsTTY: stream && stream.isTTY, - ...options, - }); - - return translateLevel(level); -} - -const supportsColor = { - stdout: createSupportsColor({isTTY: tty.isatty(1)}), - stderr: createSupportsColor({isTTY: tty.isatty(2)}), -}; - -export default supportsColor; diff --git a/claude-code-source/node_modules/chokidar/esm/handler.js b/claude-code-source/node_modules/chokidar/esm/handler.js deleted file mode 100644 index bbda0101..00000000 --- a/claude-code-source/node_modules/chokidar/esm/handler.js +++ /dev/null @@ -1,629 +0,0 @@ -import { watchFile, unwatchFile, watch as fs_watch } from 'fs'; -import { open, stat, lstat, realpath as fsrealpath } from 'fs/promises'; -import * as sysPath from 'path'; -import { type as osType } from 'os'; -export const STR_DATA = 'data'; -export const STR_END = 'end'; -export const STR_CLOSE = 'close'; -export const EMPTY_FN = () => { }; -export const IDENTITY_FN = (val) => val; -const pl = process.platform; -export const isWindows = pl === 'win32'; -export const isMacos = pl === 'darwin'; -export const isLinux = pl === 'linux'; -export const isFreeBSD = pl === 'freebsd'; -export const isIBMi = osType() === 'OS400'; -export const EVENTS = { - ALL: 'all', - READY: 'ready', - ADD: 'add', - CHANGE: 'change', - ADD_DIR: 'addDir', - UNLINK: 'unlink', - UNLINK_DIR: 'unlinkDir', - RAW: 'raw', - ERROR: 'error', -}; -const EV = EVENTS; -const THROTTLE_MODE_WATCH = 'watch'; -const statMethods = { lstat, stat }; -const KEY_LISTENERS = 'listeners'; -const KEY_ERR = 'errHandlers'; -const KEY_RAW = 'rawEmitters'; -const HANDLER_KEYS = [KEY_LISTENERS, KEY_ERR, KEY_RAW]; -// prettier-ignore -const binaryExtensions = new Set([ - '3dm', '3ds', '3g2', '3gp', '7z', 'a', 'aac', 'adp', 'afdesign', 'afphoto', 'afpub', 'ai', - 'aif', 'aiff', 'alz', 'ape', 'apk', 'appimage', 'ar', 'arj', 'asf', 'au', 'avi', - 'bak', 'baml', 'bh', 'bin', 'bk', 'bmp', 'btif', 'bz2', 'bzip2', - 'cab', 'caf', 'cgm', 'class', 'cmx', 'cpio', 'cr2', 'cur', 'dat', 'dcm', 'deb', 'dex', 'djvu', - 'dll', 'dmg', 'dng', 'doc', 'docm', 'docx', 'dot', 'dotm', 'dra', 'DS_Store', 'dsk', 'dts', - 'dtshd', 'dvb', 'dwg', 'dxf', - 'ecelp4800', 'ecelp7470', 'ecelp9600', 'egg', 'eol', 'eot', 'epub', 'exe', - 'f4v', 'fbs', 'fh', 'fla', 'flac', 'flatpak', 'fli', 'flv', 'fpx', 'fst', 'fvt', - 'g3', 'gh', 'gif', 'graffle', 'gz', 'gzip', - 'h261', 'h263', 'h264', 'icns', 'ico', 'ief', 'img', 'ipa', 'iso', - 'jar', 'jpeg', 'jpg', 'jpgv', 'jpm', 'jxr', 'key', 'ktx', - 'lha', 'lib', 'lvp', 'lz', 'lzh', 'lzma', 'lzo', - 'm3u', 'm4a', 'm4v', 'mar', 'mdi', 'mht', 'mid', 'midi', 'mj2', 'mka', 'mkv', 'mmr', 'mng', - 'mobi', 'mov', 'movie', 'mp3', - 'mp4', 'mp4a', 'mpeg', 'mpg', 'mpga', 'mxu', - 'nef', 'npx', 'numbers', 'nupkg', - 'o', 'odp', 'ods', 'odt', 'oga', 'ogg', 'ogv', 'otf', 'ott', - 'pages', 'pbm', 'pcx', 'pdb', 'pdf', 'pea', 'pgm', 'pic', 'png', 'pnm', 'pot', 'potm', - 'potx', 'ppa', 'ppam', - 'ppm', 'pps', 'ppsm', 'ppsx', 'ppt', 'pptm', 'pptx', 'psd', 'pya', 'pyc', 'pyo', 'pyv', - 'qt', - 'rar', 'ras', 'raw', 'resources', 'rgb', 'rip', 'rlc', 'rmf', 'rmvb', 'rpm', 'rtf', 'rz', - 's3m', 's7z', 'scpt', 'sgi', 'shar', 'snap', 'sil', 'sketch', 'slk', 'smv', 'snk', 'so', - 'stl', 'suo', 'sub', 'swf', - 'tar', 'tbz', 'tbz2', 'tga', 'tgz', 'thmx', 'tif', 'tiff', 'tlz', 'ttc', 'ttf', 'txz', - 'udf', 'uvh', 'uvi', 'uvm', 'uvp', 'uvs', 'uvu', - 'viv', 'vob', - 'war', 'wav', 'wax', 'wbmp', 'wdp', 'weba', 'webm', 'webp', 'whl', 'wim', 'wm', 'wma', - 'wmv', 'wmx', 'woff', 'woff2', 'wrm', 'wvx', - 'xbm', 'xif', 'xla', 'xlam', 'xls', 'xlsb', 'xlsm', 'xlsx', 'xlt', 'xltm', 'xltx', 'xm', - 'xmind', 'xpi', 'xpm', 'xwd', 'xz', - 'z', 'zip', 'zipx', -]); -const isBinaryPath = (filePath) => binaryExtensions.has(sysPath.extname(filePath).slice(1).toLowerCase()); -// TODO: emit errors properly. Example: EMFILE on Macos. -const foreach = (val, fn) => { - if (val instanceof Set) { - val.forEach(fn); - } - else { - fn(val); - } -}; -const addAndConvert = (main, prop, item) => { - let container = main[prop]; - if (!(container instanceof Set)) { - main[prop] = container = new Set([container]); - } - container.add(item); -}; -const clearItem = (cont) => (key) => { - const set = cont[key]; - if (set instanceof Set) { - set.clear(); - } - else { - delete cont[key]; - } -}; -const delFromSet = (main, prop, item) => { - const container = main[prop]; - if (container instanceof Set) { - container.delete(item); - } - else if (container === item) { - delete main[prop]; - } -}; -const isEmptySet = (val) => (val instanceof Set ? val.size === 0 : !val); -const FsWatchInstances = new Map(); -/** - * Instantiates the fs_watch interface - * @param path to be watched - * @param options to be passed to fs_watch - * @param listener main event handler - * @param errHandler emits info about errors - * @param emitRaw emits raw event data - * @returns {NativeFsWatcher} - */ -function createFsWatchInstance(path, options, listener, errHandler, emitRaw) { - const handleEvent = (rawEvent, evPath) => { - listener(path); - emitRaw(rawEvent, evPath, { watchedPath: path }); - // emit based on events occurring for files from a directory's watcher in - // case the file's watcher misses it (and rely on throttling to de-dupe) - if (evPath && path !== evPath) { - fsWatchBroadcast(sysPath.resolve(path, evPath), KEY_LISTENERS, sysPath.join(path, evPath)); - } - }; - try { - return fs_watch(path, { - persistent: options.persistent, - }, handleEvent); - } - catch (error) { - errHandler(error); - return undefined; - } -} -/** - * Helper for passing fs_watch event data to a collection of listeners - * @param fullPath absolute path bound to fs_watch instance - */ -const fsWatchBroadcast = (fullPath, listenerType, val1, val2, val3) => { - const cont = FsWatchInstances.get(fullPath); - if (!cont) - return; - foreach(cont[listenerType], (listener) => { - listener(val1, val2, val3); - }); -}; -/** - * Instantiates the fs_watch interface or binds listeners - * to an existing one covering the same file system entry - * @param path - * @param fullPath absolute path - * @param options to be passed to fs_watch - * @param handlers container for event listener functions - */ -const setFsWatchListener = (path, fullPath, options, handlers) => { - const { listener, errHandler, rawEmitter } = handlers; - let cont = FsWatchInstances.get(fullPath); - let watcher; - if (!options.persistent) { - watcher = createFsWatchInstance(path, options, listener, errHandler, rawEmitter); - if (!watcher) - return; - return watcher.close.bind(watcher); - } - if (cont) { - addAndConvert(cont, KEY_LISTENERS, listener); - addAndConvert(cont, KEY_ERR, errHandler); - addAndConvert(cont, KEY_RAW, rawEmitter); - } - else { - watcher = createFsWatchInstance(path, options, fsWatchBroadcast.bind(null, fullPath, KEY_LISTENERS), errHandler, // no need to use broadcast here - fsWatchBroadcast.bind(null, fullPath, KEY_RAW)); - if (!watcher) - return; - watcher.on(EV.ERROR, async (error) => { - const broadcastErr = fsWatchBroadcast.bind(null, fullPath, KEY_ERR); - if (cont) - cont.watcherUnusable = true; // documented since Node 10.4.1 - // Workaround for https://github.com/joyent/node/issues/4337 - if (isWindows && error.code === 'EPERM') { - try { - const fd = await open(path, 'r'); - await fd.close(); - broadcastErr(error); - } - catch (err) { - // do nothing - } - } - else { - broadcastErr(error); - } - }); - cont = { - listeners: listener, - errHandlers: errHandler, - rawEmitters: rawEmitter, - watcher, - }; - FsWatchInstances.set(fullPath, cont); - } - // const index = cont.listeners.indexOf(listener); - // removes this instance's listeners and closes the underlying fs_watch - // instance if there are no more listeners left - return () => { - delFromSet(cont, KEY_LISTENERS, listener); - delFromSet(cont, KEY_ERR, errHandler); - delFromSet(cont, KEY_RAW, rawEmitter); - if (isEmptySet(cont.listeners)) { - // Check to protect against issue gh-730. - // if (cont.watcherUnusable) { - cont.watcher.close(); - // } - FsWatchInstances.delete(fullPath); - HANDLER_KEYS.forEach(clearItem(cont)); - // @ts-ignore - cont.watcher = undefined; - Object.freeze(cont); - } - }; -}; -// fs_watchFile helpers -// object to hold per-process fs_watchFile instances -// (may be shared across chokidar FSWatcher instances) -const FsWatchFileInstances = new Map(); -/** - * Instantiates the fs_watchFile interface or binds listeners - * to an existing one covering the same file system entry - * @param path to be watched - * @param fullPath absolute path - * @param options options to be passed to fs_watchFile - * @param handlers container for event listener functions - * @returns closer - */ -const setFsWatchFileListener = (path, fullPath, options, handlers) => { - const { listener, rawEmitter } = handlers; - let cont = FsWatchFileInstances.get(fullPath); - // let listeners = new Set(); - // let rawEmitters = new Set(); - const copts = cont && cont.options; - if (copts && (copts.persistent < options.persistent || copts.interval > options.interval)) { - // "Upgrade" the watcher to persistence or a quicker interval. - // This creates some unlikely edge case issues if the user mixes - // settings in a very weird way, but solving for those cases - // doesn't seem worthwhile for the added complexity. - // listeners = cont.listeners; - // rawEmitters = cont.rawEmitters; - unwatchFile(fullPath); - cont = undefined; - } - if (cont) { - addAndConvert(cont, KEY_LISTENERS, listener); - addAndConvert(cont, KEY_RAW, rawEmitter); - } - else { - // TODO - // listeners.add(listener); - // rawEmitters.add(rawEmitter); - cont = { - listeners: listener, - rawEmitters: rawEmitter, - options, - watcher: watchFile(fullPath, options, (curr, prev) => { - foreach(cont.rawEmitters, (rawEmitter) => { - rawEmitter(EV.CHANGE, fullPath, { curr, prev }); - }); - const currmtime = curr.mtimeMs; - if (curr.size !== prev.size || currmtime > prev.mtimeMs || currmtime === 0) { - foreach(cont.listeners, (listener) => listener(path, curr)); - } - }), - }; - FsWatchFileInstances.set(fullPath, cont); - } - // const index = cont.listeners.indexOf(listener); - // Removes this instance's listeners and closes the underlying fs_watchFile - // instance if there are no more listeners left. - return () => { - delFromSet(cont, KEY_LISTENERS, listener); - delFromSet(cont, KEY_RAW, rawEmitter); - if (isEmptySet(cont.listeners)) { - FsWatchFileInstances.delete(fullPath); - unwatchFile(fullPath); - cont.options = cont.watcher = undefined; - Object.freeze(cont); - } - }; -}; -/** - * @mixin - */ -export class NodeFsHandler { - constructor(fsW) { - this.fsw = fsW; - this._boundHandleError = (error) => fsW._handleError(error); - } - /** - * Watch file for changes with fs_watchFile or fs_watch. - * @param path to file or dir - * @param listener on fs change - * @returns closer for the watcher instance - */ - _watchWithNodeFs(path, listener) { - const opts = this.fsw.options; - const directory = sysPath.dirname(path); - const basename = sysPath.basename(path); - const parent = this.fsw._getWatchedDir(directory); - parent.add(basename); - const absolutePath = sysPath.resolve(path); - const options = { - persistent: opts.persistent, - }; - if (!listener) - listener = EMPTY_FN; - let closer; - if (opts.usePolling) { - const enableBin = opts.interval !== opts.binaryInterval; - options.interval = enableBin && isBinaryPath(basename) ? opts.binaryInterval : opts.interval; - closer = setFsWatchFileListener(path, absolutePath, options, { - listener, - rawEmitter: this.fsw._emitRaw, - }); - } - else { - closer = setFsWatchListener(path, absolutePath, options, { - listener, - errHandler: this._boundHandleError, - rawEmitter: this.fsw._emitRaw, - }); - } - return closer; - } - /** - * Watch a file and emit add event if warranted. - * @returns closer for the watcher instance - */ - _handleFile(file, stats, initialAdd) { - if (this.fsw.closed) { - return; - } - const dirname = sysPath.dirname(file); - const basename = sysPath.basename(file); - const parent = this.fsw._getWatchedDir(dirname); - // stats is always present - let prevStats = stats; - // if the file is already being watched, do nothing - if (parent.has(basename)) - return; - const listener = async (path, newStats) => { - if (!this.fsw._throttle(THROTTLE_MODE_WATCH, file, 5)) - return; - if (!newStats || newStats.mtimeMs === 0) { - try { - const newStats = await stat(file); - if (this.fsw.closed) - return; - // Check that change event was not fired because of changed only accessTime. - const at = newStats.atimeMs; - const mt = newStats.mtimeMs; - if (!at || at <= mt || mt !== prevStats.mtimeMs) { - this.fsw._emit(EV.CHANGE, file, newStats); - } - if ((isMacos || isLinux || isFreeBSD) && prevStats.ino !== newStats.ino) { - this.fsw._closeFile(path); - prevStats = newStats; - const closer = this._watchWithNodeFs(file, listener); - if (closer) - this.fsw._addPathCloser(path, closer); - } - else { - prevStats = newStats; - } - } - catch (error) { - // Fix issues where mtime is null but file is still present - this.fsw._remove(dirname, basename); - } - // add is about to be emitted if file not already tracked in parent - } - else if (parent.has(basename)) { - // Check that change event was not fired because of changed only accessTime. - const at = newStats.atimeMs; - const mt = newStats.mtimeMs; - if (!at || at <= mt || mt !== prevStats.mtimeMs) { - this.fsw._emit(EV.CHANGE, file, newStats); - } - prevStats = newStats; - } - }; - // kick off the watcher - const closer = this._watchWithNodeFs(file, listener); - // emit an add event if we're supposed to - if (!(initialAdd && this.fsw.options.ignoreInitial) && this.fsw._isntIgnored(file)) { - if (!this.fsw._throttle(EV.ADD, file, 0)) - return; - this.fsw._emit(EV.ADD, file, stats); - } - return closer; - } - /** - * Handle symlinks encountered while reading a dir. - * @param entry returned by readdirp - * @param directory path of dir being read - * @param path of this item - * @param item basename of this item - * @returns true if no more processing is needed for this entry. - */ - async _handleSymlink(entry, directory, path, item) { - if (this.fsw.closed) { - return; - } - const full = entry.fullPath; - const dir = this.fsw._getWatchedDir(directory); - if (!this.fsw.options.followSymlinks) { - // watch symlink directly (don't follow) and detect changes - this.fsw._incrReadyCount(); - let linkPath; - try { - linkPath = await fsrealpath(path); - } - catch (e) { - this.fsw._emitReady(); - return true; - } - if (this.fsw.closed) - return; - if (dir.has(item)) { - if (this.fsw._symlinkPaths.get(full) !== linkPath) { - this.fsw._symlinkPaths.set(full, linkPath); - this.fsw._emit(EV.CHANGE, path, entry.stats); - } - } - else { - dir.add(item); - this.fsw._symlinkPaths.set(full, linkPath); - this.fsw._emit(EV.ADD, path, entry.stats); - } - this.fsw._emitReady(); - return true; - } - // don't follow the same symlink more than once - if (this.fsw._symlinkPaths.has(full)) { - return true; - } - this.fsw._symlinkPaths.set(full, true); - } - _handleRead(directory, initialAdd, wh, target, dir, depth, throttler) { - // Normalize the directory name on Windows - directory = sysPath.join(directory, ''); - throttler = this.fsw._throttle('readdir', directory, 1000); - if (!throttler) - return; - const previous = this.fsw._getWatchedDir(wh.path); - const current = new Set(); - let stream = this.fsw._readdirp(directory, { - fileFilter: (entry) => wh.filterPath(entry), - directoryFilter: (entry) => wh.filterDir(entry), - }); - if (!stream) - return; - stream - .on(STR_DATA, async (entry) => { - if (this.fsw.closed) { - stream = undefined; - return; - } - const item = entry.path; - let path = sysPath.join(directory, item); - current.add(item); - if (entry.stats.isSymbolicLink() && - (await this._handleSymlink(entry, directory, path, item))) { - return; - } - if (this.fsw.closed) { - stream = undefined; - return; - } - // Files that present in current directory snapshot - // but absent in previous are added to watch list and - // emit `add` event. - if (item === target || (!target && !previous.has(item))) { - this.fsw._incrReadyCount(); - // ensure relativeness of path is preserved in case of watcher reuse - path = sysPath.join(dir, sysPath.relative(dir, path)); - this._addToNodeFs(path, initialAdd, wh, depth + 1); - } - }) - .on(EV.ERROR, this._boundHandleError); - return new Promise((resolve, reject) => { - if (!stream) - return reject(); - stream.once(STR_END, () => { - if (this.fsw.closed) { - stream = undefined; - return; - } - const wasThrottled = throttler ? throttler.clear() : false; - resolve(undefined); - // Files that absent in current directory snapshot - // but present in previous emit `remove` event - // and are removed from @watched[directory]. - previous - .getChildren() - .filter((item) => { - return item !== directory && !current.has(item); - }) - .forEach((item) => { - this.fsw._remove(directory, item); - }); - stream = undefined; - // one more time for any missed in case changes came in extremely quickly - if (wasThrottled) - this._handleRead(directory, false, wh, target, dir, depth, throttler); - }); - }); - } - /** - * Read directory to add / remove files from `@watched` list and re-read it on change. - * @param dir fs path - * @param stats - * @param initialAdd - * @param depth relative to user-supplied path - * @param target child path targeted for watch - * @param wh Common watch helpers for this path - * @param realpath - * @returns closer for the watcher instance. - */ - async _handleDir(dir, stats, initialAdd, depth, target, wh, realpath) { - const parentDir = this.fsw._getWatchedDir(sysPath.dirname(dir)); - const tracked = parentDir.has(sysPath.basename(dir)); - if (!(initialAdd && this.fsw.options.ignoreInitial) && !target && !tracked) { - this.fsw._emit(EV.ADD_DIR, dir, stats); - } - // ensure dir is tracked (harmless if redundant) - parentDir.add(sysPath.basename(dir)); - this.fsw._getWatchedDir(dir); - let throttler; - let closer; - const oDepth = this.fsw.options.depth; - if ((oDepth == null || depth <= oDepth) && !this.fsw._symlinkPaths.has(realpath)) { - if (!target) { - await this._handleRead(dir, initialAdd, wh, target, dir, depth, throttler); - if (this.fsw.closed) - return; - } - closer = this._watchWithNodeFs(dir, (dirPath, stats) => { - // if current directory is removed, do nothing - if (stats && stats.mtimeMs === 0) - return; - this._handleRead(dirPath, false, wh, target, dir, depth, throttler); - }); - } - return closer; - } - /** - * Handle added file, directory, or glob pattern. - * Delegates call to _handleFile / _handleDir after checks. - * @param path to file or ir - * @param initialAdd was the file added at watch instantiation? - * @param priorWh depth relative to user-supplied path - * @param depth Child path actually targeted for watch - * @param target Child path actually targeted for watch - */ - async _addToNodeFs(path, initialAdd, priorWh, depth, target) { - const ready = this.fsw._emitReady; - if (this.fsw._isIgnored(path) || this.fsw.closed) { - ready(); - return false; - } - const wh = this.fsw._getWatchHelpers(path); - if (priorWh) { - wh.filterPath = (entry) => priorWh.filterPath(entry); - wh.filterDir = (entry) => priorWh.filterDir(entry); - } - // evaluate what is at the path we're being asked to watch - try { - const stats = await statMethods[wh.statMethod](wh.watchPath); - if (this.fsw.closed) - return; - if (this.fsw._isIgnored(wh.watchPath, stats)) { - ready(); - return false; - } - const follow = this.fsw.options.followSymlinks; - let closer; - if (stats.isDirectory()) { - const absPath = sysPath.resolve(path); - const targetPath = follow ? await fsrealpath(path) : path; - if (this.fsw.closed) - return; - closer = await this._handleDir(wh.watchPath, stats, initialAdd, depth, target, wh, targetPath); - if (this.fsw.closed) - return; - // preserve this symlink's target path - if (absPath !== targetPath && targetPath !== undefined) { - this.fsw._symlinkPaths.set(absPath, targetPath); - } - } - else if (stats.isSymbolicLink()) { - const targetPath = follow ? await fsrealpath(path) : path; - if (this.fsw.closed) - return; - const parent = sysPath.dirname(wh.watchPath); - this.fsw._getWatchedDir(parent).add(wh.watchPath); - this.fsw._emit(EV.ADD, wh.watchPath, stats); - closer = await this._handleDir(parent, stats, initialAdd, depth, path, wh, targetPath); - if (this.fsw.closed) - return; - // preserve this symlink's target path - if (targetPath !== undefined) { - this.fsw._symlinkPaths.set(sysPath.resolve(path), targetPath); - } - } - else { - closer = this._handleFile(wh.watchPath, stats, initialAdd); - } - ready(); - if (closer) - this.fsw._addPathCloser(path, closer); - return false; - } - catch (error) { - if (this.fsw._handleError(error)) { - ready(); - return path; - } - } - } -} diff --git a/claude-code-source/node_modules/chokidar/esm/index.js b/claude-code-source/node_modules/chokidar/esm/index.js deleted file mode 100644 index 1c80a40c..00000000 --- a/claude-code-source/node_modules/chokidar/esm/index.js +++ /dev/null @@ -1,798 +0,0 @@ -/*! chokidar - MIT License (c) 2012 Paul Miller (paulmillr.com) */ -import { stat as statcb } from 'fs'; -import { stat, readdir } from 'fs/promises'; -import { EventEmitter } from 'events'; -import * as sysPath from 'path'; -import { readdirp } from 'readdirp'; -import { NodeFsHandler, EVENTS as EV, isWindows, isIBMi, EMPTY_FN, STR_CLOSE, STR_END, } from './handler.js'; -const SLASH = '/'; -const SLASH_SLASH = '//'; -const ONE_DOT = '.'; -const TWO_DOTS = '..'; -const STRING_TYPE = 'string'; -const BACK_SLASH_RE = /\\/g; -const DOUBLE_SLASH_RE = /\/\//; -const DOT_RE = /\..*\.(sw[px])$|~$|\.subl.*\.tmp/; -const REPLACER_RE = /^\.[/\\]/; -function arrify(item) { - return Array.isArray(item) ? item : [item]; -} -const isMatcherObject = (matcher) => typeof matcher === 'object' && matcher !== null && !(matcher instanceof RegExp); -function createPattern(matcher) { - if (typeof matcher === 'function') - return matcher; - if (typeof matcher === 'string') - return (string) => matcher === string; - if (matcher instanceof RegExp) - return (string) => matcher.test(string); - if (typeof matcher === 'object' && matcher !== null) { - return (string) => { - if (matcher.path === string) - return true; - if (matcher.recursive) { - const relative = sysPath.relative(matcher.path, string); - if (!relative) { - return false; - } - return !relative.startsWith('..') && !sysPath.isAbsolute(relative); - } - return false; - }; - } - return () => false; -} -function normalizePath(path) { - if (typeof path !== 'string') - throw new Error('string expected'); - path = sysPath.normalize(path); - path = path.replace(/\\/g, '/'); - let prepend = false; - if (path.startsWith('//')) - prepend = true; - const DOUBLE_SLASH_RE = /\/\//; - while (path.match(DOUBLE_SLASH_RE)) - path = path.replace(DOUBLE_SLASH_RE, '/'); - if (prepend) - path = '/' + path; - return path; -} -function matchPatterns(patterns, testString, stats) { - const path = normalizePath(testString); - for (let index = 0; index < patterns.length; index++) { - const pattern = patterns[index]; - if (pattern(path, stats)) { - return true; - } - } - return false; -} -function anymatch(matchers, testString) { - if (matchers == null) { - throw new TypeError('anymatch: specify first argument'); - } - // Early cache for matchers. - const matchersArray = arrify(matchers); - const patterns = matchersArray.map((matcher) => createPattern(matcher)); - if (testString == null) { - return (testString, stats) => { - return matchPatterns(patterns, testString, stats); - }; - } - return matchPatterns(patterns, testString); -} -const unifyPaths = (paths_) => { - const paths = arrify(paths_).flat(); - if (!paths.every((p) => typeof p === STRING_TYPE)) { - throw new TypeError(`Non-string provided as watch path: ${paths}`); - } - return paths.map(normalizePathToUnix); -}; -// If SLASH_SLASH occurs at the beginning of path, it is not replaced -// because "//StoragePC/DrivePool/Movies" is a valid network path -const toUnix = (string) => { - let str = string.replace(BACK_SLASH_RE, SLASH); - let prepend = false; - if (str.startsWith(SLASH_SLASH)) { - prepend = true; - } - while (str.match(DOUBLE_SLASH_RE)) { - str = str.replace(DOUBLE_SLASH_RE, SLASH); - } - if (prepend) { - str = SLASH + str; - } - return str; -}; -// Our version of upath.normalize -// TODO: this is not equal to path-normalize module - investigate why -const normalizePathToUnix = (path) => toUnix(sysPath.normalize(toUnix(path))); -// TODO: refactor -const normalizeIgnored = (cwd = '') => (path) => { - if (typeof path === 'string') { - return normalizePathToUnix(sysPath.isAbsolute(path) ? path : sysPath.join(cwd, path)); - } - else { - return path; - } -}; -const getAbsolutePath = (path, cwd) => { - if (sysPath.isAbsolute(path)) { - return path; - } - return sysPath.join(cwd, path); -}; -const EMPTY_SET = Object.freeze(new Set()); -/** - * Directory entry. - */ -class DirEntry { - constructor(dir, removeWatcher) { - this.path = dir; - this._removeWatcher = removeWatcher; - this.items = new Set(); - } - add(item) { - const { items } = this; - if (!items) - return; - if (item !== ONE_DOT && item !== TWO_DOTS) - items.add(item); - } - async remove(item) { - const { items } = this; - if (!items) - return; - items.delete(item); - if (items.size > 0) - return; - const dir = this.path; - try { - await readdir(dir); - } - catch (err) { - if (this._removeWatcher) { - this._removeWatcher(sysPath.dirname(dir), sysPath.basename(dir)); - } - } - } - has(item) { - const { items } = this; - if (!items) - return; - return items.has(item); - } - getChildren() { - const { items } = this; - if (!items) - return []; - return [...items.values()]; - } - dispose() { - this.items.clear(); - this.path = ''; - this._removeWatcher = EMPTY_FN; - this.items = EMPTY_SET; - Object.freeze(this); - } -} -const STAT_METHOD_F = 'stat'; -const STAT_METHOD_L = 'lstat'; -export class WatchHelper { - constructor(path, follow, fsw) { - this.fsw = fsw; - const watchPath = path; - this.path = path = path.replace(REPLACER_RE, ''); - this.watchPath = watchPath; - this.fullWatchPath = sysPath.resolve(watchPath); - this.dirParts = []; - this.dirParts.forEach((parts) => { - if (parts.length > 1) - parts.pop(); - }); - this.followSymlinks = follow; - this.statMethod = follow ? STAT_METHOD_F : STAT_METHOD_L; - } - entryPath(entry) { - return sysPath.join(this.watchPath, sysPath.relative(this.watchPath, entry.fullPath)); - } - filterPath(entry) { - const { stats } = entry; - if (stats && stats.isSymbolicLink()) - return this.filterDir(entry); - const resolvedPath = this.entryPath(entry); - // TODO: what if stats is undefined? remove ! - return this.fsw._isntIgnored(resolvedPath, stats) && this.fsw._hasReadPermissions(stats); - } - filterDir(entry) { - return this.fsw._isntIgnored(this.entryPath(entry), entry.stats); - } -} -/** - * Watches files & directories for changes. Emitted events: - * `add`, `addDir`, `change`, `unlink`, `unlinkDir`, `all`, `error` - * - * new FSWatcher() - * .add(directories) - * .on('add', path => log('File', path, 'was added')) - */ -export class FSWatcher extends EventEmitter { - // Not indenting methods for history sake; for now. - constructor(_opts = {}) { - super(); - this.closed = false; - this._closers = new Map(); - this._ignoredPaths = new Set(); - this._throttled = new Map(); - this._streams = new Set(); - this._symlinkPaths = new Map(); - this._watched = new Map(); - this._pendingWrites = new Map(); - this._pendingUnlinks = new Map(); - this._readyCount = 0; - this._readyEmitted = false; - const awf = _opts.awaitWriteFinish; - const DEF_AWF = { stabilityThreshold: 2000, pollInterval: 100 }; - const opts = { - // Defaults - persistent: true, - ignoreInitial: false, - ignorePermissionErrors: false, - interval: 100, - binaryInterval: 300, - followSymlinks: true, - usePolling: false, - // useAsync: false, - atomic: true, // NOTE: overwritten later (depends on usePolling) - ..._opts, - // Change format - ignored: _opts.ignored ? arrify(_opts.ignored) : arrify([]), - awaitWriteFinish: awf === true ? DEF_AWF : typeof awf === 'object' ? { ...DEF_AWF, ...awf } : false, - }; - // Always default to polling on IBM i because fs.watch() is not available on IBM i. - if (isIBMi) - opts.usePolling = true; - // Editor atomic write normalization enabled by default with fs.watch - if (opts.atomic === undefined) - opts.atomic = !opts.usePolling; - // opts.atomic = typeof _opts.atomic === 'number' ? _opts.atomic : 100; - // Global override. Useful for developers, who need to force polling for all - // instances of chokidar, regardless of usage / dependency depth - const envPoll = process.env.CHOKIDAR_USEPOLLING; - if (envPoll !== undefined) { - const envLower = envPoll.toLowerCase(); - if (envLower === 'false' || envLower === '0') - opts.usePolling = false; - else if (envLower === 'true' || envLower === '1') - opts.usePolling = true; - else - opts.usePolling = !!envLower; - } - const envInterval = process.env.CHOKIDAR_INTERVAL; - if (envInterval) - opts.interval = Number.parseInt(envInterval, 10); - // This is done to emit ready only once, but each 'add' will increase that? - let readyCalls = 0; - this._emitReady = () => { - readyCalls++; - if (readyCalls >= this._readyCount) { - this._emitReady = EMPTY_FN; - this._readyEmitted = true; - // use process.nextTick to allow time for listener to be bound - process.nextTick(() => this.emit(EV.READY)); - } - }; - this._emitRaw = (...args) => this.emit(EV.RAW, ...args); - this._boundRemove = this._remove.bind(this); - this.options = opts; - this._nodeFsHandler = new NodeFsHandler(this); - // You’re frozen when your heart’s not open. - Object.freeze(opts); - } - _addIgnoredPath(matcher) { - if (isMatcherObject(matcher)) { - // return early if we already have a deeply equal matcher object - for (const ignored of this._ignoredPaths) { - if (isMatcherObject(ignored) && - ignored.path === matcher.path && - ignored.recursive === matcher.recursive) { - return; - } - } - } - this._ignoredPaths.add(matcher); - } - _removeIgnoredPath(matcher) { - this._ignoredPaths.delete(matcher); - // now find any matcher objects with the matcher as path - if (typeof matcher === 'string') { - for (const ignored of this._ignoredPaths) { - // TODO (43081j): make this more efficient. - // probably just make a `this._ignoredDirectories` or some - // such thing. - if (isMatcherObject(ignored) && ignored.path === matcher) { - this._ignoredPaths.delete(ignored); - } - } - } - } - // Public methods - /** - * Adds paths to be watched on an existing FSWatcher instance. - * @param paths_ file or file list. Other arguments are unused - */ - add(paths_, _origAdd, _internal) { - const { cwd } = this.options; - this.closed = false; - this._closePromise = undefined; - let paths = unifyPaths(paths_); - if (cwd) { - paths = paths.map((path) => { - const absPath = getAbsolutePath(path, cwd); - // Check `path` instead of `absPath` because the cwd portion can't be a glob - return absPath; - }); - } - paths.forEach((path) => { - this._removeIgnoredPath(path); - }); - this._userIgnored = undefined; - if (!this._readyCount) - this._readyCount = 0; - this._readyCount += paths.length; - Promise.all(paths.map(async (path) => { - const res = await this._nodeFsHandler._addToNodeFs(path, !_internal, undefined, 0, _origAdd); - if (res) - this._emitReady(); - return res; - })).then((results) => { - if (this.closed) - return; - results.forEach((item) => { - if (item) - this.add(sysPath.dirname(item), sysPath.basename(_origAdd || item)); - }); - }); - return this; - } - /** - * Close watchers or start ignoring events from specified paths. - */ - unwatch(paths_) { - if (this.closed) - return this; - const paths = unifyPaths(paths_); - const { cwd } = this.options; - paths.forEach((path) => { - // convert to absolute path unless relative path already matches - if (!sysPath.isAbsolute(path) && !this._closers.has(path)) { - if (cwd) - path = sysPath.join(cwd, path); - path = sysPath.resolve(path); - } - this._closePath(path); - this._addIgnoredPath(path); - if (this._watched.has(path)) { - this._addIgnoredPath({ - path, - recursive: true, - }); - } - // reset the cached userIgnored anymatch fn - // to make ignoredPaths changes effective - this._userIgnored = undefined; - }); - return this; - } - /** - * Close watchers and remove all listeners from watched paths. - */ - close() { - if (this._closePromise) { - return this._closePromise; - } - this.closed = true; - // Memory management. - this.removeAllListeners(); - const closers = []; - this._closers.forEach((closerList) => closerList.forEach((closer) => { - const promise = closer(); - if (promise instanceof Promise) - closers.push(promise); - })); - this._streams.forEach((stream) => stream.destroy()); - this._userIgnored = undefined; - this._readyCount = 0; - this._readyEmitted = false; - this._watched.forEach((dirent) => dirent.dispose()); - this._closers.clear(); - this._watched.clear(); - this._streams.clear(); - this._symlinkPaths.clear(); - this._throttled.clear(); - this._closePromise = closers.length - ? Promise.all(closers).then(() => undefined) - : Promise.resolve(); - return this._closePromise; - } - /** - * Expose list of watched paths - * @returns for chaining - */ - getWatched() { - const watchList = {}; - this._watched.forEach((entry, dir) => { - const key = this.options.cwd ? sysPath.relative(this.options.cwd, dir) : dir; - const index = key || ONE_DOT; - watchList[index] = entry.getChildren().sort(); - }); - return watchList; - } - emitWithAll(event, args) { - this.emit(event, ...args); - if (event !== EV.ERROR) - this.emit(EV.ALL, event, ...args); - } - // Common helpers - // -------------- - /** - * Normalize and emit events. - * Calling _emit DOES NOT MEAN emit() would be called! - * @param event Type of event - * @param path File or directory path - * @param stats arguments to be passed with event - * @returns the error if defined, otherwise the value of the FSWatcher instance's `closed` flag - */ - async _emit(event, path, stats) { - if (this.closed) - return; - const opts = this.options; - if (isWindows) - path = sysPath.normalize(path); - if (opts.cwd) - path = sysPath.relative(opts.cwd, path); - const args = [path]; - if (stats != null) - args.push(stats); - const awf = opts.awaitWriteFinish; - let pw; - if (awf && (pw = this._pendingWrites.get(path))) { - pw.lastChange = new Date(); - return this; - } - if (opts.atomic) { - if (event === EV.UNLINK) { - this._pendingUnlinks.set(path, [event, ...args]); - setTimeout(() => { - this._pendingUnlinks.forEach((entry, path) => { - this.emit(...entry); - this.emit(EV.ALL, ...entry); - this._pendingUnlinks.delete(path); - }); - }, typeof opts.atomic === 'number' ? opts.atomic : 100); - return this; - } - if (event === EV.ADD && this._pendingUnlinks.has(path)) { - event = EV.CHANGE; - this._pendingUnlinks.delete(path); - } - } - if (awf && (event === EV.ADD || event === EV.CHANGE) && this._readyEmitted) { - const awfEmit = (err, stats) => { - if (err) { - event = EV.ERROR; - args[0] = err; - this.emitWithAll(event, args); - } - else if (stats) { - // if stats doesn't exist the file must have been deleted - if (args.length > 1) { - args[1] = stats; - } - else { - args.push(stats); - } - this.emitWithAll(event, args); - } - }; - this._awaitWriteFinish(path, awf.stabilityThreshold, event, awfEmit); - return this; - } - if (event === EV.CHANGE) { - const isThrottled = !this._throttle(EV.CHANGE, path, 50); - if (isThrottled) - return this; - } - if (opts.alwaysStat && - stats === undefined && - (event === EV.ADD || event === EV.ADD_DIR || event === EV.CHANGE)) { - const fullPath = opts.cwd ? sysPath.join(opts.cwd, path) : path; - let stats; - try { - stats = await stat(fullPath); - } - catch (err) { - // do nothing - } - // Suppress event when fs_stat fails, to avoid sending undefined 'stat' - if (!stats || this.closed) - return; - args.push(stats); - } - this.emitWithAll(event, args); - return this; - } - /** - * Common handler for errors - * @returns The error if defined, otherwise the value of the FSWatcher instance's `closed` flag - */ - _handleError(error) { - const code = error && error.code; - if (error && - code !== 'ENOENT' && - code !== 'ENOTDIR' && - (!this.options.ignorePermissionErrors || (code !== 'EPERM' && code !== 'EACCES'))) { - this.emit(EV.ERROR, error); - } - return error || this.closed; - } - /** - * Helper utility for throttling - * @param actionType type being throttled - * @param path being acted upon - * @param timeout duration of time to suppress duplicate actions - * @returns tracking object or false if action should be suppressed - */ - _throttle(actionType, path, timeout) { - if (!this._throttled.has(actionType)) { - this._throttled.set(actionType, new Map()); - } - const action = this._throttled.get(actionType); - if (!action) - throw new Error('invalid throttle'); - const actionPath = action.get(path); - if (actionPath) { - actionPath.count++; - return false; - } - // eslint-disable-next-line prefer-const - let timeoutObject; - const clear = () => { - const item = action.get(path); - const count = item ? item.count : 0; - action.delete(path); - clearTimeout(timeoutObject); - if (item) - clearTimeout(item.timeoutObject); - return count; - }; - timeoutObject = setTimeout(clear, timeout); - const thr = { timeoutObject, clear, count: 0 }; - action.set(path, thr); - return thr; - } - _incrReadyCount() { - return this._readyCount++; - } - /** - * Awaits write operation to finish. - * Polls a newly created file for size variations. When files size does not change for 'threshold' milliseconds calls callback. - * @param path being acted upon - * @param threshold Time in milliseconds a file size must be fixed before acknowledging write OP is finished - * @param event - * @param awfEmit Callback to be called when ready for event to be emitted. - */ - _awaitWriteFinish(path, threshold, event, awfEmit) { - const awf = this.options.awaitWriteFinish; - if (typeof awf !== 'object') - return; - const pollInterval = awf.pollInterval; - let timeoutHandler; - let fullPath = path; - if (this.options.cwd && !sysPath.isAbsolute(path)) { - fullPath = sysPath.join(this.options.cwd, path); - } - const now = new Date(); - const writes = this._pendingWrites; - function awaitWriteFinishFn(prevStat) { - statcb(fullPath, (err, curStat) => { - if (err || !writes.has(path)) { - if (err && err.code !== 'ENOENT') - awfEmit(err); - return; - } - const now = Number(new Date()); - if (prevStat && curStat.size !== prevStat.size) { - writes.get(path).lastChange = now; - } - const pw = writes.get(path); - const df = now - pw.lastChange; - if (df >= threshold) { - writes.delete(path); - awfEmit(undefined, curStat); - } - else { - timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval, curStat); - } - }); - } - if (!writes.has(path)) { - writes.set(path, { - lastChange: now, - cancelWait: () => { - writes.delete(path); - clearTimeout(timeoutHandler); - return event; - }, - }); - timeoutHandler = setTimeout(awaitWriteFinishFn, pollInterval); - } - } - /** - * Determines whether user has asked to ignore this path. - */ - _isIgnored(path, stats) { - if (this.options.atomic && DOT_RE.test(path)) - return true; - if (!this._userIgnored) { - const { cwd } = this.options; - const ign = this.options.ignored; - const ignored = (ign || []).map(normalizeIgnored(cwd)); - const ignoredPaths = [...this._ignoredPaths]; - const list = [...ignoredPaths.map(normalizeIgnored(cwd)), ...ignored]; - this._userIgnored = anymatch(list, undefined); - } - return this._userIgnored(path, stats); - } - _isntIgnored(path, stat) { - return !this._isIgnored(path, stat); - } - /** - * Provides a set of common helpers and properties relating to symlink handling. - * @param path file or directory pattern being watched - */ - _getWatchHelpers(path) { - return new WatchHelper(path, this.options.followSymlinks, this); - } - // Directory helpers - // ----------------- - /** - * Provides directory tracking objects - * @param directory path of the directory - */ - _getWatchedDir(directory) { - const dir = sysPath.resolve(directory); - if (!this._watched.has(dir)) - this._watched.set(dir, new DirEntry(dir, this._boundRemove)); - return this._watched.get(dir); - } - // File helpers - // ------------ - /** - * Check for read permissions: https://stackoverflow.com/a/11781404/1358405 - */ - _hasReadPermissions(stats) { - if (this.options.ignorePermissionErrors) - return true; - return Boolean(Number(stats.mode) & 0o400); - } - /** - * Handles emitting unlink events for - * files and directories, and via recursion, for - * files and directories within directories that are unlinked - * @param directory within which the following item is located - * @param item base path of item/directory - */ - _remove(directory, item, isDirectory) { - // if what is being deleted is a directory, get that directory's paths - // for recursive deleting and cleaning of watched object - // if it is not a directory, nestedDirectoryChildren will be empty array - const path = sysPath.join(directory, item); - const fullPath = sysPath.resolve(path); - isDirectory = - isDirectory != null ? isDirectory : this._watched.has(path) || this._watched.has(fullPath); - // prevent duplicate handling in case of arriving here nearly simultaneously - // via multiple paths (such as _handleFile and _handleDir) - if (!this._throttle('remove', path, 100)) - return; - // if the only watched file is removed, watch for its return - if (!isDirectory && this._watched.size === 1) { - this.add(directory, item, true); - } - // This will create a new entry in the watched object in either case - // so we got to do the directory check beforehand - const wp = this._getWatchedDir(path); - const nestedDirectoryChildren = wp.getChildren(); - // Recursively remove children directories / files. - nestedDirectoryChildren.forEach((nested) => this._remove(path, nested)); - // Check if item was on the watched list and remove it - const parent = this._getWatchedDir(directory); - const wasTracked = parent.has(item); - parent.remove(item); - // Fixes issue #1042 -> Relative paths were detected and added as symlinks - // (https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L612), - // but never removed from the map in case the path was deleted. - // This leads to an incorrect state if the path was recreated: - // https://github.com/paulmillr/chokidar/blob/e1753ddbc9571bdc33b4a4af172d52cb6e611c10/lib/nodefs-handler.js#L553 - if (this._symlinkPaths.has(fullPath)) { - this._symlinkPaths.delete(fullPath); - } - // If we wait for this file to be fully written, cancel the wait. - let relPath = path; - if (this.options.cwd) - relPath = sysPath.relative(this.options.cwd, path); - if (this.options.awaitWriteFinish && this._pendingWrites.has(relPath)) { - const event = this._pendingWrites.get(relPath).cancelWait(); - if (event === EV.ADD) - return; - } - // The Entry will either be a directory that just got removed - // or a bogus entry to a file, in either case we have to remove it - this._watched.delete(path); - this._watched.delete(fullPath); - const eventName = isDirectory ? EV.UNLINK_DIR : EV.UNLINK; - if (wasTracked && !this._isIgnored(path)) - this._emit(eventName, path); - // Avoid conflicts if we later create another file with the same name - this._closePath(path); - } - /** - * Closes all watchers for a path - */ - _closePath(path) { - this._closeFile(path); - const dir = sysPath.dirname(path); - this._getWatchedDir(dir).remove(sysPath.basename(path)); - } - /** - * Closes only file-specific watchers - */ - _closeFile(path) { - const closers = this._closers.get(path); - if (!closers) - return; - closers.forEach((closer) => closer()); - this._closers.delete(path); - } - _addPathCloser(path, closer) { - if (!closer) - return; - let list = this._closers.get(path); - if (!list) { - list = []; - this._closers.set(path, list); - } - list.push(closer); - } - _readdirp(root, opts) { - if (this.closed) - return; - const options = { type: EV.ALL, alwaysStat: true, lstat: true, ...opts, depth: 0 }; - let stream = readdirp(root, options); - this._streams.add(stream); - stream.once(STR_CLOSE, () => { - stream = undefined; - }); - stream.once(STR_END, () => { - if (stream) { - this._streams.delete(stream); - stream = undefined; - } - }); - return stream; - } -} -/** - * Instantiates watcher with paths to be tracked. - * @param paths file / directory paths - * @param options opts, such as `atomic`, `awaitWriteFinish`, `ignored`, and others - * @returns an instance of FSWatcher for chaining. - * @example - * const watcher = watch('.').on('all', (event, path) => { console.log(event, path); }); - * watch('.', { atomic: true, awaitWriteFinish: true, ignored: (f, stats) => stats?.isFile() && !f.endsWith('.js') }) - */ -export function watch(paths, options = {}) { - const watcher = new FSWatcher(options); - watcher.add(paths); - return watcher; -} -export default { watch, FSWatcher }; diff --git a/claude-code-source/node_modules/cli-boxes/index.js b/claude-code-source/node_modules/cli-boxes/index.js deleted file mode 100644 index fc8a30f7..00000000 --- a/claude-code-source/node_modules/cli-boxes/index.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; -const cliBoxes = require('./boxes.json'); - -module.exports = cliBoxes; -// TODO: Remove this for the next major release -module.exports.default = cliBoxes; diff --git a/claude-code-source/node_modules/cli-highlight/dist/index.js b/claude-code-source/node_modules/cli-highlight/dist/index.js deleted file mode 100644 index 7724c5f7..00000000 --- a/claude-code-source/node_modules/cli-highlight/dist/index.js +++ /dev/null @@ -1,112 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.supportsLanguage = exports.listLanguages = exports.highlight = void 0; -var hljs = __importStar(require("highlight.js")); -var parse5 = __importStar(require("parse5")); -var parse5_htmlparser2_tree_adapter_1 = __importDefault(require("parse5-htmlparser2-tree-adapter")); -var theme_1 = require("./theme"); -function colorizeNode(node, theme, context) { - if (theme === void 0) { theme = {}; } - switch (node.type) { - case 'text': { - var text = node.data; - if (context === undefined) { - return (theme.default || theme_1.DEFAULT_THEME.default || theme_1.plain)(text); - } - return text; - } - case 'tag': { - var hljsClass = /hljs-(\w+)/.exec(node.attribs.class); - if (hljsClass) { - var token_1 = hljsClass[1]; - var nodeData = node.childNodes - .map(function (node) { return colorizeNode(node, theme, token_1); }) - .join(''); - return (theme[token_1] || theme_1.DEFAULT_THEME[token_1] || theme_1.plain)(nodeData); - } - // Return the data itself when the class name isn't prefixed with a highlight.js token prefix. - // This is common in instances of sublanguages (JSX, Markdown Code Blocks, etc.) - return node.childNodes.map(function (node) { return colorizeNode(node, theme); }).join(''); - } - } - throw new Error('Invalid node type ' + node.type); -} -function colorize(code, theme) { - if (theme === void 0) { theme = {}; } - var fragment = parse5.parseFragment(code, { - treeAdapter: parse5_htmlparser2_tree_adapter_1.default, - }); - return fragment.childNodes.map(function (node) { return colorizeNode(node, theme); }).join(''); -} -/** - * Apply syntax highlighting to `code` with ASCII color codes. The language is automatically - * detected if not set. - * - * ```ts - * import {highlight} from 'cli-highlight'; - * import * as fs from 'fs'; - * - * fs.readFile('package.json', 'utf8', (err: any, json: string) => { - * console.log('package.json:'); - * console.log(highlight(json)); - * }); - * ``` - * - * @param code The code to highlight - * @param options Optional options - */ -function highlight(code, options) { - if (options === void 0) { options = {}; } - var html; - if (options.language) { - html = hljs.highlight(code, { language: options.language, ignoreIllegals: options.ignoreIllegals }).value; - } - else { - html = hljs.highlightAuto(code, options.languageSubset).value; - } - return colorize(html, options.theme); -} -exports.highlight = highlight; -/** - * Returns all supported languages - */ -function listLanguages() { - return hljs.listLanguages(); -} -exports.listLanguages = listLanguages; -/** - * Returns true if the language is supported - * @param name A language name, alias or file extension - */ -function supportsLanguage(name) { - return !!hljs.getLanguage(name); -} -exports.supportsLanguage = supportsLanguage; -exports.default = highlight; -__exportStar(require("./theme"), exports); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/cli-highlight/dist/theme.js b/claude-code-source/node_modules/cli-highlight/dist/theme.js deleted file mode 100644 index 3df49b3a..00000000 --- a/claude-code-source/node_modules/cli-highlight/dist/theme.js +++ /dev/null @@ -1,265 +0,0 @@ -"use strict"; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.parse = exports.stringify = exports.toJson = exports.fromJson = exports.DEFAULT_THEME = exports.plain = void 0; -var chalk_1 = __importDefault(require("chalk")); -/** - * Identity function for tokens that should not be styled (returns the input string as-is). - * See [[Theme]] for an example. - */ -var plain = function (codePart) { return codePart; }; -exports.plain = plain; -/** - * The default theme. It is possible to override just individual keys. - */ -exports.DEFAULT_THEME = { - /** - * keyword in a regular Algol-style language - */ - keyword: chalk_1.default.blue, - /** - * built-in or library object (constant, class, function) - */ - built_in: chalk_1.default.cyan, - /** - * user-defined type in a language with first-class syntactically significant types, like - * Haskell - */ - type: chalk_1.default.cyan.dim, - /** - * special identifier for a built-in value ("true", "false", "null") - */ - literal: chalk_1.default.blue, - /** - * number, including units and modifiers, if any. - */ - number: chalk_1.default.green, - /** - * literal regular expression - */ - regexp: chalk_1.default.red, - /** - * literal string, character - */ - string: chalk_1.default.red, - /** - * parsed section inside a literal string - */ - subst: exports.plain, - /** - * symbolic constant, interned string, goto label - */ - symbol: exports.plain, - /** - * class or class-level declaration (interfaces, traits, modules, etc) - */ - class: chalk_1.default.blue, - /** - * function or method declaration - */ - function: chalk_1.default.yellow, - /** - * name of a class or a function at the place of declaration - */ - title: exports.plain, - /** - * block of function arguments (parameters) at the place of declaration - */ - params: exports.plain, - /** - * comment - */ - comment: chalk_1.default.green, - /** - * documentation markup within comments - */ - doctag: chalk_1.default.green, - /** - * flags, modifiers, annotations, processing instructions, preprocessor directive, etc - */ - meta: chalk_1.default.grey, - /** - * keyword or built-in within meta construct - */ - 'meta-keyword': exports.plain, - /** - * string within meta construct - */ - 'meta-string': exports.plain, - /** - * heading of a section in a config file, heading in text markup - */ - section: exports.plain, - /** - * XML/HTML tag - */ - tag: chalk_1.default.grey, - /** - * name of an XML tag, the first word in an s-expression - */ - name: chalk_1.default.blue, - /** - * s-expression name from the language standard library - */ - 'builtin-name': exports.plain, - /** - * name of an attribute with no language defined semantics (keys in JSON, setting names in - * .ini), also sub-attribute within another highlighted object, like XML tag - */ - attr: chalk_1.default.cyan, - /** - * name of an attribute followed by a structured value part, like CSS properties - */ - attribute: exports.plain, - /** - * variable in a config or a template file, environment var expansion in a script - */ - variable: exports.plain, - /** - * list item bullet in text markup - */ - bullet: exports.plain, - /** - * code block in text markup - */ - code: exports.plain, - /** - * emphasis in text markup - */ - emphasis: chalk_1.default.italic, - /** - * strong emphasis in text markup - */ - strong: chalk_1.default.bold, - /** - * mathematical formula in text markup - */ - formula: exports.plain, - /** - * hyperlink in text markup - */ - link: chalk_1.default.underline, - /** - * quotation in text markup - */ - quote: exports.plain, - /** - * tag selector in CSS - */ - 'selector-tag': exports.plain, - /** - * #id selector in CSS - */ - 'selector-id': exports.plain, - /** - * .class selector in CSS - */ - 'selector-class': exports.plain, - /** - * [attr] selector in CSS - */ - 'selector-attr': exports.plain, - /** - * :pseudo selector in CSS - */ - 'selector-pseudo': exports.plain, - /** - * tag of a template language - */ - 'template-tag': exports.plain, - /** - * variable in a template language - */ - 'template-variable': exports.plain, - /** - * added or changed line in a diff - */ - addition: chalk_1.default.green, - /** - * deleted line in a diff - */ - deletion: chalk_1.default.red, - /** - * things not matched by any token - */ - default: exports.plain, -}; -/** - * Converts a [[JsonTheme]] with string values to a [[Theme]] with formatter functions. Used by [[parse]]. - */ -function fromJson(json) { - var theme = {}; - for (var _i = 0, _a = Object.keys(json); _i < _a.length; _i++) { - var key = _a[_i]; - var style = json[key]; - if (Array.isArray(style)) { - ; - theme[key] = style.reduce(function (previous, current) { return (current === 'plain' ? exports.plain : previous[current]); }, chalk_1.default); - } - else { - ; - theme[key] = chalk_1.default[style]; - } - } - return theme; -} -exports.fromJson = fromJson; -/** - * Converts a [[Theme]] with formatter functions to a [[JsonTheme]] with string values. Used by [[stringify]]. - */ -function toJson(theme) { - var jsonTheme = {}; - for (var _i = 0, _a = Object.keys(jsonTheme); _i < _a.length; _i++) { - var key = _a[_i]; - var style = jsonTheme[key]; - jsonTheme[key] = style._styles; - } - return jsonTheme; -} -exports.toJson = toJson; -/** - * Stringifies a [[Theme]] with formatter functions to a JSON string. - * - * ```ts - * import chalk = require('chalk'); - * import {stringify} from 'cli-highlight'; - * import * as fs from 'fs'; - * - * const myTheme: Theme = { - * keyword: chalk.red.bold, - * addition: chalk.green, - * deletion: chalk.red.strikethrough, - * number: plain - * } - * const json = stringify(myTheme); - * fs.writeFile('mytheme.json', json, (err: any) => { - * if (err) throw err; - * console.log('Theme saved'); - * }); - * ``` - */ -function stringify(theme) { - return JSON.stringify(toJson(theme)); -} -exports.stringify = stringify; -/** - * Parses a JSON string into a [[Theme]] with formatter functions. - * - * ```ts - * import * as fs from 'fs'; - * import {parse, highlight} from 'cli-highlight'; - * - * fs.readFile('mytheme.json', 'utf8', (err: any, json: string) => { - * if (err) throw err; - * const code = highlight('SELECT * FROM table', {theme: parse(json)}); - * console.log(code); - * }); - * ``` - */ -function parse(json) { - return fromJson(JSON.parse(json)); -} -exports.parse = parse; -//# sourceMappingURL=theme.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/cli-highlight/node_modules/chalk/node_modules/ansi-styles/index.js b/claude-code-source/node_modules/cli-highlight/node_modules/chalk/node_modules/ansi-styles/index.js deleted file mode 100644 index 5d82581a..00000000 --- a/claude-code-source/node_modules/cli-highlight/node_modules/chalk/node_modules/ansi-styles/index.js +++ /dev/null @@ -1,163 +0,0 @@ -'use strict'; - -const wrapAnsi16 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${code + offset}m`; -}; - -const wrapAnsi256 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${38 + offset};5;${code}m`; -}; - -const wrapAnsi16m = (fn, offset) => (...args) => { - const rgb = fn(...args); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; -}; - -const ansi2ansi = n => n; -const rgb2rgb = (r, g, b) => [r, g, b]; - -const setLazyProperty = (object, property, get) => { - Object.defineProperty(object, property, { - get: () => { - const value = get(); - - Object.defineProperty(object, property, { - value, - enumerable: true, - configurable: true - }); - - return value; - }, - enumerable: true, - configurable: true - }); -}; - -/** @type {typeof import('color-convert')} */ -let colorConvert; -const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { - if (colorConvert === undefined) { - colorConvert = require('color-convert'); - } - - const offset = isBackground ? 10 : 0; - const styles = {}; - - for (const [sourceSpace, suite] of Object.entries(colorConvert)) { - const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; - if (sourceSpace === targetSpace) { - styles[name] = wrap(identity, offset); - } else if (typeof suite === 'object') { - styles[name] = wrap(suite[targetSpace], offset); - } - } - - return styles; -}; - -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - - // Bright color - blackBright: [90, 39], - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; - - // Alias bright black as gray (and grey) - styles.color.gray = styles.color.blackBright; - styles.bgColor.bgGray = styles.bgColor.bgBlackBright; - styles.color.grey = styles.color.blackBright; - styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; - - for (const [groupName, group] of Object.entries(styles)) { - for (const [styleName, style] of Object.entries(group)) { - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; - - group[styleName] = styles[styleName]; - - codes.set(style[0], style[1]); - } - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - } - - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; - - setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); - setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); - - return styles; -} - -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); diff --git a/claude-code-source/node_modules/cli-highlight/node_modules/chalk/node_modules/supports-color/index.js b/claude-code-source/node_modules/cli-highlight/node_modules/chalk/node_modules/supports-color/index.js deleted file mode 100644 index 6fada390..00000000 --- a/claude-code-source/node_modules/cli-highlight/node_modules/chalk/node_modules/supports-color/index.js +++ /dev/null @@ -1,135 +0,0 @@ -'use strict'; -const os = require('os'); -const tty = require('tty'); -const hasFlag = require('has-flag'); - -const {env} = process; - -let forceColor; -if (hasFlag('no-color') || - hasFlag('no-colors') || - hasFlag('color=false') || - hasFlag('color=never')) { - forceColor = 0; -} else if (hasFlag('color') || - hasFlag('colors') || - hasFlag('color=true') || - hasFlag('color=always')) { - forceColor = 1; -} - -if ('FORCE_COLOR' in env) { - if (env.FORCE_COLOR === 'true') { - forceColor = 1; - } else if (env.FORCE_COLOR === 'false') { - forceColor = 0; - } else { - forceColor = env.FORCE_COLOR.length === 0 ? 1 : Math.min(parseInt(env.FORCE_COLOR, 10), 3); - } -} - -function translateLevel(level) { - if (level === 0) { - return false; - } - - return { - level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3 - }; -} - -function supportsColor(haveStream, streamIsTTY) { - if (forceColor === 0) { - return 0; - } - - if (hasFlag('color=16m') || - hasFlag('color=full') || - hasFlag('color=truecolor')) { - return 3; - } - - if (hasFlag('color=256')) { - return 2; - } - - if (haveStream && !streamIsTTY && forceColor === undefined) { - return 0; - } - - const min = forceColor || 0; - - if (env.TERM === 'dumb') { - return min; - } - - if (process.platform === 'win32') { - // Windows 10 build 10586 is the first Windows release that supports 256 colors. - // Windows 10 build 14931 is the first release that supports 16m/TrueColor. - const osRelease = os.release().split('.'); - if ( - Number(osRelease[0]) >= 10 && - Number(osRelease[2]) >= 10586 - ) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; - } - - return 1; - } - - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI', 'GITHUB_ACTIONS', 'BUILDKITE'].some(sign => sign in env) || env.CI_NAME === 'codeship') { - return 1; - } - - return min; - } - - if ('TEAMCITY_VERSION' in env) { - return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; - } - - if (env.COLORTERM === 'truecolor') { - return 3; - } - - if ('TERM_PROGRAM' in env) { - const version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Apple_Terminal': - return 2; - // No default - } - } - - if (/-256(color)?$/i.test(env.TERM)) { - return 2; - } - - if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; - } - - if ('COLORTERM' in env) { - return 1; - } - - return min; -} - -function getSupportLevel(stream) { - const level = supportsColor(stream, stream && stream.isTTY); - return translateLevel(level); -} - -module.exports = { - supportsColor: getSupportLevel, - stdout: translateLevel(supportsColor(true, tty.isatty(1))), - stderr: translateLevel(supportsColor(true, tty.isatty(2))) -}; diff --git a/claude-code-source/node_modules/cli-highlight/node_modules/chalk/source/index.js b/claude-code-source/node_modules/cli-highlight/node_modules/chalk/source/index.js deleted file mode 100644 index 75ec6635..00000000 --- a/claude-code-source/node_modules/cli-highlight/node_modules/chalk/source/index.js +++ /dev/null @@ -1,229 +0,0 @@ -'use strict'; -const ansiStyles = require('ansi-styles'); -const {stdout: stdoutColor, stderr: stderrColor} = require('supports-color'); -const { - stringReplaceAll, - stringEncaseCRLFWithFirstIndex -} = require('./util'); - -const {isArray} = Array; - -// `supportsColor.level` → `ansiStyles.color[name]` mapping -const levelMapping = [ - 'ansi', - 'ansi', - 'ansi256', - 'ansi16m' -]; - -const styles = Object.create(null); - -const applyOptions = (object, options = {}) => { - if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { - throw new Error('The `level` option should be an integer from 0 to 3'); - } - - // Detect level if not set manually - const colorLevel = stdoutColor ? stdoutColor.level : 0; - object.level = options.level === undefined ? colorLevel : options.level; -}; - -class ChalkClass { - constructor(options) { - // eslint-disable-next-line no-constructor-return - return chalkFactory(options); - } -} - -const chalkFactory = options => { - const chalk = {}; - applyOptions(chalk, options); - - chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); - - Object.setPrototypeOf(chalk, Chalk.prototype); - Object.setPrototypeOf(chalk.template, chalk); - - chalk.template.constructor = () => { - throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); - }; - - chalk.template.Instance = ChalkClass; - - return chalk.template; -}; - -function Chalk(options) { - return chalkFactory(options); -} - -for (const [styleName, style] of Object.entries(ansiStyles)) { - styles[styleName] = { - get() { - const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); - Object.defineProperty(this, styleName, {value: builder}); - return builder; - } - }; -} - -styles.visible = { - get() { - const builder = createBuilder(this, this._styler, true); - Object.defineProperty(this, 'visible', {value: builder}); - return builder; - } -}; - -const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; - -for (const model of usedModels) { - styles[model] = { - get() { - const {level} = this; - return function (...arguments_) { - const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler); - return createBuilder(this, styler, this._isEmpty); - }; - } - }; -} - -for (const model of usedModels) { - const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); - styles[bgModel] = { - get() { - const {level} = this; - return function (...arguments_) { - const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler); - return createBuilder(this, styler, this._isEmpty); - }; - } - }; -} - -const proto = Object.defineProperties(() => {}, { - ...styles, - level: { - enumerable: true, - get() { - return this._generator.level; - }, - set(level) { - this._generator.level = level; - } - } -}); - -const createStyler = (open, close, parent) => { - let openAll; - let closeAll; - if (parent === undefined) { - openAll = open; - closeAll = close; - } else { - openAll = parent.openAll + open; - closeAll = close + parent.closeAll; - } - - return { - open, - close, - openAll, - closeAll, - parent - }; -}; - -const createBuilder = (self, _styler, _isEmpty) => { - const builder = (...arguments_) => { - if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) { - // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}` - return applyStyle(builder, chalkTag(builder, ...arguments_)); - } - - // Single argument is hot path, implicit coercion is faster than anything - // eslint-disable-next-line no-implicit-coercion - return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); - }; - - // We alter the prototype because we must return a function, but there is - // no way to create a function with a different prototype - Object.setPrototypeOf(builder, proto); - - builder._generator = self; - builder._styler = _styler; - builder._isEmpty = _isEmpty; - - return builder; -}; - -const applyStyle = (self, string) => { - if (self.level <= 0 || !string) { - return self._isEmpty ? '' : string; - } - - let styler = self._styler; - - if (styler === undefined) { - return string; - } - - const {openAll, closeAll} = styler; - if (string.indexOf('\u001B') !== -1) { - while (styler !== undefined) { - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - string = stringReplaceAll(string, styler.close, styler.open); - - styler = styler.parent; - } - } - - // We can move both next actions out of loop, because remaining actions in loop won't have - // any/visible effect on parts we add here. Close the styling before a linebreak and reopen - // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 - const lfIndex = string.indexOf('\n'); - if (lfIndex !== -1) { - string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); - } - - return openAll + string + closeAll; -}; - -let template; -const chalkTag = (chalk, ...strings) => { - const [firstString] = strings; - - if (!isArray(firstString) || !isArray(firstString.raw)) { - // If chalk() was called by itself or with a string, - // return the string itself as a string. - return strings.join(' '); - } - - const arguments_ = strings.slice(1); - const parts = [firstString.raw[0]]; - - for (let i = 1; i < firstString.length; i++) { - parts.push( - String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), - String(firstString.raw[i]) - ); - } - - if (template === undefined) { - template = require('./templates'); - } - - return template(chalk, parts.join('')); -}; - -Object.defineProperties(Chalk.prototype, styles); - -const chalk = Chalk(); // eslint-disable-line new-cap -chalk.supportsColor = stdoutColor; -chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap -chalk.stderr.supportsColor = stderrColor; - -module.exports = chalk; diff --git a/claude-code-source/node_modules/cli-highlight/node_modules/chalk/source/templates.js b/claude-code-source/node_modules/cli-highlight/node_modules/chalk/source/templates.js deleted file mode 100644 index b130949d..00000000 --- a/claude-code-source/node_modules/cli-highlight/node_modules/chalk/source/templates.js +++ /dev/null @@ -1,134 +0,0 @@ -'use strict'; -const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; -const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; -const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; -const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; - -const ESCAPES = new Map([ - ['n', '\n'], - ['r', '\r'], - ['t', '\t'], - ['b', '\b'], - ['f', '\f'], - ['v', '\v'], - ['0', '\0'], - ['\\', '\\'], - ['e', '\u001B'], - ['a', '\u0007'] -]); - -function unescape(c) { - const u = c[0] === 'u'; - const bracket = c[1] === '{'; - - if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { - return String.fromCharCode(parseInt(c.slice(1), 16)); - } - - if (u && bracket) { - return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); - } - - return ESCAPES.get(c) || c; -} - -function parseArguments(name, arguments_) { - const results = []; - const chunks = arguments_.trim().split(/\s*,\s*/g); - let matches; - - for (const chunk of chunks) { - const number = Number(chunk); - if (!Number.isNaN(number)) { - results.push(number); - } else if ((matches = chunk.match(STRING_REGEX))) { - results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character)); - } else { - throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); - } - } - - return results; -} - -function parseStyle(style) { - STYLE_REGEX.lastIndex = 0; - - const results = []; - let matches; - - while ((matches = STYLE_REGEX.exec(style)) !== null) { - const name = matches[1]; - - if (matches[2]) { - const args = parseArguments(name, matches[2]); - results.push([name].concat(args)); - } else { - results.push([name]); - } - } - - return results; -} - -function buildStyle(chalk, styles) { - const enabled = {}; - - for (const layer of styles) { - for (const style of layer.styles) { - enabled[style[0]] = layer.inverse ? null : style.slice(1); - } - } - - let current = chalk; - for (const [styleName, styles] of Object.entries(enabled)) { - if (!Array.isArray(styles)) { - continue; - } - - if (!(styleName in current)) { - throw new Error(`Unknown Chalk style: ${styleName}`); - } - - current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; - } - - return current; -} - -module.exports = (chalk, temporary) => { - const styles = []; - const chunks = []; - let chunk = []; - - // eslint-disable-next-line max-params - temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => { - if (escapeCharacter) { - chunk.push(unescape(escapeCharacter)); - } else if (style) { - const string = chunk.join(''); - chunk = []; - chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string)); - styles.push({inverse, styles: parseStyle(style)}); - } else if (close) { - if (styles.length === 0) { - throw new Error('Found extraneous } in Chalk template literal'); - } - - chunks.push(buildStyle(chalk, styles)(chunk.join(''))); - chunk = []; - styles.pop(); - } else { - chunk.push(character); - } - }); - - chunks.push(chunk.join('')); - - if (styles.length > 0) { - const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; - throw new Error(errMessage); - } - - return chunks.join(''); -}; diff --git a/claude-code-source/node_modules/cli-highlight/node_modules/chalk/source/util.js b/claude-code-source/node_modules/cli-highlight/node_modules/chalk/source/util.js deleted file mode 100644 index ca466fd4..00000000 --- a/claude-code-source/node_modules/cli-highlight/node_modules/chalk/source/util.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const stringReplaceAll = (string, substring, replacer) => { - let index = string.indexOf(substring); - if (index === -1) { - return string; - } - - const substringLength = substring.length; - let endIndex = 0; - let returnValue = ''; - do { - returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; - endIndex = index + substringLength; - index = string.indexOf(substring, endIndex); - } while (index !== -1); - - returnValue += string.substr(endIndex); - return returnValue; -}; - -const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { - let endIndex = 0; - let returnValue = ''; - do { - const gotCR = string[index - 1] === '\r'; - returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; - endIndex = index + 1; - index = string.indexOf('\n', endIndex); - } while (index !== -1); - - returnValue += string.substr(endIndex); - return returnValue; -}; - -module.exports = { - stringReplaceAll, - stringEncaseCRLFWithFirstIndex -}; diff --git a/claude-code-source/node_modules/cli-width/index.js b/claude-code-source/node_modules/cli-width/index.js deleted file mode 100644 index c7803381..00000000 --- a/claude-code-source/node_modules/cli-width/index.js +++ /dev/null @@ -1,49 +0,0 @@ -'use strict'; - -module.exports = cliWidth; - -function normalizeOpts(options) { - const defaultOpts = { - defaultWidth: 0, - output: process.stdout, - tty: require('tty'), - }; - - if (!options) { - return defaultOpts; - } - - Object.keys(defaultOpts).forEach(function (key) { - if (!options[key]) { - options[key] = defaultOpts[key]; - } - }); - - return options; -} - -function cliWidth(options) { - const opts = normalizeOpts(options); - - if (opts.output.getWindowSize) { - return opts.output.getWindowSize()[0] || opts.defaultWidth; - } - - if (opts.tty.getWindowSize) { - return opts.tty.getWindowSize()[1] || opts.defaultWidth; - } - - if (opts.output.columns) { - return opts.output.columns; - } - - if (process.env.CLI_WIDTH) { - const width = parseInt(process.env.CLI_WIDTH, 10); - - if (!isNaN(width) && width !== 0) { - return width; - } - } - - return opts.defaultWidth; -} diff --git a/claude-code-source/node_modules/code-excerpt/dist/index.js b/claude-code-source/node_modules/code-excerpt/dist/index.js deleted file mode 100644 index 774dc949..00000000 --- a/claude-code-source/node_modules/code-excerpt/dist/index.js +++ /dev/null @@ -1,27 +0,0 @@ -import tabsToSpaces from 'convert-to-spaces'; -const generateLineNumbers = (line, around) => { - const lineNumbers = []; - const min = line - around; - const max = line + around; - for (let lineNumber = min; lineNumber <= max; lineNumber++) { - lineNumbers.push(lineNumber); - } - return lineNumbers; -}; -const codeExcerpt = (source, line, options = {}) => { - var _a; - if (typeof source !== 'string') { - throw new TypeError('Source code is missing.'); - } - if (!line || line < 1) { - throw new TypeError('Line number must start from `1`.'); - } - const lines = tabsToSpaces(source).split(/\r?\n/); - if (line > lines.length) { - return; - } - return generateLineNumbers(line, (_a = options.around) !== null && _a !== void 0 ? _a : 3) - .filter(line => lines[line - 1] !== undefined) - .map(line => ({ line, value: lines[line - 1] })); -}; -export default codeExcerpt; diff --git a/claude-code-source/node_modules/color-convert/conversions.js b/claude-code-source/node_modules/color-convert/conversions.js deleted file mode 100644 index 2657f265..00000000 --- a/claude-code-source/node_modules/color-convert/conversions.js +++ /dev/null @@ -1,839 +0,0 @@ -/* MIT license */ -/* eslint-disable no-mixed-operators */ -const cssKeywords = require('color-name'); - -// NOTE: conversions should only return primitive values (i.e. arrays, or -// values that give correct `typeof` results). -// do not use box values types (i.e. Number(), String(), etc.) - -const reverseKeywords = {}; -for (const key of Object.keys(cssKeywords)) { - reverseKeywords[cssKeywords[key]] = key; -} - -const convert = { - rgb: {channels: 3, labels: 'rgb'}, - hsl: {channels: 3, labels: 'hsl'}, - hsv: {channels: 3, labels: 'hsv'}, - hwb: {channels: 3, labels: 'hwb'}, - cmyk: {channels: 4, labels: 'cmyk'}, - xyz: {channels: 3, labels: 'xyz'}, - lab: {channels: 3, labels: 'lab'}, - lch: {channels: 3, labels: 'lch'}, - hex: {channels: 1, labels: ['hex']}, - keyword: {channels: 1, labels: ['keyword']}, - ansi16: {channels: 1, labels: ['ansi16']}, - ansi256: {channels: 1, labels: ['ansi256']}, - hcg: {channels: 3, labels: ['h', 'c', 'g']}, - apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, - gray: {channels: 1, labels: ['gray']} -}; - -module.exports = convert; - -// Hide .channels and .labels properties -for (const model of Object.keys(convert)) { - if (!('channels' in convert[model])) { - throw new Error('missing channels property: ' + model); - } - - if (!('labels' in convert[model])) { - throw new Error('missing channel labels property: ' + model); - } - - if (convert[model].labels.length !== convert[model].channels) { - throw new Error('channel and label counts mismatch: ' + model); - } - - const {channels, labels} = convert[model]; - delete convert[model].channels; - delete convert[model].labels; - Object.defineProperty(convert[model], 'channels', {value: channels}); - Object.defineProperty(convert[model], 'labels', {value: labels}); -} - -convert.rgb.hsl = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const min = Math.min(r, g, b); - const max = Math.max(r, g, b); - const delta = max - min; - let h; - let s; - - if (max === min) { - h = 0; - } else if (r === max) { - h = (g - b) / delta; - } else if (g === max) { - h = 2 + (b - r) / delta; - } else if (b === max) { - h = 4 + (r - g) / delta; - } - - h = Math.min(h * 60, 360); - - if (h < 0) { - h += 360; - } - - const l = (min + max) / 2; - - if (max === min) { - s = 0; - } else if (l <= 0.5) { - s = delta / (max + min); - } else { - s = delta / (2 - max - min); - } - - return [h, s * 100, l * 100]; -}; - -convert.rgb.hsv = function (rgb) { - let rdif; - let gdif; - let bdif; - let h; - let s; - - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const v = Math.max(r, g, b); - const diff = v - Math.min(r, g, b); - const diffc = function (c) { - return (v - c) / 6 / diff + 1 / 2; - }; - - if (diff === 0) { - h = 0; - s = 0; - } else { - s = diff / v; - rdif = diffc(r); - gdif = diffc(g); - bdif = diffc(b); - - if (r === v) { - h = bdif - gdif; - } else if (g === v) { - h = (1 / 3) + rdif - bdif; - } else if (b === v) { - h = (2 / 3) + gdif - rdif; - } - - if (h < 0) { - h += 1; - } else if (h > 1) { - h -= 1; - } - } - - return [ - h * 360, - s * 100, - v * 100 - ]; -}; - -convert.rgb.hwb = function (rgb) { - const r = rgb[0]; - const g = rgb[1]; - let b = rgb[2]; - const h = convert.rgb.hsl(rgb)[0]; - const w = 1 / 255 * Math.min(r, Math.min(g, b)); - - b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); - - return [h, w * 100, b * 100]; -}; - -convert.rgb.cmyk = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - - const k = Math.min(1 - r, 1 - g, 1 - b); - const c = (1 - r - k) / (1 - k) || 0; - const m = (1 - g - k) / (1 - k) || 0; - const y = (1 - b - k) / (1 - k) || 0; - - return [c * 100, m * 100, y * 100, k * 100]; -}; - -function comparativeDistance(x, y) { - /* - See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance - */ - return ( - ((x[0] - y[0]) ** 2) + - ((x[1] - y[1]) ** 2) + - ((x[2] - y[2]) ** 2) - ); -} - -convert.rgb.keyword = function (rgb) { - const reversed = reverseKeywords[rgb]; - if (reversed) { - return reversed; - } - - let currentClosestDistance = Infinity; - let currentClosestKeyword; - - for (const keyword of Object.keys(cssKeywords)) { - const value = cssKeywords[keyword]; - - // Compute comparative distance - const distance = comparativeDistance(rgb, value); - - // Check if its less, if so set as closest - if (distance < currentClosestDistance) { - currentClosestDistance = distance; - currentClosestKeyword = keyword; - } - } - - return currentClosestKeyword; -}; - -convert.keyword.rgb = function (keyword) { - return cssKeywords[keyword]; -}; - -convert.rgb.xyz = function (rgb) { - let r = rgb[0] / 255; - let g = rgb[1] / 255; - let b = rgb[2] / 255; - - // Assume sRGB - r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); - g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); - b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); - - const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); - const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); - const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); - - return [x * 100, y * 100, z * 100]; -}; - -convert.rgb.lab = function (rgb) { - const xyz = convert.rgb.xyz(rgb); - let x = xyz[0]; - let y = xyz[1]; - let z = xyz[2]; - - x /= 95.047; - y /= 100; - z /= 108.883; - - x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); - - const l = (116 * y) - 16; - const a = 500 * (x - y); - const b = 200 * (y - z); - - return [l, a, b]; -}; - -convert.hsl.rgb = function (hsl) { - const h = hsl[0] / 360; - const s = hsl[1] / 100; - const l = hsl[2] / 100; - let t2; - let t3; - let val; - - if (s === 0) { - val = l * 255; - return [val, val, val]; - } - - if (l < 0.5) { - t2 = l * (1 + s); - } else { - t2 = l + s - l * s; - } - - const t1 = 2 * l - t2; - - const rgb = [0, 0, 0]; - for (let i = 0; i < 3; i++) { - t3 = h + 1 / 3 * -(i - 1); - if (t3 < 0) { - t3++; - } - - if (t3 > 1) { - t3--; - } - - if (6 * t3 < 1) { - val = t1 + (t2 - t1) * 6 * t3; - } else if (2 * t3 < 1) { - val = t2; - } else if (3 * t3 < 2) { - val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; - } else { - val = t1; - } - - rgb[i] = val * 255; - } - - return rgb; -}; - -convert.hsl.hsv = function (hsl) { - const h = hsl[0]; - let s = hsl[1] / 100; - let l = hsl[2] / 100; - let smin = s; - const lmin = Math.max(l, 0.01); - - l *= 2; - s *= (l <= 1) ? l : 2 - l; - smin *= lmin <= 1 ? lmin : 2 - lmin; - const v = (l + s) / 2; - const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); - - return [h, sv * 100, v * 100]; -}; - -convert.hsv.rgb = function (hsv) { - const h = hsv[0] / 60; - const s = hsv[1] / 100; - let v = hsv[2] / 100; - const hi = Math.floor(h) % 6; - - const f = h - Math.floor(h); - const p = 255 * v * (1 - s); - const q = 255 * v * (1 - (s * f)); - const t = 255 * v * (1 - (s * (1 - f))); - v *= 255; - - switch (hi) { - case 0: - return [v, t, p]; - case 1: - return [q, v, p]; - case 2: - return [p, v, t]; - case 3: - return [p, q, v]; - case 4: - return [t, p, v]; - case 5: - return [v, p, q]; - } -}; - -convert.hsv.hsl = function (hsv) { - const h = hsv[0]; - const s = hsv[1] / 100; - const v = hsv[2] / 100; - const vmin = Math.max(v, 0.01); - let sl; - let l; - - l = (2 - s) * v; - const lmin = (2 - s) * vmin; - sl = s * vmin; - sl /= (lmin <= 1) ? lmin : 2 - lmin; - sl = sl || 0; - l /= 2; - - return [h, sl * 100, l * 100]; -}; - -// http://dev.w3.org/csswg/css-color/#hwb-to-rgb -convert.hwb.rgb = function (hwb) { - const h = hwb[0] / 360; - let wh = hwb[1] / 100; - let bl = hwb[2] / 100; - const ratio = wh + bl; - let f; - - // Wh + bl cant be > 1 - if (ratio > 1) { - wh /= ratio; - bl /= ratio; - } - - const i = Math.floor(6 * h); - const v = 1 - bl; - f = 6 * h - i; - - if ((i & 0x01) !== 0) { - f = 1 - f; - } - - const n = wh + f * (v - wh); // Linear interpolation - - let r; - let g; - let b; - /* eslint-disable max-statements-per-line,no-multi-spaces */ - switch (i) { - default: - case 6: - case 0: r = v; g = n; b = wh; break; - case 1: r = n; g = v; b = wh; break; - case 2: r = wh; g = v; b = n; break; - case 3: r = wh; g = n; b = v; break; - case 4: r = n; g = wh; b = v; break; - case 5: r = v; g = wh; b = n; break; - } - /* eslint-enable max-statements-per-line,no-multi-spaces */ - - return [r * 255, g * 255, b * 255]; -}; - -convert.cmyk.rgb = function (cmyk) { - const c = cmyk[0] / 100; - const m = cmyk[1] / 100; - const y = cmyk[2] / 100; - const k = cmyk[3] / 100; - - const r = 1 - Math.min(1, c * (1 - k) + k); - const g = 1 - Math.min(1, m * (1 - k) + k); - const b = 1 - Math.min(1, y * (1 - k) + k); - - return [r * 255, g * 255, b * 255]; -}; - -convert.xyz.rgb = function (xyz) { - const x = xyz[0] / 100; - const y = xyz[1] / 100; - const z = xyz[2] / 100; - let r; - let g; - let b; - - r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); - g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); - b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); - - // Assume sRGB - r = r > 0.0031308 - ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) - : r * 12.92; - - g = g > 0.0031308 - ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) - : g * 12.92; - - b = b > 0.0031308 - ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) - : b * 12.92; - - r = Math.min(Math.max(0, r), 1); - g = Math.min(Math.max(0, g), 1); - b = Math.min(Math.max(0, b), 1); - - return [r * 255, g * 255, b * 255]; -}; - -convert.xyz.lab = function (xyz) { - let x = xyz[0]; - let y = xyz[1]; - let z = xyz[2]; - - x /= 95.047; - y /= 100; - z /= 108.883; - - x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); - - const l = (116 * y) - 16; - const a = 500 * (x - y); - const b = 200 * (y - z); - - return [l, a, b]; -}; - -convert.lab.xyz = function (lab) { - const l = lab[0]; - const a = lab[1]; - const b = lab[2]; - let x; - let y; - let z; - - y = (l + 16) / 116; - x = a / 500 + y; - z = y - b / 200; - - const y2 = y ** 3; - const x2 = x ** 3; - const z2 = z ** 3; - y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; - x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; - z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; - - x *= 95.047; - y *= 100; - z *= 108.883; - - return [x, y, z]; -}; - -convert.lab.lch = function (lab) { - const l = lab[0]; - const a = lab[1]; - const b = lab[2]; - let h; - - const hr = Math.atan2(b, a); - h = hr * 360 / 2 / Math.PI; - - if (h < 0) { - h += 360; - } - - const c = Math.sqrt(a * a + b * b); - - return [l, c, h]; -}; - -convert.lch.lab = function (lch) { - const l = lch[0]; - const c = lch[1]; - const h = lch[2]; - - const hr = h / 360 * 2 * Math.PI; - const a = c * Math.cos(hr); - const b = c * Math.sin(hr); - - return [l, a, b]; -}; - -convert.rgb.ansi16 = function (args, saturation = null) { - const [r, g, b] = args; - let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization - - value = Math.round(value / 50); - - if (value === 0) { - return 30; - } - - let ansi = 30 - + ((Math.round(b / 255) << 2) - | (Math.round(g / 255) << 1) - | Math.round(r / 255)); - - if (value === 2) { - ansi += 60; - } - - return ansi; -}; - -convert.hsv.ansi16 = function (args) { - // Optimization here; we already know the value and don't need to get - // it converted for us. - return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); -}; - -convert.rgb.ansi256 = function (args) { - const r = args[0]; - const g = args[1]; - const b = args[2]; - - // We use the extended greyscale palette here, with the exception of - // black and white. normal palette only has 4 greyscale shades. - if (r === g && g === b) { - if (r < 8) { - return 16; - } - - if (r > 248) { - return 231; - } - - return Math.round(((r - 8) / 247) * 24) + 232; - } - - const ansi = 16 - + (36 * Math.round(r / 255 * 5)) - + (6 * Math.round(g / 255 * 5)) - + Math.round(b / 255 * 5); - - return ansi; -}; - -convert.ansi16.rgb = function (args) { - let color = args % 10; - - // Handle greyscale - if (color === 0 || color === 7) { - if (args > 50) { - color += 3.5; - } - - color = color / 10.5 * 255; - - return [color, color, color]; - } - - const mult = (~~(args > 50) + 1) * 0.5; - const r = ((color & 1) * mult) * 255; - const g = (((color >> 1) & 1) * mult) * 255; - const b = (((color >> 2) & 1) * mult) * 255; - - return [r, g, b]; -}; - -convert.ansi256.rgb = function (args) { - // Handle greyscale - if (args >= 232) { - const c = (args - 232) * 10 + 8; - return [c, c, c]; - } - - args -= 16; - - let rem; - const r = Math.floor(args / 36) / 5 * 255; - const g = Math.floor((rem = args % 36) / 6) / 5 * 255; - const b = (rem % 6) / 5 * 255; - - return [r, g, b]; -}; - -convert.rgb.hex = function (args) { - const integer = ((Math.round(args[0]) & 0xFF) << 16) - + ((Math.round(args[1]) & 0xFF) << 8) - + (Math.round(args[2]) & 0xFF); - - const string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; -}; - -convert.hex.rgb = function (args) { - const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); - if (!match) { - return [0, 0, 0]; - } - - let colorString = match[0]; - - if (match[0].length === 3) { - colorString = colorString.split('').map(char => { - return char + char; - }).join(''); - } - - const integer = parseInt(colorString, 16); - const r = (integer >> 16) & 0xFF; - const g = (integer >> 8) & 0xFF; - const b = integer & 0xFF; - - return [r, g, b]; -}; - -convert.rgb.hcg = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const max = Math.max(Math.max(r, g), b); - const min = Math.min(Math.min(r, g), b); - const chroma = (max - min); - let grayscale; - let hue; - - if (chroma < 1) { - grayscale = min / (1 - chroma); - } else { - grayscale = 0; - } - - if (chroma <= 0) { - hue = 0; - } else - if (max === r) { - hue = ((g - b) / chroma) % 6; - } else - if (max === g) { - hue = 2 + (b - r) / chroma; - } else { - hue = 4 + (r - g) / chroma; - } - - hue /= 6; - hue %= 1; - - return [hue * 360, chroma * 100, grayscale * 100]; -}; - -convert.hsl.hcg = function (hsl) { - const s = hsl[1] / 100; - const l = hsl[2] / 100; - - const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); - - let f = 0; - if (c < 1.0) { - f = (l - 0.5 * c) / (1.0 - c); - } - - return [hsl[0], c * 100, f * 100]; -}; - -convert.hsv.hcg = function (hsv) { - const s = hsv[1] / 100; - const v = hsv[2] / 100; - - const c = s * v; - let f = 0; - - if (c < 1.0) { - f = (v - c) / (1 - c); - } - - return [hsv[0], c * 100, f * 100]; -}; - -convert.hcg.rgb = function (hcg) { - const h = hcg[0] / 360; - const c = hcg[1] / 100; - const g = hcg[2] / 100; - - if (c === 0.0) { - return [g * 255, g * 255, g * 255]; - } - - const pure = [0, 0, 0]; - const hi = (h % 1) * 6; - const v = hi % 1; - const w = 1 - v; - let mg = 0; - - /* eslint-disable max-statements-per-line */ - switch (Math.floor(hi)) { - case 0: - pure[0] = 1; pure[1] = v; pure[2] = 0; break; - case 1: - pure[0] = w; pure[1] = 1; pure[2] = 0; break; - case 2: - pure[0] = 0; pure[1] = 1; pure[2] = v; break; - case 3: - pure[0] = 0; pure[1] = w; pure[2] = 1; break; - case 4: - pure[0] = v; pure[1] = 0; pure[2] = 1; break; - default: - pure[0] = 1; pure[1] = 0; pure[2] = w; - } - /* eslint-enable max-statements-per-line */ - - mg = (1.0 - c) * g; - - return [ - (c * pure[0] + mg) * 255, - (c * pure[1] + mg) * 255, - (c * pure[2] + mg) * 255 - ]; -}; - -convert.hcg.hsv = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - - const v = c + g * (1.0 - c); - let f = 0; - - if (v > 0.0) { - f = c / v; - } - - return [hcg[0], f * 100, v * 100]; -}; - -convert.hcg.hsl = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - - const l = g * (1.0 - c) + 0.5 * c; - let s = 0; - - if (l > 0.0 && l < 0.5) { - s = c / (2 * l); - } else - if (l >= 0.5 && l < 1.0) { - s = c / (2 * (1 - l)); - } - - return [hcg[0], s * 100, l * 100]; -}; - -convert.hcg.hwb = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - const v = c + g * (1.0 - c); - return [hcg[0], (v - c) * 100, (1 - v) * 100]; -}; - -convert.hwb.hcg = function (hwb) { - const w = hwb[1] / 100; - const b = hwb[2] / 100; - const v = 1 - b; - const c = v - w; - let g = 0; - - if (c < 1) { - g = (v - c) / (1 - c); - } - - return [hwb[0], c * 100, g * 100]; -}; - -convert.apple.rgb = function (apple) { - return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; -}; - -convert.rgb.apple = function (rgb) { - return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; -}; - -convert.gray.rgb = function (args) { - return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; -}; - -convert.gray.hsl = function (args) { - return [0, 0, args[0]]; -}; - -convert.gray.hsv = convert.gray.hsl; - -convert.gray.hwb = function (gray) { - return [0, 100, gray[0]]; -}; - -convert.gray.cmyk = function (gray) { - return [0, 0, 0, gray[0]]; -}; - -convert.gray.lab = function (gray) { - return [gray[0], 0, 0]; -}; - -convert.gray.hex = function (gray) { - const val = Math.round(gray[0] / 100 * 255) & 0xFF; - const integer = (val << 16) + (val << 8) + val; - - const string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; -}; - -convert.rgb.gray = function (rgb) { - const val = (rgb[0] + rgb[1] + rgb[2]) / 3; - return [val / 255 * 100]; -}; diff --git a/claude-code-source/node_modules/color-convert/index.js b/claude-code-source/node_modules/color-convert/index.js deleted file mode 100644 index b648e573..00000000 --- a/claude-code-source/node_modules/color-convert/index.js +++ /dev/null @@ -1,81 +0,0 @@ -const conversions = require('./conversions'); -const route = require('./route'); - -const convert = {}; - -const models = Object.keys(conversions); - -function wrapRaw(fn) { - const wrappedFn = function (...args) { - const arg0 = args[0]; - if (arg0 === undefined || arg0 === null) { - return arg0; - } - - if (arg0.length > 1) { - args = arg0; - } - - return fn(args); - }; - - // Preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } - - return wrappedFn; -} - -function wrapRounded(fn) { - const wrappedFn = function (...args) { - const arg0 = args[0]; - - if (arg0 === undefined || arg0 === null) { - return arg0; - } - - if (arg0.length > 1) { - args = arg0; - } - - const result = fn(args); - - // We're assuming the result is an array here. - // see notice in conversions.js; don't use box types - // in conversion functions. - if (typeof result === 'object') { - for (let len = result.length, i = 0; i < len; i++) { - result[i] = Math.round(result[i]); - } - } - - return result; - }; - - // Preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } - - return wrappedFn; -} - -models.forEach(fromModel => { - convert[fromModel] = {}; - - Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); - Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); - - const routes = route(fromModel); - const routeModels = Object.keys(routes); - - routeModels.forEach(toModel => { - const fn = routes[toModel]; - - convert[fromModel][toModel] = wrapRounded(fn); - convert[fromModel][toModel].raw = wrapRaw(fn); - }); -}); - -module.exports = convert; diff --git a/claude-code-source/node_modules/color-convert/route.js b/claude-code-source/node_modules/color-convert/route.js deleted file mode 100644 index 1a08521b..00000000 --- a/claude-code-source/node_modules/color-convert/route.js +++ /dev/null @@ -1,97 +0,0 @@ -const conversions = require('./conversions'); - -/* - This function routes a model to all other models. - - all functions that are routed have a property `.conversion` attached - to the returned synthetic function. This property is an array - of strings, each with the steps in between the 'from' and 'to' - color models (inclusive). - - conversions that are not possible simply are not included. -*/ - -function buildGraph() { - const graph = {}; - // https://jsperf.com/object-keys-vs-for-in-with-closure/3 - const models = Object.keys(conversions); - - for (let len = models.length, i = 0; i < len; i++) { - graph[models[i]] = { - // http://jsperf.com/1-vs-infinity - // micro-opt, but this is simple. - distance: -1, - parent: null - }; - } - - return graph; -} - -// https://en.wikipedia.org/wiki/Breadth-first_search -function deriveBFS(fromModel) { - const graph = buildGraph(); - const queue = [fromModel]; // Unshift -> queue -> pop - - graph[fromModel].distance = 0; - - while (queue.length) { - const current = queue.pop(); - const adjacents = Object.keys(conversions[current]); - - for (let len = adjacents.length, i = 0; i < len; i++) { - const adjacent = adjacents[i]; - const node = graph[adjacent]; - - if (node.distance === -1) { - node.distance = graph[current].distance + 1; - node.parent = current; - queue.unshift(adjacent); - } - } - } - - return graph; -} - -function link(from, to) { - return function (args) { - return to(from(args)); - }; -} - -function wrapConversion(toModel, graph) { - const path = [graph[toModel].parent, toModel]; - let fn = conversions[graph[toModel].parent][toModel]; - - let cur = graph[toModel].parent; - while (graph[cur].parent) { - path.unshift(graph[cur].parent); - fn = link(conversions[graph[cur].parent][cur], fn); - cur = graph[cur].parent; - } - - fn.conversion = path; - return fn; -} - -module.exports = function (fromModel) { - const graph = deriveBFS(fromModel); - const conversion = {}; - - const models = Object.keys(graph); - for (let len = models.length, i = 0; i < len; i++) { - const toModel = models[i]; - const node = graph[toModel]; - - if (node.parent === null) { - // No possible conversion, or this node is the source model. - continue; - } - - conversion[toModel] = wrapConversion(toModel, graph); - } - - return conversion; -}; - diff --git a/claude-code-source/node_modules/color-name/index.js b/claude-code-source/node_modules/color-name/index.js deleted file mode 100644 index b7c198a6..00000000 --- a/claude-code-source/node_modules/color-name/index.js +++ /dev/null @@ -1,152 +0,0 @@ -'use strict' - -module.exports = { - "aliceblue": [240, 248, 255], - "antiquewhite": [250, 235, 215], - "aqua": [0, 255, 255], - "aquamarine": [127, 255, 212], - "azure": [240, 255, 255], - "beige": [245, 245, 220], - "bisque": [255, 228, 196], - "black": [0, 0, 0], - "blanchedalmond": [255, 235, 205], - "blue": [0, 0, 255], - "blueviolet": [138, 43, 226], - "brown": [165, 42, 42], - "burlywood": [222, 184, 135], - "cadetblue": [95, 158, 160], - "chartreuse": [127, 255, 0], - "chocolate": [210, 105, 30], - "coral": [255, 127, 80], - "cornflowerblue": [100, 149, 237], - "cornsilk": [255, 248, 220], - "crimson": [220, 20, 60], - "cyan": [0, 255, 255], - "darkblue": [0, 0, 139], - "darkcyan": [0, 139, 139], - "darkgoldenrod": [184, 134, 11], - "darkgray": [169, 169, 169], - "darkgreen": [0, 100, 0], - "darkgrey": [169, 169, 169], - "darkkhaki": [189, 183, 107], - "darkmagenta": [139, 0, 139], - "darkolivegreen": [85, 107, 47], - "darkorange": [255, 140, 0], - "darkorchid": [153, 50, 204], - "darkred": [139, 0, 0], - "darksalmon": [233, 150, 122], - "darkseagreen": [143, 188, 143], - "darkslateblue": [72, 61, 139], - "darkslategray": [47, 79, 79], - "darkslategrey": [47, 79, 79], - "darkturquoise": [0, 206, 209], - "darkviolet": [148, 0, 211], - "deeppink": [255, 20, 147], - "deepskyblue": [0, 191, 255], - "dimgray": [105, 105, 105], - "dimgrey": [105, 105, 105], - "dodgerblue": [30, 144, 255], - "firebrick": [178, 34, 34], - "floralwhite": [255, 250, 240], - "forestgreen": [34, 139, 34], - "fuchsia": [255, 0, 255], - "gainsboro": [220, 220, 220], - "ghostwhite": [248, 248, 255], - "gold": [255, 215, 0], - "goldenrod": [218, 165, 32], - "gray": [128, 128, 128], - "green": [0, 128, 0], - "greenyellow": [173, 255, 47], - "grey": [128, 128, 128], - "honeydew": [240, 255, 240], - "hotpink": [255, 105, 180], - "indianred": [205, 92, 92], - "indigo": [75, 0, 130], - "ivory": [255, 255, 240], - "khaki": [240, 230, 140], - "lavender": [230, 230, 250], - "lavenderblush": [255, 240, 245], - "lawngreen": [124, 252, 0], - "lemonchiffon": [255, 250, 205], - "lightblue": [173, 216, 230], - "lightcoral": [240, 128, 128], - "lightcyan": [224, 255, 255], - "lightgoldenrodyellow": [250, 250, 210], - "lightgray": [211, 211, 211], - "lightgreen": [144, 238, 144], - "lightgrey": [211, 211, 211], - "lightpink": [255, 182, 193], - "lightsalmon": [255, 160, 122], - "lightseagreen": [32, 178, 170], - "lightskyblue": [135, 206, 250], - "lightslategray": [119, 136, 153], - "lightslategrey": [119, 136, 153], - "lightsteelblue": [176, 196, 222], - "lightyellow": [255, 255, 224], - "lime": [0, 255, 0], - "limegreen": [50, 205, 50], - "linen": [250, 240, 230], - "magenta": [255, 0, 255], - "maroon": [128, 0, 0], - "mediumaquamarine": [102, 205, 170], - "mediumblue": [0, 0, 205], - "mediumorchid": [186, 85, 211], - "mediumpurple": [147, 112, 219], - "mediumseagreen": [60, 179, 113], - "mediumslateblue": [123, 104, 238], - "mediumspringgreen": [0, 250, 154], - "mediumturquoise": [72, 209, 204], - "mediumvioletred": [199, 21, 133], - "midnightblue": [25, 25, 112], - "mintcream": [245, 255, 250], - "mistyrose": [255, 228, 225], - "moccasin": [255, 228, 181], - "navajowhite": [255, 222, 173], - "navy": [0, 0, 128], - "oldlace": [253, 245, 230], - "olive": [128, 128, 0], - "olivedrab": [107, 142, 35], - "orange": [255, 165, 0], - "orangered": [255, 69, 0], - "orchid": [218, 112, 214], - "palegoldenrod": [238, 232, 170], - "palegreen": [152, 251, 152], - "paleturquoise": [175, 238, 238], - "palevioletred": [219, 112, 147], - "papayawhip": [255, 239, 213], - "peachpuff": [255, 218, 185], - "peru": [205, 133, 63], - "pink": [255, 192, 203], - "plum": [221, 160, 221], - "powderblue": [176, 224, 230], - "purple": [128, 0, 128], - "rebeccapurple": [102, 51, 153], - "red": [255, 0, 0], - "rosybrown": [188, 143, 143], - "royalblue": [65, 105, 225], - "saddlebrown": [139, 69, 19], - "salmon": [250, 128, 114], - "sandybrown": [244, 164, 96], - "seagreen": [46, 139, 87], - "seashell": [255, 245, 238], - "sienna": [160, 82, 45], - "silver": [192, 192, 192], - "skyblue": [135, 206, 235], - "slateblue": [106, 90, 205], - "slategray": [112, 128, 144], - "slategrey": [112, 128, 144], - "snow": [255, 250, 250], - "springgreen": [0, 255, 127], - "steelblue": [70, 130, 180], - "tan": [210, 180, 140], - "teal": [0, 128, 128], - "thistle": [216, 191, 216], - "tomato": [255, 99, 71], - "turquoise": [64, 224, 208], - "violet": [238, 130, 238], - "wheat": [245, 222, 179], - "white": [255, 255, 255], - "whitesmoke": [245, 245, 245], - "yellow": [255, 255, 0], - "yellowgreen": [154, 205, 50] -}; diff --git a/claude-code-source/node_modules/combined-stream/lib/combined_stream.js b/claude-code-source/node_modules/combined-stream/lib/combined_stream.js deleted file mode 100644 index 125f097f..00000000 --- a/claude-code-source/node_modules/combined-stream/lib/combined_stream.js +++ /dev/null @@ -1,208 +0,0 @@ -var util = require('util'); -var Stream = require('stream').Stream; -var DelayedStream = require('delayed-stream'); - -module.exports = CombinedStream; -function CombinedStream() { - this.writable = false; - this.readable = true; - this.dataSize = 0; - this.maxDataSize = 2 * 1024 * 1024; - this.pauseStreams = true; - - this._released = false; - this._streams = []; - this._currentStream = null; - this._insideLoop = false; - this._pendingNext = false; -} -util.inherits(CombinedStream, Stream); - -CombinedStream.create = function(options) { - var combinedStream = new this(); - - options = options || {}; - for (var option in options) { - combinedStream[option] = options[option]; - } - - return combinedStream; -}; - -CombinedStream.isStreamLike = function(stream) { - return (typeof stream !== 'function') - && (typeof stream !== 'string') - && (typeof stream !== 'boolean') - && (typeof stream !== 'number') - && (!Buffer.isBuffer(stream)); -}; - -CombinedStream.prototype.append = function(stream) { - var isStreamLike = CombinedStream.isStreamLike(stream); - - if (isStreamLike) { - if (!(stream instanceof DelayedStream)) { - var newStream = DelayedStream.create(stream, { - maxDataSize: Infinity, - pauseStream: this.pauseStreams, - }); - stream.on('data', this._checkDataSize.bind(this)); - stream = newStream; - } - - this._handleErrors(stream); - - if (this.pauseStreams) { - stream.pause(); - } - } - - this._streams.push(stream); - return this; -}; - -CombinedStream.prototype.pipe = function(dest, options) { - Stream.prototype.pipe.call(this, dest, options); - this.resume(); - return dest; -}; - -CombinedStream.prototype._getNext = function() { - this._currentStream = null; - - if (this._insideLoop) { - this._pendingNext = true; - return; // defer call - } - - this._insideLoop = true; - try { - do { - this._pendingNext = false; - this._realGetNext(); - } while (this._pendingNext); - } finally { - this._insideLoop = false; - } -}; - -CombinedStream.prototype._realGetNext = function() { - var stream = this._streams.shift(); - - - if (typeof stream == 'undefined') { - this.end(); - return; - } - - if (typeof stream !== 'function') { - this._pipeNext(stream); - return; - } - - var getStream = stream; - getStream(function(stream) { - var isStreamLike = CombinedStream.isStreamLike(stream); - if (isStreamLike) { - stream.on('data', this._checkDataSize.bind(this)); - this._handleErrors(stream); - } - - this._pipeNext(stream); - }.bind(this)); -}; - -CombinedStream.prototype._pipeNext = function(stream) { - this._currentStream = stream; - - var isStreamLike = CombinedStream.isStreamLike(stream); - if (isStreamLike) { - stream.on('end', this._getNext.bind(this)); - stream.pipe(this, {end: false}); - return; - } - - var value = stream; - this.write(value); - this._getNext(); -}; - -CombinedStream.prototype._handleErrors = function(stream) { - var self = this; - stream.on('error', function(err) { - self._emitError(err); - }); -}; - -CombinedStream.prototype.write = function(data) { - this.emit('data', data); -}; - -CombinedStream.prototype.pause = function() { - if (!this.pauseStreams) { - return; - } - - if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); - this.emit('pause'); -}; - -CombinedStream.prototype.resume = function() { - if (!this._released) { - this._released = true; - this.writable = true; - this._getNext(); - } - - if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); - this.emit('resume'); -}; - -CombinedStream.prototype.end = function() { - this._reset(); - this.emit('end'); -}; - -CombinedStream.prototype.destroy = function() { - this._reset(); - this.emit('close'); -}; - -CombinedStream.prototype._reset = function() { - this.writable = false; - this._streams = []; - this._currentStream = null; -}; - -CombinedStream.prototype._checkDataSize = function() { - this._updateDataSize(); - if (this.dataSize <= this.maxDataSize) { - return; - } - - var message = - 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; - this._emitError(new Error(message)); -}; - -CombinedStream.prototype._updateDataSize = function() { - this.dataSize = 0; - - var self = this; - this._streams.forEach(function(stream) { - if (!stream.dataSize) { - return; - } - - self.dataSize += stream.dataSize; - }); - - if (this._currentStream && this._currentStream.dataSize) { - this.dataSize += this._currentStream.dataSize; - } -}; - -CombinedStream.prototype._emitError = function(err) { - this._reset(); - this.emit('error', err); -}; diff --git a/claude-code-source/node_modules/commander/index.js b/claude-code-source/node_modules/commander/index.js deleted file mode 100644 index c30bb21a..00000000 --- a/claude-code-source/node_modules/commander/index.js +++ /dev/null @@ -1,24 +0,0 @@ -const { Argument } = require('./lib/argument.js'); -const { Command } = require('./lib/command.js'); -const { CommanderError, InvalidArgumentError } = require('./lib/error.js'); -const { Help } = require('./lib/help.js'); -const { Option } = require('./lib/option.js'); - -exports.program = new Command(); - -exports.createCommand = (name) => new Command(name); -exports.createOption = (flags, description) => new Option(flags, description); -exports.createArgument = (name, description) => new Argument(name, description); - -/** - * Expose classes - */ - -exports.Command = Command; -exports.Option = Option; -exports.Argument = Argument; -exports.Help = Help; - -exports.CommanderError = CommanderError; -exports.InvalidArgumentError = InvalidArgumentError; -exports.InvalidOptionArgumentError = InvalidArgumentError; // Deprecated diff --git a/claude-code-source/node_modules/commander/lib/argument.js b/claude-code-source/node_modules/commander/lib/argument.js deleted file mode 100644 index ee46c365..00000000 --- a/claude-code-source/node_modules/commander/lib/argument.js +++ /dev/null @@ -1,149 +0,0 @@ -const { InvalidArgumentError } = require('./error.js'); - -class Argument { - /** - * Initialize a new command argument with the given name and description. - * The default is that the argument is required, and you can explicitly - * indicate this with <> around the name. Put [] around the name for an optional argument. - * - * @param {string} name - * @param {string} [description] - */ - - constructor(name, description) { - this.description = description || ''; - this.variadic = false; - this.parseArg = undefined; - this.defaultValue = undefined; - this.defaultValueDescription = undefined; - this.argChoices = undefined; - - switch (name[0]) { - case '<': // e.g. - this.required = true; - this._name = name.slice(1, -1); - break; - case '[': // e.g. [optional] - this.required = false; - this._name = name.slice(1, -1); - break; - default: - this.required = true; - this._name = name; - break; - } - - if (this._name.length > 3 && this._name.slice(-3) === '...') { - this.variadic = true; - this._name = this._name.slice(0, -3); - } - } - - /** - * Return argument name. - * - * @return {string} - */ - - name() { - return this._name; - } - - /** - * @package - */ - - _concatValue(value, previous) { - if (previous === this.defaultValue || !Array.isArray(previous)) { - return [value]; - } - - return previous.concat(value); - } - - /** - * Set the default value, and optionally supply the description to be displayed in the help. - * - * @param {*} value - * @param {string} [description] - * @return {Argument} - */ - - default(value, description) { - this.defaultValue = value; - this.defaultValueDescription = description; - return this; - } - - /** - * Set the custom handler for processing CLI command arguments into argument values. - * - * @param {Function} [fn] - * @return {Argument} - */ - - argParser(fn) { - this.parseArg = fn; - return this; - } - - /** - * Only allow argument value to be one of choices. - * - * @param {string[]} values - * @return {Argument} - */ - - choices(values) { - this.argChoices = values.slice(); - this.parseArg = (arg, previous) => { - if (!this.argChoices.includes(arg)) { - throw new InvalidArgumentError( - `Allowed choices are ${this.argChoices.join(', ')}.`, - ); - } - if (this.variadic) { - return this._concatValue(arg, previous); - } - return arg; - }; - return this; - } - - /** - * Make argument required. - * - * @returns {Argument} - */ - argRequired() { - this.required = true; - return this; - } - - /** - * Make argument optional. - * - * @returns {Argument} - */ - argOptional() { - this.required = false; - return this; - } -} - -/** - * Takes an argument and returns its human readable equivalent for help usage. - * - * @param {Argument} arg - * @return {string} - * @private - */ - -function humanReadableArgName(arg) { - const nameOutput = arg.name() + (arg.variadic === true ? '...' : ''); - - return arg.required ? '<' + nameOutput + '>' : '[' + nameOutput + ']'; -} - -exports.Argument = Argument; -exports.humanReadableArgName = humanReadableArgName; diff --git a/claude-code-source/node_modules/commander/lib/command.js b/claude-code-source/node_modules/commander/lib/command.js deleted file mode 100644 index 20ced4b8..00000000 --- a/claude-code-source/node_modules/commander/lib/command.js +++ /dev/null @@ -1,2509 +0,0 @@ -const EventEmitter = require('node:events').EventEmitter; -const childProcess = require('node:child_process'); -const path = require('node:path'); -const fs = require('node:fs'); -const process = require('node:process'); - -const { Argument, humanReadableArgName } = require('./argument.js'); -const { CommanderError } = require('./error.js'); -const { Help } = require('./help.js'); -const { Option, DualOptions } = require('./option.js'); -const { suggestSimilar } = require('./suggestSimilar'); - -class Command extends EventEmitter { - /** - * Initialize a new `Command`. - * - * @param {string} [name] - */ - - constructor(name) { - super(); - /** @type {Command[]} */ - this.commands = []; - /** @type {Option[]} */ - this.options = []; - this.parent = null; - this._allowUnknownOption = false; - this._allowExcessArguments = true; - /** @type {Argument[]} */ - this.registeredArguments = []; - this._args = this.registeredArguments; // deprecated old name - /** @type {string[]} */ - this.args = []; // cli args with options removed - this.rawArgs = []; - this.processedArgs = []; // like .args but after custom processing and collecting variadic - this._scriptPath = null; - this._name = name || ''; - this._optionValues = {}; - this._optionValueSources = {}; // default, env, cli etc - this._storeOptionsAsProperties = false; - this._actionHandler = null; - this._executableHandler = false; - this._executableFile = null; // custom name for executable - this._executableDir = null; // custom search directory for subcommands - this._defaultCommandName = null; - this._exitCallback = null; - this._aliases = []; - this._combineFlagAndOptionalValue = true; - this._description = ''; - this._summary = ''; - this._argsDescription = undefined; // legacy - this._enablePositionalOptions = false; - this._passThroughOptions = false; - this._lifeCycleHooks = {}; // a hash of arrays - /** @type {(boolean | string)} */ - this._showHelpAfterError = false; - this._showSuggestionAfterError = true; - - // see .configureOutput() for docs - this._outputConfiguration = { - writeOut: (str) => process.stdout.write(str), - writeErr: (str) => process.stderr.write(str), - getOutHelpWidth: () => - process.stdout.isTTY ? process.stdout.columns : undefined, - getErrHelpWidth: () => - process.stderr.isTTY ? process.stderr.columns : undefined, - outputError: (str, write) => write(str), - }; - - this._hidden = false; - /** @type {(Option | null | undefined)} */ - this._helpOption = undefined; // Lazy created on demand. May be null if help option is disabled. - this._addImplicitHelpCommand = undefined; // undecided whether true or false yet, not inherited - /** @type {Command} */ - this._helpCommand = undefined; // lazy initialised, inherited - this._helpConfiguration = {}; - } - - /** - * Copy settings that are useful to have in common across root command and subcommands. - * - * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.) - * - * @param {Command} sourceCommand - * @return {Command} `this` command for chaining - */ - copyInheritedSettings(sourceCommand) { - this._outputConfiguration = sourceCommand._outputConfiguration; - this._helpOption = sourceCommand._helpOption; - this._helpCommand = sourceCommand._helpCommand; - this._helpConfiguration = sourceCommand._helpConfiguration; - this._exitCallback = sourceCommand._exitCallback; - this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties; - this._combineFlagAndOptionalValue = - sourceCommand._combineFlagAndOptionalValue; - this._allowExcessArguments = sourceCommand._allowExcessArguments; - this._enablePositionalOptions = sourceCommand._enablePositionalOptions; - this._showHelpAfterError = sourceCommand._showHelpAfterError; - this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError; - - return this; - } - - /** - * @returns {Command[]} - * @private - */ - - _getCommandAndAncestors() { - const result = []; - // eslint-disable-next-line @typescript-eslint/no-this-alias - for (let command = this; command; command = command.parent) { - result.push(command); - } - return result; - } - - /** - * Define a command. - * - * There are two styles of command: pay attention to where to put the description. - * - * @example - * // Command implemented using action handler (description is supplied separately to `.command`) - * program - * .command('clone [destination]') - * .description('clone a repository into a newly created directory') - * .action((source, destination) => { - * console.log('clone command called'); - * }); - * - * // Command implemented using separate executable file (description is second parameter to `.command`) - * program - * .command('start ', 'start named service') - * .command('stop [service]', 'stop named service, or all if no name supplied'); - * - * @param {string} nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` - * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable) - * @param {object} [execOpts] - configuration options (for executable) - * @return {Command} returns new command for action handler, or `this` for executable command - */ - - command(nameAndArgs, actionOptsOrExecDesc, execOpts) { - let desc = actionOptsOrExecDesc; - let opts = execOpts; - if (typeof desc === 'object' && desc !== null) { - opts = desc; - desc = null; - } - opts = opts || {}; - const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/); - - const cmd = this.createCommand(name); - if (desc) { - cmd.description(desc); - cmd._executableHandler = true; - } - if (opts.isDefault) this._defaultCommandName = cmd._name; - cmd._hidden = !!(opts.noHelp || opts.hidden); // noHelp is deprecated old name for hidden - cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor - if (args) cmd.arguments(args); - this._registerCommand(cmd); - cmd.parent = this; - cmd.copyInheritedSettings(this); - - if (desc) return this; - return cmd; - } - - /** - * Factory routine to create a new unattached command. - * - * See .command() for creating an attached subcommand, which uses this routine to - * create the command. You can override createCommand to customise subcommands. - * - * @param {string} [name] - * @return {Command} new command - */ - - createCommand(name) { - return new Command(name); - } - - /** - * You can customise the help with a subclass of Help by overriding createHelp, - * or by overriding Help properties using configureHelp(). - * - * @return {Help} - */ - - createHelp() { - return Object.assign(new Help(), this.configureHelp()); - } - - /** - * You can customise the help by overriding Help properties using configureHelp(), - * or with a subclass of Help by overriding createHelp(). - * - * @param {object} [configuration] - configuration options - * @return {(Command | object)} `this` command for chaining, or stored configuration - */ - - configureHelp(configuration) { - if (configuration === undefined) return this._helpConfiguration; - - this._helpConfiguration = configuration; - return this; - } - - /** - * The default output goes to stdout and stderr. You can customise this for special - * applications. You can also customise the display of errors by overriding outputError. - * - * The configuration properties are all functions: - * - * // functions to change where being written, stdout and stderr - * writeOut(str) - * writeErr(str) - * // matching functions to specify width for wrapping help - * getOutHelpWidth() - * getErrHelpWidth() - * // functions based on what is being written out - * outputError(str, write) // used for displaying errors, and not used for displaying help - * - * @param {object} [configuration] - configuration options - * @return {(Command | object)} `this` command for chaining, or stored configuration - */ - - configureOutput(configuration) { - if (configuration === undefined) return this._outputConfiguration; - - Object.assign(this._outputConfiguration, configuration); - return this; - } - - /** - * Display the help or a custom message after an error occurs. - * - * @param {(boolean|string)} [displayHelp] - * @return {Command} `this` command for chaining - */ - showHelpAfterError(displayHelp = true) { - if (typeof displayHelp !== 'string') displayHelp = !!displayHelp; - this._showHelpAfterError = displayHelp; - return this; - } - - /** - * Display suggestion of similar commands for unknown commands, or options for unknown options. - * - * @param {boolean} [displaySuggestion] - * @return {Command} `this` command for chaining - */ - showSuggestionAfterError(displaySuggestion = true) { - this._showSuggestionAfterError = !!displaySuggestion; - return this; - } - - /** - * Add a prepared subcommand. - * - * See .command() for creating an attached subcommand which inherits settings from its parent. - * - * @param {Command} cmd - new subcommand - * @param {object} [opts] - configuration options - * @return {Command} `this` command for chaining - */ - - addCommand(cmd, opts) { - if (!cmd._name) { - throw new Error(`Command passed to .addCommand() must have a name -- specify the name in Command constructor or using .name()`); - } - - opts = opts || {}; - if (opts.isDefault) this._defaultCommandName = cmd._name; - if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation - - this._registerCommand(cmd); - cmd.parent = this; - cmd._checkForBrokenPassThrough(); - - return this; - } - - /** - * Factory routine to create a new unattached argument. - * - * See .argument() for creating an attached argument, which uses this routine to - * create the argument. You can override createArgument to return a custom argument. - * - * @param {string} name - * @param {string} [description] - * @return {Argument} new argument - */ - - createArgument(name, description) { - return new Argument(name, description); - } - - /** - * Define argument syntax for command. - * - * The default is that the argument is required, and you can explicitly - * indicate this with <> around the name. Put [] around the name for an optional argument. - * - * @example - * program.argument(''); - * program.argument('[output-file]'); - * - * @param {string} name - * @param {string} [description] - * @param {(Function|*)} [fn] - custom argument processing function - * @param {*} [defaultValue] - * @return {Command} `this` command for chaining - */ - argument(name, description, fn, defaultValue) { - const argument = this.createArgument(name, description); - if (typeof fn === 'function') { - argument.default(defaultValue).argParser(fn); - } else { - argument.default(fn); - } - this.addArgument(argument); - return this; - } - - /** - * Define argument syntax for command, adding multiple at once (without descriptions). - * - * See also .argument(). - * - * @example - * program.arguments(' [env]'); - * - * @param {string} names - * @return {Command} `this` command for chaining - */ - - arguments(names) { - names - .trim() - .split(/ +/) - .forEach((detail) => { - this.argument(detail); - }); - return this; - } - - /** - * Define argument syntax for command, adding a prepared argument. - * - * @param {Argument} argument - * @return {Command} `this` command for chaining - */ - addArgument(argument) { - const previousArgument = this.registeredArguments.slice(-1)[0]; - if (previousArgument && previousArgument.variadic) { - throw new Error( - `only the last argument can be variadic '${previousArgument.name()}'`, - ); - } - if ( - argument.required && - argument.defaultValue !== undefined && - argument.parseArg === undefined - ) { - throw new Error( - `a default value for a required argument is never used: '${argument.name()}'`, - ); - } - this.registeredArguments.push(argument); - return this; - } - - /** - * Customise or override default help command. By default a help command is automatically added if your command has subcommands. - * - * @example - * program.helpCommand('help [cmd]'); - * program.helpCommand('help [cmd]', 'show help'); - * program.helpCommand(false); // suppress default help command - * program.helpCommand(true); // add help command even if no subcommands - * - * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added - * @param {string} [description] - custom description - * @return {Command} `this` command for chaining - */ - - helpCommand(enableOrNameAndArgs, description) { - if (typeof enableOrNameAndArgs === 'boolean') { - this._addImplicitHelpCommand = enableOrNameAndArgs; - return this; - } - - enableOrNameAndArgs = enableOrNameAndArgs ?? 'help [command]'; - const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/); - const helpDescription = description ?? 'display help for command'; - - const helpCommand = this.createCommand(helpName); - helpCommand.helpOption(false); - if (helpArgs) helpCommand.arguments(helpArgs); - if (helpDescription) helpCommand.description(helpDescription); - - this._addImplicitHelpCommand = true; - this._helpCommand = helpCommand; - - return this; - } - - /** - * Add prepared custom help command. - * - * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()` - * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only - * @return {Command} `this` command for chaining - */ - addHelpCommand(helpCommand, deprecatedDescription) { - // If not passed an object, call through to helpCommand for backwards compatibility, - // as addHelpCommand was originally used like helpCommand is now. - if (typeof helpCommand !== 'object') { - this.helpCommand(helpCommand, deprecatedDescription); - return this; - } - - this._addImplicitHelpCommand = true; - this._helpCommand = helpCommand; - return this; - } - - /** - * Lazy create help command. - * - * @return {(Command|null)} - * @package - */ - _getHelpCommand() { - const hasImplicitHelpCommand = - this._addImplicitHelpCommand ?? - (this.commands.length && - !this._actionHandler && - !this._findCommand('help')); - - if (hasImplicitHelpCommand) { - if (this._helpCommand === undefined) { - this.helpCommand(undefined, undefined); // use default name and description - } - return this._helpCommand; - } - return null; - } - - /** - * Add hook for life cycle event. - * - * @param {string} event - * @param {Function} listener - * @return {Command} `this` command for chaining - */ - - hook(event, listener) { - const allowedValues = ['preSubcommand', 'preAction', 'postAction']; - if (!allowedValues.includes(event)) { - throw new Error(`Unexpected value for event passed to hook : '${event}'. -Expecting one of '${allowedValues.join("', '")}'`); - } - if (this._lifeCycleHooks[event]) { - this._lifeCycleHooks[event].push(listener); - } else { - this._lifeCycleHooks[event] = [listener]; - } - return this; - } - - /** - * Register callback to use as replacement for calling process.exit. - * - * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing - * @return {Command} `this` command for chaining - */ - - exitOverride(fn) { - if (fn) { - this._exitCallback = fn; - } else { - this._exitCallback = (err) => { - if (err.code !== 'commander.executeSubCommandAsync') { - throw err; - } else { - // Async callback from spawn events, not useful to throw. - } - }; - } - return this; - } - - /** - * Call process.exit, and _exitCallback if defined. - * - * @param {number} exitCode exit code for using with process.exit - * @param {string} code an id string representing the error - * @param {string} message human-readable description of the error - * @return never - * @private - */ - - _exit(exitCode, code, message) { - if (this._exitCallback) { - this._exitCallback(new CommanderError(exitCode, code, message)); - // Expecting this line is not reached. - } - process.exit(exitCode); - } - - /** - * Register callback `fn` for the command. - * - * @example - * program - * .command('serve') - * .description('start service') - * .action(function() { - * // do work here - * }); - * - * @param {Function} fn - * @return {Command} `this` command for chaining - */ - - action(fn) { - const listener = (args) => { - // The .action callback takes an extra parameter which is the command or options. - const expectedArgsCount = this.registeredArguments.length; - const actionArgs = args.slice(0, expectedArgsCount); - if (this._storeOptionsAsProperties) { - actionArgs[expectedArgsCount] = this; // backwards compatible "options" - } else { - actionArgs[expectedArgsCount] = this.opts(); - } - actionArgs.push(this); - - return fn.apply(this, actionArgs); - }; - this._actionHandler = listener; - return this; - } - - /** - * Factory routine to create a new unattached option. - * - * See .option() for creating an attached option, which uses this routine to - * create the option. You can override createOption to return a custom option. - * - * @param {string} flags - * @param {string} [description] - * @return {Option} new option - */ - - createOption(flags, description) { - return new Option(flags, description); - } - - /** - * Wrap parseArgs to catch 'commander.invalidArgument'. - * - * @param {(Option | Argument)} target - * @param {string} value - * @param {*} previous - * @param {string} invalidArgumentMessage - * @private - */ - - _callParseArg(target, value, previous, invalidArgumentMessage) { - try { - return target.parseArg(value, previous); - } catch (err) { - if (err.code === 'commander.invalidArgument') { - const message = `${invalidArgumentMessage} ${err.message}`; - this.error(message, { exitCode: err.exitCode, code: err.code }); - } - throw err; - } - } - - /** - * Check for option flag conflicts. - * Register option if no conflicts found, or throw on conflict. - * - * @param {Option} option - * @private - */ - - _registerOption(option) { - const matchingOption = - (option.short && this._findOption(option.short)) || - (option.long && this._findOption(option.long)); - if (matchingOption) { - const matchingFlag = - option.long && this._findOption(option.long) - ? option.long - : option.short; - throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}' -- already used by option '${matchingOption.flags}'`); - } - - this.options.push(option); - } - - /** - * Check for command name and alias conflicts with existing commands. - * Register command if no conflicts found, or throw on conflict. - * - * @param {Command} command - * @private - */ - - _registerCommand(command) { - const knownBy = (cmd) => { - return [cmd.name()].concat(cmd.aliases()); - }; - - const alreadyUsed = knownBy(command).find((name) => - this._findCommand(name), - ); - if (alreadyUsed) { - const existingCmd = knownBy(this._findCommand(alreadyUsed)).join('|'); - const newCmd = knownBy(command).join('|'); - throw new Error( - `cannot add command '${newCmd}' as already have command '${existingCmd}'`, - ); - } - - this.commands.push(command); - } - - /** - * Add an option. - * - * @param {Option} option - * @return {Command} `this` command for chaining - */ - addOption(option) { - this._registerOption(option); - - const oname = option.name(); - const name = option.attributeName(); - - // store default value - if (option.negate) { - // --no-foo is special and defaults foo to true, unless a --foo option is already defined - const positiveLongFlag = option.long.replace(/^--no-/, '--'); - if (!this._findOption(positiveLongFlag)) { - this.setOptionValueWithSource( - name, - option.defaultValue === undefined ? true : option.defaultValue, - 'default', - ); - } - } else if (option.defaultValue !== undefined) { - this.setOptionValueWithSource(name, option.defaultValue, 'default'); - } - - // handler for cli and env supplied values - const handleOptionValue = (val, invalidValueMessage, valueSource) => { - // val is null for optional option used without an optional-argument. - // val is undefined for boolean and negated option. - if (val == null && option.presetArg !== undefined) { - val = option.presetArg; - } - - // custom processing - const oldValue = this.getOptionValue(name); - if (val !== null && option.parseArg) { - val = this._callParseArg(option, val, oldValue, invalidValueMessage); - } else if (val !== null && option.variadic) { - val = option._concatValue(val, oldValue); - } - - // Fill-in appropriate missing values. Long winded but easy to follow. - if (val == null) { - if (option.negate) { - val = false; - } else if (option.isBoolean() || option.optional) { - val = true; - } else { - val = ''; // not normal, parseArg might have failed or be a mock function for testing - } - } - this.setOptionValueWithSource(name, val, valueSource); - }; - - this.on('option:' + oname, (val) => { - const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`; - handleOptionValue(val, invalidValueMessage, 'cli'); - }); - - if (option.envVar) { - this.on('optionEnv:' + oname, (val) => { - const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`; - handleOptionValue(val, invalidValueMessage, 'env'); - }); - } - - return this; - } - - /** - * Internal implementation shared by .option() and .requiredOption() - * - * @return {Command} `this` command for chaining - * @private - */ - _optionEx(config, flags, description, fn, defaultValue) { - if (typeof flags === 'object' && flags instanceof Option) { - throw new Error( - 'To add an Option object use addOption() instead of option() or requiredOption()', - ); - } - const option = this.createOption(flags, description); - option.makeOptionMandatory(!!config.mandatory); - if (typeof fn === 'function') { - option.default(defaultValue).argParser(fn); - } else if (fn instanceof RegExp) { - // deprecated - const regex = fn; - fn = (val, def) => { - const m = regex.exec(val); - return m ? m[0] : def; - }; - option.default(defaultValue).argParser(fn); - } else { - option.default(fn); - } - - return this.addOption(option); - } - - /** - * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both. - * - * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required - * option-argument is indicated by `<>` and an optional option-argument by `[]`. - * - * See the README for more details, and see also addOption() and requiredOption(). - * - * @example - * program - * .option('-p, --pepper', 'add pepper') - * .option('-p, --pizza-type ', 'type of pizza') // required option-argument - * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default - * .option('-t, --tip ', 'add tip to purchase cost', parseFloat) // custom parse function - * - * @param {string} flags - * @param {string} [description] - * @param {(Function|*)} [parseArg] - custom option processing function or default value - * @param {*} [defaultValue] - * @return {Command} `this` command for chaining - */ - - option(flags, description, parseArg, defaultValue) { - return this._optionEx({}, flags, description, parseArg, defaultValue); - } - - /** - * Add a required option which must have a value after parsing. This usually means - * the option must be specified on the command line. (Otherwise the same as .option().) - * - * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. - * - * @param {string} flags - * @param {string} [description] - * @param {(Function|*)} [parseArg] - custom option processing function or default value - * @param {*} [defaultValue] - * @return {Command} `this` command for chaining - */ - - requiredOption(flags, description, parseArg, defaultValue) { - return this._optionEx( - { mandatory: true }, - flags, - description, - parseArg, - defaultValue, - ); - } - - /** - * Alter parsing of short flags with optional values. - * - * @example - * // for `.option('-f,--flag [value]'): - * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour - * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b` - * - * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag. - * @return {Command} `this` command for chaining - */ - combineFlagAndOptionalValue(combine = true) { - this._combineFlagAndOptionalValue = !!combine; - return this; - } - - /** - * Allow unknown options on the command line. - * - * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options. - * @return {Command} `this` command for chaining - */ - allowUnknownOption(allowUnknown = true) { - this._allowUnknownOption = !!allowUnknown; - return this; - } - - /** - * Allow excess command-arguments on the command line. Pass false to make excess arguments an error. - * - * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments. - * @return {Command} `this` command for chaining - */ - allowExcessArguments(allowExcess = true) { - this._allowExcessArguments = !!allowExcess; - return this; - } - - /** - * Enable positional options. Positional means global options are specified before subcommands which lets - * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions. - * The default behaviour is non-positional and global options may appear anywhere on the command line. - * - * @param {boolean} [positional] - * @return {Command} `this` command for chaining - */ - enablePositionalOptions(positional = true) { - this._enablePositionalOptions = !!positional; - return this; - } - - /** - * Pass through options that come after command-arguments rather than treat them as command-options, - * so actual command-options come before command-arguments. Turning this on for a subcommand requires - * positional options to have been enabled on the program (parent commands). - * The default behaviour is non-positional and options may appear before or after command-arguments. - * - * @param {boolean} [passThrough] for unknown options. - * @return {Command} `this` command for chaining - */ - passThroughOptions(passThrough = true) { - this._passThroughOptions = !!passThrough; - this._checkForBrokenPassThrough(); - return this; - } - - /** - * @private - */ - - _checkForBrokenPassThrough() { - if ( - this.parent && - this._passThroughOptions && - !this.parent._enablePositionalOptions - ) { - throw new Error( - `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`, - ); - } - } - - /** - * Whether to store option values as properties on command object, - * or store separately (specify false). In both cases the option values can be accessed using .opts(). - * - * @param {boolean} [storeAsProperties=true] - * @return {Command} `this` command for chaining - */ - - storeOptionsAsProperties(storeAsProperties = true) { - if (this.options.length) { - throw new Error('call .storeOptionsAsProperties() before adding options'); - } - if (Object.keys(this._optionValues).length) { - throw new Error( - 'call .storeOptionsAsProperties() before setting option values', - ); - } - this._storeOptionsAsProperties = !!storeAsProperties; - return this; - } - - /** - * Retrieve option value. - * - * @param {string} key - * @return {object} value - */ - - getOptionValue(key) { - if (this._storeOptionsAsProperties) { - return this[key]; - } - return this._optionValues[key]; - } - - /** - * Store option value. - * - * @param {string} key - * @param {object} value - * @return {Command} `this` command for chaining - */ - - setOptionValue(key, value) { - return this.setOptionValueWithSource(key, value, undefined); - } - - /** - * Store option value and where the value came from. - * - * @param {string} key - * @param {object} value - * @param {string} source - expected values are default/config/env/cli/implied - * @return {Command} `this` command for chaining - */ - - setOptionValueWithSource(key, value, source) { - if (this._storeOptionsAsProperties) { - this[key] = value; - } else { - this._optionValues[key] = value; - } - this._optionValueSources[key] = source; - return this; - } - - /** - * Get source of option value. - * Expected values are default | config | env | cli | implied - * - * @param {string} key - * @return {string} - */ - - getOptionValueSource(key) { - return this._optionValueSources[key]; - } - - /** - * Get source of option value. See also .optsWithGlobals(). - * Expected values are default | config | env | cli | implied - * - * @param {string} key - * @return {string} - */ - - getOptionValueSourceWithGlobals(key) { - // global overwrites local, like optsWithGlobals - let source; - this._getCommandAndAncestors().forEach((cmd) => { - if (cmd.getOptionValueSource(key) !== undefined) { - source = cmd.getOptionValueSource(key); - } - }); - return source; - } - - /** - * Get user arguments from implied or explicit arguments. - * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches. - * - * @private - */ - - _prepareUserArgs(argv, parseOptions) { - if (argv !== undefined && !Array.isArray(argv)) { - throw new Error('first parameter to parse must be array or undefined'); - } - parseOptions = parseOptions || {}; - - // auto-detect argument conventions if nothing supplied - if (argv === undefined && parseOptions.from === undefined) { - if (process.versions?.electron) { - parseOptions.from = 'electron'; - } - // check node specific options for scenarios where user CLI args follow executable without scriptname - const execArgv = process.execArgv ?? []; - if ( - execArgv.includes('-e') || - execArgv.includes('--eval') || - execArgv.includes('-p') || - execArgv.includes('--print') - ) { - parseOptions.from = 'eval'; // internal usage, not documented - } - } - - // default to using process.argv - if (argv === undefined) { - argv = process.argv; - } - this.rawArgs = argv.slice(); - - // extract the user args and scriptPath - let userArgs; - switch (parseOptions.from) { - case undefined: - case 'node': - this._scriptPath = argv[1]; - userArgs = argv.slice(2); - break; - case 'electron': - // @ts-ignore: because defaultApp is an unknown property - if (process.defaultApp) { - this._scriptPath = argv[1]; - userArgs = argv.slice(2); - } else { - userArgs = argv.slice(1); - } - break; - case 'user': - userArgs = argv.slice(0); - break; - case 'eval': - userArgs = argv.slice(1); - break; - default: - throw new Error( - `unexpected parse option { from: '${parseOptions.from}' }`, - ); - } - - // Find default name for program from arguments. - if (!this._name && this._scriptPath) - this.nameFromFilename(this._scriptPath); - this._name = this._name || 'program'; - - return userArgs; - } - - /** - * Parse `argv`, setting options and invoking commands when defined. - * - * Use parseAsync instead of parse if any of your action handlers are async. - * - * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode! - * - * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`: - * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that - * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged - * - `'user'`: just user arguments - * - * @example - * program.parse(); // parse process.argv and auto-detect electron and special node flags - * program.parse(process.argv); // assume argv[0] is app and argv[1] is script - * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] - * - * @param {string[]} [argv] - optional, defaults to process.argv - * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron - * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron' - * @return {Command} `this` command for chaining - */ - - parse(argv, parseOptions) { - const userArgs = this._prepareUserArgs(argv, parseOptions); - this._parseCommand([], userArgs); - - return this; - } - - /** - * Parse `argv`, setting options and invoking commands when defined. - * - * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode! - * - * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`: - * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that - * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged - * - `'user'`: just user arguments - * - * @example - * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags - * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script - * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] - * - * @param {string[]} [argv] - * @param {object} [parseOptions] - * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron' - * @return {Promise} - */ - - async parseAsync(argv, parseOptions) { - const userArgs = this._prepareUserArgs(argv, parseOptions); - await this._parseCommand([], userArgs); - - return this; - } - - /** - * Execute a sub-command executable. - * - * @private - */ - - _executeSubCommand(subcommand, args) { - args = args.slice(); - let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows. - const sourceExt = ['.js', '.ts', '.tsx', '.mjs', '.cjs']; - - function findFile(baseDir, baseName) { - // Look for specified file - const localBin = path.resolve(baseDir, baseName); - if (fs.existsSync(localBin)) return localBin; - - // Stop looking if candidate already has an expected extension. - if (sourceExt.includes(path.extname(baseName))) return undefined; - - // Try all the extensions. - const foundExt = sourceExt.find((ext) => - fs.existsSync(`${localBin}${ext}`), - ); - if (foundExt) return `${localBin}${foundExt}`; - - return undefined; - } - - // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command. - this._checkForMissingMandatoryOptions(); - this._checkForConflictingOptions(); - - // executableFile and executableDir might be full path, or just a name - let executableFile = - subcommand._executableFile || `${this._name}-${subcommand._name}`; - let executableDir = this._executableDir || ''; - if (this._scriptPath) { - let resolvedScriptPath; // resolve possible symlink for installed npm binary - try { - resolvedScriptPath = fs.realpathSync(this._scriptPath); - } catch (err) { - resolvedScriptPath = this._scriptPath; - } - executableDir = path.resolve( - path.dirname(resolvedScriptPath), - executableDir, - ); - } - - // Look for a local file in preference to a command in PATH. - if (executableDir) { - let localFile = findFile(executableDir, executableFile); - - // Legacy search using prefix of script name instead of command name - if (!localFile && !subcommand._executableFile && this._scriptPath) { - const legacyName = path.basename( - this._scriptPath, - path.extname(this._scriptPath), - ); - if (legacyName !== this._name) { - localFile = findFile( - executableDir, - `${legacyName}-${subcommand._name}`, - ); - } - } - executableFile = localFile || executableFile; - } - - launchWithNode = sourceExt.includes(path.extname(executableFile)); - - let proc; - if (process.platform !== 'win32') { - if (launchWithNode) { - args.unshift(executableFile); - // add executable arguments to spawn - args = incrementNodeInspectorPort(process.execArgv).concat(args); - - proc = childProcess.spawn(process.argv[0], args, { stdio: 'inherit' }); - } else { - proc = childProcess.spawn(executableFile, args, { stdio: 'inherit' }); - } - } else { - args.unshift(executableFile); - // add executable arguments to spawn - args = incrementNodeInspectorPort(process.execArgv).concat(args); - proc = childProcess.spawn(process.execPath, args, { stdio: 'inherit' }); - } - - if (!proc.killed) { - // testing mainly to avoid leak warnings during unit tests with mocked spawn - const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP']; - signals.forEach((signal) => { - process.on(signal, () => { - if (proc.killed === false && proc.exitCode === null) { - // @ts-ignore because signals not typed to known strings - proc.kill(signal); - } - }); - }); - } - - // By default terminate process when spawned process terminates. - const exitCallback = this._exitCallback; - proc.on('close', (code) => { - code = code ?? 1; // code is null if spawned process terminated due to a signal - if (!exitCallback) { - process.exit(code); - } else { - exitCallback( - new CommanderError( - code, - 'commander.executeSubCommandAsync', - '(close)', - ), - ); - } - }); - proc.on('error', (err) => { - // @ts-ignore: because err.code is an unknown property - if (err.code === 'ENOENT') { - const executableDirMessage = executableDir - ? `searched for local subcommand relative to directory '${executableDir}'` - : 'no directory for search for local subcommand, use .executableDir() to supply a custom directory'; - const executableMissing = `'${executableFile}' does not exist - - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead - - if the default executable name is not suitable, use the executableFile option to supply a custom name or path - - ${executableDirMessage}`; - throw new Error(executableMissing); - // @ts-ignore: because err.code is an unknown property - } else if (err.code === 'EACCES') { - throw new Error(`'${executableFile}' not executable`); - } - if (!exitCallback) { - process.exit(1); - } else { - const wrappedError = new CommanderError( - 1, - 'commander.executeSubCommandAsync', - '(error)', - ); - wrappedError.nestedError = err; - exitCallback(wrappedError); - } - }); - - // Store the reference to the child process - this.runningCommand = proc; - } - - /** - * @private - */ - - _dispatchSubcommand(commandName, operands, unknown) { - const subCommand = this._findCommand(commandName); - if (!subCommand) this.help({ error: true }); - - let promiseChain; - promiseChain = this._chainOrCallSubCommandHook( - promiseChain, - subCommand, - 'preSubcommand', - ); - promiseChain = this._chainOrCall(promiseChain, () => { - if (subCommand._executableHandler) { - this._executeSubCommand(subCommand, operands.concat(unknown)); - } else { - return subCommand._parseCommand(operands, unknown); - } - }); - return promiseChain; - } - - /** - * Invoke help directly if possible, or dispatch if necessary. - * e.g. help foo - * - * @private - */ - - _dispatchHelpCommand(subcommandName) { - if (!subcommandName) { - this.help(); - } - const subCommand = this._findCommand(subcommandName); - if (subCommand && !subCommand._executableHandler) { - subCommand.help(); - } - - // Fallback to parsing the help flag to invoke the help. - return this._dispatchSubcommand( - subcommandName, - [], - [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? '--help'], - ); - } - - /** - * Check this.args against expected this.registeredArguments. - * - * @private - */ - - _checkNumberOfArguments() { - // too few - this.registeredArguments.forEach((arg, i) => { - if (arg.required && this.args[i] == null) { - this.missingArgument(arg.name()); - } - }); - // too many - if ( - this.registeredArguments.length > 0 && - this.registeredArguments[this.registeredArguments.length - 1].variadic - ) { - return; - } - if (this.args.length > this.registeredArguments.length) { - this._excessArguments(this.args); - } - } - - /** - * Process this.args using this.registeredArguments and save as this.processedArgs! - * - * @private - */ - - _processArguments() { - const myParseArg = (argument, value, previous) => { - // Extra processing for nice error message on parsing failure. - let parsedValue = value; - if (value !== null && argument.parseArg) { - const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`; - parsedValue = this._callParseArg( - argument, - value, - previous, - invalidValueMessage, - ); - } - return parsedValue; - }; - - this._checkNumberOfArguments(); - - const processedArgs = []; - this.registeredArguments.forEach((declaredArg, index) => { - let value = declaredArg.defaultValue; - if (declaredArg.variadic) { - // Collect together remaining arguments for passing together as an array. - if (index < this.args.length) { - value = this.args.slice(index); - if (declaredArg.parseArg) { - value = value.reduce((processed, v) => { - return myParseArg(declaredArg, v, processed); - }, declaredArg.defaultValue); - } - } else if (value === undefined) { - value = []; - } - } else if (index < this.args.length) { - value = this.args[index]; - if (declaredArg.parseArg) { - value = myParseArg(declaredArg, value, declaredArg.defaultValue); - } - } - processedArgs[index] = value; - }); - this.processedArgs = processedArgs; - } - - /** - * Once we have a promise we chain, but call synchronously until then. - * - * @param {(Promise|undefined)} promise - * @param {Function} fn - * @return {(Promise|undefined)} - * @private - */ - - _chainOrCall(promise, fn) { - // thenable - if (promise && promise.then && typeof promise.then === 'function') { - // already have a promise, chain callback - return promise.then(() => fn()); - } - // callback might return a promise - return fn(); - } - - /** - * - * @param {(Promise|undefined)} promise - * @param {string} event - * @return {(Promise|undefined)} - * @private - */ - - _chainOrCallHooks(promise, event) { - let result = promise; - const hooks = []; - this._getCommandAndAncestors() - .reverse() - .filter((cmd) => cmd._lifeCycleHooks[event] !== undefined) - .forEach((hookedCommand) => { - hookedCommand._lifeCycleHooks[event].forEach((callback) => { - hooks.push({ hookedCommand, callback }); - }); - }); - if (event === 'postAction') { - hooks.reverse(); - } - - hooks.forEach((hookDetail) => { - result = this._chainOrCall(result, () => { - return hookDetail.callback(hookDetail.hookedCommand, this); - }); - }); - return result; - } - - /** - * - * @param {(Promise|undefined)} promise - * @param {Command} subCommand - * @param {string} event - * @return {(Promise|undefined)} - * @private - */ - - _chainOrCallSubCommandHook(promise, subCommand, event) { - let result = promise; - if (this._lifeCycleHooks[event] !== undefined) { - this._lifeCycleHooks[event].forEach((hook) => { - result = this._chainOrCall(result, () => { - return hook(this, subCommand); - }); - }); - } - return result; - } - - /** - * Process arguments in context of this command. - * Returns action result, in case it is a promise. - * - * @private - */ - - _parseCommand(operands, unknown) { - const parsed = this.parseOptions(unknown); - this._parseOptionsEnv(); // after cli, so parseArg not called on both cli and env - this._parseOptionsImplied(); - operands = operands.concat(parsed.operands); - unknown = parsed.unknown; - this.args = operands.concat(unknown); - - if (operands && this._findCommand(operands[0])) { - return this._dispatchSubcommand(operands[0], operands.slice(1), unknown); - } - if ( - this._getHelpCommand() && - operands[0] === this._getHelpCommand().name() - ) { - return this._dispatchHelpCommand(operands[1]); - } - if (this._defaultCommandName) { - this._outputHelpIfRequested(unknown); // Run the help for default command from parent rather than passing to default command - return this._dispatchSubcommand( - this._defaultCommandName, - operands, - unknown, - ); - } - if ( - this.commands.length && - this.args.length === 0 && - !this._actionHandler && - !this._defaultCommandName - ) { - // probably missing subcommand and no handler, user needs help (and exit) - this.help({ error: true }); - } - - this._outputHelpIfRequested(parsed.unknown); - this._checkForMissingMandatoryOptions(); - this._checkForConflictingOptions(); - - // We do not always call this check to avoid masking a "better" error, like unknown command. - const checkForUnknownOptions = () => { - if (parsed.unknown.length > 0) { - this.unknownOption(parsed.unknown[0]); - } - }; - - const commandEvent = `command:${this.name()}`; - if (this._actionHandler) { - checkForUnknownOptions(); - this._processArguments(); - - let promiseChain; - promiseChain = this._chainOrCallHooks(promiseChain, 'preAction'); - promiseChain = this._chainOrCall(promiseChain, () => - this._actionHandler(this.processedArgs), - ); - if (this.parent) { - promiseChain = this._chainOrCall(promiseChain, () => { - this.parent.emit(commandEvent, operands, unknown); // legacy - }); - } - promiseChain = this._chainOrCallHooks(promiseChain, 'postAction'); - return promiseChain; - } - if (this.parent && this.parent.listenerCount(commandEvent)) { - checkForUnknownOptions(); - this._processArguments(); - this.parent.emit(commandEvent, operands, unknown); // legacy - } else if (operands.length) { - if (this._findCommand('*')) { - // legacy default command - return this._dispatchSubcommand('*', operands, unknown); - } - if (this.listenerCount('command:*')) { - // skip option check, emit event for possible misspelling suggestion - this.emit('command:*', operands, unknown); - } else if (this.commands.length) { - this.unknownCommand(); - } else { - checkForUnknownOptions(); - this._processArguments(); - } - } else if (this.commands.length) { - checkForUnknownOptions(); - // This command has subcommands and nothing hooked up at this level, so display help (and exit). - this.help({ error: true }); - } else { - checkForUnknownOptions(); - this._processArguments(); - // fall through for caller to handle after calling .parse() - } - } - - /** - * Find matching command. - * - * @private - * @return {Command | undefined} - */ - _findCommand(name) { - if (!name) return undefined; - return this.commands.find( - (cmd) => cmd._name === name || cmd._aliases.includes(name), - ); - } - - /** - * Return an option matching `arg` if any. - * - * @param {string} arg - * @return {Option} - * @package - */ - - _findOption(arg) { - return this.options.find((option) => option.is(arg)); - } - - /** - * Display an error message if a mandatory option does not have a value. - * Called after checking for help flags in leaf subcommand. - * - * @private - */ - - _checkForMissingMandatoryOptions() { - // Walk up hierarchy so can call in subcommand after checking for displaying help. - this._getCommandAndAncestors().forEach((cmd) => { - cmd.options.forEach((anOption) => { - if ( - anOption.mandatory && - cmd.getOptionValue(anOption.attributeName()) === undefined - ) { - cmd.missingMandatoryOptionValue(anOption); - } - }); - }); - } - - /** - * Display an error message if conflicting options are used together in this. - * - * @private - */ - _checkForConflictingLocalOptions() { - const definedNonDefaultOptions = this.options.filter((option) => { - const optionKey = option.attributeName(); - if (this.getOptionValue(optionKey) === undefined) { - return false; - } - return this.getOptionValueSource(optionKey) !== 'default'; - }); - - const optionsWithConflicting = definedNonDefaultOptions.filter( - (option) => option.conflictsWith.length > 0, - ); - - optionsWithConflicting.forEach((option) => { - const conflictingAndDefined = definedNonDefaultOptions.find((defined) => - option.conflictsWith.includes(defined.attributeName()), - ); - if (conflictingAndDefined) { - this._conflictingOption(option, conflictingAndDefined); - } - }); - } - - /** - * Display an error message if conflicting options are used together. - * Called after checking for help flags in leaf subcommand. - * - * @private - */ - _checkForConflictingOptions() { - // Walk up hierarchy so can call in subcommand after checking for displaying help. - this._getCommandAndAncestors().forEach((cmd) => { - cmd._checkForConflictingLocalOptions(); - }); - } - - /** - * Parse options from `argv` removing known options, - * and return argv split into operands and unknown arguments. - * - * Examples: - * - * argv => operands, unknown - * --known kkk op => [op], [] - * op --known kkk => [op], [] - * sub --unknown uuu op => [sub], [--unknown uuu op] - * sub -- --unknown uuu op => [sub --unknown uuu op], [] - * - * @param {string[]} argv - * @return {{operands: string[], unknown: string[]}} - */ - - parseOptions(argv) { - const operands = []; // operands, not options or values - const unknown = []; // first unknown option and remaining unknown args - let dest = operands; - const args = argv.slice(); - - function maybeOption(arg) { - return arg.length > 1 && arg[0] === '-'; - } - - // parse options - let activeVariadicOption = null; - while (args.length) { - const arg = args.shift(); - - // literal - if (arg === '--') { - if (dest === unknown) dest.push(arg); - dest.push(...args); - break; - } - - if (activeVariadicOption && !maybeOption(arg)) { - this.emit(`option:${activeVariadicOption.name()}`, arg); - continue; - } - activeVariadicOption = null; - - if (maybeOption(arg)) { - const option = this._findOption(arg); - // recognised option, call listener to assign value with possible custom processing - if (option) { - if (option.required) { - const value = args.shift(); - if (value === undefined) this.optionMissingArgument(option); - this.emit(`option:${option.name()}`, value); - } else if (option.optional) { - let value = null; - // historical behaviour is optional value is following arg unless an option - if (args.length > 0 && !maybeOption(args[0])) { - value = args.shift(); - } - this.emit(`option:${option.name()}`, value); - } else { - // boolean flag - this.emit(`option:${option.name()}`); - } - activeVariadicOption = option.variadic ? option : null; - continue; - } - } - - // Look for combo options following single dash, eat first one if known. - if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') { - const option = this._findOption(`-${arg[1]}`); - if (option) { - if ( - option.required || - (option.optional && this._combineFlagAndOptionalValue) - ) { - // option with value following in same argument - this.emit(`option:${option.name()}`, arg.slice(2)); - } else { - // boolean option, emit and put back remainder of arg for further processing - this.emit(`option:${option.name()}`); - args.unshift(`-${arg.slice(2)}`); - } - continue; - } - } - - // Look for known long flag with value, like --foo=bar - if (/^--[^=]+=/.test(arg)) { - const index = arg.indexOf('='); - const option = this._findOption(arg.slice(0, index)); - if (option && (option.required || option.optional)) { - this.emit(`option:${option.name()}`, arg.slice(index + 1)); - continue; - } - } - - // Not a recognised option by this command. - // Might be a command-argument, or subcommand option, or unknown option, or help command or option. - - // An unknown option means further arguments also classified as unknown so can be reprocessed by subcommands. - if (maybeOption(arg)) { - dest = unknown; - } - - // If using positionalOptions, stop processing our options at subcommand. - if ( - (this._enablePositionalOptions || this._passThroughOptions) && - operands.length === 0 && - unknown.length === 0 - ) { - if (this._findCommand(arg)) { - operands.push(arg); - if (args.length > 0) unknown.push(...args); - break; - } else if ( - this._getHelpCommand() && - arg === this._getHelpCommand().name() - ) { - operands.push(arg); - if (args.length > 0) operands.push(...args); - break; - } else if (this._defaultCommandName) { - unknown.push(arg); - if (args.length > 0) unknown.push(...args); - break; - } - } - - // If using passThroughOptions, stop processing options at first command-argument. - if (this._passThroughOptions) { - dest.push(arg); - if (args.length > 0) dest.push(...args); - break; - } - - // add arg - dest.push(arg); - } - - return { operands, unknown }; - } - - /** - * Return an object containing local option values as key-value pairs. - * - * @return {object} - */ - opts() { - if (this._storeOptionsAsProperties) { - // Preserve original behaviour so backwards compatible when still using properties - const result = {}; - const len = this.options.length; - - for (let i = 0; i < len; i++) { - const key = this.options[i].attributeName(); - result[key] = - key === this._versionOptionName ? this._version : this[key]; - } - return result; - } - - return this._optionValues; - } - - /** - * Return an object containing merged local and global option values as key-value pairs. - * - * @return {object} - */ - optsWithGlobals() { - // globals overwrite locals - return this._getCommandAndAncestors().reduce( - (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()), - {}, - ); - } - - /** - * Display error message and exit (or call exitOverride). - * - * @param {string} message - * @param {object} [errorOptions] - * @param {string} [errorOptions.code] - an id string representing the error - * @param {number} [errorOptions.exitCode] - used with process.exit - */ - error(message, errorOptions) { - // output handling - this._outputConfiguration.outputError( - `${message}\n`, - this._outputConfiguration.writeErr, - ); - if (typeof this._showHelpAfterError === 'string') { - this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`); - } else if (this._showHelpAfterError) { - this._outputConfiguration.writeErr('\n'); - this.outputHelp({ error: true }); - } - - // exit handling - const config = errorOptions || {}; - const exitCode = config.exitCode || 1; - const code = config.code || 'commander.error'; - this._exit(exitCode, code, message); - } - - /** - * Apply any option related environment variables, if option does - * not have a value from cli or client code. - * - * @private - */ - _parseOptionsEnv() { - this.options.forEach((option) => { - if (option.envVar && option.envVar in process.env) { - const optionKey = option.attributeName(); - // Priority check. Do not overwrite cli or options from unknown source (client-code). - if ( - this.getOptionValue(optionKey) === undefined || - ['default', 'config', 'env'].includes( - this.getOptionValueSource(optionKey), - ) - ) { - if (option.required || option.optional) { - // option can take a value - // keep very simple, optional always takes value - this.emit(`optionEnv:${option.name()}`, process.env[option.envVar]); - } else { - // boolean - // keep very simple, only care that envVar defined and not the value - this.emit(`optionEnv:${option.name()}`); - } - } - } - }); - } - - /** - * Apply any implied option values, if option is undefined or default value. - * - * @private - */ - _parseOptionsImplied() { - const dualHelper = new DualOptions(this.options); - const hasCustomOptionValue = (optionKey) => { - return ( - this.getOptionValue(optionKey) !== undefined && - !['default', 'implied'].includes(this.getOptionValueSource(optionKey)) - ); - }; - this.options - .filter( - (option) => - option.implied !== undefined && - hasCustomOptionValue(option.attributeName()) && - dualHelper.valueFromOption( - this.getOptionValue(option.attributeName()), - option, - ), - ) - .forEach((option) => { - Object.keys(option.implied) - .filter((impliedKey) => !hasCustomOptionValue(impliedKey)) - .forEach((impliedKey) => { - this.setOptionValueWithSource( - impliedKey, - option.implied[impliedKey], - 'implied', - ); - }); - }); - } - - /** - * Argument `name` is missing. - * - * @param {string} name - * @private - */ - - missingArgument(name) { - const message = `error: missing required argument '${name}'`; - this.error(message, { code: 'commander.missingArgument' }); - } - - /** - * `Option` is missing an argument. - * - * @param {Option} option - * @private - */ - - optionMissingArgument(option) { - const message = `error: option '${option.flags}' argument missing`; - this.error(message, { code: 'commander.optionMissingArgument' }); - } - - /** - * `Option` does not have a value, and is a mandatory option. - * - * @param {Option} option - * @private - */ - - missingMandatoryOptionValue(option) { - const message = `error: required option '${option.flags}' not specified`; - this.error(message, { code: 'commander.missingMandatoryOptionValue' }); - } - - /** - * `Option` conflicts with another option. - * - * @param {Option} option - * @param {Option} conflictingOption - * @private - */ - _conflictingOption(option, conflictingOption) { - // The calling code does not know whether a negated option is the source of the - // value, so do some work to take an educated guess. - const findBestOptionFromValue = (option) => { - const optionKey = option.attributeName(); - const optionValue = this.getOptionValue(optionKey); - const negativeOption = this.options.find( - (target) => target.negate && optionKey === target.attributeName(), - ); - const positiveOption = this.options.find( - (target) => !target.negate && optionKey === target.attributeName(), - ); - if ( - negativeOption && - ((negativeOption.presetArg === undefined && optionValue === false) || - (negativeOption.presetArg !== undefined && - optionValue === negativeOption.presetArg)) - ) { - return negativeOption; - } - return positiveOption || option; - }; - - const getErrorMessage = (option) => { - const bestOption = findBestOptionFromValue(option); - const optionKey = bestOption.attributeName(); - const source = this.getOptionValueSource(optionKey); - if (source === 'env') { - return `environment variable '${bestOption.envVar}'`; - } - return `option '${bestOption.flags}'`; - }; - - const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`; - this.error(message, { code: 'commander.conflictingOption' }); - } - - /** - * Unknown option `flag`. - * - * @param {string} flag - * @private - */ - - unknownOption(flag) { - if (this._allowUnknownOption) return; - let suggestion = ''; - - if (flag.startsWith('--') && this._showSuggestionAfterError) { - // Looping to pick up the global options too - let candidateFlags = []; - // eslint-disable-next-line @typescript-eslint/no-this-alias - let command = this; - do { - const moreFlags = command - .createHelp() - .visibleOptions(command) - .filter((option) => option.long) - .map((option) => option.long); - candidateFlags = candidateFlags.concat(moreFlags); - command = command.parent; - } while (command && !command._enablePositionalOptions); - suggestion = suggestSimilar(flag, candidateFlags); - } - - const message = `error: unknown option '${flag}'${suggestion}`; - this.error(message, { code: 'commander.unknownOption' }); - } - - /** - * Excess arguments, more than expected. - * - * @param {string[]} receivedArgs - * @private - */ - - _excessArguments(receivedArgs) { - if (this._allowExcessArguments) return; - - const expected = this.registeredArguments.length; - const s = expected === 1 ? '' : 's'; - const forSubcommand = this.parent ? ` for '${this.name()}'` : ''; - const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`; - this.error(message, { code: 'commander.excessArguments' }); - } - - /** - * Unknown command. - * - * @private - */ - - unknownCommand() { - const unknownName = this.args[0]; - let suggestion = ''; - - if (this._showSuggestionAfterError) { - const candidateNames = []; - this.createHelp() - .visibleCommands(this) - .forEach((command) => { - candidateNames.push(command.name()); - // just visible alias - if (command.alias()) candidateNames.push(command.alias()); - }); - suggestion = suggestSimilar(unknownName, candidateNames); - } - - const message = `error: unknown command '${unknownName}'${suggestion}`; - this.error(message, { code: 'commander.unknownCommand' }); - } - - /** - * Get or set the program version. - * - * This method auto-registers the "-V, --version" option which will print the version number. - * - * You can optionally supply the flags and description to override the defaults. - * - * @param {string} [str] - * @param {string} [flags] - * @param {string} [description] - * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments - */ - - version(str, flags, description) { - if (str === undefined) return this._version; - this._version = str; - flags = flags || '-V, --version'; - description = description || 'output the version number'; - const versionOption = this.createOption(flags, description); - this._versionOptionName = versionOption.attributeName(); - this._registerOption(versionOption); - - this.on('option:' + versionOption.name(), () => { - this._outputConfiguration.writeOut(`${str}\n`); - this._exit(0, 'commander.version', str); - }); - return this; - } - - /** - * Set the description. - * - * @param {string} [str] - * @param {object} [argsDescription] - * @return {(string|Command)} - */ - description(str, argsDescription) { - if (str === undefined && argsDescription === undefined) - return this._description; - this._description = str; - if (argsDescription) { - this._argsDescription = argsDescription; - } - return this; - } - - /** - * Set the summary. Used when listed as subcommand of parent. - * - * @param {string} [str] - * @return {(string|Command)} - */ - summary(str) { - if (str === undefined) return this._summary; - this._summary = str; - return this; - } - - /** - * Set an alias for the command. - * - * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help. - * - * @param {string} [alias] - * @return {(string|Command)} - */ - - alias(alias) { - if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility - - /** @type {Command} */ - // eslint-disable-next-line @typescript-eslint/no-this-alias - let command = this; - if ( - this.commands.length !== 0 && - this.commands[this.commands.length - 1]._executableHandler - ) { - // assume adding alias for last added executable subcommand, rather than this - command = this.commands[this.commands.length - 1]; - } - - if (alias === command._name) - throw new Error("Command alias can't be the same as its name"); - const matchingCommand = this.parent?._findCommand(alias); - if (matchingCommand) { - // c.f. _registerCommand - const existingCmd = [matchingCommand.name()] - .concat(matchingCommand.aliases()) - .join('|'); - throw new Error( - `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`, - ); - } - - command._aliases.push(alias); - return this; - } - - /** - * Set aliases for the command. - * - * Only the first alias is shown in the auto-generated help. - * - * @param {string[]} [aliases] - * @return {(string[]|Command)} - */ - - aliases(aliases) { - // Getter for the array of aliases is the main reason for having aliases() in addition to alias(). - if (aliases === undefined) return this._aliases; - - aliases.forEach((alias) => this.alias(alias)); - return this; - } - - /** - * Set / get the command usage `str`. - * - * @param {string} [str] - * @return {(string|Command)} - */ - - usage(str) { - if (str === undefined) { - if (this._usage) return this._usage; - - const args = this.registeredArguments.map((arg) => { - return humanReadableArgName(arg); - }); - return [] - .concat( - this.options.length || this._helpOption !== null ? '[options]' : [], - this.commands.length ? '[command]' : [], - this.registeredArguments.length ? args : [], - ) - .join(' '); - } - - this._usage = str; - return this; - } - - /** - * Get or set the name of the command. - * - * @param {string} [str] - * @return {(string|Command)} - */ - - name(str) { - if (str === undefined) return this._name; - this._name = str; - return this; - } - - /** - * Set the name of the command from script filename, such as process.argv[1], - * or require.main.filename, or __filename. - * - * (Used internally and public although not documented in README.) - * - * @example - * program.nameFromFilename(require.main.filename); - * - * @param {string} filename - * @return {Command} - */ - - nameFromFilename(filename) { - this._name = path.basename(filename, path.extname(filename)); - - return this; - } - - /** - * Get or set the directory for searching for executable subcommands of this command. - * - * @example - * program.executableDir(__dirname); - * // or - * program.executableDir('subcommands'); - * - * @param {string} [path] - * @return {(string|null|Command)} - */ - - executableDir(path) { - if (path === undefined) return this._executableDir; - this._executableDir = path; - return this; - } - - /** - * Return program help documentation. - * - * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout - * @return {string} - */ - - helpInformation(contextOptions) { - const helper = this.createHelp(); - if (helper.helpWidth === undefined) { - helper.helpWidth = - contextOptions && contextOptions.error - ? this._outputConfiguration.getErrHelpWidth() - : this._outputConfiguration.getOutHelpWidth(); - } - return helper.formatHelp(this, helper); - } - - /** - * @private - */ - - _getHelpContext(contextOptions) { - contextOptions = contextOptions || {}; - const context = { error: !!contextOptions.error }; - let write; - if (context.error) { - write = (arg) => this._outputConfiguration.writeErr(arg); - } else { - write = (arg) => this._outputConfiguration.writeOut(arg); - } - context.write = contextOptions.write || write; - context.command = this; - return context; - } - - /** - * Output help information for this command. - * - * Outputs built-in help, and custom text added using `.addHelpText()`. - * - * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout - */ - - outputHelp(contextOptions) { - let deprecatedCallback; - if (typeof contextOptions === 'function') { - deprecatedCallback = contextOptions; - contextOptions = undefined; - } - const context = this._getHelpContext(contextOptions); - - this._getCommandAndAncestors() - .reverse() - .forEach((command) => command.emit('beforeAllHelp', context)); - this.emit('beforeHelp', context); - - let helpInformation = this.helpInformation(context); - if (deprecatedCallback) { - helpInformation = deprecatedCallback(helpInformation); - if ( - typeof helpInformation !== 'string' && - !Buffer.isBuffer(helpInformation) - ) { - throw new Error('outputHelp callback must return a string or a Buffer'); - } - } - context.write(helpInformation); - - if (this._getHelpOption()?.long) { - this.emit(this._getHelpOption().long); // deprecated - } - this.emit('afterHelp', context); - this._getCommandAndAncestors().forEach((command) => - command.emit('afterAllHelp', context), - ); - } - - /** - * You can pass in flags and a description to customise the built-in help option. - * Pass in false to disable the built-in help option. - * - * @example - * program.helpOption('-?, --help' 'show help'); // customise - * program.helpOption(false); // disable - * - * @param {(string | boolean)} flags - * @param {string} [description] - * @return {Command} `this` command for chaining - */ - - helpOption(flags, description) { - // Support disabling built-in help option. - if (typeof flags === 'boolean') { - if (flags) { - this._helpOption = this._helpOption ?? undefined; // preserve existing option - } else { - this._helpOption = null; // disable - } - return this; - } - - // Customise flags and description. - flags = flags ?? '-h, --help'; - description = description ?? 'display help for command'; - this._helpOption = this.createOption(flags, description); - - return this; - } - - /** - * Lazy create help option. - * Returns null if has been disabled with .helpOption(false). - * - * @returns {(Option | null)} the help option - * @package - */ - _getHelpOption() { - // Lazy create help option on demand. - if (this._helpOption === undefined) { - this.helpOption(undefined, undefined); - } - return this._helpOption; - } - - /** - * Supply your own option to use for the built-in help option. - * This is an alternative to using helpOption() to customise the flags and description etc. - * - * @param {Option} option - * @return {Command} `this` command for chaining - */ - addHelpOption(option) { - this._helpOption = option; - return this; - } - - /** - * Output help information and exit. - * - * Outputs built-in help, and custom text added using `.addHelpText()`. - * - * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout - */ - - help(contextOptions) { - this.outputHelp(contextOptions); - let exitCode = process.exitCode || 0; - if ( - exitCode === 0 && - contextOptions && - typeof contextOptions !== 'function' && - contextOptions.error - ) { - exitCode = 1; - } - // message: do not have all displayed text available so only passing placeholder. - this._exit(exitCode, 'commander.help', '(outputHelp)'); - } - - /** - * Add additional text to be displayed with the built-in help. - * - * Position is 'before' or 'after' to affect just this command, - * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands. - * - * @param {string} position - before or after built-in help - * @param {(string | Function)} text - string to add, or a function returning a string - * @return {Command} `this` command for chaining - */ - addHelpText(position, text) { - const allowedValues = ['beforeAll', 'before', 'after', 'afterAll']; - if (!allowedValues.includes(position)) { - throw new Error(`Unexpected value for position to addHelpText. -Expecting one of '${allowedValues.join("', '")}'`); - } - const helpEvent = `${position}Help`; - this.on(helpEvent, (context) => { - let helpStr; - if (typeof text === 'function') { - helpStr = text({ error: context.error, command: context.command }); - } else { - helpStr = text; - } - // Ignore falsy value when nothing to output. - if (helpStr) { - context.write(`${helpStr}\n`); - } - }); - return this; - } - - /** - * Output help information if help flags specified - * - * @param {Array} args - array of options to search for help flags - * @private - */ - - _outputHelpIfRequested(args) { - const helpOption = this._getHelpOption(); - const helpRequested = helpOption && args.find((arg) => helpOption.is(arg)); - if (helpRequested) { - this.outputHelp(); - // (Do not have all displayed text available so only passing placeholder.) - this._exit(0, 'commander.helpDisplayed', '(outputHelp)'); - } - } -} - -/** - * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command). - * - * @param {string[]} args - array of arguments from node.execArgv - * @returns {string[]} - * @private - */ - -function incrementNodeInspectorPort(args) { - // Testing for these options: - // --inspect[=[host:]port] - // --inspect-brk[=[host:]port] - // --inspect-port=[host:]port - return args.map((arg) => { - if (!arg.startsWith('--inspect')) { - return arg; - } - let debugOption; - let debugHost = '127.0.0.1'; - let debugPort = '9229'; - let match; - if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) { - // e.g. --inspect - debugOption = match[1]; - } else if ( - (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null - ) { - debugOption = match[1]; - if (/^\d+$/.test(match[3])) { - // e.g. --inspect=1234 - debugPort = match[3]; - } else { - // e.g. --inspect=localhost - debugHost = match[3]; - } - } else if ( - (match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null - ) { - // e.g. --inspect=localhost:1234 - debugOption = match[1]; - debugHost = match[3]; - debugPort = match[4]; - } - - if (debugOption && debugPort !== '0') { - return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; - } - return arg; - }); -} - -exports.Command = Command; diff --git a/claude-code-source/node_modules/commander/lib/error.js b/claude-code-source/node_modules/commander/lib/error.js deleted file mode 100644 index 7b5b0d39..00000000 --- a/claude-code-source/node_modules/commander/lib/error.js +++ /dev/null @@ -1,39 +0,0 @@ -/** - * CommanderError class - */ -class CommanderError extends Error { - /** - * Constructs the CommanderError class - * @param {number} exitCode suggested exit code which could be used with process.exit - * @param {string} code an id string representing the error - * @param {string} message human-readable description of the error - */ - constructor(exitCode, code, message) { - super(message); - // properly capture stack trace in Node.js - Error.captureStackTrace(this, this.constructor); - this.name = this.constructor.name; - this.code = code; - this.exitCode = exitCode; - this.nestedError = undefined; - } -} - -/** - * InvalidArgumentError class - */ -class InvalidArgumentError extends CommanderError { - /** - * Constructs the InvalidArgumentError class - * @param {string} [message] explanation of why argument is invalid - */ - constructor(message) { - super(1, 'commander.invalidArgument', message); - // properly capture stack trace in Node.js - Error.captureStackTrace(this, this.constructor); - this.name = this.constructor.name; - } -} - -exports.CommanderError = CommanderError; -exports.InvalidArgumentError = InvalidArgumentError; diff --git a/claude-code-source/node_modules/commander/lib/help.js b/claude-code-source/node_modules/commander/lib/help.js deleted file mode 100644 index ed6f9916..00000000 --- a/claude-code-source/node_modules/commander/lib/help.js +++ /dev/null @@ -1,520 +0,0 @@ -const { humanReadableArgName } = require('./argument.js'); - -/** - * TypeScript import types for JSDoc, used by Visual Studio Code IntelliSense and `npm run typescript-checkJS` - * https://www.typescriptlang.org/docs/handbook/jsdoc-supported-types.html#import-types - * @typedef { import("./argument.js").Argument } Argument - * @typedef { import("./command.js").Command } Command - * @typedef { import("./option.js").Option } Option - */ - -// Although this is a class, methods are static in style to allow override using subclass or just functions. -class Help { - constructor() { - this.helpWidth = undefined; - this.sortSubcommands = false; - this.sortOptions = false; - this.showGlobalOptions = false; - } - - /** - * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. - * - * @param {Command} cmd - * @returns {Command[]} - */ - - visibleCommands(cmd) { - const visibleCommands = cmd.commands.filter((cmd) => !cmd._hidden); - const helpCommand = cmd._getHelpCommand(); - if (helpCommand && !helpCommand._hidden) { - visibleCommands.push(helpCommand); - } - if (this.sortSubcommands) { - visibleCommands.sort((a, b) => { - // @ts-ignore: because overloaded return type - return a.name().localeCompare(b.name()); - }); - } - return visibleCommands; - } - - /** - * Compare options for sort. - * - * @param {Option} a - * @param {Option} b - * @returns {number} - */ - compareOptions(a, b) { - const getSortKey = (option) => { - // WYSIWYG for order displayed in help. Short used for comparison if present. No special handling for negated. - return option.short - ? option.short.replace(/^-/, '') - : option.long.replace(/^--/, ''); - }; - return getSortKey(a).localeCompare(getSortKey(b)); - } - - /** - * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. - * - * @param {Command} cmd - * @returns {Option[]} - */ - - visibleOptions(cmd) { - const visibleOptions = cmd.options.filter((option) => !option.hidden); - // Built-in help option. - const helpOption = cmd._getHelpOption(); - if (helpOption && !helpOption.hidden) { - // Automatically hide conflicting flags. Bit dubious but a historical behaviour that is convenient for single-command programs. - const removeShort = helpOption.short && cmd._findOption(helpOption.short); - const removeLong = helpOption.long && cmd._findOption(helpOption.long); - if (!removeShort && !removeLong) { - visibleOptions.push(helpOption); // no changes needed - } else if (helpOption.long && !removeLong) { - visibleOptions.push( - cmd.createOption(helpOption.long, helpOption.description), - ); - } else if (helpOption.short && !removeShort) { - visibleOptions.push( - cmd.createOption(helpOption.short, helpOption.description), - ); - } - } - if (this.sortOptions) { - visibleOptions.sort(this.compareOptions); - } - return visibleOptions; - } - - /** - * Get an array of the visible global options. (Not including help.) - * - * @param {Command} cmd - * @returns {Option[]} - */ - - visibleGlobalOptions(cmd) { - if (!this.showGlobalOptions) return []; - - const globalOptions = []; - for ( - let ancestorCmd = cmd.parent; - ancestorCmd; - ancestorCmd = ancestorCmd.parent - ) { - const visibleOptions = ancestorCmd.options.filter( - (option) => !option.hidden, - ); - globalOptions.push(...visibleOptions); - } - if (this.sortOptions) { - globalOptions.sort(this.compareOptions); - } - return globalOptions; - } - - /** - * Get an array of the arguments if any have a description. - * - * @param {Command} cmd - * @returns {Argument[]} - */ - - visibleArguments(cmd) { - // Side effect! Apply the legacy descriptions before the arguments are displayed. - if (cmd._argsDescription) { - cmd.registeredArguments.forEach((argument) => { - argument.description = - argument.description || cmd._argsDescription[argument.name()] || ''; - }); - } - - // If there are any arguments with a description then return all the arguments. - if (cmd.registeredArguments.find((argument) => argument.description)) { - return cmd.registeredArguments; - } - return []; - } - - /** - * Get the command term to show in the list of subcommands. - * - * @param {Command} cmd - * @returns {string} - */ - - subcommandTerm(cmd) { - // Legacy. Ignores custom usage string, and nested commands. - const args = cmd.registeredArguments - .map((arg) => humanReadableArgName(arg)) - .join(' '); - return ( - cmd._name + - (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') + - (cmd.options.length ? ' [options]' : '') + // simplistic check for non-help option - (args ? ' ' + args : '') - ); - } - - /** - * Get the option term to show in the list of options. - * - * @param {Option} option - * @returns {string} - */ - - optionTerm(option) { - return option.flags; - } - - /** - * Get the argument term to show in the list of arguments. - * - * @param {Argument} argument - * @returns {string} - */ - - argumentTerm(argument) { - return argument.name(); - } - - /** - * Get the longest command term length. - * - * @param {Command} cmd - * @param {Help} helper - * @returns {number} - */ - - longestSubcommandTermLength(cmd, helper) { - return helper.visibleCommands(cmd).reduce((max, command) => { - return Math.max(max, helper.subcommandTerm(command).length); - }, 0); - } - - /** - * Get the longest option term length. - * - * @param {Command} cmd - * @param {Help} helper - * @returns {number} - */ - - longestOptionTermLength(cmd, helper) { - return helper.visibleOptions(cmd).reduce((max, option) => { - return Math.max(max, helper.optionTerm(option).length); - }, 0); - } - - /** - * Get the longest global option term length. - * - * @param {Command} cmd - * @param {Help} helper - * @returns {number} - */ - - longestGlobalOptionTermLength(cmd, helper) { - return helper.visibleGlobalOptions(cmd).reduce((max, option) => { - return Math.max(max, helper.optionTerm(option).length); - }, 0); - } - - /** - * Get the longest argument term length. - * - * @param {Command} cmd - * @param {Help} helper - * @returns {number} - */ - - longestArgumentTermLength(cmd, helper) { - return helper.visibleArguments(cmd).reduce((max, argument) => { - return Math.max(max, helper.argumentTerm(argument).length); - }, 0); - } - - /** - * Get the command usage to be displayed at the top of the built-in help. - * - * @param {Command} cmd - * @returns {string} - */ - - commandUsage(cmd) { - // Usage - let cmdName = cmd._name; - if (cmd._aliases[0]) { - cmdName = cmdName + '|' + cmd._aliases[0]; - } - let ancestorCmdNames = ''; - for ( - let ancestorCmd = cmd.parent; - ancestorCmd; - ancestorCmd = ancestorCmd.parent - ) { - ancestorCmdNames = ancestorCmd.name() + ' ' + ancestorCmdNames; - } - return ancestorCmdNames + cmdName + ' ' + cmd.usage(); - } - - /** - * Get the description for the command. - * - * @param {Command} cmd - * @returns {string} - */ - - commandDescription(cmd) { - // @ts-ignore: because overloaded return type - return cmd.description(); - } - - /** - * Get the subcommand summary to show in the list of subcommands. - * (Fallback to description for backwards compatibility.) - * - * @param {Command} cmd - * @returns {string} - */ - - subcommandDescription(cmd) { - // @ts-ignore: because overloaded return type - return cmd.summary() || cmd.description(); - } - - /** - * Get the option description to show in the list of options. - * - * @param {Option} option - * @return {string} - */ - - optionDescription(option) { - const extraInfo = []; - - if (option.argChoices) { - extraInfo.push( - // use stringify to match the display of the default value - `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`, - ); - } - if (option.defaultValue !== undefined) { - // default for boolean and negated more for programmer than end user, - // but show true/false for boolean option as may be for hand-rolled env or config processing. - const showDefault = - option.required || - option.optional || - (option.isBoolean() && typeof option.defaultValue === 'boolean'); - if (showDefault) { - extraInfo.push( - `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`, - ); - } - } - // preset for boolean and negated are more for programmer than end user - if (option.presetArg !== undefined && option.optional) { - extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`); - } - if (option.envVar !== undefined) { - extraInfo.push(`env: ${option.envVar}`); - } - if (extraInfo.length > 0) { - return `${option.description} (${extraInfo.join(', ')})`; - } - - return option.description; - } - - /** - * Get the argument description to show in the list of arguments. - * - * @param {Argument} argument - * @return {string} - */ - - argumentDescription(argument) { - const extraInfo = []; - if (argument.argChoices) { - extraInfo.push( - // use stringify to match the display of the default value - `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(', ')}`, - ); - } - if (argument.defaultValue !== undefined) { - extraInfo.push( - `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`, - ); - } - if (extraInfo.length > 0) { - const extraDescripton = `(${extraInfo.join(', ')})`; - if (argument.description) { - return `${argument.description} ${extraDescripton}`; - } - return extraDescripton; - } - return argument.description; - } - - /** - * Generate the built-in help text. - * - * @param {Command} cmd - * @param {Help} helper - * @returns {string} - */ - - formatHelp(cmd, helper) { - const termWidth = helper.padWidth(cmd, helper); - const helpWidth = helper.helpWidth || 80; - const itemIndentWidth = 2; - const itemSeparatorWidth = 2; // between term and description - function formatItem(term, description) { - if (description) { - const fullText = `${term.padEnd(termWidth + itemSeparatorWidth)}${description}`; - return helper.wrap( - fullText, - helpWidth - itemIndentWidth, - termWidth + itemSeparatorWidth, - ); - } - return term; - } - function formatList(textArray) { - return textArray.join('\n').replace(/^/gm, ' '.repeat(itemIndentWidth)); - } - - // Usage - let output = [`Usage: ${helper.commandUsage(cmd)}`, '']; - - // Description - const commandDescription = helper.commandDescription(cmd); - if (commandDescription.length > 0) { - output = output.concat([ - helper.wrap(commandDescription, helpWidth, 0), - '', - ]); - } - - // Arguments - const argumentList = helper.visibleArguments(cmd).map((argument) => { - return formatItem( - helper.argumentTerm(argument), - helper.argumentDescription(argument), - ); - }); - if (argumentList.length > 0) { - output = output.concat(['Arguments:', formatList(argumentList), '']); - } - - // Options - const optionList = helper.visibleOptions(cmd).map((option) => { - return formatItem( - helper.optionTerm(option), - helper.optionDescription(option), - ); - }); - if (optionList.length > 0) { - output = output.concat(['Options:', formatList(optionList), '']); - } - - if (this.showGlobalOptions) { - const globalOptionList = helper - .visibleGlobalOptions(cmd) - .map((option) => { - return formatItem( - helper.optionTerm(option), - helper.optionDescription(option), - ); - }); - if (globalOptionList.length > 0) { - output = output.concat([ - 'Global Options:', - formatList(globalOptionList), - '', - ]); - } - } - - // Commands - const commandList = helper.visibleCommands(cmd).map((cmd) => { - return formatItem( - helper.subcommandTerm(cmd), - helper.subcommandDescription(cmd), - ); - }); - if (commandList.length > 0) { - output = output.concat(['Commands:', formatList(commandList), '']); - } - - return output.join('\n'); - } - - /** - * Calculate the pad width from the maximum term length. - * - * @param {Command} cmd - * @param {Help} helper - * @returns {number} - */ - - padWidth(cmd, helper) { - return Math.max( - helper.longestOptionTermLength(cmd, helper), - helper.longestGlobalOptionTermLength(cmd, helper), - helper.longestSubcommandTermLength(cmd, helper), - helper.longestArgumentTermLength(cmd, helper), - ); - } - - /** - * Wrap the given string to width characters per line, with lines after the first indented. - * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted. - * - * @param {string} str - * @param {number} width - * @param {number} indent - * @param {number} [minColumnWidth=40] - * @return {string} - * - */ - - wrap(str, width, indent, minColumnWidth = 40) { - // Full \s characters, minus the linefeeds. - const indents = - ' \\f\\t\\v\u00a0\u1680\u2000-\u200a\u202f\u205f\u3000\ufeff'; - // Detect manually wrapped and indented strings by searching for line break followed by spaces. - const manualIndent = new RegExp(`[\\n][${indents}]+`); - if (str.match(manualIndent)) return str; - // Do not wrap if not enough room for a wrapped column of text (as could end up with a word per line). - const columnWidth = width - indent; - if (columnWidth < minColumnWidth) return str; - - const leadingStr = str.slice(0, indent); - const columnText = str.slice(indent).replace('\r\n', '\n'); - const indentString = ' '.repeat(indent); - const zeroWidthSpace = '\u200B'; - const breaks = `\\s${zeroWidthSpace}`; - // Match line end (so empty lines don't collapse), - // or as much text as will fit in column, or excess text up to first break. - const regex = new RegExp( - `\n|.{1,${columnWidth - 1}}([${breaks}]|$)|[^${breaks}]+?([${breaks}]|$)`, - 'g', - ); - const lines = columnText.match(regex) || []; - return ( - leadingStr + - lines - .map((line, i) => { - if (line === '\n') return ''; // preserve empty lines - return (i > 0 ? indentString : '') + line.trimEnd(); - }) - .join('\n') - ); - } -} - -exports.Help = Help; diff --git a/claude-code-source/node_modules/commander/lib/option.js b/claude-code-source/node_modules/commander/lib/option.js deleted file mode 100644 index bded840a..00000000 --- a/claude-code-source/node_modules/commander/lib/option.js +++ /dev/null @@ -1,330 +0,0 @@ -const { InvalidArgumentError } = require('./error.js'); - -class Option { - /** - * Initialize a new `Option` with the given `flags` and `description`. - * - * @param {string} flags - * @param {string} [description] - */ - - constructor(flags, description) { - this.flags = flags; - this.description = description || ''; - - this.required = flags.includes('<'); // A value must be supplied when the option is specified. - this.optional = flags.includes('['); // A value is optional when the option is specified. - // variadic test ignores et al which might be used to describe custom splitting of single argument - this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values. - this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line. - const optionFlags = splitOptionFlags(flags); - this.short = optionFlags.shortFlag; - this.long = optionFlags.longFlag; - this.negate = false; - if (this.long) { - this.negate = this.long.startsWith('--no-'); - } - this.defaultValue = undefined; - this.defaultValueDescription = undefined; - this.presetArg = undefined; - this.envVar = undefined; - this.parseArg = undefined; - this.hidden = false; - this.argChoices = undefined; - this.conflictsWith = []; - this.implied = undefined; - } - - /** - * Set the default value, and optionally supply the description to be displayed in the help. - * - * @param {*} value - * @param {string} [description] - * @return {Option} - */ - - default(value, description) { - this.defaultValue = value; - this.defaultValueDescription = description; - return this; - } - - /** - * Preset to use when option used without option-argument, especially optional but also boolean and negated. - * The custom processing (parseArg) is called. - * - * @example - * new Option('--color').default('GREYSCALE').preset('RGB'); - * new Option('--donate [amount]').preset('20').argParser(parseFloat); - * - * @param {*} arg - * @return {Option} - */ - - preset(arg) { - this.presetArg = arg; - return this; - } - - /** - * Add option name(s) that conflict with this option. - * An error will be displayed if conflicting options are found during parsing. - * - * @example - * new Option('--rgb').conflicts('cmyk'); - * new Option('--js').conflicts(['ts', 'jsx']); - * - * @param {(string | string[])} names - * @return {Option} - */ - - conflicts(names) { - this.conflictsWith = this.conflictsWith.concat(names); - return this; - } - - /** - * Specify implied option values for when this option is set and the implied options are not. - * - * The custom processing (parseArg) is not called on the implied values. - * - * @example - * program - * .addOption(new Option('--log', 'write logging information to file')) - * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' })); - * - * @param {object} impliedOptionValues - * @return {Option} - */ - implies(impliedOptionValues) { - let newImplied = impliedOptionValues; - if (typeof impliedOptionValues === 'string') { - // string is not documented, but easy mistake and we can do what user probably intended. - newImplied = { [impliedOptionValues]: true }; - } - this.implied = Object.assign(this.implied || {}, newImplied); - return this; - } - - /** - * Set environment variable to check for option value. - * - * An environment variable is only used if when processed the current option value is - * undefined, or the source of the current value is 'default' or 'config' or 'env'. - * - * @param {string} name - * @return {Option} - */ - - env(name) { - this.envVar = name; - return this; - } - - /** - * Set the custom handler for processing CLI option arguments into option values. - * - * @param {Function} [fn] - * @return {Option} - */ - - argParser(fn) { - this.parseArg = fn; - return this; - } - - /** - * Whether the option is mandatory and must have a value after parsing. - * - * @param {boolean} [mandatory=true] - * @return {Option} - */ - - makeOptionMandatory(mandatory = true) { - this.mandatory = !!mandatory; - return this; - } - - /** - * Hide option in help. - * - * @param {boolean} [hide=true] - * @return {Option} - */ - - hideHelp(hide = true) { - this.hidden = !!hide; - return this; - } - - /** - * @package - */ - - _concatValue(value, previous) { - if (previous === this.defaultValue || !Array.isArray(previous)) { - return [value]; - } - - return previous.concat(value); - } - - /** - * Only allow option value to be one of choices. - * - * @param {string[]} values - * @return {Option} - */ - - choices(values) { - this.argChoices = values.slice(); - this.parseArg = (arg, previous) => { - if (!this.argChoices.includes(arg)) { - throw new InvalidArgumentError( - `Allowed choices are ${this.argChoices.join(', ')}.`, - ); - } - if (this.variadic) { - return this._concatValue(arg, previous); - } - return arg; - }; - return this; - } - - /** - * Return option name. - * - * @return {string} - */ - - name() { - if (this.long) { - return this.long.replace(/^--/, ''); - } - return this.short.replace(/^-/, ''); - } - - /** - * Return option name, in a camelcase format that can be used - * as a object attribute key. - * - * @return {string} - */ - - attributeName() { - return camelcase(this.name().replace(/^no-/, '')); - } - - /** - * Check if `arg` matches the short or long flag. - * - * @param {string} arg - * @return {boolean} - * @package - */ - - is(arg) { - return this.short === arg || this.long === arg; - } - - /** - * Return whether a boolean option. - * - * Options are one of boolean, negated, required argument, or optional argument. - * - * @return {boolean} - * @package - */ - - isBoolean() { - return !this.required && !this.optional && !this.negate; - } -} - -/** - * This class is to make it easier to work with dual options, without changing the existing - * implementation. We support separate dual options for separate positive and negative options, - * like `--build` and `--no-build`, which share a single option value. This works nicely for some - * use cases, but is tricky for others where we want separate behaviours despite - * the single shared option value. - */ -class DualOptions { - /** - * @param {Option[]} options - */ - constructor(options) { - this.positiveOptions = new Map(); - this.negativeOptions = new Map(); - this.dualOptions = new Set(); - options.forEach((option) => { - if (option.negate) { - this.negativeOptions.set(option.attributeName(), option); - } else { - this.positiveOptions.set(option.attributeName(), option); - } - }); - this.negativeOptions.forEach((value, key) => { - if (this.positiveOptions.has(key)) { - this.dualOptions.add(key); - } - }); - } - - /** - * Did the value come from the option, and not from possible matching dual option? - * - * @param {*} value - * @param {Option} option - * @returns {boolean} - */ - valueFromOption(value, option) { - const optionKey = option.attributeName(); - if (!this.dualOptions.has(optionKey)) return true; - - // Use the value to deduce if (probably) came from the option. - const preset = this.negativeOptions.get(optionKey).presetArg; - const negativeValue = preset !== undefined ? preset : false; - return option.negate === (negativeValue === value); - } -} - -/** - * Convert string from kebab-case to camelCase. - * - * @param {string} str - * @return {string} - * @private - */ - -function camelcase(str) { - return str.split('-').reduce((str, word) => { - return str + word[0].toUpperCase() + word.slice(1); - }); -} - -/** - * Split the short and long flag out of something like '-m,--mixed ' - * - * @private - */ - -function splitOptionFlags(flags) { - let shortFlag; - let longFlag; - // Use original very loose parsing to maintain backwards compatibility for now, - // which allowed for example unintended `-sw, --short-word` [sic]. - const flagParts = flags.split(/[ |,]+/); - if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) - shortFlag = flagParts.shift(); - longFlag = flagParts.shift(); - // Add support for lone short flag without significantly changing parsing! - if (!shortFlag && /^-[^-]$/.test(longFlag)) { - shortFlag = longFlag; - longFlag = undefined; - } - return { shortFlag, longFlag }; -} - -exports.Option = Option; -exports.DualOptions = DualOptions; diff --git a/claude-code-source/node_modules/commander/lib/suggestSimilar.js b/claude-code-source/node_modules/commander/lib/suggestSimilar.js deleted file mode 100644 index 6047306d..00000000 --- a/claude-code-source/node_modules/commander/lib/suggestSimilar.js +++ /dev/null @@ -1,101 +0,0 @@ -const maxDistance = 3; - -function editDistance(a, b) { - // https://en.wikipedia.org/wiki/Damerau–Levenshtein_distance - // Calculating optimal string alignment distance, no substring is edited more than once. - // (Simple implementation.) - - // Quick early exit, return worst case. - if (Math.abs(a.length - b.length) > maxDistance) - return Math.max(a.length, b.length); - - // distance between prefix substrings of a and b - const d = []; - - // pure deletions turn a into empty string - for (let i = 0; i <= a.length; i++) { - d[i] = [i]; - } - // pure insertions turn empty string into b - for (let j = 0; j <= b.length; j++) { - d[0][j] = j; - } - - // fill matrix - for (let j = 1; j <= b.length; j++) { - for (let i = 1; i <= a.length; i++) { - let cost = 1; - if (a[i - 1] === b[j - 1]) { - cost = 0; - } else { - cost = 1; - } - d[i][j] = Math.min( - d[i - 1][j] + 1, // deletion - d[i][j - 1] + 1, // insertion - d[i - 1][j - 1] + cost, // substitution - ); - // transposition - if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) { - d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1); - } - } - } - - return d[a.length][b.length]; -} - -/** - * Find close matches, restricted to same number of edits. - * - * @param {string} word - * @param {string[]} candidates - * @returns {string} - */ - -function suggestSimilar(word, candidates) { - if (!candidates || candidates.length === 0) return ''; - // remove possible duplicates - candidates = Array.from(new Set(candidates)); - - const searchingOptions = word.startsWith('--'); - if (searchingOptions) { - word = word.slice(2); - candidates = candidates.map((candidate) => candidate.slice(2)); - } - - let similar = []; - let bestDistance = maxDistance; - const minSimilarity = 0.4; - candidates.forEach((candidate) => { - if (candidate.length <= 1) return; // no one character guesses - - const distance = editDistance(word, candidate); - const length = Math.max(word.length, candidate.length); - const similarity = (length - distance) / length; - if (similarity > minSimilarity) { - if (distance < bestDistance) { - // better edit distance, throw away previous worse matches - bestDistance = distance; - similar = [candidate]; - } else if (distance === bestDistance) { - similar.push(candidate); - } - } - }); - - similar.sort((a, b) => a.localeCompare(b)); - if (searchingOptions) { - similar = similar.map((candidate) => `--${candidate}`); - } - - if (similar.length > 1) { - return `\n(Did you mean one of ${similar.join(', ')}?)`; - } - if (similar.length === 1) { - return `\n(Did you mean ${similar[0]}?)`; - } - return ''; -} - -exports.suggestSimilar = suggestSimilar; diff --git a/claude-code-source/node_modules/convert-to-spaces/dist/index.js b/claude-code-source/node_modules/convert-to-spaces/dist/index.js deleted file mode 100644 index c674aa80..00000000 --- a/claude-code-source/node_modules/convert-to-spaces/dist/index.js +++ /dev/null @@ -1,4 +0,0 @@ -const convertToSpaces = (input, spaces = 2) => { - return input.replace(/^\t+/gm, $1 => ' '.repeat($1.length * spaces)); -}; -export default convertToSpaces; diff --git a/claude-code-source/node_modules/cross-spawn/index.js b/claude-code-source/node_modules/cross-spawn/index.js deleted file mode 100644 index 5509742c..00000000 --- a/claude-code-source/node_modules/cross-spawn/index.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict'; - -const cp = require('child_process'); -const parse = require('./lib/parse'); -const enoent = require('./lib/enoent'); - -function spawn(command, args, options) { - // Parse the arguments - const parsed = parse(command, args, options); - - // Spawn the child process - const spawned = cp.spawn(parsed.command, parsed.args, parsed.options); - - // Hook into child process "exit" event to emit an error if the command - // does not exists, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 - enoent.hookChildProcess(spawned, parsed); - - return spawned; -} - -function spawnSync(command, args, options) { - // Parse the arguments - const parsed = parse(command, args, options); - - // Spawn the child process - const result = cp.spawnSync(parsed.command, parsed.args, parsed.options); - - // Analyze if the command does not exist, see: https://github.com/IndigoUnited/node-cross-spawn/issues/16 - result.error = result.error || enoent.verifyENOENTSync(result.status, parsed); - - return result; -} - -module.exports = spawn; -module.exports.spawn = spawn; -module.exports.sync = spawnSync; - -module.exports._parse = parse; -module.exports._enoent = enoent; diff --git a/claude-code-source/node_modules/cross-spawn/lib/enoent.js b/claude-code-source/node_modules/cross-spawn/lib/enoent.js deleted file mode 100644 index da334713..00000000 --- a/claude-code-source/node_modules/cross-spawn/lib/enoent.js +++ /dev/null @@ -1,59 +0,0 @@ -'use strict'; - -const isWin = process.platform === 'win32'; - -function notFoundError(original, syscall) { - return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), { - code: 'ENOENT', - errno: 'ENOENT', - syscall: `${syscall} ${original.command}`, - path: original.command, - spawnargs: original.args, - }); -} - -function hookChildProcess(cp, parsed) { - if (!isWin) { - return; - } - - const originalEmit = cp.emit; - - cp.emit = function (name, arg1) { - // If emitting "exit" event and exit code is 1, we need to check if - // the command exists and emit an "error" instead - // See https://github.com/IndigoUnited/node-cross-spawn/issues/16 - if (name === 'exit') { - const err = verifyENOENT(arg1, parsed); - - if (err) { - return originalEmit.call(cp, 'error', err); - } - } - - return originalEmit.apply(cp, arguments); // eslint-disable-line prefer-rest-params - }; -} - -function verifyENOENT(status, parsed) { - if (isWin && status === 1 && !parsed.file) { - return notFoundError(parsed.original, 'spawn'); - } - - return null; -} - -function verifyENOENTSync(status, parsed) { - if (isWin && status === 1 && !parsed.file) { - return notFoundError(parsed.original, 'spawnSync'); - } - - return null; -} - -module.exports = { - hookChildProcess, - verifyENOENT, - verifyENOENTSync, - notFoundError, -}; diff --git a/claude-code-source/node_modules/cross-spawn/lib/parse.js b/claude-code-source/node_modules/cross-spawn/lib/parse.js deleted file mode 100644 index 0129d747..00000000 --- a/claude-code-source/node_modules/cross-spawn/lib/parse.js +++ /dev/null @@ -1,91 +0,0 @@ -'use strict'; - -const path = require('path'); -const resolveCommand = require('./util/resolveCommand'); -const escape = require('./util/escape'); -const readShebang = require('./util/readShebang'); - -const isWin = process.platform === 'win32'; -const isExecutableRegExp = /\.(?:com|exe)$/i; -const isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i; - -function detectShebang(parsed) { - parsed.file = resolveCommand(parsed); - - const shebang = parsed.file && readShebang(parsed.file); - - if (shebang) { - parsed.args.unshift(parsed.file); - parsed.command = shebang; - - return resolveCommand(parsed); - } - - return parsed.file; -} - -function parseNonShell(parsed) { - if (!isWin) { - return parsed; - } - - // Detect & add support for shebangs - const commandFile = detectShebang(parsed); - - // We don't need a shell if the command filename is an executable - const needsShell = !isExecutableRegExp.test(commandFile); - - // If a shell is required, use cmd.exe and take care of escaping everything correctly - // Note that `forceShell` is an hidden option used only in tests - if (parsed.options.forceShell || needsShell) { - // Need to double escape meta chars if the command is a cmd-shim located in `node_modules/.bin/` - // The cmd-shim simply calls execute the package bin file with NodeJS, proxying any argument - // Because the escape of metachars with ^ gets interpreted when the cmd.exe is first called, - // we need to double escape them - const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile); - - // Normalize posix paths into OS compatible paths (e.g.: foo/bar -> foo\bar) - // This is necessary otherwise it will always fail with ENOENT in those cases - parsed.command = path.normalize(parsed.command); - - // Escape command & arguments - parsed.command = escape.command(parsed.command); - parsed.args = parsed.args.map((arg) => escape.argument(arg, needsDoubleEscapeMetaChars)); - - const shellCommand = [parsed.command].concat(parsed.args).join(' '); - - parsed.args = ['/d', '/s', '/c', `"${shellCommand}"`]; - parsed.command = process.env.comspec || 'cmd.exe'; - parsed.options.windowsVerbatimArguments = true; // Tell node's spawn that the arguments are already escaped - } - - return parsed; -} - -function parse(command, args, options) { - // Normalize arguments, similar to nodejs - if (args && !Array.isArray(args)) { - options = args; - args = null; - } - - args = args ? args.slice(0) : []; // Clone array to avoid changing the original - options = Object.assign({}, options); // Clone object to avoid changing the original - - // Build our parsed object - const parsed = { - command, - args, - options, - file: undefined, - original: { - command, - args, - }, - }; - - // Delegate further parsing to shell or non-shell - return options.shell ? parsed : parseNonShell(parsed); -} - -module.exports = parse; diff --git a/claude-code-source/node_modules/cross-spawn/lib/util/escape.js b/claude-code-source/node_modules/cross-spawn/lib/util/escape.js deleted file mode 100644 index 7bf2905c..00000000 --- a/claude-code-source/node_modules/cross-spawn/lib/util/escape.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; - -// See http://www.robvanderwoude.com/escapechars.php -const metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g; - -function escapeCommand(arg) { - // Escape meta chars - arg = arg.replace(metaCharsRegExp, '^$1'); - - return arg; -} - -function escapeArgument(arg, doubleEscapeMetaChars) { - // Convert to string - arg = `${arg}`; - - // Algorithm below is based on https://qntm.org/cmd - // It's slightly altered to disable JS backtracking to avoid hanging on specially crafted input - // Please see https://github.com/moxystudio/node-cross-spawn/pull/160 for more information - - // Sequence of backslashes followed by a double quote: - // double up all the backslashes and escape the double quote - arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"'); - - // Sequence of backslashes followed by the end of the string - // (which will become a double quote later): - // double up all the backslashes - arg = arg.replace(/(?=(\\+?)?)\1$/, '$1$1'); - - // All other backslashes occur literally - - // Quote the whole thing: - arg = `"${arg}"`; - - // Escape meta chars - arg = arg.replace(metaCharsRegExp, '^$1'); - - // Double escape meta chars if necessary - if (doubleEscapeMetaChars) { - arg = arg.replace(metaCharsRegExp, '^$1'); - } - - return arg; -} - -module.exports.command = escapeCommand; -module.exports.argument = escapeArgument; diff --git a/claude-code-source/node_modules/cross-spawn/lib/util/readShebang.js b/claude-code-source/node_modules/cross-spawn/lib/util/readShebang.js deleted file mode 100644 index 5e83733f..00000000 --- a/claude-code-source/node_modules/cross-spawn/lib/util/readShebang.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -const fs = require('fs'); -const shebangCommand = require('shebang-command'); - -function readShebang(command) { - // Read the first 150 bytes from the file - const size = 150; - const buffer = Buffer.alloc(size); - - let fd; - - try { - fd = fs.openSync(command, 'r'); - fs.readSync(fd, buffer, 0, size, 0); - fs.closeSync(fd); - } catch (e) { /* Empty */ } - - // Attempt to extract shebang (null is returned if not a shebang) - return shebangCommand(buffer.toString()); -} - -module.exports = readShebang; diff --git a/claude-code-source/node_modules/cross-spawn/lib/util/resolveCommand.js b/claude-code-source/node_modules/cross-spawn/lib/util/resolveCommand.js deleted file mode 100644 index 79724550..00000000 --- a/claude-code-source/node_modules/cross-spawn/lib/util/resolveCommand.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -const path = require('path'); -const which = require('which'); -const getPathKey = require('path-key'); - -function resolveCommandAttempt(parsed, withoutPathExt) { - const env = parsed.options.env || process.env; - const cwd = process.cwd(); - const hasCustomCwd = parsed.options.cwd != null; - // Worker threads do not have process.chdir() - const shouldSwitchCwd = hasCustomCwd && process.chdir !== undefined && !process.chdir.disabled; - - // If a custom `cwd` was specified, we need to change the process cwd - // because `which` will do stat calls but does not support a custom cwd - if (shouldSwitchCwd) { - try { - process.chdir(parsed.options.cwd); - } catch (err) { - /* Empty */ - } - } - - let resolved; - - try { - resolved = which.sync(parsed.command, { - path: env[getPathKey({ env })], - pathExt: withoutPathExt ? path.delimiter : undefined, - }); - } catch (e) { - /* Empty */ - } finally { - if (shouldSwitchCwd) { - process.chdir(cwd); - } - } - - // If we successfully resolved, ensure that an absolute path is returned - // Note that when a custom `cwd` was used, we need to resolve to an absolute path based on it - if (resolved) { - resolved = path.resolve(hasCustomCwd ? parsed.options.cwd : '', resolved); - } - - return resolved; -} - -function resolveCommand(parsed) { - return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true); -} - -module.exports = resolveCommand; diff --git a/claude-code-source/node_modules/cssfilter/lib/css.js b/claude-code-source/node_modules/cssfilter/lib/css.js deleted file mode 100644 index 49e97073..00000000 --- a/claude-code-source/node_modules/cssfilter/lib/css.js +++ /dev/null @@ -1,110 +0,0 @@ -/** - * cssfilter - * - * @author 老雷 - */ - -var DEFAULT = require('./default'); -var parseStyle = require('./parser'); -var _ = require('./util'); - - -/** - * 返回值是否为空 - * - * @param {Object} obj - * @return {Boolean} - */ -function isNull (obj) { - return (obj === undefined || obj === null); -} - -/** - * 浅拷贝对象 - * - * @param {Object} obj - * @return {Object} - */ -function shallowCopyObject (obj) { - var ret = {}; - for (var i in obj) { - ret[i] = obj[i]; - } - return ret; -} - -/** - * 创建CSS过滤器 - * - * @param {Object} options - * - {Object} whiteList - * - {Function} onAttr - * - {Function} onIgnoreAttr - * - {Function} safeAttrValue - */ -function FilterCSS (options) { - options = shallowCopyObject(options || {}); - options.whiteList = options.whiteList || DEFAULT.whiteList; - options.onAttr = options.onAttr || DEFAULT.onAttr; - options.onIgnoreAttr = options.onIgnoreAttr || DEFAULT.onIgnoreAttr; - options.safeAttrValue = options.safeAttrValue || DEFAULT.safeAttrValue; - this.options = options; -} - -FilterCSS.prototype.process = function (css) { - // 兼容各种奇葩输入 - css = css || ''; - css = css.toString(); - if (!css) return ''; - - var me = this; - var options = me.options; - var whiteList = options.whiteList; - var onAttr = options.onAttr; - var onIgnoreAttr = options.onIgnoreAttr; - var safeAttrValue = options.safeAttrValue; - - var retCSS = parseStyle(css, function (sourcePosition, position, name, value, source) { - - var check = whiteList[name]; - var isWhite = false; - if (check === true) isWhite = check; - else if (typeof check === 'function') isWhite = check(value); - else if (check instanceof RegExp) isWhite = check.test(value); - if (isWhite !== true) isWhite = false; - - // 如果过滤后 value 为空则直接忽略 - value = safeAttrValue(name, value); - if (!value) return; - - var opts = { - position: position, - sourcePosition: sourcePosition, - source: source, - isWhite: isWhite - }; - - if (isWhite) { - - var ret = onAttr(name, value, opts); - if (isNull(ret)) { - return name + ':' + value; - } else { - return ret; - } - - } else { - - var ret = onIgnoreAttr(name, value, opts); - if (!isNull(ret)) { - return ret; - } - - } - }); - - return retCSS; -}; - - -module.exports = FilterCSS; diff --git a/claude-code-source/node_modules/cssfilter/lib/default.js b/claude-code-source/node_modules/cssfilter/lib/default.js deleted file mode 100644 index b6772254..00000000 --- a/claude-code-source/node_modules/cssfilter/lib/default.js +++ /dev/null @@ -1,398 +0,0 @@ -/** - * cssfilter - * - * @author 老雷 - */ - -function getDefaultWhiteList () { - // 白名单值说明: - // true: 允许该属性 - // Function: function (val) { } 返回true表示允许该属性,其他值均表示不允许 - // RegExp: regexp.test(val) 返回true表示允许该属性,其他值均表示不允许 - // 除上面列出的值外均表示不允许 - var whiteList = {}; - - whiteList['align-content'] = false; // default: auto - whiteList['align-items'] = false; // default: auto - whiteList['align-self'] = false; // default: auto - whiteList['alignment-adjust'] = false; // default: auto - whiteList['alignment-baseline'] = false; // default: baseline - whiteList['all'] = false; // default: depending on individual properties - whiteList['anchor-point'] = false; // default: none - whiteList['animation'] = false; // default: depending on individual properties - whiteList['animation-delay'] = false; // default: 0 - whiteList['animation-direction'] = false; // default: normal - whiteList['animation-duration'] = false; // default: 0 - whiteList['animation-fill-mode'] = false; // default: none - whiteList['animation-iteration-count'] = false; // default: 1 - whiteList['animation-name'] = false; // default: none - whiteList['animation-play-state'] = false; // default: running - whiteList['animation-timing-function'] = false; // default: ease - whiteList['azimuth'] = false; // default: center - whiteList['backface-visibility'] = false; // default: visible - whiteList['background'] = true; // default: depending on individual properties - whiteList['background-attachment'] = true; // default: scroll - whiteList['background-clip'] = true; // default: border-box - whiteList['background-color'] = true; // default: transparent - whiteList['background-image'] = true; // default: none - whiteList['background-origin'] = true; // default: padding-box - whiteList['background-position'] = true; // default: 0% 0% - whiteList['background-repeat'] = true; // default: repeat - whiteList['background-size'] = true; // default: auto - whiteList['baseline-shift'] = false; // default: baseline - whiteList['binding'] = false; // default: none - whiteList['bleed'] = false; // default: 6pt - whiteList['bookmark-label'] = false; // default: content() - whiteList['bookmark-level'] = false; // default: none - whiteList['bookmark-state'] = false; // default: open - whiteList['border'] = true; // default: depending on individual properties - whiteList['border-bottom'] = true; // default: depending on individual properties - whiteList['border-bottom-color'] = true; // default: current color - whiteList['border-bottom-left-radius'] = true; // default: 0 - whiteList['border-bottom-right-radius'] = true; // default: 0 - whiteList['border-bottom-style'] = true; // default: none - whiteList['border-bottom-width'] = true; // default: medium - whiteList['border-collapse'] = true; // default: separate - whiteList['border-color'] = true; // default: depending on individual properties - whiteList['border-image'] = true; // default: none - whiteList['border-image-outset'] = true; // default: 0 - whiteList['border-image-repeat'] = true; // default: stretch - whiteList['border-image-slice'] = true; // default: 100% - whiteList['border-image-source'] = true; // default: none - whiteList['border-image-width'] = true; // default: 1 - whiteList['border-left'] = true; // default: depending on individual properties - whiteList['border-left-color'] = true; // default: current color - whiteList['border-left-style'] = true; // default: none - whiteList['border-left-width'] = true; // default: medium - whiteList['border-radius'] = true; // default: 0 - whiteList['border-right'] = true; // default: depending on individual properties - whiteList['border-right-color'] = true; // default: current color - whiteList['border-right-style'] = true; // default: none - whiteList['border-right-width'] = true; // default: medium - whiteList['border-spacing'] = true; // default: 0 - whiteList['border-style'] = true; // default: depending on individual properties - whiteList['border-top'] = true; // default: depending on individual properties - whiteList['border-top-color'] = true; // default: current color - whiteList['border-top-left-radius'] = true; // default: 0 - whiteList['border-top-right-radius'] = true; // default: 0 - whiteList['border-top-style'] = true; // default: none - whiteList['border-top-width'] = true; // default: medium - whiteList['border-width'] = true; // default: depending on individual properties - whiteList['bottom'] = false; // default: auto - whiteList['box-decoration-break'] = true; // default: slice - whiteList['box-shadow'] = true; // default: none - whiteList['box-sizing'] = true; // default: content-box - whiteList['box-snap'] = true; // default: none - whiteList['box-suppress'] = true; // default: show - whiteList['break-after'] = true; // default: auto - whiteList['break-before'] = true; // default: auto - whiteList['break-inside'] = true; // default: auto - whiteList['caption-side'] = false; // default: top - whiteList['chains'] = false; // default: none - whiteList['clear'] = true; // default: none - whiteList['clip'] = false; // default: auto - whiteList['clip-path'] = false; // default: none - whiteList['clip-rule'] = false; // default: nonzero - whiteList['color'] = true; // default: implementation dependent - whiteList['color-interpolation-filters'] = true; // default: auto - whiteList['column-count'] = false; // default: auto - whiteList['column-fill'] = false; // default: balance - whiteList['column-gap'] = false; // default: normal - whiteList['column-rule'] = false; // default: depending on individual properties - whiteList['column-rule-color'] = false; // default: current color - whiteList['column-rule-style'] = false; // default: medium - whiteList['column-rule-width'] = false; // default: medium - whiteList['column-span'] = false; // default: none - whiteList['column-width'] = false; // default: auto - whiteList['columns'] = false; // default: depending on individual properties - whiteList['contain'] = false; // default: none - whiteList['content'] = false; // default: normal - whiteList['counter-increment'] = false; // default: none - whiteList['counter-reset'] = false; // default: none - whiteList['counter-set'] = false; // default: none - whiteList['crop'] = false; // default: auto - whiteList['cue'] = false; // default: depending on individual properties - whiteList['cue-after'] = false; // default: none - whiteList['cue-before'] = false; // default: none - whiteList['cursor'] = false; // default: auto - whiteList['direction'] = false; // default: ltr - whiteList['display'] = true; // default: depending on individual properties - whiteList['display-inside'] = true; // default: auto - whiteList['display-list'] = true; // default: none - whiteList['display-outside'] = true; // default: inline-level - whiteList['dominant-baseline'] = false; // default: auto - whiteList['elevation'] = false; // default: level - whiteList['empty-cells'] = false; // default: show - whiteList['filter'] = false; // default: none - whiteList['flex'] = false; // default: depending on individual properties - whiteList['flex-basis'] = false; // default: auto - whiteList['flex-direction'] = false; // default: row - whiteList['flex-flow'] = false; // default: depending on individual properties - whiteList['flex-grow'] = false; // default: 0 - whiteList['flex-shrink'] = false; // default: 1 - whiteList['flex-wrap'] = false; // default: nowrap - whiteList['float'] = false; // default: none - whiteList['float-offset'] = false; // default: 0 0 - whiteList['flood-color'] = false; // default: black - whiteList['flood-opacity'] = false; // default: 1 - whiteList['flow-from'] = false; // default: none - whiteList['flow-into'] = false; // default: none - whiteList['font'] = true; // default: depending on individual properties - whiteList['font-family'] = true; // default: implementation dependent - whiteList['font-feature-settings'] = true; // default: normal - whiteList['font-kerning'] = true; // default: auto - whiteList['font-language-override'] = true; // default: normal - whiteList['font-size'] = true; // default: medium - whiteList['font-size-adjust'] = true; // default: none - whiteList['font-stretch'] = true; // default: normal - whiteList['font-style'] = true; // default: normal - whiteList['font-synthesis'] = true; // default: weight style - whiteList['font-variant'] = true; // default: normal - whiteList['font-variant-alternates'] = true; // default: normal - whiteList['font-variant-caps'] = true; // default: normal - whiteList['font-variant-east-asian'] = true; // default: normal - whiteList['font-variant-ligatures'] = true; // default: normal - whiteList['font-variant-numeric'] = true; // default: normal - whiteList['font-variant-position'] = true; // default: normal - whiteList['font-weight'] = true; // default: normal - whiteList['grid'] = false; // default: depending on individual properties - whiteList['grid-area'] = false; // default: depending on individual properties - whiteList['grid-auto-columns'] = false; // default: auto - whiteList['grid-auto-flow'] = false; // default: none - whiteList['grid-auto-rows'] = false; // default: auto - whiteList['grid-column'] = false; // default: depending on individual properties - whiteList['grid-column-end'] = false; // default: auto - whiteList['grid-column-start'] = false; // default: auto - whiteList['grid-row'] = false; // default: depending on individual properties - whiteList['grid-row-end'] = false; // default: auto - whiteList['grid-row-start'] = false; // default: auto - whiteList['grid-template'] = false; // default: depending on individual properties - whiteList['grid-template-areas'] = false; // default: none - whiteList['grid-template-columns'] = false; // default: none - whiteList['grid-template-rows'] = false; // default: none - whiteList['hanging-punctuation'] = false; // default: none - whiteList['height'] = true; // default: auto - whiteList['hyphens'] = false; // default: manual - whiteList['icon'] = false; // default: auto - whiteList['image-orientation'] = false; // default: auto - whiteList['image-resolution'] = false; // default: normal - whiteList['ime-mode'] = false; // default: auto - whiteList['initial-letters'] = false; // default: normal - whiteList['inline-box-align'] = false; // default: last - whiteList['justify-content'] = false; // default: auto - whiteList['justify-items'] = false; // default: auto - whiteList['justify-self'] = false; // default: auto - whiteList['left'] = false; // default: auto - whiteList['letter-spacing'] = true; // default: normal - whiteList['lighting-color'] = true; // default: white - whiteList['line-box-contain'] = false; // default: block inline replaced - whiteList['line-break'] = false; // default: auto - whiteList['line-grid'] = false; // default: match-parent - whiteList['line-height'] = false; // default: normal - whiteList['line-snap'] = false; // default: none - whiteList['line-stacking'] = false; // default: depending on individual properties - whiteList['line-stacking-ruby'] = false; // default: exclude-ruby - whiteList['line-stacking-shift'] = false; // default: consider-shifts - whiteList['line-stacking-strategy'] = false; // default: inline-line-height - whiteList['list-style'] = true; // default: depending on individual properties - whiteList['list-style-image'] = true; // default: none - whiteList['list-style-position'] = true; // default: outside - whiteList['list-style-type'] = true; // default: disc - whiteList['margin'] = true; // default: depending on individual properties - whiteList['margin-bottom'] = true; // default: 0 - whiteList['margin-left'] = true; // default: 0 - whiteList['margin-right'] = true; // default: 0 - whiteList['margin-top'] = true; // default: 0 - whiteList['marker-offset'] = false; // default: auto - whiteList['marker-side'] = false; // default: list-item - whiteList['marks'] = false; // default: none - whiteList['mask'] = false; // default: border-box - whiteList['mask-box'] = false; // default: see individual properties - whiteList['mask-box-outset'] = false; // default: 0 - whiteList['mask-box-repeat'] = false; // default: stretch - whiteList['mask-box-slice'] = false; // default: 0 fill - whiteList['mask-box-source'] = false; // default: none - whiteList['mask-box-width'] = false; // default: auto - whiteList['mask-clip'] = false; // default: border-box - whiteList['mask-image'] = false; // default: none - whiteList['mask-origin'] = false; // default: border-box - whiteList['mask-position'] = false; // default: center - whiteList['mask-repeat'] = false; // default: no-repeat - whiteList['mask-size'] = false; // default: border-box - whiteList['mask-source-type'] = false; // default: auto - whiteList['mask-type'] = false; // default: luminance - whiteList['max-height'] = true; // default: none - whiteList['max-lines'] = false; // default: none - whiteList['max-width'] = true; // default: none - whiteList['min-height'] = true; // default: 0 - whiteList['min-width'] = true; // default: 0 - whiteList['move-to'] = false; // default: normal - whiteList['nav-down'] = false; // default: auto - whiteList['nav-index'] = false; // default: auto - whiteList['nav-left'] = false; // default: auto - whiteList['nav-right'] = false; // default: auto - whiteList['nav-up'] = false; // default: auto - whiteList['object-fit'] = false; // default: fill - whiteList['object-position'] = false; // default: 50% 50% - whiteList['opacity'] = false; // default: 1 - whiteList['order'] = false; // default: 0 - whiteList['orphans'] = false; // default: 2 - whiteList['outline'] = false; // default: depending on individual properties - whiteList['outline-color'] = false; // default: invert - whiteList['outline-offset'] = false; // default: 0 - whiteList['outline-style'] = false; // default: none - whiteList['outline-width'] = false; // default: medium - whiteList['overflow'] = false; // default: depending on individual properties - whiteList['overflow-wrap'] = false; // default: normal - whiteList['overflow-x'] = false; // default: visible - whiteList['overflow-y'] = false; // default: visible - whiteList['padding'] = true; // default: depending on individual properties - whiteList['padding-bottom'] = true; // default: 0 - whiteList['padding-left'] = true; // default: 0 - whiteList['padding-right'] = true; // default: 0 - whiteList['padding-top'] = true; // default: 0 - whiteList['page'] = false; // default: auto - whiteList['page-break-after'] = false; // default: auto - whiteList['page-break-before'] = false; // default: auto - whiteList['page-break-inside'] = false; // default: auto - whiteList['page-policy'] = false; // default: start - whiteList['pause'] = false; // default: implementation dependent - whiteList['pause-after'] = false; // default: implementation dependent - whiteList['pause-before'] = false; // default: implementation dependent - whiteList['perspective'] = false; // default: none - whiteList['perspective-origin'] = false; // default: 50% 50% - whiteList['pitch'] = false; // default: medium - whiteList['pitch-range'] = false; // default: 50 - whiteList['play-during'] = false; // default: auto - whiteList['position'] = false; // default: static - whiteList['presentation-level'] = false; // default: 0 - whiteList['quotes'] = false; // default: text - whiteList['region-fragment'] = false; // default: auto - whiteList['resize'] = false; // default: none - whiteList['rest'] = false; // default: depending on individual properties - whiteList['rest-after'] = false; // default: none - whiteList['rest-before'] = false; // default: none - whiteList['richness'] = false; // default: 50 - whiteList['right'] = false; // default: auto - whiteList['rotation'] = false; // default: 0 - whiteList['rotation-point'] = false; // default: 50% 50% - whiteList['ruby-align'] = false; // default: auto - whiteList['ruby-merge'] = false; // default: separate - whiteList['ruby-position'] = false; // default: before - whiteList['shape-image-threshold'] = false; // default: 0.0 - whiteList['shape-outside'] = false; // default: none - whiteList['shape-margin'] = false; // default: 0 - whiteList['size'] = false; // default: auto - whiteList['speak'] = false; // default: auto - whiteList['speak-as'] = false; // default: normal - whiteList['speak-header'] = false; // default: once - whiteList['speak-numeral'] = false; // default: continuous - whiteList['speak-punctuation'] = false; // default: none - whiteList['speech-rate'] = false; // default: medium - whiteList['stress'] = false; // default: 50 - whiteList['string-set'] = false; // default: none - whiteList['tab-size'] = false; // default: 8 - whiteList['table-layout'] = false; // default: auto - whiteList['text-align'] = true; // default: start - whiteList['text-align-last'] = true; // default: auto - whiteList['text-combine-upright'] = true; // default: none - whiteList['text-decoration'] = true; // default: none - whiteList['text-decoration-color'] = true; // default: currentColor - whiteList['text-decoration-line'] = true; // default: none - whiteList['text-decoration-skip'] = true; // default: objects - whiteList['text-decoration-style'] = true; // default: solid - whiteList['text-emphasis'] = true; // default: depending on individual properties - whiteList['text-emphasis-color'] = true; // default: currentColor - whiteList['text-emphasis-position'] = true; // default: over right - whiteList['text-emphasis-style'] = true; // default: none - whiteList['text-height'] = true; // default: auto - whiteList['text-indent'] = true; // default: 0 - whiteList['text-justify'] = true; // default: auto - whiteList['text-orientation'] = true; // default: mixed - whiteList['text-overflow'] = true; // default: clip - whiteList['text-shadow'] = true; // default: none - whiteList['text-space-collapse'] = true; // default: collapse - whiteList['text-transform'] = true; // default: none - whiteList['text-underline-position'] = true; // default: auto - whiteList['text-wrap'] = true; // default: normal - whiteList['top'] = false; // default: auto - whiteList['transform'] = false; // default: none - whiteList['transform-origin'] = false; // default: 50% 50% 0 - whiteList['transform-style'] = false; // default: flat - whiteList['transition'] = false; // default: depending on individual properties - whiteList['transition-delay'] = false; // default: 0s - whiteList['transition-duration'] = false; // default: 0s - whiteList['transition-property'] = false; // default: all - whiteList['transition-timing-function'] = false; // default: ease - whiteList['unicode-bidi'] = false; // default: normal - whiteList['vertical-align'] = false; // default: baseline - whiteList['visibility'] = false; // default: visible - whiteList['voice-balance'] = false; // default: center - whiteList['voice-duration'] = false; // default: auto - whiteList['voice-family'] = false; // default: implementation dependent - whiteList['voice-pitch'] = false; // default: medium - whiteList['voice-range'] = false; // default: medium - whiteList['voice-rate'] = false; // default: normal - whiteList['voice-stress'] = false; // default: normal - whiteList['voice-volume'] = false; // default: medium - whiteList['volume'] = false; // default: medium - whiteList['white-space'] = false; // default: normal - whiteList['widows'] = false; // default: 2 - whiteList['width'] = true; // default: auto - whiteList['will-change'] = false; // default: auto - whiteList['word-break'] = true; // default: normal - whiteList['word-spacing'] = true; // default: normal - whiteList['word-wrap'] = true; // default: normal - whiteList['wrap-flow'] = false; // default: auto - whiteList['wrap-through'] = false; // default: wrap - whiteList['writing-mode'] = false; // default: horizontal-tb - whiteList['z-index'] = false; // default: auto - - return whiteList; -} - - -/** - * 匹配到白名单上的一个属性时 - * - * @param {String} name - * @param {String} value - * @param {Object} options - * @return {String} - */ -function onAttr (name, value, options) { - // do nothing -} - -/** - * 匹配到不在白名单上的一个属性时 - * - * @param {String} name - * @param {String} value - * @param {Object} options - * @return {String} - */ -function onIgnoreAttr (name, value, options) { - // do nothing -} - -var REGEXP_URL_JAVASCRIPT = /javascript\s*\:/img; - -/** - * 过滤属性值 - * - * @param {String} name - * @param {String} value - * @return {String} - */ -function safeAttrValue(name, value) { - if (REGEXP_URL_JAVASCRIPT.test(value)) return ''; - return value; -} - - -exports.whiteList = getDefaultWhiteList(); -exports.getDefaultWhiteList = getDefaultWhiteList; -exports.onAttr = onAttr; -exports.onIgnoreAttr = onIgnoreAttr; -exports.safeAttrValue = safeAttrValue; diff --git a/claude-code-source/node_modules/cssfilter/lib/index.js b/claude-code-source/node_modules/cssfilter/lib/index.js deleted file mode 100644 index 712f55f8..00000000 --- a/claude-code-source/node_modules/cssfilter/lib/index.js +++ /dev/null @@ -1,32 +0,0 @@ -/** - * cssfilter - * - * @author 老雷 - */ - -var DEFAULT = require('./default'); -var FilterCSS = require('./css'); - - -/** - * XSS过滤 - * - * @param {String} css 要过滤的CSS代码 - * @param {Object} options 选项:whiteList, onAttr, onIgnoreAttr - * @return {String} - */ -function filterCSS (html, options) { - var xss = new FilterCSS(options); - return xss.process(html); -} - - -// 输出 -exports = module.exports = filterCSS; -exports.FilterCSS = FilterCSS; -for (var i in DEFAULT) exports[i] = DEFAULT[i]; - -// 在浏览器端使用 -if (typeof window !== 'undefined') { - window.filterCSS = module.exports; -} diff --git a/claude-code-source/node_modules/cssfilter/lib/parser.js b/claude-code-source/node_modules/cssfilter/lib/parser.js deleted file mode 100644 index fcb94181..00000000 --- a/claude-code-source/node_modules/cssfilter/lib/parser.js +++ /dev/null @@ -1,74 +0,0 @@ -/** - * cssfilter - * - * @author 老雷 - */ - -var _ = require('./util'); - - -/** - * 解析style - * - * @param {String} css - * @param {Function} onAttr 处理属性的函数 - * 参数格式: function (sourcePosition, position, name, value, source) - * @return {String} - */ -function parseStyle (css, onAttr) { - css = _.trimRight(css); - if (css[css.length - 1] !== ';') css += ';'; - var cssLength = css.length; - var isParenthesisOpen = false; - var lastPos = 0; - var i = 0; - var retCSS = ''; - - function addNewAttr () { - // 如果没有正常的闭合圆括号,则直接忽略当前属性 - if (!isParenthesisOpen) { - var source = _.trim(css.slice(lastPos, i)); - var j = source.indexOf(':'); - if (j !== -1) { - var name = _.trim(source.slice(0, j)); - var value = _.trim(source.slice(j + 1)); - // 必须有属性名称 - if (name) { - var ret = onAttr(lastPos, retCSS.length, name, value, source); - if (ret) retCSS += ret + '; '; - } - } - } - lastPos = i + 1; - } - - for (; i < cssLength; i++) { - var c = css[i]; - if (c === '/' && css[i + 1] === '*') { - // 备注开始 - var j = css.indexOf('*/', i + 2); - // 如果没有正常的备注结束,则后面的部分全部跳过 - if (j === -1) break; - // 直接将当前位置调到备注结尾,并且初始化状态 - i = j + 1; - lastPos = i + 1; - isParenthesisOpen = false; - } else if (c === '(') { - isParenthesisOpen = true; - } else if (c === ')') { - isParenthesisOpen = false; - } else if (c === ';') { - if (isParenthesisOpen) { - // 在圆括号里面,忽略 - } else { - addNewAttr(); - } - } else if (c === '\n') { - addNewAttr(); - } - } - - return _.trim(retCSS); -} - -module.exports = parseStyle; diff --git a/claude-code-source/node_modules/cssfilter/lib/util.js b/claude-code-source/node_modules/cssfilter/lib/util.js deleted file mode 100644 index c8b4f7b9..00000000 --- a/claude-code-source/node_modules/cssfilter/lib/util.js +++ /dev/null @@ -1,35 +0,0 @@ -module.exports = { - indexOf: function (arr, item) { - var i, j; - if (Array.prototype.indexOf) { - return arr.indexOf(item); - } - for (i = 0, j = arr.length; i < j; i++) { - if (arr[i] === item) { - return i; - } - } - return -1; - }, - forEach: function (arr, fn, scope) { - var i, j; - if (Array.prototype.forEach) { - return arr.forEach(fn, scope); - } - for (i = 0, j = arr.length; i < j; i++) { - fn.call(scope, arr[i], i, arr); - } - }, - trim: function (str) { - if (String.prototype.trim) { - return str.trim(); - } - return str.replace(/(^\s*)|(\s*$)/g, ''); - }, - trimRight: function (str) { - if (String.prototype.trimRight) { - return str.trimRight(); - } - return str.replace(/(\s*$)/g, ''); - } -}; diff --git a/claude-code-source/node_modules/debug/src/browser.js b/claude-code-source/node_modules/debug/src/browser.js deleted file mode 100644 index df8e179e..00000000 --- a/claude-code-source/node_modules/debug/src/browser.js +++ /dev/null @@ -1,272 +0,0 @@ -/* eslint-env browser */ - -/** - * This is the web browser implementation of `debug()`. - */ - -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; - - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); - -/** - * Colors. - */ - -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } - - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } - - let m; - - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - // eslint-disable-next-line no-return-assign - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); - - if (!this.useColors) { - return; - } - - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); - - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public - */ -exports.log = console.debug || console.log || (() => {}); - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} - -module.exports = require('./common')(exports); - -const {formatters} = module.exports; - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; diff --git a/claude-code-source/node_modules/debug/src/common.js b/claude-code-source/node_modules/debug/src/common.js deleted file mode 100644 index 528c7ecf..00000000 --- a/claude-code-source/node_modules/debug/src/common.js +++ /dev/null @@ -1,292 +0,0 @@ - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ - -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = require('ms'); - createDebug.destroy = destroy; - - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); - - /** - * The currently active debug mode names, and names to skip. - */ - - createDebug.names = []; - createDebug.skips = []; - - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; - - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; - - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; - - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; - let namespacesCache; - let enabledCache; - - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } - - const self = debug; - - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - args[0] = createDebug.coerce(args[0]); - - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } - - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); - - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); - - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. - - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => { - if (enableOverride !== null) { - return enableOverride; - } - if (namespacesCache !== createDebug.namespaces) { - namespacesCache = createDebug.namespaces; - enabledCache = createDebug.enabled(namespace); - } - - return enabledCache; - }, - set: v => { - enableOverride = v; - } - }); - - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } - - return debug; - } - - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } - - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.namespaces = namespaces; - - createDebug.names = []; - createDebug.skips = []; - - const split = (typeof namespaces === 'string' ? namespaces : '') - .trim() - .replace(' ', ',') - .split(',') - .filter(Boolean); - - for (const ns of split) { - if (ns[0] === '-') { - createDebug.skips.push(ns.slice(1)); - } else { - createDebug.names.push(ns); - } - } - } - - /** - * Checks if the given string matches a namespace template, honoring - * asterisks as wildcards. - * - * @param {String} search - * @param {String} template - * @return {Boolean} - */ - function matchesTemplate(search, template) { - let searchIndex = 0; - let templateIndex = 0; - let starIndex = -1; - let matchIndex = 0; - - while (searchIndex < search.length) { - if (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) { - // Match character or proceed with wildcard - if (template[templateIndex] === '*') { - starIndex = templateIndex; - matchIndex = searchIndex; - templateIndex++; // Skip the '*' - } else { - searchIndex++; - templateIndex++; - } - } else if (starIndex !== -1) { // eslint-disable-line no-negated-condition - // Backtrack to the last '*' and try to match more characters - templateIndex = starIndex + 1; - matchIndex++; - searchIndex = matchIndex; - } else { - return false; // No match - } - } - - // Handle trailing '*' in template - while (templateIndex < template.length && template[templateIndex] === '*') { - templateIndex++; - } - - return templateIndex === template.length; - } - - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names, - ...createDebug.skips.map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } - - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - for (const skip of createDebug.skips) { - if (matchesTemplate(name, skip)) { - return false; - } - } - - for (const ns of createDebug.names) { - if (matchesTemplate(name, ns)) { - return true; - } - } - - return false; - } - - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } - - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - - createDebug.enable(createDebug.load()); - - return createDebug; -} - -module.exports = setup; diff --git a/claude-code-source/node_modules/debug/src/index.js b/claude-code-source/node_modules/debug/src/index.js deleted file mode 100644 index bf4c57f2..00000000 --- a/claude-code-source/node_modules/debug/src/index.js +++ /dev/null @@ -1,10 +0,0 @@ -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ - -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = require('./browser.js'); -} else { - module.exports = require('./node.js'); -} diff --git a/claude-code-source/node_modules/debug/src/node.js b/claude-code-source/node_modules/debug/src/node.js deleted file mode 100644 index 715560a4..00000000 --- a/claude-code-source/node_modules/debug/src/node.js +++ /dev/null @@ -1,263 +0,0 @@ -/** - * Module dependencies. - */ - -const tty = require('tty'); -const util = require('util'); - -/** - * This is the Node.js implementation of `debug()`. - */ - -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); - -/** - * Colors. - */ - -exports.colors = [6, 2, 3, 4, 5, 1]; - -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = require('supports-color'); - - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. -} - -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ - -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); - - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } - - obj[prop] = val; - return obj; -}, {}); - -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ - -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); -} - -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ - -function formatArgs(args) { - const {namespace: name, useColors} = this; - - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} - -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} - -/** - * Invokes `util.formatWithOptions()` with the specified arguments and writes to stderr. - */ - -function log(...args) { - return process.stderr.write(util.formatWithOptions(exports.inspectOpts, ...args) + '\n'); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - return process.env.DEBUG; -} - -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ - -function init(debug) { - debug.inspectOpts = {}; - - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} - -module.exports = require('./common')(exports); - -const {formatters} = module.exports; - -/** - * Map %o to `util.inspect()`, all on a single line. - */ - -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; - -/** - * Map %O to `util.inspect()`, allowing multiple lines if needed. - */ - -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; diff --git a/claude-code-source/node_modules/default-browser-id/index.js b/claude-code-source/node_modules/default-browser-id/index.js deleted file mode 100644 index f1edf270..00000000 --- a/claude-code-source/node_modules/default-browser-id/index.js +++ /dev/null @@ -1,18 +0,0 @@ -import {promisify} from 'node:util'; -import process from 'node:process'; -import {execFile} from 'node:child_process'; - -const execFileAsync = promisify(execFile); - -export default async function defaultBrowserId() { - if (process.platform !== 'darwin') { - throw new Error('macOS only'); - } - - const {stdout} = await execFileAsync('defaults', ['read', 'com.apple.LaunchServices/com.apple.launchservices.secure', 'LSHandlers']); - - // `(?!-)` is to prevent matching `LSHandlerRoleAll = "-";`. - const match = /LSHandlerRoleAll = "(?!-)(?[^"]+?)";\s+?LSHandlerURLScheme = (?:http|https);/.exec(stdout); - - return match?.groups.id ?? 'com.apple.Safari'; -} diff --git a/claude-code-source/node_modules/default-browser/index.js b/claude-code-source/node_modules/default-browser/index.js deleted file mode 100644 index 49451030..00000000 --- a/claude-code-source/node_modules/default-browser/index.js +++ /dev/null @@ -1,32 +0,0 @@ -import {promisify} from 'node:util'; -import process from 'node:process'; -import {execFile} from 'node:child_process'; -import defaultBrowserId from 'default-browser-id'; -import bundleName from 'bundle-name'; -import windows from './windows.js'; - -const execFileAsync = promisify(execFile); - -// Inlined: https://github.com/sindresorhus/titleize/blob/main/index.js -const titleize = string => string.toLowerCase().replaceAll(/(?:^|\s|-)\S/g, x => x.toUpperCase()); - -export default async function defaultBrowser() { - if (process.platform === 'darwin') { - const id = await defaultBrowserId(); - const name = await bundleName(id); - return {name, id}; - } - - if (process.platform === 'linux') { - const {stdout} = await execFileAsync('xdg-mime', ['query', 'default', 'x-scheme-handler/http']); - const id = stdout.trim(); - const name = titleize(id.replace(/.desktop$/, '').replace('-', ' ')); - return {name, id}; - } - - if (process.platform === 'win32') { - return windows(); - } - - throw new Error('Only macOS, Linux, and Windows are supported'); -} diff --git a/claude-code-source/node_modules/default-browser/windows.js b/claude-code-source/node_modules/default-browser/windows.js deleted file mode 100644 index fcc466fc..00000000 --- a/claude-code-source/node_modules/default-browser/windows.js +++ /dev/null @@ -1,43 +0,0 @@ -import {promisify} from 'node:util'; -import {execFile} from 'node:child_process'; - -const execFileAsync = promisify(execFile); - -// Windows doesn't have browser IDs in the same way macOS/Linux does so we give fake -// ones that look real and match the macOS/Linux versions for cross-platform apps. -const windowsBrowserProgIds = { - AppXq0fevzme2pys62n3e0fbqa7peapykr8v: {name: 'Edge', id: 'com.microsoft.edge.old'}, - MSEdgeDHTML: {name: 'Edge', id: 'com.microsoft.edge'}, // On macOS, it's "com.microsoft.edgemac" - MSEdgeHTM: {name: 'Edge', id: 'com.microsoft.edge'}, // Newer Edge/Win10 releases - 'IE.HTTP': {name: 'Internet Explorer', id: 'com.microsoft.ie'}, - FirefoxURL: {name: 'Firefox', id: 'org.mozilla.firefox'}, - ChromeHTML: {name: 'Chrome', id: 'com.google.chrome'}, - BraveHTML: {name: 'Brave', id: 'com.brave.Browser'}, - BraveBHTML: {name: 'Brave Beta', id: 'com.brave.Browser.beta'}, - BraveSSHTM: {name: 'Brave Nightly', id: 'com.brave.Browser.nightly'}, -}; - -export class UnknownBrowserError extends Error {} - -export default async function defaultBrowser(_execFileAsync = execFileAsync) { - const {stdout} = await _execFileAsync('reg', [ - 'QUERY', - ' HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice', - '/v', - 'ProgId', - ]); - - const match = /ProgId\s*REG_SZ\s*(?\S+)/.exec(stdout); - if (!match) { - throw new UnknownBrowserError(`Cannot find Windows browser in stdout: ${JSON.stringify(stdout)}`); - } - - const {id} = match.groups; - - const browser = windowsBrowserProgIds[id]; - if (!browser) { - throw new UnknownBrowserError(`Unknown browser ID: ${id}`); - } - - return browser; -} diff --git a/claude-code-source/node_modules/define-lazy-prop/index.js b/claude-code-source/node_modules/define-lazy-prop/index.js deleted file mode 100644 index 77c59f06..00000000 --- a/claude-code-source/node_modules/define-lazy-prop/index.js +++ /dev/null @@ -1,18 +0,0 @@ -export default function defineLazyProperty(object, propertyName, valueGetter) { - const define = value => Object.defineProperty(object, propertyName, {value, enumerable: true, writable: true}); - - Object.defineProperty(object, propertyName, { - configurable: true, - enumerable: true, - get() { - const result = valueGetter(); - define(result); - return result; - }, - set(value) { - define(value); - } - }); - - return object; -} diff --git a/claude-code-source/node_modules/delayed-stream/lib/delayed_stream.js b/claude-code-source/node_modules/delayed-stream/lib/delayed_stream.js deleted file mode 100644 index b38fc85f..00000000 --- a/claude-code-source/node_modules/delayed-stream/lib/delayed_stream.js +++ /dev/null @@ -1,107 +0,0 @@ -var Stream = require('stream').Stream; -var util = require('util'); - -module.exports = DelayedStream; -function DelayedStream() { - this.source = null; - this.dataSize = 0; - this.maxDataSize = 1024 * 1024; - this.pauseStream = true; - - this._maxDataSizeExceeded = false; - this._released = false; - this._bufferedEvents = []; -} -util.inherits(DelayedStream, Stream); - -DelayedStream.create = function(source, options) { - var delayedStream = new this(); - - options = options || {}; - for (var option in options) { - delayedStream[option] = options[option]; - } - - delayedStream.source = source; - - var realEmit = source.emit; - source.emit = function() { - delayedStream._handleEmit(arguments); - return realEmit.apply(source, arguments); - }; - - source.on('error', function() {}); - if (delayedStream.pauseStream) { - source.pause(); - } - - return delayedStream; -}; - -Object.defineProperty(DelayedStream.prototype, 'readable', { - configurable: true, - enumerable: true, - get: function() { - return this.source.readable; - } -}); - -DelayedStream.prototype.setEncoding = function() { - return this.source.setEncoding.apply(this.source, arguments); -}; - -DelayedStream.prototype.resume = function() { - if (!this._released) { - this.release(); - } - - this.source.resume(); -}; - -DelayedStream.prototype.pause = function() { - this.source.pause(); -}; - -DelayedStream.prototype.release = function() { - this._released = true; - - this._bufferedEvents.forEach(function(args) { - this.emit.apply(this, args); - }.bind(this)); - this._bufferedEvents = []; -}; - -DelayedStream.prototype.pipe = function() { - var r = Stream.prototype.pipe.apply(this, arguments); - this.resume(); - return r; -}; - -DelayedStream.prototype._handleEmit = function(args) { - if (this._released) { - this.emit.apply(this, args); - return; - } - - if (args[0] === 'data') { - this.dataSize += args[1].length; - this._checkIfMaxDataSizeExceeded(); - } - - this._bufferedEvents.push(args); -}; - -DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { - if (this._maxDataSizeExceeded) { - return; - } - - if (this.dataSize <= this.maxDataSize) { - return; - } - - this._maxDataSizeExceeded = true; - var message = - 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' - this.emit('error', new Error(message)); -}; diff --git a/claude-code-source/node_modules/detect-libc/lib/detect-libc.js b/claude-code-source/node_modules/detect-libc/lib/detect-libc.js deleted file mode 100644 index 01299b4d..00000000 --- a/claude-code-source/node_modules/detect-libc/lib/detect-libc.js +++ /dev/null @@ -1,313 +0,0 @@ -// Copyright 2017 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -'use strict'; - -const childProcess = require('child_process'); -const { isLinux, getReport } = require('./process'); -const { LDD_PATH, SELF_PATH, readFile, readFileSync } = require('./filesystem'); -const { interpreterPath } = require('./elf'); - -let cachedFamilyInterpreter; -let cachedFamilyFilesystem; -let cachedVersionFilesystem; - -const command = 'getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true'; -let commandOut = ''; - -const safeCommand = () => { - if (!commandOut) { - return new Promise((resolve) => { - childProcess.exec(command, (err, out) => { - commandOut = err ? ' ' : out; - resolve(commandOut); - }); - }); - } - return commandOut; -}; - -const safeCommandSync = () => { - if (!commandOut) { - try { - commandOut = childProcess.execSync(command, { encoding: 'utf8' }); - } catch (_err) { - commandOut = ' '; - } - } - return commandOut; -}; - -/** - * A String constant containing the value `glibc`. - * @type {string} - * @public - */ -const GLIBC = 'glibc'; - -/** - * A Regexp constant to get the GLIBC Version. - * @type {string} - */ -const RE_GLIBC_VERSION = /LIBC[a-z0-9 \-).]*?(\d+\.\d+)/i; - -/** - * A String constant containing the value `musl`. - * @type {string} - * @public - */ -const MUSL = 'musl'; - -const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-'); - -const familyFromReport = () => { - const report = getReport(); - if (report.header && report.header.glibcVersionRuntime) { - return GLIBC; - } - if (Array.isArray(report.sharedObjects)) { - if (report.sharedObjects.some(isFileMusl)) { - return MUSL; - } - } - return null; -}; - -const familyFromCommand = (out) => { - const [getconf, ldd1] = out.split(/[\r\n]+/); - if (getconf && getconf.includes(GLIBC)) { - return GLIBC; - } - if (ldd1 && ldd1.includes(MUSL)) { - return MUSL; - } - return null; -}; - -const familyFromInterpreterPath = (path) => { - if (path) { - if (path.includes('/ld-musl-')) { - return MUSL; - } else if (path.includes('/ld-linux-')) { - return GLIBC; - } - } - return null; -}; - -const getFamilyFromLddContent = (content) => { - content = content.toString(); - if (content.includes('musl')) { - return MUSL; - } - if (content.includes('GNU C Library')) { - return GLIBC; - } - return null; -}; - -const familyFromFilesystem = async () => { - if (cachedFamilyFilesystem !== undefined) { - return cachedFamilyFilesystem; - } - cachedFamilyFilesystem = null; - try { - const lddContent = await readFile(LDD_PATH); - cachedFamilyFilesystem = getFamilyFromLddContent(lddContent); - } catch (e) {} - return cachedFamilyFilesystem; -}; - -const familyFromFilesystemSync = () => { - if (cachedFamilyFilesystem !== undefined) { - return cachedFamilyFilesystem; - } - cachedFamilyFilesystem = null; - try { - const lddContent = readFileSync(LDD_PATH); - cachedFamilyFilesystem = getFamilyFromLddContent(lddContent); - } catch (e) {} - return cachedFamilyFilesystem; -}; - -const familyFromInterpreter = async () => { - if (cachedFamilyInterpreter !== undefined) { - return cachedFamilyInterpreter; - } - cachedFamilyInterpreter = null; - try { - const selfContent = await readFile(SELF_PATH); - const path = interpreterPath(selfContent); - cachedFamilyInterpreter = familyFromInterpreterPath(path); - } catch (e) {} - return cachedFamilyInterpreter; -}; - -const familyFromInterpreterSync = () => { - if (cachedFamilyInterpreter !== undefined) { - return cachedFamilyInterpreter; - } - cachedFamilyInterpreter = null; - try { - const selfContent = readFileSync(SELF_PATH); - const path = interpreterPath(selfContent); - cachedFamilyInterpreter = familyFromInterpreterPath(path); - } catch (e) {} - return cachedFamilyInterpreter; -}; - -/** - * Resolves with the libc family when it can be determined, `null` otherwise. - * @returns {Promise} - */ -const family = async () => { - let family = null; - if (isLinux()) { - family = await familyFromInterpreter(); - if (!family) { - family = await familyFromFilesystem(); - if (!family) { - family = familyFromReport(); - } - if (!family) { - const out = await safeCommand(); - family = familyFromCommand(out); - } - } - } - return family; -}; - -/** - * Returns the libc family when it can be determined, `null` otherwise. - * @returns {?string} - */ -const familySync = () => { - let family = null; - if (isLinux()) { - family = familyFromInterpreterSync(); - if (!family) { - family = familyFromFilesystemSync(); - if (!family) { - family = familyFromReport(); - } - if (!family) { - const out = safeCommandSync(); - family = familyFromCommand(out); - } - } - } - return family; -}; - -/** - * Resolves `true` only when the platform is Linux and the libc family is not `glibc`. - * @returns {Promise} - */ -const isNonGlibcLinux = async () => isLinux() && await family() !== GLIBC; - -/** - * Returns `true` only when the platform is Linux and the libc family is not `glibc`. - * @returns {boolean} - */ -const isNonGlibcLinuxSync = () => isLinux() && familySync() !== GLIBC; - -const versionFromFilesystem = async () => { - if (cachedVersionFilesystem !== undefined) { - return cachedVersionFilesystem; - } - cachedVersionFilesystem = null; - try { - const lddContent = await readFile(LDD_PATH); - const versionMatch = lddContent.match(RE_GLIBC_VERSION); - if (versionMatch) { - cachedVersionFilesystem = versionMatch[1]; - } - } catch (e) {} - return cachedVersionFilesystem; -}; - -const versionFromFilesystemSync = () => { - if (cachedVersionFilesystem !== undefined) { - return cachedVersionFilesystem; - } - cachedVersionFilesystem = null; - try { - const lddContent = readFileSync(LDD_PATH); - const versionMatch = lddContent.match(RE_GLIBC_VERSION); - if (versionMatch) { - cachedVersionFilesystem = versionMatch[1]; - } - } catch (e) {} - return cachedVersionFilesystem; -}; - -const versionFromReport = () => { - const report = getReport(); - if (report.header && report.header.glibcVersionRuntime) { - return report.header.glibcVersionRuntime; - } - return null; -}; - -const versionSuffix = (s) => s.trim().split(/\s+/)[1]; - -const versionFromCommand = (out) => { - const [getconf, ldd1, ldd2] = out.split(/[\r\n]+/); - if (getconf && getconf.includes(GLIBC)) { - return versionSuffix(getconf); - } - if (ldd1 && ldd2 && ldd1.includes(MUSL)) { - return versionSuffix(ldd2); - } - return null; -}; - -/** - * Resolves with the libc version when it can be determined, `null` otherwise. - * @returns {Promise} - */ -const version = async () => { - let version = null; - if (isLinux()) { - version = await versionFromFilesystem(); - if (!version) { - version = versionFromReport(); - } - if (!version) { - const out = await safeCommand(); - version = versionFromCommand(out); - } - } - return version; -}; - -/** - * Returns the libc version when it can be determined, `null` otherwise. - * @returns {?string} - */ -const versionSync = () => { - let version = null; - if (isLinux()) { - version = versionFromFilesystemSync(); - if (!version) { - version = versionFromReport(); - } - if (!version) { - const out = safeCommandSync(); - version = versionFromCommand(out); - } - } - return version; -}; - -module.exports = { - GLIBC, - MUSL, - family, - familySync, - isNonGlibcLinux, - isNonGlibcLinuxSync, - version, - versionSync -}; diff --git a/claude-code-source/node_modules/detect-libc/lib/elf.js b/claude-code-source/node_modules/detect-libc/lib/elf.js deleted file mode 100644 index aa166aa2..00000000 --- a/claude-code-source/node_modules/detect-libc/lib/elf.js +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2017 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -'use strict'; - -const interpreterPath = (elf) => { - if (elf.length < 64) { - return null; - } - if (elf.readUInt32BE(0) !== 0x7F454C46) { - // Unexpected magic bytes - return null; - } - if (elf.readUInt8(4) !== 2) { - // Not a 64-bit ELF - return null; - } - if (elf.readUInt8(5) !== 1) { - // Not little-endian - return null; - } - const offset = elf.readUInt32LE(32); - const size = elf.readUInt16LE(54); - const count = elf.readUInt16LE(56); - for (let i = 0; i < count; i++) { - const headerOffset = offset + (i * size); - const type = elf.readUInt32LE(headerOffset); - if (type === 3) { - const fileOffset = elf.readUInt32LE(headerOffset + 8); - const fileSize = elf.readUInt32LE(headerOffset + 32); - return elf.subarray(fileOffset, fileOffset + fileSize).toString().replace(/\0.*$/g, ''); - } - } - return null; -}; - -module.exports = { - interpreterPath -}; diff --git a/claude-code-source/node_modules/detect-libc/lib/filesystem.js b/claude-code-source/node_modules/detect-libc/lib/filesystem.js deleted file mode 100644 index 4c2443cc..00000000 --- a/claude-code-source/node_modules/detect-libc/lib/filesystem.js +++ /dev/null @@ -1,51 +0,0 @@ -// Copyright 2017 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -'use strict'; - -const fs = require('fs'); - -const LDD_PATH = '/usr/bin/ldd'; -const SELF_PATH = '/proc/self/exe'; -const MAX_LENGTH = 2048; - -/** - * Read the content of a file synchronous - * - * @param {string} path - * @returns {Buffer} - */ -const readFileSync = (path) => { - const fd = fs.openSync(path, 'r'); - const buffer = Buffer.alloc(MAX_LENGTH); - const bytesRead = fs.readSync(fd, buffer, 0, MAX_LENGTH, 0); - fs.close(fd, () => {}); - return buffer.subarray(0, bytesRead); -}; - -/** - * Read the content of a file - * - * @param {string} path - * @returns {Promise} - */ -const readFile = (path) => new Promise((resolve, reject) => { - fs.open(path, 'r', (err, fd) => { - if (err) { - reject(err); - } else { - const buffer = Buffer.alloc(MAX_LENGTH); - fs.read(fd, buffer, 0, MAX_LENGTH, 0, (_, bytesRead) => { - resolve(buffer.subarray(0, bytesRead)); - fs.close(fd, () => {}); - }); - } - }); -}); - -module.exports = { - LDD_PATH, - SELF_PATH, - readFileSync, - readFile -}; diff --git a/claude-code-source/node_modules/detect-libc/lib/process.js b/claude-code-source/node_modules/detect-libc/lib/process.js deleted file mode 100644 index ee78ad26..00000000 --- a/claude-code-source/node_modules/detect-libc/lib/process.js +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2017 Lovell Fuller and others. -// SPDX-License-Identifier: Apache-2.0 - -'use strict'; - -const isLinux = () => process.platform === 'linux'; - -let report = null; -const getReport = () => { - if (!report) { - /* istanbul ignore next */ - if (isLinux() && process.report) { - const orig = process.report.excludeNetwork; - process.report.excludeNetwork = true; - report = process.report.getReport(); - process.report.excludeNetwork = orig; - } else { - report = {}; - } - } - return report; -}; - -module.exports = { isLinux, getReport }; diff --git a/claude-code-source/node_modules/diff/libesm/diff/array.js b/claude-code-source/node_modules/diff/libesm/diff/array.js deleted file mode 100644 index d92aeb48..00000000 --- a/claude-code-source/node_modules/diff/libesm/diff/array.js +++ /dev/null @@ -1,16 +0,0 @@ -import Diff from './base.js'; -class ArrayDiff extends Diff { - tokenize(value) { - return value.slice(); - } - join(value) { - return value; - } - removeEmpty(value) { - return value; - } -} -export const arrayDiff = new ArrayDiff(); -export function diffArrays(oldArr, newArr, options) { - return arrayDiff.diff(oldArr, newArr, options); -} diff --git a/claude-code-source/node_modules/diff/libesm/diff/base.js b/claude-code-source/node_modules/diff/libesm/diff/base.js deleted file mode 100644 index db02845d..00000000 --- a/claude-code-source/node_modules/diff/libesm/diff/base.js +++ /dev/null @@ -1,253 +0,0 @@ -export default class Diff { - diff(oldStr, newStr, - // Type below is not accurate/complete - see above for full possibilities - but it compiles - options = {}) { - let callback; - if (typeof options === 'function') { - callback = options; - options = {}; - } - else if ('callback' in options) { - callback = options.callback; - } - // Allow subclasses to massage the input prior to running - const oldString = this.castInput(oldStr, options); - const newString = this.castInput(newStr, options); - const oldTokens = this.removeEmpty(this.tokenize(oldString, options)); - const newTokens = this.removeEmpty(this.tokenize(newString, options)); - return this.diffWithOptionsObj(oldTokens, newTokens, options, callback); - } - diffWithOptionsObj(oldTokens, newTokens, options, callback) { - var _a; - const done = (value) => { - value = this.postProcess(value, options); - if (callback) { - setTimeout(function () { callback(value); }, 0); - return undefined; - } - else { - return value; - } - }; - const newLen = newTokens.length, oldLen = oldTokens.length; - let editLength = 1; - let maxEditLength = newLen + oldLen; - if (options.maxEditLength != null) { - maxEditLength = Math.min(maxEditLength, options.maxEditLength); - } - const maxExecutionTime = (_a = options.timeout) !== null && _a !== void 0 ? _a : Infinity; - const abortAfterTimestamp = Date.now() + maxExecutionTime; - const bestPath = [{ oldPos: -1, lastComponent: undefined }]; - // Seed editLength = 0, i.e. the content starts with the same values - let newPos = this.extractCommon(bestPath[0], newTokens, oldTokens, 0, options); - if (bestPath[0].oldPos + 1 >= oldLen && newPos + 1 >= newLen) { - // Identity per the equality and tokenizer - return done(this.buildValues(bestPath[0].lastComponent, newTokens, oldTokens)); - } - // Once we hit the right edge of the edit graph on some diagonal k, we can - // definitely reach the end of the edit graph in no more than k edits, so - // there's no point in considering any moves to diagonal k+1 any more (from - // which we're guaranteed to need at least k+1 more edits). - // Similarly, once we've reached the bottom of the edit graph, there's no - // point considering moves to lower diagonals. - // We record this fact by setting minDiagonalToConsider and - // maxDiagonalToConsider to some finite value once we've hit the edge of - // the edit graph. - // This optimization is not faithful to the original algorithm presented in - // Myers's paper, which instead pointlessly extends D-paths off the end of - // the edit graph - see page 7 of Myers's paper which notes this point - // explicitly and illustrates it with a diagram. This has major performance - // implications for some common scenarios. For instance, to compute a diff - // where the new text simply appends d characters on the end of the - // original text of length n, the true Myers algorithm will take O(n+d^2) - // time while this optimization needs only O(n+d) time. - let minDiagonalToConsider = -Infinity, maxDiagonalToConsider = Infinity; - // Main worker method. checks all permutations of a given edit length for acceptance. - const execEditLength = () => { - for (let diagonalPath = Math.max(minDiagonalToConsider, -editLength); diagonalPath <= Math.min(maxDiagonalToConsider, editLength); diagonalPath += 2) { - let basePath; - const removePath = bestPath[diagonalPath - 1], addPath = bestPath[diagonalPath + 1]; - if (removePath) { - // No one else is going to attempt to use this value, clear it - // @ts-expect-error - perf optimisation. This type-violating value will never be read. - bestPath[diagonalPath - 1] = undefined; - } - let canAdd = false; - if (addPath) { - // what newPos will be after we do an insertion: - const addPathNewPos = addPath.oldPos - diagonalPath; - canAdd = addPath && 0 <= addPathNewPos && addPathNewPos < newLen; - } - const canRemove = removePath && removePath.oldPos + 1 < oldLen; - if (!canAdd && !canRemove) { - // If this path is a terminal then prune - // @ts-expect-error - perf optimisation. This type-violating value will never be read. - bestPath[diagonalPath] = undefined; - continue; - } - // Select the diagonal that we want to branch from. We select the prior - // path whose position in the old string is the farthest from the origin - // and does not pass the bounds of the diff graph - if (!canRemove || (canAdd && removePath.oldPos < addPath.oldPos)) { - basePath = this.addToPath(addPath, true, false, 0, options); - } - else { - basePath = this.addToPath(removePath, false, true, 1, options); - } - newPos = this.extractCommon(basePath, newTokens, oldTokens, diagonalPath, options); - if (basePath.oldPos + 1 >= oldLen && newPos + 1 >= newLen) { - // If we have hit the end of both strings, then we are done - return done(this.buildValues(basePath.lastComponent, newTokens, oldTokens)) || true; - } - else { - bestPath[diagonalPath] = basePath; - if (basePath.oldPos + 1 >= oldLen) { - maxDiagonalToConsider = Math.min(maxDiagonalToConsider, diagonalPath - 1); - } - if (newPos + 1 >= newLen) { - minDiagonalToConsider = Math.max(minDiagonalToConsider, diagonalPath + 1); - } - } - } - editLength++; - }; - // Performs the length of edit iteration. Is a bit fugly as this has to support the - // sync and async mode which is never fun. Loops over execEditLength until a value - // is produced, or until the edit length exceeds options.maxEditLength (if given), - // in which case it will return undefined. - if (callback) { - (function exec() { - setTimeout(function () { - if (editLength > maxEditLength || Date.now() > abortAfterTimestamp) { - return callback(undefined); - } - if (!execEditLength()) { - exec(); - } - }, 0); - }()); - } - else { - while (editLength <= maxEditLength && Date.now() <= abortAfterTimestamp) { - const ret = execEditLength(); - if (ret) { - return ret; - } - } - } - } - addToPath(path, added, removed, oldPosInc, options) { - const last = path.lastComponent; - if (last && !options.oneChangePerToken && last.added === added && last.removed === removed) { - return { - oldPos: path.oldPos + oldPosInc, - lastComponent: { count: last.count + 1, added: added, removed: removed, previousComponent: last.previousComponent } - }; - } - else { - return { - oldPos: path.oldPos + oldPosInc, - lastComponent: { count: 1, added: added, removed: removed, previousComponent: last } - }; - } - } - extractCommon(basePath, newTokens, oldTokens, diagonalPath, options) { - const newLen = newTokens.length, oldLen = oldTokens.length; - let oldPos = basePath.oldPos, newPos = oldPos - diagonalPath, commonCount = 0; - while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(oldTokens[oldPos + 1], newTokens[newPos + 1], options)) { - newPos++; - oldPos++; - commonCount++; - if (options.oneChangePerToken) { - basePath.lastComponent = { count: 1, previousComponent: basePath.lastComponent, added: false, removed: false }; - } - } - if (commonCount && !options.oneChangePerToken) { - basePath.lastComponent = { count: commonCount, previousComponent: basePath.lastComponent, added: false, removed: false }; - } - basePath.oldPos = oldPos; - return newPos; - } - equals(left, right, options) { - if (options.comparator) { - return options.comparator(left, right); - } - else { - return left === right - || (!!options.ignoreCase && left.toLowerCase() === right.toLowerCase()); - } - } - removeEmpty(array) { - const ret = []; - for (let i = 0; i < array.length; i++) { - if (array[i]) { - ret.push(array[i]); - } - } - return ret; - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - castInput(value, options) { - return value; - } - // eslint-disable-next-line @typescript-eslint/no-unused-vars - tokenize(value, options) { - return Array.from(value); - } - join(chars) { - // Assumes ValueT is string, which is the case for most subclasses. - // When it's false, e.g. in diffArrays, this method needs to be overridden (e.g. with a no-op) - // Yes, the casts are verbose and ugly, because this pattern - of having the base class SORT OF - // assume tokens and values are strings, but not completely - is weird and janky. - return chars.join(''); - } - postProcess(changeObjects, - // eslint-disable-next-line @typescript-eslint/no-unused-vars - options) { - return changeObjects; - } - get useLongestToken() { - return false; - } - buildValues(lastComponent, newTokens, oldTokens) { - // First we convert our linked list of components in reverse order to an - // array in the right order: - const components = []; - let nextComponent; - while (lastComponent) { - components.push(lastComponent); - nextComponent = lastComponent.previousComponent; - delete lastComponent.previousComponent; - lastComponent = nextComponent; - } - components.reverse(); - const componentLen = components.length; - let componentPos = 0, newPos = 0, oldPos = 0; - for (; componentPos < componentLen; componentPos++) { - const component = components[componentPos]; - if (!component.removed) { - if (!component.added && this.useLongestToken) { - let value = newTokens.slice(newPos, newPos + component.count); - value = value.map(function (value, i) { - const oldValue = oldTokens[oldPos + i]; - return oldValue.length > value.length ? oldValue : value; - }); - component.value = this.join(value); - } - else { - component.value = this.join(newTokens.slice(newPos, newPos + component.count)); - } - newPos += component.count; - // Common case - if (!component.added) { - oldPos += component.count; - } - } - else { - component.value = this.join(oldTokens.slice(oldPos, oldPos + component.count)); - oldPos += component.count; - } - } - return components; - } -} diff --git a/claude-code-source/node_modules/diff/libesm/diff/line.js b/claude-code-source/node_modules/diff/libesm/diff/line.js deleted file mode 100644 index 0675d4fb..00000000 --- a/claude-code-source/node_modules/diff/libesm/diff/line.js +++ /dev/null @@ -1,65 +0,0 @@ -import Diff from './base.js'; -import { generateOptions } from '../util/params.js'; -class LineDiff extends Diff { - constructor() { - super(...arguments); - this.tokenize = tokenize; - } - equals(left, right, options) { - // If we're ignoring whitespace, we need to normalise lines by stripping - // whitespace before checking equality. (This has an annoying interaction - // with newlineIsToken that requires special handling: if newlines get their - // own token, then we DON'T want to trim the *newline* tokens down to empty - // strings, since this would cause us to treat whitespace-only line content - // as equal to a separator between lines, which would be weird and - // inconsistent with the documented behavior of the options.) - if (options.ignoreWhitespace) { - if (!options.newlineIsToken || !left.includes('\n')) { - left = left.trim(); - } - if (!options.newlineIsToken || !right.includes('\n')) { - right = right.trim(); - } - } - else if (options.ignoreNewlineAtEof && !options.newlineIsToken) { - if (left.endsWith('\n')) { - left = left.slice(0, -1); - } - if (right.endsWith('\n')) { - right = right.slice(0, -1); - } - } - return super.equals(left, right, options); - } -} -export const lineDiff = new LineDiff(); -export function diffLines(oldStr, newStr, options) { - return lineDiff.diff(oldStr, newStr, options); -} -export function diffTrimmedLines(oldStr, newStr, options) { - options = generateOptions(options, { ignoreWhitespace: true }); - return lineDiff.diff(oldStr, newStr, options); -} -// Exported standalone so it can be used from jsonDiff too. -export function tokenize(value, options) { - if (options.stripTrailingCr) { - // remove one \r before \n to match GNU diff's --strip-trailing-cr behavior - value = value.replace(/\r\n/g, '\n'); - } - const retLines = [], linesAndNewlines = value.split(/(\n|\r\n)/); - // Ignore the final empty token that occurs if the string ends with a new line - if (!linesAndNewlines[linesAndNewlines.length - 1]) { - linesAndNewlines.pop(); - } - // Merge the content and line separators into single tokens - for (let i = 0; i < linesAndNewlines.length; i++) { - const line = linesAndNewlines[i]; - if (i % 2 && !options.newlineIsToken) { - retLines[retLines.length - 1] += line; - } - else { - retLines.push(line); - } - } - return retLines; -} diff --git a/claude-code-source/node_modules/diff/libesm/diff/word.js b/claude-code-source/node_modules/diff/libesm/diff/word.js deleted file mode 100644 index e828f825..00000000 --- a/claude-code-source/node_modules/diff/libesm/diff/word.js +++ /dev/null @@ -1,296 +0,0 @@ -import Diff from './base.js'; -import { longestCommonPrefix, longestCommonSuffix, replacePrefix, replaceSuffix, removePrefix, removeSuffix, maximumOverlap, leadingWs, trailingWs } from '../util/string.js'; -// Based on https://en.wikipedia.org/wiki/Latin_script_in_Unicode -// -// Chars/ranges counted as "word" characters by this regex are as follows: -// -// + U+00AD Soft hyphen -// + 00C0–00FF (letters with diacritics from the Latin-1 Supplement), except: -// - U+00D7 × Multiplication sign -// - U+00F7 ÷ Division sign -// + Latin Extended-A, 0100–017F -// + Latin Extended-B, 0180–024F -// + IPA Extensions, 0250–02AF -// + Spacing Modifier Letters, 02B0–02FF, except: -// - U+02C7 ˇ ˇ Caron -// - U+02D8 ˘ ˘ Breve -// - U+02D9 ˙ ˙ Dot Above -// - U+02DA ˚ ˚ Ring Above -// - U+02DB ˛ ˛ Ogonek -// - U+02DC ˜ ˜ Small Tilde -// - U+02DD ˝ ˝ Double Acute Accent -// + Latin Extended Additional, 1E00–1EFF -const extendedWordChars = 'a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}'; -// Each token is one of the following: -// - A punctuation mark plus the surrounding whitespace -// - A word plus the surrounding whitespace -// - Pure whitespace (but only in the special case where the entire text -// is just whitespace) -// -// We have to include surrounding whitespace in the tokens because the two -// alternative approaches produce horribly broken results: -// * If we just discard the whitespace, we can't fully reproduce the original -// text from the sequence of tokens and any attempt to render the diff will -// get the whitespace wrong. -// * If we have separate tokens for whitespace, then in a typical text every -// second token will be a single space character. But this often results in -// the optimal diff between two texts being a perverse one that preserves -// the spaces between words but deletes and reinserts actual common words. -// See https://github.com/kpdecker/jsdiff/issues/160#issuecomment-1866099640 -// for an example. -// -// Keeping the surrounding whitespace of course has implications for .equals -// and .join, not just .tokenize. -// This regex does NOT fully implement the tokenization rules described above. -// Instead, it gives runs of whitespace their own "token". The tokenize method -// then handles stitching whitespace tokens onto adjacent word or punctuation -// tokens. -const tokenizeIncludingWhitespace = new RegExp(`[${extendedWordChars}]+|\\s+|[^${extendedWordChars}]`, 'ug'); -class WordDiff extends Diff { - equals(left, right, options) { - if (options.ignoreCase) { - left = left.toLowerCase(); - right = right.toLowerCase(); - } - return left.trim() === right.trim(); - } - tokenize(value, options = {}) { - let parts; - if (options.intlSegmenter) { - const segmenter = options.intlSegmenter; - if (segmenter.resolvedOptions().granularity != 'word') { - throw new Error('The segmenter passed must have a granularity of "word"'); - } - // We want `parts` to be an array whose elements alternate between being - // pure whitespace and being pure non-whitespace. This is ALMOST what the - // segments returned by a word-based Intl.Segmenter already look like, - // and therefore we can ALMOST get what we want by simply doing... - // parts = Array.from(segmenter.segment(value), segment => segment.segment); - // ... but not QUITE, because there's of one annoying special case: every - // newline character gets its own segment, instead of sharing a segment - // with other surrounding whitespace. We therefore need to manually merge - // consecutive segments of whitespace into a single part: - parts = []; - for (const segmentObj of Array.from(segmenter.segment(value))) { - const segment = segmentObj.segment; - if (parts.length && (/\s/).test(parts[parts.length - 1]) && (/\s/).test(segment)) { - parts[parts.length - 1] += segment; - } - else { - parts.push(segment); - } - } - } - else { - parts = value.match(tokenizeIncludingWhitespace) || []; - } - const tokens = []; - let prevPart = null; - parts.forEach(part => { - if ((/\s/).test(part)) { - if (prevPart == null) { - tokens.push(part); - } - else { - tokens.push(tokens.pop() + part); - } - } - else if (prevPart != null && (/\s/).test(prevPart)) { - if (tokens[tokens.length - 1] == prevPart) { - tokens.push(tokens.pop() + part); - } - else { - tokens.push(prevPart + part); - } - } - else { - tokens.push(part); - } - prevPart = part; - }); - return tokens; - } - join(tokens) { - // Tokens being joined here will always have appeared consecutively in the - // same text, so we can simply strip off the leading whitespace from all the - // tokens except the first (and except any whitespace-only tokens - but such - // a token will always be the first and only token anyway) and then join them - // and the whitespace around words and punctuation will end up correct. - return tokens.map((token, i) => { - if (i == 0) { - return token; - } - else { - return token.replace((/^\s+/), ''); - } - }).join(''); - } - postProcess(changes, options) { - if (!changes || options.oneChangePerToken) { - return changes; - } - let lastKeep = null; - // Change objects representing any insertion or deletion since the last - // "keep" change object. There can be at most one of each. - let insertion = null; - let deletion = null; - changes.forEach(change => { - if (change.added) { - insertion = change; - } - else if (change.removed) { - deletion = change; - } - else { - if (insertion || deletion) { // May be false at start of text - dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, change); - } - lastKeep = change; - insertion = null; - deletion = null; - } - }); - if (insertion || deletion) { - dedupeWhitespaceInChangeObjects(lastKeep, deletion, insertion, null); - } - return changes; - } -} -export const wordDiff = new WordDiff(); -export function diffWords(oldStr, newStr, options) { - // This option has never been documented and never will be (it's clearer to - // just call `diffWordsWithSpace` directly if you need that behavior), but - // has existed in jsdiff for a long time, so we retain support for it here - // for the sake of backwards compatibility. - if ((options === null || options === void 0 ? void 0 : options.ignoreWhitespace) != null && !options.ignoreWhitespace) { - return diffWordsWithSpace(oldStr, newStr, options); - } - return wordDiff.diff(oldStr, newStr, options); -} -function dedupeWhitespaceInChangeObjects(startKeep, deletion, insertion, endKeep) { - // Before returning, we tidy up the leading and trailing whitespace of the - // change objects to eliminate cases where trailing whitespace in one object - // is repeated as leading whitespace in the next. - // Below are examples of the outcomes we want here to explain the code. - // I=insert, K=keep, D=delete - // 1. diffing 'foo bar baz' vs 'foo baz' - // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz' - // After cleanup, we want: K:'foo ' D:'bar ' K:'baz' - // - // 2. Diffing 'foo bar baz' vs 'foo qux baz' - // Prior to cleanup, we have K:'foo ' D:' bar ' I:' qux ' K:' baz' - // After cleanup, we want K:'foo ' D:'bar' I:'qux' K:' baz' - // - // 3. Diffing 'foo\nbar baz' vs 'foo baz' - // Prior to cleanup, we have K:'foo ' D:'\nbar ' K:' baz' - // After cleanup, we want K'foo' D:'\nbar' K:' baz' - // - // 4. Diffing 'foo baz' vs 'foo\nbar baz' - // Prior to cleanup, we have K:'foo\n' I:'\nbar ' K:' baz' - // After cleanup, we ideally want K'foo' I:'\nbar' K:' baz' - // but don't actually manage this currently (the pre-cleanup change - // objects don't contain enough information to make it possible). - // - // 5. Diffing 'foo bar baz' vs 'foo baz' - // Prior to cleanup, we have K:'foo ' D:' bar ' K:' baz' - // After cleanup, we want K:'foo ' D:' bar ' K:'baz' - // - // Our handling is unavoidably imperfect in the case where there's a single - // indel between keeps and the whitespace has changed. For instance, consider - // diffing 'foo\tbar\nbaz' vs 'foo baz'. Unless we create an extra change - // object to represent the insertion of the space character (which isn't even - // a token), we have no way to avoid losing information about the texts' - // original whitespace in the result we return. Still, we do our best to - // output something that will look sensible if we e.g. print it with - // insertions in green and deletions in red. - // Between two "keep" change objects (or before the first or after the last - // change object), we can have either: - // * A "delete" followed by an "insert" - // * Just an "insert" - // * Just a "delete" - // We handle the three cases separately. - if (deletion && insertion) { - const oldWsPrefix = leadingWs(deletion.value); - const oldWsSuffix = trailingWs(deletion.value); - const newWsPrefix = leadingWs(insertion.value); - const newWsSuffix = trailingWs(insertion.value); - if (startKeep) { - const commonWsPrefix = longestCommonPrefix(oldWsPrefix, newWsPrefix); - startKeep.value = replaceSuffix(startKeep.value, newWsPrefix, commonWsPrefix); - deletion.value = removePrefix(deletion.value, commonWsPrefix); - insertion.value = removePrefix(insertion.value, commonWsPrefix); - } - if (endKeep) { - const commonWsSuffix = longestCommonSuffix(oldWsSuffix, newWsSuffix); - endKeep.value = replacePrefix(endKeep.value, newWsSuffix, commonWsSuffix); - deletion.value = removeSuffix(deletion.value, commonWsSuffix); - insertion.value = removeSuffix(insertion.value, commonWsSuffix); - } - } - else if (insertion) { - // The whitespaces all reflect what was in the new text rather than - // the old, so we essentially have no information about whitespace - // insertion or deletion. We just want to dedupe the whitespace. - // We do that by having each change object keep its trailing - // whitespace and deleting duplicate leading whitespace where - // present. - if (startKeep) { - const ws = leadingWs(insertion.value); - insertion.value = insertion.value.substring(ws.length); - } - if (endKeep) { - const ws = leadingWs(endKeep.value); - endKeep.value = endKeep.value.substring(ws.length); - } - // otherwise we've got a deletion and no insertion - } - else if (startKeep && endKeep) { - const newWsFull = leadingWs(endKeep.value), delWsStart = leadingWs(deletion.value), delWsEnd = trailingWs(deletion.value); - // Any whitespace that comes straight after startKeep in both the old and - // new texts, assign to startKeep and remove from the deletion. - const newWsStart = longestCommonPrefix(newWsFull, delWsStart); - deletion.value = removePrefix(deletion.value, newWsStart); - // Any whitespace that comes straight before endKeep in both the old and - // new texts, and hasn't already been assigned to startKeep, assign to - // endKeep and remove from the deletion. - const newWsEnd = longestCommonSuffix(removePrefix(newWsFull, newWsStart), delWsEnd); - deletion.value = removeSuffix(deletion.value, newWsEnd); - endKeep.value = replacePrefix(endKeep.value, newWsFull, newWsEnd); - // If there's any whitespace from the new text that HASN'T already been - // assigned, assign it to the start: - startKeep.value = replaceSuffix(startKeep.value, newWsFull, newWsFull.slice(0, newWsFull.length - newWsEnd.length)); - } - else if (endKeep) { - // We are at the start of the text. Preserve all the whitespace on - // endKeep, and just remove whitespace from the end of deletion to the - // extent that it overlaps with the start of endKeep. - const endKeepWsPrefix = leadingWs(endKeep.value); - const deletionWsSuffix = trailingWs(deletion.value); - const overlap = maximumOverlap(deletionWsSuffix, endKeepWsPrefix); - deletion.value = removeSuffix(deletion.value, overlap); - } - else if (startKeep) { - // We are at the END of the text. Preserve all the whitespace on - // startKeep, and just remove whitespace from the start of deletion to - // the extent that it overlaps with the end of startKeep. - const startKeepWsSuffix = trailingWs(startKeep.value); - const deletionWsPrefix = leadingWs(deletion.value); - const overlap = maximumOverlap(startKeepWsSuffix, deletionWsPrefix); - deletion.value = removePrefix(deletion.value, overlap); - } -} -class WordsWithSpaceDiff extends Diff { - tokenize(value) { - // Slightly different to the tokenizeIncludingWhitespace regex used above in - // that this one treats each individual newline as a distinct token, rather - // than merging them into other surrounding whitespace. This was requested - // in https://github.com/kpdecker/jsdiff/issues/180 & - // https://github.com/kpdecker/jsdiff/issues/211 - const regex = new RegExp(`(\\r?\\n)|[${extendedWordChars}]+|[^\\S\\n\\r]+|[^${extendedWordChars}]`, 'ug'); - return value.match(regex) || []; - } -} -export const wordsWithSpaceDiff = new WordsWithSpaceDiff(); -export function diffWordsWithSpace(oldStr, newStr, options) { - return wordsWithSpaceDiff.diff(oldStr, newStr, options); -} diff --git a/claude-code-source/node_modules/diff/libesm/index.js b/claude-code-source/node_modules/diff/libesm/index.js deleted file mode 100644 index 18a495a1..00000000 --- a/claude-code-source/node_modules/diff/libesm/index.js +++ /dev/null @@ -1,30 +0,0 @@ -/* See LICENSE file for terms of use */ -/* - * Text diff implementation. - * - * This library supports the following APIs: - * Diff.diffChars: Character by character diff - * Diff.diffWords: Word (as defined by \b regex) diff which ignores whitespace - * Diff.diffLines: Line based diff - * - * Diff.diffCss: Diff targeted at CSS content - * - * These methods are based on the implementation proposed in - * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). - * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 - */ -import Diff from './diff/base.js'; -import { diffChars, characterDiff } from './diff/character.js'; -import { diffWords, diffWordsWithSpace, wordDiff, wordsWithSpaceDiff } from './diff/word.js'; -import { diffLines, diffTrimmedLines, lineDiff } from './diff/line.js'; -import { diffSentences, sentenceDiff } from './diff/sentence.js'; -import { diffCss, cssDiff } from './diff/css.js'; -import { diffJson, canonicalize, jsonDiff } from './diff/json.js'; -import { diffArrays, arrayDiff } from './diff/array.js'; -import { applyPatch, applyPatches } from './patch/apply.js'; -import { parsePatch } from './patch/parse.js'; -import { reversePatch } from './patch/reverse.js'; -import { structuredPatch, createTwoFilesPatch, createPatch, formatPatch, INCLUDE_HEADERS, FILE_HEADERS_ONLY, OMIT_HEADERS } from './patch/create.js'; -import { convertChangesToDMP } from './convert/dmp.js'; -import { convertChangesToXML } from './convert/xml.js'; -export { Diff, diffChars, characterDiff, diffWords, wordDiff, diffWordsWithSpace, wordsWithSpaceDiff, diffLines, lineDiff, diffTrimmedLines, diffSentences, sentenceDiff, diffCss, cssDiff, diffJson, jsonDiff, diffArrays, arrayDiff, structuredPatch, createTwoFilesPatch, createPatch, formatPatch, INCLUDE_HEADERS, FILE_HEADERS_ONLY, OMIT_HEADERS, applyPatch, applyPatches, parsePatch, reversePatch, convertChangesToDMP, convertChangesToXML, canonicalize }; diff --git a/claude-code-source/node_modules/diff/libesm/patch/create.js b/claude-code-source/node_modules/diff/libesm/patch/create.js deleted file mode 100644 index 73ba2969..00000000 --- a/claude-code-source/node_modules/diff/libesm/patch/create.js +++ /dev/null @@ -1,228 +0,0 @@ -import { diffLines } from '../diff/line.js'; -export const INCLUDE_HEADERS = { - includeIndex: true, - includeUnderline: true, - includeFileHeaders: true -}; -export const FILE_HEADERS_ONLY = { - includeIndex: false, - includeUnderline: false, - includeFileHeaders: true -}; -export const OMIT_HEADERS = { - includeIndex: false, - includeUnderline: false, - includeFileHeaders: false -}; -export function structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { - let optionsObj; - if (!options) { - optionsObj = {}; - } - else if (typeof options === 'function') { - optionsObj = { callback: options }; - } - else { - optionsObj = options; - } - if (typeof optionsObj.context === 'undefined') { - optionsObj.context = 4; - } - // We copy this into its own variable to placate TypeScript, which thinks - // optionsObj.context might be undefined in the callbacks below. - const context = optionsObj.context; - // @ts-expect-error (runtime check for something that is correctly a static type error) - if (optionsObj.newlineIsToken) { - throw new Error('newlineIsToken may not be used with patch-generation functions, only with diffing functions'); - } - if (!optionsObj.callback) { - return diffLinesResultToPatch(diffLines(oldStr, newStr, optionsObj)); - } - else { - const { callback } = optionsObj; - diffLines(oldStr, newStr, Object.assign(Object.assign({}, optionsObj), { callback: (diff) => { - const patch = diffLinesResultToPatch(diff); - // TypeScript is unhappy without the cast because it does not understand that `patch` may - // be undefined here only if `callback` is StructuredPatchCallbackAbortable: - callback(patch); - } })); - } - function diffLinesResultToPatch(diff) { - // STEP 1: Build up the patch with no "\ No newline at end of file" lines and with the arrays - // of lines containing trailing newline characters. We'll tidy up later... - if (!diff) { - return; - } - diff.push({ value: '', lines: [] }); // Append an empty value to make cleanup easier - function contextLines(lines) { - return lines.map(function (entry) { return ' ' + entry; }); - } - const hunks = []; - let oldRangeStart = 0, newRangeStart = 0, curRange = [], oldLine = 1, newLine = 1; - for (let i = 0; i < diff.length; i++) { - const current = diff[i], lines = current.lines || splitLines(current.value); - current.lines = lines; - if (current.added || current.removed) { - // If we have previous context, start with that - if (!oldRangeStart) { - const prev = diff[i - 1]; - oldRangeStart = oldLine; - newRangeStart = newLine; - if (prev) { - curRange = context > 0 ? contextLines(prev.lines.slice(-context)) : []; - oldRangeStart -= curRange.length; - newRangeStart -= curRange.length; - } - } - // Output our changes - for (const line of lines) { - curRange.push((current.added ? '+' : '-') + line); - } - // Track the updated file position - if (current.added) { - newLine += lines.length; - } - else { - oldLine += lines.length; - } - } - else { - // Identical context lines. Track line changes - if (oldRangeStart) { - // Close out any changes that have been output (or join overlapping) - if (lines.length <= context * 2 && i < diff.length - 2) { - // Overlapping - for (const line of contextLines(lines)) { - curRange.push(line); - } - } - else { - // end the range and output - const contextSize = Math.min(lines.length, context); - for (const line of contextLines(lines.slice(0, contextSize))) { - curRange.push(line); - } - const hunk = { - oldStart: oldRangeStart, - oldLines: (oldLine - oldRangeStart + contextSize), - newStart: newRangeStart, - newLines: (newLine - newRangeStart + contextSize), - lines: curRange - }; - hunks.push(hunk); - oldRangeStart = 0; - newRangeStart = 0; - curRange = []; - } - } - oldLine += lines.length; - newLine += lines.length; - } - } - // Step 2: eliminate the trailing `\n` from each line of each hunk, and, where needed, add - // "\ No newline at end of file". - for (const hunk of hunks) { - for (let i = 0; i < hunk.lines.length; i++) { - if (hunk.lines[i].endsWith('\n')) { - hunk.lines[i] = hunk.lines[i].slice(0, -1); - } - else { - hunk.lines.splice(i + 1, 0, '\\ No newline at end of file'); - i++; // Skip the line we just added, then continue iterating - } - } - } - return { - oldFileName: oldFileName, newFileName: newFileName, - oldHeader: oldHeader, newHeader: newHeader, - hunks: hunks - }; - } -} -/** - * creates a unified diff patch. - * @param patch either a single structured patch object (as returned by `structuredPatch`) or an array of them (as returned by `parsePatch`) - */ -export function formatPatch(patch, headerOptions) { - if (!headerOptions) { - headerOptions = INCLUDE_HEADERS; - } - if (Array.isArray(patch)) { - if (patch.length > 1 && !headerOptions.includeFileHeaders) { - throw new Error('Cannot omit file headers on a multi-file patch. ' - + '(The result would be unparseable; how would a tool trying to apply ' - + 'the patch know which changes are to which file?)'); - } - return patch.map(p => formatPatch(p, headerOptions)).join('\n'); - } - const ret = []; - if (headerOptions.includeIndex && patch.oldFileName == patch.newFileName) { - ret.push('Index: ' + patch.oldFileName); - } - if (headerOptions.includeUnderline) { - ret.push('==================================================================='); - } - if (headerOptions.includeFileHeaders) { - ret.push('--- ' + patch.oldFileName + (typeof patch.oldHeader === 'undefined' ? '' : '\t' + patch.oldHeader)); - ret.push('+++ ' + patch.newFileName + (typeof patch.newHeader === 'undefined' ? '' : '\t' + patch.newHeader)); - } - for (let i = 0; i < patch.hunks.length; i++) { - const hunk = patch.hunks[i]; - // Unified Diff Format quirk: If the chunk size is 0, - // the first number is one lower than one would expect. - // https://www.artima.com/weblogs/viewpost.jsp?thread=164293 - if (hunk.oldLines === 0) { - hunk.oldStart -= 1; - } - if (hunk.newLines === 0) { - hunk.newStart -= 1; - } - ret.push('@@ -' + hunk.oldStart + ',' + hunk.oldLines - + ' +' + hunk.newStart + ',' + hunk.newLines - + ' @@'); - for (const line of hunk.lines) { - ret.push(line); - } - } - return ret.join('\n') + '\n'; -} -export function createTwoFilesPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options) { - if (typeof options === 'function') { - options = { callback: options }; - } - if (!(options === null || options === void 0 ? void 0 : options.callback)) { - const patchObj = structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, options); - if (!patchObj) { - return; - } - return formatPatch(patchObj, options === null || options === void 0 ? void 0 : options.headerOptions); - } - else { - const { callback } = options; - structuredPatch(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader, Object.assign(Object.assign({}, options), { callback: patchObj => { - if (!patchObj) { - callback(undefined); - } - else { - callback(formatPatch(patchObj, options.headerOptions)); - } - } })); - } -} -export function createPatch(fileName, oldStr, newStr, oldHeader, newHeader, options) { - return createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader, options); -} -/** - * Split `text` into an array of lines, including the trailing newline character (where present) - */ -function splitLines(text) { - const hasTrailingNl = text.endsWith('\n'); - const result = text.split('\n').map(line => line + '\n'); - if (hasTrailingNl) { - result.pop(); - } - else { - result.push(result.pop().slice(0, -1)); - } - return result; -} diff --git a/claude-code-source/node_modules/diff/libesm/util/string.js b/claude-code-source/node_modules/diff/libesm/util/string.js deleted file mode 100644 index 32ab8645..00000000 --- a/claude-code-source/node_modules/diff/libesm/util/string.js +++ /dev/null @@ -1,128 +0,0 @@ -export function longestCommonPrefix(str1, str2) { - let i; - for (i = 0; i < str1.length && i < str2.length; i++) { - if (str1[i] != str2[i]) { - return str1.slice(0, i); - } - } - return str1.slice(0, i); -} -export function longestCommonSuffix(str1, str2) { - let i; - // Unlike longestCommonPrefix, we need a special case to handle all scenarios - // where we return the empty string since str1.slice(-0) will return the - // entire string. - if (!str1 || !str2 || str1[str1.length - 1] != str2[str2.length - 1]) { - return ''; - } - for (i = 0; i < str1.length && i < str2.length; i++) { - if (str1[str1.length - (i + 1)] != str2[str2.length - (i + 1)]) { - return str1.slice(-i); - } - } - return str1.slice(-i); -} -export function replacePrefix(string, oldPrefix, newPrefix) { - if (string.slice(0, oldPrefix.length) != oldPrefix) { - throw Error(`string ${JSON.stringify(string)} doesn't start with prefix ${JSON.stringify(oldPrefix)}; this is a bug`); - } - return newPrefix + string.slice(oldPrefix.length); -} -export function replaceSuffix(string, oldSuffix, newSuffix) { - if (!oldSuffix) { - return string + newSuffix; - } - if (string.slice(-oldSuffix.length) != oldSuffix) { - throw Error(`string ${JSON.stringify(string)} doesn't end with suffix ${JSON.stringify(oldSuffix)}; this is a bug`); - } - return string.slice(0, -oldSuffix.length) + newSuffix; -} -export function removePrefix(string, oldPrefix) { - return replacePrefix(string, oldPrefix, ''); -} -export function removeSuffix(string, oldSuffix) { - return replaceSuffix(string, oldSuffix, ''); -} -export function maximumOverlap(string1, string2) { - return string2.slice(0, overlapCount(string1, string2)); -} -// Nicked from https://stackoverflow.com/a/60422853/1709587 -function overlapCount(a, b) { - // Deal with cases where the strings differ in length - let startA = 0; - if (a.length > b.length) { - startA = a.length - b.length; - } - let endB = b.length; - if (a.length < b.length) { - endB = a.length; - } - // Create a back-reference for each index - // that should be followed in case of a mismatch. - // We only need B to make these references: - const map = Array(endB); - let k = 0; // Index that lags behind j - map[0] = 0; - for (let j = 1; j < endB; j++) { - if (b[j] == b[k]) { - map[j] = map[k]; // skip over the same character (optional optimisation) - } - else { - map[j] = k; - } - while (k > 0 && b[j] != b[k]) { - k = map[k]; - } - if (b[j] == b[k]) { - k++; - } - } - // Phase 2: use these references while iterating over A - k = 0; - for (let i = startA; i < a.length; i++) { - while (k > 0 && a[i] != b[k]) { - k = map[k]; - } - if (a[i] == b[k]) { - k++; - } - } - return k; -} -/** - * Returns true if the string consistently uses Windows line endings. - */ -export function hasOnlyWinLineEndings(string) { - return string.includes('\r\n') && !string.startsWith('\n') && !string.match(/[^\r]\n/); -} -/** - * Returns true if the string consistently uses Unix line endings. - */ -export function hasOnlyUnixLineEndings(string) { - return !string.includes('\r\n') && string.includes('\n'); -} -export function trailingWs(string) { - // Yes, this looks overcomplicated and dumb - why not replace the whole function with - // return string.match(/\s*$/)[0] - // you ask? Because: - // 1. the trap described at https://markamery.com/blog/quadratic-time-regexes/ would mean doing - // this would cause this function to take O(n²) time in the worst case (specifically when - // there is a massive run of NON-TRAILING whitespace in `string`), and - // 2. the fix proposed in the same blog post, of using a negative lookbehind, is incompatible - // with old Safari versions that we'd like to not break if possible (see - // https://github.com/kpdecker/jsdiff/pull/550) - // It feels absurd to do this with an explicit loop instead of a regex, but I really can't see a - // better way that doesn't result in broken behaviour. - let i; - for (i = string.length - 1; i >= 0; i--) { - if (!string[i].match(/\s/)) { - break; - } - } - return string.substring(i + 1); -} -export function leadingWs(string) { - // Thankfully the annoying considerations described in trailingWs don't apply here: - const match = string.match(/^\s*/); - return match ? match[0] : ''; -} diff --git a/claude-code-source/node_modules/dijkstrajs/dijkstra.js b/claude-code-source/node_modules/dijkstrajs/dijkstra.js deleted file mode 100644 index 4f83f1f2..00000000 --- a/claude-code-source/node_modules/dijkstrajs/dijkstra.js +++ /dev/null @@ -1,165 +0,0 @@ -'use strict'; - -/****************************************************************************** - * Created 2008-08-19. - * - * Dijkstra path-finding functions. Adapted from the Dijkstar Python project. - * - * Copyright (C) 2008 - * Wyatt Baldwin - * All rights reserved - * - * Licensed under the MIT license. - * - * http://www.opensource.org/licenses/mit-license.php - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - *****************************************************************************/ -var dijkstra = { - single_source_shortest_paths: function(graph, s, d) { - // Predecessor map for each node that has been encountered. - // node ID => predecessor node ID - var predecessors = {}; - - // Costs of shortest paths from s to all nodes encountered. - // node ID => cost - var costs = {}; - costs[s] = 0; - - // Costs of shortest paths from s to all nodes encountered; differs from - // `costs` in that it provides easy access to the node that currently has - // the known shortest path from s. - // XXX: Do we actually need both `costs` and `open`? - var open = dijkstra.PriorityQueue.make(); - open.push(s, 0); - - var closest, - u, v, - cost_of_s_to_u, - adjacent_nodes, - cost_of_e, - cost_of_s_to_u_plus_cost_of_e, - cost_of_s_to_v, - first_visit; - while (!open.empty()) { - // In the nodes remaining in graph that have a known cost from s, - // find the node, u, that currently has the shortest path from s. - closest = open.pop(); - u = closest.value; - cost_of_s_to_u = closest.cost; - - // Get nodes adjacent to u... - adjacent_nodes = graph[u] || {}; - - // ...and explore the edges that connect u to those nodes, updating - // the cost of the shortest paths to any or all of those nodes as - // necessary. v is the node across the current edge from u. - for (v in adjacent_nodes) { - if (adjacent_nodes.hasOwnProperty(v)) { - // Get the cost of the edge running from u to v. - cost_of_e = adjacent_nodes[v]; - - // Cost of s to u plus the cost of u to v across e--this is *a* - // cost from s to v that may or may not be less than the current - // known cost to v. - cost_of_s_to_u_plus_cost_of_e = cost_of_s_to_u + cost_of_e; - - // If we haven't visited v yet OR if the current known cost from s to - // v is greater than the new cost we just found (cost of s to u plus - // cost of u to v across e), update v's cost in the cost list and - // update v's predecessor in the predecessor list (it's now u). - cost_of_s_to_v = costs[v]; - first_visit = (typeof costs[v] === 'undefined'); - if (first_visit || cost_of_s_to_v > cost_of_s_to_u_plus_cost_of_e) { - costs[v] = cost_of_s_to_u_plus_cost_of_e; - open.push(v, cost_of_s_to_u_plus_cost_of_e); - predecessors[v] = u; - } - } - } - } - - if (typeof d !== 'undefined' && typeof costs[d] === 'undefined') { - var msg = ['Could not find a path from ', s, ' to ', d, '.'].join(''); - throw new Error(msg); - } - - return predecessors; - }, - - extract_shortest_path_from_predecessor_list: function(predecessors, d) { - var nodes = []; - var u = d; - var predecessor; - while (u) { - nodes.push(u); - predecessor = predecessors[u]; - u = predecessors[u]; - } - nodes.reverse(); - return nodes; - }, - - find_path: function(graph, s, d) { - var predecessors = dijkstra.single_source_shortest_paths(graph, s, d); - return dijkstra.extract_shortest_path_from_predecessor_list( - predecessors, d); - }, - - /** - * A very naive priority queue implementation. - */ - PriorityQueue: { - make: function (opts) { - var T = dijkstra.PriorityQueue, - t = {}, - key; - opts = opts || {}; - for (key in T) { - if (T.hasOwnProperty(key)) { - t[key] = T[key]; - } - } - t.queue = []; - t.sorter = opts.sorter || T.default_sorter; - return t; - }, - - default_sorter: function (a, b) { - return a.cost - b.cost; - }, - - /** - * Add a new item to the queue and ensure the highest priority element - * is at the front of the queue. - */ - push: function (value, cost) { - var item = {value: value, cost: cost}; - this.queue.push(item); - this.queue.sort(this.sorter); - }, - - /** - * Return the highest priority element in the queue. - */ - pop: function () { - return this.queue.shift(); - }, - - empty: function () { - return this.queue.length === 0; - } - } -}; - - -// node.js module exports -if (typeof module !== 'undefined') { - module.exports = dijkstra; -} diff --git a/claude-code-source/node_modules/dom-mutator/dist/dom-mutator.cjs.production.min.js b/claude-code-source/node_modules/dom-mutator/dist/dom-mutator.cjs.production.min.js deleted file mode 100644 index 89d8dc16..00000000 --- a/claude-code-source/node_modules/dom-mutator/dist/dom-mutator.cjs.production.min.js +++ /dev/null @@ -1,2 +0,0 @@ -"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=/^[a-zA-Z:_][a-zA-Z0-9:_.-]*$/,t={revert:function(){}},n=new Map,r=new Set;function i(e){var t=n.get(e);return t||n.set(e,t={element:e,attributes:{}}),t}function o(e,t,n,r,i){var o=n(e),u={isDirty:!1,originalValue:o,virtualValue:o,mutations:[],el:e,_positionTimeout:null,observer:new MutationObserver((function(){if("position"!==t||!u._positionTimeout){"position"===t&&(u._positionTimeout=setTimeout((function(){u._positionTimeout=null}),1e3));var r=n(e);"position"===t&&r.parentNode===u.virtualValue.parentNode&&r.insertBeforeNode===u.virtualValue.insertBeforeNode||r!==u.virtualValue&&(u.originalValue=r,i(u))}})),mutationRunner:i,setValue:r,getCurrentValue:n};return"position"===t&&e.parentNode?u.observer.observe(e.parentNode,{childList:!0,subtree:!0,attributes:!1,characterData:!1}):u.observer.observe(e,function(e){return"html"===e?{childList:!0,subtree:!0,attributes:!0,characterData:!0}:{childList:!1,subtree:!1,attributes:!0,attributeFilter:[e]}}(t)),u}function u(e,t){var n=t.getCurrentValue(t.el);t.virtualValue=e,e&&"string"!=typeof e?n&&e.parentNode===n.parentNode&&e.insertBeforeNode===n.insertBeforeNode||(t.isDirty=!0,E()):e!==n&&(t.isDirty=!0,E())}function a(e){var t=e.originalValue;e.mutations.forEach((function(e){return t=e.mutate(t)})),u(function(e){return h||(h=document.createElement("div")),h.innerHTML=e,h.innerHTML}(t),e)}function l(e){var t=new Set(e.originalValue.split(/\s+/).filter(Boolean));e.mutations.forEach((function(e){return e.mutate(t)})),u(Array.from(t).filter(Boolean).join(" "),e)}function s(e){var t=e.originalValue;e.mutations.forEach((function(e){return t=e.mutate(t)})),u(t,e)}function c(e){var t=e.originalValue;e.mutations.forEach((function(e){var n=function(e){var t=e.insertBeforeSelector,n=document.querySelector(e.parentSelector);if(!n)return null;var r=t?document.querySelector(t):null;return t&&!r?null:{parentNode:n,insertBeforeNode:r}}(e.mutate());t=n||t})),u(t,e)}var f=function(e){return e.innerHTML},d=function(e,t){return e.innerHTML=t};function m(e){var t=i(e);return t.html||(t.html=o(e,"html",f,d,a)),t.html}var v=function(e){return{parentNode:e.parentElement,insertBeforeNode:e.nextElementSibling}},p=function(e,t){t.insertBeforeNode&&!t.parentNode.contains(t.insertBeforeNode)||t.parentNode.insertBefore(e,t.insertBeforeNode)};function b(e){var t=i(e);return t.position||(t.position=o(e,"position",v,p,c)),t.position}var h,N,S=function(e,t){return t?e.className=t:e.removeAttribute("class")},B=function(e){return e.className};function V(e){var t=i(e);return t.classes||(t.classes=o(e,"class",B,S,l)),t.classes}function g(e,t){var n,r=i(e);return r.attributes[t]||(r.attributes[t]=o(e,t,(n=t,function(e){var t;return null!=(t=e.getAttribute(n))?t:null}),function(e){return function(t,n){return null!==n?t.setAttribute(e,n):t.removeAttribute(e)}}(t),s)),r.attributes[t]}function y(e,t,r){if(r.isDirty){r.isDirty=!1;var i=r.virtualValue;r.mutations.length||function(e,t){var r,i,o=n.get(e);if(o)if("html"===t)null==(r=o.html)||null==(i=r.observer)||i.disconnect(),delete o.html;else if("class"===t){var u,a;null==(u=o.classes)||null==(a=u.observer)||a.disconnect(),delete o.classes}else if("position"===t){var l,s;null==(l=o.position)||null==(s=l.observer)||s.disconnect(),delete o.position}else{var c,f,d;null==(c=o.attributes)||null==(f=c[t])||null==(d=f.observer)||d.disconnect(),delete o.attributes[t]}}(e,t),r.setValue(e,i)}}function k(e,t){e.html&&y(t,"html",e.html),e.classes&&y(t,"class",e.classes),e.position&&y(t,"position",e.position),Object.keys(e.attributes).forEach((function(n){y(t,n,e.attributes[n])}))}function E(){n.forEach(k)}function w(e){if("position"!==e.kind||1!==e.elements.size){var t=new Set(e.elements);document.querySelectorAll(e.selector).forEach((function(n){t.has(n)||(e.elements.add(n),function(e,t){var n=null;"html"===e.kind?n=m(t):"class"===e.kind?n=V(t):"attribute"===e.kind?n=g(t,e.attribute):"position"===e.kind&&(n=b(t)),n&&(n.mutations.push(e),n.mutationRunner(n))}(e,n))}))}}function A(){r.forEach(w)}function T(){"undefined"!=typeof document&&(N||(N=new MutationObserver((function(){A()}))),A(),N.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!1,characterData:!1}))}function D(e){return"undefined"==typeof document?t:(r.add(e),w(e),{revert:function(){var t;(t=e).elements.forEach((function(e){return function(e,t){var n=null;if("html"===e.kind?n=m(t):"class"===e.kind?n=V(t):"attribute"===e.kind?n=g(t,e.attribute):"position"===e.kind&&(n=b(t)),n){var r=n.mutations.indexOf(e);-1!==r&&n.mutations.splice(r,1),n.mutationRunner(n)}}(t,e)})),t.elements.clear(),r.delete(t)}})}function L(e,t){return D({kind:"html",elements:new Set,mutate:t,selector:e})}function M(e,t){return D({kind:"position",elements:new Set,mutate:t,selector:e})}function _(e,t){return D({kind:"class",elements:new Set,mutate:t,selector:e})}function x(n,r,i){return e.test(r)?"class"===r||"className"===r?_(n,(function(e){var t=i(Array.from(e).join(" "));e.clear(),t&&t.split(/\s+/g).filter(Boolean).forEach((function(t){return e.add(t)}))})):D({kind:"attribute",attribute:r,elements:new Set,mutate:i,selector:n}):t}T();var O={html:L,classes:_,attribute:x,position:M,declarative:function(e){var n=e.selector,r=e.action,i=e.value,o=e.attribute,u=e.parentSelector,a=e.insertBeforeSelector;if("html"===o){if("append"===r)return L(n,(function(e){return e+(null!=i?i:"")}));if("set"===r)return L(n,(function(){return null!=i?i:""}))}else if("class"===o){if("append"===r)return _(n,(function(e){i&&e.add(i)}));if("remove"===r)return _(n,(function(e){i&&e.delete(i)}));if("set"===r)return _(n,(function(e){e.clear(),i&&e.add(i)}))}else if("position"===o){if("set"===r&&u)return M(n,(function(){return{insertBeforeSelector:a,parentSelector:u}}))}else{if("append"===r)return x(n,o,(function(e){return null!==e?e+(null!=i?i:""):null!=i?i:""}));if("set"===r)return x(n,o,(function(){return null!=i?i:""}));if("remove"===r)return x(n,o,(function(){return null}))}return t}};exports.connectGlobalObserver=T,exports.default=O,exports.disconnectGlobalObserver=function(){N&&N.disconnect()},exports.validAttributeName=e; -//# sourceMappingURL=dom-mutator.cjs.production.min.js.map diff --git a/claude-code-source/node_modules/dunder-proto/get.js b/claude-code-source/node_modules/dunder-proto/get.js deleted file mode 100644 index 45093df9..00000000 --- a/claude-code-source/node_modules/dunder-proto/get.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict'; - -var callBind = require('call-bind-apply-helpers'); -var gOPD = require('gopd'); - -var hasProtoAccessor; -try { - // eslint-disable-next-line no-extra-parens, no-proto - hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ ([]).__proto__ === Array.prototype; -} catch (e) { - if (!e || typeof e !== 'object' || !('code' in e) || e.code !== 'ERR_PROTO_ACCESS') { - throw e; - } -} - -// eslint-disable-next-line no-extra-parens -var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, /** @type {keyof typeof Object.prototype} */ ('__proto__')); - -var $Object = Object; -var $getPrototypeOf = $Object.getPrototypeOf; - -/** @type {import('./get')} */ -module.exports = desc && typeof desc.get === 'function' - ? callBind([desc.get]) - : typeof $getPrototypeOf === 'function' - ? /** @type {import('./get')} */ function getDunder(value) { - // eslint-disable-next-line eqeqeq - return $getPrototypeOf(value == null ? value : $Object(value)); - } - : false; diff --git a/claude-code-source/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js b/claude-code-source/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js deleted file mode 100644 index 38eeb9b9..00000000 --- a/claude-code-source/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js +++ /dev/null @@ -1,187 +0,0 @@ -'use strict'; - -var Buffer = require('safe-buffer').Buffer; - -var getParamBytesForAlg = require('./param-bytes-for-alg'); - -var MAX_OCTET = 0x80, - CLASS_UNIVERSAL = 0, - PRIMITIVE_BIT = 0x20, - TAG_SEQ = 0x10, - TAG_INT = 0x02, - ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), - ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); - -function base64Url(base64) { - return base64 - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} - -function signatureAsBuffer(signature) { - if (Buffer.isBuffer(signature)) { - return signature; - } else if ('string' === typeof signature) { - return Buffer.from(signature, 'base64'); - } - - throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); -} - -function derToJose(signature, alg) { - signature = signatureAsBuffer(signature); - var paramBytes = getParamBytesForAlg(alg); - - // the DER encoded param should at most be the param size, plus a padding - // zero, since due to being a signed integer - var maxEncodedParamLength = paramBytes + 1; - - var inputLength = signature.length; - - var offset = 0; - if (signature[offset++] !== ENCODED_TAG_SEQ) { - throw new Error('Could not find expected "seq"'); - } - - var seqLength = signature[offset++]; - if (seqLength === (MAX_OCTET | 1)) { - seqLength = signature[offset++]; - } - - if (inputLength - offset < seqLength) { - throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); - } - - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "r"'); - } - - var rLength = signature[offset++]; - - if (inputLength - offset - 2 < rLength) { - throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); - } - - if (maxEncodedParamLength < rLength) { - throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); - } - - var rOffset = offset; - offset += rLength; - - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "s"'); - } - - var sLength = signature[offset++]; - - if (inputLength - offset !== sLength) { - throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); - } - - if (maxEncodedParamLength < sLength) { - throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); - } - - var sOffset = offset; - offset += sLength; - - if (offset !== inputLength) { - throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); - } - - var rPadding = paramBytes - rLength, - sPadding = paramBytes - sLength; - - var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); - - for (offset = 0; offset < rPadding; ++offset) { - dst[offset] = 0; - } - signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); - - offset = paramBytes; - - for (var o = offset; offset < o + sPadding; ++offset) { - dst[offset] = 0; - } - signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); - - dst = dst.toString('base64'); - dst = base64Url(dst); - - return dst; -} - -function countPadding(buf, start, stop) { - var padding = 0; - while (start + padding < stop && buf[start + padding] === 0) { - ++padding; - } - - var needsSign = buf[start + padding] >= MAX_OCTET; - if (needsSign) { - --padding; - } - - return padding; -} - -function joseToDer(signature, alg) { - signature = signatureAsBuffer(signature); - var paramBytes = getParamBytesForAlg(alg); - - var signatureBytes = signature.length; - if (signatureBytes !== paramBytes * 2) { - throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); - } - - var rPadding = countPadding(signature, 0, paramBytes); - var sPadding = countPadding(signature, paramBytes, signature.length); - var rLength = paramBytes - rPadding; - var sLength = paramBytes - sPadding; - - var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; - - var shortLength = rsBytes < MAX_OCTET; - - var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); - - var offset = 0; - dst[offset++] = ENCODED_TAG_SEQ; - if (shortLength) { - // Bit 8 has value "0" - // bits 7-1 give the length. - dst[offset++] = rsBytes; - } else { - // Bit 8 of first octet has value "1" - // bits 7-1 give the number of additional length octets. - dst[offset++] = MAX_OCTET | 1; - // length, base 256 - dst[offset++] = rsBytes & 0xff; - } - dst[offset++] = ENCODED_TAG_INT; - dst[offset++] = rLength; - if (rPadding < 0) { - dst[offset++] = 0; - offset += signature.copy(dst, offset, 0, paramBytes); - } else { - offset += signature.copy(dst, offset, rPadding, paramBytes); - } - dst[offset++] = ENCODED_TAG_INT; - dst[offset++] = sLength; - if (sPadding < 0) { - dst[offset++] = 0; - signature.copy(dst, offset, paramBytes); - } else { - signature.copy(dst, offset, paramBytes + sPadding); - } - - return dst; -} - -module.exports = { - derToJose: derToJose, - joseToDer: joseToDer -}; diff --git a/claude-code-source/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js b/claude-code-source/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js deleted file mode 100644 index 9fe67acc..00000000 --- a/claude-code-source/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict'; - -function getParamSize(keySize) { - var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); - return result; -} - -var paramBytesForAlg = { - ES256: getParamSize(256), - ES384: getParamSize(384), - ES512: getParamSize(521) -}; - -function getParamBytesForAlg(alg) { - var paramBytes = paramBytesForAlg[alg]; - if (paramBytes) { - return paramBytes; - } - - throw new Error('Unknown algorithm "' + alg + '"'); -} - -module.exports = getParamBytesForAlg; diff --git a/claude-code-source/node_modules/emoji-regex/index.js b/claude-code-source/node_modules/emoji-regex/index.js deleted file mode 100644 index d993a3a9..00000000 --- a/claude-code-source/node_modules/emoji-regex/index.js +++ /dev/null @@ -1,6 +0,0 @@ -"use strict"; - -module.exports = function () { - // https://mths.be/emoji - return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; -}; diff --git a/claude-code-source/node_modules/env-paths/index.js b/claude-code-source/node_modules/env-paths/index.js deleted file mode 100644 index ae067451..00000000 --- a/claude-code-source/node_modules/env-paths/index.js +++ /dev/null @@ -1,68 +0,0 @@ -import path from 'node:path'; -import os from 'node:os'; -import process from 'node:process'; - -const homedir = os.homedir(); -const tmpdir = os.tmpdir(); -const {env} = process; - -const macos = name => { - const library = path.join(homedir, 'Library'); - - return { - data: path.join(library, 'Application Support', name), - config: path.join(library, 'Preferences', name), - cache: path.join(library, 'Caches', name), - log: path.join(library, 'Logs', name), - temp: path.join(tmpdir, name), - }; -}; - -const windows = name => { - const appData = env.APPDATA || path.join(homedir, 'AppData', 'Roaming'); - const localAppData = env.LOCALAPPDATA || path.join(homedir, 'AppData', 'Local'); - - return { - // Data/config/cache/log are invented by me as Windows isn't opinionated about this - data: path.join(localAppData, name, 'Data'), - config: path.join(appData, name, 'Config'), - cache: path.join(localAppData, name, 'Cache'), - log: path.join(localAppData, name, 'Log'), - temp: path.join(tmpdir, name), - }; -}; - -// https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html -const linux = name => { - const username = path.basename(homedir); - - return { - data: path.join(env.XDG_DATA_HOME || path.join(homedir, '.local', 'share'), name), - config: path.join(env.XDG_CONFIG_HOME || path.join(homedir, '.config'), name), - cache: path.join(env.XDG_CACHE_HOME || path.join(homedir, '.cache'), name), - // https://wiki.debian.org/XDGBaseDirectorySpecification#state - log: path.join(env.XDG_STATE_HOME || path.join(homedir, '.local', 'state'), name), - temp: path.join(tmpdir, username, name), - }; -}; - -export default function envPaths(name, {suffix = 'nodejs'} = {}) { - if (typeof name !== 'string') { - throw new TypeError(`Expected a string, got ${typeof name}`); - } - - if (suffix) { - // Add suffix to prevent possible conflict with native apps - name += `-${suffix}`; - } - - if (process.platform === 'darwin') { - return macos(name); - } - - if (process.platform === 'win32') { - return windows(name); - } - - return linux(name); -} diff --git a/claude-code-source/node_modules/es-define-property/index.js b/claude-code-source/node_modules/es-define-property/index.js deleted file mode 100644 index e0a29251..00000000 --- a/claude-code-source/node_modules/es-define-property/index.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -/** @type {import('.')} */ -var $defineProperty = Object.defineProperty || false; -if ($defineProperty) { - try { - $defineProperty({}, 'a', { value: 1 }); - } catch (e) { - // IE 8 has a broken defineProperty - $defineProperty = false; - } -} - -module.exports = $defineProperty; diff --git a/claude-code-source/node_modules/es-errors/eval.js b/claude-code-source/node_modules/es-errors/eval.js deleted file mode 100644 index 725ccb61..00000000 --- a/claude-code-source/node_modules/es-errors/eval.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; - -/** @type {import('./eval')} */ -module.exports = EvalError; diff --git a/claude-code-source/node_modules/es-errors/index.js b/claude-code-source/node_modules/es-errors/index.js deleted file mode 100644 index cc0c5212..00000000 --- a/claude-code-source/node_modules/es-errors/index.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; - -/** @type {import('.')} */ -module.exports = Error; diff --git a/claude-code-source/node_modules/es-errors/range.js b/claude-code-source/node_modules/es-errors/range.js deleted file mode 100644 index 2044fe03..00000000 --- a/claude-code-source/node_modules/es-errors/range.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; - -/** @type {import('./range')} */ -module.exports = RangeError; diff --git a/claude-code-source/node_modules/es-errors/ref.js b/claude-code-source/node_modules/es-errors/ref.js deleted file mode 100644 index d7c430fd..00000000 --- a/claude-code-source/node_modules/es-errors/ref.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; - -/** @type {import('./ref')} */ -module.exports = ReferenceError; diff --git a/claude-code-source/node_modules/es-errors/syntax.js b/claude-code-source/node_modules/es-errors/syntax.js deleted file mode 100644 index 5f5fddee..00000000 --- a/claude-code-source/node_modules/es-errors/syntax.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; - -/** @type {import('./syntax')} */ -module.exports = SyntaxError; diff --git a/claude-code-source/node_modules/es-errors/type.js b/claude-code-source/node_modules/es-errors/type.js deleted file mode 100644 index 9769e44e..00000000 --- a/claude-code-source/node_modules/es-errors/type.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; - -/** @type {import('./type')} */ -module.exports = TypeError; diff --git a/claude-code-source/node_modules/es-errors/uri.js b/claude-code-source/node_modules/es-errors/uri.js deleted file mode 100644 index e9cd1c78..00000000 --- a/claude-code-source/node_modules/es-errors/uri.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; - -/** @type {import('./uri')} */ -module.exports = URIError; diff --git a/claude-code-source/node_modules/es-object-atoms/index.js b/claude-code-source/node_modules/es-object-atoms/index.js deleted file mode 100644 index 1d33cef4..00000000 --- a/claude-code-source/node_modules/es-object-atoms/index.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; - -/** @type {import('.')} */ -module.exports = Object; diff --git a/claude-code-source/node_modules/es-set-tostringtag/index.js b/claude-code-source/node_modules/es-set-tostringtag/index.js deleted file mode 100644 index 6b6b49c7..00000000 --- a/claude-code-source/node_modules/es-set-tostringtag/index.js +++ /dev/null @@ -1,35 +0,0 @@ -'use strict'; - -var GetIntrinsic = require('get-intrinsic'); - -var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); - -var hasToStringTag = require('has-tostringtag/shams')(); -var hasOwn = require('hasown'); -var $TypeError = require('es-errors/type'); - -var toStringTag = hasToStringTag ? Symbol.toStringTag : null; - -/** @type {import('.')} */ -module.exports = function setToStringTag(object, value) { - var overrideIfSet = arguments.length > 2 && !!arguments[2] && arguments[2].force; - var nonConfigurable = arguments.length > 2 && !!arguments[2] && arguments[2].nonConfigurable; - if ( - (typeof overrideIfSet !== 'undefined' && typeof overrideIfSet !== 'boolean') - || (typeof nonConfigurable !== 'undefined' && typeof nonConfigurable !== 'boolean') - ) { - throw new $TypeError('if provided, the `overrideIfSet` and `nonConfigurable` options must be booleans'); - } - if (toStringTag && (overrideIfSet || !hasOwn(object, toStringTag))) { - if ($defineProperty) { - $defineProperty(object, toStringTag, { - configurable: !nonConfigurable, - enumerable: false, - value: value, - writable: false - }); - } else { - object[toStringTag] = value; // eslint-disable-line no-param-reassign - } - } -}; diff --git a/claude-code-source/node_modules/eventsource-parser/dist/index.js b/claude-code-source/node_modules/eventsource-parser/dist/index.js deleted file mode 100644 index 23839fec..00000000 --- a/claude-code-source/node_modules/eventsource-parser/dist/index.js +++ /dev/null @@ -1,106 +0,0 @@ -class ParseError extends Error { - constructor(message, options) { - super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line; - } -} -function noop(_arg) { -} -function createParser(callbacks) { - if (typeof callbacks == "function") - throw new TypeError( - "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?" - ); - const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks; - let incompleteLine = "", isFirstChunk = !0, id, data = "", eventType = ""; - function feed(newChunk) { - const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`); - for (const line of complete) - parseLine(line); - incompleteLine = incomplete, isFirstChunk = !1; - } - function parseLine(line) { - if (line === "") { - dispatchEvent(); - return; - } - if (line.startsWith(":")) { - onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1)); - return; - } - const fieldSeparatorIndex = line.indexOf(":"); - if (fieldSeparatorIndex !== -1) { - const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset); - processField(field, value, line); - return; - } - processField(line, "", line); - } - function processField(field, value, line) { - switch (field) { - case "event": - eventType = value; - break; - case "data": - data = `${data}${value} -`; - break; - case "id": - id = value.includes("\0") ? void 0 : value; - break; - case "retry": - /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError( - new ParseError(`Invalid \`retry\` value: "${value}"`, { - type: "invalid-retry", - value, - line - }) - ); - break; - default: - onError( - new ParseError( - `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, - { type: "unknown-field", field, value, line } - ) - ); - break; - } - } - function dispatchEvent() { - data.length > 0 && onEvent({ - id, - event: eventType || void 0, - // If the data buffer's last character is a U+000A LINE FEED (LF) character, - // then remove the last character from the data buffer. - data: data.endsWith(` -`) ? data.slice(0, -1) : data - }), id = void 0, data = "", eventType = ""; - } - function reset(options = {}) { - incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = !0, id = void 0, data = "", eventType = "", incompleteLine = ""; - } - return { feed, reset }; -} -function splitLines(chunk) { - const lines = []; - let incompleteLine = "", searchIndex = 0; - for (; searchIndex < chunk.length; ) { - const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(` -`, searchIndex); - let lineEnd = -1; - if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) { - incompleteLine = chunk.slice(searchIndex); - break; - } else { - const line = chunk.slice(searchIndex, lineEnd); - lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === ` -` && searchIndex++; - } - } - return [lines, incompleteLine]; -} -export { - ParseError, - createParser -}; -//# sourceMappingURL=index.js.map diff --git a/claude-code-source/node_modules/eventsource-parser/dist/stream.js b/claude-code-source/node_modules/eventsource-parser/dist/stream.js deleted file mode 100644 index b551fc38..00000000 --- a/claude-code-source/node_modules/eventsource-parser/dist/stream.js +++ /dev/null @@ -1,29 +0,0 @@ -import { createParser } from "./index.js"; -import { ParseError } from "./index.js"; -class EventSourceParserStream extends TransformStream { - constructor({ onError, onRetry, onComment } = {}) { - let parser; - super({ - start(controller) { - parser = createParser({ - onEvent: (event) => { - controller.enqueue(event); - }, - onError(error) { - onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error); - }, - onRetry, - onComment - }); - }, - transform(chunk) { - parser.feed(chunk); - } - }); - } -} -export { - EventSourceParserStream, - ParseError -}; -//# sourceMappingURL=stream.js.map diff --git a/claude-code-source/node_modules/eventsource/dist/index.js b/claude-code-source/node_modules/eventsource/dist/index.js deleted file mode 100644 index d5713a3b..00000000 --- a/claude-code-source/node_modules/eventsource/dist/index.js +++ /dev/null @@ -1,273 +0,0 @@ -import { createParser } from "eventsource-parser"; -class ErrorEvent extends Event { - /** - * Constructs a new `ErrorEvent` instance. This is typically not called directly, - * but rather emitted by the `EventSource` object when an error occurs. - * - * @param type - The type of the event (should be "error") - * @param errorEventInitDict - Optional properties to include in the error event - */ - constructor(type, errorEventInitDict) { - var _a, _b; - super(type), this.code = (_a = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a : void 0, this.message = (_b = errorEventInitDict == null ? void 0 : errorEventInitDict.message) != null ? _b : void 0; - } - /** - * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance, - * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging, - * we explicitly include the properties in the `inspect` method. - * - * This is automatically called by Node.js when you `console.log` an instance of this class. - * - * @param _depth - The current depth - * @param options - The options passed to `util.inspect` - * @param inspect - The inspect function to use (prevents having to import it from `util`) - * @returns A string representation of the error - */ - [Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) { - return inspect(inspectableError(this), options); - } - /** - * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance, - * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging, - * we explicitly include the properties in the `inspect` method. - * - * This is automatically called by Deno when you `console.log` an instance of this class. - * - * @param inspect - The inspect function to use (prevents having to import it from `util`) - * @param options - The options passed to `Deno.inspect` - * @returns A string representation of the error - */ - [Symbol.for("Deno.customInspect")](inspect, options) { - return inspect(inspectableError(this), options); - } -} -function syntaxError(message) { - const DomException = globalThis.DOMException; - return typeof DomException == "function" ? new DomException(message, "SyntaxError") : new SyntaxError(message); -} -function flattenError(err) { - return err instanceof Error ? "errors" in err && Array.isArray(err.errors) ? err.errors.map(flattenError).join(", ") : "cause" in err && err.cause instanceof Error ? `${err}: ${flattenError(err.cause)}` : err.message : `${err}`; -} -function inspectableError(err) { - return { - type: err.type, - message: err.message, - code: err.code, - defaultPrevented: err.defaultPrevented, - cancelable: err.cancelable, - timeStamp: err.timeStamp - }; -} -var __typeError = (msg) => { - throw TypeError(msg); -}, __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg), __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj)), __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value), __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), member.set(obj, value), value), __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method), _readyState, _url, _redirectUrl, _withCredentials, _fetch, _reconnectInterval, _reconnectTimer, _lastEventId, _controller, _parser, _onError, _onMessage, _onOpen, _EventSource_instances, connect_fn, _onFetchResponse, _onFetchError, getRequestOptions_fn, _onEvent, _onRetryChange, failConnection_fn, scheduleReconnect_fn, _reconnect; -class EventSource extends EventTarget { - constructor(url, eventSourceInitDict) { - var _a, _b; - super(), __privateAdd(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd(this, _readyState), __privateAdd(this, _url), __privateAdd(this, _redirectUrl), __privateAdd(this, _withCredentials), __privateAdd(this, _fetch), __privateAdd(this, _reconnectInterval), __privateAdd(this, _reconnectTimer), __privateAdd(this, _lastEventId, null), __privateAdd(this, _controller), __privateAdd(this, _parser), __privateAdd(this, _onError, null), __privateAdd(this, _onMessage, null), __privateAdd(this, _onOpen, null), __privateAdd(this, _onFetchResponse, async (response) => { - var _a2; - __privateGet(this, _parser).reset(); - const { body, redirected, status, headers } = response; - if (status === 204) { - __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close(); - return; - } - if (redirected ? __privateSet(this, _redirectUrl, new URL(response.url)) : __privateSet(this, _redirectUrl, void 0), status !== 200) { - __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status); - return; - } - if (!(headers.get("content-type") || "").startsWith("text/event-stream")) { - __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, 'Invalid content type, expected "text/event-stream"', status); - return; - } - if (__privateGet(this, _readyState) === this.CLOSED) - return; - __privateSet(this, _readyState, this.OPEN); - const openEvent = new Event("open"); - if ((_a2 = __privateGet(this, _onOpen)) == null || _a2.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != "object" || !body || !("getReader" in body)) { - __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close(); - return; - } - const decoder = new TextDecoder(), reader = body.getReader(); - let open = !0; - do { - const { done, value } = await reader.read(); - value && __privateGet(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open = !1, __privateGet(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this)); - } while (open); - }), __privateAdd(this, _onFetchError, (err) => { - __privateSet(this, _controller, void 0), !(err.name === "AbortError" || err.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError(err)); - }), __privateAdd(this, _onEvent, (event) => { - typeof event.id == "string" && __privateSet(this, _lastEventId, event.id); - const messageEvent = new MessageEvent(event.event || "message", { - data: event.data, - origin: __privateGet(this, _redirectUrl) ? __privateGet(this, _redirectUrl).origin : __privateGet(this, _url).origin, - lastEventId: event.id || "" - }); - __privateGet(this, _onMessage) && (!event.event || event.event === "message") && __privateGet(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent); - }), __privateAdd(this, _onRetryChange, (value) => { - __privateSet(this, _reconnectInterval, value); - }), __privateAdd(this, _reconnect, () => { - __privateSet(this, _reconnectTimer, void 0), __privateGet(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this); - }); - try { - if (url instanceof URL) - __privateSet(this, _url, url); - else if (typeof url == "string") - __privateSet(this, _url, new URL(url, getBaseURL())); - else - throw new Error("Invalid URL"); - } catch { - throw syntaxError("An invalid or illegal string was specified"); - } - __privateSet(this, _parser, createParser({ - onEvent: __privateGet(this, _onEvent), - onRetry: __privateGet(this, _onRetryChange) - })), __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _reconnectInterval, 3e3), __privateSet(this, _fetch, (_a = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a : globalThis.fetch), __privateSet(this, _withCredentials, (_b = eventSourceInitDict == null ? void 0 : eventSourceInitDict.withCredentials) != null ? _b : !1), __privateMethod(this, _EventSource_instances, connect_fn).call(this); - } - /** - * Returns the state of this EventSource object's connection. It can have the values described below. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState) - * - * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface, - * defined in the TypeScript `dom` library. - * - * @public - */ - get readyState() { - return __privateGet(this, _readyState); - } - /** - * Returns the URL providing the event stream. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url) - * - * @public - */ - get url() { - return __privateGet(this, _url).href; - } - /** - * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials) - */ - get withCredentials() { - return __privateGet(this, _withCredentials); - } - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */ - get onerror() { - return __privateGet(this, _onError); - } - set onerror(value) { - __privateSet(this, _onError, value); - } - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */ - get onmessage() { - return __privateGet(this, _onMessage); - } - set onmessage(value) { - __privateSet(this, _onMessage, value); - } - /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */ - get onopen() { - return __privateGet(this, _onOpen); - } - set onopen(value) { - __privateSet(this, _onOpen, value); - } - addEventListener(type, listener, options) { - const listen = listener; - super.addEventListener(type, listen, options); - } - removeEventListener(type, listener, options) { - const listen = listener; - super.removeEventListener(type, listen, options); - } - /** - * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED. - * - * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close) - * - * @public - */ - close() { - __privateGet(this, _reconnectTimer) && clearTimeout(__privateGet(this, _reconnectTimer)), __privateGet(this, _readyState) !== this.CLOSED && (__privateGet(this, _controller) && __privateGet(this, _controller).abort(), __privateSet(this, _readyState, this.CLOSED), __privateSet(this, _controller, void 0)); - } -} -_readyState = /* @__PURE__ */ new WeakMap(), _url = /* @__PURE__ */ new WeakMap(), _redirectUrl = /* @__PURE__ */ new WeakMap(), _withCredentials = /* @__PURE__ */ new WeakMap(), _fetch = /* @__PURE__ */ new WeakMap(), _reconnectInterval = /* @__PURE__ */ new WeakMap(), _reconnectTimer = /* @__PURE__ */ new WeakMap(), _lastEventId = /* @__PURE__ */ new WeakMap(), _controller = /* @__PURE__ */ new WeakMap(), _parser = /* @__PURE__ */ new WeakMap(), _onError = /* @__PURE__ */ new WeakMap(), _onMessage = /* @__PURE__ */ new WeakMap(), _onOpen = /* @__PURE__ */ new WeakMap(), _EventSource_instances = /* @__PURE__ */ new WeakSet(), /** -* Connect to the given URL and start receiving events -* -* @internal -*/ -connect_fn = function() { - __privateSet(this, _readyState, this.CONNECTING), __privateSet(this, _controller, new AbortController()), __privateGet(this, _fetch)(__privateGet(this, _url), __privateMethod(this, _EventSource_instances, getRequestOptions_fn).call(this)).then(__privateGet(this, _onFetchResponse)).catch(__privateGet(this, _onFetchError)); -}, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), /** -* Get request options for the `fetch()` request -* -* @returns The request options -* @internal -*/ -getRequestOptions_fn = function() { - var _a; - const init = { - // [spec] Let `corsAttributeState` be `Anonymous`… - // [spec] …will have their mode set to "cors"… - mode: "cors", - redirect: "follow", - headers: { Accept: "text/event-stream", ...__privateGet(this, _lastEventId) ? { "Last-Event-ID": __privateGet(this, _lastEventId) } : void 0 }, - cache: "no-store", - signal: (_a = __privateGet(this, _controller)) == null ? void 0 : _a.signal - }; - return "window" in globalThis && (init.credentials = this.withCredentials ? "include" : "same-origin"), init; -}, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), /** -* Handles the process referred to in the EventSource specification as "failing a connection". -* -* @param error - The error causing the connection to fail -* @param code - The HTTP status code, if available -* @internal -*/ -failConnection_fn = function(message, code) { - var _a; - __privateGet(this, _readyState) !== this.CLOSED && __privateSet(this, _readyState, this.CLOSED); - const errorEvent = new ErrorEvent("error", { code, message }); - (_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent); -}, /** -* Schedules a reconnection attempt against the EventSource endpoint. -* -* @param message - The error causing the connection to fail -* @param code - The HTTP status code, if available -* @internal -*/ -scheduleReconnect_fn = function(message, code) { - var _a; - if (__privateGet(this, _readyState) === this.CLOSED) - return; - __privateSet(this, _readyState, this.CONNECTING); - const errorEvent = new ErrorEvent("error", { code, message }); - (_a = __privateGet(this, _onError)) == null || _a.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet(this, _reconnectTimer, setTimeout(__privateGet(this, _reconnect), __privateGet(this, _reconnectInterval))); -}, _reconnect = /* @__PURE__ */ new WeakMap(), /** -* ReadyState representing an EventSource currently trying to connect -* -* @public -*/ -EventSource.CONNECTING = 0, /** -* ReadyState representing an EventSource connection that is open (eg connected) -* -* @public -*/ -EventSource.OPEN = 1, /** -* ReadyState representing an EventSource connection that is closed (eg disconnected) -* -* @public -*/ -EventSource.CLOSED = 2; -function getBaseURL() { - const doc = "document" in globalThis ? globalThis.document : void 0; - return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0; -} -export { - ErrorEvent, - EventSource -}; -//# sourceMappingURL=index.js.map diff --git a/claude-code-source/node_modules/execa/index.js b/claude-code-source/node_modules/execa/index.js deleted file mode 100644 index fa417620..00000000 --- a/claude-code-source/node_modules/execa/index.js +++ /dev/null @@ -1,309 +0,0 @@ -import {Buffer} from 'node:buffer'; -import path from 'node:path'; -import childProcess from 'node:child_process'; -import process from 'node:process'; -import crossSpawn from 'cross-spawn'; -import stripFinalNewline from 'strip-final-newline'; -import {npmRunPathEnv} from 'npm-run-path'; -import onetime from 'onetime'; -import {makeError} from './lib/error.js'; -import {normalizeStdio, normalizeStdioNode} from './lib/stdio.js'; -import {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} from './lib/kill.js'; -import {addPipeMethods} from './lib/pipe.js'; -import {handleInput, getSpawnedResult, makeAllStream, handleInputSync} from './lib/stream.js'; -import {mergePromise, getSpawnedPromise} from './lib/promise.js'; -import {joinCommand, parseCommand, parseTemplates, getEscapedCommand} from './lib/command.js'; -import {logCommand, verboseDefault} from './lib/verbose.js'; - -const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100; - -const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => { - const env = extendEnv ? {...process.env, ...envOption} : envOption; - - if (preferLocal) { - return npmRunPathEnv({env, cwd: localDir, execPath}); - } - - return env; -}; - -const handleArguments = (file, args, options = {}) => { - const parsed = crossSpawn._parse(file, args, options); - file = parsed.command; - args = parsed.args; - options = parsed.options; - - options = { - maxBuffer: DEFAULT_MAX_BUFFER, - buffer: true, - stripFinalNewline: true, - extendEnv: true, - preferLocal: false, - localDir: options.cwd || process.cwd(), - execPath: process.execPath, - encoding: 'utf8', - reject: true, - cleanup: true, - all: false, - windowsHide: true, - verbose: verboseDefault, - ...options, - }; - - options.env = getEnv(options); - - options.stdio = normalizeStdio(options); - - if (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') { - // #116 - args.unshift('/q'); - } - - return {file, args, options, parsed}; -}; - -const handleOutput = (options, value, error) => { - if (typeof value !== 'string' && !Buffer.isBuffer(value)) { - // When `execaSync()` errors, we normalize it to '' to mimic `execa()` - return error === undefined ? undefined : ''; - } - - if (options.stripFinalNewline) { - return stripFinalNewline(value); - } - - return value; -}; - -export function execa(file, args, options) { - const parsed = handleArguments(file, args, options); - const command = joinCommand(file, args); - const escapedCommand = getEscapedCommand(file, args); - logCommand(escapedCommand, parsed.options); - - validateTimeout(parsed.options); - - let spawned; - try { - spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options); - } catch (error) { - // Ensure the returned error is always both a promise and a child process - const dummySpawned = new childProcess.ChildProcess(); - const errorPromise = Promise.reject(makeError({ - error, - stdout: '', - stderr: '', - all: '', - command, - escapedCommand, - parsed, - timedOut: false, - isCanceled: false, - killed: false, - })); - mergePromise(dummySpawned, errorPromise); - return dummySpawned; - } - - const spawnedPromise = getSpawnedPromise(spawned); - const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise); - const processDone = setExitHandler(spawned, parsed.options, timedPromise); - - const context = {isCanceled: false}; - - spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned)); - spawned.cancel = spawnedCancel.bind(null, spawned, context); - - const handlePromise = async () => { - const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone); - const stdout = handleOutput(parsed.options, stdoutResult); - const stderr = handleOutput(parsed.options, stderrResult); - const all = handleOutput(parsed.options, allResult); - - if (error || exitCode !== 0 || signal !== null) { - const returnedError = makeError({ - error, - exitCode, - signal, - stdout, - stderr, - all, - command, - escapedCommand, - parsed, - timedOut, - isCanceled: context.isCanceled || (parsed.options.signal ? parsed.options.signal.aborted : false), - killed: spawned.killed, - }); - - if (!parsed.options.reject) { - return returnedError; - } - - throw returnedError; - } - - return { - command, - escapedCommand, - exitCode: 0, - stdout, - stderr, - all, - failed: false, - timedOut: false, - isCanceled: false, - killed: false, - }; - }; - - const handlePromiseOnce = onetime(handlePromise); - - handleInput(spawned, parsed.options); - - spawned.all = makeAllStream(spawned, parsed.options); - - addPipeMethods(spawned); - mergePromise(spawned, handlePromiseOnce); - return spawned; -} - -export function execaSync(file, args, options) { - const parsed = handleArguments(file, args, options); - const command = joinCommand(file, args); - const escapedCommand = getEscapedCommand(file, args); - logCommand(escapedCommand, parsed.options); - - const input = handleInputSync(parsed.options); - - let result; - try { - result = childProcess.spawnSync(parsed.file, parsed.args, {...parsed.options, input}); - } catch (error) { - throw makeError({ - error, - stdout: '', - stderr: '', - all: '', - command, - escapedCommand, - parsed, - timedOut: false, - isCanceled: false, - killed: false, - }); - } - - const stdout = handleOutput(parsed.options, result.stdout, result.error); - const stderr = handleOutput(parsed.options, result.stderr, result.error); - - if (result.error || result.status !== 0 || result.signal !== null) { - const error = makeError({ - stdout, - stderr, - error: result.error, - signal: result.signal, - exitCode: result.status, - command, - escapedCommand, - parsed, - timedOut: result.error && result.error.code === 'ETIMEDOUT', - isCanceled: false, - killed: result.signal !== null, - }); - - if (!parsed.options.reject) { - return error; - } - - throw error; - } - - return { - command, - escapedCommand, - exitCode: 0, - stdout, - stderr, - failed: false, - timedOut: false, - isCanceled: false, - killed: false, - }; -} - -const normalizeScriptStdin = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined - ? {stdin: 'inherit'} - : {}; - -const normalizeScriptOptions = (options = {}) => ({ - preferLocal: true, - ...normalizeScriptStdin(options), - ...options, -}); - -function create$(options) { - function $(templatesOrOptions, ...expressions) { - if (!Array.isArray(templatesOrOptions)) { - return create$({...options, ...templatesOrOptions}); - } - - const [file, ...args] = parseTemplates(templatesOrOptions, expressions); - return execa(file, args, normalizeScriptOptions(options)); - } - - $.sync = (templates, ...expressions) => { - if (!Array.isArray(templates)) { - throw new TypeError('Please use $(options).sync`command` instead of $.sync(options)`command`.'); - } - - const [file, ...args] = parseTemplates(templates, expressions); - return execaSync(file, args, normalizeScriptOptions(options)); - }; - - return $; -} - -export const $ = create$(); - -export function execaCommand(command, options) { - const [file, ...args] = parseCommand(command); - return execa(file, args, options); -} - -export function execaCommandSync(command, options) { - const [file, ...args] = parseCommand(command); - return execaSync(file, args, options); -} - -export function execaNode(scriptPath, args, options = {}) { - if (args && !Array.isArray(args) && typeof args === 'object') { - options = args; - args = []; - } - - const stdio = normalizeStdioNode(options); - const defaultExecArgv = process.execArgv.filter(arg => !arg.startsWith('--inspect')); - - const { - nodePath = process.execPath, - nodeOptions = defaultExecArgv, - } = options; - - return execa( - nodePath, - [ - ...nodeOptions, - scriptPath, - ...(Array.isArray(args) ? args : []), - ], - { - ...options, - stdin: undefined, - stdout: undefined, - stderr: undefined, - stdio, - shell: false, - }, - ); -} diff --git a/claude-code-source/node_modules/execa/lib/command.js b/claude-code-source/node_modules/execa/lib/command.js deleted file mode 100644 index 727ce5f5..00000000 --- a/claude-code-source/node_modules/execa/lib/command.js +++ /dev/null @@ -1,119 +0,0 @@ -import {Buffer} from 'node:buffer'; -import {ChildProcess} from 'node:child_process'; - -const normalizeArgs = (file, args = []) => { - if (!Array.isArray(args)) { - return [file]; - } - - return [file, ...args]; -}; - -const NO_ESCAPE_REGEXP = /^[\w.-]+$/; - -const escapeArg = arg => { - if (typeof arg !== 'string' || NO_ESCAPE_REGEXP.test(arg)) { - return arg; - } - - return `"${arg.replaceAll('"', '\\"')}"`; -}; - -export const joinCommand = (file, args) => normalizeArgs(file, args).join(' '); - -export const getEscapedCommand = (file, args) => normalizeArgs(file, args).map(arg => escapeArg(arg)).join(' '); - -const SPACES_REGEXP = / +/g; - -// Handle `execaCommand()` -export const parseCommand = command => { - const tokens = []; - for (const token of command.trim().split(SPACES_REGEXP)) { - // Allow spaces to be escaped by a backslash if not meant as a delimiter - const previousToken = tokens.at(-1); - if (previousToken && previousToken.endsWith('\\')) { - // Merge previous token with current one - tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`; - } else { - tokens.push(token); - } - } - - return tokens; -}; - -const parseExpression = expression => { - const typeOfExpression = typeof expression; - - if (typeOfExpression === 'string') { - return expression; - } - - if (typeOfExpression === 'number') { - return String(expression); - } - - if ( - typeOfExpression === 'object' - && expression !== null - && !(expression instanceof ChildProcess) - && 'stdout' in expression - ) { - const typeOfStdout = typeof expression.stdout; - - if (typeOfStdout === 'string') { - return expression.stdout; - } - - if (Buffer.isBuffer(expression.stdout)) { - return expression.stdout.toString(); - } - - throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`); - } - - throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`); -}; - -const concatTokens = (tokens, nextTokens, isNew) => isNew || tokens.length === 0 || nextTokens.length === 0 - ? [...tokens, ...nextTokens] - : [ - ...tokens.slice(0, -1), - `${tokens.at(-1)}${nextTokens[0]}`, - ...nextTokens.slice(1), - ]; - -const parseTemplate = ({templates, expressions, tokens, index, template}) => { - const templateString = template ?? templates.raw[index]; - const templateTokens = templateString.split(SPACES_REGEXP).filter(Boolean); - const newTokens = concatTokens( - tokens, - templateTokens, - templateString.startsWith(' '), - ); - - if (index === expressions.length) { - return newTokens; - } - - const expression = expressions[index]; - const expressionTokens = Array.isArray(expression) - ? expression.map(expression => parseExpression(expression)) - : [parseExpression(expression)]; - return concatTokens( - newTokens, - expressionTokens, - templateString.endsWith(' '), - ); -}; - -export const parseTemplates = (templates, expressions) => { - let tokens = []; - - for (const [index, template] of templates.entries()) { - tokens = parseTemplate({templates, expressions, tokens, index, template}); - } - - return tokens; -}; - diff --git a/claude-code-source/node_modules/execa/lib/error.js b/claude-code-source/node_modules/execa/lib/error.js deleted file mode 100644 index 5e80c527..00000000 --- a/claude-code-source/node_modules/execa/lib/error.js +++ /dev/null @@ -1,87 +0,0 @@ -import process from 'node:process'; -import {signalsByName} from 'human-signals'; - -const getErrorPrefix = ({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}) => { - if (timedOut) { - return `timed out after ${timeout} milliseconds`; - } - - if (isCanceled) { - return 'was canceled'; - } - - if (errorCode !== undefined) { - return `failed with ${errorCode}`; - } - - if (signal !== undefined) { - return `was killed with ${signal} (${signalDescription})`; - } - - if (exitCode !== undefined) { - return `failed with exit code ${exitCode}`; - } - - return 'failed'; -}; - -export const makeError = ({ - stdout, - stderr, - all, - error, - signal, - exitCode, - command, - escapedCommand, - timedOut, - isCanceled, - killed, - parsed: {options: {timeout, cwd = process.cwd()}}, -}) => { - // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`. - // We normalize them to `undefined` - exitCode = exitCode === null ? undefined : exitCode; - signal = signal === null ? undefined : signal; - const signalDescription = signal === undefined ? undefined : signalsByName[signal].description; - - const errorCode = error && error.code; - - const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled}); - const execaMessage = `Command ${prefix}: ${command}`; - const isError = Object.prototype.toString.call(error) === '[object Error]'; - const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage; - const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n'); - - if (isError) { - error.originalMessage = error.message; - error.message = message; - } else { - error = new Error(message); - } - - error.shortMessage = shortMessage; - error.command = command; - error.escapedCommand = escapedCommand; - error.exitCode = exitCode; - error.signal = signal; - error.signalDescription = signalDescription; - error.stdout = stdout; - error.stderr = stderr; - error.cwd = cwd; - - if (all !== undefined) { - error.all = all; - } - - if ('bufferedData' in error) { - delete error.bufferedData; - } - - error.failed = true; - error.timedOut = Boolean(timedOut); - error.isCanceled = isCanceled; - error.killed = killed && !timedOut; - - return error; -}; diff --git a/claude-code-source/node_modules/execa/lib/kill.js b/claude-code-source/node_modules/execa/lib/kill.js deleted file mode 100644 index 12ce0a1c..00000000 --- a/claude-code-source/node_modules/execa/lib/kill.js +++ /dev/null @@ -1,102 +0,0 @@ -import os from 'node:os'; -import {onExit} from 'signal-exit'; - -const DEFAULT_FORCE_KILL_TIMEOUT = 1000 * 5; - -// Monkey-patches `childProcess.kill()` to add `forceKillAfterTimeout` behavior -export const spawnedKill = (kill, signal = 'SIGTERM', options = {}) => { - const killResult = kill(signal); - setKillTimeout(kill, signal, options, killResult); - return killResult; -}; - -const setKillTimeout = (kill, signal, options, killResult) => { - if (!shouldForceKill(signal, options, killResult)) { - return; - } - - const timeout = getForceKillAfterTimeout(options); - const t = setTimeout(() => { - kill('SIGKILL'); - }, timeout); - - // Guarded because there's no `.unref()` when `execa` is used in the renderer - // process in Electron. This cannot be tested since we don't run tests in - // Electron. - // istanbul ignore else - if (t.unref) { - t.unref(); - } -}; - -const shouldForceKill = (signal, {forceKillAfterTimeout}, killResult) => isSigterm(signal) && forceKillAfterTimeout !== false && killResult; - -const isSigterm = signal => signal === os.constants.signals.SIGTERM - || (typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM'); - -const getForceKillAfterTimeout = ({forceKillAfterTimeout = true}) => { - if (forceKillAfterTimeout === true) { - return DEFAULT_FORCE_KILL_TIMEOUT; - } - - if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) { - throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`); - } - - return forceKillAfterTimeout; -}; - -// `childProcess.cancel()` -export const spawnedCancel = (spawned, context) => { - const killResult = spawned.kill(); - - if (killResult) { - context.isCanceled = true; - } -}; - -const timeoutKill = (spawned, signal, reject) => { - spawned.kill(signal); - reject(Object.assign(new Error('Timed out'), {timedOut: true, signal})); -}; - -// `timeout` option handling -export const setupTimeout = (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => { - if (timeout === 0 || timeout === undefined) { - return spawnedPromise; - } - - let timeoutId; - const timeoutPromise = new Promise((resolve, reject) => { - timeoutId = setTimeout(() => { - timeoutKill(spawned, killSignal, reject); - }, timeout); - }); - - const safeSpawnedPromise = spawnedPromise.finally(() => { - clearTimeout(timeoutId); - }); - - return Promise.race([timeoutPromise, safeSpawnedPromise]); -}; - -export const validateTimeout = ({timeout}) => { - if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) { - throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`); - } -}; - -// `cleanup` option handling -export const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => { - if (!cleanup || detached) { - return timedPromise; - } - - const removeExitHandler = onExit(() => { - spawned.kill(); - }); - - return timedPromise.finally(() => { - removeExitHandler(); - }); -}; diff --git a/claude-code-source/node_modules/execa/lib/pipe.js b/claude-code-source/node_modules/execa/lib/pipe.js deleted file mode 100644 index e73ffcc9..00000000 --- a/claude-code-source/node_modules/execa/lib/pipe.js +++ /dev/null @@ -1,42 +0,0 @@ -import {createWriteStream} from 'node:fs'; -import {ChildProcess} from 'node:child_process'; -import {isWritableStream} from 'is-stream'; - -const isExecaChildProcess = target => target instanceof ChildProcess && typeof target.then === 'function'; - -const pipeToTarget = (spawned, streamName, target) => { - if (typeof target === 'string') { - spawned[streamName].pipe(createWriteStream(target)); - return spawned; - } - - if (isWritableStream(target)) { - spawned[streamName].pipe(target); - return spawned; - } - - if (!isExecaChildProcess(target)) { - throw new TypeError('The second argument must be a string, a stream or an Execa child process.'); - } - - if (!isWritableStream(target.stdin)) { - throw new TypeError('The target child process\'s stdin must be available.'); - } - - spawned[streamName].pipe(target.stdin); - return target; -}; - -export const addPipeMethods = spawned => { - if (spawned.stdout !== null) { - spawned.pipeStdout = pipeToTarget.bind(undefined, spawned, 'stdout'); - } - - if (spawned.stderr !== null) { - spawned.pipeStderr = pipeToTarget.bind(undefined, spawned, 'stderr'); - } - - if (spawned.all !== undefined) { - spawned.pipeAll = pipeToTarget.bind(undefined, spawned, 'all'); - } -}; diff --git a/claude-code-source/node_modules/execa/lib/promise.js b/claude-code-source/node_modules/execa/lib/promise.js deleted file mode 100644 index a4773f30..00000000 --- a/claude-code-source/node_modules/execa/lib/promise.js +++ /dev/null @@ -1,36 +0,0 @@ -// eslint-disable-next-line unicorn/prefer-top-level-await -const nativePromisePrototype = (async () => {})().constructor.prototype; - -const descriptors = ['then', 'catch', 'finally'].map(property => [ - property, - Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property), -]); - -// The return value is a mixin of `childProcess` and `Promise` -export const mergePromise = (spawned, promise) => { - for (const [property, descriptor] of descriptors) { - // Starting the main `promise` is deferred to avoid consuming streams - const value = typeof promise === 'function' - ? (...args) => Reflect.apply(descriptor.value, promise(), args) - : descriptor.value.bind(promise); - - Reflect.defineProperty(spawned, property, {...descriptor, value}); - } -}; - -// Use promises instead of `child_process` events -export const getSpawnedPromise = spawned => new Promise((resolve, reject) => { - spawned.on('exit', (exitCode, signal) => { - resolve({exitCode, signal}); - }); - - spawned.on('error', error => { - reject(error); - }); - - if (spawned.stdin) { - spawned.stdin.on('error', error => { - reject(error); - }); - } -}); diff --git a/claude-code-source/node_modules/execa/lib/stdio.js b/claude-code-source/node_modules/execa/lib/stdio.js deleted file mode 100644 index e8c1132d..00000000 --- a/claude-code-source/node_modules/execa/lib/stdio.js +++ /dev/null @@ -1,49 +0,0 @@ -const aliases = ['stdin', 'stdout', 'stderr']; - -const hasAlias = options => aliases.some(alias => options[alias] !== undefined); - -export const normalizeStdio = options => { - if (!options) { - return; - } - - const {stdio} = options; - - if (stdio === undefined) { - return aliases.map(alias => options[alias]); - } - - if (hasAlias(options)) { - throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`); - } - - if (typeof stdio === 'string') { - return stdio; - } - - if (!Array.isArray(stdio)) { - throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``); - } - - const length = Math.max(stdio.length, aliases.length); - return Array.from({length}, (value, index) => stdio[index]); -}; - -// `ipc` is pushed unless it is already present -export const normalizeStdioNode = options => { - const stdio = normalizeStdio(options); - - if (stdio === 'ipc') { - return 'ipc'; - } - - if (stdio === undefined || typeof stdio === 'string') { - return [stdio, stdio, stdio, 'ipc']; - } - - if (stdio.includes('ipc')) { - return stdio; - } - - return [...stdio, 'ipc']; -}; diff --git a/claude-code-source/node_modules/execa/lib/stream.js b/claude-code-source/node_modules/execa/lib/stream.js deleted file mode 100644 index 4e064592..00000000 --- a/claude-code-source/node_modules/execa/lib/stream.js +++ /dev/null @@ -1,133 +0,0 @@ -import {createReadStream, readFileSync} from 'node:fs'; -import {setTimeout} from 'node:timers/promises'; -import {isStream} from 'is-stream'; -import getStream, {getStreamAsBuffer} from 'get-stream'; -import mergeStream from 'merge-stream'; - -const validateInputOptions = input => { - if (input !== undefined) { - throw new TypeError('The `input` and `inputFile` options cannot be both set.'); - } -}; - -const getInputSync = ({input, inputFile}) => { - if (typeof inputFile !== 'string') { - return input; - } - - validateInputOptions(input); - return readFileSync(inputFile); -}; - -// `input` and `inputFile` option in sync mode -export const handleInputSync = options => { - const input = getInputSync(options); - - if (isStream(input)) { - throw new TypeError('The `input` option cannot be a stream in sync mode'); - } - - return input; -}; - -const getInput = ({input, inputFile}) => { - if (typeof inputFile !== 'string') { - return input; - } - - validateInputOptions(input); - return createReadStream(inputFile); -}; - -// `input` and `inputFile` option in async mode -export const handleInput = (spawned, options) => { - const input = getInput(options); - - if (input === undefined) { - return; - } - - if (isStream(input)) { - input.pipe(spawned.stdin); - } else { - spawned.stdin.end(input); - } -}; - -// `all` interleaves `stdout` and `stderr` -export const makeAllStream = (spawned, {all}) => { - if (!all || (!spawned.stdout && !spawned.stderr)) { - return; - } - - const mixed = mergeStream(); - - if (spawned.stdout) { - mixed.add(spawned.stdout); - } - - if (spawned.stderr) { - mixed.add(spawned.stderr); - } - - return mixed; -}; - -// On failure, `result.stdout|stderr|all` should contain the currently buffered stream -const getBufferedData = async (stream, streamPromise) => { - // When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve - if (!stream || streamPromise === undefined) { - return; - } - - // Wait for the `all` stream to receive the last chunk before destroying the stream - await setTimeout(0); - - stream.destroy(); - - try { - return await streamPromise; - } catch (error) { - return error.bufferedData; - } -}; - -const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => { - if (!stream || !buffer) { - return; - } - - // eslint-disable-next-line unicorn/text-encoding-identifier-case - if (encoding === 'utf8' || encoding === 'utf-8') { - return getStream(stream, {maxBuffer}); - } - - if (encoding === null || encoding === 'buffer') { - return getStreamAsBuffer(stream, {maxBuffer}); - } - - return applyEncoding(stream, maxBuffer, encoding); -}; - -const applyEncoding = async (stream, maxBuffer, encoding) => { - const buffer = await getStreamAsBuffer(stream, {maxBuffer}); - return buffer.toString(encoding); -}; - -// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all) -export const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => { - const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer}); - const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer}); - const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2}); - - try { - return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]); - } catch (error) { - return Promise.all([ - {error, signal: error.signal, timedOut: error.timedOut}, - getBufferedData(stdout, stdoutPromise), - getBufferedData(stderr, stderrPromise), - getBufferedData(all, allPromise), - ]); - } -}; diff --git a/claude-code-source/node_modules/execa/lib/verbose.js b/claude-code-source/node_modules/execa/lib/verbose.js deleted file mode 100644 index 5f5490ed..00000000 --- a/claude-code-source/node_modules/execa/lib/verbose.js +++ /dev/null @@ -1,19 +0,0 @@ -import {debuglog} from 'node:util'; -import process from 'node:process'; - -export const verboseDefault = debuglog('execa').enabled; - -const padField = (field, padding) => String(field).padStart(padding, '0'); - -const getTimestamp = () => { - const date = new Date(); - return `${padField(date.getHours(), 2)}:${padField(date.getMinutes(), 2)}:${padField(date.getSeconds(), 2)}.${padField(date.getMilliseconds(), 3)}`; -}; - -export const logCommand = (escapedCommand, {verbose}) => { - if (!verbose) { - return; - } - - process.stderr.write(`[${getTimestamp()}] ${escapedCommand}\n`); -}; diff --git a/claude-code-source/node_modules/extend/index.js b/claude-code-source/node_modules/extend/index.js deleted file mode 100644 index 2aa3faae..00000000 --- a/claude-code-source/node_modules/extend/index.js +++ /dev/null @@ -1,117 +0,0 @@ -'use strict'; - -var hasOwn = Object.prototype.hasOwnProperty; -var toStr = Object.prototype.toString; -var defineProperty = Object.defineProperty; -var gOPD = Object.getOwnPropertyDescriptor; - -var isArray = function isArray(arr) { - if (typeof Array.isArray === 'function') { - return Array.isArray(arr); - } - - return toStr.call(arr) === '[object Array]'; -}; - -var isPlainObject = function isPlainObject(obj) { - if (!obj || toStr.call(obj) !== '[object Object]') { - return false; - } - - var hasOwnConstructor = hasOwn.call(obj, 'constructor'); - var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); - // Not own constructor property must be Object - if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { - return false; - } - - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - var key; - for (key in obj) { /**/ } - - return typeof key === 'undefined' || hasOwn.call(obj, key); -}; - -// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target -var setProperty = function setProperty(target, options) { - if (defineProperty && options.name === '__proto__') { - defineProperty(target, options.name, { - enumerable: true, - configurable: true, - value: options.newValue, - writable: true - }); - } else { - target[options.name] = options.newValue; - } -}; - -// Return undefined instead of __proto__ if '__proto__' is not an own property -var getProperty = function getProperty(obj, name) { - if (name === '__proto__') { - if (!hasOwn.call(obj, name)) { - return void 0; - } else if (gOPD) { - // In early versions of node, obj['__proto__'] is buggy when obj has - // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. - return gOPD(obj, name).value; - } - } - - return obj[name]; -}; - -module.exports = function extend() { - var options, name, src, copy, copyIsArray, clone; - var target = arguments[0]; - var i = 1; - var length = arguments.length; - var deep = false; - - // Handle a deep copy situation - if (typeof target === 'boolean') { - deep = target; - target = arguments[1] || {}; - // skip the boolean and the target - i = 2; - } - if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { - target = {}; - } - - for (; i < length; ++i) { - options = arguments[i]; - // Only deal with non-null/undefined values - if (options != null) { - // Extend the base object - for (name in options) { - src = getProperty(target, name); - copy = getProperty(options, name); - - // Prevent never-ending loop - if (target !== copy) { - // Recurse if we're merging plain objects or arrays - if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { - if (copyIsArray) { - copyIsArray = false; - clone = src && isArray(src) ? src : []; - } else { - clone = src && isPlainObject(src) ? src : {}; - } - - // Never move original objects, clone them - setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); - - // Don't bring in undefined values - } else if (typeof copy !== 'undefined') { - setProperty(target, { name: name, newValue: copy }); - } - } - } - } - } - - // Return the modified object - return target; -}; diff --git a/claude-code-source/node_modules/fast-deep-equal/index.js b/claude-code-source/node_modules/fast-deep-equal/index.js deleted file mode 100644 index 30dd1ba7..00000000 --- a/claude-code-source/node_modules/fast-deep-equal/index.js +++ /dev/null @@ -1,46 +0,0 @@ -'use strict'; - -// do not edit .js files directly - edit src/index.jst - - - -module.exports = function equal(a, b) { - if (a === b) return true; - - if (a && b && typeof a == 'object' && typeof b == 'object') { - if (a.constructor !== b.constructor) return false; - - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0;) - if (!equal(a[i], b[i])) return false; - return true; - } - - - - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - - for (i = length; i-- !== 0;) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - - for (i = length; i-- !== 0;) { - var key = keys[i]; - - if (!equal(a[key], b[key])) return false; - } - - return true; - } - - // true if both NaN, false otherwise - return a!==a && b!==b; -}; diff --git a/claude-code-source/node_modules/fast-uri/index.js b/claude-code-source/node_modules/fast-uri/index.js deleted file mode 100644 index ab6c477c..00000000 --- a/claude-code-source/node_modules/fast-uri/index.js +++ /dev/null @@ -1,303 +0,0 @@ -'use strict' - -const { normalizeIPv6, normalizeIPv4, removeDotSegments, recomposeAuthority, normalizeComponentEncoding } = require('./lib/utils') -const SCHEMES = require('./lib/schemes') - -function normalize (uri, options) { - if (typeof uri === 'string') { - uri = serialize(parse(uri, options), options) - } else if (typeof uri === 'object') { - uri = parse(serialize(uri, options), options) - } - return uri -} - -function resolve (baseURI, relativeURI, options) { - const schemelessOptions = Object.assign({ scheme: 'null' }, options) - const resolved = resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true) - return serialize(resolved, { ...schemelessOptions, skipEscape: true }) -} - -function resolveComponents (base, relative, options, skipNormalization) { - const target = {} - if (!skipNormalization) { - base = parse(serialize(base, options), options) // normalize base components - relative = parse(serialize(relative, options), options) // normalize relative components - } - options = options || {} - - if (!options.tolerant && relative.scheme) { - target.scheme = relative.scheme - // target.authority = relative.authority; - target.userinfo = relative.userinfo - target.host = relative.host - target.port = relative.port - target.path = removeDotSegments(relative.path || '') - target.query = relative.query - } else { - if (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) { - // target.authority = relative.authority; - target.userinfo = relative.userinfo - target.host = relative.host - target.port = relative.port - target.path = removeDotSegments(relative.path || '') - target.query = relative.query - } else { - if (!relative.path) { - target.path = base.path - if (relative.query !== undefined) { - target.query = relative.query - } else { - target.query = base.query - } - } else { - if (relative.path.charAt(0) === '/') { - target.path = removeDotSegments(relative.path) - } else { - if ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) { - target.path = '/' + relative.path - } else if (!base.path) { - target.path = relative.path - } else { - target.path = base.path.slice(0, base.path.lastIndexOf('/') + 1) + relative.path - } - target.path = removeDotSegments(target.path) - } - target.query = relative.query - } - // target.authority = base.authority; - target.userinfo = base.userinfo - target.host = base.host - target.port = base.port - } - target.scheme = base.scheme - } - - target.fragment = relative.fragment - - return target -} - -function equal (uriA, uriB, options) { - if (typeof uriA === 'string') { - uriA = unescape(uriA) - uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { ...options, skipEscape: true }) - } else if (typeof uriA === 'object') { - uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true }) - } - - if (typeof uriB === 'string') { - uriB = unescape(uriB) - uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { ...options, skipEscape: true }) - } else if (typeof uriB === 'object') { - uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true }) - } - - return uriA.toLowerCase() === uriB.toLowerCase() -} - -function serialize (cmpts, opts) { - const components = { - host: cmpts.host, - scheme: cmpts.scheme, - userinfo: cmpts.userinfo, - port: cmpts.port, - path: cmpts.path, - query: cmpts.query, - nid: cmpts.nid, - nss: cmpts.nss, - uuid: cmpts.uuid, - fragment: cmpts.fragment, - reference: cmpts.reference, - resourceName: cmpts.resourceName, - secure: cmpts.secure, - error: '' - } - const options = Object.assign({}, opts) - const uriTokens = [] - - // find scheme handler - const schemeHandler = SCHEMES[(options.scheme || components.scheme || '').toLowerCase()] - - // perform scheme specific serialization - if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options) - - if (components.path !== undefined) { - if (!options.skipEscape) { - components.path = escape(components.path) - - if (components.scheme !== undefined) { - components.path = components.path.split('%3A').join(':') - } - } else { - components.path = unescape(components.path) - } - } - - if (options.reference !== 'suffix' && components.scheme) { - uriTokens.push(components.scheme, ':') - } - - const authority = recomposeAuthority(components) - if (authority !== undefined) { - if (options.reference !== 'suffix') { - uriTokens.push('//') - } - - uriTokens.push(authority) - - if (components.path && components.path.charAt(0) !== '/') { - uriTokens.push('/') - } - } - if (components.path !== undefined) { - let s = components.path - - if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) { - s = removeDotSegments(s) - } - - if (authority === undefined) { - s = s.replace(/^\/\//u, '/%2F') // don't allow the path to start with "//" - } - - uriTokens.push(s) - } - - if (components.query !== undefined) { - uriTokens.push('?', components.query) - } - - if (components.fragment !== undefined) { - uriTokens.push('#', components.fragment) - } - return uriTokens.join('') -} - -const hexLookUp = Array.from({ length: 127 }, (_v, k) => /[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(k))) - -function nonSimpleDomain (value) { - let code = 0 - for (let i = 0, len = value.length; i < len; ++i) { - code = value.charCodeAt(i) - if (code > 126 || hexLookUp[code]) { - return true - } - } - return false -} - -const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u - -function parse (uri, opts) { - const options = Object.assign({}, opts) - const parsed = { - scheme: undefined, - userinfo: undefined, - host: '', - port: undefined, - path: '', - query: undefined, - fragment: undefined - } - const gotEncoding = uri.indexOf('%') !== -1 - let isIP = false - if (options.reference === 'suffix') uri = (options.scheme ? options.scheme + ':' : '') + '//' + uri - - const matches = uri.match(URI_PARSE) - - if (matches) { - // store each component - parsed.scheme = matches[1] - parsed.userinfo = matches[3] - parsed.host = matches[4] - parsed.port = parseInt(matches[5], 10) - parsed.path = matches[6] || '' - parsed.query = matches[7] - parsed.fragment = matches[8] - - // fix port number - if (isNaN(parsed.port)) { - parsed.port = matches[5] - } - if (parsed.host) { - const ipv4result = normalizeIPv4(parsed.host) - if (ipv4result.isIPV4 === false) { - const ipv6result = normalizeIPv6(ipv4result.host) - parsed.host = ipv6result.host.toLowerCase() - isIP = ipv6result.isIPV6 - } else { - parsed.host = ipv4result.host - isIP = true - } - } - if (parsed.scheme === undefined && parsed.userinfo === undefined && parsed.host === undefined && parsed.port === undefined && parsed.query === undefined && !parsed.path) { - parsed.reference = 'same-document' - } else if (parsed.scheme === undefined) { - parsed.reference = 'relative' - } else if (parsed.fragment === undefined) { - parsed.reference = 'absolute' - } else { - parsed.reference = 'uri' - } - - // check for reference errors - if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) { - parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.' - } - - // find scheme handler - const schemeHandler = SCHEMES[(options.scheme || parsed.scheme || '').toLowerCase()] - - // check if scheme can't handle IRIs - if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { - // if host component is a domain name - if (parsed.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost)) && isIP === false && nonSimpleDomain(parsed.host)) { - // convert Unicode IDN -> ASCII IDN - try { - parsed.host = URL.domainToASCII(parsed.host.toLowerCase()) - } catch (e) { - parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e - } - } - // convert IRI -> URI - } - - if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) { - if (gotEncoding && parsed.scheme !== undefined) { - parsed.scheme = unescape(parsed.scheme) - } - if (gotEncoding && parsed.host !== undefined) { - parsed.host = unescape(parsed.host) - } - if (parsed.path) { - parsed.path = escape(unescape(parsed.path)) - } - if (parsed.fragment) { - parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)) - } - } - - // perform scheme specific parsing - if (schemeHandler && schemeHandler.parse) { - schemeHandler.parse(parsed, options) - } - } else { - parsed.error = parsed.error || 'URI can not be parsed.' - } - return parsed -} - -const fastUri = { - SCHEMES, - normalize, - resolve, - resolveComponents, - equal, - serialize, - parse -} - -module.exports = fastUri -module.exports.default = fastUri -module.exports.fastUri = fastUri diff --git a/claude-code-source/node_modules/fast-uri/lib/schemes.js b/claude-code-source/node_modules/fast-uri/lib/schemes.js deleted file mode 100644 index fe0f91a7..00000000 --- a/claude-code-source/node_modules/fast-uri/lib/schemes.js +++ /dev/null @@ -1,188 +0,0 @@ -'use strict' - -const UUID_REG = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu -const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu - -function isSecure (wsComponents) { - return typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === 'wss' -} - -function httpParse (components) { - if (!components.host) { - components.error = components.error || 'HTTP URIs must have a host.' - } - - return components -} - -function httpSerialize (components) { - const secure = String(components.scheme).toLowerCase() === 'https' - - // normalize the default port - if (components.port === (secure ? 443 : 80) || components.port === '') { - components.port = undefined - } - - // normalize the empty path - if (!components.path) { - components.path = '/' - } - - // NOTE: We do not parse query strings for HTTP URIs - // as WWW Form Url Encoded query strings are part of the HTML4+ spec, - // and not the HTTP spec. - - return components -} - -function wsParse (wsComponents) { -// indicate if the secure flag is set - wsComponents.secure = isSecure(wsComponents) - - // construct resouce name - wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : '') - wsComponents.path = undefined - wsComponents.query = undefined - - return wsComponents -} - -function wsSerialize (wsComponents) { -// normalize the default port - if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === '') { - wsComponents.port = undefined - } - - // ensure scheme matches secure flag - if (typeof wsComponents.secure === 'boolean') { - wsComponents.scheme = (wsComponents.secure ? 'wss' : 'ws') - wsComponents.secure = undefined - } - - // reconstruct path from resource name - if (wsComponents.resourceName) { - const [path, query] = wsComponents.resourceName.split('?') - wsComponents.path = (path && path !== '/' ? path : undefined) - wsComponents.query = query - wsComponents.resourceName = undefined - } - - // forbid fragment component - wsComponents.fragment = undefined - - return wsComponents -} - -function urnParse (urnComponents, options) { - if (!urnComponents.path) { - urnComponents.error = 'URN can not be parsed' - return urnComponents - } - const matches = urnComponents.path.match(URN_REG) - if (matches) { - const scheme = options.scheme || urnComponents.scheme || 'urn' - urnComponents.nid = matches[1].toLowerCase() - urnComponents.nss = matches[2] - const urnScheme = `${scheme}:${options.nid || urnComponents.nid}` - const schemeHandler = SCHEMES[urnScheme] - urnComponents.path = undefined - - if (schemeHandler) { - urnComponents = schemeHandler.parse(urnComponents, options) - } - } else { - urnComponents.error = urnComponents.error || 'URN can not be parsed.' - } - - return urnComponents -} - -function urnSerialize (urnComponents, options) { - const scheme = options.scheme || urnComponents.scheme || 'urn' - const nid = urnComponents.nid.toLowerCase() - const urnScheme = `${scheme}:${options.nid || nid}` - const schemeHandler = SCHEMES[urnScheme] - - if (schemeHandler) { - urnComponents = schemeHandler.serialize(urnComponents, options) - } - - const uriComponents = urnComponents - const nss = urnComponents.nss - uriComponents.path = `${nid || options.nid}:${nss}` - - options.skipEscape = true - return uriComponents -} - -function urnuuidParse (urnComponents, options) { - const uuidComponents = urnComponents - uuidComponents.uuid = uuidComponents.nss - uuidComponents.nss = undefined - - if (!options.tolerant && (!uuidComponents.uuid || !UUID_REG.test(uuidComponents.uuid))) { - uuidComponents.error = uuidComponents.error || 'UUID is not valid.' - } - - return uuidComponents -} - -function urnuuidSerialize (uuidComponents) { - const urnComponents = uuidComponents - // normalize UUID - urnComponents.nss = (uuidComponents.uuid || '').toLowerCase() - return urnComponents -} - -const http = { - scheme: 'http', - domainHost: true, - parse: httpParse, - serialize: httpSerialize -} - -const https = { - scheme: 'https', - domainHost: http.domainHost, - parse: httpParse, - serialize: httpSerialize -} - -const ws = { - scheme: 'ws', - domainHost: true, - parse: wsParse, - serialize: wsSerialize -} - -const wss = { - scheme: 'wss', - domainHost: ws.domainHost, - parse: ws.parse, - serialize: ws.serialize -} - -const urn = { - scheme: 'urn', - parse: urnParse, - serialize: urnSerialize, - skipNormalize: true -} - -const urnuuid = { - scheme: 'urn:uuid', - parse: urnuuidParse, - serialize: urnuuidSerialize, - skipNormalize: true -} - -const SCHEMES = { - http, - https, - ws, - wss, - urn, - 'urn:uuid': urnuuid -} - -module.exports = SCHEMES diff --git a/claude-code-source/node_modules/fast-uri/lib/scopedChars.js b/claude-code-source/node_modules/fast-uri/lib/scopedChars.js deleted file mode 100644 index d4a61103..00000000 --- a/claude-code-source/node_modules/fast-uri/lib/scopedChars.js +++ /dev/null @@ -1,30 +0,0 @@ -'use strict' - -const HEX = { - 0: 0, - 1: 1, - 2: 2, - 3: 3, - 4: 4, - 5: 5, - 6: 6, - 7: 7, - 8: 8, - 9: 9, - a: 10, - A: 10, - b: 11, - B: 11, - c: 12, - C: 12, - d: 13, - D: 13, - e: 14, - E: 14, - f: 15, - F: 15 -} - -module.exports = { - HEX -} diff --git a/claude-code-source/node_modules/fast-uri/lib/utils.js b/claude-code-source/node_modules/fast-uri/lib/utils.js deleted file mode 100644 index 972c1a27..00000000 --- a/claude-code-source/node_modules/fast-uri/lib/utils.js +++ /dev/null @@ -1,244 +0,0 @@ -'use strict' - -const { HEX } = require('./scopedChars') - -const IPV4_REG = /^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u - -function normalizeIPv4 (host) { - if (findToken(host, '.') < 3) { return { host, isIPV4: false } } - const matches = host.match(IPV4_REG) || [] - const [address] = matches - if (address) { - return { host: stripLeadingZeros(address, '.'), isIPV4: true } - } else { - return { host, isIPV4: false } - } -} - -/** - * @param {string[]} input - * @param {boolean} [keepZero=false] - * @returns {string|undefined} - */ -function stringArrayToHexStripped (input, keepZero = false) { - let acc = '' - let strip = true - for (const c of input) { - if (HEX[c] === undefined) return undefined - if (c !== '0' && strip === true) strip = false - if (!strip) acc += c - } - if (keepZero && acc.length === 0) acc = '0' - return acc -} - -function getIPV6 (input) { - let tokenCount = 0 - const output = { error: false, address: '', zone: '' } - const address = [] - const buffer = [] - let isZone = false - let endipv6Encountered = false - let endIpv6 = false - - function consume () { - if (buffer.length) { - if (isZone === false) { - const hex = stringArrayToHexStripped(buffer) - if (hex !== undefined) { - address.push(hex) - } else { - output.error = true - return false - } - } - buffer.length = 0 - } - return true - } - - for (let i = 0; i < input.length; i++) { - const cursor = input[i] - if (cursor === '[' || cursor === ']') { continue } - if (cursor === ':') { - if (endipv6Encountered === true) { - endIpv6 = true - } - if (!consume()) { break } - tokenCount++ - address.push(':') - if (tokenCount > 7) { - // not valid - output.error = true - break - } - if (i - 1 >= 0 && input[i - 1] === ':') { - endipv6Encountered = true - } - continue - } else if (cursor === '%') { - if (!consume()) { break } - // switch to zone detection - isZone = true - } else { - buffer.push(cursor) - continue - } - } - if (buffer.length) { - if (isZone) { - output.zone = buffer.join('') - } else if (endIpv6) { - address.push(buffer.join('')) - } else { - address.push(stringArrayToHexStripped(buffer)) - } - } - output.address = address.join('') - return output -} - -function normalizeIPv6 (host) { - if (findToken(host, ':') < 2) { return { host, isIPV6: false } } - const ipv6 = getIPV6(host) - - if (!ipv6.error) { - let newHost = ipv6.address - let escapedHost = ipv6.address - if (ipv6.zone) { - newHost += '%' + ipv6.zone - escapedHost += '%25' + ipv6.zone - } - return { host: newHost, escapedHost, isIPV6: true } - } else { - return { host, isIPV6: false } - } -} - -function stripLeadingZeros (str, token) { - let out = '' - let skip = true - const l = str.length - for (let i = 0; i < l; i++) { - const c = str[i] - if (c === '0' && skip) { - if ((i + 1 <= l && str[i + 1] === token) || i + 1 === l) { - out += c - skip = false - } - } else { - if (c === token) { - skip = true - } else { - skip = false - } - out += c - } - } - return out -} - -function findToken (str, token) { - let ind = 0 - for (let i = 0; i < str.length; i++) { - if (str[i] === token) ind++ - } - return ind -} - -const RDS1 = /^\.\.?\//u -const RDS2 = /^\/\.(?:\/|$)/u -const RDS3 = /^\/\.\.(?:\/|$)/u -const RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/u - -function removeDotSegments (input) { - const output = [] - - while (input.length) { - if (input.match(RDS1)) { - input = input.replace(RDS1, '') - } else if (input.match(RDS2)) { - input = input.replace(RDS2, '/') - } else if (input.match(RDS3)) { - input = input.replace(RDS3, '/') - output.pop() - } else if (input === '.' || input === '..') { - input = '' - } else { - const im = input.match(RDS5) - if (im) { - const s = im[0] - input = input.slice(s.length) - output.push(s) - } else { - throw new Error('Unexpected dot segment condition') - } - } - } - return output.join('') -} - -function normalizeComponentEncoding (components, esc) { - const func = esc !== true ? escape : unescape - if (components.scheme !== undefined) { - components.scheme = func(components.scheme) - } - if (components.userinfo !== undefined) { - components.userinfo = func(components.userinfo) - } - if (components.host !== undefined) { - components.host = func(components.host) - } - if (components.path !== undefined) { - components.path = func(components.path) - } - if (components.query !== undefined) { - components.query = func(components.query) - } - if (components.fragment !== undefined) { - components.fragment = func(components.fragment) - } - return components -} - -function recomposeAuthority (components) { - const uriTokens = [] - - if (components.userinfo !== undefined) { - uriTokens.push(components.userinfo) - uriTokens.push('@') - } - - if (components.host !== undefined) { - let host = unescape(components.host) - const ipV4res = normalizeIPv4(host) - - if (ipV4res.isIPV4) { - host = ipV4res.host - } else { - const ipV6res = normalizeIPv6(ipV4res.host) - if (ipV6res.isIPV6 === true) { - host = `[${ipV6res.escapedHost}]` - } else { - host = components.host - } - } - uriTokens.push(host) - } - - if (typeof components.port === 'number' || typeof components.port === 'string') { - uriTokens.push(':') - uriTokens.push(String(components.port)) - } - - return uriTokens.length ? uriTokens.join('') : undefined -}; - -module.exports = { - recomposeAuthority, - normalizeComponentEncoding, - removeDotSegments, - normalizeIPv4, - normalizeIPv6, - stringArrayToHexStripped -} diff --git a/claude-code-source/node_modules/fast-xml-parser/lib/fxp.cjs b/claude-code-source/node_modules/fast-xml-parser/lib/fxp.cjs deleted file mode 100644 index 83b9e5cf..00000000 --- a/claude-code-source/node_modules/fast-xml-parser/lib/fxp.cjs +++ /dev/null @@ -1 +0,0 @@ -(()=>{"use strict";var t={d:(e,n)=>{for(var i in n)t.o(n,i)&&!t.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:n[i]})},o:(t,e)=>Object.prototype.hasOwnProperty.call(t,e),r:t=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})}},e={};t.r(e),t.d(e,{XMLBuilder:()=>pt,XMLParser:()=>st,XMLValidator:()=>xt});const n=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",i=new RegExp("^["+n+"]["+n+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$");function s(t,e){const n=[];let i=e.exec(t);for(;i;){const s=[];s.startIndex=e.lastIndex-i[0].length;const r=i.length;for(let t=0;t"!==t[r]&&" "!==t[r]&&"\t"!==t[r]&&"\n"!==t[r]&&"\r"!==t[r];r++)h+=t[r];if(h=h.trim(),"/"===h[h.length-1]&&(h=h.substring(0,h.length-1),r--),!b(h)){let e;return e=0===h.trim().length?"Invalid space after '<'.":"Tag '"+h+"' is an invalid name.",m("InvalidTag",e,N(t,r))}const p=c(t,r);if(!1===p)return m("InvalidAttr","Attributes for '"+h+"' have open quote.",N(t,r));let f=p.value;if(r=p.index,"/"===f[f.length-1]){const n=r-f.length;f=f.substring(0,f.length-1);const s=g(f,e);if(!0!==s)return m(s.err.code,s.err.msg,N(t,n+s.err.line));i=!0}else if(a){if(!p.tagClosed)return m("InvalidTag","Closing tag '"+h+"' doesn't have proper closing.",N(t,r));if(f.trim().length>0)return m("InvalidTag","Closing tag '"+h+"' can't have attributes or invalid starting.",N(t,o));if(0===n.length)return m("InvalidTag","Closing tag '"+h+"' has not been opened.",N(t,o));{const e=n.pop();if(h!==e.tagName){let n=N(t,e.tagStartPos);return m("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+n.line+", col "+n.col+") instead of closing tag '"+h+"'.",N(t,o))}0==n.length&&(s=!0)}}else{const a=g(f,e);if(!0!==a)return m(a.err.code,a.err.msg,N(t,r-f.length+a.err.line));if(!0===s)return m("InvalidXml","Multiple possible root nodes found.",N(t,r));-1!==e.unpairedTags.indexOf(h)||n.push({tagName:h,tagStartPos:o}),i=!0}for(r++;r0)||m("InvalidXml","Invalid '"+JSON.stringify(n.map(t=>t.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):m("InvalidXml","Start tag expected.",1)}function l(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function u(t,e){const n=e;for(;e5&&"xml"===i)return m("InvalidXml","XML declaration allowed only at the start of the document.",N(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}continue}return e}function d(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){let n=1;for(e+=8;e"===t[e]&&(n--,0===n))break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e"===t[e+2]){e+=2;break}return e}const h='"',p="'";function c(t,e){let n="",i="",s=!1;for(;e"===t[e]&&""===i){s=!0;break}n+=t[e]}return""===i&&{value:n,index:e,tagClosed:s}}const f=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function g(t,e){const n=s(t,f),i={};for(let t=0;t!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,n){return t},captureMetaData:!1,maxNestedTags:100,strictReservedNames:!0};function w(t){return"boolean"==typeof t?{enabled:t,maxEntitySize:1e4,maxExpansionDepth:10,maxTotalExpansions:1e3,maxExpandedLength:1e5,allowedTags:null,tagFilter:null}:"object"==typeof t&&null!==t?{enabled:!1!==t.enabled,maxEntitySize:t.maxEntitySize??1e4,maxExpansionDepth:t.maxExpansionDepth??10,maxTotalExpansions:t.maxTotalExpansions??1e3,maxExpandedLength:t.maxExpandedLength??1e5,allowedTags:t.allowedTags??null,tagFilter:t.tagFilter??null}:w(!0)}const v=function(t){const e=Object.assign({},T,t);return e.processEntities=w(e.processEntities),e};let O;O="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class I{constructor(t){this.tagname=t,this.child=[],this[":@"]=Object.create(null)}add(t,e){"__proto__"===t&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){"__proto__"===t.tagname&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),void 0!==e&&(this.child[this.child.length-1][O]={startIndex:e})}static getMetaDataSymbol(){return O}}class P{constructor(t){this.suppressValidationErr=!t,this.options=t}readDocType(t,e){const n=Object.create(null);if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");{e+=9;let i=1,s=!1,r=!1,o="";for(;e"===t[e]){if(r?"-"===t[e-1]&&"-"===t[e-2]&&(r=!1,i--):i--,0===i)break}else"["===t[e]?s=!0:o+=t[e];else{if(s&&S(t,"!ENTITY",e)){let i,s;if(e+=7,[i,s,e]=this.readEntityExp(t,e+1,this.suppressValidationErr),-1===s.indexOf("&")){const t=i.replace(/[.\-+*:]/g,"\\.");n[i]={regx:RegExp(`&${t};`,"g"),val:s}}}else if(s&&S(t,"!ELEMENT",e)){e+=8;const{index:n}=this.readElementExp(t,e+1);e=n}else if(s&&S(t,"!ATTLIST",e))e+=8;else if(s&&S(t,"!NOTATION",e)){e+=9;const{index:n}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=n}else{if(!S(t,"!--",e))throw new Error("Invalid DOCTYPE");r=!0}i++,o=""}if(0!==i)throw new Error("Unclosed DOCTYPE")}return{entities:n,i:e}}readEntityExp(t,e){e=A(t,e);let n="";for(;ethis.options.maxEntitySize)throw new Error(`Entity "${n}" size (${i.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return[n,i,--e]}readNotationExp(t,e){e=A(t,e);let n="";for(;e{for(;e{for(const n of t){if("string"==typeof n&&e===n)return!0;if(n instanceof RegExp&&n.test(e))return!0}}:()=>!1}class F{constructor(t){if(this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(t,e)=>Q(e,10,"&#")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(t,e)=>Q(e,16,"&#x")}},this.addExternalEntities=M,this.parseXml=B,this.parseTextData=k,this.resolveNameSpace=_,this.buildAttributesMap=R,this.isItStopNode=z,this.replaceEntitiesValue=G,this.readStopNodeData=Z,this.saveTextToParentTag=X,this.addChild=Y,this.ignoreAttributesFn=L(this.options.ignoreAttributes),this.entityExpansionCount=0,this.currentExpandedLength=0,this.options.stopNodes&&this.options.stopNodes.length>0){this.stopNodesExact=new Set,this.stopNodesWildcard=new Set;for(let t=0;t0)){o||(t=this.replaceEntitiesValue(t,e,n));const i=this.options.tagValueProcessor(e,t,n,s,r);return null==i?t:typeof i!=typeof t||i!==t?i:this.options.trimValues||t.trim()===t?K(t,this.options.parseTagValue,this.options.numberParseOptions):t}}function _(t){if(this.options.removeNSPrefix){const e=t.split(":"),n="/"===t.charAt(0)?"/":"";if("xmlns"===e[0])return"";2===e.length&&(t=n+e[1])}return t}const U=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function R(t,e,n){if(!0!==this.options.ignoreAttributes&&"string"==typeof t){const i=s(t,U),r=i.length,o={};for(let t=0;t",o,"Closing Tag is not closed.");let r=t.substring(o+2,e).trim();if(this.options.removeNSPrefix){const t=r.indexOf(":");-1!==t&&(r=r.substr(t+1))}this.options.transformTagName&&(r=this.options.transformTagName(r)),n&&(i=this.saveTextToParentTag(i,n,s));const a=s.substring(s.lastIndexOf(".")+1);if(r&&-1!==this.options.unpairedTags.indexOf(r))throw new Error(`Unpaired tag can not be used as closing tag: `);let l=0;a&&-1!==this.options.unpairedTags.indexOf(a)?(l=s.lastIndexOf(".",s.lastIndexOf(".")-1),this.tagsNodeStack.pop()):l=s.lastIndexOf("."),s=s.substring(0,l),n=this.tagsNodeStack.pop(),i="",o=e}else if("?"===t[o+1]){let e=q(t,o,!1,"?>");if(!e)throw new Error("Pi Tag is not closed.");if(i=this.saveTextToParentTag(i,n,s),this.options.ignoreDeclaration&&"?xml"===e.tagName||this.options.ignorePiTags);else{const t=new I(e.tagName);t.add(this.options.textNodeName,""),e.tagName!==e.tagExp&&e.attrExpPresent&&(t[":@"]=this.buildAttributesMap(e.tagExp,s,e.tagName)),this.addChild(n,t,s,o)}o=e.closeIndex+1}else if("!--"===t.substr(o+1,3)){const e=W(t,"--\x3e",o+4,"Comment is not closed.");if(this.options.commentPropName){const r=t.substring(o+4,e-2);i=this.saveTextToParentTag(i,n,s),n.add(this.options.commentPropName,[{[this.options.textNodeName]:r}])}o=e}else if("!D"===t.substr(o+1,2)){const e=r.readDocType(t,o);this.docTypeEntities=e.entities,o=e.i}else if("!["===t.substr(o+1,2)){const e=W(t,"]]>",o,"CDATA is not closed.")-2,r=t.substring(o+9,e);i=this.saveTextToParentTag(i,n,s);let a=this.parseTextData(r,n.tagname,s,!0,!1,!0,!0);null==a&&(a=""),this.options.cdataPropName?n.add(this.options.cdataPropName,[{[this.options.textNodeName]:r}]):n.add(this.options.textNodeName,a),o=e+2}else{let r=q(t,o,this.options.removeNSPrefix),a=r.tagName;const l=r.rawTagName;let u=r.tagExp,d=r.attrExpPresent,h=r.closeIndex;if(this.options.transformTagName){const t=this.options.transformTagName(a);u===a&&(u=t),a=t}if(this.options.strictReservedNames&&(a===this.options.commentPropName||a===this.options.cdataPropName))throw new Error(`Invalid tag name: ${a}`);n&&i&&"!xml"!==n.tagname&&(i=this.saveTextToParentTag(i,n,s,!1));const p=n;p&&-1!==this.options.unpairedTags.indexOf(p.tagname)&&(n=this.tagsNodeStack.pop(),s=s.substring(0,s.lastIndexOf("."))),a!==e.tagname&&(s+=s?"."+a:a);const c=o;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,s,a)){let e="";if(u.length>0&&u.lastIndexOf("/")===u.length-1)"/"===a[a.length-1]?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),u=a):u=u.substr(0,u.length-1),o=r.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(a))o=r.closeIndex;else{const n=this.readStopNodeData(t,l,h+1);if(!n)throw new Error(`Unexpected end of ${l}`);o=n.i,e=n.tagContent}const i=new I(a);a!==u&&d&&(i[":@"]=this.buildAttributesMap(u,s,a)),e&&(e=this.parseTextData(e,a,s,!0,d,!0,!0)),s=s.substr(0,s.lastIndexOf(".")),i.add(this.options.textNodeName,e),this.addChild(n,i,s,c)}else{if(u.length>0&&u.lastIndexOf("/")===u.length-1){if("/"===a[a.length-1]?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),u=a):u=u.substr(0,u.length-1),this.options.transformTagName){const t=this.options.transformTagName(a);u===a&&(u=t),a=t}const t=new I(a);a!==u&&d&&(t[":@"]=this.buildAttributesMap(u,s,a)),this.addChild(n,t,s,c),s=s.substr(0,s.lastIndexOf("."))}else{const t=new I(a);if(this.tagsNodeStack.length>this.options.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(n),a!==u&&d&&(t[":@"]=this.buildAttributesMap(u,s,a)),this.addChild(n,t,s,c),n=t}i="",o=h}}else i+=t[o];return e.child};function Y(t,e,n,i){this.options.captureMetaData||(i=void 0);const s=this.options.updateTag(e.tagname,n,e[":@"]);!1===s||("string"==typeof s?(e.tagname=s,t.addChild(e,i)):t.addChild(e,i))}const G=function(t,e,n){if(-1===t.indexOf("&"))return t;const i=this.options.processEntities;if(!i.enabled)return t;if(i.allowedTags&&!i.allowedTags.includes(e))return t;if(i.tagFilter&&!i.tagFilter(e,n))return t;for(let e in this.docTypeEntities){const n=this.docTypeEntities[e],s=t.match(n.regx);if(s){if(this.entityExpansionCount+=s.length,i.maxTotalExpansions&&this.entityExpansionCount>i.maxTotalExpansions)throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${i.maxTotalExpansions}`);const e=t.length;if(t=t.replace(n.regx,n.val),i.maxExpandedLength&&(this.currentExpandedLength+=t.length-e,this.currentExpandedLength>i.maxExpandedLength))throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${i.maxExpandedLength}`)}}if(-1===t.indexOf("&"))return t;for(let e in this.lastEntities){const n=this.lastEntities[e];t=t.replace(n.regex,n.val)}if(-1===t.indexOf("&"))return t;if(this.options.htmlEntities)for(let e in this.htmlEntities){const n=this.htmlEntities[e];t=t.replace(n.regex,n.val)}return t.replace(this.ampEntity.regex,this.ampEntity.val)};function X(t,e,n,i){return t&&(void 0===i&&(i=0===e.child.length),void 0!==(t=this.parseTextData(t,e.tagname,n,!1,!!e[":@"]&&0!==Object.keys(e[":@"]).length,i))&&""!==t&&e.add(this.options.textNodeName,t),t=""),t}function z(t,e,n,i){return!(!e||!e.has(i))||!(!t||!t.has(n))}function W(t,e,n,i){const s=t.indexOf(e,n);if(-1===s)throw new Error(i);return s+e.length-1}function q(t,e,n,i=">"){const s=function(t,e,n=">"){let i,s="";for(let r=e;r",n,`${e} is not closed`);if(t.substring(n+2,r).trim()===e&&(s--,0===s))return{tagContent:t.substring(i,n),i:r};n=r}else if("?"===t[n+1])n=W(t,"?>",n+1,"StopNode is not closed.");else if("!--"===t.substr(n+1,3))n=W(t,"--\x3e",n+3,"StopNode is not closed.");else if("!["===t.substr(n+1,2))n=W(t,"]]>",n,"StopNode is not closed.")-2;else{const i=q(t,n,">");i&&((i&&i.tagName)===e&&"/"!==i.tagExp[i.tagExp.length-1]&&s++,n=i.closeIndex)}}function K(t,e,n){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&function(t,e={}){if(e=Object.assign({},D,e),!t||"string"!=typeof t)return t;let n=t.trim();if(void 0!==e.skipLike&&e.skipLike.test(n))return t;if("0"===t)return 0;if(e.hex&&$.test(n))return function(t){if(parseInt)return parseInt(t,16);if(Number.parseInt)return Number.parseInt(t,16);if(window&&window.parseInt)return window.parseInt(t,16);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(n);if(n.includes("e")||n.includes("E"))return function(t,e,n){if(!n.eNotation)return t;const i=e.match(j);if(i){let s=i[1]||"";const r=-1===i[3].indexOf("e")?"E":"e",o=i[2],a=s?t[o.length+1]===r:t[o.length]===r;return o.length>1&&a?t:1!==o.length||!i[3].startsWith(`.${r}`)&&i[3][0]!==r?n.leadingZeros&&!a?(e=(i[1]||"")+i[3],Number(e)):t:Number(e)}return t}(t,n,e);{const s=V.exec(n);if(s){const r=s[1]||"",o=s[2];let a=(i=s[3])&&-1!==i.indexOf(".")?("."===(i=i.replace(/0+$/,""))?i="0":"."===i[0]?i="0"+i:"."===i[i.length-1]&&(i=i.substring(0,i.length-1)),i):i;const l=r?"."===t[o.length+1]:"."===t[o.length];if(!e.leadingZeros&&(o.length>1||1===o.length&&!l))return t;{const i=Number(n),s=String(i);if(0===i)return i;if(-1!==s.search(/[eE]/))return e.eNotation?i:t;if(-1!==n.indexOf("."))return"0"===s||s===a||s===`${r}${a}`?i:t;let l=o?a:n;return o?l===s||r+l===s?i:t:l===s||l===r+s?i:t}}return t}var i}(t,n)}return void 0!==t?t:""}function Q(t,e,n){const i=Number.parseInt(t,e);return i>=0&&i<=1114111?String.fromCodePoint(i):n+t+";"}const J=I.getMetaDataSymbol();function H(t,e){return tt(t,e)}function tt(t,e,n){let i;const s={};for(let r=0;r0&&(s[e.textNodeName]=i):void 0!==i&&(s[e.textNodeName]=i),s}function et(t){const e=Object.keys(t);for(let t=0;t0&&(n="\n"),ot(t,e,"",n)}function ot(t,e,n,i){let s="",r=!1;if(!Array.isArray(t)){if(null!=t){let n=t.toString();return n=dt(n,e),n}return""}for(let o=0;o`,r=!1;continue}if(l===e.commentPropName){s+=i+`\x3c!--${a[l][0][e.textNodeName]}--\x3e`,r=!0;continue}if("?"===l[0]){const t=lt(a[":@"],e),n="?xml"===l?"":i;let o=a[l][0][e.textNodeName];o=0!==o.length?" "+o:"",s+=n+`<${l}${o}${t}?>`,r=!0;continue}let d=i;""!==d&&(d+=e.indentBy);const h=i+`<${l}${lt(a[":@"],e)}`,p=ot(a[l],e,u,d);-1!==e.unpairedTags.indexOf(l)?e.suppressUnpairedNode?s+=h+">":s+=h+"/>":p&&0!==p.length||!e.suppressEmptyNode?p&&p.endsWith(">")?s+=h+`>${p}${i}`:(s+=h+">",p&&""!==i&&(p.includes("/>")||p.includes("`):s+=h+"/>",r=!0}return s}function at(t){const e=Object.keys(t);for(let n=0;n0&&e.processEntities)for(let n=0;n","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function pt(t){this.options=Object.assign({},ht,t),!0===this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=L(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=gt),this.processTextOrObjNode=ct,this.options.format?(this.indentate=ft,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function ct(t,e,n,i){const s=this.j2x(t,n+1,i.concat(e));return void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,s.attrStr,n):this.buildObjectNode(s.val,e,s.attrStr,n)}function ft(t){return this.options.indentBy.repeat(t)}function gt(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}pt.prototype.build=function(t){return this.options.preserveOrder?rt(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0,[]).val)},pt.prototype.j2x=function(t,e,n){let i="",s="";const r=n.join(".");for(let o in t)if(Object.prototype.hasOwnProperty.call(t,o))if(void 0===t[o])this.isAttribute(o)&&(s+="");else if(null===t[o])this.isAttribute(o)||o===this.options.cdataPropName?s+="":"?"===o[0]?s+=this.indentate(e)+"<"+o+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+o+"/"+this.tagEndChar;else if(t[o]instanceof Date)s+=this.buildTextValNode(t[o],o,"",e);else if("object"!=typeof t[o]){const n=this.isAttribute(o);if(n&&!this.ignoreAttributesFn(n,r))i+=this.buildAttrPairStr(n,""+t[o]);else if(!n)if(o===this.options.textNodeName){let e=this.options.tagValueProcessor(o,""+t[o]);s+=this.replaceEntitiesValue(e)}else s+=this.buildTextValNode(t[o],o,"",e)}else if(Array.isArray(t[o])){const i=t[o].length;let r="",a="";for(let l=0;l"+t+s}},pt.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`>`+this.newLine;if(!1!==this.options.commentPropName&&e===this.options.commentPropName)return this.indentate(i)+`\x3c!--${t}--\x3e`+this.newLine;if("?"===e[0])return this.indentate(i)+"<"+e+n+"?"+this.tagEndChar;{let s=this.options.tagValueProcessor(e,t);return s=this.replaceEntitiesValue(s),""===s?this.indentate(i)+"<"+e+n+this.closeTag(e)+this.tagEndChar:this.indentate(i)+"<"+e+n+">"+s+"0&&this.options.processEntities)for(let e=0;e> 1) | ((i & 0x5555) << 1); - x = ((x & 0xCCCC) >> 2) | ((x & 0x3333) << 2); - x = ((x & 0xF0F0) >> 4) | ((x & 0x0F0F) << 4); - rev[i] = (((x & 0xFF00) >> 8) | ((x & 0x00FF) << 8)) >> 1; -} -// create huffman tree from u8 "map": index -> code length for code index -// mb (max bits) must be at most 15 -// TODO: optimize/split up? -var hMap = (function (cd, mb, r) { - var s = cd.length; - // index - var i = 0; - // u16 "map": index -> # of codes with bit length = index - var l = new u16(mb); - // length of cd must be 288 (total # of codes) - for (; i < s; ++i) { - if (cd[i]) - ++l[cd[i] - 1]; - } - // u16 "map": index -> minimum code for bit length = index - var le = new u16(mb); - for (i = 1; i < mb; ++i) { - le[i] = (le[i - 1] + l[i - 1]) << 1; - } - var co; - if (r) { - // u16 "map": index -> number of actual bits, symbol for code - co = new u16(1 << mb); - // bits to remove for reverser - var rvb = 15 - mb; - for (i = 0; i < s; ++i) { - // ignore 0 lengths - if (cd[i]) { - // num encoding both symbol and bits read - var sv = (i << 4) | cd[i]; - // free bits - var r_1 = mb - cd[i]; - // start value - var v = le[cd[i] - 1]++ << r_1; - // m is end value - for (var m = v | ((1 << r_1) - 1); v <= m; ++v) { - // every 16 bit value starting with the code yields the same result - co[rev[v] >> rvb] = sv; - } - } - } - } - else { - co = new u16(s); - for (i = 0; i < s; ++i) { - if (cd[i]) { - co[i] = rev[le[cd[i] - 1]++] >> (15 - cd[i]); - } - } - } - return co; -}); -// fixed length tree -var flt = new u8(288); -for (var i = 0; i < 144; ++i) - flt[i] = 8; -for (var i = 144; i < 256; ++i) - flt[i] = 9; -for (var i = 256; i < 280; ++i) - flt[i] = 7; -for (var i = 280; i < 288; ++i) - flt[i] = 8; -// fixed distance tree -var fdt = new u8(32); -for (var i = 0; i < 32; ++i) - fdt[i] = 5; -// fixed length map -var flm = /*#__PURE__*/ hMap(flt, 9, 0), flrm = /*#__PURE__*/ hMap(flt, 9, 1); -// fixed distance map -var fdm = /*#__PURE__*/ hMap(fdt, 5, 0), fdrm = /*#__PURE__*/ hMap(fdt, 5, 1); -// find max of array -var max = function (a) { - var m = a[0]; - for (var i = 1; i < a.length; ++i) { - if (a[i] > m) - m = a[i]; - } - return m; -}; -// read d, starting at bit p and mask with m -var bits = function (d, p, m) { - var o = (p / 8) | 0; - return ((d[o] | (d[o + 1] << 8)) >> (p & 7)) & m; -}; -// read d, starting at bit p continuing for at least 16 bits -var bits16 = function (d, p) { - var o = (p / 8) | 0; - return ((d[o] | (d[o + 1] << 8) | (d[o + 2] << 16)) >> (p & 7)); -}; -// get end of byte -var shft = function (p) { return ((p + 7) / 8) | 0; }; -// typed array slice - allows garbage collector to free original reference, -// while being more compatible than .slice -var slc = function (v, s, e) { - if (s == null || s < 0) - s = 0; - if (e == null || e > v.length) - e = v.length; - // can't use .constructor in case user-supplied - return new u8(v.subarray(s, e)); -}; -/** - * Codes for errors generated within this library - */ -export var FlateErrorCode = { - UnexpectedEOF: 0, - InvalidBlockType: 1, - InvalidLengthLiteral: 2, - InvalidDistance: 3, - StreamFinished: 4, - NoStreamHandler: 5, - InvalidHeader: 6, - NoCallback: 7, - InvalidUTF8: 8, - ExtraFieldTooLong: 9, - InvalidDate: 10, - FilenameTooLong: 11, - StreamFinishing: 12, - InvalidZipData: 13, - UnknownCompressionMethod: 14 -}; -// error codes -var ec = [ - 'unexpected EOF', - 'invalid block type', - 'invalid length/literal', - 'invalid distance', - 'stream finished', - 'no stream handler', - , - 'no callback', - 'invalid UTF-8 data', - 'extra field too long', - 'date not in range 1980-2099', - 'filename too long', - 'stream finishing', - 'invalid zip data' - // determined by unknown compression method -]; -; -var err = function (ind, msg, nt) { - var e = new Error(msg || ec[ind]); - e.code = ind; - if (Error.captureStackTrace) - Error.captureStackTrace(e, err); - if (!nt) - throw e; - return e; -}; -// expands raw DEFLATE data -var inflt = function (dat, st, buf, dict) { - // source length dict length - var sl = dat.length, dl = dict ? dict.length : 0; - if (!sl || st.f && !st.l) - return buf || new u8(0); - var noBuf = !buf; - // have to estimate size - var resize = noBuf || st.i != 2; - // no state - var noSt = st.i; - // Assumes roughly 33% compression ratio average - if (noBuf) - buf = new u8(sl * 3); - // ensure buffer can fit at least l elements - var cbuf = function (l) { - var bl = buf.length; - // need to increase size to fit - if (l > bl) { - // Double or set to necessary, whichever is greater - var nbuf = new u8(Math.max(bl * 2, l)); - nbuf.set(buf); - buf = nbuf; - } - }; - // last chunk bitpos bytes - var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n; - // total bits - var tbts = sl * 8; - do { - if (!lm) { - // BFINAL - this is only 1 when last chunk is next - final = bits(dat, pos, 1); - // type: 0 = no compression, 1 = fixed huffman, 2 = dynamic huffman - var type = bits(dat, pos + 1, 3); - pos += 3; - if (!type) { - // go to end of byte boundary - var s = shft(pos) + 4, l = dat[s - 4] | (dat[s - 3] << 8), t = s + l; - if (t > sl) { - if (noSt) - err(0); - break; - } - // ensure size - if (resize) - cbuf(bt + l); - // Copy over uncompressed data - buf.set(dat.subarray(s, t), bt); - // Get new bitpos, update byte count - st.b = bt += l, st.p = pos = t * 8, st.f = final; - continue; - } - else if (type == 1) - lm = flrm, dm = fdrm, lbt = 9, dbt = 5; - else if (type == 2) { - // literal lengths - var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4; - var tl = hLit + bits(dat, pos + 5, 31) + 1; - pos += 14; - // length+distance tree - var ldt = new u8(tl); - // code length tree - var clt = new u8(19); - for (var i = 0; i < hcLen; ++i) { - // use index map to get real code - clt[clim[i]] = bits(dat, pos + i * 3, 7); - } - pos += hcLen * 3; - // code lengths bits - var clb = max(clt), clbmsk = (1 << clb) - 1; - // code lengths map - var clm = hMap(clt, clb, 1); - for (var i = 0; i < tl;) { - var r = clm[bits(dat, pos, clbmsk)]; - // bits read - pos += r & 15; - // symbol - var s = r >> 4; - // code length to copy - if (s < 16) { - ldt[i++] = s; - } - else { - // copy count - var c = 0, n = 0; - if (s == 16) - n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1]; - else if (s == 17) - n = 3 + bits(dat, pos, 7), pos += 3; - else if (s == 18) - n = 11 + bits(dat, pos, 127), pos += 7; - while (n--) - ldt[i++] = c; - } - } - // length tree distance tree - var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit); - // max length bits - lbt = max(lt); - // max dist bits - dbt = max(dt); - lm = hMap(lt, lbt, 1); - dm = hMap(dt, dbt, 1); - } - else - err(1); - if (pos > tbts) { - if (noSt) - err(0); - break; - } - } - // Make sure the buffer can hold this + the largest possible addition - // Maximum chunk size (practically, theoretically infinite) is 2^17 - if (resize) - cbuf(bt + 131072); - var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1; - var lpos = pos; - for (;; lpos = pos) { - // bits read, code - var c = lm[bits16(dat, pos) & lms], sym = c >> 4; - pos += c & 15; - if (pos > tbts) { - if (noSt) - err(0); - break; - } - if (!c) - err(2); - if (sym < 256) - buf[bt++] = sym; - else if (sym == 256) { - lpos = pos, lm = null; - break; - } - else { - var add = sym - 254; - // no extra bits needed if less - if (sym > 264) { - // index - var i = sym - 257, b = fleb[i]; - add = bits(dat, pos, (1 << b) - 1) + fl[i]; - pos += b; - } - // dist - var d = dm[bits16(dat, pos) & dms], dsym = d >> 4; - if (!d) - err(3); - pos += d & 15; - var dt = fd[dsym]; - if (dsym > 3) { - var b = fdeb[dsym]; - dt += bits16(dat, pos) & (1 << b) - 1, pos += b; - } - if (pos > tbts) { - if (noSt) - err(0); - break; - } - if (resize) - cbuf(bt + 131072); - var end = bt + add; - if (bt < dt) { - var shift = dl - dt, dend = Math.min(dt, end); - if (shift + bt < 0) - err(3); - for (; bt < dend; ++bt) - buf[bt] = dict[shift + bt]; - } - for (; bt < end; ++bt) - buf[bt] = buf[bt - dt]; - } - } - st.l = lm, st.p = lpos, st.b = bt, st.f = final; - if (lm) - final = 1, st.m = lbt, st.d = dm, st.n = dbt; - } while (!final); - // don't reallocate for streams or user buffers - return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt); -}; -// starting at p, write the minimum number of bits that can hold v to d -var wbits = function (d, p, v) { - v <<= p & 7; - var o = (p / 8) | 0; - d[o] |= v; - d[o + 1] |= v >> 8; -}; -// starting at p, write the minimum number of bits (>8) that can hold v to d -var wbits16 = function (d, p, v) { - v <<= p & 7; - var o = (p / 8) | 0; - d[o] |= v; - d[o + 1] |= v >> 8; - d[o + 2] |= v >> 16; -}; -// creates code lengths from a frequency table -var hTree = function (d, mb) { - // Need extra info to make a tree - var t = []; - for (var i = 0; i < d.length; ++i) { - if (d[i]) - t.push({ s: i, f: d[i] }); - } - var s = t.length; - var t2 = t.slice(); - if (!s) - return { t: et, l: 0 }; - if (s == 1) { - var v = new u8(t[0].s + 1); - v[t[0].s] = 1; - return { t: v, l: 1 }; - } - t.sort(function (a, b) { return a.f - b.f; }); - // after i2 reaches last ind, will be stopped - // freq must be greater than largest possible number of symbols - t.push({ s: -1, f: 25001 }); - var l = t[0], r = t[1], i0 = 0, i1 = 1, i2 = 2; - t[0] = { s: -1, f: l.f + r.f, l: l, r: r }; - // efficient algorithm from UZIP.js - // i0 is lookbehind, i2 is lookahead - after processing two low-freq - // symbols that combined have high freq, will start processing i2 (high-freq, - // non-composite) symbols instead - // see https://reddit.com/r/photopea/comments/ikekht/uzipjs_questions/ - while (i1 != s - 1) { - l = t[t[i0].f < t[i2].f ? i0++ : i2++]; - r = t[i0 != i1 && t[i0].f < t[i2].f ? i0++ : i2++]; - t[i1++] = { s: -1, f: l.f + r.f, l: l, r: r }; - } - var maxSym = t2[0].s; - for (var i = 1; i < s; ++i) { - if (t2[i].s > maxSym) - maxSym = t2[i].s; - } - // code lengths - var tr = new u16(maxSym + 1); - // max bits in tree - var mbt = ln(t[i1 - 1], tr, 0); - if (mbt > mb) { - // more algorithms from UZIP.js - // TODO: find out how this code works (debt) - // ind debt - var i = 0, dt = 0; - // left cost - var lft = mbt - mb, cst = 1 << lft; - t2.sort(function (a, b) { return tr[b.s] - tr[a.s] || a.f - b.f; }); - for (; i < s; ++i) { - var i2_1 = t2[i].s; - if (tr[i2_1] > mb) { - dt += cst - (1 << (mbt - tr[i2_1])); - tr[i2_1] = mb; - } - else - break; - } - dt >>= lft; - while (dt > 0) { - var i2_2 = t2[i].s; - if (tr[i2_2] < mb) - dt -= 1 << (mb - tr[i2_2]++ - 1); - else - ++i; - } - for (; i >= 0 && dt; --i) { - var i2_3 = t2[i].s; - if (tr[i2_3] == mb) { - --tr[i2_3]; - ++dt; - } - } - mbt = mb; - } - return { t: new u8(tr), l: mbt }; -}; -// get the max length and assign length codes -var ln = function (n, l, d) { - return n.s == -1 - ? Math.max(ln(n.l, l, d + 1), ln(n.r, l, d + 1)) - : (l[n.s] = d); -}; -// length codes generation -var lc = function (c) { - var s = c.length; - // Note that the semicolon was intentional - while (s && !c[--s]) - ; - var cl = new u16(++s); - // ind num streak - var cli = 0, cln = c[0], cls = 1; - var w = function (v) { cl[cli++] = v; }; - for (var i = 1; i <= s; ++i) { - if (c[i] == cln && i != s) - ++cls; - else { - if (!cln && cls > 2) { - for (; cls > 138; cls -= 138) - w(32754); - if (cls > 2) { - w(cls > 10 ? ((cls - 11) << 5) | 28690 : ((cls - 3) << 5) | 12305); - cls = 0; - } - } - else if (cls > 3) { - w(cln), --cls; - for (; cls > 6; cls -= 6) - w(8304); - if (cls > 2) - w(((cls - 3) << 5) | 8208), cls = 0; - } - while (cls--) - w(cln); - cls = 1; - cln = c[i]; - } - } - return { c: cl.subarray(0, cli), n: s }; -}; -// calculate the length of output from tree, code lengths -var clen = function (cf, cl) { - var l = 0; - for (var i = 0; i < cl.length; ++i) - l += cf[i] * cl[i]; - return l; -}; -// writes a fixed block -// returns the new bit pos -var wfblk = function (out, pos, dat) { - // no need to write 00 as type: TypedArray defaults to 0 - var s = dat.length; - var o = shft(pos + 2); - out[o] = s & 255; - out[o + 1] = s >> 8; - out[o + 2] = out[o] ^ 255; - out[o + 3] = out[o + 1] ^ 255; - for (var i = 0; i < s; ++i) - out[o + i + 4] = dat[i]; - return (o + 4 + s) * 8; -}; -// writes a block -var wblk = function (dat, out, final, syms, lf, df, eb, li, bs, bl, p) { - wbits(out, p++, final); - ++lf[256]; - var _a = hTree(lf, 15), dlt = _a.t, mlb = _a.l; - var _b = hTree(df, 15), ddt = _b.t, mdb = _b.l; - var _c = lc(dlt), lclt = _c.c, nlc = _c.n; - var _d = lc(ddt), lcdt = _d.c, ndc = _d.n; - var lcfreq = new u16(19); - for (var i = 0; i < lclt.length; ++i) - ++lcfreq[lclt[i] & 31]; - for (var i = 0; i < lcdt.length; ++i) - ++lcfreq[lcdt[i] & 31]; - var _e = hTree(lcfreq, 7), lct = _e.t, mlcb = _e.l; - var nlcc = 19; - for (; nlcc > 4 && !lct[clim[nlcc - 1]]; --nlcc) - ; - var flen = (bl + 5) << 3; - var ftlen = clen(lf, flt) + clen(df, fdt) + eb; - var dtlen = clen(lf, dlt) + clen(df, ddt) + eb + 14 + 3 * nlcc + clen(lcfreq, lct) + 2 * lcfreq[16] + 3 * lcfreq[17] + 7 * lcfreq[18]; - if (bs >= 0 && flen <= ftlen && flen <= dtlen) - return wfblk(out, p, dat.subarray(bs, bs + bl)); - var lm, ll, dm, dl; - wbits(out, p, 1 + (dtlen < ftlen)), p += 2; - if (dtlen < ftlen) { - lm = hMap(dlt, mlb, 0), ll = dlt, dm = hMap(ddt, mdb, 0), dl = ddt; - var llm = hMap(lct, mlcb, 0); - wbits(out, p, nlc - 257); - wbits(out, p + 5, ndc - 1); - wbits(out, p + 10, nlcc - 4); - p += 14; - for (var i = 0; i < nlcc; ++i) - wbits(out, p + 3 * i, lct[clim[i]]); - p += 3 * nlcc; - var lcts = [lclt, lcdt]; - for (var it = 0; it < 2; ++it) { - var clct = lcts[it]; - for (var i = 0; i < clct.length; ++i) { - var len = clct[i] & 31; - wbits(out, p, llm[len]), p += lct[len]; - if (len > 15) - wbits(out, p, (clct[i] >> 5) & 127), p += clct[i] >> 12; - } - } - } - else { - lm = flm, ll = flt, dm = fdm, dl = fdt; - } - for (var i = 0; i < li; ++i) { - var sym = syms[i]; - if (sym > 255) { - var len = (sym >> 18) & 31; - wbits16(out, p, lm[len + 257]), p += ll[len + 257]; - if (len > 7) - wbits(out, p, (sym >> 23) & 31), p += fleb[len]; - var dst = sym & 31; - wbits16(out, p, dm[dst]), p += dl[dst]; - if (dst > 3) - wbits16(out, p, (sym >> 5) & 8191), p += fdeb[dst]; - } - else { - wbits16(out, p, lm[sym]), p += ll[sym]; - } - } - wbits16(out, p, lm[256]); - return p + ll[256]; -}; -// deflate options (nice << 13) | chain -var deo = /*#__PURE__*/ new i32([65540, 131080, 131088, 131104, 262176, 1048704, 1048832, 2114560, 2117632]); -// empty -var et = /*#__PURE__*/ new u8(0); -// compresses data into a raw DEFLATE buffer -var dflt = function (dat, lvl, plvl, pre, post, st) { - var s = st.z || dat.length; - var o = new u8(pre + s + 5 * (1 + Math.ceil(s / 7000)) + post); - // writing to this writes to the output buffer - var w = o.subarray(pre, o.length - post); - var lst = st.l; - var pos = (st.r || 0) & 7; - if (lvl) { - if (pos) - w[0] = st.r >> 3; - var opt = deo[lvl - 1]; - var n = opt >> 13, c = opt & 8191; - var msk_1 = (1 << plvl) - 1; - // prev 2-byte val map curr 2-byte val map - var prev = st.p || new u16(32768), head = st.h || new u16(msk_1 + 1); - var bs1_1 = Math.ceil(plvl / 3), bs2_1 = 2 * bs1_1; - var hsh = function (i) { return (dat[i] ^ (dat[i + 1] << bs1_1) ^ (dat[i + 2] << bs2_1)) & msk_1; }; - // 24576 is an arbitrary number of maximum symbols per block - // 424 buffer for last block - var syms = new i32(25000); - // length/literal freq distance freq - var lf = new u16(288), df = new u16(32); - // l/lcnt exbits index l/lind waitdx blkpos - var lc_1 = 0, eb = 0, i = st.i || 0, li = 0, wi = st.w || 0, bs = 0; - for (; i + 2 < s; ++i) { - // hash value - var hv = hsh(i); - // index mod 32768 previous index mod - var imod = i & 32767, pimod = head[hv]; - prev[imod] = pimod; - head[hv] = imod; - // We always should modify head and prev, but only add symbols if - // this data is not yet processed ("wait" for wait index) - if (wi <= i) { - // bytes remaining - var rem = s - i; - if ((lc_1 > 7000 || li > 24576) && (rem > 423 || !lst)) { - pos = wblk(dat, w, 0, syms, lf, df, eb, li, bs, i - bs, pos); - li = lc_1 = eb = 0, bs = i; - for (var j = 0; j < 286; ++j) - lf[j] = 0; - for (var j = 0; j < 30; ++j) - df[j] = 0; - } - // len dist chain - var l = 2, d = 0, ch_1 = c, dif = imod - pimod & 32767; - if (rem > 2 && hv == hsh(i - dif)) { - var maxn = Math.min(n, rem) - 1; - var maxd = Math.min(32767, i); - // max possible length - // not capped at dif because decompressors implement "rolling" index population - var ml = Math.min(258, rem); - while (dif <= maxd && --ch_1 && imod != pimod) { - if (dat[i + l] == dat[i + l - dif]) { - var nl = 0; - for (; nl < ml && dat[i + nl] == dat[i + nl - dif]; ++nl) - ; - if (nl > l) { - l = nl, d = dif; - // break out early when we reach "nice" (we are satisfied enough) - if (nl > maxn) - break; - // now, find the rarest 2-byte sequence within this - // length of literals and search for that instead. - // Much faster than just using the start - var mmd = Math.min(dif, nl - 2); - var md = 0; - for (var j = 0; j < mmd; ++j) { - var ti = i - dif + j & 32767; - var pti = prev[ti]; - var cd = ti - pti & 32767; - if (cd > md) - md = cd, pimod = ti; - } - } - } - // check the previous match - imod = pimod, pimod = prev[imod]; - dif += imod - pimod & 32767; - } - } - // d will be nonzero only when a match was found - if (d) { - // store both dist and len data in one int32 - // Make sure this is recognized as a len/dist with 28th bit (2^28) - syms[li++] = 268435456 | (revfl[l] << 18) | revfd[d]; - var lin = revfl[l] & 31, din = revfd[d] & 31; - eb += fleb[lin] + fdeb[din]; - ++lf[257 + lin]; - ++df[din]; - wi = i + l; - ++lc_1; - } - else { - syms[li++] = dat[i]; - ++lf[dat[i]]; - } - } - } - for (i = Math.max(i, wi); i < s; ++i) { - syms[li++] = dat[i]; - ++lf[dat[i]]; - } - pos = wblk(dat, w, lst, syms, lf, df, eb, li, bs, i - bs, pos); - if (!lst) { - st.r = (pos & 7) | w[(pos / 8) | 0] << 3; - // shft(pos) now 1 less if pos & 7 != 0 - pos -= 7; - st.h = head, st.p = prev, st.i = i, st.w = wi; - } - } - else { - for (var i = st.w || 0; i < s + lst; i += 65535) { - // end - var e = i + 65535; - if (e >= s) { - // write final block - w[(pos / 8) | 0] = lst; - e = s; - } - pos = wfblk(w, pos + 1, dat.subarray(i, e)); - } - st.i = s; - } - return slc(o, 0, pre + shft(pos) + post); -}; -// CRC32 table -var crct = /*#__PURE__*/ (function () { - var t = new Int32Array(256); - for (var i = 0; i < 256; ++i) { - var c = i, k = 9; - while (--k) - c = ((c & 1) && -306674912) ^ (c >>> 1); - t[i] = c; - } - return t; -})(); -// CRC32 -var crc = function () { - var c = -1; - return { - p: function (d) { - // closures have awful performance - var cr = c; - for (var i = 0; i < d.length; ++i) - cr = crct[(cr & 255) ^ d[i]] ^ (cr >>> 8); - c = cr; - }, - d: function () { return ~c; } - }; -}; -// Adler32 -var adler = function () { - var a = 1, b = 0; - return { - p: function (d) { - // closures have awful performance - var n = a, m = b; - var l = d.length | 0; - for (var i = 0; i != l;) { - var e = Math.min(i + 2655, l); - for (; i < e; ++i) - m += n += d[i]; - n = (n & 65535) + 15 * (n >> 16), m = (m & 65535) + 15 * (m >> 16); - } - a = n, b = m; - }, - d: function () { - a %= 65521, b %= 65521; - return (a & 255) << 24 | (a & 0xFF00) << 8 | (b & 255) << 8 | (b >> 8); - } - }; -}; -; -// deflate with opts -var dopt = function (dat, opt, pre, post, st) { - if (!st) { - st = { l: 1 }; - if (opt.dictionary) { - var dict = opt.dictionary.subarray(-32768); - var newDat = new u8(dict.length + dat.length); - newDat.set(dict); - newDat.set(dat, dict.length); - dat = newDat; - st.w = dict.length; - } - } - return dflt(dat, opt.level == null ? 6 : opt.level, opt.mem == null ? (st.l ? Math.ceil(Math.max(8, Math.min(13, Math.log(dat.length))) * 1.5) : 20) : (12 + opt.mem), pre, post, st); -}; -// Walmart object spread -var mrg = function (a, b) { - var o = {}; - for (var k in a) - o[k] = a[k]; - for (var k in b) - o[k] = b[k]; - return o; -}; -// worker clone -// This is possibly the craziest part of the entire codebase, despite how simple it may seem. -// The only parameter to this function is a closure that returns an array of variables outside of the function scope. -// We're going to try to figure out the variable names used in the closure as strings because that is crucial for workerization. -// We will return an object mapping of true variable name to value (basically, the current scope as a JS object). -// The reason we can't just use the original variable names is minifiers mangling the toplevel scope. -// This took me three weeks to figure out how to do. -var wcln = function (fn, fnStr, td) { - var dt = fn(); - var st = fn.toString(); - var ks = st.slice(st.indexOf('[') + 1, st.lastIndexOf(']')).replace(/\s+/g, '').split(','); - for (var i = 0; i < dt.length; ++i) { - var v = dt[i], k = ks[i]; - if (typeof v == 'function') { - fnStr += ';' + k + '='; - var st_1 = v.toString(); - if (v.prototype) { - // for global objects - if (st_1.indexOf('[native code]') != -1) { - var spInd = st_1.indexOf(' ', 8) + 1; - fnStr += st_1.slice(spInd, st_1.indexOf('(', spInd)); - } - else { - fnStr += st_1; - for (var t in v.prototype) - fnStr += ';' + k + '.prototype.' + t + '=' + v.prototype[t].toString(); - } - } - else - fnStr += st_1; - } - else - td[k] = v; - } - return fnStr; -}; -var ch = []; -// clone bufs -var cbfs = function (v) { - var tl = []; - for (var k in v) { - if (v[k].buffer) { - tl.push((v[k] = new v[k].constructor(v[k])).buffer); - } - } - return tl; -}; -// use a worker to execute code -var wrkr = function (fns, init, id, cb) { - if (!ch[id]) { - var fnStr = '', td_1 = {}, m = fns.length - 1; - for (var i = 0; i < m; ++i) - fnStr = wcln(fns[i], fnStr, td_1); - ch[id] = { c: wcln(fns[m], fnStr, td_1), e: td_1 }; - } - var td = mrg({}, ch[id].e); - return wk(ch[id].c + ';onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage=' + init.toString() + '}', id, td, cbfs(td), cb); -}; -// base async inflate fn -var bInflt = function () { return [u8, u16, i32, fleb, fdeb, clim, fl, fd, flrm, fdrm, rev, ec, hMap, max, bits, bits16, shft, slc, err, inflt, inflateSync, pbf, gopt]; }; -var bDflt = function () { return [u8, u16, i32, fleb, fdeb, clim, revfl, revfd, flm, flt, fdm, fdt, rev, deo, et, hMap, wbits, wbits16, hTree, ln, lc, clen, wfblk, wblk, shft, slc, dflt, dopt, deflateSync, pbf]; }; -// gzip extra -var gze = function () { return [gzh, gzhl, wbytes, crc, crct]; }; -// gunzip extra -var guze = function () { return [gzs, gzl]; }; -// zlib extra -var zle = function () { return [zlh, wbytes, adler]; }; -// unzlib extra -var zule = function () { return [zls]; }; -// post buf -var pbf = function (msg) { return postMessage(msg, [msg.buffer]); }; -// get opts -var gopt = function (o) { return o && { - out: o.size && new u8(o.size), - dictionary: o.dictionary -}; }; -// async helper -var cbify = function (dat, opts, fns, init, id, cb) { - var w = wrkr(fns, init, id, function (err, dat) { - w.terminate(); - cb(err, dat); - }); - w.postMessage([dat, opts], opts.consume ? [dat.buffer] : []); - return function () { w.terminate(); }; -}; -// auto stream -var astrm = function (strm) { - strm.ondata = function (dat, final) { return postMessage([dat, final], [dat.buffer]); }; - return function (ev) { - if (ev.data.length) { - strm.push(ev.data[0], ev.data[1]); - postMessage([ev.data[0].length]); - } - else - strm.flush(); - }; -}; -// async stream attach -var astrmify = function (fns, strm, opts, init, id, flush, ext) { - var t; - var w = wrkr(fns, init, id, function (err, dat) { - if (err) - w.terminate(), strm.ondata.call(strm, err); - else if (!Array.isArray(dat)) - ext(dat); - else if (dat.length == 1) { - strm.queuedSize -= dat[0]; - if (strm.ondrain) - strm.ondrain(dat[0]); - } - else { - if (dat[1]) - w.terminate(); - strm.ondata.call(strm, err, dat[0], dat[1]); - } - }); - w.postMessage(opts); - strm.queuedSize = 0; - strm.push = function (d, f) { - if (!strm.ondata) - err(5); - if (t) - strm.ondata(err(4, 0, 1), null, !!f); - strm.queuedSize += d.length; - w.postMessage([d, t = f], [d.buffer]); - }; - strm.terminate = function () { w.terminate(); }; - if (flush) { - strm.flush = function () { w.postMessage([]); }; - } -}; -// read 2 bytes -var b2 = function (d, b) { return d[b] | (d[b + 1] << 8); }; -// read 4 bytes -var b4 = function (d, b) { return (d[b] | (d[b + 1] << 8) | (d[b + 2] << 16) | (d[b + 3] << 24)) >>> 0; }; -var b8 = function (d, b) { return b4(d, b) + (b4(d, b + 4) * 4294967296); }; -// write bytes -var wbytes = function (d, b, v) { - for (; v; ++b) - d[b] = v, v >>>= 8; -}; -// gzip header -var gzh = function (c, o) { - var fn = o.filename; - c[0] = 31, c[1] = 139, c[2] = 8, c[8] = o.level < 2 ? 4 : o.level == 9 ? 2 : 0, c[9] = 3; // assume Unix - if (o.mtime != 0) - wbytes(c, 4, Math.floor(new Date(o.mtime || Date.now()) / 1000)); - if (fn) { - c[3] = 8; - for (var i = 0; i <= fn.length; ++i) - c[i + 10] = fn.charCodeAt(i); - } -}; -// gzip footer: -8 to -4 = CRC, -4 to -0 is length -// gzip start -var gzs = function (d) { - if (d[0] != 31 || d[1] != 139 || d[2] != 8) - err(6, 'invalid gzip data'); - var flg = d[3]; - var st = 10; - if (flg & 4) - st += (d[10] | d[11] << 8) + 2; - for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++]) - ; - return st + (flg & 2); -}; -// gzip length -var gzl = function (d) { - var l = d.length; - return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0; -}; -// gzip header length -var gzhl = function (o) { return 10 + (o.filename ? o.filename.length + 1 : 0); }; -// zlib header -var zlh = function (c, o) { - var lv = o.level, fl = lv == 0 ? 0 : lv < 6 ? 1 : lv == 9 ? 3 : 2; - c[0] = 120, c[1] = (fl << 6) | (o.dictionary && 32); - c[1] |= 31 - ((c[0] << 8) | c[1]) % 31; - if (o.dictionary) { - var h = adler(); - h.p(o.dictionary); - wbytes(c, 2, h.d()); - } -}; -// zlib start -var zls = function (d, dict) { - if ((d[0] & 15) != 8 || (d[0] >> 4) > 7 || ((d[0] << 8 | d[1]) % 31)) - err(6, 'invalid zlib data'); - if ((d[1] >> 5 & 1) == +!dict) - err(6, 'invalid zlib data: ' + (d[1] & 32 ? 'need' : 'unexpected') + ' dictionary'); - return (d[1] >> 3 & 4) + 2; -}; -function StrmOpt(opts, cb) { - if (typeof opts == 'function') - cb = opts, opts = {}; - this.ondata = cb; - return opts; -} -/** - * Streaming DEFLATE compression - */ -var Deflate = /*#__PURE__*/ (function () { - function Deflate(opts, cb) { - if (typeof opts == 'function') - cb = opts, opts = {}; - this.ondata = cb; - this.o = opts || {}; - this.s = { l: 0, i: 32768, w: 32768, z: 32768 }; - // Buffer length must always be 0 mod 32768 for index calculations to be correct when modifying head and prev - // 98304 = 32768 (lookback) + 65536 (common chunk size) - this.b = new u8(98304); - if (this.o.dictionary) { - var dict = this.o.dictionary.subarray(-32768); - this.b.set(dict, 32768 - dict.length); - this.s.i = 32768 - dict.length; - } - } - Deflate.prototype.p = function (c, f) { - this.ondata(dopt(c, this.o, 0, 0, this.s), f); - }; - /** - * Pushes a chunk to be deflated - * @param chunk The chunk to push - * @param final Whether this is the last chunk - */ - Deflate.prototype.push = function (chunk, final) { - if (!this.ondata) - err(5); - if (this.s.l) - err(4); - var endLen = chunk.length + this.s.z; - if (endLen > this.b.length) { - if (endLen > 2 * this.b.length - 32768) { - var newBuf = new u8(endLen & -32768); - newBuf.set(this.b.subarray(0, this.s.z)); - this.b = newBuf; - } - var split = this.b.length - this.s.z; - this.b.set(chunk.subarray(0, split), this.s.z); - this.s.z = this.b.length; - this.p(this.b, false); - this.b.set(this.b.subarray(-32768)); - this.b.set(chunk.subarray(split), 32768); - this.s.z = chunk.length - split + 32768; - this.s.i = 32766, this.s.w = 32768; - } - else { - this.b.set(chunk, this.s.z); - this.s.z += chunk.length; - } - this.s.l = final & 1; - if (this.s.z > this.s.w + 8191 || final) { - this.p(this.b, final || false); - this.s.w = this.s.i, this.s.i -= 2; - } - }; - /** - * Flushes buffered uncompressed data. Useful to immediately retrieve the - * deflated output for small inputs. - */ - Deflate.prototype.flush = function () { - if (!this.ondata) - err(5); - if (this.s.l) - err(4); - this.p(this.b, false); - this.s.w = this.s.i, this.s.i -= 2; - }; - return Deflate; -}()); -export { Deflate }; -/** - * Asynchronous streaming DEFLATE compression - */ -var AsyncDeflate = /*#__PURE__*/ (function () { - function AsyncDeflate(opts, cb) { - astrmify([ - bDflt, - function () { return [astrm, Deflate]; } - ], this, StrmOpt.call(this, opts, cb), function (ev) { - var strm = new Deflate(ev.data); - onmessage = astrm(strm); - }, 6, 1); - } - return AsyncDeflate; -}()); -export { AsyncDeflate }; -export function deflate(data, opts, cb) { - if (!cb) - cb = opts, opts = {}; - if (typeof cb != 'function') - err(7); - return cbify(data, opts, [ - bDflt, - ], function (ev) { return pbf(deflateSync(ev.data[0], ev.data[1])); }, 0, cb); -} -/** - * Compresses data with DEFLATE without any wrapper - * @param data The data to compress - * @param opts The compression options - * @returns The deflated version of the data - */ -export function deflateSync(data, opts) { - return dopt(data, opts || {}, 0, 0); -} -/** - * Streaming DEFLATE decompression - */ -var Inflate = /*#__PURE__*/ (function () { - function Inflate(opts, cb) { - // no StrmOpt here to avoid adding to workerizer - if (typeof opts == 'function') - cb = opts, opts = {}; - this.ondata = cb; - var dict = opts && opts.dictionary && opts.dictionary.subarray(-32768); - this.s = { i: 0, b: dict ? dict.length : 0 }; - this.o = new u8(32768); - this.p = new u8(0); - if (dict) - this.o.set(dict); - } - Inflate.prototype.e = function (c) { - if (!this.ondata) - err(5); - if (this.d) - err(4); - if (!this.p.length) - this.p = c; - else if (c.length) { - var n = new u8(this.p.length + c.length); - n.set(this.p), n.set(c, this.p.length), this.p = n; - } - }; - Inflate.prototype.c = function (final) { - this.s.i = +(this.d = final || false); - var bts = this.s.b; - var dt = inflt(this.p, this.s, this.o); - this.ondata(slc(dt, bts, this.s.b), this.d); - this.o = slc(dt, this.s.b - 32768), this.s.b = this.o.length; - this.p = slc(this.p, (this.s.p / 8) | 0), this.s.p &= 7; - }; - /** - * Pushes a chunk to be inflated - * @param chunk The chunk to push - * @param final Whether this is the final chunk - */ - Inflate.prototype.push = function (chunk, final) { - this.e(chunk), this.c(final); - }; - return Inflate; -}()); -export { Inflate }; -/** - * Asynchronous streaming DEFLATE decompression - */ -var AsyncInflate = /*#__PURE__*/ (function () { - function AsyncInflate(opts, cb) { - astrmify([ - bInflt, - function () { return [astrm, Inflate]; } - ], this, StrmOpt.call(this, opts, cb), function (ev) { - var strm = new Inflate(ev.data); - onmessage = astrm(strm); - }, 7, 0); - } - return AsyncInflate; -}()); -export { AsyncInflate }; -export function inflate(data, opts, cb) { - if (!cb) - cb = opts, opts = {}; - if (typeof cb != 'function') - err(7); - return cbify(data, opts, [ - bInflt - ], function (ev) { return pbf(inflateSync(ev.data[0], gopt(ev.data[1]))); }, 1, cb); -} -/** - * Expands DEFLATE data with no wrapper - * @param data The data to decompress - * @param opts The decompression options - * @returns The decompressed version of the data - */ -export function inflateSync(data, opts) { - return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary); -} -// before you yell at me for not just using extends, my reason is that TS inheritance is hard to workerize. -/** - * Streaming GZIP compression - */ -var Gzip = /*#__PURE__*/ (function () { - function Gzip(opts, cb) { - this.c = crc(); - this.l = 0; - this.v = 1; - Deflate.call(this, opts, cb); - } - /** - * Pushes a chunk to be GZIPped - * @param chunk The chunk to push - * @param final Whether this is the last chunk - */ - Gzip.prototype.push = function (chunk, final) { - this.c.p(chunk); - this.l += chunk.length; - Deflate.prototype.push.call(this, chunk, final); - }; - Gzip.prototype.p = function (c, f) { - var raw = dopt(c, this.o, this.v && gzhl(this.o), f && 8, this.s); - if (this.v) - gzh(raw, this.o), this.v = 0; - if (f) - wbytes(raw, raw.length - 8, this.c.d()), wbytes(raw, raw.length - 4, this.l); - this.ondata(raw, f); - }; - /** - * Flushes buffered uncompressed data. Useful to immediately retrieve the - * GZIPped output for small inputs. - */ - Gzip.prototype.flush = function () { - Deflate.prototype.flush.call(this); - }; - return Gzip; -}()); -export { Gzip }; -/** - * Asynchronous streaming GZIP compression - */ -var AsyncGzip = /*#__PURE__*/ (function () { - function AsyncGzip(opts, cb) { - astrmify([ - bDflt, - gze, - function () { return [astrm, Deflate, Gzip]; } - ], this, StrmOpt.call(this, opts, cb), function (ev) { - var strm = new Gzip(ev.data); - onmessage = astrm(strm); - }, 8, 1); - } - return AsyncGzip; -}()); -export { AsyncGzip }; -export function gzip(data, opts, cb) { - if (!cb) - cb = opts, opts = {}; - if (typeof cb != 'function') - err(7); - return cbify(data, opts, [ - bDflt, - gze, - function () { return [gzipSync]; } - ], function (ev) { return pbf(gzipSync(ev.data[0], ev.data[1])); }, 2, cb); -} -/** - * Compresses data with GZIP - * @param data The data to compress - * @param opts The compression options - * @returns The gzipped version of the data - */ -export function gzipSync(data, opts) { - if (!opts) - opts = {}; - var c = crc(), l = data.length; - c.p(data); - var d = dopt(data, opts, gzhl(opts), 8), s = d.length; - return gzh(d, opts), wbytes(d, s - 8, c.d()), wbytes(d, s - 4, l), d; -} -/** - * Streaming single or multi-member GZIP decompression - */ -var Gunzip = /*#__PURE__*/ (function () { - function Gunzip(opts, cb) { - this.v = 1; - this.r = 0; - Inflate.call(this, opts, cb); - } - /** - * Pushes a chunk to be GUNZIPped - * @param chunk The chunk to push - * @param final Whether this is the last chunk - */ - Gunzip.prototype.push = function (chunk, final) { - Inflate.prototype.e.call(this, chunk); - this.r += chunk.length; - if (this.v) { - var p = this.p.subarray(this.v - 1); - var s = p.length > 3 ? gzs(p) : 4; - if (s > p.length) { - if (!final) - return; - } - else if (this.v > 1 && this.onmember) { - this.onmember(this.r - p.length); - } - this.p = p.subarray(s), this.v = 0; - } - // necessary to prevent TS from using the closure value - // This allows for workerization to function correctly - Inflate.prototype.c.call(this, final); - // process concatenated GZIP - if (this.s.f && !this.s.l && !final) { - this.v = shft(this.s.p) + 9; - this.s = { i: 0 }; - this.o = new u8(0); - this.push(new u8(0), final); - } - }; - return Gunzip; -}()); -export { Gunzip }; -/** - * Asynchronous streaming single or multi-member GZIP decompression - */ -var AsyncGunzip = /*#__PURE__*/ (function () { - function AsyncGunzip(opts, cb) { - var _this = this; - astrmify([ - bInflt, - guze, - function () { return [astrm, Inflate, Gunzip]; } - ], this, StrmOpt.call(this, opts, cb), function (ev) { - var strm = new Gunzip(ev.data); - strm.onmember = function (offset) { return postMessage(offset); }; - onmessage = astrm(strm); - }, 9, 0, function (offset) { return _this.onmember && _this.onmember(offset); }); - } - return AsyncGunzip; -}()); -export { AsyncGunzip }; -export function gunzip(data, opts, cb) { - if (!cb) - cb = opts, opts = {}; - if (typeof cb != 'function') - err(7); - return cbify(data, opts, [ - bInflt, - guze, - function () { return [gunzipSync]; } - ], function (ev) { return pbf(gunzipSync(ev.data[0], ev.data[1])); }, 3, cb); -} -/** - * Expands GZIP data - * @param data The data to decompress - * @param opts The decompression options - * @returns The decompressed version of the data - */ -export function gunzipSync(data, opts) { - var st = gzs(data); - if (st + 8 > data.length) - err(6, 'invalid gzip data'); - return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary); -} -/** - * Streaming Zlib compression - */ -var Zlib = /*#__PURE__*/ (function () { - function Zlib(opts, cb) { - this.c = adler(); - this.v = 1; - Deflate.call(this, opts, cb); - } - /** - * Pushes a chunk to be zlibbed - * @param chunk The chunk to push - * @param final Whether this is the last chunk - */ - Zlib.prototype.push = function (chunk, final) { - this.c.p(chunk); - Deflate.prototype.push.call(this, chunk, final); - }; - Zlib.prototype.p = function (c, f) { - var raw = dopt(c, this.o, this.v && (this.o.dictionary ? 6 : 2), f && 4, this.s); - if (this.v) - zlh(raw, this.o), this.v = 0; - if (f) - wbytes(raw, raw.length - 4, this.c.d()); - this.ondata(raw, f); - }; - /** - * Flushes buffered uncompressed data. Useful to immediately retrieve the - * zlibbed output for small inputs. - */ - Zlib.prototype.flush = function () { - Deflate.prototype.flush.call(this); - }; - return Zlib; -}()); -export { Zlib }; -/** - * Asynchronous streaming Zlib compression - */ -var AsyncZlib = /*#__PURE__*/ (function () { - function AsyncZlib(opts, cb) { - astrmify([ - bDflt, - zle, - function () { return [astrm, Deflate, Zlib]; } - ], this, StrmOpt.call(this, opts, cb), function (ev) { - var strm = new Zlib(ev.data); - onmessage = astrm(strm); - }, 10, 1); - } - return AsyncZlib; -}()); -export { AsyncZlib }; -export function zlib(data, opts, cb) { - if (!cb) - cb = opts, opts = {}; - if (typeof cb != 'function') - err(7); - return cbify(data, opts, [ - bDflt, - zle, - function () { return [zlibSync]; } - ], function (ev) { return pbf(zlibSync(ev.data[0], ev.data[1])); }, 4, cb); -} -/** - * Compress data with Zlib - * @param data The data to compress - * @param opts The compression options - * @returns The zlib-compressed version of the data - */ -export function zlibSync(data, opts) { - if (!opts) - opts = {}; - var a = adler(); - a.p(data); - var d = dopt(data, opts, opts.dictionary ? 6 : 2, 4); - return zlh(d, opts), wbytes(d, d.length - 4, a.d()), d; -} -/** - * Streaming Zlib decompression - */ -var Unzlib = /*#__PURE__*/ (function () { - function Unzlib(opts, cb) { - Inflate.call(this, opts, cb); - this.v = opts && opts.dictionary ? 2 : 1; - } - /** - * Pushes a chunk to be unzlibbed - * @param chunk The chunk to push - * @param final Whether this is the last chunk - */ - Unzlib.prototype.push = function (chunk, final) { - Inflate.prototype.e.call(this, chunk); - if (this.v) { - if (this.p.length < 6 && !final) - return; - this.p = this.p.subarray(zls(this.p, this.v - 1)), this.v = 0; - } - if (final) { - if (this.p.length < 4) - err(6, 'invalid zlib data'); - this.p = this.p.subarray(0, -4); - } - // necessary to prevent TS from using the closure value - // This allows for workerization to function correctly - Inflate.prototype.c.call(this, final); - }; - return Unzlib; -}()); -export { Unzlib }; -/** - * Asynchronous streaming Zlib decompression - */ -var AsyncUnzlib = /*#__PURE__*/ (function () { - function AsyncUnzlib(opts, cb) { - astrmify([ - bInflt, - zule, - function () { return [astrm, Inflate, Unzlib]; } - ], this, StrmOpt.call(this, opts, cb), function (ev) { - var strm = new Unzlib(ev.data); - onmessage = astrm(strm); - }, 11, 0); - } - return AsyncUnzlib; -}()); -export { AsyncUnzlib }; -export function unzlib(data, opts, cb) { - if (!cb) - cb = opts, opts = {}; - if (typeof cb != 'function') - err(7); - return cbify(data, opts, [ - bInflt, - zule, - function () { return [unzlibSync]; } - ], function (ev) { return pbf(unzlibSync(ev.data[0], gopt(ev.data[1]))); }, 5, cb); -} -/** - * Expands Zlib data - * @param data The data to decompress - * @param opts The decompression options - * @returns The decompressed version of the data - */ -export function unzlibSync(data, opts) { - return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary); -} -// Default algorithm for compression (used because having a known output size allows faster decompression) -export { gzip as compress, AsyncGzip as AsyncCompress }; -export { gzipSync as compressSync, Gzip as Compress }; -/** - * Streaming GZIP, Zlib, or raw DEFLATE decompression - */ -var Decompress = /*#__PURE__*/ (function () { - function Decompress(opts, cb) { - this.o = StrmOpt.call(this, opts, cb) || {}; - this.G = Gunzip; - this.I = Inflate; - this.Z = Unzlib; - } - // init substream - // overriden by AsyncDecompress - Decompress.prototype.i = function () { - var _this = this; - this.s.ondata = function (dat, final) { - _this.ondata(dat, final); - }; - }; - /** - * Pushes a chunk to be decompressed - * @param chunk The chunk to push - * @param final Whether this is the last chunk - */ - Decompress.prototype.push = function (chunk, final) { - if (!this.ondata) - err(5); - if (!this.s) { - if (this.p && this.p.length) { - var n = new u8(this.p.length + chunk.length); - n.set(this.p), n.set(chunk, this.p.length); - } - else - this.p = chunk; - if (this.p.length > 2) { - this.s = (this.p[0] == 31 && this.p[1] == 139 && this.p[2] == 8) - ? new this.G(this.o) - : ((this.p[0] & 15) != 8 || (this.p[0] >> 4) > 7 || ((this.p[0] << 8 | this.p[1]) % 31)) - ? new this.I(this.o) - : new this.Z(this.o); - this.i(); - this.s.push(this.p, final); - this.p = null; - } - } - else - this.s.push(chunk, final); - }; - return Decompress; -}()); -export { Decompress }; -/** - * Asynchronous streaming GZIP, Zlib, or raw DEFLATE decompression - */ -var AsyncDecompress = /*#__PURE__*/ (function () { - function AsyncDecompress(opts, cb) { - Decompress.call(this, opts, cb); - this.queuedSize = 0; - this.G = AsyncGunzip; - this.I = AsyncInflate; - this.Z = AsyncUnzlib; - } - AsyncDecompress.prototype.i = function () { - var _this = this; - this.s.ondata = function (err, dat, final) { - _this.ondata(err, dat, final); - }; - this.s.ondrain = function (size) { - _this.queuedSize -= size; - if (_this.ondrain) - _this.ondrain(size); - }; - }; - /** - * Pushes a chunk to be decompressed - * @param chunk The chunk to push - * @param final Whether this is the last chunk - */ - AsyncDecompress.prototype.push = function (chunk, final) { - this.queuedSize += chunk.length; - Decompress.prototype.push.call(this, chunk, final); - }; - return AsyncDecompress; -}()); -export { AsyncDecompress }; -export function decompress(data, opts, cb) { - if (!cb) - cb = opts, opts = {}; - if (typeof cb != 'function') - err(7); - return (data[0] == 31 && data[1] == 139 && data[2] == 8) - ? gunzip(data, opts, cb) - : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31)) - ? inflate(data, opts, cb) - : unzlib(data, opts, cb); -} -/** - * Expands compressed GZIP, Zlib, or raw DEFLATE data, automatically detecting the format - * @param data The data to decompress - * @param opts The decompression options - * @returns The decompressed version of the data - */ -export function decompressSync(data, opts) { - return (data[0] == 31 && data[1] == 139 && data[2] == 8) - ? gunzipSync(data, opts) - : ((data[0] & 15) != 8 || (data[0] >> 4) > 7 || ((data[0] << 8 | data[1]) % 31)) - ? inflateSync(data, opts) - : unzlibSync(data, opts); -} -// flatten a directory structure -var fltn = function (d, p, t, o) { - for (var k in d) { - var val = d[k], n = p + k, op = o; - if (Array.isArray(val)) - op = mrg(o, val[1]), val = val[0]; - if (val instanceof u8) - t[n] = [val, op]; - else { - t[n += '/'] = [new u8(0), op]; - fltn(val, n, t, o); - } - } -}; -// text encoder -var te = typeof TextEncoder != 'undefined' && /*#__PURE__*/ new TextEncoder(); -// text decoder -var td = typeof TextDecoder != 'undefined' && /*#__PURE__*/ new TextDecoder(); -// text decoder stream -var tds = 0; -try { - td.decode(et, { stream: true }); - tds = 1; -} -catch (e) { } -// decode UTF8 -var dutf8 = function (d) { - for (var r = '', i = 0;;) { - var c = d[i++]; - var eb = (c > 127) + (c > 223) + (c > 239); - if (i + eb > d.length) - return { s: r, r: slc(d, i - 1) }; - if (!eb) - r += String.fromCharCode(c); - else if (eb == 3) { - c = ((c & 15) << 18 | (d[i++] & 63) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)) - 65536, - r += String.fromCharCode(55296 | (c >> 10), 56320 | (c & 1023)); - } - else if (eb & 1) - r += String.fromCharCode((c & 31) << 6 | (d[i++] & 63)); - else - r += String.fromCharCode((c & 15) << 12 | (d[i++] & 63) << 6 | (d[i++] & 63)); - } -}; -/** - * Streaming UTF-8 decoding - */ -var DecodeUTF8 = /*#__PURE__*/ (function () { - /** - * Creates a UTF-8 decoding stream - * @param cb The callback to call whenever data is decoded - */ - function DecodeUTF8(cb) { - this.ondata = cb; - if (tds) - this.t = new TextDecoder(); - else - this.p = et; - } - /** - * Pushes a chunk to be decoded from UTF-8 binary - * @param chunk The chunk to push - * @param final Whether this is the last chunk - */ - DecodeUTF8.prototype.push = function (chunk, final) { - if (!this.ondata) - err(5); - final = !!final; - if (this.t) { - this.ondata(this.t.decode(chunk, { stream: true }), final); - if (final) { - if (this.t.decode().length) - err(8); - this.t = null; - } - return; - } - if (!this.p) - err(4); - var dat = new u8(this.p.length + chunk.length); - dat.set(this.p); - dat.set(chunk, this.p.length); - var _a = dutf8(dat), s = _a.s, r = _a.r; - if (final) { - if (r.length) - err(8); - this.p = null; - } - else - this.p = r; - this.ondata(s, final); - }; - return DecodeUTF8; -}()); -export { DecodeUTF8 }; -/** - * Streaming UTF-8 encoding - */ -var EncodeUTF8 = /*#__PURE__*/ (function () { - /** - * Creates a UTF-8 decoding stream - * @param cb The callback to call whenever data is encoded - */ - function EncodeUTF8(cb) { - this.ondata = cb; - } - /** - * Pushes a chunk to be encoded to UTF-8 - * @param chunk The string data to push - * @param final Whether this is the last chunk - */ - EncodeUTF8.prototype.push = function (chunk, final) { - if (!this.ondata) - err(5); - if (this.d) - err(4); - this.ondata(strToU8(chunk), this.d = final || false); - }; - return EncodeUTF8; -}()); -export { EncodeUTF8 }; -/** - * Converts a string into a Uint8Array for use with compression/decompression methods - * @param str The string to encode - * @param latin1 Whether or not to interpret the data as Latin-1. This should - * not need to be true unless decoding a binary string. - * @returns The string encoded in UTF-8/Latin-1 binary - */ -export function strToU8(str, latin1) { - if (latin1) { - var ar_1 = new u8(str.length); - for (var i = 0; i < str.length; ++i) - ar_1[i] = str.charCodeAt(i); - return ar_1; - } - if (te) - return te.encode(str); - var l = str.length; - var ar = new u8(str.length + (str.length >> 1)); - var ai = 0; - var w = function (v) { ar[ai++] = v; }; - for (var i = 0; i < l; ++i) { - if (ai + 5 > ar.length) { - var n = new u8(ai + 8 + ((l - i) << 1)); - n.set(ar); - ar = n; - } - var c = str.charCodeAt(i); - if (c < 128 || latin1) - w(c); - else if (c < 2048) - w(192 | (c >> 6)), w(128 | (c & 63)); - else if (c > 55295 && c < 57344) - c = 65536 + (c & 1023 << 10) | (str.charCodeAt(++i) & 1023), - w(240 | (c >> 18)), w(128 | ((c >> 12) & 63)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63)); - else - w(224 | (c >> 12)), w(128 | ((c >> 6) & 63)), w(128 | (c & 63)); - } - return slc(ar, 0, ai); -} -/** - * Converts a Uint8Array to a string - * @param dat The data to decode to string - * @param latin1 Whether or not to interpret the data as Latin-1. This should - * not need to be true unless encoding to binary string. - * @returns The original UTF-8/Latin-1 string - */ -export function strFromU8(dat, latin1) { - if (latin1) { - var r = ''; - for (var i = 0; i < dat.length; i += 16384) - r += String.fromCharCode.apply(null, dat.subarray(i, i + 16384)); - return r; - } - else if (td) { - return td.decode(dat); - } - else { - var _a = dutf8(dat), s = _a.s, r = _a.r; - if (r.length) - err(8); - return s; - } -} -; -// deflate bit flag -var dbf = function (l) { return l == 1 ? 3 : l < 6 ? 2 : l == 9 ? 1 : 0; }; -// skip local zip header -var slzh = function (d, b) { return b + 30 + b2(d, b + 26) + b2(d, b + 28); }; -// read zip header -var zh = function (d, b, z) { - var fnl = b2(d, b + 28), fn = strFromU8(d.subarray(b + 46, b + 46 + fnl), !(b2(d, b + 8) & 2048)), es = b + 46 + fnl, bs = b4(d, b + 20); - var _a = z && bs == 4294967295 ? z64e(d, es) : [bs, b4(d, b + 24), b4(d, b + 42)], sc = _a[0], su = _a[1], off = _a[2]; - return [b2(d, b + 10), sc, su, fn, es + b2(d, b + 30) + b2(d, b + 32), off]; -}; -// read zip64 extra field -var z64e = function (d, b) { - for (; b2(d, b) != 1; b += 4 + b2(d, b + 2)) - ; - return [b8(d, b + 12), b8(d, b + 4), b8(d, b + 20)]; -}; -// extra field length -var exfl = function (ex) { - var le = 0; - if (ex) { - for (var k in ex) { - var l = ex[k].length; - if (l > 65535) - err(9); - le += l + 4; - } - } - return le; -}; -// write zip header -var wzh = function (d, b, f, fn, u, c, ce, co) { - var fl = fn.length, ex = f.extra, col = co && co.length; - var exl = exfl(ex); - wbytes(d, b, ce != null ? 0x2014B50 : 0x4034B50), b += 4; - if (ce != null) - d[b++] = 20, d[b++] = f.os; - d[b] = 20, b += 2; // spec compliance? what's that? - d[b++] = (f.flag << 1) | (c < 0 && 8), d[b++] = u && 8; - d[b++] = f.compression & 255, d[b++] = f.compression >> 8; - var dt = new Date(f.mtime == null ? Date.now() : f.mtime), y = dt.getFullYear() - 1980; - if (y < 0 || y > 119) - err(10); - wbytes(d, b, (y << 25) | ((dt.getMonth() + 1) << 21) | (dt.getDate() << 16) | (dt.getHours() << 11) | (dt.getMinutes() << 5) | (dt.getSeconds() >> 1)), b += 4; - if (c != -1) { - wbytes(d, b, f.crc); - wbytes(d, b + 4, c < 0 ? -c - 2 : c); - wbytes(d, b + 8, f.size); - } - wbytes(d, b + 12, fl); - wbytes(d, b + 14, exl), b += 16; - if (ce != null) { - wbytes(d, b, col); - wbytes(d, b + 6, f.attrs); - wbytes(d, b + 10, ce), b += 14; - } - d.set(fn, b); - b += fl; - if (exl) { - for (var k in ex) { - var exf = ex[k], l = exf.length; - wbytes(d, b, +k); - wbytes(d, b + 2, l); - d.set(exf, b + 4), b += 4 + l; - } - } - if (col) - d.set(co, b), b += col; - return b; -}; -// write zip footer (end of central directory) -var wzf = function (o, b, c, d, e) { - wbytes(o, b, 0x6054B50); // skip disk - wbytes(o, b + 8, c); - wbytes(o, b + 10, c); - wbytes(o, b + 12, d); - wbytes(o, b + 16, e); -}; -/** - * A pass-through stream to keep data uncompressed in a ZIP archive. - */ -var ZipPassThrough = /*#__PURE__*/ (function () { - /** - * Creates a pass-through stream that can be added to ZIP archives - * @param filename The filename to associate with this data stream - */ - function ZipPassThrough(filename) { - this.filename = filename; - this.c = crc(); - this.size = 0; - this.compression = 0; - } - /** - * Processes a chunk and pushes to the output stream. You can override this - * method in a subclass for custom behavior, but by default this passes - * the data through. You must call this.ondata(err, chunk, final) at some - * point in this method. - * @param chunk The chunk to process - * @param final Whether this is the last chunk - */ - ZipPassThrough.prototype.process = function (chunk, final) { - this.ondata(null, chunk, final); - }; - /** - * Pushes a chunk to be added. If you are subclassing this with a custom - * compression algorithm, note that you must push data from the source - * file only, pre-compression. - * @param chunk The chunk to push - * @param final Whether this is the last chunk - */ - ZipPassThrough.prototype.push = function (chunk, final) { - if (!this.ondata) - err(5); - this.c.p(chunk); - this.size += chunk.length; - if (final) - this.crc = this.c.d(); - this.process(chunk, final || false); - }; - return ZipPassThrough; -}()); -export { ZipPassThrough }; -// I don't extend because TypeScript extension adds 1kB of runtime bloat -/** - * Streaming DEFLATE compression for ZIP archives. Prefer using AsyncZipDeflate - * for better performance - */ -var ZipDeflate = /*#__PURE__*/ (function () { - /** - * Creates a DEFLATE stream that can be added to ZIP archives - * @param filename The filename to associate with this data stream - * @param opts The compression options - */ - function ZipDeflate(filename, opts) { - var _this = this; - if (!opts) - opts = {}; - ZipPassThrough.call(this, filename); - this.d = new Deflate(opts, function (dat, final) { - _this.ondata(null, dat, final); - }); - this.compression = 8; - this.flag = dbf(opts.level); - } - ZipDeflate.prototype.process = function (chunk, final) { - try { - this.d.push(chunk, final); - } - catch (e) { - this.ondata(e, null, final); - } - }; - /** - * Pushes a chunk to be deflated - * @param chunk The chunk to push - * @param final Whether this is the last chunk - */ - ZipDeflate.prototype.push = function (chunk, final) { - ZipPassThrough.prototype.push.call(this, chunk, final); - }; - return ZipDeflate; -}()); -export { ZipDeflate }; -/** - * Asynchronous streaming DEFLATE compression for ZIP archives - */ -var AsyncZipDeflate = /*#__PURE__*/ (function () { - /** - * Creates an asynchronous DEFLATE stream that can be added to ZIP archives - * @param filename The filename to associate with this data stream - * @param opts The compression options - */ - function AsyncZipDeflate(filename, opts) { - var _this = this; - if (!opts) - opts = {}; - ZipPassThrough.call(this, filename); - this.d = new AsyncDeflate(opts, function (err, dat, final) { - _this.ondata(err, dat, final); - }); - this.compression = 8; - this.flag = dbf(opts.level); - this.terminate = this.d.terminate; - } - AsyncZipDeflate.prototype.process = function (chunk, final) { - this.d.push(chunk, final); - }; - /** - * Pushes a chunk to be deflated - * @param chunk The chunk to push - * @param final Whether this is the last chunk - */ - AsyncZipDeflate.prototype.push = function (chunk, final) { - ZipPassThrough.prototype.push.call(this, chunk, final); - }; - return AsyncZipDeflate; -}()); -export { AsyncZipDeflate }; -// TODO: Better tree shaking -/** - * A zippable archive to which files can incrementally be added - */ -var Zip = /*#__PURE__*/ (function () { - /** - * Creates an empty ZIP archive to which files can be added - * @param cb The callback to call whenever data for the generated ZIP archive - * is available - */ - function Zip(cb) { - this.ondata = cb; - this.u = []; - this.d = 1; - } - /** - * Adds a file to the ZIP archive - * @param file The file stream to add - */ - Zip.prototype.add = function (file) { - var _this = this; - if (!this.ondata) - err(5); - // finishing or finished - if (this.d & 2) - this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, false); - else { - var f = strToU8(file.filename), fl_1 = f.length; - var com = file.comment, o = com && strToU8(com); - var u = fl_1 != file.filename.length || (o && (com.length != o.length)); - var hl_1 = fl_1 + exfl(file.extra) + 30; - if (fl_1 > 65535) - this.ondata(err(11, 0, 1), null, false); - var header = new u8(hl_1); - wzh(header, 0, file, f, u, -1); - var chks_1 = [header]; - var pAll_1 = function () { - for (var _i = 0, chks_2 = chks_1; _i < chks_2.length; _i++) { - var chk = chks_2[_i]; - _this.ondata(null, chk, false); - } - chks_1 = []; - }; - var tr_1 = this.d; - this.d = 0; - var ind_1 = this.u.length; - var uf_1 = mrg(file, { - f: f, - u: u, - o: o, - t: function () { - if (file.terminate) - file.terminate(); - }, - r: function () { - pAll_1(); - if (tr_1) { - var nxt = _this.u[ind_1 + 1]; - if (nxt) - nxt.r(); - else - _this.d = 1; - } - tr_1 = 1; - } - }); - var cl_1 = 0; - file.ondata = function (err, dat, final) { - if (err) { - _this.ondata(err, dat, final); - _this.terminate(); - } - else { - cl_1 += dat.length; - chks_1.push(dat); - if (final) { - var dd = new u8(16); - wbytes(dd, 0, 0x8074B50); - wbytes(dd, 4, file.crc); - wbytes(dd, 8, cl_1); - wbytes(dd, 12, file.size); - chks_1.push(dd); - uf_1.c = cl_1, uf_1.b = hl_1 + cl_1 + 16, uf_1.crc = file.crc, uf_1.size = file.size; - if (tr_1) - uf_1.r(); - tr_1 = 1; - } - else if (tr_1) - pAll_1(); - } - }; - this.u.push(uf_1); - } - }; - /** - * Ends the process of adding files and prepares to emit the final chunks. - * This *must* be called after adding all desired files for the resulting - * ZIP file to work properly. - */ - Zip.prototype.end = function () { - var _this = this; - if (this.d & 2) { - this.ondata(err(4 + (this.d & 1) * 8, 0, 1), null, true); - return; - } - if (this.d) - this.e(); - else - this.u.push({ - r: function () { - if (!(_this.d & 1)) - return; - _this.u.splice(-1, 1); - _this.e(); - }, - t: function () { } - }); - this.d = 3; - }; - Zip.prototype.e = function () { - var bt = 0, l = 0, tl = 0; - for (var _i = 0, _a = this.u; _i < _a.length; _i++) { - var f = _a[_i]; - tl += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0); - } - var out = new u8(tl + 22); - for (var _b = 0, _c = this.u; _b < _c.length; _b++) { - var f = _c[_b]; - wzh(out, bt, f, f.f, f.u, -f.c - 2, l, f.o); - bt += 46 + f.f.length + exfl(f.extra) + (f.o ? f.o.length : 0), l += f.b; - } - wzf(out, bt, this.u.length, tl, l); - this.ondata(null, out, true); - this.d = 2; - }; - /** - * A method to terminate any internal workers used by the stream. Subsequent - * calls to add() will fail. - */ - Zip.prototype.terminate = function () { - for (var _i = 0, _a = this.u; _i < _a.length; _i++) { - var f = _a[_i]; - f.t(); - } - this.d = 2; - }; - return Zip; -}()); -export { Zip }; -export function zip(data, opts, cb) { - if (!cb) - cb = opts, opts = {}; - if (typeof cb != 'function') - err(7); - var r = {}; - fltn(data, '', r, opts); - var k = Object.keys(r); - var lft = k.length, o = 0, tot = 0; - var slft = lft, files = new Array(lft); - var term = []; - var tAll = function () { - for (var i = 0; i < term.length; ++i) - term[i](); - }; - var cbd = function (a, b) { - mt(function () { cb(a, b); }); - }; - mt(function () { cbd = cb; }); - var cbf = function () { - var out = new u8(tot + 22), oe = o, cdl = tot - o; - tot = 0; - for (var i = 0; i < slft; ++i) { - var f = files[i]; - try { - var l = f.c.length; - wzh(out, tot, f, f.f, f.u, l); - var badd = 30 + f.f.length + exfl(f.extra); - var loc = tot + badd; - out.set(f.c, loc); - wzh(out, o, f, f.f, f.u, l, tot, f.m), o += 16 + badd + (f.m ? f.m.length : 0), tot = loc + l; - } - catch (e) { - return cbd(e, null); - } - } - wzf(out, o, files.length, cdl, oe); - cbd(null, out); - }; - if (!lft) - cbf(); - var _loop_1 = function (i) { - var fn = k[i]; - var _a = r[fn], file = _a[0], p = _a[1]; - var c = crc(), size = file.length; - c.p(file); - var f = strToU8(fn), s = f.length; - var com = p.comment, m = com && strToU8(com), ms = m && m.length; - var exl = exfl(p.extra); - var compression = p.level == 0 ? 0 : 8; - var cbl = function (e, d) { - if (e) { - tAll(); - cbd(e, null); - } - else { - var l = d.length; - files[i] = mrg(p, { - size: size, - crc: c.d(), - c: d, - f: f, - m: m, - u: s != fn.length || (m && (com.length != ms)), - compression: compression - }); - o += 30 + s + exl + l; - tot += 76 + 2 * (s + exl) + (ms || 0) + l; - if (!--lft) - cbf(); - } - }; - if (s > 65535) - cbl(err(11, 0, 1), null); - if (!compression) - cbl(null, file); - else if (size < 160000) { - try { - cbl(null, deflateSync(file, p)); - } - catch (e) { - cbl(e, null); - } - } - else - term.push(deflate(file, p, cbl)); - }; - // Cannot use lft because it can decrease - for (var i = 0; i < slft; ++i) { - _loop_1(i); - } - return tAll; -} -/** - * Synchronously creates a ZIP file. Prefer using `zip` for better performance - * with more than one file. - * @param data The directory structure for the ZIP archive - * @param opts The main options, merged with per-file options - * @returns The generated ZIP archive - */ -export function zipSync(data, opts) { - if (!opts) - opts = {}; - var r = {}; - var files = []; - fltn(data, '', r, opts); - var o = 0; - var tot = 0; - for (var fn in r) { - var _a = r[fn], file = _a[0], p = _a[1]; - var compression = p.level == 0 ? 0 : 8; - var f = strToU8(fn), s = f.length; - var com = p.comment, m = com && strToU8(com), ms = m && m.length; - var exl = exfl(p.extra); - if (s > 65535) - err(11); - var d = compression ? deflateSync(file, p) : file, l = d.length; - var c = crc(); - c.p(file); - files.push(mrg(p, { - size: file.length, - crc: c.d(), - c: d, - f: f, - m: m, - u: s != fn.length || (m && (com.length != ms)), - o: o, - compression: compression - })); - o += 30 + s + exl + l; - tot += 76 + 2 * (s + exl) + (ms || 0) + l; - } - var out = new u8(tot + 22), oe = o, cdl = tot - o; - for (var i = 0; i < files.length; ++i) { - var f = files[i]; - wzh(out, f.o, f, f.f, f.u, f.c.length); - var badd = 30 + f.f.length + exfl(f.extra); - out.set(f.c, f.o + badd); - wzh(out, o, f, f.f, f.u, f.c.length, f.o, f.m), o += 16 + badd + (f.m ? f.m.length : 0); - } - wzf(out, o, files.length, cdl, oe); - return out; -} -/** - * Streaming pass-through decompression for ZIP archives - */ -var UnzipPassThrough = /*#__PURE__*/ (function () { - function UnzipPassThrough() { - } - UnzipPassThrough.prototype.push = function (data, final) { - this.ondata(null, data, final); - }; - UnzipPassThrough.compression = 0; - return UnzipPassThrough; -}()); -export { UnzipPassThrough }; -/** - * Streaming DEFLATE decompression for ZIP archives. Prefer AsyncZipInflate for - * better performance. - */ -var UnzipInflate = /*#__PURE__*/ (function () { - /** - * Creates a DEFLATE decompression that can be used in ZIP archives - */ - function UnzipInflate() { - var _this = this; - this.i = new Inflate(function (dat, final) { - _this.ondata(null, dat, final); - }); - } - UnzipInflate.prototype.push = function (data, final) { - try { - this.i.push(data, final); - } - catch (e) { - this.ondata(e, null, final); - } - }; - UnzipInflate.compression = 8; - return UnzipInflate; -}()); -export { UnzipInflate }; -/** - * Asynchronous streaming DEFLATE decompression for ZIP archives - */ -var AsyncUnzipInflate = /*#__PURE__*/ (function () { - /** - * Creates a DEFLATE decompression that can be used in ZIP archives - */ - function AsyncUnzipInflate(_, sz) { - var _this = this; - if (sz < 320000) { - this.i = new Inflate(function (dat, final) { - _this.ondata(null, dat, final); - }); - } - else { - this.i = new AsyncInflate(function (err, dat, final) { - _this.ondata(err, dat, final); - }); - this.terminate = this.i.terminate; - } - } - AsyncUnzipInflate.prototype.push = function (data, final) { - if (this.i.terminate) - data = slc(data, 0); - this.i.push(data, final); - }; - AsyncUnzipInflate.compression = 8; - return AsyncUnzipInflate; -}()); -export { AsyncUnzipInflate }; -/** - * A ZIP archive decompression stream that emits files as they are discovered - */ -var Unzip = /*#__PURE__*/ (function () { - /** - * Creates a ZIP decompression stream - * @param cb The callback to call whenever a file in the ZIP archive is found - */ - function Unzip(cb) { - this.onfile = cb; - this.k = []; - this.o = { - 0: UnzipPassThrough - }; - this.p = et; - } - /** - * Pushes a chunk to be unzipped - * @param chunk The chunk to push - * @param final Whether this is the last chunk - */ - Unzip.prototype.push = function (chunk, final) { - var _this = this; - if (!this.onfile) - err(5); - if (!this.p) - err(4); - if (this.c > 0) { - var len = Math.min(this.c, chunk.length); - var toAdd = chunk.subarray(0, len); - this.c -= len; - if (this.d) - this.d.push(toAdd, !this.c); - else - this.k[0].push(toAdd); - chunk = chunk.subarray(len); - if (chunk.length) - return this.push(chunk, final); - } - else { - var f = 0, i = 0, is = void 0, buf = void 0; - if (!this.p.length) - buf = chunk; - else if (!chunk.length) - buf = this.p; - else { - buf = new u8(this.p.length + chunk.length); - buf.set(this.p), buf.set(chunk, this.p.length); - } - var l = buf.length, oc = this.c, add = oc && this.d; - var _loop_2 = function () { - var _a; - var sig = b4(buf, i); - if (sig == 0x4034B50) { - f = 1, is = i; - this_1.d = null; - this_1.c = 0; - var bf = b2(buf, i + 6), cmp_1 = b2(buf, i + 8), u = bf & 2048, dd = bf & 8, fnl = b2(buf, i + 26), es = b2(buf, i + 28); - if (l > i + 30 + fnl + es) { - var chks_3 = []; - this_1.k.unshift(chks_3); - f = 2; - var sc_1 = b4(buf, i + 18), su_1 = b4(buf, i + 22); - var fn_1 = strFromU8(buf.subarray(i + 30, i += 30 + fnl), !u); - if (sc_1 == 4294967295) { - _a = dd ? [-2] : z64e(buf, i), sc_1 = _a[0], su_1 = _a[1]; - } - else if (dd) - sc_1 = -1; - i += es; - this_1.c = sc_1; - var d_1; - var file_1 = { - name: fn_1, - compression: cmp_1, - start: function () { - if (!file_1.ondata) - err(5); - if (!sc_1) - file_1.ondata(null, et, true); - else { - var ctr = _this.o[cmp_1]; - if (!ctr) - file_1.ondata(err(14, 'unknown compression type ' + cmp_1, 1), null, false); - d_1 = sc_1 < 0 ? new ctr(fn_1) : new ctr(fn_1, sc_1, su_1); - d_1.ondata = function (err, dat, final) { file_1.ondata(err, dat, final); }; - for (var _i = 0, chks_4 = chks_3; _i < chks_4.length; _i++) { - var dat = chks_4[_i]; - d_1.push(dat, false); - } - if (_this.k[0] == chks_3 && _this.c) - _this.d = d_1; - else - d_1.push(et, true); - } - }, - terminate: function () { - if (d_1 && d_1.terminate) - d_1.terminate(); - } - }; - if (sc_1 >= 0) - file_1.size = sc_1, file_1.originalSize = su_1; - this_1.onfile(file_1); - } - return "break"; - } - else if (oc) { - if (sig == 0x8074B50) { - is = i += 12 + (oc == -2 && 8), f = 3, this_1.c = 0; - return "break"; - } - else if (sig == 0x2014B50) { - is = i -= 4, f = 3, this_1.c = 0; - return "break"; - } - } - }; - var this_1 = this; - for (; i < l - 4; ++i) { - var state_1 = _loop_2(); - if (state_1 === "break") - break; - } - this.p = et; - if (oc < 0) { - var dat = f ? buf.subarray(0, is - 12 - (oc == -2 && 8) - (b4(buf, is - 16) == 0x8074B50 && 4)) : buf.subarray(0, i); - if (add) - add.push(dat, !!f); - else - this.k[+(f == 2)].push(dat); - } - if (f & 2) - return this.push(buf.subarray(i), final); - this.p = buf.subarray(i); - } - if (final) { - if (this.c) - err(13); - this.p = null; - } - }; - /** - * Registers a decoder with the stream, allowing for files compressed with - * the compression type provided to be expanded correctly - * @param decoder The decoder constructor - */ - Unzip.prototype.register = function (decoder) { - this.o[decoder.compression] = decoder; - }; - return Unzip; -}()); -export { Unzip }; -var mt = typeof queueMicrotask == 'function' ? queueMicrotask : typeof setTimeout == 'function' ? setTimeout : function (fn) { fn(); }; -export function unzip(data, opts, cb) { - if (!cb) - cb = opts, opts = {}; - if (typeof cb != 'function') - err(7); - var term = []; - var tAll = function () { - for (var i = 0; i < term.length; ++i) - term[i](); - }; - var files = {}; - var cbd = function (a, b) { - mt(function () { cb(a, b); }); - }; - mt(function () { cbd = cb; }); - var e = data.length - 22; - for (; b4(data, e) != 0x6054B50; --e) { - if (!e || data.length - e > 65558) { - cbd(err(13, 0, 1), null); - return tAll; - } - } - ; - var lft = b2(data, e + 8); - if (lft) { - var c = lft; - var o = b4(data, e + 16); - var z = o == 4294967295 || c == 65535; - if (z) { - var ze = b4(data, e - 12); - z = b4(data, ze) == 0x6064B50; - if (z) { - c = lft = b4(data, ze + 32); - o = b4(data, ze + 48); - } - } - var fltr = opts && opts.filter; - var _loop_3 = function (i) { - var _a = zh(data, o, z), c_1 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off); - o = no; - var cbl = function (e, d) { - if (e) { - tAll(); - cbd(e, null); - } - else { - if (d) - files[fn] = d; - if (!--lft) - cbd(null, files); - } - }; - if (!fltr || fltr({ - name: fn, - size: sc, - originalSize: su, - compression: c_1 - })) { - if (!c_1) - cbl(null, slc(data, b, b + sc)); - else if (c_1 == 8) { - var infl = data.subarray(b, b + sc); - // Synchronously decompress under 512KB, or barely-compressed data - if (su < 524288 || sc > 0.8 * su) { - try { - cbl(null, inflateSync(infl, { out: new u8(su) })); - } - catch (e) { - cbl(e, null); - } - } - else - term.push(inflate(infl, { size: su }, cbl)); - } - else - cbl(err(14, 'unknown compression type ' + c_1, 1), null); - } - else - cbl(null, null); - }; - for (var i = 0; i < c; ++i) { - _loop_3(i); - } - } - else - cbd(null, {}); - return tAll; -} -/** - * Synchronously decompresses a ZIP archive. Prefer using `unzip` for better - * performance with more than one file. - * @param data The raw compressed ZIP file - * @param opts The ZIP extraction options - * @returns The decompressed files - */ -export function unzipSync(data, opts) { - var files = {}; - var e = data.length - 22; - for (; b4(data, e) != 0x6054B50; --e) { - if (!e || data.length - e > 65558) - err(13); - } - ; - var c = b2(data, e + 8); - if (!c) - return {}; - var o = b4(data, e + 16); - var z = o == 4294967295 || c == 65535; - if (z) { - var ze = b4(data, e - 12); - z = b4(data, ze) == 0x6064B50; - if (z) { - c = b4(data, ze + 32); - o = b4(data, ze + 48); - } - } - var fltr = opts && opts.filter; - for (var i = 0; i < c; ++i) { - var _a = zh(data, o, z), c_2 = _a[0], sc = _a[1], su = _a[2], fn = _a[3], no = _a[4], off = _a[5], b = slzh(data, off); - o = no; - if (!fltr || fltr({ - name: fn, - size: sc, - originalSize: su, - compression: c_2 - })) { - if (!c_2) - files[fn] = slc(data, b, b + sc); - else if (c_2 == 8) - files[fn] = inflateSync(data.subarray(b, b + sc), { out: new u8(su) }); - else - err(14, 'unknown compression type ' + c_2); - } - } - return files; -} diff --git a/claude-code-source/node_modules/figures/index.js b/claude-code-source/node_modules/figures/index.js deleted file mode 100644 index 642bce72..00000000 --- a/claude-code-source/node_modules/figures/index.js +++ /dev/null @@ -1,292 +0,0 @@ -import isUnicodeSupported from 'is-unicode-supported'; - -const common = { - circleQuestionMark: '(?)', - questionMarkPrefix: '(?)', - square: '█', - squareDarkShade: '▓', - squareMediumShade: '▒', - squareLightShade: '░', - squareTop: '▀', - squareBottom: '▄', - squareLeft: '▌', - squareRight: '▐', - squareCenter: '■', - bullet: '●', - dot: '․', - ellipsis: '…', - pointerSmall: '›', - triangleUp: '▲', - triangleUpSmall: '▴', - triangleDown: '▼', - triangleDownSmall: '▾', - triangleLeftSmall: '◂', - triangleRightSmall: '▸', - home: '⌂', - heart: '♥', - musicNote: '♪', - musicNoteBeamed: '♫', - arrowUp: '↑', - arrowDown: '↓', - arrowLeft: '←', - arrowRight: '→', - arrowLeftRight: '↔', - arrowUpDown: '↕', - almostEqual: '≈', - notEqual: '≠', - lessOrEqual: '≤', - greaterOrEqual: '≥', - identical: '≡', - infinity: '∞', - subscriptZero: '₀', - subscriptOne: '₁', - subscriptTwo: '₂', - subscriptThree: '₃', - subscriptFour: '₄', - subscriptFive: '₅', - subscriptSix: '₆', - subscriptSeven: '₇', - subscriptEight: '₈', - subscriptNine: '₉', - oneHalf: '½', - oneThird: '⅓', - oneQuarter: '¼', - oneFifth: '⅕', - oneSixth: '⅙', - oneEighth: '⅛', - twoThirds: '⅔', - twoFifths: '⅖', - threeQuarters: '¾', - threeFifths: '⅗', - threeEighths: '⅜', - fourFifths: '⅘', - fiveSixths: '⅚', - fiveEighths: '⅝', - sevenEighths: '⅞', - line: '─', - lineBold: '━', - lineDouble: '═', - lineDashed0: '┄', - lineDashed1: '┅', - lineDashed2: '┈', - lineDashed3: '┉', - lineDashed4: '╌', - lineDashed5: '╍', - lineDashed6: '╴', - lineDashed7: '╶', - lineDashed8: '╸', - lineDashed9: '╺', - lineDashed10: '╼', - lineDashed11: '╾', - lineDashed12: '−', - lineDashed13: '–', - lineDashed14: '‐', - lineDashed15: '⁃', - lineVertical: '│', - lineVerticalBold: '┃', - lineVerticalDouble: '║', - lineVerticalDashed0: '┆', - lineVerticalDashed1: '┇', - lineVerticalDashed2: '┊', - lineVerticalDashed3: '┋', - lineVerticalDashed4: '╎', - lineVerticalDashed5: '╏', - lineVerticalDashed6: '╵', - lineVerticalDashed7: '╷', - lineVerticalDashed8: '╹', - lineVerticalDashed9: '╻', - lineVerticalDashed10: '╽', - lineVerticalDashed11: '╿', - lineDownLeft: '┐', - lineDownLeftArc: '╮', - lineDownBoldLeftBold: '┓', - lineDownBoldLeft: '┒', - lineDownLeftBold: '┑', - lineDownDoubleLeftDouble: '╗', - lineDownDoubleLeft: '╖', - lineDownLeftDouble: '╕', - lineDownRight: '┌', - lineDownRightArc: '╭', - lineDownBoldRightBold: '┏', - lineDownBoldRight: '┎', - lineDownRightBold: '┍', - lineDownDoubleRightDouble: '╔', - lineDownDoubleRight: '╓', - lineDownRightDouble: '╒', - lineUpLeft: '┘', - lineUpLeftArc: '╯', - lineUpBoldLeftBold: '┛', - lineUpBoldLeft: '┚', - lineUpLeftBold: '┙', - lineUpDoubleLeftDouble: '╝', - lineUpDoubleLeft: '╜', - lineUpLeftDouble: '╛', - lineUpRight: '└', - lineUpRightArc: '╰', - lineUpBoldRightBold: '┗', - lineUpBoldRight: '┖', - lineUpRightBold: '┕', - lineUpDoubleRightDouble: '╚', - lineUpDoubleRight: '╙', - lineUpRightDouble: '╘', - lineUpDownLeft: '┤', - lineUpBoldDownBoldLeftBold: '┫', - lineUpBoldDownBoldLeft: '┨', - lineUpDownLeftBold: '┥', - lineUpBoldDownLeftBold: '┩', - lineUpDownBoldLeftBold: '┪', - lineUpDownBoldLeft: '┧', - lineUpBoldDownLeft: '┦', - lineUpDoubleDownDoubleLeftDouble: '╣', - lineUpDoubleDownDoubleLeft: '╢', - lineUpDownLeftDouble: '╡', - lineUpDownRight: '├', - lineUpBoldDownBoldRightBold: '┣', - lineUpBoldDownBoldRight: '┠', - lineUpDownRightBold: '┝', - lineUpBoldDownRightBold: '┡', - lineUpDownBoldRightBold: '┢', - lineUpDownBoldRight: '┟', - lineUpBoldDownRight: '┞', - lineUpDoubleDownDoubleRightDouble: '╠', - lineUpDoubleDownDoubleRight: '╟', - lineUpDownRightDouble: '╞', - lineDownLeftRight: '┬', - lineDownBoldLeftBoldRightBold: '┳', - lineDownLeftBoldRightBold: '┯', - lineDownBoldLeftRight: '┰', - lineDownBoldLeftBoldRight: '┱', - lineDownBoldLeftRightBold: '┲', - lineDownLeftRightBold: '┮', - lineDownLeftBoldRight: '┭', - lineDownDoubleLeftDoubleRightDouble: '╦', - lineDownDoubleLeftRight: '╥', - lineDownLeftDoubleRightDouble: '╤', - lineUpLeftRight: '┴', - lineUpBoldLeftBoldRightBold: '┻', - lineUpLeftBoldRightBold: '┷', - lineUpBoldLeftRight: '┸', - lineUpBoldLeftBoldRight: '┹', - lineUpBoldLeftRightBold: '┺', - lineUpLeftRightBold: '┶', - lineUpLeftBoldRight: '┵', - lineUpDoubleLeftDoubleRightDouble: '╩', - lineUpDoubleLeftRight: '╨', - lineUpLeftDoubleRightDouble: '╧', - lineUpDownLeftRight: '┼', - lineUpBoldDownBoldLeftBoldRightBold: '╋', - lineUpDownBoldLeftBoldRightBold: '╈', - lineUpBoldDownLeftBoldRightBold: '╇', - lineUpBoldDownBoldLeftRightBold: '╊', - lineUpBoldDownBoldLeftBoldRight: '╉', - lineUpBoldDownLeftRight: '╀', - lineUpDownBoldLeftRight: '╁', - lineUpDownLeftBoldRight: '┽', - lineUpDownLeftRightBold: '┾', - lineUpBoldDownBoldLeftRight: '╂', - lineUpDownLeftBoldRightBold: '┿', - lineUpBoldDownLeftBoldRight: '╃', - lineUpBoldDownLeftRightBold: '╄', - lineUpDownBoldLeftBoldRight: '╅', - lineUpDownBoldLeftRightBold: '╆', - lineUpDoubleDownDoubleLeftDoubleRightDouble: '╬', - lineUpDoubleDownDoubleLeftRight: '╫', - lineUpDownLeftDoubleRightDouble: '╪', - lineCross: '╳', - lineBackslash: '╲', - lineSlash: '╱', -}; - -const specialMainSymbols = { - tick: '✔', - info: 'ℹ', - warning: '⚠', - cross: '✘', - squareSmall: '◻', - squareSmallFilled: '◼', - circle: '◯', - circleFilled: '◉', - circleDotted: '◌', - circleDouble: '◎', - circleCircle: 'ⓞ', - circleCross: 'ⓧ', - circlePipe: 'Ⓘ', - radioOn: '◉', - radioOff: '◯', - checkboxOn: '☒', - checkboxOff: '☐', - checkboxCircleOn: 'ⓧ', - checkboxCircleOff: 'Ⓘ', - pointer: '❯', - triangleUpOutline: '△', - triangleLeft: '◀', - triangleRight: '▶', - lozenge: '◆', - lozengeOutline: '◇', - hamburger: '☰', - smiley: '㋡', - mustache: '෴', - star: '★', - play: '▶', - nodejs: '⬢', - oneSeventh: '⅐', - oneNinth: '⅑', - oneTenth: '⅒', -}; - -const specialFallbackSymbols = { - tick: '√', - info: 'i', - warning: '‼', - cross: '×', - squareSmall: '□', - squareSmallFilled: '■', - circle: '( )', - circleFilled: '(*)', - circleDotted: '( )', - circleDouble: '( )', - circleCircle: '(○)', - circleCross: '(×)', - circlePipe: '(│)', - radioOn: '(*)', - radioOff: '( )', - checkboxOn: '[×]', - checkboxOff: '[ ]', - checkboxCircleOn: '(×)', - checkboxCircleOff: '( )', - pointer: '>', - triangleUpOutline: '∆', - triangleLeft: '◄', - triangleRight: '►', - lozenge: '♦', - lozengeOutline: '◊', - hamburger: '≡', - smiley: '☺', - mustache: '┌─┐', - star: '✶', - play: '►', - nodejs: '♦', - oneSeventh: '1/7', - oneNinth: '1/9', - oneTenth: '1/10', -}; - -export const mainSymbols = {...common, ...specialMainSymbols}; -export const fallbackSymbols = {...common, ...specialFallbackSymbols}; - -const shouldUseMain = isUnicodeSupported(); -const figures = shouldUseMain ? mainSymbols : fallbackSymbols; -export default figures; - -const replacements = Object.entries(specialMainSymbols); - -// On terminals which do not support Unicode symbols, substitute them to other symbols -export const replaceSymbols = (string, {useFallback = !shouldUseMain} = {}) => { - if (useFallback) { - for (const [key, mainSymbol] of replacements) { - string = string.replaceAll(mainSymbol, fallbackSymbols[key]); - } - } - - return string; -}; diff --git a/claude-code-source/node_modules/flora-colossus/lib/Walker.js b/claude-code-source/node_modules/flora-colossus/lib/Walker.js deleted file mode 100644 index 084dd698..00000000 --- a/claude-code-source/node_modules/flora-colossus/lib/Walker.js +++ /dev/null @@ -1,152 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Walker = void 0; -const debug = require("debug"); -const fs = require("fs-extra"); -const path = require("path"); -const depTypes_1 = require("./depTypes"); -const nativeModuleTypes_1 = require("./nativeModuleTypes"); -const d = debug('flora-colossus'); -class Walker { - constructor(modulePath) { - this.modules = []; - this.walkHistory = new Set(); - this.cache = null; - if (!modulePath || typeof modulePath !== 'string') { - throw new Error('modulePath must be provided as a string'); - } - d(`creating walker with rootModule=${modulePath}`); - this.rootModule = modulePath; - } - relativeModule(rootPath, moduleName) { - return path.resolve(rootPath, 'node_modules', moduleName); - } - async loadPackageJSON(modulePath) { - const pJPath = path.resolve(modulePath, 'package.json'); - if (await fs.pathExists(pJPath)) { - const pJ = await fs.readJson(pJPath); - if (!pJ.dependencies) - pJ.dependencies = {}; - if (!pJ.devDependencies) - pJ.devDependencies = {}; - if (!pJ.optionalDependencies) - pJ.optionalDependencies = {}; - return pJ; - } - return null; - } - async walkDependenciesForModuleInModule(moduleName, modulePath, depType) { - let testPath = modulePath; - let discoveredPath = null; - let lastRelative = null; - // Try find it while searching recursively up the tree - while (!discoveredPath && this.relativeModule(testPath, moduleName) !== lastRelative) { - lastRelative = this.relativeModule(testPath, moduleName); - if (await fs.pathExists(lastRelative)) { - discoveredPath = lastRelative; - } - else { - if (path.basename(path.dirname(testPath)) !== 'node_modules') { - testPath = path.dirname(testPath); - } - testPath = path.dirname(path.dirname(testPath)); - } - } - // If we can't find it the install is probably buggered - if (!discoveredPath && depType !== depTypes_1.DepType.OPTIONAL && depType !== depTypes_1.DepType.DEV_OPTIONAL) { - throw new Error(`Failed to locate module "${moduleName}" from "${modulePath}" - - This normally means that either you have deleted this package already somehow (check your ignore settings if using electron-packager). Or your module installation failed.`); - } - // If we can find it let's do the same thing for that module - if (discoveredPath) { - await this.walkDependenciesForModule(discoveredPath, depType); - } - } - async detectNativeModuleType(modulePath, pJ) { - if (pJ.dependencies['prebuild-install']) { - return nativeModuleTypes_1.NativeModuleType.PREBUILD; - } - else if (await fs.pathExists(path.join(modulePath, 'binding.gyp'))) { - return nativeModuleTypes_1.NativeModuleType.NODE_GYP; - } - return nativeModuleTypes_1.NativeModuleType.NONE; - } - async walkDependenciesForModule(modulePath, depType) { - d('walk reached:', modulePath, ' Type is:', depTypes_1.DepType[depType]); - // We have already traversed this module - if (this.walkHistory.has(modulePath)) { - d('already walked this route'); - // Find the existing module reference - const existingModule = this.modules.find(module => module.path === modulePath); - // If the depType we are traversing with now is higher than the - // last traversal then update it (prod superseeds dev for instance) - if ((0, depTypes_1.depTypeGreater)(depType, existingModule.depType)) { - d(`existing module has a type of "${existingModule.depType}", new module type would be "${depType}" therefore updating`); - existingModule.depType = depType; - } - return; - } - const pJ = await this.loadPackageJSON(modulePath); - // If the module doesn't have a package.json file it is probably a - // dead install from yarn (they dont clean up for some reason) - if (!pJ) { - d('walk hit a dead end, this module is incomplete'); - return; - } - // Record this module as being traversed - this.walkHistory.add(modulePath); - this.modules.push({ - depType, - nativeModuleType: await this.detectNativeModuleType(modulePath, pJ), - path: modulePath, - name: pJ.name, - }); - // For every prod dep - for (const moduleName in pJ.dependencies) { - // npm decides it's a funny thing to put optional dependencies in the "dependencies" section - // after install, because that makes perfect sense - if (moduleName in pJ.optionalDependencies) { - d(`found ${moduleName} in prod deps of ${modulePath} but it is also marked optional`); - continue; - } - await this.walkDependenciesForModuleInModule(moduleName, modulePath, (0, depTypes_1.childDepType)(depType, depTypes_1.DepType.PROD)); - } - // For every optional dep - for (const moduleName in pJ.optionalDependencies) { - await this.walkDependenciesForModuleInModule(moduleName, modulePath, (0, depTypes_1.childDepType)(depType, depTypes_1.DepType.OPTIONAL)); - } - // For every dev dep, but only if we are in the root module - if (depType === depTypes_1.DepType.ROOT) { - d('we\'re still at the beginning, walking down the dev route'); - for (const moduleName in pJ.devDependencies) { - await this.walkDependenciesForModuleInModule(moduleName, modulePath, (0, depTypes_1.childDepType)(depType, depTypes_1.DepType.DEV)); - } - } - } - async walkTree() { - d('starting tree walk'); - if (!this.cache) { - this.cache = new Promise(async (resolve, reject) => { - this.modules = []; - try { - await this.walkDependenciesForModule(this.rootModule, depTypes_1.DepType.ROOT); - } - catch (err) { - reject(err); - return; - } - resolve(this.modules); - }); - } - else { - d('tree walk in progress / completed already, waiting for existing walk to complete'); - } - return await this.cache; - } - getRootModule() { - return this.rootModule; - } -} -exports.Walker = Walker; -//# sourceMappingURL=Walker.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/flora-colossus/lib/depTypes.js b/claude-code-source/node_modules/flora-colossus/lib/depTypes.js deleted file mode 100644 index 906e63f9..00000000 --- a/claude-code-source/node_modules/flora-colossus/lib/depTypes.js +++ /dev/null @@ -1,95 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.childDepType = exports.depTypeGreater = exports.DepType = void 0; -var DepType; -(function (DepType) { - DepType[DepType["PROD"] = 0] = "PROD"; - DepType[DepType["DEV"] = 1] = "DEV"; - DepType[DepType["OPTIONAL"] = 2] = "OPTIONAL"; - DepType[DepType["DEV_OPTIONAL"] = 3] = "DEV_OPTIONAL"; - DepType[DepType["ROOT"] = 4] = "ROOT"; -})(DepType = exports.DepType || (exports.DepType = {})); -const depTypeGreater = (newType, existing) => { - switch (existing) { - case DepType.DEV: - switch (newType) { - case DepType.OPTIONAL: - case DepType.PROD: - case DepType.ROOT: - return true; - case DepType.DEV: - case DepType.DEV_OPTIONAL: - default: - return false; - } - case DepType.DEV_OPTIONAL: - switch (newType) { - case DepType.OPTIONAL: - case DepType.PROD: - case DepType.ROOT: - case DepType.DEV: - return true; - case DepType.DEV_OPTIONAL: - default: - return false; - } - case DepType.OPTIONAL: - switch (newType) { - case DepType.PROD: - case DepType.ROOT: - return true; - case DepType.OPTIONAL: - case DepType.DEV: - case DepType.DEV_OPTIONAL: - default: - return false; - } - case DepType.PROD: - switch (newType) { - case DepType.ROOT: - return true; - case DepType.PROD: - case DepType.OPTIONAL: - case DepType.DEV: - case DepType.DEV_OPTIONAL: - default: - return false; - } - case DepType.ROOT: - switch (newType) { - case DepType.ROOT: - case DepType.PROD: - case DepType.OPTIONAL: - case DepType.DEV: - case DepType.DEV_OPTIONAL: - default: - return false; - } - default: - return false; - } -}; -exports.depTypeGreater = depTypeGreater; -const childDepType = (parentType, childType) => { - if (childType === DepType.ROOT) { - throw new Error('Something went wrong, a child dependency can\'t be marked as the ROOT'); - } - switch (parentType) { - case DepType.ROOT: - return childType; - case DepType.PROD: - if (childType === DepType.OPTIONAL) - return DepType.OPTIONAL; - return DepType.PROD; - case DepType.OPTIONAL: - return DepType.OPTIONAL; - case DepType.DEV_OPTIONAL: - return DepType.DEV_OPTIONAL; - case DepType.DEV: - if (childType === DepType.OPTIONAL) - return DepType.DEV_OPTIONAL; - return DepType.DEV; - } -}; -exports.childDepType = childDepType; -//# sourceMappingURL=depTypes.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/flora-colossus/lib/index.js b/claude-code-source/node_modules/flora-colossus/lib/index.js deleted file mode 100644 index 7a0505e0..00000000 --- a/claude-code-source/node_modules/flora-colossus/lib/index.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -__exportStar(require("./Walker"), exports); -__exportStar(require("./depTypes"), exports); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/flora-colossus/lib/nativeModuleTypes.js b/claude-code-source/node_modules/flora-colossus/lib/nativeModuleTypes.js deleted file mode 100644 index 70019b3b..00000000 --- a/claude-code-source/node_modules/flora-colossus/lib/nativeModuleTypes.js +++ /dev/null @@ -1,10 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.NativeModuleType = void 0; -var NativeModuleType; -(function (NativeModuleType) { - NativeModuleType[NativeModuleType["NONE"] = 0] = "NONE"; - NativeModuleType[NativeModuleType["NODE_GYP"] = 1] = "NODE_GYP"; - NativeModuleType[NativeModuleType["PREBUILD"] = 2] = "PREBUILD"; -})(NativeModuleType = exports.NativeModuleType || (exports.NativeModuleType = {})); -//# sourceMappingURL=nativeModuleTypes.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/copy/copy-sync.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/copy/copy-sync.js deleted file mode 100644 index 551abe0c..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/copy/copy-sync.js +++ /dev/null @@ -1,169 +0,0 @@ -'use strict' - -const fs = require('graceful-fs') -const path = require('path') -const mkdirsSync = require('../mkdirs').mkdirsSync -const utimesMillisSync = require('../util/utimes').utimesMillisSync -const stat = require('../util/stat') - -function copySync (src, dest, opts) { - if (typeof opts === 'function') { - opts = { filter: opts } - } - - opts = opts || {} - opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now - opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber - - // Warn about using preserveTimestamps on 32-bit node - if (opts.preserveTimestamps && process.arch === 'ia32') { - process.emitWarning( - 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' + - '\tsee https://github.com/jprichardson/node-fs-extra/issues/269', - 'Warning', 'fs-extra-WARN0002' - ) - } - - const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy', opts) - stat.checkParentPathsSync(src, srcStat, dest, 'copy') - return handleFilterAndCopy(destStat, src, dest, opts) -} - -function handleFilterAndCopy (destStat, src, dest, opts) { - if (opts.filter && !opts.filter(src, dest)) return - const destParent = path.dirname(dest) - if (!fs.existsSync(destParent)) mkdirsSync(destParent) - return getStats(destStat, src, dest, opts) -} - -function startCopy (destStat, src, dest, opts) { - if (opts.filter && !opts.filter(src, dest)) return - return getStats(destStat, src, dest, opts) -} - -function getStats (destStat, src, dest, opts) { - const statSync = opts.dereference ? fs.statSync : fs.lstatSync - const srcStat = statSync(src) - - if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts) - else if (srcStat.isFile() || - srcStat.isCharacterDevice() || - srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts) - else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts) - else if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`) - else if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`) - throw new Error(`Unknown file: ${src}`) -} - -function onFile (srcStat, destStat, src, dest, opts) { - if (!destStat) return copyFile(srcStat, src, dest, opts) - return mayCopyFile(srcStat, src, dest, opts) -} - -function mayCopyFile (srcStat, src, dest, opts) { - if (opts.overwrite) { - fs.unlinkSync(dest) - return copyFile(srcStat, src, dest, opts) - } else if (opts.errorOnExist) { - throw new Error(`'${dest}' already exists`) - } -} - -function copyFile (srcStat, src, dest, opts) { - fs.copyFileSync(src, dest) - if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest) - return setDestMode(dest, srcStat.mode) -} - -function handleTimestamps (srcMode, src, dest) { - // Make sure the file is writable before setting the timestamp - // otherwise open fails with EPERM when invoked with 'r+' - // (through utimes call) - if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode) - return setDestTimestamps(src, dest) -} - -function fileIsNotWritable (srcMode) { - return (srcMode & 0o200) === 0 -} - -function makeFileWritable (dest, srcMode) { - return setDestMode(dest, srcMode | 0o200) -} - -function setDestMode (dest, srcMode) { - return fs.chmodSync(dest, srcMode) -} - -function setDestTimestamps (src, dest) { - // The initial srcStat.atime cannot be trusted - // because it is modified by the read(2) system call - // (See https://nodejs.org/api/fs.html#fs_stat_time_values) - const updatedSrcStat = fs.statSync(src) - return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime) -} - -function onDir (srcStat, destStat, src, dest, opts) { - if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts) - return copyDir(src, dest, opts) -} - -function mkDirAndCopy (srcMode, src, dest, opts) { - fs.mkdirSync(dest) - copyDir(src, dest, opts) - return setDestMode(dest, srcMode) -} - -function copyDir (src, dest, opts) { - fs.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts)) -} - -function copyDirItem (item, src, dest, opts) { - const srcItem = path.join(src, item) - const destItem = path.join(dest, item) - const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy', opts) - return startCopy(destStat, srcItem, destItem, opts) -} - -function onLink (destStat, src, dest, opts) { - let resolvedSrc = fs.readlinkSync(src) - if (opts.dereference) { - resolvedSrc = path.resolve(process.cwd(), resolvedSrc) - } - - if (!destStat) { - return fs.symlinkSync(resolvedSrc, dest) - } else { - let resolvedDest - try { - resolvedDest = fs.readlinkSync(dest) - } catch (err) { - // dest exists and is a regular file or directory, - // Windows may throw UNKNOWN error. If dest already exists, - // fs throws error anyway, so no need to guard against it here. - if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest) - throw err - } - if (opts.dereference) { - resolvedDest = path.resolve(process.cwd(), resolvedDest) - } - if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { - throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`) - } - - // prevent copy if src is a subdir of dest since unlinking - // dest in this case would result in removing src contents - // and therefore a broken symlink would be created. - if (fs.statSync(dest).isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { - throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`) - } - return copyLink(resolvedSrc, dest) - } -} - -function copyLink (resolvedSrc, dest) { - fs.unlinkSync(dest) - return fs.symlinkSync(resolvedSrc, dest) -} - -module.exports = copySync diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/copy/copy.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/copy/copy.js deleted file mode 100644 index 09d53dfd..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/copy/copy.js +++ /dev/null @@ -1,235 +0,0 @@ -'use strict' - -const fs = require('graceful-fs') -const path = require('path') -const mkdirs = require('../mkdirs').mkdirs -const pathExists = require('../path-exists').pathExists -const utimesMillis = require('../util/utimes').utimesMillis -const stat = require('../util/stat') - -function copy (src, dest, opts, cb) { - if (typeof opts === 'function' && !cb) { - cb = opts - opts = {} - } else if (typeof opts === 'function') { - opts = { filter: opts } - } - - cb = cb || function () {} - opts = opts || {} - - opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now - opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber - - // Warn about using preserveTimestamps on 32-bit node - if (opts.preserveTimestamps && process.arch === 'ia32') { - process.emitWarning( - 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' + - '\tsee https://github.com/jprichardson/node-fs-extra/issues/269', - 'Warning', 'fs-extra-WARN0001' - ) - } - - stat.checkPaths(src, dest, 'copy', opts, (err, stats) => { - if (err) return cb(err) - const { srcStat, destStat } = stats - stat.checkParentPaths(src, srcStat, dest, 'copy', err => { - if (err) return cb(err) - if (opts.filter) return handleFilter(checkParentDir, destStat, src, dest, opts, cb) - return checkParentDir(destStat, src, dest, opts, cb) - }) - }) -} - -function checkParentDir (destStat, src, dest, opts, cb) { - const destParent = path.dirname(dest) - pathExists(destParent, (err, dirExists) => { - if (err) return cb(err) - if (dirExists) return getStats(destStat, src, dest, opts, cb) - mkdirs(destParent, err => { - if (err) return cb(err) - return getStats(destStat, src, dest, opts, cb) - }) - }) -} - -function handleFilter (onInclude, destStat, src, dest, opts, cb) { - Promise.resolve(opts.filter(src, dest)).then(include => { - if (include) return onInclude(destStat, src, dest, opts, cb) - return cb() - }, error => cb(error)) -} - -function startCopy (destStat, src, dest, opts, cb) { - if (opts.filter) return handleFilter(getStats, destStat, src, dest, opts, cb) - return getStats(destStat, src, dest, opts, cb) -} - -function getStats (destStat, src, dest, opts, cb) { - const stat = opts.dereference ? fs.stat : fs.lstat - stat(src, (err, srcStat) => { - if (err) return cb(err) - - if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts, cb) - else if (srcStat.isFile() || - srcStat.isCharacterDevice() || - srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts, cb) - else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts, cb) - else if (srcStat.isSocket()) return cb(new Error(`Cannot copy a socket file: ${src}`)) - else if (srcStat.isFIFO()) return cb(new Error(`Cannot copy a FIFO pipe: ${src}`)) - return cb(new Error(`Unknown file: ${src}`)) - }) -} - -function onFile (srcStat, destStat, src, dest, opts, cb) { - if (!destStat) return copyFile(srcStat, src, dest, opts, cb) - return mayCopyFile(srcStat, src, dest, opts, cb) -} - -function mayCopyFile (srcStat, src, dest, opts, cb) { - if (opts.overwrite) { - fs.unlink(dest, err => { - if (err) return cb(err) - return copyFile(srcStat, src, dest, opts, cb) - }) - } else if (opts.errorOnExist) { - return cb(new Error(`'${dest}' already exists`)) - } else return cb() -} - -function copyFile (srcStat, src, dest, opts, cb) { - fs.copyFile(src, dest, err => { - if (err) return cb(err) - if (opts.preserveTimestamps) return handleTimestampsAndMode(srcStat.mode, src, dest, cb) - return setDestMode(dest, srcStat.mode, cb) - }) -} - -function handleTimestampsAndMode (srcMode, src, dest, cb) { - // Make sure the file is writable before setting the timestamp - // otherwise open fails with EPERM when invoked with 'r+' - // (through utimes call) - if (fileIsNotWritable(srcMode)) { - return makeFileWritable(dest, srcMode, err => { - if (err) return cb(err) - return setDestTimestampsAndMode(srcMode, src, dest, cb) - }) - } - return setDestTimestampsAndMode(srcMode, src, dest, cb) -} - -function fileIsNotWritable (srcMode) { - return (srcMode & 0o200) === 0 -} - -function makeFileWritable (dest, srcMode, cb) { - return setDestMode(dest, srcMode | 0o200, cb) -} - -function setDestTimestampsAndMode (srcMode, src, dest, cb) { - setDestTimestamps(src, dest, err => { - if (err) return cb(err) - return setDestMode(dest, srcMode, cb) - }) -} - -function setDestMode (dest, srcMode, cb) { - return fs.chmod(dest, srcMode, cb) -} - -function setDestTimestamps (src, dest, cb) { - // The initial srcStat.atime cannot be trusted - // because it is modified by the read(2) system call - // (See https://nodejs.org/api/fs.html#fs_stat_time_values) - fs.stat(src, (err, updatedSrcStat) => { - if (err) return cb(err) - return utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime, cb) - }) -} - -function onDir (srcStat, destStat, src, dest, opts, cb) { - if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts, cb) - return copyDir(src, dest, opts, cb) -} - -function mkDirAndCopy (srcMode, src, dest, opts, cb) { - fs.mkdir(dest, err => { - if (err) return cb(err) - copyDir(src, dest, opts, err => { - if (err) return cb(err) - return setDestMode(dest, srcMode, cb) - }) - }) -} - -function copyDir (src, dest, opts, cb) { - fs.readdir(src, (err, items) => { - if (err) return cb(err) - return copyDirItems(items, src, dest, opts, cb) - }) -} - -function copyDirItems (items, src, dest, opts, cb) { - const item = items.pop() - if (!item) return cb() - return copyDirItem(items, item, src, dest, opts, cb) -} - -function copyDirItem (items, item, src, dest, opts, cb) { - const srcItem = path.join(src, item) - const destItem = path.join(dest, item) - stat.checkPaths(srcItem, destItem, 'copy', opts, (err, stats) => { - if (err) return cb(err) - const { destStat } = stats - startCopy(destStat, srcItem, destItem, opts, err => { - if (err) return cb(err) - return copyDirItems(items, src, dest, opts, cb) - }) - }) -} - -function onLink (destStat, src, dest, opts, cb) { - fs.readlink(src, (err, resolvedSrc) => { - if (err) return cb(err) - if (opts.dereference) { - resolvedSrc = path.resolve(process.cwd(), resolvedSrc) - } - - if (!destStat) { - return fs.symlink(resolvedSrc, dest, cb) - } else { - fs.readlink(dest, (err, resolvedDest) => { - if (err) { - // dest exists and is a regular file or directory, - // Windows may throw UNKNOWN error. If dest already exists, - // fs throws error anyway, so no need to guard against it here. - if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest, cb) - return cb(err) - } - if (opts.dereference) { - resolvedDest = path.resolve(process.cwd(), resolvedDest) - } - if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { - return cb(new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)) - } - - // do not copy if src is a subdir of dest since unlinking - // dest in this case would result in removing src contents - // and therefore a broken symlink would be created. - if (destStat.isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { - return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)) - } - return copyLink(resolvedSrc, dest, cb) - }) - } - }) -} - -function copyLink (resolvedSrc, dest, cb) { - fs.unlink(dest, err => { - if (err) return cb(err) - return fs.symlink(resolvedSrc, dest, cb) - }) -} - -module.exports = copy diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/copy/index.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/copy/index.js deleted file mode 100644 index 45c07a2f..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/copy/index.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict' - -const u = require('universalify').fromCallback -module.exports = { - copy: u(require('./copy')), - copySync: require('./copy-sync') -} diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/empty/index.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/empty/index.js deleted file mode 100644 index b4a2e823..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/empty/index.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict' - -const u = require('universalify').fromPromise -const fs = require('../fs') -const path = require('path') -const mkdir = require('../mkdirs') -const remove = require('../remove') - -const emptyDir = u(async function emptyDir (dir) { - let items - try { - items = await fs.readdir(dir) - } catch { - return mkdir.mkdirs(dir) - } - - return Promise.all(items.map(item => remove.remove(path.join(dir, item)))) -}) - -function emptyDirSync (dir) { - let items - try { - items = fs.readdirSync(dir) - } catch { - return mkdir.mkdirsSync(dir) - } - - items.forEach(item => { - item = path.join(dir, item) - remove.removeSync(item) - }) -} - -module.exports = { - emptyDirSync, - emptydirSync: emptyDirSync, - emptyDir, - emptydir: emptyDir -} diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/ensure/file.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/ensure/file.js deleted file mode 100644 index 15cc473c..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/ensure/file.js +++ /dev/null @@ -1,69 +0,0 @@ -'use strict' - -const u = require('universalify').fromCallback -const path = require('path') -const fs = require('graceful-fs') -const mkdir = require('../mkdirs') - -function createFile (file, callback) { - function makeFile () { - fs.writeFile(file, '', err => { - if (err) return callback(err) - callback() - }) - } - - fs.stat(file, (err, stats) => { // eslint-disable-line handle-callback-err - if (!err && stats.isFile()) return callback() - const dir = path.dirname(file) - fs.stat(dir, (err, stats) => { - if (err) { - // if the directory doesn't exist, make it - if (err.code === 'ENOENT') { - return mkdir.mkdirs(dir, err => { - if (err) return callback(err) - makeFile() - }) - } - return callback(err) - } - - if (stats.isDirectory()) makeFile() - else { - // parent is not a directory - // This is just to cause an internal ENOTDIR error to be thrown - fs.readdir(dir, err => { - if (err) return callback(err) - }) - } - }) - }) -} - -function createFileSync (file) { - let stats - try { - stats = fs.statSync(file) - } catch {} - if (stats && stats.isFile()) return - - const dir = path.dirname(file) - try { - if (!fs.statSync(dir).isDirectory()) { - // parent is not a directory - // This is just to cause an internal ENOTDIR error to be thrown - fs.readdirSync(dir) - } - } catch (err) { - // If the stat call above failed because the directory doesn't exist, create it - if (err && err.code === 'ENOENT') mkdir.mkdirsSync(dir) - else throw err - } - - fs.writeFileSync(file, '') -} - -module.exports = { - createFile: u(createFile), - createFileSync -} diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/ensure/index.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/ensure/index.js deleted file mode 100644 index ecbcdd0b..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/ensure/index.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict' - -const { createFile, createFileSync } = require('./file') -const { createLink, createLinkSync } = require('./link') -const { createSymlink, createSymlinkSync } = require('./symlink') - -module.exports = { - // file - createFile, - createFileSync, - ensureFile: createFile, - ensureFileSync: createFileSync, - // link - createLink, - createLinkSync, - ensureLink: createLink, - ensureLinkSync: createLinkSync, - // symlink - createSymlink, - createSymlinkSync, - ensureSymlink: createSymlink, - ensureSymlinkSync: createSymlinkSync -} diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/ensure/link.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/ensure/link.js deleted file mode 100644 index f6d67486..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/ensure/link.js +++ /dev/null @@ -1,64 +0,0 @@ -'use strict' - -const u = require('universalify').fromCallback -const path = require('path') -const fs = require('graceful-fs') -const mkdir = require('../mkdirs') -const pathExists = require('../path-exists').pathExists -const { areIdentical } = require('../util/stat') - -function createLink (srcpath, dstpath, callback) { - function makeLink (srcpath, dstpath) { - fs.link(srcpath, dstpath, err => { - if (err) return callback(err) - callback(null) - }) - } - - fs.lstat(dstpath, (_, dstStat) => { - fs.lstat(srcpath, (err, srcStat) => { - if (err) { - err.message = err.message.replace('lstat', 'ensureLink') - return callback(err) - } - if (dstStat && areIdentical(srcStat, dstStat)) return callback(null) - - const dir = path.dirname(dstpath) - pathExists(dir, (err, dirExists) => { - if (err) return callback(err) - if (dirExists) return makeLink(srcpath, dstpath) - mkdir.mkdirs(dir, err => { - if (err) return callback(err) - makeLink(srcpath, dstpath) - }) - }) - }) - }) -} - -function createLinkSync (srcpath, dstpath) { - let dstStat - try { - dstStat = fs.lstatSync(dstpath) - } catch {} - - try { - const srcStat = fs.lstatSync(srcpath) - if (dstStat && areIdentical(srcStat, dstStat)) return - } catch (err) { - err.message = err.message.replace('lstat', 'ensureLink') - throw err - } - - const dir = path.dirname(dstpath) - const dirExists = fs.existsSync(dir) - if (dirExists) return fs.linkSync(srcpath, dstpath) - mkdir.mkdirsSync(dir) - - return fs.linkSync(srcpath, dstpath) -} - -module.exports = { - createLink: u(createLink), - createLinkSync -} diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/ensure/symlink-paths.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/ensure/symlink-paths.js deleted file mode 100644 index 33cd7600..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/ensure/symlink-paths.js +++ /dev/null @@ -1,99 +0,0 @@ -'use strict' - -const path = require('path') -const fs = require('graceful-fs') -const pathExists = require('../path-exists').pathExists - -/** - * Function that returns two types of paths, one relative to symlink, and one - * relative to the current working directory. Checks if path is absolute or - * relative. If the path is relative, this function checks if the path is - * relative to symlink or relative to current working directory. This is an - * initiative to find a smarter `srcpath` to supply when building symlinks. - * This allows you to determine which path to use out of one of three possible - * types of source paths. The first is an absolute path. This is detected by - * `path.isAbsolute()`. When an absolute path is provided, it is checked to - * see if it exists. If it does it's used, if not an error is returned - * (callback)/ thrown (sync). The other two options for `srcpath` are a - * relative url. By default Node's `fs.symlink` works by creating a symlink - * using `dstpath` and expects the `srcpath` to be relative to the newly - * created symlink. If you provide a `srcpath` that does not exist on the file - * system it results in a broken symlink. To minimize this, the function - * checks to see if the 'relative to symlink' source file exists, and if it - * does it will use it. If it does not, it checks if there's a file that - * exists that is relative to the current working directory, if does its used. - * This preserves the expectations of the original fs.symlink spec and adds - * the ability to pass in `relative to current working direcotry` paths. - */ - -function symlinkPaths (srcpath, dstpath, callback) { - if (path.isAbsolute(srcpath)) { - return fs.lstat(srcpath, (err) => { - if (err) { - err.message = err.message.replace('lstat', 'ensureSymlink') - return callback(err) - } - return callback(null, { - toCwd: srcpath, - toDst: srcpath - }) - }) - } else { - const dstdir = path.dirname(dstpath) - const relativeToDst = path.join(dstdir, srcpath) - return pathExists(relativeToDst, (err, exists) => { - if (err) return callback(err) - if (exists) { - return callback(null, { - toCwd: relativeToDst, - toDst: srcpath - }) - } else { - return fs.lstat(srcpath, (err) => { - if (err) { - err.message = err.message.replace('lstat', 'ensureSymlink') - return callback(err) - } - return callback(null, { - toCwd: srcpath, - toDst: path.relative(dstdir, srcpath) - }) - }) - } - }) - } -} - -function symlinkPathsSync (srcpath, dstpath) { - let exists - if (path.isAbsolute(srcpath)) { - exists = fs.existsSync(srcpath) - if (!exists) throw new Error('absolute srcpath does not exist') - return { - toCwd: srcpath, - toDst: srcpath - } - } else { - const dstdir = path.dirname(dstpath) - const relativeToDst = path.join(dstdir, srcpath) - exists = fs.existsSync(relativeToDst) - if (exists) { - return { - toCwd: relativeToDst, - toDst: srcpath - } - } else { - exists = fs.existsSync(srcpath) - if (!exists) throw new Error('relative srcpath does not exist') - return { - toCwd: srcpath, - toDst: path.relative(dstdir, srcpath) - } - } - } -} - -module.exports = { - symlinkPaths, - symlinkPathsSync -} diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/ensure/symlink-type.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/ensure/symlink-type.js deleted file mode 100644 index 42dc0ce7..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/ensure/symlink-type.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict' - -const fs = require('graceful-fs') - -function symlinkType (srcpath, type, callback) { - callback = (typeof type === 'function') ? type : callback - type = (typeof type === 'function') ? false : type - if (type) return callback(null, type) - fs.lstat(srcpath, (err, stats) => { - if (err) return callback(null, 'file') - type = (stats && stats.isDirectory()) ? 'dir' : 'file' - callback(null, type) - }) -} - -function symlinkTypeSync (srcpath, type) { - let stats - - if (type) return type - try { - stats = fs.lstatSync(srcpath) - } catch { - return 'file' - } - return (stats && stats.isDirectory()) ? 'dir' : 'file' -} - -module.exports = { - symlinkType, - symlinkTypeSync -} diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/ensure/symlink.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/ensure/symlink.js deleted file mode 100644 index 2b93052f..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/ensure/symlink.js +++ /dev/null @@ -1,82 +0,0 @@ -'use strict' - -const u = require('universalify').fromCallback -const path = require('path') -const fs = require('../fs') -const _mkdirs = require('../mkdirs') -const mkdirs = _mkdirs.mkdirs -const mkdirsSync = _mkdirs.mkdirsSync - -const _symlinkPaths = require('./symlink-paths') -const symlinkPaths = _symlinkPaths.symlinkPaths -const symlinkPathsSync = _symlinkPaths.symlinkPathsSync - -const _symlinkType = require('./symlink-type') -const symlinkType = _symlinkType.symlinkType -const symlinkTypeSync = _symlinkType.symlinkTypeSync - -const pathExists = require('../path-exists').pathExists - -const { areIdentical } = require('../util/stat') - -function createSymlink (srcpath, dstpath, type, callback) { - callback = (typeof type === 'function') ? type : callback - type = (typeof type === 'function') ? false : type - - fs.lstat(dstpath, (err, stats) => { - if (!err && stats.isSymbolicLink()) { - Promise.all([ - fs.stat(srcpath), - fs.stat(dstpath) - ]).then(([srcStat, dstStat]) => { - if (areIdentical(srcStat, dstStat)) return callback(null) - _createSymlink(srcpath, dstpath, type, callback) - }) - } else _createSymlink(srcpath, dstpath, type, callback) - }) -} - -function _createSymlink (srcpath, dstpath, type, callback) { - symlinkPaths(srcpath, dstpath, (err, relative) => { - if (err) return callback(err) - srcpath = relative.toDst - symlinkType(relative.toCwd, type, (err, type) => { - if (err) return callback(err) - const dir = path.dirname(dstpath) - pathExists(dir, (err, dirExists) => { - if (err) return callback(err) - if (dirExists) return fs.symlink(srcpath, dstpath, type, callback) - mkdirs(dir, err => { - if (err) return callback(err) - fs.symlink(srcpath, dstpath, type, callback) - }) - }) - }) - }) -} - -function createSymlinkSync (srcpath, dstpath, type) { - let stats - try { - stats = fs.lstatSync(dstpath) - } catch {} - if (stats && stats.isSymbolicLink()) { - const srcStat = fs.statSync(srcpath) - const dstStat = fs.statSync(dstpath) - if (areIdentical(srcStat, dstStat)) return - } - - const relative = symlinkPathsSync(srcpath, dstpath) - srcpath = relative.toDst - type = symlinkTypeSync(relative.toCwd, type) - const dir = path.dirname(dstpath) - const exists = fs.existsSync(dir) - if (exists) return fs.symlinkSync(srcpath, dstpath, type) - mkdirsSync(dir) - return fs.symlinkSync(srcpath, dstpath, type) -} - -module.exports = { - createSymlink: u(createSymlink), - createSymlinkSync -} diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/fs/index.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/fs/index.js deleted file mode 100644 index 7b025e29..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/fs/index.js +++ /dev/null @@ -1,128 +0,0 @@ -'use strict' -// This is adapted from https://github.com/normalize/mz -// Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors -const u = require('universalify').fromCallback -const fs = require('graceful-fs') - -const api = [ - 'access', - 'appendFile', - 'chmod', - 'chown', - 'close', - 'copyFile', - 'fchmod', - 'fchown', - 'fdatasync', - 'fstat', - 'fsync', - 'ftruncate', - 'futimes', - 'lchmod', - 'lchown', - 'link', - 'lstat', - 'mkdir', - 'mkdtemp', - 'open', - 'opendir', - 'readdir', - 'readFile', - 'readlink', - 'realpath', - 'rename', - 'rm', - 'rmdir', - 'stat', - 'symlink', - 'truncate', - 'unlink', - 'utimes', - 'writeFile' -].filter(key => { - // Some commands are not available on some systems. Ex: - // fs.opendir was added in Node.js v12.12.0 - // fs.rm was added in Node.js v14.14.0 - // fs.lchown is not available on at least some Linux - return typeof fs[key] === 'function' -}) - -// Export cloned fs: -Object.assign(exports, fs) - -// Universalify async methods: -api.forEach(method => { - exports[method] = u(fs[method]) -}) - -// We differ from mz/fs in that we still ship the old, broken, fs.exists() -// since we are a drop-in replacement for the native module -exports.exists = function (filename, callback) { - if (typeof callback === 'function') { - return fs.exists(filename, callback) - } - return new Promise(resolve => { - return fs.exists(filename, resolve) - }) -} - -// fs.read(), fs.write(), & fs.writev() need special treatment due to multiple callback args - -exports.read = function (fd, buffer, offset, length, position, callback) { - if (typeof callback === 'function') { - return fs.read(fd, buffer, offset, length, position, callback) - } - return new Promise((resolve, reject) => { - fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => { - if (err) return reject(err) - resolve({ bytesRead, buffer }) - }) - }) -} - -// Function signature can be -// fs.write(fd, buffer[, offset[, length[, position]]], callback) -// OR -// fs.write(fd, string[, position[, encoding]], callback) -// We need to handle both cases, so we use ...args -exports.write = function (fd, buffer, ...args) { - if (typeof args[args.length - 1] === 'function') { - return fs.write(fd, buffer, ...args) - } - - return new Promise((resolve, reject) => { - fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => { - if (err) return reject(err) - resolve({ bytesWritten, buffer }) - }) - }) -} - -// fs.writev only available in Node v12.9.0+ -if (typeof fs.writev === 'function') { - // Function signature is - // s.writev(fd, buffers[, position], callback) - // We need to handle the optional arg, so we use ...args - exports.writev = function (fd, buffers, ...args) { - if (typeof args[args.length - 1] === 'function') { - return fs.writev(fd, buffers, ...args) - } - - return new Promise((resolve, reject) => { - fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => { - if (err) return reject(err) - resolve({ bytesWritten, buffers }) - }) - }) - } -} - -// fs.realpath.native sometimes not available if fs is monkey-patched -if (typeof fs.realpath.native === 'function') { - exports.realpath.native = u(fs.realpath.native) -} else { - process.emitWarning( - 'fs.realpath.native is not a function. Is fs being monkey-patched?', - 'Warning', 'fs-extra-WARN0003' - ) -} diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/index.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/index.js deleted file mode 100644 index da6711a4..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/index.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict' - -module.exports = { - // Export promiseified graceful-fs: - ...require('./fs'), - // Export extra methods: - ...require('./copy'), - ...require('./empty'), - ...require('./ensure'), - ...require('./json'), - ...require('./mkdirs'), - ...require('./move'), - ...require('./output-file'), - ...require('./path-exists'), - ...require('./remove') -} diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/json/index.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/json/index.js deleted file mode 100644 index 900126ad..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/json/index.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict' - -const u = require('universalify').fromPromise -const jsonFile = require('./jsonfile') - -jsonFile.outputJson = u(require('./output-json')) -jsonFile.outputJsonSync = require('./output-json-sync') -// aliases -jsonFile.outputJSON = jsonFile.outputJson -jsonFile.outputJSONSync = jsonFile.outputJsonSync -jsonFile.writeJSON = jsonFile.writeJson -jsonFile.writeJSONSync = jsonFile.writeJsonSync -jsonFile.readJSON = jsonFile.readJson -jsonFile.readJSONSync = jsonFile.readJsonSync - -module.exports = jsonFile diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/json/jsonfile.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/json/jsonfile.js deleted file mode 100644 index f11d34d6..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/json/jsonfile.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict' - -const jsonFile = require('jsonfile') - -module.exports = { - // jsonfile exports - readJson: jsonFile.readFile, - readJsonSync: jsonFile.readFileSync, - writeJson: jsonFile.writeFile, - writeJsonSync: jsonFile.writeFileSync -} diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/json/output-json-sync.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/json/output-json-sync.js deleted file mode 100644 index d4e564f2..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/json/output-json-sync.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict' - -const { stringify } = require('jsonfile/utils') -const { outputFileSync } = require('../output-file') - -function outputJsonSync (file, data, options) { - const str = stringify(data, options) - - outputFileSync(file, str, options) -} - -module.exports = outputJsonSync diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/json/output-json.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/json/output-json.js deleted file mode 100644 index 0afdeb63..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/json/output-json.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict' - -const { stringify } = require('jsonfile/utils') -const { outputFile } = require('../output-file') - -async function outputJson (file, data, options = {}) { - const str = stringify(data, options) - - await outputFile(file, str, options) -} - -module.exports = outputJson diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/mkdirs/index.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/mkdirs/index.js deleted file mode 100644 index 9edecee0..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/mkdirs/index.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict' -const u = require('universalify').fromPromise -const { makeDir: _makeDir, makeDirSync } = require('./make-dir') -const makeDir = u(_makeDir) - -module.exports = { - mkdirs: makeDir, - mkdirsSync: makeDirSync, - // alias - mkdirp: makeDir, - mkdirpSync: makeDirSync, - ensureDir: makeDir, - ensureDirSync: makeDirSync -} diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/mkdirs/make-dir.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/mkdirs/make-dir.js deleted file mode 100644 index 45ece64d..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/mkdirs/make-dir.js +++ /dev/null @@ -1,27 +0,0 @@ -'use strict' -const fs = require('../fs') -const { checkPath } = require('./utils') - -const getMode = options => { - const defaults = { mode: 0o777 } - if (typeof options === 'number') return options - return ({ ...defaults, ...options }).mode -} - -module.exports.makeDir = async (dir, options) => { - checkPath(dir) - - return fs.mkdir(dir, { - mode: getMode(options), - recursive: true - }) -} - -module.exports.makeDirSync = (dir, options) => { - checkPath(dir) - - return fs.mkdirSync(dir, { - mode: getMode(options), - recursive: true - }) -} diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/mkdirs/utils.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/mkdirs/utils.js deleted file mode 100644 index a4059ad4..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/mkdirs/utils.js +++ /dev/null @@ -1,21 +0,0 @@ -// Adapted from https://github.com/sindresorhus/make-dir -// Copyright (c) Sindre Sorhus (sindresorhus.com) -// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -'use strict' -const path = require('path') - -// https://github.com/nodejs/node/issues/8987 -// https://github.com/libuv/libuv/pull/1088 -module.exports.checkPath = function checkPath (pth) { - if (process.platform === 'win32') { - const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, '')) - - if (pathHasInvalidWinCharacters) { - const error = new Error(`Path contains invalid characters: ${pth}`) - error.code = 'EINVAL' - throw error - } - } -} diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/move/index.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/move/index.js deleted file mode 100644 index fcee73c4..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/move/index.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict' - -const u = require('universalify').fromCallback -module.exports = { - move: u(require('./move')), - moveSync: require('./move-sync') -} diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/move/move-sync.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/move/move-sync.js deleted file mode 100644 index 84533664..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/move/move-sync.js +++ /dev/null @@ -1,54 +0,0 @@ -'use strict' - -const fs = require('graceful-fs') -const path = require('path') -const copySync = require('../copy').copySync -const removeSync = require('../remove').removeSync -const mkdirpSync = require('../mkdirs').mkdirpSync -const stat = require('../util/stat') - -function moveSync (src, dest, opts) { - opts = opts || {} - const overwrite = opts.overwrite || opts.clobber || false - - const { srcStat, isChangingCase = false } = stat.checkPathsSync(src, dest, 'move', opts) - stat.checkParentPathsSync(src, srcStat, dest, 'move') - if (!isParentRoot(dest)) mkdirpSync(path.dirname(dest)) - return doRename(src, dest, overwrite, isChangingCase) -} - -function isParentRoot (dest) { - const parent = path.dirname(dest) - const parsedPath = path.parse(parent) - return parsedPath.root === parent -} - -function doRename (src, dest, overwrite, isChangingCase) { - if (isChangingCase) return rename(src, dest, overwrite) - if (overwrite) { - removeSync(dest) - return rename(src, dest, overwrite) - } - if (fs.existsSync(dest)) throw new Error('dest already exists.') - return rename(src, dest, overwrite) -} - -function rename (src, dest, overwrite) { - try { - fs.renameSync(src, dest) - } catch (err) { - if (err.code !== 'EXDEV') throw err - return moveAcrossDevice(src, dest, overwrite) - } -} - -function moveAcrossDevice (src, dest, overwrite) { - const opts = { - overwrite, - errorOnExist: true - } - copySync(src, dest, opts) - return removeSync(src) -} - -module.exports = moveSync diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/move/move.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/move/move.js deleted file mode 100644 index 7dc6ecd1..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/move/move.js +++ /dev/null @@ -1,75 +0,0 @@ -'use strict' - -const fs = require('graceful-fs') -const path = require('path') -const copy = require('../copy').copy -const remove = require('../remove').remove -const mkdirp = require('../mkdirs').mkdirp -const pathExists = require('../path-exists').pathExists -const stat = require('../util/stat') - -function move (src, dest, opts, cb) { - if (typeof opts === 'function') { - cb = opts - opts = {} - } - - opts = opts || {} - - const overwrite = opts.overwrite || opts.clobber || false - - stat.checkPaths(src, dest, 'move', opts, (err, stats) => { - if (err) return cb(err) - const { srcStat, isChangingCase = false } = stats - stat.checkParentPaths(src, srcStat, dest, 'move', err => { - if (err) return cb(err) - if (isParentRoot(dest)) return doRename(src, dest, overwrite, isChangingCase, cb) - mkdirp(path.dirname(dest), err => { - if (err) return cb(err) - return doRename(src, dest, overwrite, isChangingCase, cb) - }) - }) - }) -} - -function isParentRoot (dest) { - const parent = path.dirname(dest) - const parsedPath = path.parse(parent) - return parsedPath.root === parent -} - -function doRename (src, dest, overwrite, isChangingCase, cb) { - if (isChangingCase) return rename(src, dest, overwrite, cb) - if (overwrite) { - return remove(dest, err => { - if (err) return cb(err) - return rename(src, dest, overwrite, cb) - }) - } - pathExists(dest, (err, destExists) => { - if (err) return cb(err) - if (destExists) return cb(new Error('dest already exists.')) - return rename(src, dest, overwrite, cb) - }) -} - -function rename (src, dest, overwrite, cb) { - fs.rename(src, dest, err => { - if (!err) return cb() - if (err.code !== 'EXDEV') return cb(err) - return moveAcrossDevice(src, dest, overwrite, cb) - }) -} - -function moveAcrossDevice (src, dest, overwrite, cb) { - const opts = { - overwrite, - errorOnExist: true - } - copy(src, dest, opts, err => { - if (err) return cb(err) - return remove(src, cb) - }) -} - -module.exports = move diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/output-file/index.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/output-file/index.js deleted file mode 100644 index 92297ca3..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/output-file/index.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict' - -const u = require('universalify').fromCallback -const fs = require('graceful-fs') -const path = require('path') -const mkdir = require('../mkdirs') -const pathExists = require('../path-exists').pathExists - -function outputFile (file, data, encoding, callback) { - if (typeof encoding === 'function') { - callback = encoding - encoding = 'utf8' - } - - const dir = path.dirname(file) - pathExists(dir, (err, itDoes) => { - if (err) return callback(err) - if (itDoes) return fs.writeFile(file, data, encoding, callback) - - mkdir.mkdirs(dir, err => { - if (err) return callback(err) - - fs.writeFile(file, data, encoding, callback) - }) - }) -} - -function outputFileSync (file, ...args) { - const dir = path.dirname(file) - if (fs.existsSync(dir)) { - return fs.writeFileSync(file, ...args) - } - mkdir.mkdirsSync(dir) - fs.writeFileSync(file, ...args) -} - -module.exports = { - outputFile: u(outputFile), - outputFileSync -} diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/path-exists/index.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/path-exists/index.js deleted file mode 100644 index ddd9bc71..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/path-exists/index.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict' -const u = require('universalify').fromPromise -const fs = require('../fs') - -function pathExists (path) { - return fs.access(path).then(() => true).catch(() => false) -} - -module.exports = { - pathExists: u(pathExists), - pathExistsSync: fs.existsSync -} diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/remove/index.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/remove/index.js deleted file mode 100644 index 4428e59a..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/remove/index.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict' - -const fs = require('graceful-fs') -const u = require('universalify').fromCallback -const rimraf = require('./rimraf') - -function remove (path, callback) { - // Node 14.14.0+ - if (fs.rm) return fs.rm(path, { recursive: true, force: true }, callback) - rimraf(path, callback) -} - -function removeSync (path) { - // Node 14.14.0+ - if (fs.rmSync) return fs.rmSync(path, { recursive: true, force: true }) - rimraf.sync(path) -} - -module.exports = { - remove: u(remove), - removeSync -} diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/remove/rimraf.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/remove/rimraf.js deleted file mode 100644 index 2c771026..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/remove/rimraf.js +++ /dev/null @@ -1,302 +0,0 @@ -'use strict' - -const fs = require('graceful-fs') -const path = require('path') -const assert = require('assert') - -const isWindows = (process.platform === 'win32') - -function defaults (options) { - const methods = [ - 'unlink', - 'chmod', - 'stat', - 'lstat', - 'rmdir', - 'readdir' - ] - methods.forEach(m => { - options[m] = options[m] || fs[m] - m = m + 'Sync' - options[m] = options[m] || fs[m] - }) - - options.maxBusyTries = options.maxBusyTries || 3 -} - -function rimraf (p, options, cb) { - let busyTries = 0 - - if (typeof options === 'function') { - cb = options - options = {} - } - - assert(p, 'rimraf: missing path') - assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string') - assert.strictEqual(typeof cb, 'function', 'rimraf: callback function required') - assert(options, 'rimraf: invalid options argument provided') - assert.strictEqual(typeof options, 'object', 'rimraf: options should be object') - - defaults(options) - - rimraf_(p, options, function CB (er) { - if (er) { - if ((er.code === 'EBUSY' || er.code === 'ENOTEMPTY' || er.code === 'EPERM') && - busyTries < options.maxBusyTries) { - busyTries++ - const time = busyTries * 100 - // try again, with the same exact callback as this one. - return setTimeout(() => rimraf_(p, options, CB), time) - } - - // already gone - if (er.code === 'ENOENT') er = null - } - - cb(er) - }) -} - -// Two possible strategies. -// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR -// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR -// -// Both result in an extra syscall when you guess wrong. However, there -// are likely far more normal files in the world than directories. This -// is based on the assumption that a the average number of files per -// directory is >= 1. -// -// If anyone ever complains about this, then I guess the strategy could -// be made configurable somehow. But until then, YAGNI. -function rimraf_ (p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - - // sunos lets the root user unlink directories, which is... weird. - // so we have to lstat here and make sure it's not a dir. - options.lstat(p, (er, st) => { - if (er && er.code === 'ENOENT') { - return cb(null) - } - - // Windows can EPERM on stat. Life is suffering. - if (er && er.code === 'EPERM' && isWindows) { - return fixWinEPERM(p, options, er, cb) - } - - if (st && st.isDirectory()) { - return rmdir(p, options, er, cb) - } - - options.unlink(p, er => { - if (er) { - if (er.code === 'ENOENT') { - return cb(null) - } - if (er.code === 'EPERM') { - return (isWindows) - ? fixWinEPERM(p, options, er, cb) - : rmdir(p, options, er, cb) - } - if (er.code === 'EISDIR') { - return rmdir(p, options, er, cb) - } - } - return cb(er) - }) - }) -} - -function fixWinEPERM (p, options, er, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - - options.chmod(p, 0o666, er2 => { - if (er2) { - cb(er2.code === 'ENOENT' ? null : er) - } else { - options.stat(p, (er3, stats) => { - if (er3) { - cb(er3.code === 'ENOENT' ? null : er) - } else if (stats.isDirectory()) { - rmdir(p, options, er, cb) - } else { - options.unlink(p, cb) - } - }) - } - }) -} - -function fixWinEPERMSync (p, options, er) { - let stats - - assert(p) - assert(options) - - try { - options.chmodSync(p, 0o666) - } catch (er2) { - if (er2.code === 'ENOENT') { - return - } else { - throw er - } - } - - try { - stats = options.statSync(p) - } catch (er3) { - if (er3.code === 'ENOENT') { - return - } else { - throw er - } - } - - if (stats.isDirectory()) { - rmdirSync(p, options, er) - } else { - options.unlinkSync(p) - } -} - -function rmdir (p, options, originalEr, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - - // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) - // if we guessed wrong, and it's not a directory, then - // raise the original error. - options.rmdir(p, er => { - if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) { - rmkids(p, options, cb) - } else if (er && er.code === 'ENOTDIR') { - cb(originalEr) - } else { - cb(er) - } - }) -} - -function rmkids (p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - - options.readdir(p, (er, files) => { - if (er) return cb(er) - - let n = files.length - let errState - - if (n === 0) return options.rmdir(p, cb) - - files.forEach(f => { - rimraf(path.join(p, f), options, er => { - if (errState) { - return - } - if (er) return cb(errState = er) - if (--n === 0) { - options.rmdir(p, cb) - } - }) - }) - }) -} - -// this looks simpler, and is strictly *faster*, but will -// tie up the JavaScript thread and fail on excessively -// deep directory trees. -function rimrafSync (p, options) { - let st - - options = options || {} - defaults(options) - - assert(p, 'rimraf: missing path') - assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string') - assert(options, 'rimraf: missing options') - assert.strictEqual(typeof options, 'object', 'rimraf: options should be object') - - try { - st = options.lstatSync(p) - } catch (er) { - if (er.code === 'ENOENT') { - return - } - - // Windows can EPERM on stat. Life is suffering. - if (er.code === 'EPERM' && isWindows) { - fixWinEPERMSync(p, options, er) - } - } - - try { - // sunos lets the root user unlink directories, which is... weird. - if (st && st.isDirectory()) { - rmdirSync(p, options, null) - } else { - options.unlinkSync(p) - } - } catch (er) { - if (er.code === 'ENOENT') { - return - } else if (er.code === 'EPERM') { - return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) - } else if (er.code !== 'EISDIR') { - throw er - } - rmdirSync(p, options, er) - } -} - -function rmdirSync (p, options, originalEr) { - assert(p) - assert(options) - - try { - options.rmdirSync(p) - } catch (er) { - if (er.code === 'ENOTDIR') { - throw originalEr - } else if (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM') { - rmkidsSync(p, options) - } else if (er.code !== 'ENOENT') { - throw er - } - } -} - -function rmkidsSync (p, options) { - assert(p) - assert(options) - options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) - - if (isWindows) { - // We only end up here once we got ENOTEMPTY at least once, and - // at this point, we are guaranteed to have removed all the kids. - // So, we know that it won't be ENOENT or ENOTDIR or anything else. - // try really hard to delete stuff on windows, because it has a - // PROFOUNDLY annoying habit of not closing handles promptly when - // files are deleted, resulting in spurious ENOTEMPTY errors. - const startTime = Date.now() - do { - try { - const ret = options.rmdirSync(p, options) - return ret - } catch {} - } while (Date.now() - startTime < 500) // give up after 500ms - } else { - const ret = options.rmdirSync(p, options) - return ret - } -} - -module.exports = rimraf -rimraf.sync = rimrafSync diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/util/stat.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/util/stat.js deleted file mode 100644 index 0ed5aecf..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/util/stat.js +++ /dev/null @@ -1,154 +0,0 @@ -'use strict' - -const fs = require('../fs') -const path = require('path') -const util = require('util') - -function getStats (src, dest, opts) { - const statFunc = opts.dereference - ? (file) => fs.stat(file, { bigint: true }) - : (file) => fs.lstat(file, { bigint: true }) - return Promise.all([ - statFunc(src), - statFunc(dest).catch(err => { - if (err.code === 'ENOENT') return null - throw err - }) - ]).then(([srcStat, destStat]) => ({ srcStat, destStat })) -} - -function getStatsSync (src, dest, opts) { - let destStat - const statFunc = opts.dereference - ? (file) => fs.statSync(file, { bigint: true }) - : (file) => fs.lstatSync(file, { bigint: true }) - const srcStat = statFunc(src) - try { - destStat = statFunc(dest) - } catch (err) { - if (err.code === 'ENOENT') return { srcStat, destStat: null } - throw err - } - return { srcStat, destStat } -} - -function checkPaths (src, dest, funcName, opts, cb) { - util.callbackify(getStats)(src, dest, opts, (err, stats) => { - if (err) return cb(err) - const { srcStat, destStat } = stats - - if (destStat) { - if (areIdentical(srcStat, destStat)) { - const srcBaseName = path.basename(src) - const destBaseName = path.basename(dest) - if (funcName === 'move' && - srcBaseName !== destBaseName && - srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { - return cb(null, { srcStat, destStat, isChangingCase: true }) - } - return cb(new Error('Source and destination must not be the same.')) - } - if (srcStat.isDirectory() && !destStat.isDirectory()) { - return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)) - } - if (!srcStat.isDirectory() && destStat.isDirectory()) { - return cb(new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)) - } - } - - if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { - return cb(new Error(errMsg(src, dest, funcName))) - } - return cb(null, { srcStat, destStat }) - }) -} - -function checkPathsSync (src, dest, funcName, opts) { - const { srcStat, destStat } = getStatsSync(src, dest, opts) - - if (destStat) { - if (areIdentical(srcStat, destStat)) { - const srcBaseName = path.basename(src) - const destBaseName = path.basename(dest) - if (funcName === 'move' && - srcBaseName !== destBaseName && - srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { - return { srcStat, destStat, isChangingCase: true } - } - throw new Error('Source and destination must not be the same.') - } - if (srcStat.isDirectory() && !destStat.isDirectory()) { - throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) - } - if (!srcStat.isDirectory() && destStat.isDirectory()) { - throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`) - } - } - - if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { - throw new Error(errMsg(src, dest, funcName)) - } - return { srcStat, destStat } -} - -// recursively check if dest parent is a subdirectory of src. -// It works for all file types including symlinks since it -// checks the src and dest inodes. It starts from the deepest -// parent and stops once it reaches the src parent or the root path. -function checkParentPaths (src, srcStat, dest, funcName, cb) { - const srcParent = path.resolve(path.dirname(src)) - const destParent = path.resolve(path.dirname(dest)) - if (destParent === srcParent || destParent === path.parse(destParent).root) return cb() - fs.stat(destParent, { bigint: true }, (err, destStat) => { - if (err) { - if (err.code === 'ENOENT') return cb() - return cb(err) - } - if (areIdentical(srcStat, destStat)) { - return cb(new Error(errMsg(src, dest, funcName))) - } - return checkParentPaths(src, srcStat, destParent, funcName, cb) - }) -} - -function checkParentPathsSync (src, srcStat, dest, funcName) { - const srcParent = path.resolve(path.dirname(src)) - const destParent = path.resolve(path.dirname(dest)) - if (destParent === srcParent || destParent === path.parse(destParent).root) return - let destStat - try { - destStat = fs.statSync(destParent, { bigint: true }) - } catch (err) { - if (err.code === 'ENOENT') return - throw err - } - if (areIdentical(srcStat, destStat)) { - throw new Error(errMsg(src, dest, funcName)) - } - return checkParentPathsSync(src, srcStat, destParent, funcName) -} - -function areIdentical (srcStat, destStat) { - return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev -} - -// return true if dest is a subdir of src, otherwise false. -// It only checks the path strings. -function isSrcSubdir (src, dest) { - const srcArr = path.resolve(src).split(path.sep).filter(i => i) - const destArr = path.resolve(dest).split(path.sep).filter(i => i) - return srcArr.reduce((acc, cur, i) => acc && destArr[i] === cur, true) -} - -function errMsg (src, dest, funcName) { - return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.` -} - -module.exports = { - checkPaths, - checkPathsSync, - checkParentPaths, - checkParentPathsSync, - isSrcSubdir, - areIdentical -} diff --git a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/util/utimes.js b/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/util/utimes.js deleted file mode 100644 index 75395def..00000000 --- a/claude-code-source/node_modules/flora-colossus/node_modules/fs-extra/lib/util/utimes.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict' - -const fs = require('graceful-fs') - -function utimesMillis (path, atime, mtime, callback) { - // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback) - fs.open(path, 'r+', (err, fd) => { - if (err) return callback(err) - fs.futimes(fd, atime, mtime, futimesErr => { - fs.close(fd, closeErr => { - if (callback) callback(futimesErr || closeErr) - }) - }) - }) -} - -function utimesMillisSync (path, atime, mtime) { - const fd = fs.openSync(path, 'r+') - fs.futimesSync(fd, atime, mtime) - return fs.closeSync(fd) -} - -module.exports = { - utimesMillis, - utimesMillisSync -} diff --git a/claude-code-source/node_modules/follow-redirects/debug.js b/claude-code-source/node_modules/follow-redirects/debug.js deleted file mode 100644 index decb77de..00000000 --- a/claude-code-source/node_modules/follow-redirects/debug.js +++ /dev/null @@ -1,15 +0,0 @@ -var debug; - -module.exports = function () { - if (!debug) { - try { - /* eslint global-require: off */ - debug = require("debug")("follow-redirects"); - } - catch (error) { /* */ } - if (typeof debug !== "function") { - debug = function () { /* */ }; - } - } - debug.apply(null, arguments); -}; diff --git a/claude-code-source/node_modules/follow-redirects/index.js b/claude-code-source/node_modules/follow-redirects/index.js deleted file mode 100644 index e18a7539..00000000 --- a/claude-code-source/node_modules/follow-redirects/index.js +++ /dev/null @@ -1,686 +0,0 @@ -var url = require("url"); -var URL = url.URL; -var http = require("http"); -var https = require("https"); -var Writable = require("stream").Writable; -var assert = require("assert"); -var debug = require("./debug"); - -// Preventive platform detection -// istanbul ignore next -(function detectUnsupportedEnvironment() { - var looksLikeNode = typeof process !== "undefined"; - var looksLikeBrowser = typeof window !== "undefined" && typeof document !== "undefined"; - var looksLikeV8 = isFunction(Error.captureStackTrace); - if (!looksLikeNode && (looksLikeBrowser || !looksLikeV8)) { - console.warn("The follow-redirects package should be excluded from browser builds."); - } -}()); - -// Whether to use the native URL object or the legacy url module -var useNativeURL = false; -try { - assert(new URL("")); -} -catch (error) { - useNativeURL = error.code === "ERR_INVALID_URL"; -} - -// URL fields to preserve in copy operations -var preservedUrlFields = [ - "auth", - "host", - "hostname", - "href", - "path", - "pathname", - "port", - "protocol", - "query", - "search", - "hash", -]; - -// Create handlers that pass events from native requests -var events = ["abort", "aborted", "connect", "error", "socket", "timeout"]; -var eventHandlers = Object.create(null); -events.forEach(function (event) { - eventHandlers[event] = function (arg1, arg2, arg3) { - this._redirectable.emit(event, arg1, arg2, arg3); - }; -}); - -// Error types with codes -var InvalidUrlError = createErrorType( - "ERR_INVALID_URL", - "Invalid URL", - TypeError -); -var RedirectionError = createErrorType( - "ERR_FR_REDIRECTION_FAILURE", - "Redirected request failed" -); -var TooManyRedirectsError = createErrorType( - "ERR_FR_TOO_MANY_REDIRECTS", - "Maximum number of redirects exceeded", - RedirectionError -); -var MaxBodyLengthExceededError = createErrorType( - "ERR_FR_MAX_BODY_LENGTH_EXCEEDED", - "Request body larger than maxBodyLength limit" -); -var WriteAfterEndError = createErrorType( - "ERR_STREAM_WRITE_AFTER_END", - "write after end" -); - -// istanbul ignore next -var destroy = Writable.prototype.destroy || noop; - -// An HTTP(S) request that can be redirected -function RedirectableRequest(options, responseCallback) { - // Initialize the request - Writable.call(this); - this._sanitizeOptions(options); - this._options = options; - this._ended = false; - this._ending = false; - this._redirectCount = 0; - this._redirects = []; - this._requestBodyLength = 0; - this._requestBodyBuffers = []; - - // Attach a callback if passed - if (responseCallback) { - this.on("response", responseCallback); - } - - // React to responses of native requests - var self = this; - this._onNativeResponse = function (response) { - try { - self._processResponse(response); - } - catch (cause) { - self.emit("error", cause instanceof RedirectionError ? - cause : new RedirectionError({ cause: cause })); - } - }; - - // Perform the first request - this._performRequest(); -} -RedirectableRequest.prototype = Object.create(Writable.prototype); - -RedirectableRequest.prototype.abort = function () { - destroyRequest(this._currentRequest); - this._currentRequest.abort(); - this.emit("abort"); -}; - -RedirectableRequest.prototype.destroy = function (error) { - destroyRequest(this._currentRequest, error); - destroy.call(this, error); - return this; -}; - -// Writes buffered data to the current native request -RedirectableRequest.prototype.write = function (data, encoding, callback) { - // Writing is not allowed if end has been called - if (this._ending) { - throw new WriteAfterEndError(); - } - - // Validate input and shift parameters if necessary - if (!isString(data) && !isBuffer(data)) { - throw new TypeError("data should be a string, Buffer or Uint8Array"); - } - if (isFunction(encoding)) { - callback = encoding; - encoding = null; - } - - // Ignore empty buffers, since writing them doesn't invoke the callback - // https://github.com/nodejs/node/issues/22066 - if (data.length === 0) { - if (callback) { - callback(); - } - return; - } - // Only write when we don't exceed the maximum body length - if (this._requestBodyLength + data.length <= this._options.maxBodyLength) { - this._requestBodyLength += data.length; - this._requestBodyBuffers.push({ data: data, encoding: encoding }); - this._currentRequest.write(data, encoding, callback); - } - // Error when we exceed the maximum body length - else { - this.emit("error", new MaxBodyLengthExceededError()); - this.abort(); - } -}; - -// Ends the current native request -RedirectableRequest.prototype.end = function (data, encoding, callback) { - // Shift parameters if necessary - if (isFunction(data)) { - callback = data; - data = encoding = null; - } - else if (isFunction(encoding)) { - callback = encoding; - encoding = null; - } - - // Write data if needed and end - if (!data) { - this._ended = this._ending = true; - this._currentRequest.end(null, null, callback); - } - else { - var self = this; - var currentRequest = this._currentRequest; - this.write(data, encoding, function () { - self._ended = true; - currentRequest.end(null, null, callback); - }); - this._ending = true; - } -}; - -// Sets a header value on the current native request -RedirectableRequest.prototype.setHeader = function (name, value) { - this._options.headers[name] = value; - this._currentRequest.setHeader(name, value); -}; - -// Clears a header value on the current native request -RedirectableRequest.prototype.removeHeader = function (name) { - delete this._options.headers[name]; - this._currentRequest.removeHeader(name); -}; - -// Global timeout for all underlying requests -RedirectableRequest.prototype.setTimeout = function (msecs, callback) { - var self = this; - - // Destroys the socket on timeout - function destroyOnTimeout(socket) { - socket.setTimeout(msecs); - socket.removeListener("timeout", socket.destroy); - socket.addListener("timeout", socket.destroy); - } - - // Sets up a timer to trigger a timeout event - function startTimer(socket) { - if (self._timeout) { - clearTimeout(self._timeout); - } - self._timeout = setTimeout(function () { - self.emit("timeout"); - clearTimer(); - }, msecs); - destroyOnTimeout(socket); - } - - // Stops a timeout from triggering - function clearTimer() { - // Clear the timeout - if (self._timeout) { - clearTimeout(self._timeout); - self._timeout = null; - } - - // Clean up all attached listeners - self.removeListener("abort", clearTimer); - self.removeListener("error", clearTimer); - self.removeListener("response", clearTimer); - self.removeListener("close", clearTimer); - if (callback) { - self.removeListener("timeout", callback); - } - if (!self.socket) { - self._currentRequest.removeListener("socket", startTimer); - } - } - - // Attach callback if passed - if (callback) { - this.on("timeout", callback); - } - - // Start the timer if or when the socket is opened - if (this.socket) { - startTimer(this.socket); - } - else { - this._currentRequest.once("socket", startTimer); - } - - // Clean up on events - this.on("socket", destroyOnTimeout); - this.on("abort", clearTimer); - this.on("error", clearTimer); - this.on("response", clearTimer); - this.on("close", clearTimer); - - return this; -}; - -// Proxy all other public ClientRequest methods -[ - "flushHeaders", "getHeader", - "setNoDelay", "setSocketKeepAlive", -].forEach(function (method) { - RedirectableRequest.prototype[method] = function (a, b) { - return this._currentRequest[method](a, b); - }; -}); - -// Proxy all public ClientRequest properties -["aborted", "connection", "socket"].forEach(function (property) { - Object.defineProperty(RedirectableRequest.prototype, property, { - get: function () { return this._currentRequest[property]; }, - }); -}); - -RedirectableRequest.prototype._sanitizeOptions = function (options) { - // Ensure headers are always present - if (!options.headers) { - options.headers = {}; - } - - // Since http.request treats host as an alias of hostname, - // but the url module interprets host as hostname plus port, - // eliminate the host property to avoid confusion. - if (options.host) { - // Use hostname if set, because it has precedence - if (!options.hostname) { - options.hostname = options.host; - } - delete options.host; - } - - // Complete the URL object when necessary - if (!options.pathname && options.path) { - var searchPos = options.path.indexOf("?"); - if (searchPos < 0) { - options.pathname = options.path; - } - else { - options.pathname = options.path.substring(0, searchPos); - options.search = options.path.substring(searchPos); - } - } -}; - - -// Executes the next native request (initial or redirect) -RedirectableRequest.prototype._performRequest = function () { - // Load the native protocol - var protocol = this._options.protocol; - var nativeProtocol = this._options.nativeProtocols[protocol]; - if (!nativeProtocol) { - throw new TypeError("Unsupported protocol " + protocol); - } - - // If specified, use the agent corresponding to the protocol - // (HTTP and HTTPS use different types of agents) - if (this._options.agents) { - var scheme = protocol.slice(0, -1); - this._options.agent = this._options.agents[scheme]; - } - - // Create the native request and set up its event handlers - var request = this._currentRequest = - nativeProtocol.request(this._options, this._onNativeResponse); - request._redirectable = this; - for (var event of events) { - request.on(event, eventHandlers[event]); - } - - // RFC7230§5.3.1: When making a request directly to an origin server, […] - // a client MUST send only the absolute path […] as the request-target. - this._currentUrl = /^\//.test(this._options.path) ? - url.format(this._options) : - // When making a request to a proxy, […] - // a client MUST send the target URI in absolute-form […]. - this._options.path; - - // End a redirected request - // (The first request must be ended explicitly with RedirectableRequest#end) - if (this._isRedirect) { - // Write the request entity and end - var i = 0; - var self = this; - var buffers = this._requestBodyBuffers; - (function writeNext(error) { - // Only write if this request has not been redirected yet - // istanbul ignore else - if (request === self._currentRequest) { - // Report any write errors - // istanbul ignore if - if (error) { - self.emit("error", error); - } - // Write the next buffer if there are still left - else if (i < buffers.length) { - var buffer = buffers[i++]; - // istanbul ignore else - if (!request.finished) { - request.write(buffer.data, buffer.encoding, writeNext); - } - } - // End the request if `end` has been called on us - else if (self._ended) { - request.end(); - } - } - }()); - } -}; - -// Processes a response from the current native request -RedirectableRequest.prototype._processResponse = function (response) { - // Store the redirected response - var statusCode = response.statusCode; - if (this._options.trackRedirects) { - this._redirects.push({ - url: this._currentUrl, - headers: response.headers, - statusCode: statusCode, - }); - } - - // RFC7231§6.4: The 3xx (Redirection) class of status code indicates - // that further action needs to be taken by the user agent in order to - // fulfill the request. If a Location header field is provided, - // the user agent MAY automatically redirect its request to the URI - // referenced by the Location field value, - // even if the specific status code is not understood. - - // If the response is not a redirect; return it as-is - var location = response.headers.location; - if (!location || this._options.followRedirects === false || - statusCode < 300 || statusCode >= 400) { - response.responseUrl = this._currentUrl; - response.redirects = this._redirects; - this.emit("response", response); - - // Clean up - this._requestBodyBuffers = []; - return; - } - - // The response is a redirect, so abort the current request - destroyRequest(this._currentRequest); - // Discard the remainder of the response to avoid waiting for data - response.destroy(); - - // RFC7231§6.4: A client SHOULD detect and intervene - // in cyclical redirections (i.e., "infinite" redirection loops). - if (++this._redirectCount > this._options.maxRedirects) { - throw new TooManyRedirectsError(); - } - - // Store the request headers if applicable - var requestHeaders; - var beforeRedirect = this._options.beforeRedirect; - if (beforeRedirect) { - requestHeaders = Object.assign({ - // The Host header was set by nativeProtocol.request - Host: response.req.getHeader("host"), - }, this._options.headers); - } - - // RFC7231§6.4: Automatic redirection needs to done with - // care for methods not known to be safe, […] - // RFC7231§6.4.2–3: For historical reasons, a user agent MAY change - // the request method from POST to GET for the subsequent request. - var method = this._options.method; - if ((statusCode === 301 || statusCode === 302) && this._options.method === "POST" || - // RFC7231§6.4.4: The 303 (See Other) status code indicates that - // the server is redirecting the user agent to a different resource […] - // A user agent can perform a retrieval request targeting that URI - // (a GET or HEAD request if using HTTP) […] - (statusCode === 303) && !/^(?:GET|HEAD)$/.test(this._options.method)) { - this._options.method = "GET"; - // Drop a possible entity and headers related to it - this._requestBodyBuffers = []; - removeMatchingHeaders(/^content-/i, this._options.headers); - } - - // Drop the Host header, as the redirect might lead to a different host - var currentHostHeader = removeMatchingHeaders(/^host$/i, this._options.headers); - - // If the redirect is relative, carry over the host of the last request - var currentUrlParts = parseUrl(this._currentUrl); - var currentHost = currentHostHeader || currentUrlParts.host; - var currentUrl = /^\w+:/.test(location) ? this._currentUrl : - url.format(Object.assign(currentUrlParts, { host: currentHost })); - - // Create the redirected request - var redirectUrl = resolveUrl(location, currentUrl); - debug("redirecting to", redirectUrl.href); - this._isRedirect = true; - spreadUrlObject(redirectUrl, this._options); - - // Drop confidential headers when redirecting to a less secure protocol - // or to a different domain that is not a superdomain - if (redirectUrl.protocol !== currentUrlParts.protocol && - redirectUrl.protocol !== "https:" || - redirectUrl.host !== currentHost && - !isSubdomain(redirectUrl.host, currentHost)) { - removeMatchingHeaders(/^(?:(?:proxy-)?authorization|cookie)$/i, this._options.headers); - } - - // Evaluate the beforeRedirect callback - if (isFunction(beforeRedirect)) { - var responseDetails = { - headers: response.headers, - statusCode: statusCode, - }; - var requestDetails = { - url: currentUrl, - method: method, - headers: requestHeaders, - }; - beforeRedirect(this._options, responseDetails, requestDetails); - this._sanitizeOptions(this._options); - } - - // Perform the redirected request - this._performRequest(); -}; - -// Wraps the key/value object of protocols with redirect functionality -function wrap(protocols) { - // Default settings - var exports = { - maxRedirects: 21, - maxBodyLength: 10 * 1024 * 1024, - }; - - // Wrap each protocol - var nativeProtocols = {}; - Object.keys(protocols).forEach(function (scheme) { - var protocol = scheme + ":"; - var nativeProtocol = nativeProtocols[protocol] = protocols[scheme]; - var wrappedProtocol = exports[scheme] = Object.create(nativeProtocol); - - // Executes a request, following redirects - function request(input, options, callback) { - // Parse parameters, ensuring that input is an object - if (isURL(input)) { - input = spreadUrlObject(input); - } - else if (isString(input)) { - input = spreadUrlObject(parseUrl(input)); - } - else { - callback = options; - options = validateUrl(input); - input = { protocol: protocol }; - } - if (isFunction(options)) { - callback = options; - options = null; - } - - // Set defaults - options = Object.assign({ - maxRedirects: exports.maxRedirects, - maxBodyLength: exports.maxBodyLength, - }, input, options); - options.nativeProtocols = nativeProtocols; - if (!isString(options.host) && !isString(options.hostname)) { - options.hostname = "::1"; - } - - assert.equal(options.protocol, protocol, "protocol mismatch"); - debug("options", options); - return new RedirectableRequest(options, callback); - } - - // Executes a GET request, following redirects - function get(input, options, callback) { - var wrappedRequest = wrappedProtocol.request(input, options, callback); - wrappedRequest.end(); - return wrappedRequest; - } - - // Expose the properties on the wrapped protocol - Object.defineProperties(wrappedProtocol, { - request: { value: request, configurable: true, enumerable: true, writable: true }, - get: { value: get, configurable: true, enumerable: true, writable: true }, - }); - }); - return exports; -} - -function noop() { /* empty */ } - -function parseUrl(input) { - var parsed; - // istanbul ignore else - if (useNativeURL) { - parsed = new URL(input); - } - else { - // Ensure the URL is valid and absolute - parsed = validateUrl(url.parse(input)); - if (!isString(parsed.protocol)) { - throw new InvalidUrlError({ input }); - } - } - return parsed; -} - -function resolveUrl(relative, base) { - // istanbul ignore next - return useNativeURL ? new URL(relative, base) : parseUrl(url.resolve(base, relative)); -} - -function validateUrl(input) { - if (/^\[/.test(input.hostname) && !/^\[[:0-9a-f]+\]$/i.test(input.hostname)) { - throw new InvalidUrlError({ input: input.href || input }); - } - if (/^\[/.test(input.host) && !/^\[[:0-9a-f]+\](:\d+)?$/i.test(input.host)) { - throw new InvalidUrlError({ input: input.href || input }); - } - return input; -} - -function spreadUrlObject(urlObject, target) { - var spread = target || {}; - for (var key of preservedUrlFields) { - spread[key] = urlObject[key]; - } - - // Fix IPv6 hostname - if (spread.hostname.startsWith("[")) { - spread.hostname = spread.hostname.slice(1, -1); - } - // Ensure port is a number - if (spread.port !== "") { - spread.port = Number(spread.port); - } - // Concatenate path - spread.path = spread.search ? spread.pathname + spread.search : spread.pathname; - - return spread; -} - -function removeMatchingHeaders(regex, headers) { - var lastValue; - for (var header in headers) { - if (regex.test(header)) { - lastValue = headers[header]; - delete headers[header]; - } - } - return (lastValue === null || typeof lastValue === "undefined") ? - undefined : String(lastValue).trim(); -} - -function createErrorType(code, message, baseClass) { - // Create constructor - function CustomError(properties) { - // istanbul ignore else - if (isFunction(Error.captureStackTrace)) { - Error.captureStackTrace(this, this.constructor); - } - Object.assign(this, properties || {}); - this.code = code; - this.message = this.cause ? message + ": " + this.cause.message : message; - } - - // Attach constructor and set default properties - CustomError.prototype = Object.create((baseClass || Error).prototype); - Object.defineProperties(CustomError.prototype, { - constructor: { - value: CustomError, - enumerable: false, - }, - name: { - value: "Error [" + code + "]", - enumerable: false, - }, - }); - return CustomError; -} - -function destroyRequest(request, error) { - for (var event of events) { - request.removeListener(event, eventHandlers[event]); - } - request.on("error", noop); - request.destroy(error); -} - -function isSubdomain(subdomain, domain) { - assert(isString(subdomain) && isString(domain)); - var dot = subdomain.length - domain.length - 1; - return dot > 0 && subdomain[dot] === "." && subdomain.endsWith(domain); -} - -function isString(value) { - return typeof value === "string" || value instanceof String; -} - -function isFunction(value) { - return typeof value === "function"; -} - -function isBuffer(value) { - return typeof value === "object" && ("length" in value); -} - -function isURL(value) { - return URL && value instanceof URL; -} - -// Exports -module.exports = wrap({ http: http, https: https }); -module.exports.wrap = wrap; diff --git a/claude-code-source/node_modules/form-data/lib/form_data.js b/claude-code-source/node_modules/form-data/lib/form_data.js deleted file mode 100644 index 63a0f016..00000000 --- a/claude-code-source/node_modules/form-data/lib/form_data.js +++ /dev/null @@ -1,494 +0,0 @@ -'use strict'; - -var CombinedStream = require('combined-stream'); -var util = require('util'); -var path = require('path'); -var http = require('http'); -var https = require('https'); -var parseUrl = require('url').parse; -var fs = require('fs'); -var Stream = require('stream').Stream; -var crypto = require('crypto'); -var mime = require('mime-types'); -var asynckit = require('asynckit'); -var setToStringTag = require('es-set-tostringtag'); -var hasOwn = require('hasown'); -var populate = require('./populate.js'); - -/** - * Create readable "multipart/form-data" streams. - * Can be used to submit forms - * and file uploads to other web applications. - * - * @constructor - * @param {object} options - Properties to be added/overriden for FormData and CombinedStream - */ -function FormData(options) { - if (!(this instanceof FormData)) { - return new FormData(options); - } - - this._overheadLength = 0; - this._valueLength = 0; - this._valuesToMeasure = []; - - CombinedStream.call(this); - - options = options || {}; // eslint-disable-line no-param-reassign - for (var option in options) { // eslint-disable-line no-restricted-syntax - this[option] = options[option]; - } -} - -// make it a Stream -util.inherits(FormData, CombinedStream); - -FormData.LINE_BREAK = '\r\n'; -FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; - -FormData.prototype.append = function (field, value, options) { - options = options || {}; // eslint-disable-line no-param-reassign - - // allow filename as single option - if (typeof options === 'string') { - options = { filename: options }; // eslint-disable-line no-param-reassign - } - - var append = CombinedStream.prototype.append.bind(this); - - // all that streamy business can't handle numbers - if (typeof value === 'number' || value == null) { - value = String(value); // eslint-disable-line no-param-reassign - } - - // https://github.com/felixge/node-form-data/issues/38 - if (Array.isArray(value)) { - /* - * Please convert your array into string - * the way web server expects it - */ - this._error(new Error('Arrays are not supported.')); - return; - } - - var header = this._multiPartHeader(field, value, options); - var footer = this._multiPartFooter(); - - append(header); - append(value); - append(footer); - - // pass along options.knownLength - this._trackLength(header, value, options); -}; - -FormData.prototype._trackLength = function (header, value, options) { - var valueLength = 0; - - /* - * used w/ getLengthSync(), when length is known. - * e.g. for streaming directly from a remote server, - * w/ a known file a size, and not wanting to wait for - * incoming file to finish to get its size. - */ - if (options.knownLength != null) { - valueLength += Number(options.knownLength); - } else if (Buffer.isBuffer(value)) { - valueLength = value.length; - } else if (typeof value === 'string') { - valueLength = Buffer.byteLength(value); - } - - this._valueLength += valueLength; - - // @check why add CRLF? does this account for custom/multiple CRLFs? - this._overheadLength += Buffer.byteLength(header) + FormData.LINE_BREAK.length; - - // empty or either doesn't have path or not an http response or not a stream - if (!value || (!value.path && !(value.readable && hasOwn(value, 'httpVersion')) && !(value instanceof Stream))) { - return; - } - - // no need to bother with the length - if (!options.knownLength) { - this._valuesToMeasure.push(value); - } -}; - -FormData.prototype._lengthRetriever = function (value, callback) { - if (hasOwn(value, 'fd')) { - // take read range into a account - // `end` = Infinity –> read file till the end - // - // TODO: Looks like there is bug in Node fs.createReadStream - // it doesn't respect `end` options without `start` options - // Fix it when node fixes it. - // https://github.com/joyent/node/issues/7819 - if (value.end != undefined && value.end != Infinity && value.start != undefined) { - // when end specified - // no need to calculate range - // inclusive, starts with 0 - callback(null, value.end + 1 - (value.start ? value.start : 0)); // eslint-disable-line callback-return - - // not that fast snoopy - } else { - // still need to fetch file size from fs - fs.stat(value.path, function (err, stat) { - if (err) { - callback(err); - return; - } - - // update final size based on the range options - var fileSize = stat.size - (value.start ? value.start : 0); - callback(null, fileSize); - }); - } - - // or http response - } else if (hasOwn(value, 'httpVersion')) { - callback(null, Number(value.headers['content-length'])); // eslint-disable-line callback-return - - // or request stream http://github.com/mikeal/request - } else if (hasOwn(value, 'httpModule')) { - // wait till response come back - value.on('response', function (response) { - value.pause(); - callback(null, Number(response.headers['content-length'])); - }); - value.resume(); - - // something else - } else { - callback('Unknown stream'); // eslint-disable-line callback-return - } -}; - -FormData.prototype._multiPartHeader = function (field, value, options) { - /* - * custom header specified (as string)? - * it becomes responsible for boundary - * (e.g. to handle extra CRLFs on .NET servers) - */ - if (typeof options.header === 'string') { - return options.header; - } - - var contentDisposition = this._getContentDisposition(value, options); - var contentType = this._getContentType(value, options); - - var contents = ''; - var headers = { - // add custom disposition as third element or keep it two elements if not - 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), - // if no content type. allow it to be empty array - 'Content-Type': [].concat(contentType || []) - }; - - // allow custom headers. - if (typeof options.header === 'object') { - populate(headers, options.header); - } - - var header; - for (var prop in headers) { // eslint-disable-line no-restricted-syntax - if (hasOwn(headers, prop)) { - header = headers[prop]; - - // skip nullish headers. - if (header == null) { - continue; // eslint-disable-line no-restricted-syntax, no-continue - } - - // convert all headers to arrays. - if (!Array.isArray(header)) { - header = [header]; - } - - // add non-empty headers. - if (header.length) { - contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; - } - } - } - - return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; -}; - -FormData.prototype._getContentDisposition = function (value, options) { // eslint-disable-line consistent-return - var filename; - - if (typeof options.filepath === 'string') { - // custom filepath for relative paths - filename = path.normalize(options.filepath).replace(/\\/g, '/'); - } else if (options.filename || (value && (value.name || value.path))) { - /* - * custom filename take precedence - * formidable and the browser add a name property - * fs- and request- streams have path property - */ - filename = path.basename(options.filename || (value && (value.name || value.path))); - } else if (value && value.readable && hasOwn(value, 'httpVersion')) { - // or try http response - filename = path.basename(value.client._httpMessage.path || ''); - } - - if (filename) { - return 'filename="' + filename + '"'; - } -}; - -FormData.prototype._getContentType = function (value, options) { - // use custom content-type above all - var contentType = options.contentType; - - // or try `name` from formidable, browser - if (!contentType && value && value.name) { - contentType = mime.lookup(value.name); - } - - // or try `path` from fs-, request- streams - if (!contentType && value && value.path) { - contentType = mime.lookup(value.path); - } - - // or if it's http-reponse - if (!contentType && value && value.readable && hasOwn(value, 'httpVersion')) { - contentType = value.headers['content-type']; - } - - // or guess it from the filepath or filename - if (!contentType && (options.filepath || options.filename)) { - contentType = mime.lookup(options.filepath || options.filename); - } - - // fallback to the default content type if `value` is not simple value - if (!contentType && value && typeof value === 'object') { - contentType = FormData.DEFAULT_CONTENT_TYPE; - } - - return contentType; -}; - -FormData.prototype._multiPartFooter = function () { - return function (next) { - var footer = FormData.LINE_BREAK; - - var lastPart = this._streams.length === 0; - if (lastPart) { - footer += this._lastBoundary(); - } - - next(footer); - }.bind(this); -}; - -FormData.prototype._lastBoundary = function () { - return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; -}; - -FormData.prototype.getHeaders = function (userHeaders) { - var header; - var formHeaders = { - 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() - }; - - for (header in userHeaders) { // eslint-disable-line no-restricted-syntax - if (hasOwn(userHeaders, header)) { - formHeaders[header.toLowerCase()] = userHeaders[header]; - } - } - - return formHeaders; -}; - -FormData.prototype.setBoundary = function (boundary) { - if (typeof boundary !== 'string') { - throw new TypeError('FormData boundary must be a string'); - } - this._boundary = boundary; -}; - -FormData.prototype.getBoundary = function () { - if (!this._boundary) { - this._generateBoundary(); - } - - return this._boundary; -}; - -FormData.prototype.getBuffer = function () { - var dataBuffer = new Buffer.alloc(0); // eslint-disable-line new-cap - var boundary = this.getBoundary(); - - // Create the form content. Add Line breaks to the end of data. - for (var i = 0, len = this._streams.length; i < len; i++) { - if (typeof this._streams[i] !== 'function') { - // Add content to the buffer. - if (Buffer.isBuffer(this._streams[i])) { - dataBuffer = Buffer.concat([dataBuffer, this._streams[i]]); - } else { - dataBuffer = Buffer.concat([dataBuffer, Buffer.from(this._streams[i])]); - } - - // Add break after content. - if (typeof this._streams[i] !== 'string' || this._streams[i].substring(2, boundary.length + 2) !== boundary) { - dataBuffer = Buffer.concat([dataBuffer, Buffer.from(FormData.LINE_BREAK)]); - } - } - } - - // Add the footer and return the Buffer object. - return Buffer.concat([dataBuffer, Buffer.from(this._lastBoundary())]); -}; - -FormData.prototype._generateBoundary = function () { - // This generates a 50 character boundary similar to those used by Firefox. - - // They are optimized for boyer-moore parsing. - this._boundary = '--------------------------' + crypto.randomBytes(12).toString('hex'); -}; - -// Note: getLengthSync DOESN'T calculate streams length -// As workaround one can calculate file size manually and add it as knownLength option -FormData.prototype.getLengthSync = function () { - var knownLength = this._overheadLength + this._valueLength; - - // Don't get confused, there are 3 "internal" streams for each keyval pair so it basically checks if there is any value added to the form - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } - - // https://github.com/form-data/form-data/issues/40 - if (!this.hasKnownLength()) { - /* - * Some async length retrievers are present - * therefore synchronous length calculation is false. - * Please use getLength(callback) to get proper length - */ - this._error(new Error('Cannot calculate proper length in synchronous way.')); - } - - return knownLength; -}; - -// Public API to check if length of added values is known -// https://github.com/form-data/form-data/issues/196 -// https://github.com/form-data/form-data/issues/262 -FormData.prototype.hasKnownLength = function () { - var hasKnownLength = true; - - if (this._valuesToMeasure.length) { - hasKnownLength = false; - } - - return hasKnownLength; -}; - -FormData.prototype.getLength = function (cb) { - var knownLength = this._overheadLength + this._valueLength; - - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } - - if (!this._valuesToMeasure.length) { - process.nextTick(cb.bind(this, null, knownLength)); - return; - } - - asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function (err, values) { - if (err) { - cb(err); - return; - } - - values.forEach(function (length) { - knownLength += length; - }); - - cb(null, knownLength); - }); -}; - -FormData.prototype.submit = function (params, cb) { - var request; - var options; - var defaults = { method: 'post' }; - - // parse provided url if it's string or treat it as options object - if (typeof params === 'string') { - params = parseUrl(params); // eslint-disable-line no-param-reassign - /* eslint sort-keys: 0 */ - options = populate({ - port: params.port, - path: params.pathname, - host: params.hostname, - protocol: params.protocol - }, defaults); - } else { // use custom params - options = populate(params, defaults); - // if no port provided use default one - if (!options.port) { - options.port = options.protocol === 'https:' ? 443 : 80; - } - } - - // put that good code in getHeaders to some use - options.headers = this.getHeaders(params.headers); - - // https if specified, fallback to http in any other case - if (options.protocol === 'https:') { - request = https.request(options); - } else { - request = http.request(options); - } - - // get content length and fire away - this.getLength(function (err, length) { - if (err && err !== 'Unknown stream') { - this._error(err); - return; - } - - // add content length - if (length) { - request.setHeader('Content-Length', length); - } - - this.pipe(request); - if (cb) { - var onResponse; - - var callback = function (error, responce) { - request.removeListener('error', callback); - request.removeListener('response', onResponse); - - return cb.call(this, error, responce); - }; - - onResponse = callback.bind(this, null); - - request.on('error', callback); - request.on('response', onResponse); - } - }.bind(this)); - - return request; -}; - -FormData.prototype._error = function (err) { - if (!this.error) { - this.error = err; - this.pause(); - this.emit('error', err); - } -}; - -FormData.prototype.toString = function () { - return '[object FormData]'; -}; -setToStringTag(FormData.prototype, 'FormData'); - -// Public API -module.exports = FormData; diff --git a/claude-code-source/node_modules/form-data/lib/populate.js b/claude-code-source/node_modules/form-data/lib/populate.js deleted file mode 100644 index 55ac3bb2..00000000 --- a/claude-code-source/node_modules/form-data/lib/populate.js +++ /dev/null @@ -1,10 +0,0 @@ -'use strict'; - -// populates missing values -module.exports = function (dst, src) { - Object.keys(src).forEach(function (prop) { - dst[prop] = dst[prop] || src[prop]; // eslint-disable-line no-param-reassign - }); - - return dst; -}; diff --git a/claude-code-source/node_modules/function-bind/implementation.js b/claude-code-source/node_modules/function-bind/implementation.js deleted file mode 100644 index fd4384cc..00000000 --- a/claude-code-source/node_modules/function-bind/implementation.js +++ /dev/null @@ -1,84 +0,0 @@ -'use strict'; - -/* eslint no-invalid-this: 1 */ - -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var toStr = Object.prototype.toString; -var max = Math.max; -var funcType = '[object Function]'; - -var concatty = function concatty(a, b) { - var arr = []; - - for (var i = 0; i < a.length; i += 1) { - arr[i] = a[i]; - } - for (var j = 0; j < b.length; j += 1) { - arr[j + a.length] = b[j]; - } - - return arr; -}; - -var slicy = function slicy(arrLike, offset) { - var arr = []; - for (var i = offset || 0, j = 0; i < arrLike.length; i += 1, j += 1) { - arr[j] = arrLike[i]; - } - return arr; -}; - -var joiny = function (arr, joiner) { - var str = ''; - for (var i = 0; i < arr.length; i += 1) { - str += arr[i]; - if (i + 1 < arr.length) { - str += joiner; - } - } - return str; -}; - -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.apply(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); - } - var args = slicy(arguments, 1); - - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - concatty(args, arguments) - ); - if (Object(result) === result) { - return result; - } - return this; - } - return target.apply( - that, - concatty(args, arguments) - ); - - }; - - var boundLength = max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs[i] = '$' + i; - } - - bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); - - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; - } - - return bound; -}; diff --git a/claude-code-source/node_modules/function-bind/index.js b/claude-code-source/node_modules/function-bind/index.js deleted file mode 100644 index 3bb6b960..00000000 --- a/claude-code-source/node_modules/function-bind/index.js +++ /dev/null @@ -1,5 +0,0 @@ -'use strict'; - -var implementation = require('./implementation'); - -module.exports = Function.prototype.bind || implementation; diff --git a/claude-code-source/node_modules/fuse.js/dist/fuse.mjs b/claude-code-source/node_modules/fuse.js/dist/fuse.mjs deleted file mode 100644 index 4a9d2543..00000000 --- a/claude-code-source/node_modules/fuse.js/dist/fuse.mjs +++ /dev/null @@ -1,1778 +0,0 @@ -/** - * Fuse.js v7.0.0 - Lightweight fuzzy-search (http://fusejs.io) - * - * Copyright (c) 2023 Kiro Risk (http://kiro.me) - * All Rights Reserved. Apache Software License 2.0 - * - * http://www.apache.org/licenses/LICENSE-2.0 - */ - -function isArray(value) { - return !Array.isArray - ? getTag(value) === '[object Array]' - : Array.isArray(value) -} - -// Adapted from: https://github.com/lodash/lodash/blob/master/.internal/baseToString.js -const INFINITY = 1 / 0; -function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value - } - let result = value + ''; - return result == '0' && 1 / value == -INFINITY ? '-0' : result -} - -function toString(value) { - return value == null ? '' : baseToString(value) -} - -function isString(value) { - return typeof value === 'string' -} - -function isNumber(value) { - return typeof value === 'number' -} - -// Adapted from: https://github.com/lodash/lodash/blob/master/isBoolean.js -function isBoolean(value) { - return ( - value === true || - value === false || - (isObjectLike(value) && getTag(value) == '[object Boolean]') - ) -} - -function isObject(value) { - return typeof value === 'object' -} - -// Checks if `value` is object-like. -function isObjectLike(value) { - return isObject(value) && value !== null -} - -function isDefined(value) { - return value !== undefined && value !== null -} - -function isBlank(value) { - return !value.trim().length -} - -// Gets the `toStringTag` of `value`. -// Adapted from: https://github.com/lodash/lodash/blob/master/.internal/getTag.js -function getTag(value) { - return value == null - ? value === undefined - ? '[object Undefined]' - : '[object Null]' - : Object.prototype.toString.call(value) -} - -const EXTENDED_SEARCH_UNAVAILABLE = 'Extended search is not available'; - -const INCORRECT_INDEX_TYPE = "Incorrect 'index' type"; - -const LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY = (key) => - `Invalid value for key ${key}`; - -const PATTERN_LENGTH_TOO_LARGE = (max) => - `Pattern length exceeds max of ${max}.`; - -const MISSING_KEY_PROPERTY = (name) => `Missing ${name} property in key`; - -const INVALID_KEY_WEIGHT_VALUE = (key) => - `Property 'weight' in key '${key}' must be a positive integer`; - -const hasOwn = Object.prototype.hasOwnProperty; - -class KeyStore { - constructor(keys) { - this._keys = []; - this._keyMap = {}; - - let totalWeight = 0; - - keys.forEach((key) => { - let obj = createKey(key); - - this._keys.push(obj); - this._keyMap[obj.id] = obj; - - totalWeight += obj.weight; - }); - - // Normalize weights so that their sum is equal to 1 - this._keys.forEach((key) => { - key.weight /= totalWeight; - }); - } - get(keyId) { - return this._keyMap[keyId] - } - keys() { - return this._keys - } - toJSON() { - return JSON.stringify(this._keys) - } -} - -function createKey(key) { - let path = null; - let id = null; - let src = null; - let weight = 1; - let getFn = null; - - if (isString(key) || isArray(key)) { - src = key; - path = createKeyPath(key); - id = createKeyId(key); - } else { - if (!hasOwn.call(key, 'name')) { - throw new Error(MISSING_KEY_PROPERTY('name')) - } - - const name = key.name; - src = name; - - if (hasOwn.call(key, 'weight')) { - weight = key.weight; - - if (weight <= 0) { - throw new Error(INVALID_KEY_WEIGHT_VALUE(name)) - } - } - - path = createKeyPath(name); - id = createKeyId(name); - getFn = key.getFn; - } - - return { path, id, weight, src, getFn } -} - -function createKeyPath(key) { - return isArray(key) ? key : key.split('.') -} - -function createKeyId(key) { - return isArray(key) ? key.join('.') : key -} - -function get(obj, path) { - let list = []; - let arr = false; - - const deepGet = (obj, path, index) => { - if (!isDefined(obj)) { - return - } - if (!path[index]) { - // If there's no path left, we've arrived at the object we care about. - list.push(obj); - } else { - let key = path[index]; - - const value = obj[key]; - - if (!isDefined(value)) { - return - } - - // If we're at the last value in the path, and if it's a string/number/bool, - // add it to the list - if ( - index === path.length - 1 && - (isString(value) || isNumber(value) || isBoolean(value)) - ) { - list.push(toString(value)); - } else if (isArray(value)) { - arr = true; - // Search each item in the array. - for (let i = 0, len = value.length; i < len; i += 1) { - deepGet(value[i], path, index + 1); - } - } else if (path.length) { - // An object. Recurse further. - deepGet(value, path, index + 1); - } - } - }; - - // Backwards compatibility (since path used to be a string) - deepGet(obj, isString(path) ? path.split('.') : path, 0); - - return arr ? list : list[0] -} - -const MatchOptions = { - // Whether the matches should be included in the result set. When `true`, each record in the result - // set will include the indices of the matched characters. - // These can consequently be used for highlighting purposes. - includeMatches: false, - // When `true`, the matching function will continue to the end of a search pattern even if - // a perfect match has already been located in the string. - findAllMatches: false, - // Minimum number of characters that must be matched before a result is considered a match - minMatchCharLength: 1 -}; - -const BasicOptions = { - // When `true`, the algorithm continues searching to the end of the input even if a perfect - // match is found before the end of the same input. - isCaseSensitive: false, - // When true, the matching function will continue to the end of a search pattern even if - includeScore: false, - // List of properties that will be searched. This also supports nested properties. - keys: [], - // Whether to sort the result list, by score - shouldSort: true, - // Default sort function: sort by ascending score, ascending index - sortFn: (a, b) => - a.score === b.score ? (a.idx < b.idx ? -1 : 1) : a.score < b.score ? -1 : 1 -}; - -const FuzzyOptions = { - // Approximately where in the text is the pattern expected to be found? - location: 0, - // At what point does the match algorithm give up. A threshold of '0.0' requires a perfect match - // (of both letters and location), a threshold of '1.0' would match anything. - threshold: 0.6, - // Determines how close the match must be to the fuzzy location (specified above). - // An exact letter match which is 'distance' characters away from the fuzzy location - // would score as a complete mismatch. A distance of '0' requires the match be at - // the exact location specified, a threshold of '1000' would require a perfect match - // to be within 800 characters of the fuzzy location to be found using a 0.8 threshold. - distance: 100 -}; - -const AdvancedOptions = { - // When `true`, it enables the use of unix-like search commands - useExtendedSearch: false, - // The get function to use when fetching an object's properties. - // The default will search nested paths *ie foo.bar.baz* - getFn: get, - // When `true`, search will ignore `location` and `distance`, so it won't matter - // where in the string the pattern appears. - // More info: https://fusejs.io/concepts/scoring-theory.html#fuzziness-score - ignoreLocation: false, - // When `true`, the calculation for the relevance score (used for sorting) will - // ignore the field-length norm. - // More info: https://fusejs.io/concepts/scoring-theory.html#field-length-norm - ignoreFieldNorm: false, - // The weight to determine how much field length norm effects scoring. - fieldNormWeight: 1 -}; - -var Config = { - ...BasicOptions, - ...MatchOptions, - ...FuzzyOptions, - ...AdvancedOptions -}; - -const SPACE = /[^ ]+/g; - -// Field-length norm: the shorter the field, the higher the weight. -// Set to 3 decimals to reduce index size. -function norm(weight = 1, mantissa = 3) { - const cache = new Map(); - const m = Math.pow(10, mantissa); - - return { - get(value) { - const numTokens = value.match(SPACE).length; - - if (cache.has(numTokens)) { - return cache.get(numTokens) - } - - // Default function is 1/sqrt(x), weight makes that variable - const norm = 1 / Math.pow(numTokens, 0.5 * weight); - - // In place of `toFixed(mantissa)`, for faster computation - const n = parseFloat(Math.round(norm * m) / m); - - cache.set(numTokens, n); - - return n - }, - clear() { - cache.clear(); - } - } -} - -class FuseIndex { - constructor({ - getFn = Config.getFn, - fieldNormWeight = Config.fieldNormWeight - } = {}) { - this.norm = norm(fieldNormWeight, 3); - this.getFn = getFn; - this.isCreated = false; - - this.setIndexRecords(); - } - setSources(docs = []) { - this.docs = docs; - } - setIndexRecords(records = []) { - this.records = records; - } - setKeys(keys = []) { - this.keys = keys; - this._keysMap = {}; - keys.forEach((key, idx) => { - this._keysMap[key.id] = idx; - }); - } - create() { - if (this.isCreated || !this.docs.length) { - return - } - - this.isCreated = true; - - // List is Array - if (isString(this.docs[0])) { - this.docs.forEach((doc, docIndex) => { - this._addString(doc, docIndex); - }); - } else { - // List is Array - this.docs.forEach((doc, docIndex) => { - this._addObject(doc, docIndex); - }); - } - - this.norm.clear(); - } - // Adds a doc to the end of the index - add(doc) { - const idx = this.size(); - - if (isString(doc)) { - this._addString(doc, idx); - } else { - this._addObject(doc, idx); - } - } - // Removes the doc at the specified index of the index - removeAt(idx) { - this.records.splice(idx, 1); - - // Change ref index of every subsquent doc - for (let i = idx, len = this.size(); i < len; i += 1) { - this.records[i].i -= 1; - } - } - getValueForItemAtKeyId(item, keyId) { - return item[this._keysMap[keyId]] - } - size() { - return this.records.length - } - _addString(doc, docIndex) { - if (!isDefined(doc) || isBlank(doc)) { - return - } - - let record = { - v: doc, - i: docIndex, - n: this.norm.get(doc) - }; - - this.records.push(record); - } - _addObject(doc, docIndex) { - let record = { i: docIndex, $: {} }; - - // Iterate over every key (i.e, path), and fetch the value at that key - this.keys.forEach((key, keyIndex) => { - let value = key.getFn ? key.getFn(doc) : this.getFn(doc, key.path); - - if (!isDefined(value)) { - return - } - - if (isArray(value)) { - let subRecords = []; - const stack = [{ nestedArrIndex: -1, value }]; - - while (stack.length) { - const { nestedArrIndex, value } = stack.pop(); - - if (!isDefined(value)) { - continue - } - - if (isString(value) && !isBlank(value)) { - let subRecord = { - v: value, - i: nestedArrIndex, - n: this.norm.get(value) - }; - - subRecords.push(subRecord); - } else if (isArray(value)) { - value.forEach((item, k) => { - stack.push({ - nestedArrIndex: k, - value: item - }); - }); - } else ; - } - record.$[keyIndex] = subRecords; - } else if (isString(value) && !isBlank(value)) { - let subRecord = { - v: value, - n: this.norm.get(value) - }; - - record.$[keyIndex] = subRecord; - } - }); - - this.records.push(record); - } - toJSON() { - return { - keys: this.keys, - records: this.records - } - } -} - -function createIndex( - keys, - docs, - { getFn = Config.getFn, fieldNormWeight = Config.fieldNormWeight } = {} -) { - const myIndex = new FuseIndex({ getFn, fieldNormWeight }); - myIndex.setKeys(keys.map(createKey)); - myIndex.setSources(docs); - myIndex.create(); - return myIndex -} - -function parseIndex( - data, - { getFn = Config.getFn, fieldNormWeight = Config.fieldNormWeight } = {} -) { - const { keys, records } = data; - const myIndex = new FuseIndex({ getFn, fieldNormWeight }); - myIndex.setKeys(keys); - myIndex.setIndexRecords(records); - return myIndex -} - -function computeScore$1( - pattern, - { - errors = 0, - currentLocation = 0, - expectedLocation = 0, - distance = Config.distance, - ignoreLocation = Config.ignoreLocation - } = {} -) { - const accuracy = errors / pattern.length; - - if (ignoreLocation) { - return accuracy - } - - const proximity = Math.abs(expectedLocation - currentLocation); - - if (!distance) { - // Dodge divide by zero error. - return proximity ? 1.0 : accuracy - } - - return accuracy + proximity / distance -} - -function convertMaskToIndices( - matchmask = [], - minMatchCharLength = Config.minMatchCharLength -) { - let indices = []; - let start = -1; - let end = -1; - let i = 0; - - for (let len = matchmask.length; i < len; i += 1) { - let match = matchmask[i]; - if (match && start === -1) { - start = i; - } else if (!match && start !== -1) { - end = i - 1; - if (end - start + 1 >= minMatchCharLength) { - indices.push([start, end]); - } - start = -1; - } - } - - // (i-1 - start) + 1 => i - start - if (matchmask[i - 1] && i - start >= minMatchCharLength) { - indices.push([start, i - 1]); - } - - return indices -} - -// Machine word size -const MAX_BITS = 32; - -function search( - text, - pattern, - patternAlphabet, - { - location = Config.location, - distance = Config.distance, - threshold = Config.threshold, - findAllMatches = Config.findAllMatches, - minMatchCharLength = Config.minMatchCharLength, - includeMatches = Config.includeMatches, - ignoreLocation = Config.ignoreLocation - } = {} -) { - if (pattern.length > MAX_BITS) { - throw new Error(PATTERN_LENGTH_TOO_LARGE(MAX_BITS)) - } - - const patternLen = pattern.length; - // Set starting location at beginning text and initialize the alphabet. - const textLen = text.length; - // Handle the case when location > text.length - const expectedLocation = Math.max(0, Math.min(location, textLen)); - // Highest score beyond which we give up. - let currentThreshold = threshold; - // Is there a nearby exact match? (speedup) - let bestLocation = expectedLocation; - - // Performance: only computer matches when the minMatchCharLength > 1 - // OR if `includeMatches` is true. - const computeMatches = minMatchCharLength > 1 || includeMatches; - // A mask of the matches, used for building the indices - const matchMask = computeMatches ? Array(textLen) : []; - - let index; - - // Get all exact matches, here for speed up - while ((index = text.indexOf(pattern, bestLocation)) > -1) { - let score = computeScore$1(pattern, { - currentLocation: index, - expectedLocation, - distance, - ignoreLocation - }); - - currentThreshold = Math.min(score, currentThreshold); - bestLocation = index + patternLen; - - if (computeMatches) { - let i = 0; - while (i < patternLen) { - matchMask[index + i] = 1; - i += 1; - } - } - } - - // Reset the best location - bestLocation = -1; - - let lastBitArr = []; - let finalScore = 1; - let binMax = patternLen + textLen; - - const mask = 1 << (patternLen - 1); - - for (let i = 0; i < patternLen; i += 1) { - // Scan for the best match; each iteration allows for one more error. - // Run a binary search to determine how far from the match location we can stray - // at this error level. - let binMin = 0; - let binMid = binMax; - - while (binMin < binMid) { - const score = computeScore$1(pattern, { - errors: i, - currentLocation: expectedLocation + binMid, - expectedLocation, - distance, - ignoreLocation - }); - - if (score <= currentThreshold) { - binMin = binMid; - } else { - binMax = binMid; - } - - binMid = Math.floor((binMax - binMin) / 2 + binMin); - } - - // Use the result from this iteration as the maximum for the next. - binMax = binMid; - - let start = Math.max(1, expectedLocation - binMid + 1); - let finish = findAllMatches - ? textLen - : Math.min(expectedLocation + binMid, textLen) + patternLen; - - // Initialize the bit array - let bitArr = Array(finish + 2); - - bitArr[finish + 1] = (1 << i) - 1; - - for (let j = finish; j >= start; j -= 1) { - let currentLocation = j - 1; - let charMatch = patternAlphabet[text.charAt(currentLocation)]; - - if (computeMatches) { - // Speed up: quick bool to int conversion (i.e, `charMatch ? 1 : 0`) - matchMask[currentLocation] = +!!charMatch; - } - - // First pass: exact match - bitArr[j] = ((bitArr[j + 1] << 1) | 1) & charMatch; - - // Subsequent passes: fuzzy match - if (i) { - bitArr[j] |= - ((lastBitArr[j + 1] | lastBitArr[j]) << 1) | 1 | lastBitArr[j + 1]; - } - - if (bitArr[j] & mask) { - finalScore = computeScore$1(pattern, { - errors: i, - currentLocation, - expectedLocation, - distance, - ignoreLocation - }); - - // This match will almost certainly be better than any existing match. - // But check anyway. - if (finalScore <= currentThreshold) { - // Indeed it is - currentThreshold = finalScore; - bestLocation = currentLocation; - - // Already passed `loc`, downhill from here on in. - if (bestLocation <= expectedLocation) { - break - } - - // When passing `bestLocation`, don't exceed our current distance from `expectedLocation`. - start = Math.max(1, 2 * expectedLocation - bestLocation); - } - } - } - - // No hope for a (better) match at greater error levels. - const score = computeScore$1(pattern, { - errors: i + 1, - currentLocation: expectedLocation, - expectedLocation, - distance, - ignoreLocation - }); - - if (score > currentThreshold) { - break - } - - lastBitArr = bitArr; - } - - const result = { - isMatch: bestLocation >= 0, - // Count exact matches (those with a score of 0) to be "almost" exact - score: Math.max(0.001, finalScore) - }; - - if (computeMatches) { - const indices = convertMaskToIndices(matchMask, minMatchCharLength); - if (!indices.length) { - result.isMatch = false; - } else if (includeMatches) { - result.indices = indices; - } - } - - return result -} - -function createPatternAlphabet(pattern) { - let mask = {}; - - for (let i = 0, len = pattern.length; i < len; i += 1) { - const char = pattern.charAt(i); - mask[char] = (mask[char] || 0) | (1 << (len - i - 1)); - } - - return mask -} - -class BitapSearch { - constructor( - pattern, - { - location = Config.location, - threshold = Config.threshold, - distance = Config.distance, - includeMatches = Config.includeMatches, - findAllMatches = Config.findAllMatches, - minMatchCharLength = Config.minMatchCharLength, - isCaseSensitive = Config.isCaseSensitive, - ignoreLocation = Config.ignoreLocation - } = {} - ) { - this.options = { - location, - threshold, - distance, - includeMatches, - findAllMatches, - minMatchCharLength, - isCaseSensitive, - ignoreLocation - }; - - this.pattern = isCaseSensitive ? pattern : pattern.toLowerCase(); - - this.chunks = []; - - if (!this.pattern.length) { - return - } - - const addChunk = (pattern, startIndex) => { - this.chunks.push({ - pattern, - alphabet: createPatternAlphabet(pattern), - startIndex - }); - }; - - const len = this.pattern.length; - - if (len > MAX_BITS) { - let i = 0; - const remainder = len % MAX_BITS; - const end = len - remainder; - - while (i < end) { - addChunk(this.pattern.substr(i, MAX_BITS), i); - i += MAX_BITS; - } - - if (remainder) { - const startIndex = len - MAX_BITS; - addChunk(this.pattern.substr(startIndex), startIndex); - } - } else { - addChunk(this.pattern, 0); - } - } - - searchIn(text) { - const { isCaseSensitive, includeMatches } = this.options; - - if (!isCaseSensitive) { - text = text.toLowerCase(); - } - - // Exact match - if (this.pattern === text) { - let result = { - isMatch: true, - score: 0 - }; - - if (includeMatches) { - result.indices = [[0, text.length - 1]]; - } - - return result - } - - // Otherwise, use Bitap algorithm - const { - location, - distance, - threshold, - findAllMatches, - minMatchCharLength, - ignoreLocation - } = this.options; - - let allIndices = []; - let totalScore = 0; - let hasMatches = false; - - this.chunks.forEach(({ pattern, alphabet, startIndex }) => { - const { isMatch, score, indices } = search(text, pattern, alphabet, { - location: location + startIndex, - distance, - threshold, - findAllMatches, - minMatchCharLength, - includeMatches, - ignoreLocation - }); - - if (isMatch) { - hasMatches = true; - } - - totalScore += score; - - if (isMatch && indices) { - allIndices = [...allIndices, ...indices]; - } - }); - - let result = { - isMatch: hasMatches, - score: hasMatches ? totalScore / this.chunks.length : 1 - }; - - if (hasMatches && includeMatches) { - result.indices = allIndices; - } - - return result - } -} - -class BaseMatch { - constructor(pattern) { - this.pattern = pattern; - } - static isMultiMatch(pattern) { - return getMatch(pattern, this.multiRegex) - } - static isSingleMatch(pattern) { - return getMatch(pattern, this.singleRegex) - } - search(/*text*/) {} -} - -function getMatch(pattern, exp) { - const matches = pattern.match(exp); - return matches ? matches[1] : null -} - -// Token: 'file - -class ExactMatch extends BaseMatch { - constructor(pattern) { - super(pattern); - } - static get type() { - return 'exact' - } - static get multiRegex() { - return /^="(.*)"$/ - } - static get singleRegex() { - return /^=(.*)$/ - } - search(text) { - const isMatch = text === this.pattern; - - return { - isMatch, - score: isMatch ? 0 : 1, - indices: [0, this.pattern.length - 1] - } - } -} - -// Token: !fire - -class InverseExactMatch extends BaseMatch { - constructor(pattern) { - super(pattern); - } - static get type() { - return 'inverse-exact' - } - static get multiRegex() { - return /^!"(.*)"$/ - } - static get singleRegex() { - return /^!(.*)$/ - } - search(text) { - const index = text.indexOf(this.pattern); - const isMatch = index === -1; - - return { - isMatch, - score: isMatch ? 0 : 1, - indices: [0, text.length - 1] - } - } -} - -// Token: ^file - -class PrefixExactMatch extends BaseMatch { - constructor(pattern) { - super(pattern); - } - static get type() { - return 'prefix-exact' - } - static get multiRegex() { - return /^\^"(.*)"$/ - } - static get singleRegex() { - return /^\^(.*)$/ - } - search(text) { - const isMatch = text.startsWith(this.pattern); - - return { - isMatch, - score: isMatch ? 0 : 1, - indices: [0, this.pattern.length - 1] - } - } -} - -// Token: !^fire - -class InversePrefixExactMatch extends BaseMatch { - constructor(pattern) { - super(pattern); - } - static get type() { - return 'inverse-prefix-exact' - } - static get multiRegex() { - return /^!\^"(.*)"$/ - } - static get singleRegex() { - return /^!\^(.*)$/ - } - search(text) { - const isMatch = !text.startsWith(this.pattern); - - return { - isMatch, - score: isMatch ? 0 : 1, - indices: [0, text.length - 1] - } - } -} - -// Token: .file$ - -class SuffixExactMatch extends BaseMatch { - constructor(pattern) { - super(pattern); - } - static get type() { - return 'suffix-exact' - } - static get multiRegex() { - return /^"(.*)"\$$/ - } - static get singleRegex() { - return /^(.*)\$$/ - } - search(text) { - const isMatch = text.endsWith(this.pattern); - - return { - isMatch, - score: isMatch ? 0 : 1, - indices: [text.length - this.pattern.length, text.length - 1] - } - } -} - -// Token: !.file$ - -class InverseSuffixExactMatch extends BaseMatch { - constructor(pattern) { - super(pattern); - } - static get type() { - return 'inverse-suffix-exact' - } - static get multiRegex() { - return /^!"(.*)"\$$/ - } - static get singleRegex() { - return /^!(.*)\$$/ - } - search(text) { - const isMatch = !text.endsWith(this.pattern); - return { - isMatch, - score: isMatch ? 0 : 1, - indices: [0, text.length - 1] - } - } -} - -class FuzzyMatch extends BaseMatch { - constructor( - pattern, - { - location = Config.location, - threshold = Config.threshold, - distance = Config.distance, - includeMatches = Config.includeMatches, - findAllMatches = Config.findAllMatches, - minMatchCharLength = Config.minMatchCharLength, - isCaseSensitive = Config.isCaseSensitive, - ignoreLocation = Config.ignoreLocation - } = {} - ) { - super(pattern); - this._bitapSearch = new BitapSearch(pattern, { - location, - threshold, - distance, - includeMatches, - findAllMatches, - minMatchCharLength, - isCaseSensitive, - ignoreLocation - }); - } - static get type() { - return 'fuzzy' - } - static get multiRegex() { - return /^"(.*)"$/ - } - static get singleRegex() { - return /^(.*)$/ - } - search(text) { - return this._bitapSearch.searchIn(text) - } -} - -// Token: 'file - -class IncludeMatch extends BaseMatch { - constructor(pattern) { - super(pattern); - } - static get type() { - return 'include' - } - static get multiRegex() { - return /^'"(.*)"$/ - } - static get singleRegex() { - return /^'(.*)$/ - } - search(text) { - let location = 0; - let index; - - const indices = []; - const patternLen = this.pattern.length; - - // Get all exact matches - while ((index = text.indexOf(this.pattern, location)) > -1) { - location = index + patternLen; - indices.push([index, location - 1]); - } - - const isMatch = !!indices.length; - - return { - isMatch, - score: isMatch ? 0 : 1, - indices - } - } -} - -// ❗Order is important. DO NOT CHANGE. -const searchers = [ - ExactMatch, - IncludeMatch, - PrefixExactMatch, - InversePrefixExactMatch, - InverseSuffixExactMatch, - SuffixExactMatch, - InverseExactMatch, - FuzzyMatch -]; - -const searchersLen = searchers.length; - -// Regex to split by spaces, but keep anything in quotes together -const SPACE_RE = / +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/; -const OR_TOKEN = '|'; - -// Return a 2D array representation of the query, for simpler parsing. -// Example: -// "^core go$ | rb$ | py$ xy$" => [["^core", "go$"], ["rb$"], ["py$", "xy$"]] -function parseQuery(pattern, options = {}) { - return pattern.split(OR_TOKEN).map((item) => { - let query = item - .trim() - .split(SPACE_RE) - .filter((item) => item && !!item.trim()); - - let results = []; - for (let i = 0, len = query.length; i < len; i += 1) { - const queryItem = query[i]; - - // 1. Handle multiple query match (i.e, once that are quoted, like `"hello world"`) - let found = false; - let idx = -1; - while (!found && ++idx < searchersLen) { - const searcher = searchers[idx]; - let token = searcher.isMultiMatch(queryItem); - if (token) { - results.push(new searcher(token, options)); - found = true; - } - } - - if (found) { - continue - } - - // 2. Handle single query matches (i.e, once that are *not* quoted) - idx = -1; - while (++idx < searchersLen) { - const searcher = searchers[idx]; - let token = searcher.isSingleMatch(queryItem); - if (token) { - results.push(new searcher(token, options)); - break - } - } - } - - return results - }) -} - -// These extended matchers can return an array of matches, as opposed -// to a singl match -const MultiMatchSet = new Set([FuzzyMatch.type, IncludeMatch.type]); - -/** - * Command-like searching - * ====================== - * - * Given multiple search terms delimited by spaces.e.g. `^jscript .python$ ruby !java`, - * search in a given text. - * - * Search syntax: - * - * | Token | Match type | Description | - * | ----------- | -------------------------- | -------------------------------------- | - * | `jscript` | fuzzy-match | Items that fuzzy match `jscript` | - * | `=scheme` | exact-match | Items that are `scheme` | - * | `'python` | include-match | Items that include `python` | - * | `!ruby` | inverse-exact-match | Items that do not include `ruby` | - * | `^java` | prefix-exact-match | Items that start with `java` | - * | `!^earlang` | inverse-prefix-exact-match | Items that do not start with `earlang` | - * | `.js$` | suffix-exact-match | Items that end with `.js` | - * | `!.go$` | inverse-suffix-exact-match | Items that do not end with `.go` | - * - * A single pipe character acts as an OR operator. For example, the following - * query matches entries that start with `core` and end with either`go`, `rb`, - * or`py`. - * - * ``` - * ^core go$ | rb$ | py$ - * ``` - */ -class ExtendedSearch { - constructor( - pattern, - { - isCaseSensitive = Config.isCaseSensitive, - includeMatches = Config.includeMatches, - minMatchCharLength = Config.minMatchCharLength, - ignoreLocation = Config.ignoreLocation, - findAllMatches = Config.findAllMatches, - location = Config.location, - threshold = Config.threshold, - distance = Config.distance - } = {} - ) { - this.query = null; - this.options = { - isCaseSensitive, - includeMatches, - minMatchCharLength, - findAllMatches, - ignoreLocation, - location, - threshold, - distance - }; - - this.pattern = isCaseSensitive ? pattern : pattern.toLowerCase(); - this.query = parseQuery(this.pattern, this.options); - } - - static condition(_, options) { - return options.useExtendedSearch - } - - searchIn(text) { - const query = this.query; - - if (!query) { - return { - isMatch: false, - score: 1 - } - } - - const { includeMatches, isCaseSensitive } = this.options; - - text = isCaseSensitive ? text : text.toLowerCase(); - - let numMatches = 0; - let allIndices = []; - let totalScore = 0; - - // ORs - for (let i = 0, qLen = query.length; i < qLen; i += 1) { - const searchers = query[i]; - - // Reset indices - allIndices.length = 0; - numMatches = 0; - - // ANDs - for (let j = 0, pLen = searchers.length; j < pLen; j += 1) { - const searcher = searchers[j]; - const { isMatch, indices, score } = searcher.search(text); - - if (isMatch) { - numMatches += 1; - totalScore += score; - if (includeMatches) { - const type = searcher.constructor.type; - if (MultiMatchSet.has(type)) { - allIndices = [...allIndices, ...indices]; - } else { - allIndices.push(indices); - } - } - } else { - totalScore = 0; - numMatches = 0; - allIndices.length = 0; - break - } - } - - // OR condition, so if TRUE, return - if (numMatches) { - let result = { - isMatch: true, - score: totalScore / numMatches - }; - - if (includeMatches) { - result.indices = allIndices; - } - - return result - } - } - - // Nothing was matched - return { - isMatch: false, - score: 1 - } - } -} - -const registeredSearchers = []; - -function register(...args) { - registeredSearchers.push(...args); -} - -function createSearcher(pattern, options) { - for (let i = 0, len = registeredSearchers.length; i < len; i += 1) { - let searcherClass = registeredSearchers[i]; - if (searcherClass.condition(pattern, options)) { - return new searcherClass(pattern, options) - } - } - - return new BitapSearch(pattern, options) -} - -const LogicalOperator = { - AND: '$and', - OR: '$or' -}; - -const KeyType = { - PATH: '$path', - PATTERN: '$val' -}; - -const isExpression = (query) => - !!(query[LogicalOperator.AND] || query[LogicalOperator.OR]); - -const isPath = (query) => !!query[KeyType.PATH]; - -const isLeaf = (query) => - !isArray(query) && isObject(query) && !isExpression(query); - -const convertToExplicit = (query) => ({ - [LogicalOperator.AND]: Object.keys(query).map((key) => ({ - [key]: query[key] - })) -}); - -// When `auto` is `true`, the parse function will infer and initialize and add -// the appropriate `Searcher` instance -function parse(query, options, { auto = true } = {}) { - const next = (query) => { - let keys = Object.keys(query); - - const isQueryPath = isPath(query); - - if (!isQueryPath && keys.length > 1 && !isExpression(query)) { - return next(convertToExplicit(query)) - } - - if (isLeaf(query)) { - const key = isQueryPath ? query[KeyType.PATH] : keys[0]; - - const pattern = isQueryPath ? query[KeyType.PATTERN] : query[key]; - - if (!isString(pattern)) { - throw new Error(LOGICAL_SEARCH_INVALID_QUERY_FOR_KEY(key)) - } - - const obj = { - keyId: createKeyId(key), - pattern - }; - - if (auto) { - obj.searcher = createSearcher(pattern, options); - } - - return obj - } - - let node = { - children: [], - operator: keys[0] - }; - - keys.forEach((key) => { - const value = query[key]; - - if (isArray(value)) { - value.forEach((item) => { - node.children.push(next(item)); - }); - } - }); - - return node - }; - - if (!isExpression(query)) { - query = convertToExplicit(query); - } - - return next(query) -} - -// Practical scoring function -function computeScore( - results, - { ignoreFieldNorm = Config.ignoreFieldNorm } -) { - results.forEach((result) => { - let totalScore = 1; - - result.matches.forEach(({ key, norm, score }) => { - const weight = key ? key.weight : null; - - totalScore *= Math.pow( - score === 0 && weight ? Number.EPSILON : score, - (weight || 1) * (ignoreFieldNorm ? 1 : norm) - ); - }); - - result.score = totalScore; - }); -} - -function transformMatches(result, data) { - const matches = result.matches; - data.matches = []; - - if (!isDefined(matches)) { - return - } - - matches.forEach((match) => { - if (!isDefined(match.indices) || !match.indices.length) { - return - } - - const { indices, value } = match; - - let obj = { - indices, - value - }; - - if (match.key) { - obj.key = match.key.src; - } - - if (match.idx > -1) { - obj.refIndex = match.idx; - } - - data.matches.push(obj); - }); -} - -function transformScore(result, data) { - data.score = result.score; -} - -function format( - results, - docs, - { - includeMatches = Config.includeMatches, - includeScore = Config.includeScore - } = {} -) { - const transformers = []; - - if (includeMatches) transformers.push(transformMatches); - if (includeScore) transformers.push(transformScore); - - return results.map((result) => { - const { idx } = result; - - const data = { - item: docs[idx], - refIndex: idx - }; - - if (transformers.length) { - transformers.forEach((transformer) => { - transformer(result, data); - }); - } - - return data - }) -} - -class Fuse { - constructor(docs, options = {}, index) { - this.options = { ...Config, ...options }; - - if ( - this.options.useExtendedSearch && - !true - ) { - throw new Error(EXTENDED_SEARCH_UNAVAILABLE) - } - - this._keyStore = new KeyStore(this.options.keys); - - this.setCollection(docs, index); - } - - setCollection(docs, index) { - this._docs = docs; - - if (index && !(index instanceof FuseIndex)) { - throw new Error(INCORRECT_INDEX_TYPE) - } - - this._myIndex = - index || - createIndex(this.options.keys, this._docs, { - getFn: this.options.getFn, - fieldNormWeight: this.options.fieldNormWeight - }); - } - - add(doc) { - if (!isDefined(doc)) { - return - } - - this._docs.push(doc); - this._myIndex.add(doc); - } - - remove(predicate = (/* doc, idx */) => false) { - const results = []; - - for (let i = 0, len = this._docs.length; i < len; i += 1) { - const doc = this._docs[i]; - if (predicate(doc, i)) { - this.removeAt(i); - i -= 1; - len -= 1; - - results.push(doc); - } - } - - return results - } - - removeAt(idx) { - this._docs.splice(idx, 1); - this._myIndex.removeAt(idx); - } - - getIndex() { - return this._myIndex - } - - search(query, { limit = -1 } = {}) { - const { - includeMatches, - includeScore, - shouldSort, - sortFn, - ignoreFieldNorm - } = this.options; - - let results = isString(query) - ? isString(this._docs[0]) - ? this._searchStringList(query) - : this._searchObjectList(query) - : this._searchLogical(query); - - computeScore(results, { ignoreFieldNorm }); - - if (shouldSort) { - results.sort(sortFn); - } - - if (isNumber(limit) && limit > -1) { - results = results.slice(0, limit); - } - - return format(results, this._docs, { - includeMatches, - includeScore - }) - } - - _searchStringList(query) { - const searcher = createSearcher(query, this.options); - const { records } = this._myIndex; - const results = []; - - // Iterate over every string in the index - records.forEach(({ v: text, i: idx, n: norm }) => { - if (!isDefined(text)) { - return - } - - const { isMatch, score, indices } = searcher.searchIn(text); - - if (isMatch) { - results.push({ - item: text, - idx, - matches: [{ score, value: text, norm, indices }] - }); - } - }); - - return results - } - - _searchLogical(query) { - - const expression = parse(query, this.options); - - const evaluate = (node, item, idx) => { - if (!node.children) { - const { keyId, searcher } = node; - - const matches = this._findMatches({ - key: this._keyStore.get(keyId), - value: this._myIndex.getValueForItemAtKeyId(item, keyId), - searcher - }); - - if (matches && matches.length) { - return [ - { - idx, - item, - matches - } - ] - } - - return [] - } - - const res = []; - for (let i = 0, len = node.children.length; i < len; i += 1) { - const child = node.children[i]; - const result = evaluate(child, item, idx); - if (result.length) { - res.push(...result); - } else if (node.operator === LogicalOperator.AND) { - return [] - } - } - return res - }; - - const records = this._myIndex.records; - const resultMap = {}; - const results = []; - - records.forEach(({ $: item, i: idx }) => { - if (isDefined(item)) { - let expResults = evaluate(expression, item, idx); - - if (expResults.length) { - // Dedupe when adding - if (!resultMap[idx]) { - resultMap[idx] = { idx, item, matches: [] }; - results.push(resultMap[idx]); - } - expResults.forEach(({ matches }) => { - resultMap[idx].matches.push(...matches); - }); - } - } - }); - - return results - } - - _searchObjectList(query) { - const searcher = createSearcher(query, this.options); - const { keys, records } = this._myIndex; - const results = []; - - // List is Array - records.forEach(({ $: item, i: idx }) => { - if (!isDefined(item)) { - return - } - - let matches = []; - - // Iterate over every key (i.e, path), and fetch the value at that key - keys.forEach((key, keyIndex) => { - matches.push( - ...this._findMatches({ - key, - value: item[keyIndex], - searcher - }) - ); - }); - - if (matches.length) { - results.push({ - idx, - item, - matches - }); - } - }); - - return results - } - _findMatches({ key, value, searcher }) { - if (!isDefined(value)) { - return [] - } - - let matches = []; - - if (isArray(value)) { - value.forEach(({ v: text, i: idx, n: norm }) => { - if (!isDefined(text)) { - return - } - - const { isMatch, score, indices } = searcher.searchIn(text); - - if (isMatch) { - matches.push({ - score, - key, - value: text, - idx, - norm, - indices - }); - } - }); - } else { - const { v: text, n: norm } = value; - - const { isMatch, score, indices } = searcher.searchIn(text); - - if (isMatch) { - matches.push({ score, key, value: text, norm, indices }); - } - } - - return matches - } -} - -Fuse.version = '7.0.0'; -Fuse.createIndex = createIndex; -Fuse.parseIndex = parseIndex; -Fuse.config = Config; - -{ - Fuse.parseQuery = parse; -} - -{ - register(ExtendedSearch); -} - -export { Fuse as default }; diff --git a/claude-code-source/node_modules/galactus/lib/DestroyerOfModules.js b/claude-code-source/node_modules/galactus/lib/DestroyerOfModules.js deleted file mode 100644 index f1d1a09c..00000000 --- a/claude-code-source/node_modules/galactus/lib/DestroyerOfModules.js +++ /dev/null @@ -1,69 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DestroyerOfModules = void 0; -const fs = require("fs-extra"); -const path = require("path"); -const flora_colossus_1 = require("flora-colossus"); -class DestroyerOfModules { - constructor({ rootDirectory, walker, shouldKeepModuleTest, }) { - if (rootDirectory) { - this.walker = new flora_colossus_1.Walker(rootDirectory); - } - else if (walker) { - this.walker = walker; - } - else { - throw new Error('Must either provide rootDirectory or walker argument'); - } - if (shouldKeepModuleTest) { - this.shouldKeepFn = shouldKeepModuleTest; - } - } - async destroyModule(modulePath, moduleMap) { - const module = moduleMap.get(modulePath); - if (module) { - const nodeModulesPath = path.resolve(modulePath, 'node_modules'); - if (!await fs.pathExists(nodeModulesPath)) { - return; - } - for (const subModuleName of await fs.readdir(nodeModulesPath)) { - if (subModuleName.startsWith('@')) { - for (const subScopedModuleName of await fs.readdir(path.resolve(nodeModulesPath, subModuleName))) { - await this.destroyModule(path.resolve(nodeModulesPath, subModuleName, subScopedModuleName), moduleMap); - } - } - else { - await this.destroyModule(path.resolve(nodeModulesPath, subModuleName), moduleMap); - } - } - } - else { - await fs.remove(modulePath); - } - } - async collectKeptModules({ relativePaths = false }) { - const modules = await this.walker.walkTree(); - const moduleMap = new Map(); - const rootPath = path.resolve(this.walker.getRootModule()); - for (const module of modules) { - if (this.shouldKeepModule(module)) { - let modulePath = module.path; - if (relativePaths) { - modulePath = modulePath.replace(`${rootPath}${path.sep}`, ''); - } - moduleMap.set(modulePath, module); - } - } - return moduleMap; - } - async destroy() { - await this.destroyModule(this.walker.getRootModule(), await this.collectKeptModules({ relativePaths: false })); - } - shouldKeepModule(module) { - const isDevDep = module.depType === flora_colossus_1.DepType.DEV || module.depType === flora_colossus_1.DepType.DEV_OPTIONAL; - const shouldKeep = this.shouldKeepFn ? this.shouldKeepFn(module, isDevDep) : !isDevDep; - return shouldKeep; - } -} -exports.DestroyerOfModules = DestroyerOfModules; -//# sourceMappingURL=DestroyerOfModules.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/galactus/lib/index.js b/claude-code-source/node_modules/galactus/lib/index.js deleted file mode 100644 index 4727d1c5..00000000 --- a/claude-code-source/node_modules/galactus/lib/index.js +++ /dev/null @@ -1,19 +0,0 @@ -"use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -__exportStar(require("./DestroyerOfModules"), exports); -__exportStar(require("flora-colossus"), exports); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/copy/copy-sync.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/copy/copy-sync.js deleted file mode 100644 index 551abe0c..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/copy/copy-sync.js +++ /dev/null @@ -1,169 +0,0 @@ -'use strict' - -const fs = require('graceful-fs') -const path = require('path') -const mkdirsSync = require('../mkdirs').mkdirsSync -const utimesMillisSync = require('../util/utimes').utimesMillisSync -const stat = require('../util/stat') - -function copySync (src, dest, opts) { - if (typeof opts === 'function') { - opts = { filter: opts } - } - - opts = opts || {} - opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now - opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber - - // Warn about using preserveTimestamps on 32-bit node - if (opts.preserveTimestamps && process.arch === 'ia32') { - process.emitWarning( - 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' + - '\tsee https://github.com/jprichardson/node-fs-extra/issues/269', - 'Warning', 'fs-extra-WARN0002' - ) - } - - const { srcStat, destStat } = stat.checkPathsSync(src, dest, 'copy', opts) - stat.checkParentPathsSync(src, srcStat, dest, 'copy') - return handleFilterAndCopy(destStat, src, dest, opts) -} - -function handleFilterAndCopy (destStat, src, dest, opts) { - if (opts.filter && !opts.filter(src, dest)) return - const destParent = path.dirname(dest) - if (!fs.existsSync(destParent)) mkdirsSync(destParent) - return getStats(destStat, src, dest, opts) -} - -function startCopy (destStat, src, dest, opts) { - if (opts.filter && !opts.filter(src, dest)) return - return getStats(destStat, src, dest, opts) -} - -function getStats (destStat, src, dest, opts) { - const statSync = opts.dereference ? fs.statSync : fs.lstatSync - const srcStat = statSync(src) - - if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts) - else if (srcStat.isFile() || - srcStat.isCharacterDevice() || - srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts) - else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts) - else if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`) - else if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`) - throw new Error(`Unknown file: ${src}`) -} - -function onFile (srcStat, destStat, src, dest, opts) { - if (!destStat) return copyFile(srcStat, src, dest, opts) - return mayCopyFile(srcStat, src, dest, opts) -} - -function mayCopyFile (srcStat, src, dest, opts) { - if (opts.overwrite) { - fs.unlinkSync(dest) - return copyFile(srcStat, src, dest, opts) - } else if (opts.errorOnExist) { - throw new Error(`'${dest}' already exists`) - } -} - -function copyFile (srcStat, src, dest, opts) { - fs.copyFileSync(src, dest) - if (opts.preserveTimestamps) handleTimestamps(srcStat.mode, src, dest) - return setDestMode(dest, srcStat.mode) -} - -function handleTimestamps (srcMode, src, dest) { - // Make sure the file is writable before setting the timestamp - // otherwise open fails with EPERM when invoked with 'r+' - // (through utimes call) - if (fileIsNotWritable(srcMode)) makeFileWritable(dest, srcMode) - return setDestTimestamps(src, dest) -} - -function fileIsNotWritable (srcMode) { - return (srcMode & 0o200) === 0 -} - -function makeFileWritable (dest, srcMode) { - return setDestMode(dest, srcMode | 0o200) -} - -function setDestMode (dest, srcMode) { - return fs.chmodSync(dest, srcMode) -} - -function setDestTimestamps (src, dest) { - // The initial srcStat.atime cannot be trusted - // because it is modified by the read(2) system call - // (See https://nodejs.org/api/fs.html#fs_stat_time_values) - const updatedSrcStat = fs.statSync(src) - return utimesMillisSync(dest, updatedSrcStat.atime, updatedSrcStat.mtime) -} - -function onDir (srcStat, destStat, src, dest, opts) { - if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts) - return copyDir(src, dest, opts) -} - -function mkDirAndCopy (srcMode, src, dest, opts) { - fs.mkdirSync(dest) - copyDir(src, dest, opts) - return setDestMode(dest, srcMode) -} - -function copyDir (src, dest, opts) { - fs.readdirSync(src).forEach(item => copyDirItem(item, src, dest, opts)) -} - -function copyDirItem (item, src, dest, opts) { - const srcItem = path.join(src, item) - const destItem = path.join(dest, item) - const { destStat } = stat.checkPathsSync(srcItem, destItem, 'copy', opts) - return startCopy(destStat, srcItem, destItem, opts) -} - -function onLink (destStat, src, dest, opts) { - let resolvedSrc = fs.readlinkSync(src) - if (opts.dereference) { - resolvedSrc = path.resolve(process.cwd(), resolvedSrc) - } - - if (!destStat) { - return fs.symlinkSync(resolvedSrc, dest) - } else { - let resolvedDest - try { - resolvedDest = fs.readlinkSync(dest) - } catch (err) { - // dest exists and is a regular file or directory, - // Windows may throw UNKNOWN error. If dest already exists, - // fs throws error anyway, so no need to guard against it here. - if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlinkSync(resolvedSrc, dest) - throw err - } - if (opts.dereference) { - resolvedDest = path.resolve(process.cwd(), resolvedDest) - } - if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { - throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`) - } - - // prevent copy if src is a subdir of dest since unlinking - // dest in this case would result in removing src contents - // and therefore a broken symlink would be created. - if (fs.statSync(dest).isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { - throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`) - } - return copyLink(resolvedSrc, dest) - } -} - -function copyLink (resolvedSrc, dest) { - fs.unlinkSync(dest) - return fs.symlinkSync(resolvedSrc, dest) -} - -module.exports = copySync diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/copy/copy.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/copy/copy.js deleted file mode 100644 index 09d53dfd..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/copy/copy.js +++ /dev/null @@ -1,235 +0,0 @@ -'use strict' - -const fs = require('graceful-fs') -const path = require('path') -const mkdirs = require('../mkdirs').mkdirs -const pathExists = require('../path-exists').pathExists -const utimesMillis = require('../util/utimes').utimesMillis -const stat = require('../util/stat') - -function copy (src, dest, opts, cb) { - if (typeof opts === 'function' && !cb) { - cb = opts - opts = {} - } else if (typeof opts === 'function') { - opts = { filter: opts } - } - - cb = cb || function () {} - opts = opts || {} - - opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now - opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber - - // Warn about using preserveTimestamps on 32-bit node - if (opts.preserveTimestamps && process.arch === 'ia32') { - process.emitWarning( - 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' + - '\tsee https://github.com/jprichardson/node-fs-extra/issues/269', - 'Warning', 'fs-extra-WARN0001' - ) - } - - stat.checkPaths(src, dest, 'copy', opts, (err, stats) => { - if (err) return cb(err) - const { srcStat, destStat } = stats - stat.checkParentPaths(src, srcStat, dest, 'copy', err => { - if (err) return cb(err) - if (opts.filter) return handleFilter(checkParentDir, destStat, src, dest, opts, cb) - return checkParentDir(destStat, src, dest, opts, cb) - }) - }) -} - -function checkParentDir (destStat, src, dest, opts, cb) { - const destParent = path.dirname(dest) - pathExists(destParent, (err, dirExists) => { - if (err) return cb(err) - if (dirExists) return getStats(destStat, src, dest, opts, cb) - mkdirs(destParent, err => { - if (err) return cb(err) - return getStats(destStat, src, dest, opts, cb) - }) - }) -} - -function handleFilter (onInclude, destStat, src, dest, opts, cb) { - Promise.resolve(opts.filter(src, dest)).then(include => { - if (include) return onInclude(destStat, src, dest, opts, cb) - return cb() - }, error => cb(error)) -} - -function startCopy (destStat, src, dest, opts, cb) { - if (opts.filter) return handleFilter(getStats, destStat, src, dest, opts, cb) - return getStats(destStat, src, dest, opts, cb) -} - -function getStats (destStat, src, dest, opts, cb) { - const stat = opts.dereference ? fs.stat : fs.lstat - stat(src, (err, srcStat) => { - if (err) return cb(err) - - if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts, cb) - else if (srcStat.isFile() || - srcStat.isCharacterDevice() || - srcStat.isBlockDevice()) return onFile(srcStat, destStat, src, dest, opts, cb) - else if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts, cb) - else if (srcStat.isSocket()) return cb(new Error(`Cannot copy a socket file: ${src}`)) - else if (srcStat.isFIFO()) return cb(new Error(`Cannot copy a FIFO pipe: ${src}`)) - return cb(new Error(`Unknown file: ${src}`)) - }) -} - -function onFile (srcStat, destStat, src, dest, opts, cb) { - if (!destStat) return copyFile(srcStat, src, dest, opts, cb) - return mayCopyFile(srcStat, src, dest, opts, cb) -} - -function mayCopyFile (srcStat, src, dest, opts, cb) { - if (opts.overwrite) { - fs.unlink(dest, err => { - if (err) return cb(err) - return copyFile(srcStat, src, dest, opts, cb) - }) - } else if (opts.errorOnExist) { - return cb(new Error(`'${dest}' already exists`)) - } else return cb() -} - -function copyFile (srcStat, src, dest, opts, cb) { - fs.copyFile(src, dest, err => { - if (err) return cb(err) - if (opts.preserveTimestamps) return handleTimestampsAndMode(srcStat.mode, src, dest, cb) - return setDestMode(dest, srcStat.mode, cb) - }) -} - -function handleTimestampsAndMode (srcMode, src, dest, cb) { - // Make sure the file is writable before setting the timestamp - // otherwise open fails with EPERM when invoked with 'r+' - // (through utimes call) - if (fileIsNotWritable(srcMode)) { - return makeFileWritable(dest, srcMode, err => { - if (err) return cb(err) - return setDestTimestampsAndMode(srcMode, src, dest, cb) - }) - } - return setDestTimestampsAndMode(srcMode, src, dest, cb) -} - -function fileIsNotWritable (srcMode) { - return (srcMode & 0o200) === 0 -} - -function makeFileWritable (dest, srcMode, cb) { - return setDestMode(dest, srcMode | 0o200, cb) -} - -function setDestTimestampsAndMode (srcMode, src, dest, cb) { - setDestTimestamps(src, dest, err => { - if (err) return cb(err) - return setDestMode(dest, srcMode, cb) - }) -} - -function setDestMode (dest, srcMode, cb) { - return fs.chmod(dest, srcMode, cb) -} - -function setDestTimestamps (src, dest, cb) { - // The initial srcStat.atime cannot be trusted - // because it is modified by the read(2) system call - // (See https://nodejs.org/api/fs.html#fs_stat_time_values) - fs.stat(src, (err, updatedSrcStat) => { - if (err) return cb(err) - return utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime, cb) - }) -} - -function onDir (srcStat, destStat, src, dest, opts, cb) { - if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts, cb) - return copyDir(src, dest, opts, cb) -} - -function mkDirAndCopy (srcMode, src, dest, opts, cb) { - fs.mkdir(dest, err => { - if (err) return cb(err) - copyDir(src, dest, opts, err => { - if (err) return cb(err) - return setDestMode(dest, srcMode, cb) - }) - }) -} - -function copyDir (src, dest, opts, cb) { - fs.readdir(src, (err, items) => { - if (err) return cb(err) - return copyDirItems(items, src, dest, opts, cb) - }) -} - -function copyDirItems (items, src, dest, opts, cb) { - const item = items.pop() - if (!item) return cb() - return copyDirItem(items, item, src, dest, opts, cb) -} - -function copyDirItem (items, item, src, dest, opts, cb) { - const srcItem = path.join(src, item) - const destItem = path.join(dest, item) - stat.checkPaths(srcItem, destItem, 'copy', opts, (err, stats) => { - if (err) return cb(err) - const { destStat } = stats - startCopy(destStat, srcItem, destItem, opts, err => { - if (err) return cb(err) - return copyDirItems(items, src, dest, opts, cb) - }) - }) -} - -function onLink (destStat, src, dest, opts, cb) { - fs.readlink(src, (err, resolvedSrc) => { - if (err) return cb(err) - if (opts.dereference) { - resolvedSrc = path.resolve(process.cwd(), resolvedSrc) - } - - if (!destStat) { - return fs.symlink(resolvedSrc, dest, cb) - } else { - fs.readlink(dest, (err, resolvedDest) => { - if (err) { - // dest exists and is a regular file or directory, - // Windows may throw UNKNOWN error. If dest already exists, - // fs throws error anyway, so no need to guard against it here. - if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest, cb) - return cb(err) - } - if (opts.dereference) { - resolvedDest = path.resolve(process.cwd(), resolvedDest) - } - if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) { - return cb(new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)) - } - - // do not copy if src is a subdir of dest since unlinking - // dest in this case would result in removing src contents - // and therefore a broken symlink would be created. - if (destStat.isDirectory() && stat.isSrcSubdir(resolvedDest, resolvedSrc)) { - return cb(new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)) - } - return copyLink(resolvedSrc, dest, cb) - }) - } - }) -} - -function copyLink (resolvedSrc, dest, cb) { - fs.unlink(dest, err => { - if (err) return cb(err) - return fs.symlink(resolvedSrc, dest, cb) - }) -} - -module.exports = copy diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/copy/index.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/copy/index.js deleted file mode 100644 index 45c07a2f..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/copy/index.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict' - -const u = require('universalify').fromCallback -module.exports = { - copy: u(require('./copy')), - copySync: require('./copy-sync') -} diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/empty/index.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/empty/index.js deleted file mode 100644 index b4a2e823..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/empty/index.js +++ /dev/null @@ -1,39 +0,0 @@ -'use strict' - -const u = require('universalify').fromPromise -const fs = require('../fs') -const path = require('path') -const mkdir = require('../mkdirs') -const remove = require('../remove') - -const emptyDir = u(async function emptyDir (dir) { - let items - try { - items = await fs.readdir(dir) - } catch { - return mkdir.mkdirs(dir) - } - - return Promise.all(items.map(item => remove.remove(path.join(dir, item)))) -}) - -function emptyDirSync (dir) { - let items - try { - items = fs.readdirSync(dir) - } catch { - return mkdir.mkdirsSync(dir) - } - - items.forEach(item => { - item = path.join(dir, item) - remove.removeSync(item) - }) -} - -module.exports = { - emptyDirSync, - emptydirSync: emptyDirSync, - emptyDir, - emptydir: emptyDir -} diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/ensure/file.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/ensure/file.js deleted file mode 100644 index 15cc473c..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/ensure/file.js +++ /dev/null @@ -1,69 +0,0 @@ -'use strict' - -const u = require('universalify').fromCallback -const path = require('path') -const fs = require('graceful-fs') -const mkdir = require('../mkdirs') - -function createFile (file, callback) { - function makeFile () { - fs.writeFile(file, '', err => { - if (err) return callback(err) - callback() - }) - } - - fs.stat(file, (err, stats) => { // eslint-disable-line handle-callback-err - if (!err && stats.isFile()) return callback() - const dir = path.dirname(file) - fs.stat(dir, (err, stats) => { - if (err) { - // if the directory doesn't exist, make it - if (err.code === 'ENOENT') { - return mkdir.mkdirs(dir, err => { - if (err) return callback(err) - makeFile() - }) - } - return callback(err) - } - - if (stats.isDirectory()) makeFile() - else { - // parent is not a directory - // This is just to cause an internal ENOTDIR error to be thrown - fs.readdir(dir, err => { - if (err) return callback(err) - }) - } - }) - }) -} - -function createFileSync (file) { - let stats - try { - stats = fs.statSync(file) - } catch {} - if (stats && stats.isFile()) return - - const dir = path.dirname(file) - try { - if (!fs.statSync(dir).isDirectory()) { - // parent is not a directory - // This is just to cause an internal ENOTDIR error to be thrown - fs.readdirSync(dir) - } - } catch (err) { - // If the stat call above failed because the directory doesn't exist, create it - if (err && err.code === 'ENOENT') mkdir.mkdirsSync(dir) - else throw err - } - - fs.writeFileSync(file, '') -} - -module.exports = { - createFile: u(createFile), - createFileSync -} diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/ensure/index.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/ensure/index.js deleted file mode 100644 index ecbcdd0b..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/ensure/index.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict' - -const { createFile, createFileSync } = require('./file') -const { createLink, createLinkSync } = require('./link') -const { createSymlink, createSymlinkSync } = require('./symlink') - -module.exports = { - // file - createFile, - createFileSync, - ensureFile: createFile, - ensureFileSync: createFileSync, - // link - createLink, - createLinkSync, - ensureLink: createLink, - ensureLinkSync: createLinkSync, - // symlink - createSymlink, - createSymlinkSync, - ensureSymlink: createSymlink, - ensureSymlinkSync: createSymlinkSync -} diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/ensure/link.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/ensure/link.js deleted file mode 100644 index f6d67486..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/ensure/link.js +++ /dev/null @@ -1,64 +0,0 @@ -'use strict' - -const u = require('universalify').fromCallback -const path = require('path') -const fs = require('graceful-fs') -const mkdir = require('../mkdirs') -const pathExists = require('../path-exists').pathExists -const { areIdentical } = require('../util/stat') - -function createLink (srcpath, dstpath, callback) { - function makeLink (srcpath, dstpath) { - fs.link(srcpath, dstpath, err => { - if (err) return callback(err) - callback(null) - }) - } - - fs.lstat(dstpath, (_, dstStat) => { - fs.lstat(srcpath, (err, srcStat) => { - if (err) { - err.message = err.message.replace('lstat', 'ensureLink') - return callback(err) - } - if (dstStat && areIdentical(srcStat, dstStat)) return callback(null) - - const dir = path.dirname(dstpath) - pathExists(dir, (err, dirExists) => { - if (err) return callback(err) - if (dirExists) return makeLink(srcpath, dstpath) - mkdir.mkdirs(dir, err => { - if (err) return callback(err) - makeLink(srcpath, dstpath) - }) - }) - }) - }) -} - -function createLinkSync (srcpath, dstpath) { - let dstStat - try { - dstStat = fs.lstatSync(dstpath) - } catch {} - - try { - const srcStat = fs.lstatSync(srcpath) - if (dstStat && areIdentical(srcStat, dstStat)) return - } catch (err) { - err.message = err.message.replace('lstat', 'ensureLink') - throw err - } - - const dir = path.dirname(dstpath) - const dirExists = fs.existsSync(dir) - if (dirExists) return fs.linkSync(srcpath, dstpath) - mkdir.mkdirsSync(dir) - - return fs.linkSync(srcpath, dstpath) -} - -module.exports = { - createLink: u(createLink), - createLinkSync -} diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/ensure/symlink-paths.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/ensure/symlink-paths.js deleted file mode 100644 index 33cd7600..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/ensure/symlink-paths.js +++ /dev/null @@ -1,99 +0,0 @@ -'use strict' - -const path = require('path') -const fs = require('graceful-fs') -const pathExists = require('../path-exists').pathExists - -/** - * Function that returns two types of paths, one relative to symlink, and one - * relative to the current working directory. Checks if path is absolute or - * relative. If the path is relative, this function checks if the path is - * relative to symlink or relative to current working directory. This is an - * initiative to find a smarter `srcpath` to supply when building symlinks. - * This allows you to determine which path to use out of one of three possible - * types of source paths. The first is an absolute path. This is detected by - * `path.isAbsolute()`. When an absolute path is provided, it is checked to - * see if it exists. If it does it's used, if not an error is returned - * (callback)/ thrown (sync). The other two options for `srcpath` are a - * relative url. By default Node's `fs.symlink` works by creating a symlink - * using `dstpath` and expects the `srcpath` to be relative to the newly - * created symlink. If you provide a `srcpath` that does not exist on the file - * system it results in a broken symlink. To minimize this, the function - * checks to see if the 'relative to symlink' source file exists, and if it - * does it will use it. If it does not, it checks if there's a file that - * exists that is relative to the current working directory, if does its used. - * This preserves the expectations of the original fs.symlink spec and adds - * the ability to pass in `relative to current working direcotry` paths. - */ - -function symlinkPaths (srcpath, dstpath, callback) { - if (path.isAbsolute(srcpath)) { - return fs.lstat(srcpath, (err) => { - if (err) { - err.message = err.message.replace('lstat', 'ensureSymlink') - return callback(err) - } - return callback(null, { - toCwd: srcpath, - toDst: srcpath - }) - }) - } else { - const dstdir = path.dirname(dstpath) - const relativeToDst = path.join(dstdir, srcpath) - return pathExists(relativeToDst, (err, exists) => { - if (err) return callback(err) - if (exists) { - return callback(null, { - toCwd: relativeToDst, - toDst: srcpath - }) - } else { - return fs.lstat(srcpath, (err) => { - if (err) { - err.message = err.message.replace('lstat', 'ensureSymlink') - return callback(err) - } - return callback(null, { - toCwd: srcpath, - toDst: path.relative(dstdir, srcpath) - }) - }) - } - }) - } -} - -function symlinkPathsSync (srcpath, dstpath) { - let exists - if (path.isAbsolute(srcpath)) { - exists = fs.existsSync(srcpath) - if (!exists) throw new Error('absolute srcpath does not exist') - return { - toCwd: srcpath, - toDst: srcpath - } - } else { - const dstdir = path.dirname(dstpath) - const relativeToDst = path.join(dstdir, srcpath) - exists = fs.existsSync(relativeToDst) - if (exists) { - return { - toCwd: relativeToDst, - toDst: srcpath - } - } else { - exists = fs.existsSync(srcpath) - if (!exists) throw new Error('relative srcpath does not exist') - return { - toCwd: srcpath, - toDst: path.relative(dstdir, srcpath) - } - } - } -} - -module.exports = { - symlinkPaths, - symlinkPathsSync -} diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/ensure/symlink-type.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/ensure/symlink-type.js deleted file mode 100644 index 42dc0ce7..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/ensure/symlink-type.js +++ /dev/null @@ -1,31 +0,0 @@ -'use strict' - -const fs = require('graceful-fs') - -function symlinkType (srcpath, type, callback) { - callback = (typeof type === 'function') ? type : callback - type = (typeof type === 'function') ? false : type - if (type) return callback(null, type) - fs.lstat(srcpath, (err, stats) => { - if (err) return callback(null, 'file') - type = (stats && stats.isDirectory()) ? 'dir' : 'file' - callback(null, type) - }) -} - -function symlinkTypeSync (srcpath, type) { - let stats - - if (type) return type - try { - stats = fs.lstatSync(srcpath) - } catch { - return 'file' - } - return (stats && stats.isDirectory()) ? 'dir' : 'file' -} - -module.exports = { - symlinkType, - symlinkTypeSync -} diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/ensure/symlink.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/ensure/symlink.js deleted file mode 100644 index 2b93052f..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/ensure/symlink.js +++ /dev/null @@ -1,82 +0,0 @@ -'use strict' - -const u = require('universalify').fromCallback -const path = require('path') -const fs = require('../fs') -const _mkdirs = require('../mkdirs') -const mkdirs = _mkdirs.mkdirs -const mkdirsSync = _mkdirs.mkdirsSync - -const _symlinkPaths = require('./symlink-paths') -const symlinkPaths = _symlinkPaths.symlinkPaths -const symlinkPathsSync = _symlinkPaths.symlinkPathsSync - -const _symlinkType = require('./symlink-type') -const symlinkType = _symlinkType.symlinkType -const symlinkTypeSync = _symlinkType.symlinkTypeSync - -const pathExists = require('../path-exists').pathExists - -const { areIdentical } = require('../util/stat') - -function createSymlink (srcpath, dstpath, type, callback) { - callback = (typeof type === 'function') ? type : callback - type = (typeof type === 'function') ? false : type - - fs.lstat(dstpath, (err, stats) => { - if (!err && stats.isSymbolicLink()) { - Promise.all([ - fs.stat(srcpath), - fs.stat(dstpath) - ]).then(([srcStat, dstStat]) => { - if (areIdentical(srcStat, dstStat)) return callback(null) - _createSymlink(srcpath, dstpath, type, callback) - }) - } else _createSymlink(srcpath, dstpath, type, callback) - }) -} - -function _createSymlink (srcpath, dstpath, type, callback) { - symlinkPaths(srcpath, dstpath, (err, relative) => { - if (err) return callback(err) - srcpath = relative.toDst - symlinkType(relative.toCwd, type, (err, type) => { - if (err) return callback(err) - const dir = path.dirname(dstpath) - pathExists(dir, (err, dirExists) => { - if (err) return callback(err) - if (dirExists) return fs.symlink(srcpath, dstpath, type, callback) - mkdirs(dir, err => { - if (err) return callback(err) - fs.symlink(srcpath, dstpath, type, callback) - }) - }) - }) - }) -} - -function createSymlinkSync (srcpath, dstpath, type) { - let stats - try { - stats = fs.lstatSync(dstpath) - } catch {} - if (stats && stats.isSymbolicLink()) { - const srcStat = fs.statSync(srcpath) - const dstStat = fs.statSync(dstpath) - if (areIdentical(srcStat, dstStat)) return - } - - const relative = symlinkPathsSync(srcpath, dstpath) - srcpath = relative.toDst - type = symlinkTypeSync(relative.toCwd, type) - const dir = path.dirname(dstpath) - const exists = fs.existsSync(dir) - if (exists) return fs.symlinkSync(srcpath, dstpath, type) - mkdirsSync(dir) - return fs.symlinkSync(srcpath, dstpath, type) -} - -module.exports = { - createSymlink: u(createSymlink), - createSymlinkSync -} diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/fs/index.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/fs/index.js deleted file mode 100644 index 7b025e29..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/fs/index.js +++ /dev/null @@ -1,128 +0,0 @@ -'use strict' -// This is adapted from https://github.com/normalize/mz -// Copyright (c) 2014-2016 Jonathan Ong me@jongleberry.com and Contributors -const u = require('universalify').fromCallback -const fs = require('graceful-fs') - -const api = [ - 'access', - 'appendFile', - 'chmod', - 'chown', - 'close', - 'copyFile', - 'fchmod', - 'fchown', - 'fdatasync', - 'fstat', - 'fsync', - 'ftruncate', - 'futimes', - 'lchmod', - 'lchown', - 'link', - 'lstat', - 'mkdir', - 'mkdtemp', - 'open', - 'opendir', - 'readdir', - 'readFile', - 'readlink', - 'realpath', - 'rename', - 'rm', - 'rmdir', - 'stat', - 'symlink', - 'truncate', - 'unlink', - 'utimes', - 'writeFile' -].filter(key => { - // Some commands are not available on some systems. Ex: - // fs.opendir was added in Node.js v12.12.0 - // fs.rm was added in Node.js v14.14.0 - // fs.lchown is not available on at least some Linux - return typeof fs[key] === 'function' -}) - -// Export cloned fs: -Object.assign(exports, fs) - -// Universalify async methods: -api.forEach(method => { - exports[method] = u(fs[method]) -}) - -// We differ from mz/fs in that we still ship the old, broken, fs.exists() -// since we are a drop-in replacement for the native module -exports.exists = function (filename, callback) { - if (typeof callback === 'function') { - return fs.exists(filename, callback) - } - return new Promise(resolve => { - return fs.exists(filename, resolve) - }) -} - -// fs.read(), fs.write(), & fs.writev() need special treatment due to multiple callback args - -exports.read = function (fd, buffer, offset, length, position, callback) { - if (typeof callback === 'function') { - return fs.read(fd, buffer, offset, length, position, callback) - } - return new Promise((resolve, reject) => { - fs.read(fd, buffer, offset, length, position, (err, bytesRead, buffer) => { - if (err) return reject(err) - resolve({ bytesRead, buffer }) - }) - }) -} - -// Function signature can be -// fs.write(fd, buffer[, offset[, length[, position]]], callback) -// OR -// fs.write(fd, string[, position[, encoding]], callback) -// We need to handle both cases, so we use ...args -exports.write = function (fd, buffer, ...args) { - if (typeof args[args.length - 1] === 'function') { - return fs.write(fd, buffer, ...args) - } - - return new Promise((resolve, reject) => { - fs.write(fd, buffer, ...args, (err, bytesWritten, buffer) => { - if (err) return reject(err) - resolve({ bytesWritten, buffer }) - }) - }) -} - -// fs.writev only available in Node v12.9.0+ -if (typeof fs.writev === 'function') { - // Function signature is - // s.writev(fd, buffers[, position], callback) - // We need to handle the optional arg, so we use ...args - exports.writev = function (fd, buffers, ...args) { - if (typeof args[args.length - 1] === 'function') { - return fs.writev(fd, buffers, ...args) - } - - return new Promise((resolve, reject) => { - fs.writev(fd, buffers, ...args, (err, bytesWritten, buffers) => { - if (err) return reject(err) - resolve({ bytesWritten, buffers }) - }) - }) - } -} - -// fs.realpath.native sometimes not available if fs is monkey-patched -if (typeof fs.realpath.native === 'function') { - exports.realpath.native = u(fs.realpath.native) -} else { - process.emitWarning( - 'fs.realpath.native is not a function. Is fs being monkey-patched?', - 'Warning', 'fs-extra-WARN0003' - ) -} diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/index.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/index.js deleted file mode 100644 index da6711a4..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/index.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict' - -module.exports = { - // Export promiseified graceful-fs: - ...require('./fs'), - // Export extra methods: - ...require('./copy'), - ...require('./empty'), - ...require('./ensure'), - ...require('./json'), - ...require('./mkdirs'), - ...require('./move'), - ...require('./output-file'), - ...require('./path-exists'), - ...require('./remove') -} diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/json/index.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/json/index.js deleted file mode 100644 index 900126ad..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/json/index.js +++ /dev/null @@ -1,16 +0,0 @@ -'use strict' - -const u = require('universalify').fromPromise -const jsonFile = require('./jsonfile') - -jsonFile.outputJson = u(require('./output-json')) -jsonFile.outputJsonSync = require('./output-json-sync') -// aliases -jsonFile.outputJSON = jsonFile.outputJson -jsonFile.outputJSONSync = jsonFile.outputJsonSync -jsonFile.writeJSON = jsonFile.writeJson -jsonFile.writeJSONSync = jsonFile.writeJsonSync -jsonFile.readJSON = jsonFile.readJson -jsonFile.readJSONSync = jsonFile.readJsonSync - -module.exports = jsonFile diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/json/jsonfile.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/json/jsonfile.js deleted file mode 100644 index f11d34d6..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/json/jsonfile.js +++ /dev/null @@ -1,11 +0,0 @@ -'use strict' - -const jsonFile = require('jsonfile') - -module.exports = { - // jsonfile exports - readJson: jsonFile.readFile, - readJsonSync: jsonFile.readFileSync, - writeJson: jsonFile.writeFile, - writeJsonSync: jsonFile.writeFileSync -} diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/json/output-json-sync.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/json/output-json-sync.js deleted file mode 100644 index d4e564f2..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/json/output-json-sync.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict' - -const { stringify } = require('jsonfile/utils') -const { outputFileSync } = require('../output-file') - -function outputJsonSync (file, data, options) { - const str = stringify(data, options) - - outputFileSync(file, str, options) -} - -module.exports = outputJsonSync diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/json/output-json.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/json/output-json.js deleted file mode 100644 index 0afdeb63..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/json/output-json.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict' - -const { stringify } = require('jsonfile/utils') -const { outputFile } = require('../output-file') - -async function outputJson (file, data, options = {}) { - const str = stringify(data, options) - - await outputFile(file, str, options) -} - -module.exports = outputJson diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/mkdirs/index.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/mkdirs/index.js deleted file mode 100644 index 9edecee0..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/mkdirs/index.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict' -const u = require('universalify').fromPromise -const { makeDir: _makeDir, makeDirSync } = require('./make-dir') -const makeDir = u(_makeDir) - -module.exports = { - mkdirs: makeDir, - mkdirsSync: makeDirSync, - // alias - mkdirp: makeDir, - mkdirpSync: makeDirSync, - ensureDir: makeDir, - ensureDirSync: makeDirSync -} diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/mkdirs/make-dir.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/mkdirs/make-dir.js deleted file mode 100644 index 45ece64d..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/mkdirs/make-dir.js +++ /dev/null @@ -1,27 +0,0 @@ -'use strict' -const fs = require('../fs') -const { checkPath } = require('./utils') - -const getMode = options => { - const defaults = { mode: 0o777 } - if (typeof options === 'number') return options - return ({ ...defaults, ...options }).mode -} - -module.exports.makeDir = async (dir, options) => { - checkPath(dir) - - return fs.mkdir(dir, { - mode: getMode(options), - recursive: true - }) -} - -module.exports.makeDirSync = (dir, options) => { - checkPath(dir) - - return fs.mkdirSync(dir, { - mode: getMode(options), - recursive: true - }) -} diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/mkdirs/utils.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/mkdirs/utils.js deleted file mode 100644 index a4059ad4..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/mkdirs/utils.js +++ /dev/null @@ -1,21 +0,0 @@ -// Adapted from https://github.com/sindresorhus/make-dir -// Copyright (c) Sindre Sorhus (sindresorhus.com) -// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -'use strict' -const path = require('path') - -// https://github.com/nodejs/node/issues/8987 -// https://github.com/libuv/libuv/pull/1088 -module.exports.checkPath = function checkPath (pth) { - if (process.platform === 'win32') { - const pathHasInvalidWinCharacters = /[<>:"|?*]/.test(pth.replace(path.parse(pth).root, '')) - - if (pathHasInvalidWinCharacters) { - const error = new Error(`Path contains invalid characters: ${pth}`) - error.code = 'EINVAL' - throw error - } - } -} diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/move/index.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/move/index.js deleted file mode 100644 index fcee73c4..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/move/index.js +++ /dev/null @@ -1,7 +0,0 @@ -'use strict' - -const u = require('universalify').fromCallback -module.exports = { - move: u(require('./move')), - moveSync: require('./move-sync') -} diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/move/move-sync.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/move/move-sync.js deleted file mode 100644 index 84533664..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/move/move-sync.js +++ /dev/null @@ -1,54 +0,0 @@ -'use strict' - -const fs = require('graceful-fs') -const path = require('path') -const copySync = require('../copy').copySync -const removeSync = require('../remove').removeSync -const mkdirpSync = require('../mkdirs').mkdirpSync -const stat = require('../util/stat') - -function moveSync (src, dest, opts) { - opts = opts || {} - const overwrite = opts.overwrite || opts.clobber || false - - const { srcStat, isChangingCase = false } = stat.checkPathsSync(src, dest, 'move', opts) - stat.checkParentPathsSync(src, srcStat, dest, 'move') - if (!isParentRoot(dest)) mkdirpSync(path.dirname(dest)) - return doRename(src, dest, overwrite, isChangingCase) -} - -function isParentRoot (dest) { - const parent = path.dirname(dest) - const parsedPath = path.parse(parent) - return parsedPath.root === parent -} - -function doRename (src, dest, overwrite, isChangingCase) { - if (isChangingCase) return rename(src, dest, overwrite) - if (overwrite) { - removeSync(dest) - return rename(src, dest, overwrite) - } - if (fs.existsSync(dest)) throw new Error('dest already exists.') - return rename(src, dest, overwrite) -} - -function rename (src, dest, overwrite) { - try { - fs.renameSync(src, dest) - } catch (err) { - if (err.code !== 'EXDEV') throw err - return moveAcrossDevice(src, dest, overwrite) - } -} - -function moveAcrossDevice (src, dest, overwrite) { - const opts = { - overwrite, - errorOnExist: true - } - copySync(src, dest, opts) - return removeSync(src) -} - -module.exports = moveSync diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/move/move.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/move/move.js deleted file mode 100644 index 7dc6ecd1..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/move/move.js +++ /dev/null @@ -1,75 +0,0 @@ -'use strict' - -const fs = require('graceful-fs') -const path = require('path') -const copy = require('../copy').copy -const remove = require('../remove').remove -const mkdirp = require('../mkdirs').mkdirp -const pathExists = require('../path-exists').pathExists -const stat = require('../util/stat') - -function move (src, dest, opts, cb) { - if (typeof opts === 'function') { - cb = opts - opts = {} - } - - opts = opts || {} - - const overwrite = opts.overwrite || opts.clobber || false - - stat.checkPaths(src, dest, 'move', opts, (err, stats) => { - if (err) return cb(err) - const { srcStat, isChangingCase = false } = stats - stat.checkParentPaths(src, srcStat, dest, 'move', err => { - if (err) return cb(err) - if (isParentRoot(dest)) return doRename(src, dest, overwrite, isChangingCase, cb) - mkdirp(path.dirname(dest), err => { - if (err) return cb(err) - return doRename(src, dest, overwrite, isChangingCase, cb) - }) - }) - }) -} - -function isParentRoot (dest) { - const parent = path.dirname(dest) - const parsedPath = path.parse(parent) - return parsedPath.root === parent -} - -function doRename (src, dest, overwrite, isChangingCase, cb) { - if (isChangingCase) return rename(src, dest, overwrite, cb) - if (overwrite) { - return remove(dest, err => { - if (err) return cb(err) - return rename(src, dest, overwrite, cb) - }) - } - pathExists(dest, (err, destExists) => { - if (err) return cb(err) - if (destExists) return cb(new Error('dest already exists.')) - return rename(src, dest, overwrite, cb) - }) -} - -function rename (src, dest, overwrite, cb) { - fs.rename(src, dest, err => { - if (!err) return cb() - if (err.code !== 'EXDEV') return cb(err) - return moveAcrossDevice(src, dest, overwrite, cb) - }) -} - -function moveAcrossDevice (src, dest, overwrite, cb) { - const opts = { - overwrite, - errorOnExist: true - } - copy(src, dest, opts, err => { - if (err) return cb(err) - return remove(src, cb) - }) -} - -module.exports = move diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/output-file/index.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/output-file/index.js deleted file mode 100644 index 92297ca3..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/output-file/index.js +++ /dev/null @@ -1,40 +0,0 @@ -'use strict' - -const u = require('universalify').fromCallback -const fs = require('graceful-fs') -const path = require('path') -const mkdir = require('../mkdirs') -const pathExists = require('../path-exists').pathExists - -function outputFile (file, data, encoding, callback) { - if (typeof encoding === 'function') { - callback = encoding - encoding = 'utf8' - } - - const dir = path.dirname(file) - pathExists(dir, (err, itDoes) => { - if (err) return callback(err) - if (itDoes) return fs.writeFile(file, data, encoding, callback) - - mkdir.mkdirs(dir, err => { - if (err) return callback(err) - - fs.writeFile(file, data, encoding, callback) - }) - }) -} - -function outputFileSync (file, ...args) { - const dir = path.dirname(file) - if (fs.existsSync(dir)) { - return fs.writeFileSync(file, ...args) - } - mkdir.mkdirsSync(dir) - fs.writeFileSync(file, ...args) -} - -module.exports = { - outputFile: u(outputFile), - outputFileSync -} diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/path-exists/index.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/path-exists/index.js deleted file mode 100644 index ddd9bc71..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/path-exists/index.js +++ /dev/null @@ -1,12 +0,0 @@ -'use strict' -const u = require('universalify').fromPromise -const fs = require('../fs') - -function pathExists (path) { - return fs.access(path).then(() => true).catch(() => false) -} - -module.exports = { - pathExists: u(pathExists), - pathExistsSync: fs.existsSync -} diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/remove/index.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/remove/index.js deleted file mode 100644 index 4428e59a..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/remove/index.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict' - -const fs = require('graceful-fs') -const u = require('universalify').fromCallback -const rimraf = require('./rimraf') - -function remove (path, callback) { - // Node 14.14.0+ - if (fs.rm) return fs.rm(path, { recursive: true, force: true }, callback) - rimraf(path, callback) -} - -function removeSync (path) { - // Node 14.14.0+ - if (fs.rmSync) return fs.rmSync(path, { recursive: true, force: true }) - rimraf.sync(path) -} - -module.exports = { - remove: u(remove), - removeSync -} diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/remove/rimraf.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/remove/rimraf.js deleted file mode 100644 index 2c771026..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/remove/rimraf.js +++ /dev/null @@ -1,302 +0,0 @@ -'use strict' - -const fs = require('graceful-fs') -const path = require('path') -const assert = require('assert') - -const isWindows = (process.platform === 'win32') - -function defaults (options) { - const methods = [ - 'unlink', - 'chmod', - 'stat', - 'lstat', - 'rmdir', - 'readdir' - ] - methods.forEach(m => { - options[m] = options[m] || fs[m] - m = m + 'Sync' - options[m] = options[m] || fs[m] - }) - - options.maxBusyTries = options.maxBusyTries || 3 -} - -function rimraf (p, options, cb) { - let busyTries = 0 - - if (typeof options === 'function') { - cb = options - options = {} - } - - assert(p, 'rimraf: missing path') - assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string') - assert.strictEqual(typeof cb, 'function', 'rimraf: callback function required') - assert(options, 'rimraf: invalid options argument provided') - assert.strictEqual(typeof options, 'object', 'rimraf: options should be object') - - defaults(options) - - rimraf_(p, options, function CB (er) { - if (er) { - if ((er.code === 'EBUSY' || er.code === 'ENOTEMPTY' || er.code === 'EPERM') && - busyTries < options.maxBusyTries) { - busyTries++ - const time = busyTries * 100 - // try again, with the same exact callback as this one. - return setTimeout(() => rimraf_(p, options, CB), time) - } - - // already gone - if (er.code === 'ENOENT') er = null - } - - cb(er) - }) -} - -// Two possible strategies. -// 1. Assume it's a file. unlink it, then do the dir stuff on EPERM or EISDIR -// 2. Assume it's a directory. readdir, then do the file stuff on ENOTDIR -// -// Both result in an extra syscall when you guess wrong. However, there -// are likely far more normal files in the world than directories. This -// is based on the assumption that a the average number of files per -// directory is >= 1. -// -// If anyone ever complains about this, then I guess the strategy could -// be made configurable somehow. But until then, YAGNI. -function rimraf_ (p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - - // sunos lets the root user unlink directories, which is... weird. - // so we have to lstat here and make sure it's not a dir. - options.lstat(p, (er, st) => { - if (er && er.code === 'ENOENT') { - return cb(null) - } - - // Windows can EPERM on stat. Life is suffering. - if (er && er.code === 'EPERM' && isWindows) { - return fixWinEPERM(p, options, er, cb) - } - - if (st && st.isDirectory()) { - return rmdir(p, options, er, cb) - } - - options.unlink(p, er => { - if (er) { - if (er.code === 'ENOENT') { - return cb(null) - } - if (er.code === 'EPERM') { - return (isWindows) - ? fixWinEPERM(p, options, er, cb) - : rmdir(p, options, er, cb) - } - if (er.code === 'EISDIR') { - return rmdir(p, options, er, cb) - } - } - return cb(er) - }) - }) -} - -function fixWinEPERM (p, options, er, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - - options.chmod(p, 0o666, er2 => { - if (er2) { - cb(er2.code === 'ENOENT' ? null : er) - } else { - options.stat(p, (er3, stats) => { - if (er3) { - cb(er3.code === 'ENOENT' ? null : er) - } else if (stats.isDirectory()) { - rmdir(p, options, er, cb) - } else { - options.unlink(p, cb) - } - }) - } - }) -} - -function fixWinEPERMSync (p, options, er) { - let stats - - assert(p) - assert(options) - - try { - options.chmodSync(p, 0o666) - } catch (er2) { - if (er2.code === 'ENOENT') { - return - } else { - throw er - } - } - - try { - stats = options.statSync(p) - } catch (er3) { - if (er3.code === 'ENOENT') { - return - } else { - throw er - } - } - - if (stats.isDirectory()) { - rmdirSync(p, options, er) - } else { - options.unlinkSync(p) - } -} - -function rmdir (p, options, originalEr, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - - // try to rmdir first, and only readdir on ENOTEMPTY or EEXIST (SunOS) - // if we guessed wrong, and it's not a directory, then - // raise the original error. - options.rmdir(p, er => { - if (er && (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM')) { - rmkids(p, options, cb) - } else if (er && er.code === 'ENOTDIR') { - cb(originalEr) - } else { - cb(er) - } - }) -} - -function rmkids (p, options, cb) { - assert(p) - assert(options) - assert(typeof cb === 'function') - - options.readdir(p, (er, files) => { - if (er) return cb(er) - - let n = files.length - let errState - - if (n === 0) return options.rmdir(p, cb) - - files.forEach(f => { - rimraf(path.join(p, f), options, er => { - if (errState) { - return - } - if (er) return cb(errState = er) - if (--n === 0) { - options.rmdir(p, cb) - } - }) - }) - }) -} - -// this looks simpler, and is strictly *faster*, but will -// tie up the JavaScript thread and fail on excessively -// deep directory trees. -function rimrafSync (p, options) { - let st - - options = options || {} - defaults(options) - - assert(p, 'rimraf: missing path') - assert.strictEqual(typeof p, 'string', 'rimraf: path should be a string') - assert(options, 'rimraf: missing options') - assert.strictEqual(typeof options, 'object', 'rimraf: options should be object') - - try { - st = options.lstatSync(p) - } catch (er) { - if (er.code === 'ENOENT') { - return - } - - // Windows can EPERM on stat. Life is suffering. - if (er.code === 'EPERM' && isWindows) { - fixWinEPERMSync(p, options, er) - } - } - - try { - // sunos lets the root user unlink directories, which is... weird. - if (st && st.isDirectory()) { - rmdirSync(p, options, null) - } else { - options.unlinkSync(p) - } - } catch (er) { - if (er.code === 'ENOENT') { - return - } else if (er.code === 'EPERM') { - return isWindows ? fixWinEPERMSync(p, options, er) : rmdirSync(p, options, er) - } else if (er.code !== 'EISDIR') { - throw er - } - rmdirSync(p, options, er) - } -} - -function rmdirSync (p, options, originalEr) { - assert(p) - assert(options) - - try { - options.rmdirSync(p) - } catch (er) { - if (er.code === 'ENOTDIR') { - throw originalEr - } else if (er.code === 'ENOTEMPTY' || er.code === 'EEXIST' || er.code === 'EPERM') { - rmkidsSync(p, options) - } else if (er.code !== 'ENOENT') { - throw er - } - } -} - -function rmkidsSync (p, options) { - assert(p) - assert(options) - options.readdirSync(p).forEach(f => rimrafSync(path.join(p, f), options)) - - if (isWindows) { - // We only end up here once we got ENOTEMPTY at least once, and - // at this point, we are guaranteed to have removed all the kids. - // So, we know that it won't be ENOENT or ENOTDIR or anything else. - // try really hard to delete stuff on windows, because it has a - // PROFOUNDLY annoying habit of not closing handles promptly when - // files are deleted, resulting in spurious ENOTEMPTY errors. - const startTime = Date.now() - do { - try { - const ret = options.rmdirSync(p, options) - return ret - } catch {} - } while (Date.now() - startTime < 500) // give up after 500ms - } else { - const ret = options.rmdirSync(p, options) - return ret - } -} - -module.exports = rimraf -rimraf.sync = rimrafSync diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/util/stat.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/util/stat.js deleted file mode 100644 index 0ed5aecf..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/util/stat.js +++ /dev/null @@ -1,154 +0,0 @@ -'use strict' - -const fs = require('../fs') -const path = require('path') -const util = require('util') - -function getStats (src, dest, opts) { - const statFunc = opts.dereference - ? (file) => fs.stat(file, { bigint: true }) - : (file) => fs.lstat(file, { bigint: true }) - return Promise.all([ - statFunc(src), - statFunc(dest).catch(err => { - if (err.code === 'ENOENT') return null - throw err - }) - ]).then(([srcStat, destStat]) => ({ srcStat, destStat })) -} - -function getStatsSync (src, dest, opts) { - let destStat - const statFunc = opts.dereference - ? (file) => fs.statSync(file, { bigint: true }) - : (file) => fs.lstatSync(file, { bigint: true }) - const srcStat = statFunc(src) - try { - destStat = statFunc(dest) - } catch (err) { - if (err.code === 'ENOENT') return { srcStat, destStat: null } - throw err - } - return { srcStat, destStat } -} - -function checkPaths (src, dest, funcName, opts, cb) { - util.callbackify(getStats)(src, dest, opts, (err, stats) => { - if (err) return cb(err) - const { srcStat, destStat } = stats - - if (destStat) { - if (areIdentical(srcStat, destStat)) { - const srcBaseName = path.basename(src) - const destBaseName = path.basename(dest) - if (funcName === 'move' && - srcBaseName !== destBaseName && - srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { - return cb(null, { srcStat, destStat, isChangingCase: true }) - } - return cb(new Error('Source and destination must not be the same.')) - } - if (srcStat.isDirectory() && !destStat.isDirectory()) { - return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)) - } - if (!srcStat.isDirectory() && destStat.isDirectory()) { - return cb(new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`)) - } - } - - if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { - return cb(new Error(errMsg(src, dest, funcName))) - } - return cb(null, { srcStat, destStat }) - }) -} - -function checkPathsSync (src, dest, funcName, opts) { - const { srcStat, destStat } = getStatsSync(src, dest, opts) - - if (destStat) { - if (areIdentical(srcStat, destStat)) { - const srcBaseName = path.basename(src) - const destBaseName = path.basename(dest) - if (funcName === 'move' && - srcBaseName !== destBaseName && - srcBaseName.toLowerCase() === destBaseName.toLowerCase()) { - return { srcStat, destStat, isChangingCase: true } - } - throw new Error('Source and destination must not be the same.') - } - if (srcStat.isDirectory() && !destStat.isDirectory()) { - throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`) - } - if (!srcStat.isDirectory() && destStat.isDirectory()) { - throw new Error(`Cannot overwrite directory '${dest}' with non-directory '${src}'.`) - } - } - - if (srcStat.isDirectory() && isSrcSubdir(src, dest)) { - throw new Error(errMsg(src, dest, funcName)) - } - return { srcStat, destStat } -} - -// recursively check if dest parent is a subdirectory of src. -// It works for all file types including symlinks since it -// checks the src and dest inodes. It starts from the deepest -// parent and stops once it reaches the src parent or the root path. -function checkParentPaths (src, srcStat, dest, funcName, cb) { - const srcParent = path.resolve(path.dirname(src)) - const destParent = path.resolve(path.dirname(dest)) - if (destParent === srcParent || destParent === path.parse(destParent).root) return cb() - fs.stat(destParent, { bigint: true }, (err, destStat) => { - if (err) { - if (err.code === 'ENOENT') return cb() - return cb(err) - } - if (areIdentical(srcStat, destStat)) { - return cb(new Error(errMsg(src, dest, funcName))) - } - return checkParentPaths(src, srcStat, destParent, funcName, cb) - }) -} - -function checkParentPathsSync (src, srcStat, dest, funcName) { - const srcParent = path.resolve(path.dirname(src)) - const destParent = path.resolve(path.dirname(dest)) - if (destParent === srcParent || destParent === path.parse(destParent).root) return - let destStat - try { - destStat = fs.statSync(destParent, { bigint: true }) - } catch (err) { - if (err.code === 'ENOENT') return - throw err - } - if (areIdentical(srcStat, destStat)) { - throw new Error(errMsg(src, dest, funcName)) - } - return checkParentPathsSync(src, srcStat, destParent, funcName) -} - -function areIdentical (srcStat, destStat) { - return destStat.ino && destStat.dev && destStat.ino === srcStat.ino && destStat.dev === srcStat.dev -} - -// return true if dest is a subdir of src, otherwise false. -// It only checks the path strings. -function isSrcSubdir (src, dest) { - const srcArr = path.resolve(src).split(path.sep).filter(i => i) - const destArr = path.resolve(dest).split(path.sep).filter(i => i) - return srcArr.reduce((acc, cur, i) => acc && destArr[i] === cur, true) -} - -function errMsg (src, dest, funcName) { - return `Cannot ${funcName} '${src}' to a subdirectory of itself, '${dest}'.` -} - -module.exports = { - checkPaths, - checkPathsSync, - checkParentPaths, - checkParentPathsSync, - isSrcSubdir, - areIdentical -} diff --git a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/util/utimes.js b/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/util/utimes.js deleted file mode 100644 index 75395def..00000000 --- a/claude-code-source/node_modules/galactus/node_modules/fs-extra/lib/util/utimes.js +++ /dev/null @@ -1,26 +0,0 @@ -'use strict' - -const fs = require('graceful-fs') - -function utimesMillis (path, atime, mtime, callback) { - // if (!HAS_MILLIS_RES) return fs.utimes(path, atime, mtime, callback) - fs.open(path, 'r+', (err, fd) => { - if (err) return callback(err) - fs.futimes(fd, atime, mtime, futimesErr => { - fs.close(fd, closeErr => { - if (callback) callback(futimesErr || closeErr) - }) - }) - }) -} - -function utimesMillisSync (path, atime, mtime) { - const fd = fs.openSync(path, 'r+') - fs.futimesSync(fd, atime, mtime) - return fs.closeSync(fd) -} - -module.exports = { - utimesMillis, - utimesMillisSync -} diff --git a/claude-code-source/node_modules/gaxios/build/src/common.js b/claude-code-source/node_modules/gaxios/build/src/common.js deleted file mode 100644 index 4e9dceae..00000000 --- a/claude-code-source/node_modules/gaxios/build/src/common.js +++ /dev/null @@ -1,188 +0,0 @@ -"use strict"; -// Copyright 2018 Google LLC -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -var _a; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.GaxiosError = exports.GAXIOS_ERROR_SYMBOL = void 0; -exports.defaultErrorRedactor = defaultErrorRedactor; -const url_1 = require("url"); -const util_1 = require("./util"); -const extend_1 = __importDefault(require("extend")); -/** - * Support `instanceof` operator for `GaxiosError`s in different versions of this library. - * - * @see {@link GaxiosError[Symbol.hasInstance]} - */ -exports.GAXIOS_ERROR_SYMBOL = Symbol.for(`${util_1.pkg.name}-gaxios-error`); -/* eslint-disable-next-line @typescript-eslint/no-explicit-any */ -class GaxiosError extends Error { - /** - * Support `instanceof` operator for `GaxiosError` across builds/duplicated files. - * - * @see {@link GAXIOS_ERROR_SYMBOL} - * @see {@link GaxiosError[GAXIOS_ERROR_SYMBOL]} - */ - static [(_a = exports.GAXIOS_ERROR_SYMBOL, Symbol.hasInstance)](instance) { - if (instance && - typeof instance === 'object' && - exports.GAXIOS_ERROR_SYMBOL in instance && - instance[exports.GAXIOS_ERROR_SYMBOL] === util_1.pkg.version) { - return true; - } - // fallback to native - return Function.prototype[Symbol.hasInstance].call(GaxiosError, instance); - } - constructor(message, config, response, error) { - var _b; - super(message); - this.config = config; - this.response = response; - this.error = error; - /** - * Support `instanceof` operator for `GaxiosError` across builds/duplicated files. - * - * @see {@link GAXIOS_ERROR_SYMBOL} - * @see {@link GaxiosError[Symbol.hasInstance]} - * @see {@link https://github.com/microsoft/TypeScript/issues/13965#issuecomment-278570200} - * @see {@link https://stackoverflow.com/questions/46618852/require-and-instanceof} - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/@@hasInstance#reverting_to_default_instanceof_behavior} - */ - this[_a] = util_1.pkg.version; - // deep-copy config as we do not want to mutate - // the existing config for future retries/use - this.config = (0, extend_1.default)(true, {}, config); - if (this.response) { - this.response.config = (0, extend_1.default)(true, {}, this.response.config); - } - if (this.response) { - try { - this.response.data = translateData(this.config.responseType, (_b = this.response) === null || _b === void 0 ? void 0 : _b.data); - } - catch (_c) { - // best effort - don't throw an error within an error - // we could set `this.response.config.responseType = 'unknown'`, but - // that would mutate future calls with this config object. - } - this.status = this.response.status; - } - if (error && 'code' in error && error.code) { - this.code = error.code; - } - if (config.errorRedactor) { - config.errorRedactor({ - config: this.config, - response: this.response, - }); - } - } -} -exports.GaxiosError = GaxiosError; -function translateData(responseType, data) { - switch (responseType) { - case 'stream': - return data; - case 'json': - return JSON.parse(JSON.stringify(data)); - case 'arraybuffer': - return JSON.parse(Buffer.from(data).toString('utf8')); - case 'blob': - return JSON.parse(data.text()); - default: - return data; - } -} -/** - * An experimental error redactor. - * - * @param config Config to potentially redact properties of - * @param response Config to potentially redact properties of - * - * @experimental - */ -function defaultErrorRedactor(data) { - const REDACT = '< - See `errorRedactor` option in `gaxios` for configuration>.'; - function redactHeaders(headers) { - if (!headers) - return; - for (const key of Object.keys(headers)) { - // any casing of `Authentication` - if (/^authentication$/i.test(key)) { - headers[key] = REDACT; - } - // any casing of `Authorization` - if (/^authorization$/i.test(key)) { - headers[key] = REDACT; - } - // anything containing secret, such as 'client secret' - if (/secret/i.test(key)) { - headers[key] = REDACT; - } - } - } - function redactString(obj, key) { - if (typeof obj === 'object' && - obj !== null && - typeof obj[key] === 'string') { - const text = obj[key]; - if (/grant_type=/i.test(text) || - /assertion=/i.test(text) || - /secret/i.test(text)) { - obj[key] = REDACT; - } - } - } - function redactObject(obj) { - if (typeof obj === 'object' && obj !== null) { - if ('grant_type' in obj) { - obj['grant_type'] = REDACT; - } - if ('assertion' in obj) { - obj['assertion'] = REDACT; - } - if ('client_secret' in obj) { - obj['client_secret'] = REDACT; - } - } - } - if (data.config) { - redactHeaders(data.config.headers); - redactString(data.config, 'data'); - redactObject(data.config.data); - redactString(data.config, 'body'); - redactObject(data.config.body); - try { - const url = new url_1.URL('', data.config.url); - if (url.searchParams.has('token')) { - url.searchParams.set('token', REDACT); - } - if (url.searchParams.has('client_secret')) { - url.searchParams.set('client_secret', REDACT); - } - data.config.url = url.toString(); - } - catch (_b) { - // ignore error - no need to parse an invalid URL - } - } - if (data.response) { - defaultErrorRedactor({ config: data.response.config }); - redactHeaders(data.response.headers); - redactString(data.response, 'data'); - redactObject(data.response.data); - } - return data; -} -//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/build/src/gaxios.js b/claude-code-source/node_modules/gaxios/build/src/gaxios.js deleted file mode 100644 index b9fc1c09..00000000 --- a/claude-code-source/node_modules/gaxios/build/src/gaxios.js +++ /dev/null @@ -1,480 +0,0 @@ -"use strict"; -// Copyright 2018 Google LLC -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -var _Gaxios_instances, _a, _Gaxios_urlMayUseProxy, _Gaxios_applyRequestInterceptors, _Gaxios_applyResponseInterceptors, _Gaxios_prepareRequest, _Gaxios_proxyAgent, _Gaxios_getProxyAgent; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Gaxios = void 0; -const extend_1 = __importDefault(require("extend")); -const https_1 = require("https"); -const node_fetch_1 = __importDefault(require("node-fetch")); -const querystring_1 = __importDefault(require("querystring")); -const is_stream_1 = __importDefault(require("is-stream")); -const url_1 = require("url"); -const common_1 = require("./common"); -const retry_1 = require("./retry"); -const stream_1 = require("stream"); -const uuid_1 = require("uuid"); -const interceptor_1 = require("./interceptor"); -/* eslint-disable @typescript-eslint/no-explicit-any */ -const fetch = hasFetch() ? window.fetch : node_fetch_1.default; -function hasWindow() { - return typeof window !== 'undefined' && !!window; -} -function hasFetch() { - return hasWindow() && !!window.fetch; -} -function hasBuffer() { - return typeof Buffer !== 'undefined'; -} -function hasHeader(options, header) { - return !!getHeader(options, header); -} -function getHeader(options, header) { - header = header.toLowerCase(); - for (const key of Object.keys((options === null || options === void 0 ? void 0 : options.headers) || {})) { - if (header === key.toLowerCase()) { - return options.headers[key]; - } - } - return undefined; -} -class Gaxios { - /** - * The Gaxios class is responsible for making HTTP requests. - * @param defaults The default set of options to be used for this instance. - */ - constructor(defaults) { - _Gaxios_instances.add(this); - this.agentCache = new Map(); - this.defaults = defaults || {}; - this.interceptors = { - request: new interceptor_1.GaxiosInterceptorManager(), - response: new interceptor_1.GaxiosInterceptorManager(), - }; - } - /** - * Perform an HTTP request with the given options. - * @param opts Set of HTTP options that will be used for this HTTP request. - */ - async request(opts = {}) { - opts = await __classPrivateFieldGet(this, _Gaxios_instances, "m", _Gaxios_prepareRequest).call(this, opts); - opts = await __classPrivateFieldGet(this, _Gaxios_instances, "m", _Gaxios_applyRequestInterceptors).call(this, opts); - return __classPrivateFieldGet(this, _Gaxios_instances, "m", _Gaxios_applyResponseInterceptors).call(this, this._request(opts)); - } - async _defaultAdapter(opts) { - const fetchImpl = opts.fetchImplementation || fetch; - const res = (await fetchImpl(opts.url, opts)); - const data = await this.getResponseData(opts, res); - return this.translateResponse(opts, res, data); - } - /** - * Internal, retryable version of the `request` method. - * @param opts Set of HTTP options that will be used for this HTTP request. - */ - async _request(opts = {}) { - var _b; - try { - let translatedResponse; - if (opts.adapter) { - translatedResponse = await opts.adapter(opts, this._defaultAdapter.bind(this)); - } - else { - translatedResponse = await this._defaultAdapter(opts); - } - if (!opts.validateStatus(translatedResponse.status)) { - if (opts.responseType === 'stream') { - let response = ''; - await new Promise(resolve => { - (translatedResponse === null || translatedResponse === void 0 ? void 0 : translatedResponse.data).on('data', chunk => { - response += chunk; - }); - (translatedResponse === null || translatedResponse === void 0 ? void 0 : translatedResponse.data).on('end', resolve); - }); - translatedResponse.data = response; - } - throw new common_1.GaxiosError(`Request failed with status code ${translatedResponse.status}`, opts, translatedResponse); - } - return translatedResponse; - } - catch (e) { - const err = e instanceof common_1.GaxiosError - ? e - : new common_1.GaxiosError(e.message, opts, undefined, e); - const { shouldRetry, config } = await (0, retry_1.getRetryConfig)(err); - if (shouldRetry && config) { - err.config.retryConfig.currentRetryAttempt = - config.retryConfig.currentRetryAttempt; - // The error's config could be redacted - therefore we only want to - // copy the retry state over to the existing config - opts.retryConfig = (_b = err.config) === null || _b === void 0 ? void 0 : _b.retryConfig; - return this._request(opts); - } - throw err; - } - } - async getResponseData(opts, res) { - switch (opts.responseType) { - case 'stream': - return res.body; - case 'json': { - let data = await res.text(); - try { - data = JSON.parse(data); - } - catch (_b) { - // continue - } - return data; - } - case 'arraybuffer': - return res.arrayBuffer(); - case 'blob': - return res.blob(); - case 'text': - return res.text(); - default: - return this.getResponseDataFromContentType(res); - } - } - /** - * By default, throw for any non-2xx status code - * @param status status code from the HTTP response - */ - validateStatus(status) { - return status >= 200 && status < 300; - } - /** - * Encode a set of key/value pars into a querystring format (?foo=bar&baz=boo) - * @param params key value pars to encode - */ - paramsSerializer(params) { - return querystring_1.default.stringify(params); - } - translateResponse(opts, res, data) { - // headers need to be converted from a map to an obj - const headers = {}; - res.headers.forEach((value, key) => { - headers[key] = value; - }); - return { - config: opts, - data: data, - headers, - status: res.status, - statusText: res.statusText, - // XMLHttpRequestLike - request: { - responseURL: res.url, - }, - }; - } - /** - * Attempts to parse a response by looking at the Content-Type header. - * @param {FetchResponse} response the HTTP response. - * @returns {Promise} a promise that resolves to the response data. - */ - async getResponseDataFromContentType(response) { - let contentType = response.headers.get('Content-Type'); - if (contentType === null) { - // Maintain existing functionality by calling text() - return response.text(); - } - contentType = contentType.toLowerCase(); - if (contentType.includes('application/json')) { - let data = await response.text(); - try { - data = JSON.parse(data); - } - catch (_b) { - // continue - } - return data; - } - else if (contentType.match(/^text\//)) { - return response.text(); - } - else { - // If the content type is something not easily handled, just return the raw data (blob) - return response.blob(); - } - } - /** - * Creates an async generator that yields the pieces of a multipart/related request body. - * This implementation follows the spec: https://www.ietf.org/rfc/rfc2387.txt. However, recursive - * multipart/related requests are not currently supported. - * - * @param {GaxioMultipartOptions[]} multipartOptions the pieces to turn into a multipart/related body. - * @param {string} boundary the boundary string to be placed between each part. - */ - async *getMultipartRequest(multipartOptions, boundary) { - const finale = `--${boundary}--`; - for (const currentPart of multipartOptions) { - const partContentType = currentPart.headers['Content-Type'] || 'application/octet-stream'; - const preamble = `--${boundary}\r\nContent-Type: ${partContentType}\r\n\r\n`; - yield preamble; - if (typeof currentPart.content === 'string') { - yield currentPart.content; - } - else { - yield* currentPart.content; - } - yield '\r\n'; - } - yield finale; - } -} -exports.Gaxios = Gaxios; -_a = Gaxios, _Gaxios_instances = new WeakSet(), _Gaxios_urlMayUseProxy = function _Gaxios_urlMayUseProxy(url, noProxy = []) { - var _b, _c; - const candidate = new url_1.URL(url); - const noProxyList = [...noProxy]; - const noProxyEnvList = ((_c = ((_b = process.env.NO_PROXY) !== null && _b !== void 0 ? _b : process.env.no_proxy)) === null || _c === void 0 ? void 0 : _c.split(',')) || []; - for (const rule of noProxyEnvList) { - noProxyList.push(rule.trim()); - } - for (const rule of noProxyList) { - // Match regex - if (rule instanceof RegExp) { - if (rule.test(candidate.toString())) { - return false; - } - } - // Match URL - else if (rule instanceof url_1.URL) { - if (rule.origin === candidate.origin) { - return false; - } - } - // Match string regex - else if (rule.startsWith('*.') || rule.startsWith('.')) { - const cleanedRule = rule.replace(/^\*\./, '.'); - if (candidate.hostname.endsWith(cleanedRule)) { - return false; - } - } - // Basic string match - else if (rule === candidate.origin || - rule === candidate.hostname || - rule === candidate.href) { - return false; - } - } - return true; -}, _Gaxios_applyRequestInterceptors = -/** - * Applies the request interceptors. The request interceptors are applied after the - * call to prepareRequest is completed. - * - * @param {GaxiosOptions} options The current set of options. - * - * @returns {Promise} Promise that resolves to the set of options or response after interceptors are applied. - */ -async function _Gaxios_applyRequestInterceptors(options) { - let promiseChain = Promise.resolve(options); - for (const interceptor of this.interceptors.request.values()) { - if (interceptor) { - promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected); - } - } - return promiseChain; -}, _Gaxios_applyResponseInterceptors = -/** - * Applies the response interceptors. The response interceptors are applied after the - * call to request is made. - * - * @param {GaxiosOptions} options The current set of options. - * - * @returns {Promise} Promise that resolves to the set of options or response after interceptors are applied. - */ -async function _Gaxios_applyResponseInterceptors(response) { - let promiseChain = Promise.resolve(response); - for (const interceptor of this.interceptors.response.values()) { - if (interceptor) { - promiseChain = promiseChain.then(interceptor.resolved, interceptor.rejected); - } - } - return promiseChain; -}, _Gaxios_prepareRequest = -/** - * Validates the options, merges them with defaults, and prepare request. - * - * @param options The original options passed from the client. - * @returns Prepared options, ready to make a request - */ -async function _Gaxios_prepareRequest(options) { - var _b, _c, _d, _e; - const opts = (0, extend_1.default)(true, {}, this.defaults, options); - if (!opts.url) { - throw new Error('URL is required.'); - } - // baseUrl has been deprecated, remove in 2.0 - const baseUrl = opts.baseUrl || opts.baseURL; - if (baseUrl) { - opts.url = baseUrl.toString() + opts.url; - } - opts.paramsSerializer = opts.paramsSerializer || this.paramsSerializer; - if (opts.params && Object.keys(opts.params).length > 0) { - let additionalQueryParams = opts.paramsSerializer(opts.params); - if (additionalQueryParams.startsWith('?')) { - additionalQueryParams = additionalQueryParams.slice(1); - } - const prefix = opts.url.toString().includes('?') ? '&' : '?'; - opts.url = opts.url + prefix + additionalQueryParams; - } - if (typeof options.maxContentLength === 'number') { - opts.size = options.maxContentLength; - } - if (typeof options.maxRedirects === 'number') { - opts.follow = options.maxRedirects; - } - opts.headers = opts.headers || {}; - if (opts.multipart === undefined && opts.data) { - const isFormData = typeof FormData === 'undefined' - ? false - : (opts === null || opts === void 0 ? void 0 : opts.data) instanceof FormData; - if (is_stream_1.default.readable(opts.data)) { - opts.body = opts.data; - } - else if (hasBuffer() && Buffer.isBuffer(opts.data)) { - // Do not attempt to JSON.stringify() a Buffer: - opts.body = opts.data; - if (!hasHeader(opts, 'Content-Type')) { - opts.headers['Content-Type'] = 'application/json'; - } - } - else if (typeof opts.data === 'object') { - // If www-form-urlencoded content type has been set, but data is - // provided as an object, serialize the content using querystring: - if (!isFormData) { - if (getHeader(opts, 'content-type') === - 'application/x-www-form-urlencoded') { - opts.body = opts.paramsSerializer(opts.data); - } - else { - // } else if (!(opts.data instanceof FormData)) { - if (!hasHeader(opts, 'Content-Type')) { - opts.headers['Content-Type'] = 'application/json'; - } - opts.body = JSON.stringify(opts.data); - } - } - } - else { - opts.body = opts.data; - } - } - else if (opts.multipart && opts.multipart.length > 0) { - // note: once the minimum version reaches Node 16, - // this can be replaced with randomUUID() function from crypto - // and the dependency on UUID removed - const boundary = (0, uuid_1.v4)(); - opts.headers['Content-Type'] = `multipart/related; boundary=${boundary}`; - const bodyStream = new stream_1.PassThrough(); - opts.body = bodyStream; - (0, stream_1.pipeline)(this.getMultipartRequest(opts.multipart, boundary), bodyStream, () => { }); - } - opts.validateStatus = opts.validateStatus || this.validateStatus; - opts.responseType = opts.responseType || 'unknown'; - if (!opts.headers['Accept'] && opts.responseType === 'json') { - opts.headers['Accept'] = 'application/json'; - } - opts.method = opts.method || 'GET'; - const proxy = opts.proxy || - ((_b = process === null || process === void 0 ? void 0 : process.env) === null || _b === void 0 ? void 0 : _b.HTTPS_PROXY) || - ((_c = process === null || process === void 0 ? void 0 : process.env) === null || _c === void 0 ? void 0 : _c.https_proxy) || - ((_d = process === null || process === void 0 ? void 0 : process.env) === null || _d === void 0 ? void 0 : _d.HTTP_PROXY) || - ((_e = process === null || process === void 0 ? void 0 : process.env) === null || _e === void 0 ? void 0 : _e.http_proxy); - const urlMayUseProxy = __classPrivateFieldGet(this, _Gaxios_instances, "m", _Gaxios_urlMayUseProxy).call(this, opts.url, opts.noProxy); - if (opts.agent) { - // don't do any of the following options - use the user-provided agent. - } - else if (proxy && urlMayUseProxy) { - const HttpsProxyAgent = await __classPrivateFieldGet(_a, _a, "m", _Gaxios_getProxyAgent).call(_a); - if (this.agentCache.has(proxy)) { - opts.agent = this.agentCache.get(proxy); - } - else { - opts.agent = new HttpsProxyAgent(proxy, { - cert: opts.cert, - key: opts.key, - }); - this.agentCache.set(proxy, opts.agent); - } - } - else if (opts.cert && opts.key) { - // Configure client for mTLS - if (this.agentCache.has(opts.key)) { - opts.agent = this.agentCache.get(opts.key); - } - else { - opts.agent = new https_1.Agent({ - cert: opts.cert, - key: opts.key, - }); - this.agentCache.set(opts.key, opts.agent); - } - } - if (typeof opts.errorRedactor !== 'function' && - opts.errorRedactor !== false) { - opts.errorRedactor = common_1.defaultErrorRedactor; - } - return opts; -}, _Gaxios_getProxyAgent = async function _Gaxios_getProxyAgent() { - __classPrivateFieldSet(this, _a, __classPrivateFieldGet(this, _a, "f", _Gaxios_proxyAgent) || (await Promise.resolve().then(() => __importStar(require('https-proxy-agent')))).HttpsProxyAgent, "f", _Gaxios_proxyAgent); - return __classPrivateFieldGet(this, _a, "f", _Gaxios_proxyAgent); -}; -/** - * A cache for the lazily-loaded proxy agent. - * - * Should use {@link Gaxios[#getProxyAgent]} to retrieve. - */ -// using `import` to dynamically import the types here -_Gaxios_proxyAgent = { value: void 0 }; -//# sourceMappingURL=gaxios.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/build/src/index.js b/claude-code-source/node_modules/gaxios/build/src/index.js deleted file mode 100644 index cbda1522..00000000 --- a/claude-code-source/node_modules/gaxios/build/src/index.js +++ /dev/null @@ -1,48 +0,0 @@ -"use strict"; -// Copyright 2018 Google LLC -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.instance = exports.Gaxios = exports.GaxiosError = void 0; -exports.request = request; -const gaxios_1 = require("./gaxios"); -Object.defineProperty(exports, "Gaxios", { enumerable: true, get: function () { return gaxios_1.Gaxios; } }); -var common_1 = require("./common"); -Object.defineProperty(exports, "GaxiosError", { enumerable: true, get: function () { return common_1.GaxiosError; } }); -__exportStar(require("./interceptor"), exports); -/** - * The default instance used when the `request` method is directly - * invoked. - */ -exports.instance = new gaxios_1.Gaxios(); -/** - * Make an HTTP request using the given options. - * @param opts Options for the request - */ -async function request(opts) { - return exports.instance.request(opts); -} -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/build/src/interceptor.js b/claude-code-source/node_modules/gaxios/build/src/interceptor.js deleted file mode 100644 index c5e632e9..00000000 --- a/claude-code-source/node_modules/gaxios/build/src/interceptor.js +++ /dev/null @@ -1,22 +0,0 @@ -"use strict"; -// Copyright 2024 Google LLC -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.GaxiosInterceptorManager = void 0; -/** - * Class to manage collections of GaxiosInterceptors for both requests and responses. - */ -class GaxiosInterceptorManager extends Set { -} -exports.GaxiosInterceptorManager = GaxiosInterceptorManager; -//# sourceMappingURL=interceptor.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/build/src/retry.js b/claude-code-source/node_modules/gaxios/build/src/retry.js deleted file mode 100644 index 16074a40..00000000 --- a/claude-code-source/node_modules/gaxios/build/src/retry.js +++ /dev/null @@ -1,166 +0,0 @@ -"use strict"; -// Copyright 2018 Google LLC -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.getRetryConfig = getRetryConfig; -async function getRetryConfig(err) { - let config = getConfig(err); - if (!err || !err.config || (!config && !err.config.retry)) { - return { shouldRetry: false }; - } - config = config || {}; - config.currentRetryAttempt = config.currentRetryAttempt || 0; - config.retry = - config.retry === undefined || config.retry === null ? 3 : config.retry; - config.httpMethodsToRetry = config.httpMethodsToRetry || [ - 'GET', - 'HEAD', - 'PUT', - 'OPTIONS', - 'DELETE', - ]; - config.noResponseRetries = - config.noResponseRetries === undefined || config.noResponseRetries === null - ? 2 - : config.noResponseRetries; - config.retryDelayMultiplier = config.retryDelayMultiplier - ? config.retryDelayMultiplier - : 2; - config.timeOfFirstRequest = config.timeOfFirstRequest - ? config.timeOfFirstRequest - : Date.now(); - config.totalTimeout = config.totalTimeout - ? config.totalTimeout - : Number.MAX_SAFE_INTEGER; - config.maxRetryDelay = config.maxRetryDelay - ? config.maxRetryDelay - : Number.MAX_SAFE_INTEGER; - // If this wasn't in the list of status codes where we want - // to automatically retry, return. - const retryRanges = [ - // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes - // 1xx - Retry (Informational, request still processing) - // 2xx - Do not retry (Success) - // 3xx - Do not retry (Redirect) - // 4xx - Do not retry (Client errors) - // 408 - Retry ("Request Timeout") - // 429 - Retry ("Too Many Requests") - // 5xx - Retry (Server errors) - [100, 199], - [408, 408], - [429, 429], - [500, 599], - ]; - config.statusCodesToRetry = config.statusCodesToRetry || retryRanges; - // Put the config back into the err - err.config.retryConfig = config; - // Determine if we should retry the request - const shouldRetryFn = config.shouldRetry || shouldRetryRequest; - if (!(await shouldRetryFn(err))) { - return { shouldRetry: false, config: err.config }; - } - const delay = getNextRetryDelay(config); - // We're going to retry! Incremenent the counter. - err.config.retryConfig.currentRetryAttempt += 1; - // Create a promise that invokes the retry after the backOffDelay - const backoff = config.retryBackoff - ? config.retryBackoff(err, delay) - : new Promise(resolve => { - setTimeout(resolve, delay); - }); - // Notify the user if they added an `onRetryAttempt` handler - if (config.onRetryAttempt) { - config.onRetryAttempt(err); - } - // Return the promise in which recalls Gaxios to retry the request - await backoff; - return { shouldRetry: true, config: err.config }; -} -/** - * Determine based on config if we should retry the request. - * @param err The GaxiosError passed to the interceptor. - */ -function shouldRetryRequest(err) { - var _a; - const config = getConfig(err); - // node-fetch raises an AbortError if signaled: - // https://github.com/bitinn/node-fetch#request-cancellation-with-abortsignal - if (err.name === 'AbortError' || ((_a = err.error) === null || _a === void 0 ? void 0 : _a.name) === 'AbortError') { - return false; - } - // If there's no config, or retries are disabled, return. - if (!config || config.retry === 0) { - return false; - } - // Check if this error has no response (ETIMEDOUT, ENOTFOUND, etc) - if (!err.response && - (config.currentRetryAttempt || 0) >= config.noResponseRetries) { - return false; - } - // Only retry with configured HttpMethods. - if (!err.config.method || - config.httpMethodsToRetry.indexOf(err.config.method.toUpperCase()) < 0) { - return false; - } - // If this wasn't in the list of status codes where we want - // to automatically retry, return. - if (err.response && err.response.status) { - let isInRange = false; - for (const [min, max] of config.statusCodesToRetry) { - const status = err.response.status; - if (status >= min && status <= max) { - isInRange = true; - break; - } - } - if (!isInRange) { - return false; - } - } - // If we are out of retry attempts, return - config.currentRetryAttempt = config.currentRetryAttempt || 0; - if (config.currentRetryAttempt >= config.retry) { - return false; - } - return true; -} -/** - * Acquire the raxConfig object from an GaxiosError if available. - * @param err The Gaxios error with a config object. - */ -function getConfig(err) { - if (err && err.config && err.config.retryConfig) { - return err.config.retryConfig; - } - return; -} -/** - * Gets the delay to wait before the next retry. - * - * @param {RetryConfig} config The current set of retry options - * @returns {number} the amount of ms to wait before the next retry attempt. - */ -function getNextRetryDelay(config) { - var _a; - // Calculate time to wait with exponential backoff. - // If this is the first retry, look for a configured retryDelay. - const retryDelay = config.currentRetryAttempt ? 0 : (_a = config.retryDelay) !== null && _a !== void 0 ? _a : 100; - // Formula: retryDelay + ((retryDelayMultiplier^currentRetryAttempt - 1 / 2) * 1000) - const calculatedDelay = retryDelay + - ((Math.pow(config.retryDelayMultiplier, config.currentRetryAttempt) - 1) / - 2) * - 1000; - const maxAllowableDelay = config.totalTimeout - (Date.now() - config.timeOfFirstRequest); - return Math.min(calculatedDelay, maxAllowableDelay, config.maxRetryDelay); -} -//# sourceMappingURL=retry.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/build/src/util.js b/claude-code-source/node_modules/gaxios/build/src/util.js deleted file mode 100644 index be418448..00000000 --- a/claude-code-source/node_modules/gaxios/build/src/util.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; -// Copyright 2023 Google LLC -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.pkg = void 0; -exports.pkg = require('../../package.json'); -//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/node_modules/is-stream/index.js b/claude-code-source/node_modules/gaxios/node_modules/is-stream/index.js deleted file mode 100644 index 2e43434d..00000000 --- a/claude-code-source/node_modules/gaxios/node_modules/is-stream/index.js +++ /dev/null @@ -1,28 +0,0 @@ -'use strict'; - -const isStream = stream => - stream !== null && - typeof stream === 'object' && - typeof stream.pipe === 'function'; - -isStream.writable = stream => - isStream(stream) && - stream.writable !== false && - typeof stream._write === 'function' && - typeof stream._writableState === 'object'; - -isStream.readable = stream => - isStream(stream) && - stream.readable !== false && - typeof stream._read === 'function' && - typeof stream._readableState === 'object'; - -isStream.duplex = stream => - isStream.writable(stream) && - isStream.readable(stream); - -isStream.transform = stream => - isStream.duplex(stream) && - typeof stream._transform === 'function'; - -module.exports = isStream; diff --git a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/index.js b/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/index.js deleted file mode 100644 index 88d676a2..00000000 --- a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/index.js +++ /dev/null @@ -1,79 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -Object.defineProperty(exports, "NIL", { - enumerable: true, - get: function () { - return _nil.default; - } -}); -Object.defineProperty(exports, "parse", { - enumerable: true, - get: function () { - return _parse.default; - } -}); -Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function () { - return _stringify.default; - } -}); -Object.defineProperty(exports, "v1", { - enumerable: true, - get: function () { - return _v.default; - } -}); -Object.defineProperty(exports, "v3", { - enumerable: true, - get: function () { - return _v2.default; - } -}); -Object.defineProperty(exports, "v4", { - enumerable: true, - get: function () { - return _v3.default; - } -}); -Object.defineProperty(exports, "v5", { - enumerable: true, - get: function () { - return _v4.default; - } -}); -Object.defineProperty(exports, "validate", { - enumerable: true, - get: function () { - return _validate.default; - } -}); -Object.defineProperty(exports, "version", { - enumerable: true, - get: function () { - return _version.default; - } -}); - -var _v = _interopRequireDefault(require("./v1.js")); - -var _v2 = _interopRequireDefault(require("./v3.js")); - -var _v3 = _interopRequireDefault(require("./v4.js")); - -var _v4 = _interopRequireDefault(require("./v5.js")); - -var _nil = _interopRequireDefault(require("./nil.js")); - -var _version = _interopRequireDefault(require("./version.js")); - -var _validate = _interopRequireDefault(require("./validate.js")); - -var _stringify = _interopRequireDefault(require("./stringify.js")); - -var _parse = _interopRequireDefault(require("./parse.js")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/md5.js b/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/md5.js deleted file mode 100644 index 824d4816..00000000 --- a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/md5.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _crypto = _interopRequireDefault(require("crypto")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function md5(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - - return _crypto.default.createHash('md5').update(bytes).digest(); -} - -var _default = md5; -exports.default = _default; \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/native.js b/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/native.js deleted file mode 100644 index de804691..00000000 --- a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/native.js +++ /dev/null @@ -1,15 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _crypto = _interopRequireDefault(require("crypto")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var _default = { - randomUUID: _crypto.default.randomUUID -}; -exports.default = _default; \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/nil.js b/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/nil.js deleted file mode 100644 index 7ade577b..00000000 --- a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/nil.js +++ /dev/null @@ -1,8 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; -var _default = '00000000-0000-0000-0000-000000000000'; -exports.default = _default; \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/parse.js b/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/parse.js deleted file mode 100644 index 4c69fc39..00000000 --- a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/parse.js +++ /dev/null @@ -1,45 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _validate = _interopRequireDefault(require("./validate.js")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function parse(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - - let v; - const arr = new Uint8Array(16); // Parse ########-....-....-....-............ - - arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; - arr[1] = v >>> 16 & 0xff; - arr[2] = v >>> 8 & 0xff; - arr[3] = v & 0xff; // Parse ........-####-....-....-............ - - arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; // Parse ........-....-####-....-............ - - arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; // Parse ........-....-....-####-............ - - arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) - - arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; - arr[11] = v / 0x100000000 & 0xff; - arr[12] = v >>> 24 & 0xff; - arr[13] = v >>> 16 & 0xff; - arr[14] = v >>> 8 & 0xff; - arr[15] = v & 0xff; - return arr; -} - -var _default = parse; -exports.default = _default; \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/regex.js b/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/regex.js deleted file mode 100644 index 1ef91d64..00000000 --- a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/regex.js +++ /dev/null @@ -1,8 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; -var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; -exports.default = _default; \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/rng.js b/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/rng.js deleted file mode 100644 index 3507f937..00000000 --- a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/rng.js +++ /dev/null @@ -1,24 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = rng; - -var _crypto = _interopRequireDefault(require("crypto")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate - -let poolPtr = rnds8Pool.length; - -function rng() { - if (poolPtr > rnds8Pool.length - 16) { - _crypto.default.randomFillSync(rnds8Pool); - - poolPtr = 0; - } - - return rnds8Pool.slice(poolPtr, poolPtr += 16); -} \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/sha1.js b/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/sha1.js deleted file mode 100644 index 03bdd63c..00000000 --- a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/sha1.js +++ /dev/null @@ -1,23 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _crypto = _interopRequireDefault(require("crypto")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function sha1(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - - return _crypto.default.createHash('sha1').update(bytes).digest(); -} - -var _default = sha1; -exports.default = _default; \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/stringify.js b/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/stringify.js deleted file mode 100644 index 390bf891..00000000 --- a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/stringify.js +++ /dev/null @@ -1,44 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; -exports.unsafeStringify = unsafeStringify; - -var _validate = _interopRequireDefault(require("./validate.js")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -const byteToHex = []; - -for (let i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).slice(1)); -} - -function unsafeStringify(arr, offset = 0) { - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]; -} - -function stringify(arr, offset = 0) { - const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields - - if (!(0, _validate.default)(uuid)) { - throw TypeError('Stringified UUID is invalid'); - } - - return uuid; -} - -var _default = stringify; -exports.default = _default; \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/v1.js b/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/v1.js deleted file mode 100644 index 125bc58f..00000000 --- a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/v1.js +++ /dev/null @@ -1,107 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _rng = _interopRequireDefault(require("./rng.js")); - -var _stringify = require("./stringify.js"); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html -let _nodeId; - -let _clockseq; // Previous uuid creation time - - -let _lastMSecs = 0; -let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details - -function v1(options, buf, offset) { - let i = buf && offset || 0; - const b = buf || new Array(16); - options = options || {}; - let node = options.node || _nodeId; - let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not - // specified. We do this lazily to minimize issues related to insufficient - // system entropy. See #189 - - if (node == null || clockseq == null) { - const seedBytes = options.random || (options.rng || _rng.default)(); - - if (node == null) { - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; - } - - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; - } - } // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - - - let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - - let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) - - const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression - - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval - - - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } // Per 4.2.1.2 Throw error if too many uuids are requested - - - if (nsecs >= 10000) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); - } - - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - - msecs += 12219292800000; // `time_low` - - const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; // `time_mid` - - const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; // `time_high_and_version` - - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - - b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - - b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` - - b[i++] = clockseq & 0xff; // `node` - - for (let n = 0; n < 6; ++n) { - b[i + n] = node[n]; - } - - return buf || (0, _stringify.unsafeStringify)(b); -} - -var _default = v1; -exports.default = _default; \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/v3.js b/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/v3.js deleted file mode 100644 index 6b47ff51..00000000 --- a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/v3.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _v = _interopRequireDefault(require("./v35.js")); - -var _md = _interopRequireDefault(require("./md5.js")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const v3 = (0, _v.default)('v3', 0x30, _md.default); -var _default = v3; -exports.default = _default; \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/v35.js b/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/v35.js deleted file mode 100644 index 7c522d97..00000000 --- a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/v35.js +++ /dev/null @@ -1,80 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.URL = exports.DNS = void 0; -exports.default = v35; - -var _stringify = require("./stringify.js"); - -var _parse = _interopRequireDefault(require("./parse.js")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape - - const bytes = []; - - for (let i = 0; i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); - } - - return bytes; -} - -const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -exports.DNS = DNS; -const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -exports.URL = URL; - -function v35(name, version, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - var _namespace; - - if (typeof value === 'string') { - value = stringToBytes(value); - } - - if (typeof namespace === 'string') { - namespace = (0, _parse.default)(namespace); - } - - if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { - throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); - } // Compute hash of namespace and value, Per 4.3 - // Future: Use spread syntax when supported on all platforms, e.g. `bytes = - // hashfunc([...namespace, ... value])` - - - let bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; - - if (buf) { - offset = offset || 0; - - for (let i = 0; i < 16; ++i) { - buf[offset + i] = bytes[i]; - } - - return buf; - } - - return (0, _stringify.unsafeStringify)(bytes); - } // Function#name is not settable on some platforms (#270) - - - try { - generateUUID.name = name; // eslint-disable-next-line no-empty - } catch (err) {} // For CommonJS default export support - - - generateUUID.DNS = DNS; - generateUUID.URL = URL; - return generateUUID; -} \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/v4.js b/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/v4.js deleted file mode 100644 index 959d6986..00000000 --- a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/v4.js +++ /dev/null @@ -1,43 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _native = _interopRequireDefault(require("./native.js")); - -var _rng = _interopRequireDefault(require("./rng.js")); - -var _stringify = require("./stringify.js"); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function v4(options, buf, offset) { - if (_native.default.randomUUID && !buf && !options) { - return _native.default.randomUUID(); - } - - options = options || {}; - - const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - - - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided - - if (buf) { - offset = offset || 0; - - for (let i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; - } - - return buf; - } - - return (0, _stringify.unsafeStringify)(rnds); -} - -var _default = v4; -exports.default = _default; \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/v5.js b/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/v5.js deleted file mode 100644 index 99d615e0..00000000 --- a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/v5.js +++ /dev/null @@ -1,16 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _v = _interopRequireDefault(require("./v35.js")); - -var _sha = _interopRequireDefault(require("./sha1.js")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const v5 = (0, _v.default)('v5', 0x50, _sha.default); -var _default = v5; -exports.default = _default; \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/validate.js b/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/validate.js deleted file mode 100644 index fd052157..00000000 --- a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/validate.js +++ /dev/null @@ -1,17 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _regex = _interopRequireDefault(require("./regex.js")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function validate(uuid) { - return typeof uuid === 'string' && _regex.default.test(uuid); -} - -var _default = validate; -exports.default = _default; \ No newline at end of file diff --git a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/version.js b/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/version.js deleted file mode 100644 index f63af01a..00000000 --- a/claude-code-source/node_modules/gaxios/node_modules/uuid/dist/version.js +++ /dev/null @@ -1,21 +0,0 @@ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = void 0; - -var _validate = _interopRequireDefault(require("./validate.js")); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function version(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - - return parseInt(uuid.slice(14, 15), 16); -} - -var _default = version; -exports.default = _default; \ No newline at end of file diff --git a/claude-code-source/node_modules/gcp-metadata/build/src/gcp-residency.js b/claude-code-source/node_modules/gcp-metadata/build/src/gcp-residency.js deleted file mode 100644 index 83e7dbfa..00000000 --- a/claude-code-source/node_modules/gcp-metadata/build/src/gcp-residency.js +++ /dev/null @@ -1,114 +0,0 @@ -"use strict"; -/** - * Copyright 2022 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.GCE_LINUX_BIOS_PATHS = void 0; -exports.isGoogleCloudServerless = isGoogleCloudServerless; -exports.isGoogleComputeEngineLinux = isGoogleComputeEngineLinux; -exports.isGoogleComputeEngineMACAddress = isGoogleComputeEngineMACAddress; -exports.isGoogleComputeEngine = isGoogleComputeEngine; -exports.detectGCPResidency = detectGCPResidency; -const fs_1 = require("fs"); -const os_1 = require("os"); -/** - * Known paths unique to Google Compute Engine Linux instances - */ -exports.GCE_LINUX_BIOS_PATHS = { - BIOS_DATE: '/sys/class/dmi/id/bios_date', - BIOS_VENDOR: '/sys/class/dmi/id/bios_vendor', -}; -const GCE_MAC_ADDRESS_REGEX = /^42:01/; -/** - * Determines if the process is running on a Google Cloud Serverless environment (Cloud Run or Cloud Functions instance). - * - * Uses the: - * - {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}. - * - {@link https://cloud.google.com/functions/docs/env-var Cloud Functions environment variables}. - * - * @returns {boolean} `true` if the process is running on GCP serverless, `false` otherwise. - */ -function isGoogleCloudServerless() { - /** - * `CLOUD_RUN_JOB` is used for Cloud Run Jobs - * - See {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}. - * - * `FUNCTION_NAME` is used in older Cloud Functions environments: - * - See {@link https://cloud.google.com/functions/docs/env-var Python 3.7 and Go 1.11}. - * - * `K_SERVICE` is used in Cloud Run and newer Cloud Functions environments: - * - See {@link https://cloud.google.com/run/docs/container-contract#env-vars Cloud Run environment variables}. - * - See {@link https://cloud.google.com/functions/docs/env-var Cloud Functions newer runtimes}. - */ - const isGFEnvironment = process.env.CLOUD_RUN_JOB || - process.env.FUNCTION_NAME || - process.env.K_SERVICE; - return !!isGFEnvironment; -} -/** - * Determines if the process is running on a Linux Google Compute Engine instance. - * - * @returns {boolean} `true` if the process is running on Linux GCE, `false` otherwise. - */ -function isGoogleComputeEngineLinux() { - if ((0, os_1.platform)() !== 'linux') - return false; - try { - // ensure this file exist - (0, fs_1.statSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_DATE); - // ensure this file exist and matches - const biosVendor = (0, fs_1.readFileSync)(exports.GCE_LINUX_BIOS_PATHS.BIOS_VENDOR, 'utf8'); - return /Google/.test(biosVendor); - } - catch (_a) { - return false; - } -} -/** - * Determines if the process is running on a Google Compute Engine instance with a known - * MAC address. - * - * @returns {boolean} `true` if the process is running on GCE (as determined by MAC address), `false` otherwise. - */ -function isGoogleComputeEngineMACAddress() { - const interfaces = (0, os_1.networkInterfaces)(); - for (const item of Object.values(interfaces)) { - if (!item) - continue; - for (const { mac } of item) { - if (GCE_MAC_ADDRESS_REGEX.test(mac)) { - return true; - } - } - } - return false; -} -/** - * Determines if the process is running on a Google Compute Engine instance. - * - * @returns {boolean} `true` if the process is running on GCE, `false` otherwise. - */ -function isGoogleComputeEngine() { - return isGoogleComputeEngineLinux() || isGoogleComputeEngineMACAddress(); -} -/** - * Determines if the process is running on Google Cloud Platform. - * - * @returns {boolean} `true` if the process is running on GCP, `false` otherwise. - */ -function detectGCPResidency() { - return isGoogleCloudServerless() || isGoogleComputeEngine(); -} -//# sourceMappingURL=gcp-residency.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/gcp-metadata/build/src/index.js b/claude-code-source/node_modules/gcp-metadata/build/src/index.js deleted file mode 100644 index 13459362..00000000 --- a/claude-code-source/node_modules/gcp-metadata/build/src/index.js +++ /dev/null @@ -1,408 +0,0 @@ -"use strict"; -/** - * Copyright 2018 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.gcpResidencyCache = exports.METADATA_SERVER_DETECTION = exports.HEADERS = exports.HEADER_VALUE = exports.HEADER_NAME = exports.SECONDARY_HOST_ADDRESS = exports.HOST_ADDRESS = exports.BASE_PATH = void 0; -exports.instance = instance; -exports.project = project; -exports.universe = universe; -exports.bulk = bulk; -exports.isAvailable = isAvailable; -exports.resetIsAvailableCache = resetIsAvailableCache; -exports.getGCPResidency = getGCPResidency; -exports.setGCPResidency = setGCPResidency; -exports.requestTimeout = requestTimeout; -const gaxios_1 = require("gaxios"); -const jsonBigint = require("json-bigint"); -const gcp_residency_1 = require("./gcp-residency"); -const logger = require("google-logging-utils"); -exports.BASE_PATH = '/computeMetadata/v1'; -exports.HOST_ADDRESS = 'http://169.254.169.254'; -exports.SECONDARY_HOST_ADDRESS = 'http://metadata.google.internal.'; -exports.HEADER_NAME = 'Metadata-Flavor'; -exports.HEADER_VALUE = 'Google'; -exports.HEADERS = Object.freeze({ [exports.HEADER_NAME]: exports.HEADER_VALUE }); -const log = logger.log('gcp metadata'); -/** - * Metadata server detection override options. - * - * Available via `process.env.METADATA_SERVER_DETECTION`. - */ -exports.METADATA_SERVER_DETECTION = Object.freeze({ - 'assume-present': "don't try to ping the metadata server, but assume it's present", - none: "don't try to ping the metadata server, but don't try to use it either", - 'bios-only': "treat the result of a BIOS probe as canonical (don't fall back to pinging)", - 'ping-only': 'skip the BIOS probe, and go straight to pinging', -}); -/** - * Returns the base URL while taking into account the GCE_METADATA_HOST - * environment variable if it exists. - * - * @returns The base URL, e.g., http://169.254.169.254/computeMetadata/v1. - */ -function getBaseUrl(baseUrl) { - if (!baseUrl) { - baseUrl = - process.env.GCE_METADATA_IP || - process.env.GCE_METADATA_HOST || - exports.HOST_ADDRESS; - } - // If no scheme is provided default to HTTP: - if (!/^https?:\/\//.test(baseUrl)) { - baseUrl = `http://${baseUrl}`; - } - return new URL(exports.BASE_PATH, baseUrl).href; -} -// Accepts an options object passed from the user to the API. In previous -// versions of the API, it referred to a `Request` or an `Axios` request -// options object. Now it refers to an object with very limited property -// names. This is here to help ensure users don't pass invalid options when -// they upgrade from 0.4 to 0.5 to 0.8. -function validate(options) { - Object.keys(options).forEach(key => { - switch (key) { - case 'params': - case 'property': - case 'headers': - break; - case 'qs': - throw new Error("'qs' is not a valid configuration option. Please use 'params' instead."); - default: - throw new Error(`'${key}' is not a valid configuration option.`); - } - }); -} -async function metadataAccessor(type, options = {}, noResponseRetries = 3, fastFail = false) { - let metadataKey = ''; - let params = {}; - let headers = {}; - if (typeof type === 'object') { - const metadataAccessor = type; - metadataKey = metadataAccessor.metadataKey; - params = metadataAccessor.params || params; - headers = metadataAccessor.headers || headers; - noResponseRetries = metadataAccessor.noResponseRetries || noResponseRetries; - fastFail = metadataAccessor.fastFail || fastFail; - } - else { - metadataKey = type; - } - if (typeof options === 'string') { - metadataKey += `/${options}`; - } - else { - validate(options); - if (options.property) { - metadataKey += `/${options.property}`; - } - headers = options.headers || headers; - params = options.params || params; - } - const requestMethod = fastFail ? fastFailMetadataRequest : gaxios_1.request; - const req = { - url: `${getBaseUrl()}/${metadataKey}`, - headers: { ...exports.HEADERS, ...headers }, - retryConfig: { noResponseRetries }, - params, - responseType: 'text', - timeout: requestTimeout(), - }; - log.info('instance request %j', req); - const res = await requestMethod(req); - log.info('instance metadata is %s', res.data); - // NOTE: node.js converts all incoming headers to lower case. - if (res.headers[exports.HEADER_NAME.toLowerCase()] !== exports.HEADER_VALUE) { - throw new Error(`Invalid response from metadata service: incorrect ${exports.HEADER_NAME} header. Expected '${exports.HEADER_VALUE}', got ${res.headers[exports.HEADER_NAME.toLowerCase()] ? `'${res.headers[exports.HEADER_NAME.toLowerCase()]}'` : 'no header'}`); - } - if (typeof res.data === 'string') { - try { - return jsonBigint.parse(res.data); - } - catch (_a) { - /* ignore */ - } - } - return res.data; -} -async function fastFailMetadataRequest(options) { - var _a; - const secondaryOptions = { - ...options, - url: (_a = options.url) === null || _a === void 0 ? void 0 : _a.toString().replace(getBaseUrl(), getBaseUrl(exports.SECONDARY_HOST_ADDRESS)), - }; - // We race a connection between DNS/IP to metadata server. There are a couple - // reasons for this: - // - // 1. the DNS is slow in some GCP environments; by checking both, we might - // detect the runtime environment signficantly faster. - // 2. we can't just check the IP, which is tarpitted and slow to respond - // on a user's local machine. - // - // Additional logic has been added to make sure that we don't create an - // unhandled rejection in scenarios where a failure happens sometime - // after a success. - // - // Note, however, if a failure happens prior to a success, a rejection should - // occur, this is for folks running locally. - // - let responded = false; - const r1 = (0, gaxios_1.request)(options) - .then(res => { - responded = true; - return res; - }) - .catch(err => { - if (responded) { - return r2; - } - else { - responded = true; - throw err; - } - }); - const r2 = (0, gaxios_1.request)(secondaryOptions) - .then(res => { - responded = true; - return res; - }) - .catch(err => { - if (responded) { - return r1; - } - else { - responded = true; - throw err; - } - }); - return Promise.race([r1, r2]); -} -/** - * Obtain metadata for the current GCE instance. - * - * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} - * - * @example - * ``` - * const serviceAccount: {} = await instance('service-accounts/'); - * const serviceAccountEmail: string = await instance('service-accounts/default/email'); - * ``` - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function instance(options) { - return metadataAccessor('instance', options); -} -/** - * Obtain metadata for the current GCP project. - * - * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} - * - * @example - * ``` - * const projectId: string = await project('project-id'); - * const numericProjectId: number = await project('numeric-project-id'); - * ``` - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function project(options) { - return metadataAccessor('project', options); -} -/** - * Obtain metadata for the current universe. - * - * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} - * - * @example - * ``` - * const universeDomain: string = await universe('universe-domain'); - * ``` - */ -function universe(options) { - return metadataAccessor('universe', options); -} -/** - * Retrieve metadata items in parallel. - * - * @see {@link https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys} - * - * @example - * ``` - * const data = await bulk([ - * { - * metadataKey: 'instance', - * }, - * { - * metadataKey: 'project/project-id', - * }, - * ] as const); - * - * // data.instance; - * // data['project/project-id']; - * ``` - * - * @param properties The metadata properties to retrieve - * @returns The metadata in `metadatakey:value` format - */ -async function bulk(properties) { - const r = {}; - await Promise.all(properties.map(item => { - return (async () => { - const res = await metadataAccessor(item); - const key = item.metadataKey; - r[key] = res; - })(); - })); - return r; -} -/* - * How many times should we retry detecting GCP environment. - */ -function detectGCPAvailableRetries() { - return process.env.DETECT_GCP_RETRIES - ? Number(process.env.DETECT_GCP_RETRIES) - : 0; -} -let cachedIsAvailableResponse; -/** - * Determine if the metadata server is currently available. - */ -async function isAvailable() { - if (process.env.METADATA_SERVER_DETECTION) { - const value = process.env.METADATA_SERVER_DETECTION.trim().toLocaleLowerCase(); - if (!(value in exports.METADATA_SERVER_DETECTION)) { - throw new RangeError(`Unknown \`METADATA_SERVER_DETECTION\` env variable. Got \`${value}\`, but it should be \`${Object.keys(exports.METADATA_SERVER_DETECTION).join('`, `')}\`, or unset`); - } - switch (value) { - case 'assume-present': - return true; - case 'none': - return false; - case 'bios-only': - return getGCPResidency(); - case 'ping-only': - // continue, we want to ping the server - } - } - try { - // If a user is instantiating several GCP libraries at the same time, - // this may result in multiple calls to isAvailable(), to detect the - // runtime environment. We use the same promise for each of these calls - // to reduce the network load. - if (cachedIsAvailableResponse === undefined) { - cachedIsAvailableResponse = metadataAccessor('instance', undefined, detectGCPAvailableRetries(), - // If the default HOST_ADDRESS has been overridden, we should not - // make an effort to try SECONDARY_HOST_ADDRESS (as we are likely in - // a non-GCP environment): - !(process.env.GCE_METADATA_IP || process.env.GCE_METADATA_HOST)); - } - await cachedIsAvailableResponse; - return true; - } - catch (e) { - const err = e; - if (process.env.DEBUG_AUTH) { - console.info(err); - } - if (err.type === 'request-timeout') { - // If running in a GCP environment, metadata endpoint should return - // within ms. - return false; - } - if (err.response && err.response.status === 404) { - return false; - } - else { - if (!(err.response && err.response.status === 404) && - // A warning is emitted if we see an unexpected err.code, or err.code - // is not populated: - (!err.code || - ![ - 'EHOSTDOWN', - 'EHOSTUNREACH', - 'ENETUNREACH', - 'ENOENT', - 'ENOTFOUND', - 'ECONNREFUSED', - ].includes(err.code))) { - let code = 'UNKNOWN'; - if (err.code) - code = err.code; - process.emitWarning(`received unexpected error = ${err.message} code = ${code}`, 'MetadataLookupWarning'); - } - // Failure to resolve the metadata service means that it is not available. - return false; - } - } -} -/** - * reset the memoized isAvailable() lookup. - */ -function resetIsAvailableCache() { - cachedIsAvailableResponse = undefined; -} -/** - * A cache for the detected GCP Residency. - */ -exports.gcpResidencyCache = null; -/** - * Detects GCP Residency. - * Caches results to reduce costs for subsequent calls. - * - * @see setGCPResidency for setting - */ -function getGCPResidency() { - if (exports.gcpResidencyCache === null) { - setGCPResidency(); - } - return exports.gcpResidencyCache; -} -/** - * Sets the detected GCP Residency. - * Useful for forcing metadata server detection behavior. - * - * Set `null` to autodetect the environment (default behavior). - * @see getGCPResidency for getting - */ -function setGCPResidency(value = null) { - exports.gcpResidencyCache = value !== null ? value : (0, gcp_residency_1.detectGCPResidency)(); -} -/** - * Obtain the timeout for requests to the metadata server. - * - * In certain environments and conditions requests can take longer than - * the default timeout to complete. This function will determine the - * appropriate timeout based on the environment. - * - * @returns {number} a request timeout duration in milliseconds. - */ -function requestTimeout() { - return getGCPResidency() ? 0 : 3000; -} -__exportStar(require("./gcp-residency"), exports); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/get-east-asian-width/index.js b/claude-code-source/node_modules/get-east-asian-width/index.js deleted file mode 100644 index f95d5c51..00000000 --- a/claude-code-source/node_modules/get-east-asian-width/index.js +++ /dev/null @@ -1,30 +0,0 @@ -import {getCategory, isAmbiguous, isFullWidth, isWide} from './lookup.js'; - -function validate(codePoint) { - if (!Number.isSafeInteger(codePoint)) { - throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`); - } -} - -export function eastAsianWidthType(codePoint) { - validate(codePoint); - - return getCategory(codePoint); -} - -export function eastAsianWidth(codePoint, {ambiguousAsWide = false} = {}) { - validate(codePoint); - - if ( - isFullWidth(codePoint) - || isWide(codePoint) - || (ambiguousAsWide && isAmbiguous(codePoint)) - ) { - return 2; - } - - return 1; -} - -// Private exports for https://github.com/sindresorhus/is-fullwidth-code-point -export {isFullWidth as _isFullWidth, isWide as _isWide} from './lookup.js'; diff --git a/claude-code-source/node_modules/get-east-asian-width/lookup.js b/claude-code-source/node_modules/get-east-asian-width/lookup.js deleted file mode 100644 index 5c407131..00000000 --- a/claude-code-source/node_modules/get-east-asian-width/lookup.js +++ /dev/null @@ -1,403 +0,0 @@ -// Generated code. - -function isAmbiguous(x) { - return x === 0xA1 - || x === 0xA4 - || x === 0xA7 - || x === 0xA8 - || x === 0xAA - || x === 0xAD - || x === 0xAE - || x >= 0xB0 && x <= 0xB4 - || x >= 0xB6 && x <= 0xBA - || x >= 0xBC && x <= 0xBF - || x === 0xC6 - || x === 0xD0 - || x === 0xD7 - || x === 0xD8 - || x >= 0xDE && x <= 0xE1 - || x === 0xE6 - || x >= 0xE8 && x <= 0xEA - || x === 0xEC - || x === 0xED - || x === 0xF0 - || x === 0xF2 - || x === 0xF3 - || x >= 0xF7 && x <= 0xFA - || x === 0xFC - || x === 0xFE - || x === 0x101 - || x === 0x111 - || x === 0x113 - || x === 0x11B - || x === 0x126 - || x === 0x127 - || x === 0x12B - || x >= 0x131 && x <= 0x133 - || x === 0x138 - || x >= 0x13F && x <= 0x142 - || x === 0x144 - || x >= 0x148 && x <= 0x14B - || x === 0x14D - || x === 0x152 - || x === 0x153 - || x === 0x166 - || x === 0x167 - || x === 0x16B - || x === 0x1CE - || x === 0x1D0 - || x === 0x1D2 - || x === 0x1D4 - || x === 0x1D6 - || x === 0x1D8 - || x === 0x1DA - || x === 0x1DC - || x === 0x251 - || x === 0x261 - || x === 0x2C4 - || x === 0x2C7 - || x >= 0x2C9 && x <= 0x2CB - || x === 0x2CD - || x === 0x2D0 - || x >= 0x2D8 && x <= 0x2DB - || x === 0x2DD - || x === 0x2DF - || x >= 0x300 && x <= 0x36F - || x >= 0x391 && x <= 0x3A1 - || x >= 0x3A3 && x <= 0x3A9 - || x >= 0x3B1 && x <= 0x3C1 - || x >= 0x3C3 && x <= 0x3C9 - || x === 0x401 - || x >= 0x410 && x <= 0x44F - || x === 0x451 - || x === 0x2010 - || x >= 0x2013 && x <= 0x2016 - || x === 0x2018 - || x === 0x2019 - || x === 0x201C - || x === 0x201D - || x >= 0x2020 && x <= 0x2022 - || x >= 0x2024 && x <= 0x2027 - || x === 0x2030 - || x === 0x2032 - || x === 0x2033 - || x === 0x2035 - || x === 0x203B - || x === 0x203E - || x === 0x2074 - || x === 0x207F - || x >= 0x2081 && x <= 0x2084 - || x === 0x20AC - || x === 0x2103 - || x === 0x2105 - || x === 0x2109 - || x === 0x2113 - || x === 0x2116 - || x === 0x2121 - || x === 0x2122 - || x === 0x2126 - || x === 0x212B - || x === 0x2153 - || x === 0x2154 - || x >= 0x215B && x <= 0x215E - || x >= 0x2160 && x <= 0x216B - || x >= 0x2170 && x <= 0x2179 - || x === 0x2189 - || x >= 0x2190 && x <= 0x2199 - || x === 0x21B8 - || x === 0x21B9 - || x === 0x21D2 - || x === 0x21D4 - || x === 0x21E7 - || x === 0x2200 - || x === 0x2202 - || x === 0x2203 - || x === 0x2207 - || x === 0x2208 - || x === 0x220B - || x === 0x220F - || x === 0x2211 - || x === 0x2215 - || x === 0x221A - || x >= 0x221D && x <= 0x2220 - || x === 0x2223 - || x === 0x2225 - || x >= 0x2227 && x <= 0x222C - || x === 0x222E - || x >= 0x2234 && x <= 0x2237 - || x === 0x223C - || x === 0x223D - || x === 0x2248 - || x === 0x224C - || x === 0x2252 - || x === 0x2260 - || x === 0x2261 - || x >= 0x2264 && x <= 0x2267 - || x === 0x226A - || x === 0x226B - || x === 0x226E - || x === 0x226F - || x === 0x2282 - || x === 0x2283 - || x === 0x2286 - || x === 0x2287 - || x === 0x2295 - || x === 0x2299 - || x === 0x22A5 - || x === 0x22BF - || x === 0x2312 - || x >= 0x2460 && x <= 0x24E9 - || x >= 0x24EB && x <= 0x254B - || x >= 0x2550 && x <= 0x2573 - || x >= 0x2580 && x <= 0x258F - || x >= 0x2592 && x <= 0x2595 - || x === 0x25A0 - || x === 0x25A1 - || x >= 0x25A3 && x <= 0x25A9 - || x === 0x25B2 - || x === 0x25B3 - || x === 0x25B6 - || x === 0x25B7 - || x === 0x25BC - || x === 0x25BD - || x === 0x25C0 - || x === 0x25C1 - || x >= 0x25C6 && x <= 0x25C8 - || x === 0x25CB - || x >= 0x25CE && x <= 0x25D1 - || x >= 0x25E2 && x <= 0x25E5 - || x === 0x25EF - || x === 0x2605 - || x === 0x2606 - || x === 0x2609 - || x === 0x260E - || x === 0x260F - || x === 0x261C - || x === 0x261E - || x === 0x2640 - || x === 0x2642 - || x === 0x2660 - || x === 0x2661 - || x >= 0x2663 && x <= 0x2665 - || x >= 0x2667 && x <= 0x266A - || x === 0x266C - || x === 0x266D - || x === 0x266F - || x === 0x269E - || x === 0x269F - || x === 0x26BF - || x >= 0x26C6 && x <= 0x26CD - || x >= 0x26CF && x <= 0x26D3 - || x >= 0x26D5 && x <= 0x26E1 - || x === 0x26E3 - || x === 0x26E8 - || x === 0x26E9 - || x >= 0x26EB && x <= 0x26F1 - || x === 0x26F4 - || x >= 0x26F6 && x <= 0x26F9 - || x === 0x26FB - || x === 0x26FC - || x === 0x26FE - || x === 0x26FF - || x === 0x273D - || x >= 0x2776 && x <= 0x277F - || x >= 0x2B56 && x <= 0x2B59 - || x >= 0x3248 && x <= 0x324F - || x >= 0xE000 && x <= 0xF8FF - || x >= 0xFE00 && x <= 0xFE0F - || x === 0xFFFD - || x >= 0x1F100 && x <= 0x1F10A - || x >= 0x1F110 && x <= 0x1F12D - || x >= 0x1F130 && x <= 0x1F169 - || x >= 0x1F170 && x <= 0x1F18D - || x === 0x1F18F - || x === 0x1F190 - || x >= 0x1F19B && x <= 0x1F1AC - || x >= 0xE0100 && x <= 0xE01EF - || x >= 0xF0000 && x <= 0xFFFFD - || x >= 0x100000 && x <= 0x10FFFD; -} - -function isFullWidth(x) { - return x === 0x3000 - || x >= 0xFF01 && x <= 0xFF60 - || x >= 0xFFE0 && x <= 0xFFE6; -} - -function isWide(x) { - return x >= 0x1100 && x <= 0x115F - || x === 0x231A - || x === 0x231B - || x === 0x2329 - || x === 0x232A - || x >= 0x23E9 && x <= 0x23EC - || x === 0x23F0 - || x === 0x23F3 - || x === 0x25FD - || x === 0x25FE - || x === 0x2614 - || x === 0x2615 - || x >= 0x2630 && x <= 0x2637 - || x >= 0x2648 && x <= 0x2653 - || x === 0x267F - || x >= 0x268A && x <= 0x268F - || x === 0x2693 - || x === 0x26A1 - || x === 0x26AA - || x === 0x26AB - || x === 0x26BD - || x === 0x26BE - || x === 0x26C4 - || x === 0x26C5 - || x === 0x26CE - || x === 0x26D4 - || x === 0x26EA - || x === 0x26F2 - || x === 0x26F3 - || x === 0x26F5 - || x === 0x26FA - || x === 0x26FD - || x === 0x2705 - || x === 0x270A - || x === 0x270B - || x === 0x2728 - || x === 0x274C - || x === 0x274E - || x >= 0x2753 && x <= 0x2755 - || x === 0x2757 - || x >= 0x2795 && x <= 0x2797 - || x === 0x27B0 - || x === 0x27BF - || x === 0x2B1B - || x === 0x2B1C - || x === 0x2B50 - || x === 0x2B55 - || x >= 0x2E80 && x <= 0x2E99 - || x >= 0x2E9B && x <= 0x2EF3 - || x >= 0x2F00 && x <= 0x2FD5 - || x >= 0x2FF0 && x <= 0x2FFF - || x >= 0x3001 && x <= 0x303E - || x >= 0x3041 && x <= 0x3096 - || x >= 0x3099 && x <= 0x30FF - || x >= 0x3105 && x <= 0x312F - || x >= 0x3131 && x <= 0x318E - || x >= 0x3190 && x <= 0x31E5 - || x >= 0x31EF && x <= 0x321E - || x >= 0x3220 && x <= 0x3247 - || x >= 0x3250 && x <= 0xA48C - || x >= 0xA490 && x <= 0xA4C6 - || x >= 0xA960 && x <= 0xA97C - || x >= 0xAC00 && x <= 0xD7A3 - || x >= 0xF900 && x <= 0xFAFF - || x >= 0xFE10 && x <= 0xFE19 - || x >= 0xFE30 && x <= 0xFE52 - || x >= 0xFE54 && x <= 0xFE66 - || x >= 0xFE68 && x <= 0xFE6B - || x >= 0x16FE0 && x <= 0x16FE4 - || x >= 0x16FF0 && x <= 0x16FF6 - || x >= 0x17000 && x <= 0x18CD5 - || x >= 0x18CFF && x <= 0x18D1E - || x >= 0x18D80 && x <= 0x18DF2 - || x >= 0x1AFF0 && x <= 0x1AFF3 - || x >= 0x1AFF5 && x <= 0x1AFFB - || x === 0x1AFFD - || x === 0x1AFFE - || x >= 0x1B000 && x <= 0x1B122 - || x === 0x1B132 - || x >= 0x1B150 && x <= 0x1B152 - || x === 0x1B155 - || x >= 0x1B164 && x <= 0x1B167 - || x >= 0x1B170 && x <= 0x1B2FB - || x >= 0x1D300 && x <= 0x1D356 - || x >= 0x1D360 && x <= 0x1D376 - || x === 0x1F004 - || x === 0x1F0CF - || x === 0x1F18E - || x >= 0x1F191 && x <= 0x1F19A - || x >= 0x1F200 && x <= 0x1F202 - || x >= 0x1F210 && x <= 0x1F23B - || x >= 0x1F240 && x <= 0x1F248 - || x === 0x1F250 - || x === 0x1F251 - || x >= 0x1F260 && x <= 0x1F265 - || x >= 0x1F300 && x <= 0x1F320 - || x >= 0x1F32D && x <= 0x1F335 - || x >= 0x1F337 && x <= 0x1F37C - || x >= 0x1F37E && x <= 0x1F393 - || x >= 0x1F3A0 && x <= 0x1F3CA - || x >= 0x1F3CF && x <= 0x1F3D3 - || x >= 0x1F3E0 && x <= 0x1F3F0 - || x === 0x1F3F4 - || x >= 0x1F3F8 && x <= 0x1F43E - || x === 0x1F440 - || x >= 0x1F442 && x <= 0x1F4FC - || x >= 0x1F4FF && x <= 0x1F53D - || x >= 0x1F54B && x <= 0x1F54E - || x >= 0x1F550 && x <= 0x1F567 - || x === 0x1F57A - || x === 0x1F595 - || x === 0x1F596 - || x === 0x1F5A4 - || x >= 0x1F5FB && x <= 0x1F64F - || x >= 0x1F680 && x <= 0x1F6C5 - || x === 0x1F6CC - || x >= 0x1F6D0 && x <= 0x1F6D2 - || x >= 0x1F6D5 && x <= 0x1F6D8 - || x >= 0x1F6DC && x <= 0x1F6DF - || x === 0x1F6EB - || x === 0x1F6EC - || x >= 0x1F6F4 && x <= 0x1F6FC - || x >= 0x1F7E0 && x <= 0x1F7EB - || x === 0x1F7F0 - || x >= 0x1F90C && x <= 0x1F93A - || x >= 0x1F93C && x <= 0x1F945 - || x >= 0x1F947 && x <= 0x1F9FF - || x >= 0x1FA70 && x <= 0x1FA7C - || x >= 0x1FA80 && x <= 0x1FA8A - || x >= 0x1FA8E && x <= 0x1FAC6 - || x === 0x1FAC8 - || x >= 0x1FACD && x <= 0x1FADC - || x >= 0x1FADF && x <= 0x1FAEA - || x >= 0x1FAEF && x <= 0x1FAF8 - || x >= 0x20000 && x <= 0x2FFFD - || x >= 0x30000 && x <= 0x3FFFD; -} - -function getCategory(x) { - if (isAmbiguous(x)) return 'ambiguous'; - - if (isFullWidth(x)) return 'fullwidth'; - - if ( - x === 0x20A9 - || x >= 0xFF61 && x <= 0xFFBE - || x >= 0xFFC2 && x <= 0xFFC7 - || x >= 0xFFCA && x <= 0xFFCF - || x >= 0xFFD2 && x <= 0xFFD7 - || x >= 0xFFDA && x <= 0xFFDC - || x >= 0xFFE8 && x <= 0xFFEE - ) { - return 'halfwidth'; - } - - if ( - x >= 0x20 && x <= 0x7E - || x === 0xA2 - || x === 0xA3 - || x === 0xA5 - || x === 0xA6 - || x === 0xAC - || x === 0xAF - || x >= 0x27E6 && x <= 0x27ED - || x === 0x2985 - || x === 0x2986 - ) { - return 'narrow'; - } - - if (isWide(x)) return 'wide'; - - return 'neutral'; -} - -export {isAmbiguous, isFullWidth, isWide, getCategory}; diff --git a/claude-code-source/node_modules/get-intrinsic/index.js b/claude-code-source/node_modules/get-intrinsic/index.js deleted file mode 100644 index bd1d94b7..00000000 --- a/claude-code-source/node_modules/get-intrinsic/index.js +++ /dev/null @@ -1,378 +0,0 @@ -'use strict'; - -var undefined; - -var $Object = require('es-object-atoms'); - -var $Error = require('es-errors'); -var $EvalError = require('es-errors/eval'); -var $RangeError = require('es-errors/range'); -var $ReferenceError = require('es-errors/ref'); -var $SyntaxError = require('es-errors/syntax'); -var $TypeError = require('es-errors/type'); -var $URIError = require('es-errors/uri'); - -var abs = require('math-intrinsics/abs'); -var floor = require('math-intrinsics/floor'); -var max = require('math-intrinsics/max'); -var min = require('math-intrinsics/min'); -var pow = require('math-intrinsics/pow'); -var round = require('math-intrinsics/round'); -var sign = require('math-intrinsics/sign'); - -var $Function = Function; - -// eslint-disable-next-line consistent-return -var getEvalledConstructor = function (expressionSyntax) { - try { - return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); - } catch (e) {} -}; - -var $gOPD = require('gopd'); -var $defineProperty = require('es-define-property'); - -var throwTypeError = function () { - throw new $TypeError(); -}; -var ThrowTypeError = $gOPD - ? (function () { - try { - // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties - arguments.callee; // IE 8 does not throw here - return throwTypeError; - } catch (calleeThrows) { - try { - // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') - return $gOPD(arguments, 'callee').get; - } catch (gOPDthrows) { - return throwTypeError; - } - } - }()) - : throwTypeError; - -var hasSymbols = require('has-symbols')(); - -var getProto = require('get-proto'); -var $ObjectGPO = require('get-proto/Object.getPrototypeOf'); -var $ReflectGPO = require('get-proto/Reflect.getPrototypeOf'); - -var $apply = require('call-bind-apply-helpers/functionApply'); -var $call = require('call-bind-apply-helpers/functionCall'); - -var needsEval = {}; - -var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined : getProto(Uint8Array); - -var INTRINSICS = { - __proto__: null, - '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, - '%Array%': Array, - '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, - '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined, - '%AsyncFromSyncIteratorPrototype%': undefined, - '%AsyncFunction%': needsEval, - '%AsyncGenerator%': needsEval, - '%AsyncGeneratorFunction%': needsEval, - '%AsyncIteratorPrototype%': needsEval, - '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, - '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, - '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined : BigInt64Array, - '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined : BigUint64Array, - '%Boolean%': Boolean, - '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, - '%Date%': Date, - '%decodeURI%': decodeURI, - '%decodeURIComponent%': decodeURIComponent, - '%encodeURI%': encodeURI, - '%encodeURIComponent%': encodeURIComponent, - '%Error%': $Error, - '%eval%': eval, // eslint-disable-line no-eval - '%EvalError%': $EvalError, - '%Float16Array%': typeof Float16Array === 'undefined' ? undefined : Float16Array, - '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, - '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, - '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, - '%Function%': $Function, - '%GeneratorFunction%': needsEval, - '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, - '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, - '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, - '%isFinite%': isFinite, - '%isNaN%': isNaN, - '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined, - '%JSON%': typeof JSON === 'object' ? JSON : undefined, - '%Map%': typeof Map === 'undefined' ? undefined : Map, - '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Map()[Symbol.iterator]()), - '%Math%': Math, - '%Number%': Number, - '%Object%': $Object, - '%Object.getOwnPropertyDescriptor%': $gOPD, - '%parseFloat%': parseFloat, - '%parseInt%': parseInt, - '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, - '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, - '%RangeError%': $RangeError, - '%ReferenceError%': $ReferenceError, - '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, - '%RegExp%': RegExp, - '%Set%': typeof Set === 'undefined' ? undefined : Set, - '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined : getProto(new Set()[Symbol.iterator]()), - '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, - '%String%': String, - '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined, - '%Symbol%': hasSymbols ? Symbol : undefined, - '%SyntaxError%': $SyntaxError, - '%ThrowTypeError%': ThrowTypeError, - '%TypedArray%': TypedArray, - '%TypeError%': $TypeError, - '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, - '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, - '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, - '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, - '%URIError%': $URIError, - '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, - '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, - '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet, - - '%Function.prototype.call%': $call, - '%Function.prototype.apply%': $apply, - '%Object.defineProperty%': $defineProperty, - '%Object.getPrototypeOf%': $ObjectGPO, - '%Math.abs%': abs, - '%Math.floor%': floor, - '%Math.max%': max, - '%Math.min%': min, - '%Math.pow%': pow, - '%Math.round%': round, - '%Math.sign%': sign, - '%Reflect.getPrototypeOf%': $ReflectGPO -}; - -if (getProto) { - try { - null.error; // eslint-disable-line no-unused-expressions - } catch (e) { - // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 - var errorProto = getProto(getProto(e)); - INTRINSICS['%Error.prototype%'] = errorProto; - } -} - -var doEval = function doEval(name) { - var value; - if (name === '%AsyncFunction%') { - value = getEvalledConstructor('async function () {}'); - } else if (name === '%GeneratorFunction%') { - value = getEvalledConstructor('function* () {}'); - } else if (name === '%AsyncGeneratorFunction%') { - value = getEvalledConstructor('async function* () {}'); - } else if (name === '%AsyncGenerator%') { - var fn = doEval('%AsyncGeneratorFunction%'); - if (fn) { - value = fn.prototype; - } - } else if (name === '%AsyncIteratorPrototype%') { - var gen = doEval('%AsyncGenerator%'); - if (gen && getProto) { - value = getProto(gen.prototype); - } - } - - INTRINSICS[name] = value; - - return value; -}; - -var LEGACY_ALIASES = { - __proto__: null, - '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], - '%ArrayPrototype%': ['Array', 'prototype'], - '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], - '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], - '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], - '%ArrayProto_values%': ['Array', 'prototype', 'values'], - '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], - '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], - '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], - '%BooleanPrototype%': ['Boolean', 'prototype'], - '%DataViewPrototype%': ['DataView', 'prototype'], - '%DatePrototype%': ['Date', 'prototype'], - '%ErrorPrototype%': ['Error', 'prototype'], - '%EvalErrorPrototype%': ['EvalError', 'prototype'], - '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], - '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], - '%FunctionPrototype%': ['Function', 'prototype'], - '%Generator%': ['GeneratorFunction', 'prototype'], - '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], - '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], - '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], - '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], - '%JSONParse%': ['JSON', 'parse'], - '%JSONStringify%': ['JSON', 'stringify'], - '%MapPrototype%': ['Map', 'prototype'], - '%NumberPrototype%': ['Number', 'prototype'], - '%ObjectPrototype%': ['Object', 'prototype'], - '%ObjProto_toString%': ['Object', 'prototype', 'toString'], - '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], - '%PromisePrototype%': ['Promise', 'prototype'], - '%PromiseProto_then%': ['Promise', 'prototype', 'then'], - '%Promise_all%': ['Promise', 'all'], - '%Promise_reject%': ['Promise', 'reject'], - '%Promise_resolve%': ['Promise', 'resolve'], - '%RangeErrorPrototype%': ['RangeError', 'prototype'], - '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], - '%RegExpPrototype%': ['RegExp', 'prototype'], - '%SetPrototype%': ['Set', 'prototype'], - '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], - '%StringPrototype%': ['String', 'prototype'], - '%SymbolPrototype%': ['Symbol', 'prototype'], - '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], - '%TypedArrayPrototype%': ['TypedArray', 'prototype'], - '%TypeErrorPrototype%': ['TypeError', 'prototype'], - '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], - '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], - '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], - '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], - '%URIErrorPrototype%': ['URIError', 'prototype'], - '%WeakMapPrototype%': ['WeakMap', 'prototype'], - '%WeakSetPrototype%': ['WeakSet', 'prototype'] -}; - -var bind = require('function-bind'); -var hasOwn = require('hasown'); -var $concat = bind.call($call, Array.prototype.concat); -var $spliceApply = bind.call($apply, Array.prototype.splice); -var $replace = bind.call($call, String.prototype.replace); -var $strSlice = bind.call($call, String.prototype.slice); -var $exec = bind.call($call, RegExp.prototype.exec); - -/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ -var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; -var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ -var stringToPath = function stringToPath(string) { - var first = $strSlice(string, 0, 1); - var last = $strSlice(string, -1); - if (first === '%' && last !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); - } else if (last === '%' && first !== '%') { - throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); - } - var result = []; - $replace(string, rePropName, function (match, number, quote, subString) { - result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; - }); - return result; -}; -/* end adaptation */ - -var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { - var intrinsicName = name; - var alias; - if (hasOwn(LEGACY_ALIASES, intrinsicName)) { - alias = LEGACY_ALIASES[intrinsicName]; - intrinsicName = '%' + alias[0] + '%'; - } - - if (hasOwn(INTRINSICS, intrinsicName)) { - var value = INTRINSICS[intrinsicName]; - if (value === needsEval) { - value = doEval(intrinsicName); - } - if (typeof value === 'undefined' && !allowMissing) { - throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); - } - - return { - alias: alias, - name: intrinsicName, - value: value - }; - } - - throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); -}; - -module.exports = function GetIntrinsic(name, allowMissing) { - if (typeof name !== 'string' || name.length === 0) { - throw new $TypeError('intrinsic name must be a non-empty string'); - } - if (arguments.length > 1 && typeof allowMissing !== 'boolean') { - throw new $TypeError('"allowMissing" argument must be a boolean'); - } - - if ($exec(/^%?[^%]*%?$/, name) === null) { - throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); - } - var parts = stringToPath(name); - var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; - - var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); - var intrinsicRealName = intrinsic.name; - var value = intrinsic.value; - var skipFurtherCaching = false; - - var alias = intrinsic.alias; - if (alias) { - intrinsicBaseName = alias[0]; - $spliceApply(parts, $concat([0, 1], alias)); - } - - for (var i = 1, isOwn = true; i < parts.length; i += 1) { - var part = parts[i]; - var first = $strSlice(part, 0, 1); - var last = $strSlice(part, -1); - if ( - ( - (first === '"' || first === "'" || first === '`') - || (last === '"' || last === "'" || last === '`') - ) - && first !== last - ) { - throw new $SyntaxError('property names with quotes must have matching quotes'); - } - if (part === 'constructor' || !isOwn) { - skipFurtherCaching = true; - } - - intrinsicBaseName += '.' + part; - intrinsicRealName = '%' + intrinsicBaseName + '%'; - - if (hasOwn(INTRINSICS, intrinsicRealName)) { - value = INTRINSICS[intrinsicRealName]; - } else if (value != null) { - if (!(part in value)) { - if (!allowMissing) { - throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); - } - return void undefined; - } - if ($gOPD && (i + 1) >= parts.length) { - var desc = $gOPD(value, part); - isOwn = !!desc; - - // By convention, when a data property is converted to an accessor - // property to emulate a data property that does not suffer from - // the override mistake, that accessor's getter is marked with - // an `originalValue` property. Here, when we detect this, we - // uphold the illusion by pretending to see that original data - // property, i.e., returning the value rather than the getter - // itself. - if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { - value = desc.get; - } else { - value = value[part]; - } - } else { - isOwn = hasOwn(value, part); - value = value[part]; - } - - if (isOwn && !skipFurtherCaching) { - INTRINSICS[intrinsicRealName] = value; - } - } - } - return value; -}; diff --git a/claude-code-source/node_modules/get-proto/Object.getPrototypeOf.js b/claude-code-source/node_modules/get-proto/Object.getPrototypeOf.js deleted file mode 100644 index c2cbbdfc..00000000 --- a/claude-code-source/node_modules/get-proto/Object.getPrototypeOf.js +++ /dev/null @@ -1,6 +0,0 @@ -'use strict'; - -var $Object = require('es-object-atoms'); - -/** @type {import('./Object.getPrototypeOf')} */ -module.exports = $Object.getPrototypeOf || null; diff --git a/claude-code-source/node_modules/get-proto/Reflect.getPrototypeOf.js b/claude-code-source/node_modules/get-proto/Reflect.getPrototypeOf.js deleted file mode 100644 index e6c51bee..00000000 --- a/claude-code-source/node_modules/get-proto/Reflect.getPrototypeOf.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; - -/** @type {import('./Reflect.getPrototypeOf')} */ -module.exports = (typeof Reflect !== 'undefined' && Reflect.getPrototypeOf) || null; diff --git a/claude-code-source/node_modules/get-proto/index.js b/claude-code-source/node_modules/get-proto/index.js deleted file mode 100644 index 7e5747be..00000000 --- a/claude-code-source/node_modules/get-proto/index.js +++ /dev/null @@ -1,27 +0,0 @@ -'use strict'; - -var reflectGetProto = require('./Reflect.getPrototypeOf'); -var originalGetProto = require('./Object.getPrototypeOf'); - -var getDunderProto = require('dunder-proto/get'); - -/** @type {import('.')} */ -module.exports = reflectGetProto - ? function getProto(O) { - // @ts-expect-error TS can't narrow inside a closure, for some reason - return reflectGetProto(O); - } - : originalGetProto - ? function getProto(O) { - if (!O || (typeof O !== 'object' && typeof O !== 'function')) { - throw new TypeError('getProto: not an object'); - } - // @ts-expect-error TS can't narrow inside a closure, for some reason - return originalGetProto(O); - } - : getDunderProto - ? function getProto(O) { - // @ts-expect-error TS can't narrow inside a closure, for some reason - return getDunderProto(O); - } - : null; diff --git a/claude-code-source/node_modules/get-stream/source/array-buffer.js b/claude-code-source/node_modules/get-stream/source/array-buffer.js deleted file mode 100644 index a547405e..00000000 --- a/claude-code-source/node_modules/get-stream/source/array-buffer.js +++ /dev/null @@ -1,84 +0,0 @@ -import {getStreamContents} from './contents.js'; -import {noop, throwObjectStream, getLengthProp} from './utils.js'; - -export async function getStreamAsArrayBuffer(stream, options) { - return getStreamContents(stream, arrayBufferMethods, options); -} - -const initArrayBuffer = () => ({contents: new ArrayBuffer(0)}); - -const useTextEncoder = chunk => textEncoder.encode(chunk); -const textEncoder = new TextEncoder(); - -const useUint8Array = chunk => new Uint8Array(chunk); - -const useUint8ArrayWithOffset = chunk => new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength); - -const truncateArrayBufferChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize); - -// `contents` is an increasingly growing `Uint8Array`. -const addArrayBufferChunk = (convertedChunk, {contents, length: previousLength}, length) => { - const newContents = hasArrayBufferResize() ? resizeArrayBuffer(contents, length) : resizeArrayBufferSlow(contents, length); - new Uint8Array(newContents).set(convertedChunk, previousLength); - return newContents; -}; - -// Without `ArrayBuffer.resize()`, `contents` size is always a power of 2. -// This means its last bytes are zeroes (not stream data), which need to be -// trimmed at the end with `ArrayBuffer.slice()`. -const resizeArrayBufferSlow = (contents, length) => { - if (length <= contents.byteLength) { - return contents; - } - - const arrayBuffer = new ArrayBuffer(getNewContentsLength(length)); - new Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0); - return arrayBuffer; -}; - -// With `ArrayBuffer.resize()`, `contents` size matches exactly the size of -// the stream data. It does not include extraneous zeroes to trim at the end. -// The underlying `ArrayBuffer` does allocate a number of bytes that is a power -// of 2, but those bytes are only visible after calling `ArrayBuffer.resize()`. -const resizeArrayBuffer = (contents, length) => { - if (length <= contents.maxByteLength) { - contents.resize(length); - return contents; - } - - const arrayBuffer = new ArrayBuffer(length, {maxByteLength: getNewContentsLength(length)}); - new Uint8Array(arrayBuffer).set(new Uint8Array(contents), 0); - return arrayBuffer; -}; - -// Retrieve the closest `length` that is both >= and a power of 2 -const getNewContentsLength = length => SCALE_FACTOR ** Math.ceil(Math.log(length) / Math.log(SCALE_FACTOR)); - -const SCALE_FACTOR = 2; - -const finalizeArrayBuffer = ({contents, length}) => hasArrayBufferResize() ? contents : contents.slice(0, length); - -// `ArrayBuffer.slice()` is slow. When `ArrayBuffer.resize()` is available -// (Node >=20.0.0, Safari >=16.4 and Chrome), we can use it instead. -// eslint-disable-next-line no-warning-comments -// TODO: remove after dropping support for Node 20. -// eslint-disable-next-line no-warning-comments -// TODO: use `ArrayBuffer.transferToFixedLength()` instead once it is available -const hasArrayBufferResize = () => 'resize' in ArrayBuffer.prototype; - -const arrayBufferMethods = { - init: initArrayBuffer, - convertChunk: { - string: useTextEncoder, - buffer: useUint8Array, - arrayBuffer: useUint8Array, - dataView: useUint8ArrayWithOffset, - typedArray: useUint8ArrayWithOffset, - others: throwObjectStream, - }, - getSize: getLengthProp, - truncateChunk: truncateArrayBufferChunk, - addChunk: addArrayBufferChunk, - getFinalChunk: noop, - finalize: finalizeArrayBuffer, -}; diff --git a/claude-code-source/node_modules/get-stream/source/array.js b/claude-code-source/node_modules/get-stream/source/array.js deleted file mode 100644 index 468bad11..00000000 --- a/claude-code-source/node_modules/get-stream/source/array.js +++ /dev/null @@ -1,32 +0,0 @@ -import {getStreamContents} from './contents.js'; -import {identity, noop, getContentsProp} from './utils.js'; - -export async function getStreamAsArray(stream, options) { - return getStreamContents(stream, arrayMethods, options); -} - -const initArray = () => ({contents: []}); - -const increment = () => 1; - -const addArrayChunk = (convertedChunk, {contents}) => { - contents.push(convertedChunk); - return contents; -}; - -const arrayMethods = { - init: initArray, - convertChunk: { - string: identity, - buffer: identity, - arrayBuffer: identity, - dataView: identity, - typedArray: identity, - others: identity, - }, - getSize: increment, - truncateChunk: noop, - addChunk: addArrayChunk, - getFinalChunk: noop, - finalize: getContentsProp, -}; diff --git a/claude-code-source/node_modules/get-stream/source/buffer.js b/claude-code-source/node_modules/get-stream/source/buffer.js deleted file mode 100644 index 7d22d78d..00000000 --- a/claude-code-source/node_modules/get-stream/source/buffer.js +++ /dev/null @@ -1,20 +0,0 @@ -import {getStreamAsArrayBuffer} from './array-buffer.js'; - -export async function getStreamAsBuffer(stream, options) { - if (!('Buffer' in globalThis)) { - throw new Error('getStreamAsBuffer() is only supported in Node.js'); - } - - try { - return arrayBufferToNodeBuffer(await getStreamAsArrayBuffer(stream, options)); - } catch (error) { - if (error.bufferedData !== undefined) { - error.bufferedData = arrayBufferToNodeBuffer(error.bufferedData); - } - - throw error; - } -} - -// eslint-disable-next-line n/prefer-global/buffer -const arrayBufferToNodeBuffer = arrayBuffer => globalThis.Buffer.from(arrayBuffer); diff --git a/claude-code-source/node_modules/get-stream/source/contents.js b/claude-code-source/node_modules/get-stream/source/contents.js deleted file mode 100644 index 2ca36f2e..00000000 --- a/claude-code-source/node_modules/get-stream/source/contents.js +++ /dev/null @@ -1,101 +0,0 @@ -export const getStreamContents = async (stream, {init, convertChunk, getSize, truncateChunk, addChunk, getFinalChunk, finalize}, {maxBuffer = Number.POSITIVE_INFINITY} = {}) => { - if (!isAsyncIterable(stream)) { - throw new Error('The first argument must be a Readable, a ReadableStream, or an async iterable.'); - } - - const state = init(); - state.length = 0; - - try { - for await (const chunk of stream) { - const chunkType = getChunkType(chunk); - const convertedChunk = convertChunk[chunkType](chunk, state); - appendChunk({convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer}); - } - - appendFinalChunk({state, convertChunk, getSize, truncateChunk, addChunk, getFinalChunk, maxBuffer}); - return finalize(state); - } catch (error) { - error.bufferedData = finalize(state); - throw error; - } -}; - -const appendFinalChunk = ({state, getSize, truncateChunk, addChunk, getFinalChunk, maxBuffer}) => { - const convertedChunk = getFinalChunk(state); - if (convertedChunk !== undefined) { - appendChunk({convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer}); - } -}; - -const appendChunk = ({convertedChunk, state, getSize, truncateChunk, addChunk, maxBuffer}) => { - const chunkSize = getSize(convertedChunk); - const newLength = state.length + chunkSize; - - if (newLength <= maxBuffer) { - addNewChunk(convertedChunk, state, addChunk, newLength); - return; - } - - const truncatedChunk = truncateChunk(convertedChunk, maxBuffer - state.length); - - if (truncatedChunk !== undefined) { - addNewChunk(truncatedChunk, state, addChunk, maxBuffer); - } - - throw new MaxBufferError(); -}; - -const addNewChunk = (convertedChunk, state, addChunk, newLength) => { - state.contents = addChunk(convertedChunk, state, newLength); - state.length = newLength; -}; - -const isAsyncIterable = stream => typeof stream === 'object' && stream !== null && typeof stream[Symbol.asyncIterator] === 'function'; - -const getChunkType = chunk => { - const typeOfChunk = typeof chunk; - - if (typeOfChunk === 'string') { - return 'string'; - } - - if (typeOfChunk !== 'object' || chunk === null) { - return 'others'; - } - - // eslint-disable-next-line n/prefer-global/buffer - if (globalThis.Buffer?.isBuffer(chunk)) { - return 'buffer'; - } - - const prototypeName = objectToString.call(chunk); - - if (prototypeName === '[object ArrayBuffer]') { - return 'arrayBuffer'; - } - - if (prototypeName === '[object DataView]') { - return 'dataView'; - } - - if ( - Number.isInteger(chunk.byteLength) - && Number.isInteger(chunk.byteOffset) - && objectToString.call(chunk.buffer) === '[object ArrayBuffer]' - ) { - return 'typedArray'; - } - - return 'others'; -}; - -const {toString: objectToString} = Object.prototype; - -export class MaxBufferError extends Error { - name = 'MaxBufferError'; - - constructor() { - super('maxBuffer exceeded'); - } -} diff --git a/claude-code-source/node_modules/get-stream/source/index.js b/claude-code-source/node_modules/get-stream/source/index.js deleted file mode 100644 index 43c2dd4b..00000000 --- a/claude-code-source/node_modules/get-stream/source/index.js +++ /dev/null @@ -1,5 +0,0 @@ -export {getStreamAsArray} from './array.js'; -export {getStreamAsArrayBuffer} from './array-buffer.js'; -export {getStreamAsBuffer} from './buffer.js'; -export {getStreamAsString as default} from './string.js'; -export {MaxBufferError} from './contents.js'; diff --git a/claude-code-source/node_modules/get-stream/source/string.js b/claude-code-source/node_modules/get-stream/source/string.js deleted file mode 100644 index 90f94b96..00000000 --- a/claude-code-source/node_modules/get-stream/source/string.js +++ /dev/null @@ -1,36 +0,0 @@ -import {getStreamContents} from './contents.js'; -import {identity, getContentsProp, throwObjectStream, getLengthProp} from './utils.js'; - -export async function getStreamAsString(stream, options) { - return getStreamContents(stream, stringMethods, options); -} - -const initString = () => ({contents: '', textDecoder: new TextDecoder()}); - -const useTextDecoder = (chunk, {textDecoder}) => textDecoder.decode(chunk, {stream: true}); - -const addStringChunk = (convertedChunk, {contents}) => contents + convertedChunk; - -const truncateStringChunk = (convertedChunk, chunkSize) => convertedChunk.slice(0, chunkSize); - -const getFinalStringChunk = ({textDecoder}) => { - const finalChunk = textDecoder.decode(); - return finalChunk === '' ? undefined : finalChunk; -}; - -const stringMethods = { - init: initString, - convertChunk: { - string: identity, - buffer: useTextDecoder, - arrayBuffer: useTextDecoder, - dataView: useTextDecoder, - typedArray: useTextDecoder, - others: throwObjectStream, - }, - getSize: getLengthProp, - truncateChunk: truncateStringChunk, - addChunk: addStringChunk, - getFinalChunk: getFinalStringChunk, - finalize: getContentsProp, -}; diff --git a/claude-code-source/node_modules/get-stream/source/utils.js b/claude-code-source/node_modules/get-stream/source/utils.js deleted file mode 100644 index af8d5e29..00000000 --- a/claude-code-source/node_modules/get-stream/source/utils.js +++ /dev/null @@ -1,11 +0,0 @@ -export const identity = value => value; - -export const noop = () => undefined; - -export const getContentsProp = ({contents}) => contents; - -export const throwObjectStream = chunk => { - throw new Error(`Streams in object mode are not supported: ${String(chunk)}`); -}; - -export const getLengthProp = convertedChunk => convertedChunk.length; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/authclient.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/authclient.js deleted file mode 100644 index f80ca587..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/authclient.js +++ /dev/null @@ -1,116 +0,0 @@ -"use strict"; -// Copyright 2012 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AuthClient = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = exports.DEFAULT_UNIVERSE = void 0; -const events_1 = require("events"); -const gaxios_1 = require("gaxios"); -const transporters_1 = require("../transporters"); -const util_1 = require("../util"); -/** - * The default cloud universe - * - * @see {@link AuthJSONOptions.universe_domain} - */ -exports.DEFAULT_UNIVERSE = 'googleapis.com'; -/** - * The default {@link AuthClientOptions.eagerRefreshThresholdMillis} - */ -exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS = 5 * 60 * 1000; -class AuthClient extends events_1.EventEmitter { - constructor(opts = {}) { - var _a, _b, _c, _d, _e; - super(); - this.credentials = {}; - this.eagerRefreshThresholdMillis = exports.DEFAULT_EAGER_REFRESH_THRESHOLD_MILLIS; - this.forceRefreshOnFailure = false; - this.universeDomain = exports.DEFAULT_UNIVERSE; - const options = (0, util_1.originalOrCamelOptions)(opts); - // Shared auth options - this.apiKey = opts.apiKey; - this.projectId = (_a = options.get('project_id')) !== null && _a !== void 0 ? _a : null; - this.quotaProjectId = options.get('quota_project_id'); - this.credentials = (_b = options.get('credentials')) !== null && _b !== void 0 ? _b : {}; - this.universeDomain = (_c = options.get('universe_domain')) !== null && _c !== void 0 ? _c : exports.DEFAULT_UNIVERSE; - // Shared client options - this.transporter = (_d = opts.transporter) !== null && _d !== void 0 ? _d : new transporters_1.DefaultTransporter(); - if (opts.transporterOptions) { - this.transporter.defaults = opts.transporterOptions; - } - if (opts.eagerRefreshThresholdMillis) { - this.eagerRefreshThresholdMillis = opts.eagerRefreshThresholdMillis; - } - this.forceRefreshOnFailure = (_e = opts.forceRefreshOnFailure) !== null && _e !== void 0 ? _e : false; - } - /** - * Return the {@link Gaxios `Gaxios`} instance from the {@link AuthClient.transporter}. - * - * @expiremental - */ - get gaxios() { - if (this.transporter instanceof gaxios_1.Gaxios) { - return this.transporter; - } - else if (this.transporter instanceof transporters_1.DefaultTransporter) { - return this.transporter.instance; - } - else if ('instance' in this.transporter && - this.transporter.instance instanceof gaxios_1.Gaxios) { - return this.transporter.instance; - } - return null; - } - /** - * Sets the auth credentials. - */ - setCredentials(credentials) { - this.credentials = credentials; - } - /** - * Append additional headers, e.g., x-goog-user-project, shared across the - * classes inheriting AuthClient. This method should be used by any method - * that overrides getRequestMetadataAsync(), which is a shared helper for - * setting request information in both gRPC and HTTP API calls. - * - * @param headers object to append additional headers to. - */ - addSharedMetadataHeaders(headers) { - // quota_project_id, stored in application_default_credentials.json, is set in - // the x-goog-user-project header, to indicate an alternate account for - // billing and quota: - if (!headers['x-goog-user-project'] && // don't override a value the user sets. - this.quotaProjectId) { - headers['x-goog-user-project'] = this.quotaProjectId; - } - return headers; - } - /** - * Retry config for Auth-related requests. - * - * @remarks - * - * This is not a part of the default {@link AuthClient.transporter transporter/gaxios} - * config as some downstream APIs would prefer if customers explicitly enable retries, - * such as GCS. - */ - static get RETRY_CONFIG() { - return { - retry: true, - retryConfig: { - httpMethodsToRetry: ['GET', 'PUT', 'POST', 'HEAD', 'OPTIONS', 'DELETE'], - }, - }; - } -} -exports.AuthClient = AuthClient; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/awsclient.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/awsclient.js deleted file mode 100644 index c2bebd4e..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/awsclient.js +++ /dev/null @@ -1,164 +0,0 @@ -"use strict"; -// Copyright 2021 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var _a, _AwsClient_DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AwsClient = void 0; -const awsrequestsigner_1 = require("./awsrequestsigner"); -const baseexternalclient_1 = require("./baseexternalclient"); -const defaultawssecuritycredentialssupplier_1 = require("./defaultawssecuritycredentialssupplier"); -const util_1 = require("../util"); -/** - * AWS external account client. This is used for AWS workloads, where - * AWS STS GetCallerIdentity serialized signed requests are exchanged for - * GCP access token. - */ -class AwsClient extends baseexternalclient_1.BaseExternalAccountClient { - /** - * Instantiates an AwsClient instance using the provided JSON - * object loaded from an external account credentials file. - * An error is thrown if the credential is not a valid AWS credential. - * @param options The external account options object typically loaded - * from the external account JSON credential file. - * @param additionalOptions **DEPRECATED, all options are available in the - * `options` parameter.** Optional additional behavior customization options. - * These currently customize expiration threshold time and whether to retry - * on 401/403 API request errors. - */ - constructor(options, additionalOptions) { - super(options, additionalOptions); - const opts = (0, util_1.originalOrCamelOptions)(options); - const credentialSource = opts.get('credential_source'); - const awsSecurityCredentialsSupplier = opts.get('aws_security_credentials_supplier'); - // Validate credential sourcing configuration. - if (!credentialSource && !awsSecurityCredentialsSupplier) { - throw new Error('A credential source or AWS security credentials supplier must be specified.'); - } - if (credentialSource && awsSecurityCredentialsSupplier) { - throw new Error('Only one of credential source or AWS security credentials supplier can be specified.'); - } - if (awsSecurityCredentialsSupplier) { - this.awsSecurityCredentialsSupplier = awsSecurityCredentialsSupplier; - this.regionalCredVerificationUrl = - __classPrivateFieldGet(_a, _a, "f", _AwsClient_DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL); - this.credentialSourceType = 'programmatic'; - } - else { - const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource); - this.environmentId = credentialSourceOpts.get('environment_id'); - // This is only required if the AWS region is not available in the - // AWS_REGION or AWS_DEFAULT_REGION environment variables. - const regionUrl = credentialSourceOpts.get('region_url'); - // This is only required if AWS security credentials are not available in - // environment variables. - const securityCredentialsUrl = credentialSourceOpts.get('url'); - const imdsV2SessionTokenUrl = credentialSourceOpts.get('imdsv2_session_token_url'); - this.awsSecurityCredentialsSupplier = - new defaultawssecuritycredentialssupplier_1.DefaultAwsSecurityCredentialsSupplier({ - regionUrl: regionUrl, - securityCredentialsUrl: securityCredentialsUrl, - imdsV2SessionTokenUrl: imdsV2SessionTokenUrl, - }); - this.regionalCredVerificationUrl = credentialSourceOpts.get('regional_cred_verification_url'); - this.credentialSourceType = 'aws'; - // Data validators. - this.validateEnvironmentId(); - } - this.awsRequestSigner = null; - this.region = ''; - } - validateEnvironmentId() { - var _b; - const match = (_b = this.environmentId) === null || _b === void 0 ? void 0 : _b.match(/^(aws)(\d+)$/); - if (!match || !this.regionalCredVerificationUrl) { - throw new Error('No valid AWS "credential_source" provided'); - } - else if (parseInt(match[2], 10) !== 1) { - throw new Error(`aws version "${match[2]}" is not supported in the current build.`); - } - } - /** - * Triggered when an external subject token is needed to be exchanged for a - * GCP access token via GCP STS endpoint. This will call the - * {@link AwsSecurityCredentialsSupplier} to retrieve an AWS region and AWS - * Security Credentials, then use them to create a signed AWS STS request that - * can be exchanged for a GCP access token. - * @return A promise that resolves with the external subject token. - */ - async retrieveSubjectToken() { - // Initialize AWS request signer if not already initialized. - if (!this.awsRequestSigner) { - this.region = await this.awsSecurityCredentialsSupplier.getAwsRegion(this.supplierContext); - this.awsRequestSigner = new awsrequestsigner_1.AwsRequestSigner(async () => { - return this.awsSecurityCredentialsSupplier.getAwsSecurityCredentials(this.supplierContext); - }, this.region); - } - // Generate signed request to AWS STS GetCallerIdentity API. - // Use the required regional endpoint. Otherwise, the request will fail. - const options = await this.awsRequestSigner.getRequestOptions({ - ..._a.RETRY_CONFIG, - url: this.regionalCredVerificationUrl.replace('{region}', this.region), - method: 'POST', - }); - // The GCP STS endpoint expects the headers to be formatted as: - // [ - // {key: 'x-amz-date', value: '...'}, - // {key: 'Authorization', value: '...'}, - // ... - // ] - // And then serialized as: - // encodeURIComponent(JSON.stringify({ - // url: '...', - // method: 'POST', - // headers: [{key: 'x-amz-date', value: '...'}, ...] - // })) - const reformattedHeader = []; - const extendedHeaders = Object.assign({ - // The full, canonical resource name of the workload identity pool - // provider, with or without the HTTPS prefix. - // Including this header as part of the signature is recommended to - // ensure data integrity. - 'x-goog-cloud-target-resource': this.audience, - }, options.headers); - // Reformat header to GCP STS expected format. - for (const key in extendedHeaders) { - reformattedHeader.push({ - key, - value: extendedHeaders[key], - }); - } - // Serialize the reformatted signed request. - return encodeURIComponent(JSON.stringify({ - url: options.url, - method: options.method, - headers: reformattedHeader, - })); - } -} -exports.AwsClient = AwsClient; -_a = AwsClient; -_AwsClient_DEFAULT_AWS_REGIONAL_CREDENTIAL_VERIFICATION_URL = { value: 'https://sts.{region}.amazonaws.com?Action=GetCallerIdentity&Version=2011-06-15' }; -/** - * @deprecated AWS client no validates the EC2 metadata address. - **/ -AwsClient.AWS_EC2_METADATA_IPV4_ADDRESS = '169.254.169.254'; -/** - * @deprecated AWS client no validates the EC2 metadata address. - **/ -AwsClient.AWS_EC2_METADATA_IPV6_ADDRESS = 'fd00:ec2::254'; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js deleted file mode 100644 index 882a9a91..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/awsrequestsigner.js +++ /dev/null @@ -1,209 +0,0 @@ -"use strict"; -// Copyright 2021 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.AwsRequestSigner = void 0; -const crypto_1 = require("../crypto/crypto"); -/** AWS Signature Version 4 signing algorithm identifier. */ -const AWS_ALGORITHM = 'AWS4-HMAC-SHA256'; -/** - * The termination string for the AWS credential scope value as defined in - * https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html - */ -const AWS_REQUEST_TYPE = 'aws4_request'; -/** - * Implements an AWS API request signer based on the AWS Signature Version 4 - * signing process. - * https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html - */ -class AwsRequestSigner { - /** - * Instantiates an AWS API request signer used to send authenticated signed - * requests to AWS APIs based on the AWS Signature Version 4 signing process. - * This also provides a mechanism to generate the signed request without - * sending it. - * @param getCredentials A mechanism to retrieve AWS security credentials - * when needed. - * @param region The AWS region to use. - */ - constructor(getCredentials, region) { - this.getCredentials = getCredentials; - this.region = region; - this.crypto = (0, crypto_1.createCrypto)(); - } - /** - * Generates the signed request for the provided HTTP request for calling - * an AWS API. This follows the steps described at: - * https://docs.aws.amazon.com/general/latest/gr/sigv4_signing.html - * @param amzOptions The AWS request options that need to be signed. - * @return A promise that resolves with the GaxiosOptions containing the - * signed HTTP request parameters. - */ - async getRequestOptions(amzOptions) { - if (!amzOptions.url) { - throw new Error('"url" is required in "amzOptions"'); - } - // Stringify JSON requests. This will be set in the request body of the - // generated signed request. - const requestPayloadData = typeof amzOptions.data === 'object' - ? JSON.stringify(amzOptions.data) - : amzOptions.data; - const url = amzOptions.url; - const method = amzOptions.method || 'GET'; - const requestPayload = amzOptions.body || requestPayloadData; - const additionalAmzHeaders = amzOptions.headers; - const awsSecurityCredentials = await this.getCredentials(); - const uri = new URL(url); - const headerMap = await generateAuthenticationHeaderMap({ - crypto: this.crypto, - host: uri.host, - canonicalUri: uri.pathname, - canonicalQuerystring: uri.search.substr(1), - method, - region: this.region, - securityCredentials: awsSecurityCredentials, - requestPayload, - additionalAmzHeaders, - }); - // Append additional optional headers, eg. X-Amz-Target, Content-Type, etc. - const headers = Object.assign( - // Add x-amz-date if available. - headerMap.amzDate ? { 'x-amz-date': headerMap.amzDate } : {}, { - Authorization: headerMap.authorizationHeader, - host: uri.host, - }, additionalAmzHeaders || {}); - if (awsSecurityCredentials.token) { - Object.assign(headers, { - 'x-amz-security-token': awsSecurityCredentials.token, - }); - } - const awsSignedReq = { - url, - method: method, - headers, - }; - if (typeof requestPayload !== 'undefined') { - awsSignedReq.body = requestPayload; - } - return awsSignedReq; - } -} -exports.AwsRequestSigner = AwsRequestSigner; -/** - * Creates the HMAC-SHA256 hash of the provided message using the - * provided key. - * - * @param crypto The crypto instance used to facilitate cryptographic - * operations. - * @param key The HMAC-SHA256 key to use. - * @param msg The message to hash. - * @return The computed hash bytes. - */ -async function sign(crypto, key, msg) { - return await crypto.signWithHmacSha256(key, msg); -} -/** - * Calculates the signing key used to calculate the signature for - * AWS Signature Version 4 based on: - * https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html - * - * @param crypto The crypto instance used to facilitate cryptographic - * operations. - * @param key The AWS secret access key. - * @param dateStamp The '%Y%m%d' date format. - * @param region The AWS region. - * @param serviceName The AWS service name, eg. sts. - * @return The signing key bytes. - */ -async function getSigningKey(crypto, key, dateStamp, region, serviceName) { - const kDate = await sign(crypto, `AWS4${key}`, dateStamp); - const kRegion = await sign(crypto, kDate, region); - const kService = await sign(crypto, kRegion, serviceName); - const kSigning = await sign(crypto, kService, 'aws4_request'); - return kSigning; -} -/** - * Generates the authentication header map needed for generating the AWS - * Signature Version 4 signed request. - * - * @param option The options needed to compute the authentication header map. - * @return The AWS authentication header map which constitutes of the following - * components: amz-date, authorization header and canonical query string. - */ -async function generateAuthenticationHeaderMap(options) { - const additionalAmzHeaders = options.additionalAmzHeaders || {}; - const requestPayload = options.requestPayload || ''; - // iam.amazonaws.com host => iam service. - // sts.us-east-2.amazonaws.com => sts service. - const serviceName = options.host.split('.')[0]; - const now = new Date(); - // Format: '%Y%m%dT%H%M%SZ'. - const amzDate = now - .toISOString() - .replace(/[-:]/g, '') - .replace(/\.[0-9]+/, ''); - // Format: '%Y%m%d'. - const dateStamp = now.toISOString().replace(/[-]/g, '').replace(/T.*/, ''); - // Change all additional headers to be lower case. - const reformattedAdditionalAmzHeaders = {}; - Object.keys(additionalAmzHeaders).forEach(key => { - reformattedAdditionalAmzHeaders[key.toLowerCase()] = - additionalAmzHeaders[key]; - }); - // Add AWS token if available. - if (options.securityCredentials.token) { - reformattedAdditionalAmzHeaders['x-amz-security-token'] = - options.securityCredentials.token; - } - // Header keys need to be sorted alphabetically. - const amzHeaders = Object.assign({ - host: options.host, - }, - // Previously the date was not fixed with x-amz- and could be provided manually. - // https://github.com/boto/botocore/blob/879f8440a4e9ace5d3cf145ce8b3d5e5ffb892ef/tests/unit/auth/aws4_testsuite/get-header-value-trim.req - reformattedAdditionalAmzHeaders.date ? {} : { 'x-amz-date': amzDate }, reformattedAdditionalAmzHeaders); - let canonicalHeaders = ''; - const signedHeadersList = Object.keys(amzHeaders).sort(); - signedHeadersList.forEach(key => { - canonicalHeaders += `${key}:${amzHeaders[key]}\n`; - }); - const signedHeaders = signedHeadersList.join(';'); - const payloadHash = await options.crypto.sha256DigestHex(requestPayload); - // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-canonical-request.html - const canonicalRequest = `${options.method}\n` + - `${options.canonicalUri}\n` + - `${options.canonicalQuerystring}\n` + - `${canonicalHeaders}\n` + - `${signedHeaders}\n` + - `${payloadHash}`; - const credentialScope = `${dateStamp}/${options.region}/${serviceName}/${AWS_REQUEST_TYPE}`; - // https://docs.aws.amazon.com/general/latest/gr/sigv4-create-string-to-sign.html - const stringToSign = `${AWS_ALGORITHM}\n` + - `${amzDate}\n` + - `${credentialScope}\n` + - (await options.crypto.sha256DigestHex(canonicalRequest)); - // https://docs.aws.amazon.com/general/latest/gr/sigv4-calculate-signature.html - const signingKey = await getSigningKey(options.crypto, options.securityCredentials.secretAccessKey, dateStamp, options.region, serviceName); - const signature = await sign(options.crypto, signingKey, stringToSign); - // https://docs.aws.amazon.com/general/latest/gr/sigv4-add-signature-to-request.html - const authorizationHeader = `${AWS_ALGORITHM} Credential=${options.securityCredentials.accessKeyId}/` + - `${credentialScope}, SignedHeaders=${signedHeaders}, ` + - `Signature=${(0, crypto_1.fromArrayBufferToHex)(signature)}`; - return { - // Do not return x-amz-date if date is available. - amzDate: reformattedAdditionalAmzHeaders.date ? undefined : amzDate, - authorizationHeader, - canonicalQuerystring: options.canonicalQuerystring, - }; -} diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/baseexternalclient.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/baseexternalclient.js deleted file mode 100644 index c39861bf..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/baseexternalclient.js +++ /dev/null @@ -1,468 +0,0 @@ -"use strict"; -// Copyright 2021 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var _BaseExternalAccountClient_instances, _BaseExternalAccountClient_pendingAccessToken, _BaseExternalAccountClient_internalRefreshAccessTokenAsync; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BaseExternalAccountClient = exports.DEFAULT_UNIVERSE = exports.CLOUD_RESOURCE_MANAGER = exports.EXTERNAL_ACCOUNT_TYPE = exports.EXPIRATION_TIME_OFFSET = void 0; -const stream = require("stream"); -const authclient_1 = require("./authclient"); -const sts = require("./stscredentials"); -const util_1 = require("../util"); -/** - * The required token exchange grant_type: rfc8693#section-2.1 - */ -const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange'; -/** - * The requested token exchange requested_token_type: rfc8693#section-2.1 - */ -const STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'; -/** The default OAuth scope to request when none is provided. */ -const DEFAULT_OAUTH_SCOPE = 'https://www.googleapis.com/auth/cloud-platform'; -/** Default impersonated token lifespan in seconds.*/ -const DEFAULT_TOKEN_LIFESPAN = 3600; -/** - * Offset to take into account network delays and server clock skews. - */ -exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000; -/** - * The credentials JSON file type for external account clients. - * There are 3 types of JSON configs: - * 1. authorized_user => Google end user credential - * 2. service_account => Google service account credential - * 3. external_Account => non-GCP service (eg. AWS, Azure, K8s) - */ -exports.EXTERNAL_ACCOUNT_TYPE = 'external_account'; -/** - * Cloud resource manager URL used to retrieve project information. - * - * @deprecated use {@link BaseExternalAccountClient.cloudResourceManagerURL} instead - **/ -exports.CLOUD_RESOURCE_MANAGER = 'https://cloudresourcemanager.googleapis.com/v1/projects/'; -/** The workforce audience pattern. */ -const WORKFORCE_AUDIENCE_PATTERN = '//iam\\.googleapis\\.com/locations/[^/]+/workforcePools/[^/]+/providers/.+'; -const DEFAULT_TOKEN_URL = 'https://sts.{universeDomain}/v1/token'; -// eslint-disable-next-line @typescript-eslint/no-var-requires -const pkg = require('../../../package.json'); -/** - * For backwards compatibility. - */ -var authclient_2 = require("./authclient"); -Object.defineProperty(exports, "DEFAULT_UNIVERSE", { enumerable: true, get: function () { return authclient_2.DEFAULT_UNIVERSE; } }); -/** - * Base external account client. This is used to instantiate AuthClients for - * exchanging external account credentials for GCP access token and authorizing - * requests to GCP APIs. - * The base class implements common logic for exchanging various type of - * external credentials for GCP access token. The logic of determining and - * retrieving the external credential based on the environment and - * credential_source will be left for the subclasses. - */ -class BaseExternalAccountClient extends authclient_1.AuthClient { - /** - * Instantiate a BaseExternalAccountClient instance using the provided JSON - * object loaded from an external account credentials file. - * @param options The external account options object typically loaded - * from the external account JSON credential file. The camelCased options - * are aliases for the snake_cased options. - * @param additionalOptions **DEPRECATED, all options are available in the - * `options` parameter.** Optional additional behavior customization options. - * These currently customize expiration threshold time and whether to retry - * on 401/403 API request errors. - */ - constructor(options, additionalOptions) { - var _a; - super({ ...options, ...additionalOptions }); - _BaseExternalAccountClient_instances.add(this); - /** - * A pending access token request. Used for concurrent calls. - */ - _BaseExternalAccountClient_pendingAccessToken.set(this, null); - const opts = (0, util_1.originalOrCamelOptions)(options); - const type = opts.get('type'); - if (type && type !== exports.EXTERNAL_ACCOUNT_TYPE) { - throw new Error(`Expected "${exports.EXTERNAL_ACCOUNT_TYPE}" type but ` + - `received "${options.type}"`); - } - const clientId = opts.get('client_id'); - const clientSecret = opts.get('client_secret'); - const tokenUrl = (_a = opts.get('token_url')) !== null && _a !== void 0 ? _a : DEFAULT_TOKEN_URL.replace('{universeDomain}', this.universeDomain); - const subjectTokenType = opts.get('subject_token_type'); - const workforcePoolUserProject = opts.get('workforce_pool_user_project'); - const serviceAccountImpersonationUrl = opts.get('service_account_impersonation_url'); - const serviceAccountImpersonation = opts.get('service_account_impersonation'); - const serviceAccountImpersonationLifetime = (0, util_1.originalOrCamelOptions)(serviceAccountImpersonation).get('token_lifetime_seconds'); - this.cloudResourceManagerURL = new URL(opts.get('cloud_resource_manager_url') || - `https://cloudresourcemanager.${this.universeDomain}/v1/projects/`); - if (clientId) { - this.clientAuth = { - confidentialClientType: 'basic', - clientId, - clientSecret, - }; - } - this.stsCredential = new sts.StsCredentials(tokenUrl, this.clientAuth); - this.scopes = opts.get('scopes') || [DEFAULT_OAUTH_SCOPE]; - this.cachedAccessToken = null; - this.audience = opts.get('audience'); - this.subjectTokenType = subjectTokenType; - this.workforcePoolUserProject = workforcePoolUserProject; - const workforceAudiencePattern = new RegExp(WORKFORCE_AUDIENCE_PATTERN); - if (this.workforcePoolUserProject && - !this.audience.match(workforceAudiencePattern)) { - throw new Error('workforcePoolUserProject should not be set for non-workforce pool ' + - 'credentials.'); - } - this.serviceAccountImpersonationUrl = serviceAccountImpersonationUrl; - this.serviceAccountImpersonationLifetime = - serviceAccountImpersonationLifetime; - if (this.serviceAccountImpersonationLifetime) { - this.configLifetimeRequested = true; - } - else { - this.configLifetimeRequested = false; - this.serviceAccountImpersonationLifetime = DEFAULT_TOKEN_LIFESPAN; - } - this.projectNumber = this.getProjectNumber(this.audience); - this.supplierContext = { - audience: this.audience, - subjectTokenType: this.subjectTokenType, - transporter: this.transporter, - }; - } - /** The service account email to be impersonated, if available. */ - getServiceAccountEmail() { - var _a; - if (this.serviceAccountImpersonationUrl) { - if (this.serviceAccountImpersonationUrl.length > 256) { - /** - * Prevents DOS attacks. - * @see {@link https://github.com/googleapis/google-auth-library-nodejs/security/code-scanning/84} - **/ - throw new RangeError(`URL is too long: ${this.serviceAccountImpersonationUrl}`); - } - // Parse email from URL. The formal looks as follows: - // https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/name@project-id.iam.gserviceaccount.com:generateAccessToken - const re = /serviceAccounts\/(?[^:]+):generateAccessToken$/; - const result = re.exec(this.serviceAccountImpersonationUrl); - return ((_a = result === null || result === void 0 ? void 0 : result.groups) === null || _a === void 0 ? void 0 : _a.email) || null; - } - return null; - } - /** - * Provides a mechanism to inject GCP access tokens directly. - * When the provided credential expires, a new credential, using the - * external account options, is retrieved. - * @param credentials The Credentials object to set on the current client. - */ - setCredentials(credentials) { - super.setCredentials(credentials); - this.cachedAccessToken = credentials; - } - /** - * @return A promise that resolves with the current GCP access token - * response. If the current credential is expired, a new one is retrieved. - */ - async getAccessToken() { - // If cached access token is unavailable or expired, force refresh. - if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) { - await this.refreshAccessTokenAsync(); - } - // Return GCP access token in GetAccessTokenResponse format. - return { - token: this.cachedAccessToken.access_token, - res: this.cachedAccessToken.res, - }; - } - /** - * The main authentication interface. It takes an optional url which when - * present is the endpoint being accessed, and returns a Promise which - * resolves with authorization header fields. - * - * The result has the form: - * { Authorization: 'Bearer ' } - */ - async getRequestHeaders() { - const accessTokenResponse = await this.getAccessToken(); - const headers = { - Authorization: `Bearer ${accessTokenResponse.token}`, - }; - return this.addSharedMetadataHeaders(headers); - } - request(opts, callback) { - if (callback) { - this.requestAsync(opts).then(r => callback(null, r), e => { - return callback(e, e.response); - }); - } - else { - return this.requestAsync(opts); - } - } - /** - * @return A promise that resolves with the project ID corresponding to the - * current workload identity pool or current workforce pool if - * determinable. For workforce pool credential, it returns the project ID - * corresponding to the workforcePoolUserProject. - * This is introduced to match the current pattern of using the Auth - * library: - * const projectId = await auth.getProjectId(); - * const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; - * const res = await client.request({ url }); - * The resource may not have permission - * (resourcemanager.projects.get) to call this API or the required - * scopes may not be selected: - * https://cloud.google.com/resource-manager/reference/rest/v1/projects/get#authorization-scopes - */ - async getProjectId() { - const projectNumber = this.projectNumber || this.workforcePoolUserProject; - if (this.projectId) { - // Return previously determined project ID. - return this.projectId; - } - else if (projectNumber) { - // Preferable not to use request() to avoid retrial policies. - const headers = await this.getRequestHeaders(); - const response = await this.transporter.request({ - ...BaseExternalAccountClient.RETRY_CONFIG, - headers, - url: `${this.cloudResourceManagerURL.toString()}${projectNumber}`, - responseType: 'json', - }); - this.projectId = response.data.projectId; - return this.projectId; - } - return null; - } - /** - * Authenticates the provided HTTP request, processes it and resolves with the - * returned response. - * @param opts The HTTP request options. - * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure. - * @return A promise that resolves with the successful response. - */ - async requestAsync(opts, reAuthRetried = false) { - let response; - try { - const requestHeaders = await this.getRequestHeaders(); - opts.headers = opts.headers || {}; - if (requestHeaders && requestHeaders['x-goog-user-project']) { - opts.headers['x-goog-user-project'] = - requestHeaders['x-goog-user-project']; - } - if (requestHeaders && requestHeaders.Authorization) { - opts.headers.Authorization = requestHeaders.Authorization; - } - response = await this.transporter.request(opts); - } - catch (e) { - const res = e.response; - if (res) { - const statusCode = res.status; - // Retry the request for metadata if the following criteria are true: - // - We haven't already retried. It only makes sense to retry once. - // - The response was a 401 or a 403 - // - The request didn't send a readableStream - // - forceRefreshOnFailure is true - const isReadableStream = res.config.data instanceof stream.Readable; - const isAuthErr = statusCode === 401 || statusCode === 403; - if (!reAuthRetried && - isAuthErr && - !isReadableStream && - this.forceRefreshOnFailure) { - await this.refreshAccessTokenAsync(); - return await this.requestAsync(opts, true); - } - } - throw e; - } - return response; - } - /** - * Forces token refresh, even if unexpired tokens are currently cached. - * External credentials are exchanged for GCP access tokens via the token - * exchange endpoint and other settings provided in the client options - * object. - * If the service_account_impersonation_url is provided, an additional - * step to exchange the external account GCP access token for a service - * account impersonated token is performed. - * @return A promise that resolves with the fresh GCP access tokens. - */ - async refreshAccessTokenAsync() { - // Use an existing access token request, or cache a new one - __classPrivateFieldSet(this, _BaseExternalAccountClient_pendingAccessToken, __classPrivateFieldGet(this, _BaseExternalAccountClient_pendingAccessToken, "f") || __classPrivateFieldGet(this, _BaseExternalAccountClient_instances, "m", _BaseExternalAccountClient_internalRefreshAccessTokenAsync).call(this), "f"); - try { - return await __classPrivateFieldGet(this, _BaseExternalAccountClient_pendingAccessToken, "f"); - } - finally { - // clear pending access token for future requests - __classPrivateFieldSet(this, _BaseExternalAccountClient_pendingAccessToken, null, "f"); - } - } - /** - * Returns the workload identity pool project number if it is determinable - * from the audience resource name. - * @param audience The STS audience used to determine the project number. - * @return The project number associated with the workload identity pool, if - * this can be determined from the STS audience field. Otherwise, null is - * returned. - */ - getProjectNumber(audience) { - // STS audience pattern: - // //iam.googleapis.com/projects/$PROJECT_NUMBER/locations/... - const match = audience.match(/\/projects\/([^/]+)/); - if (!match) { - return null; - } - return match[1]; - } - /** - * Exchanges an external account GCP access token for a service - * account impersonated access token using iamcredentials - * GenerateAccessToken API. - * @param token The access token to exchange for a service account access - * token. - * @return A promise that resolves with the service account impersonated - * credentials response. - */ - async getImpersonatedAccessToken(token) { - const opts = { - ...BaseExternalAccountClient.RETRY_CONFIG, - url: this.serviceAccountImpersonationUrl, - method: 'POST', - headers: { - 'Content-Type': 'application/json', - Authorization: `Bearer ${token}`, - }, - data: { - scope: this.getScopesArray(), - lifetime: this.serviceAccountImpersonationLifetime + 's', - }, - responseType: 'json', - }; - const response = await this.transporter.request(opts); - const successResponse = response.data; - return { - access_token: successResponse.accessToken, - // Convert from ISO format to timestamp. - expiry_date: new Date(successResponse.expireTime).getTime(), - res: response, - }; - } - /** - * Returns whether the provided credentials are expired or not. - * If there is no expiry time, assumes the token is not expired or expiring. - * @param accessToken The credentials to check for expiration. - * @return Whether the credentials are expired or not. - */ - isExpired(accessToken) { - const now = new Date().getTime(); - return accessToken.expiry_date - ? now >= accessToken.expiry_date - this.eagerRefreshThresholdMillis - : false; - } - /** - * @return The list of scopes for the requested GCP access token. - */ - getScopesArray() { - // Since scopes can be provided as string or array, the type should - // be normalized. - if (typeof this.scopes === 'string') { - return [this.scopes]; - } - return this.scopes || [DEFAULT_OAUTH_SCOPE]; - } - getMetricsHeaderValue() { - const nodeVersion = process.version.replace(/^v/, ''); - const saImpersonation = this.serviceAccountImpersonationUrl !== undefined; - const credentialSourceType = this.credentialSourceType - ? this.credentialSourceType - : 'unknown'; - return `gl-node/${nodeVersion} auth/${pkg.version} google-byoid-sdk source/${credentialSourceType} sa-impersonation/${saImpersonation} config-lifetime/${this.configLifetimeRequested}`; - } -} -exports.BaseExternalAccountClient = BaseExternalAccountClient; -_BaseExternalAccountClient_pendingAccessToken = new WeakMap(), _BaseExternalAccountClient_instances = new WeakSet(), _BaseExternalAccountClient_internalRefreshAccessTokenAsync = async function _BaseExternalAccountClient_internalRefreshAccessTokenAsync() { - // Retrieve the external credential. - const subjectToken = await this.retrieveSubjectToken(); - // Construct the STS credentials options. - const stsCredentialsOptions = { - grantType: STS_GRANT_TYPE, - audience: this.audience, - requestedTokenType: STS_REQUEST_TOKEN_TYPE, - subjectToken, - subjectTokenType: this.subjectTokenType, - // generateAccessToken requires the provided access token to have - // scopes: - // https://www.googleapis.com/auth/iam or - // https://www.googleapis.com/auth/cloud-platform - // The new service account access token scopes will match the user - // provided ones. - scope: this.serviceAccountImpersonationUrl - ? [DEFAULT_OAUTH_SCOPE] - : this.getScopesArray(), - }; - // Exchange the external credentials for a GCP access token. - // Client auth is prioritized over passing the workforcePoolUserProject - // parameter for STS token exchange. - const additionalOptions = !this.clientAuth && this.workforcePoolUserProject - ? { userProject: this.workforcePoolUserProject } - : undefined; - const additionalHeaders = { - 'x-goog-api-client': this.getMetricsHeaderValue(), - }; - const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, additionalHeaders, additionalOptions); - if (this.serviceAccountImpersonationUrl) { - this.cachedAccessToken = await this.getImpersonatedAccessToken(stsResponse.access_token); - } - else if (stsResponse.expires_in) { - // Save response in cached access token. - this.cachedAccessToken = { - access_token: stsResponse.access_token, - expiry_date: new Date().getTime() + stsResponse.expires_in * 1000, - res: stsResponse.res, - }; - } - else { - // Save response in cached access token. - this.cachedAccessToken = { - access_token: stsResponse.access_token, - res: stsResponse.res, - }; - } - // Save credentials. - this.credentials = {}; - Object.assign(this.credentials, this.cachedAccessToken); - delete this.credentials.res; - // Trigger tokens event to notify external listeners. - this.emit('tokens', { - refresh_token: null, - expiry_date: this.cachedAccessToken.expiry_date, - access_token: this.cachedAccessToken.access_token, - token_type: 'Bearer', - id_token: null, - }); - // Return the cached access token. - return this.cachedAccessToken; -}; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/computeclient.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/computeclient.js deleted file mode 100644 index 4554e03e..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/computeclient.js +++ /dev/null @@ -1,117 +0,0 @@ -"use strict"; -// Copyright 2013 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Compute = void 0; -const gaxios_1 = require("gaxios"); -const gcpMetadata = require("gcp-metadata"); -const oauth2client_1 = require("./oauth2client"); -class Compute extends oauth2client_1.OAuth2Client { - /** - * Google Compute Engine service account credentials. - * - * Retrieve access token from the metadata server. - * See: https://cloud.google.com/compute/docs/access/authenticate-workloads#applications - */ - constructor(options = {}) { - super(options); - // Start with an expired refresh token, which will automatically be - // refreshed before the first API call is made. - this.credentials = { expiry_date: 1, refresh_token: 'compute-placeholder' }; - this.serviceAccountEmail = options.serviceAccountEmail || 'default'; - this.scopes = Array.isArray(options.scopes) - ? options.scopes - : options.scopes - ? [options.scopes] - : []; - } - /** - * Refreshes the access token. - * @param refreshToken Unused parameter - */ - async refreshTokenNoCache( - // eslint-disable-next-line @typescript-eslint/no-unused-vars - refreshToken) { - const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`; - let data; - try { - const instanceOptions = { - property: tokenPath, - }; - if (this.scopes.length > 0) { - instanceOptions.params = { - scopes: this.scopes.join(','), - }; - } - data = await gcpMetadata.instance(instanceOptions); - } - catch (e) { - if (e instanceof gaxios_1.GaxiosError) { - e.message = `Could not refresh access token: ${e.message}`; - this.wrapError(e); - } - throw e; - } - const tokens = data; - if (data && data.expires_in) { - tokens.expiry_date = new Date().getTime() + data.expires_in * 1000; - delete tokens.expires_in; - } - this.emit('tokens', tokens); - return { tokens, res: null }; - } - /** - * Fetches an ID token. - * @param targetAudience the audience for the fetched ID token. - */ - async fetchIdToken(targetAudience) { - const idTokenPath = `service-accounts/${this.serviceAccountEmail}/identity` + - `?format=full&audience=${targetAudience}`; - let idToken; - try { - const instanceOptions = { - property: idTokenPath, - }; - idToken = await gcpMetadata.instance(instanceOptions); - } - catch (e) { - if (e instanceof Error) { - e.message = `Could not fetch ID token: ${e.message}`; - } - throw e; - } - return idToken; - } - wrapError(e) { - const res = e.response; - if (res && res.status) { - e.status = res.status; - if (res.status === 403) { - e.message = - 'A Forbidden error was returned while attempting to retrieve an access ' + - 'token for the Compute Engine built-in service account. This may be because the Compute ' + - 'Engine instance does not have the correct permission scopes specified: ' + - e.message; - } - else if (res.status === 404) { - e.message = - 'A Not Found error was returned while attempting to retrieve an access' + - 'token for the Compute Engine built-in service account. This may be because the Compute ' + - 'Engine instance does not have any permission scopes specified: ' + - e.message; - } - } - } -} -exports.Compute = Compute; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js deleted file mode 100644 index 83d95bc3..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/defaultawssecuritycredentialssupplier.js +++ /dev/null @@ -1,196 +0,0 @@ -"use strict"; -// Copyright 2024 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var _DefaultAwsSecurityCredentialsSupplier_instances, _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken, _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName, _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials, _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get, _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DefaultAwsSecurityCredentialsSupplier = void 0; -/** - * Internal AWS security credentials supplier implementation used by {@link AwsClient} - * when a credential source is provided instead of a user defined supplier. - * The logic is summarized as: - * 1. If imdsv2_session_token_url is provided in the credential source, then - * fetch the aws session token and include it in the headers of the - * metadata requests. This is a requirement for IDMSv2 but optional - * for IDMSv1. - * 2. Retrieve AWS region from availability-zone. - * 3a. Check AWS credentials in environment variables. If not found, get - * from security-credentials endpoint. - * 3b. Get AWS credentials from security-credentials endpoint. In order - * to retrieve this, the AWS role needs to be determined by calling - * security-credentials endpoint without any argument. Then the - * credentials can be retrieved via: security-credentials/role_name - * 4. Generate the signed request to AWS STS GetCallerIdentity action. - * 5. Inject x-goog-cloud-target-resource into header and serialize the - * signed request. This will be the subject-token to pass to GCP STS. - */ -class DefaultAwsSecurityCredentialsSupplier { - /** - * Instantiates a new DefaultAwsSecurityCredentialsSupplier using information - * from the credential_source stored in the ADC file. - * @param opts The default aws security credentials supplier options object to - * build the supplier with. - */ - constructor(opts) { - _DefaultAwsSecurityCredentialsSupplier_instances.add(this); - this.regionUrl = opts.regionUrl; - this.securityCredentialsUrl = opts.securityCredentialsUrl; - this.imdsV2SessionTokenUrl = opts.imdsV2SessionTokenUrl; - this.additionalGaxiosOptions = opts.additionalGaxiosOptions; - } - /** - * Returns the active AWS region. This first checks to see if the region - * is available as an environment variable. If it is not, then the supplier - * will call the region URL. - * @param context {@link ExternalAccountSupplierContext} from the calling - * {@link AwsClient}, contains the requested audience and subject token type - * for the external account identity. - * @return A promise that resolves with the AWS region string. - */ - async getAwsRegion(context) { - // Priority order for region determination: - // AWS_REGION > AWS_DEFAULT_REGION > metadata server. - if (__classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get)) { - return __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get); - } - const metadataHeaders = {}; - if (!__classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get) && this.imdsV2SessionTokenUrl) { - metadataHeaders['x-aws-ec2-metadata-token'] = - await __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken).call(this, context.transporter); - } - if (!this.regionUrl) { - throw new Error('Unable to determine AWS region due to missing ' + - '"options.credential_source.region_url"'); - } - const opts = { - ...this.additionalGaxiosOptions, - url: this.regionUrl, - method: 'GET', - responseType: 'text', - headers: metadataHeaders, - }; - const response = await context.transporter.request(opts); - // Remove last character. For example, if us-east-2b is returned, - // the region would be us-east-2. - return response.data.substr(0, response.data.length - 1); - } - /** - * Returns AWS security credentials. This first checks to see if the credentials - * is available as environment variables. If it is not, then the supplier - * will call the security credentials URL. - * @param context {@link ExternalAccountSupplierContext} from the calling - * {@link AwsClient}, contains the requested audience and subject token type - * for the external account identity. - * @return A promise that resolves with the AWS security credentials. - */ - async getAwsSecurityCredentials(context) { - // Check environment variables for permanent credentials first. - // https://docs.aws.amazon.com/general/latest/gr/aws-sec-cred-types.html - if (__classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get)) { - return __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "a", _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get); - } - const metadataHeaders = {}; - if (this.imdsV2SessionTokenUrl) { - metadataHeaders['x-aws-ec2-metadata-token'] = - await __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken).call(this, context.transporter); - } - // Since the role on a VM can change, we don't need to cache it. - const roleName = await __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName).call(this, metadataHeaders, context.transporter); - // Temporary credentials typically last for several hours. - // Expiration is returned in response. - // Consider future optimization of this logic to cache AWS tokens - // until their natural expiration. - const awsCreds = await __classPrivateFieldGet(this, _DefaultAwsSecurityCredentialsSupplier_instances, "m", _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials).call(this, roleName, metadataHeaders, context.transporter); - return { - accessKeyId: awsCreds.AccessKeyId, - secretAccessKey: awsCreds.SecretAccessKey, - token: awsCreds.Token, - }; - } -} -exports.DefaultAwsSecurityCredentialsSupplier = DefaultAwsSecurityCredentialsSupplier; -_DefaultAwsSecurityCredentialsSupplier_instances = new WeakSet(), _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken = -/** - * @param transporter The transporter to use for requests. - * @return A promise that resolves with the IMDSv2 Session Token. - */ -async function _DefaultAwsSecurityCredentialsSupplier_getImdsV2SessionToken(transporter) { - const opts = { - ...this.additionalGaxiosOptions, - url: this.imdsV2SessionTokenUrl, - method: 'PUT', - responseType: 'text', - headers: { 'x-aws-ec2-metadata-token-ttl-seconds': '300' }, - }; - const response = await transporter.request(opts); - return response.data; -}, _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName = -/** - * @param headers The headers to be used in the metadata request. - * @param transporter The transporter to use for requests. - * @return A promise that resolves with the assigned role to the current - * AWS VM. This is needed for calling the security-credentials endpoint. - */ -async function _DefaultAwsSecurityCredentialsSupplier_getAwsRoleName(headers, transporter) { - if (!this.securityCredentialsUrl) { - throw new Error('Unable to determine AWS role name due to missing ' + - '"options.credential_source.url"'); - } - const opts = { - ...this.additionalGaxiosOptions, - url: this.securityCredentialsUrl, - method: 'GET', - responseType: 'text', - headers: headers, - }; - const response = await transporter.request(opts); - return response.data; -}, _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials = -/** - * Retrieves the temporary AWS credentials by calling the security-credentials - * endpoint as specified in the `credential_source` object. - * @param roleName The role attached to the current VM. - * @param headers The headers to be used in the metadata request. - * @param transporter The transporter to use for requests. - * @return A promise that resolves with the temporary AWS credentials - * needed for creating the GetCallerIdentity signed request. - */ -async function _DefaultAwsSecurityCredentialsSupplier_retrieveAwsSecurityCredentials(roleName, headers, transporter) { - const response = await transporter.request({ - ...this.additionalGaxiosOptions, - url: `${this.securityCredentialsUrl}/${roleName}`, - responseType: 'json', - headers: headers, - }); - return response.data; -}, _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get = function _DefaultAwsSecurityCredentialsSupplier_regionFromEnv_get() { - // The AWS region can be provided through AWS_REGION or AWS_DEFAULT_REGION. - // Only one is required. - return (process.env['AWS_REGION'] || process.env['AWS_DEFAULT_REGION'] || null); -}, _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get = function _DefaultAwsSecurityCredentialsSupplier_securityCredentialsFromEnv_get() { - // Both AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY are required. - if (process.env['AWS_ACCESS_KEY_ID'] && - process.env['AWS_SECRET_ACCESS_KEY']) { - return { - accessKeyId: process.env['AWS_ACCESS_KEY_ID'], - secretAccessKey: process.env['AWS_SECRET_ACCESS_KEY'], - token: process.env['AWS_SESSION_TOKEN'], - }; - } - return null; -}; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/downscopedclient.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/downscopedclient.js deleted file mode 100644 index 92529742..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/downscopedclient.js +++ /dev/null @@ -1,262 +0,0 @@ -"use strict"; -// Copyright 2021 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DownscopedClient = exports.EXPIRATION_TIME_OFFSET = exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = void 0; -const stream = require("stream"); -const authclient_1 = require("./authclient"); -const sts = require("./stscredentials"); -/** - * The required token exchange grant_type: rfc8693#section-2.1 - */ -const STS_GRANT_TYPE = 'urn:ietf:params:oauth:grant-type:token-exchange'; -/** - * The requested token exchange requested_token_type: rfc8693#section-2.1 - */ -const STS_REQUEST_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'; -/** - * The requested token exchange subject_token_type: rfc8693#section-2.1 - */ -const STS_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token'; -/** - * The maximum number of access boundary rules a Credential Access Boundary - * can contain. - */ -exports.MAX_ACCESS_BOUNDARY_RULES_COUNT = 10; -/** - * Offset to take into account network delays and server clock skews. - */ -exports.EXPIRATION_TIME_OFFSET = 5 * 60 * 1000; -/** - * Defines a set of Google credentials that are downscoped from an existing set - * of Google OAuth2 credentials. This is useful to restrict the Identity and - * Access Management (IAM) permissions that a short-lived credential can use. - * The common pattern of usage is to have a token broker with elevated access - * generate these downscoped credentials from higher access source credentials - * and pass the downscoped short-lived access tokens to a token consumer via - * some secure authenticated channel for limited access to Google Cloud Storage - * resources. - */ -class DownscopedClient extends authclient_1.AuthClient { - /** - * Instantiates a downscoped client object using the provided source - * AuthClient and credential access boundary rules. - * To downscope permissions of a source AuthClient, a Credential Access - * Boundary that specifies which resources the new credential can access, as - * well as an upper bound on the permissions that are available on each - * resource, has to be defined. A downscoped client can then be instantiated - * using the source AuthClient and the Credential Access Boundary. - * @param authClient The source AuthClient to be downscoped based on the - * provided Credential Access Boundary rules. - * @param credentialAccessBoundary The Credential Access Boundary which - * contains a list of access boundary rules. Each rule contains information - * on the resource that the rule applies to, the upper bound of the - * permissions that are available on that resource and an optional - * condition to further restrict permissions. - * @param additionalOptions **DEPRECATED, set this in the provided `authClient`.** - * Optional additional behavior customization options. - * @param quotaProjectId **DEPRECATED, set this in the provided `authClient`.** - * Optional quota project id for setting up in the x-goog-user-project header. - */ - constructor(authClient, credentialAccessBoundary, additionalOptions, quotaProjectId) { - super({ ...additionalOptions, quotaProjectId }); - this.authClient = authClient; - this.credentialAccessBoundary = credentialAccessBoundary; - // Check 1-10 Access Boundary Rules are defined within Credential Access - // Boundary. - if (credentialAccessBoundary.accessBoundary.accessBoundaryRules.length === 0) { - throw new Error('At least one access boundary rule needs to be defined.'); - } - else if (credentialAccessBoundary.accessBoundary.accessBoundaryRules.length > - exports.MAX_ACCESS_BOUNDARY_RULES_COUNT) { - throw new Error('The provided access boundary has more than ' + - `${exports.MAX_ACCESS_BOUNDARY_RULES_COUNT} access boundary rules.`); - } - // Check at least one permission should be defined in each Access Boundary - // Rule. - for (const rule of credentialAccessBoundary.accessBoundary - .accessBoundaryRules) { - if (rule.availablePermissions.length === 0) { - throw new Error('At least one permission should be defined in access boundary rules.'); - } - } - this.stsCredential = new sts.StsCredentials(`https://sts.${this.universeDomain}/v1/token`); - this.cachedDownscopedAccessToken = null; - } - /** - * Provides a mechanism to inject Downscoped access tokens directly. - * The expiry_date field is required to facilitate determination of the token - * expiration which would make it easier for the token consumer to handle. - * @param credentials The Credentials object to set on the current client. - */ - setCredentials(credentials) { - if (!credentials.expiry_date) { - throw new Error('The access token expiry_date field is missing in the provided ' + - 'credentials.'); - } - super.setCredentials(credentials); - this.cachedDownscopedAccessToken = credentials; - } - async getAccessToken() { - // If the cached access token is unavailable or expired, force refresh. - // The Downscoped access token will be returned in - // DownscopedAccessTokenResponse format. - if (!this.cachedDownscopedAccessToken || - this.isExpired(this.cachedDownscopedAccessToken)) { - await this.refreshAccessTokenAsync(); - } - // Return Downscoped access token in DownscopedAccessTokenResponse format. - return { - token: this.cachedDownscopedAccessToken.access_token, - expirationTime: this.cachedDownscopedAccessToken.expiry_date, - res: this.cachedDownscopedAccessToken.res, - }; - } - /** - * The main authentication interface. It takes an optional url which when - * present is the endpoint being accessed, and returns a Promise which - * resolves with authorization header fields. - * - * The result has the form: - * { Authorization: 'Bearer ' } - */ - async getRequestHeaders() { - const accessTokenResponse = await this.getAccessToken(); - const headers = { - Authorization: `Bearer ${accessTokenResponse.token}`, - }; - return this.addSharedMetadataHeaders(headers); - } - request(opts, callback) { - if (callback) { - this.requestAsync(opts).then(r => callback(null, r), e => { - return callback(e, e.response); - }); - } - else { - return this.requestAsync(opts); - } - } - /** - * Authenticates the provided HTTP request, processes it and resolves with the - * returned response. - * @param opts The HTTP request options. - * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure - * @return A promise that resolves with the successful response. - */ - async requestAsync(opts, reAuthRetried = false) { - let response; - try { - const requestHeaders = await this.getRequestHeaders(); - opts.headers = opts.headers || {}; - if (requestHeaders && requestHeaders['x-goog-user-project']) { - opts.headers['x-goog-user-project'] = - requestHeaders['x-goog-user-project']; - } - if (requestHeaders && requestHeaders.Authorization) { - opts.headers.Authorization = requestHeaders.Authorization; - } - response = await this.transporter.request(opts); - } - catch (e) { - const res = e.response; - if (res) { - const statusCode = res.status; - // Retry the request for metadata if the following criteria are true: - // - We haven't already retried. It only makes sense to retry once. - // - The response was a 401 or a 403 - // - The request didn't send a readableStream - // - forceRefreshOnFailure is true - const isReadableStream = res.config.data instanceof stream.Readable; - const isAuthErr = statusCode === 401 || statusCode === 403; - if (!reAuthRetried && - isAuthErr && - !isReadableStream && - this.forceRefreshOnFailure) { - await this.refreshAccessTokenAsync(); - return await this.requestAsync(opts, true); - } - } - throw e; - } - return response; - } - /** - * Forces token refresh, even if unexpired tokens are currently cached. - * GCP access tokens are retrieved from authclient object/source credential. - * Then GCP access tokens are exchanged for downscoped access tokens via the - * token exchange endpoint. - * @return A promise that resolves with the fresh downscoped access token. - */ - async refreshAccessTokenAsync() { - var _a; - // Retrieve GCP access token from source credential. - const subjectToken = (await this.authClient.getAccessToken()).token; - // Construct the STS credentials options. - const stsCredentialsOptions = { - grantType: STS_GRANT_TYPE, - requestedTokenType: STS_REQUEST_TOKEN_TYPE, - subjectToken: subjectToken, - subjectTokenType: STS_SUBJECT_TOKEN_TYPE, - }; - // Exchange the source AuthClient access token for a Downscoped access - // token. - const stsResponse = await this.stsCredential.exchangeToken(stsCredentialsOptions, undefined, this.credentialAccessBoundary); - /** - * The STS endpoint will only return the expiration time for the downscoped - * access token if the original access token represents a service account. - * The downscoped token's expiration time will always match the source - * credential expiration. When no expires_in is returned, we can copy the - * source credential's expiration time. - */ - const sourceCredExpireDate = ((_a = this.authClient.credentials) === null || _a === void 0 ? void 0 : _a.expiry_date) || null; - const expiryDate = stsResponse.expires_in - ? new Date().getTime() + stsResponse.expires_in * 1000 - : sourceCredExpireDate; - // Save response in cached access token. - this.cachedDownscopedAccessToken = { - access_token: stsResponse.access_token, - expiry_date: expiryDate, - res: stsResponse.res, - }; - // Save credentials. - this.credentials = {}; - Object.assign(this.credentials, this.cachedDownscopedAccessToken); - delete this.credentials.res; - // Trigger tokens event to notify external listeners. - this.emit('tokens', { - refresh_token: null, - expiry_date: this.cachedDownscopedAccessToken.expiry_date, - access_token: this.cachedDownscopedAccessToken.access_token, - token_type: 'Bearer', - id_token: null, - }); - // Return the cached access token. - return this.cachedDownscopedAccessToken; - } - /** - * Returns whether the provided credentials are expired or not. - * If there is no expiry time, assumes the token is not expired or expiring. - * @param downscopedAccessToken The credentials to check for expiration. - * @return Whether the credentials are expired or not. - */ - isExpired(downscopedAccessToken) { - const now = new Date().getTime(); - return downscopedAccessToken.expiry_date - ? now >= - downscopedAccessToken.expiry_date - this.eagerRefreshThresholdMillis - : false; - } -} -exports.DownscopedClient = DownscopedClient; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/envDetect.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/envDetect.js deleted file mode 100644 index 73fb915c..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/envDetect.js +++ /dev/null @@ -1,89 +0,0 @@ -"use strict"; -// Copyright 2018 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.GCPEnv = void 0; -exports.clear = clear; -exports.getEnv = getEnv; -const gcpMetadata = require("gcp-metadata"); -var GCPEnv; -(function (GCPEnv) { - GCPEnv["APP_ENGINE"] = "APP_ENGINE"; - GCPEnv["KUBERNETES_ENGINE"] = "KUBERNETES_ENGINE"; - GCPEnv["CLOUD_FUNCTIONS"] = "CLOUD_FUNCTIONS"; - GCPEnv["COMPUTE_ENGINE"] = "COMPUTE_ENGINE"; - GCPEnv["CLOUD_RUN"] = "CLOUD_RUN"; - GCPEnv["NONE"] = "NONE"; -})(GCPEnv || (exports.GCPEnv = GCPEnv = {})); -let envPromise; -function clear() { - envPromise = undefined; -} -async function getEnv() { - if (envPromise) { - return envPromise; - } - envPromise = getEnvMemoized(); - return envPromise; -} -async function getEnvMemoized() { - let env = GCPEnv.NONE; - if (isAppEngine()) { - env = GCPEnv.APP_ENGINE; - } - else if (isCloudFunction()) { - env = GCPEnv.CLOUD_FUNCTIONS; - } - else if (await isComputeEngine()) { - if (await isKubernetesEngine()) { - env = GCPEnv.KUBERNETES_ENGINE; - } - else if (isCloudRun()) { - env = GCPEnv.CLOUD_RUN; - } - else { - env = GCPEnv.COMPUTE_ENGINE; - } - } - else { - env = GCPEnv.NONE; - } - return env; -} -function isAppEngine() { - return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME); -} -function isCloudFunction() { - return !!(process.env.FUNCTION_NAME || process.env.FUNCTION_TARGET); -} -/** - * This check only verifies that the environment is running knative. - * This must be run *after* checking for Kubernetes, otherwise it will - * return a false positive. - */ -function isCloudRun() { - return !!process.env.K_CONFIGURATION; -} -async function isKubernetesEngine() { - try { - await gcpMetadata.instance('attributes/cluster-name'); - return true; - } - catch (e) { - return false; - } -} -async function isComputeEngine() { - return gcpMetadata.isAvailable(); -} diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/executable-response.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/executable-response.js deleted file mode 100644 index be4e818c..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/executable-response.js +++ /dev/null @@ -1,146 +0,0 @@ -"use strict"; -// Copyright 2022 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.InvalidSubjectTokenError = exports.InvalidMessageFieldError = exports.InvalidCodeFieldError = exports.InvalidTokenTypeFieldError = exports.InvalidExpirationTimeFieldError = exports.InvalidSuccessFieldError = exports.InvalidVersionFieldError = exports.ExecutableResponseError = exports.ExecutableResponse = void 0; -const SAML_SUBJECT_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:saml2'; -const OIDC_SUBJECT_TOKEN_TYPE1 = 'urn:ietf:params:oauth:token-type:id_token'; -const OIDC_SUBJECT_TOKEN_TYPE2 = 'urn:ietf:params:oauth:token-type:jwt'; -/** - * Defines the response of a 3rd party executable run by the pluggable auth client. - */ -class ExecutableResponse { - /** - * Instantiates an ExecutableResponse instance using the provided JSON object - * from the output of the executable. - * @param responseJson Response from a 3rd party executable, loaded from a - * run of the executable or a cached output file. - */ - constructor(responseJson) { - // Check that the required fields exist in the json response. - if (!responseJson.version) { - throw new InvalidVersionFieldError("Executable response must contain a 'version' field."); - } - if (responseJson.success === undefined) { - throw new InvalidSuccessFieldError("Executable response must contain a 'success' field."); - } - this.version = responseJson.version; - this.success = responseJson.success; - // Validate required fields for a successful response. - if (this.success) { - this.expirationTime = responseJson.expiration_time; - this.tokenType = responseJson.token_type; - // Validate token type field. - if (this.tokenType !== SAML_SUBJECT_TOKEN_TYPE && - this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE1 && - this.tokenType !== OIDC_SUBJECT_TOKEN_TYPE2) { - throw new InvalidTokenTypeFieldError("Executable response must contain a 'token_type' field when successful " + - `and it must be one of ${OIDC_SUBJECT_TOKEN_TYPE1}, ${OIDC_SUBJECT_TOKEN_TYPE2}, or ${SAML_SUBJECT_TOKEN_TYPE}.`); - } - // Validate subject token. - if (this.tokenType === SAML_SUBJECT_TOKEN_TYPE) { - if (!responseJson.saml_response) { - throw new InvalidSubjectTokenError(`Executable response must contain a 'saml_response' field when token_type=${SAML_SUBJECT_TOKEN_TYPE}.`); - } - this.subjectToken = responseJson.saml_response; - } - else { - if (!responseJson.id_token) { - throw new InvalidSubjectTokenError("Executable response must contain a 'id_token' field when " + - `token_type=${OIDC_SUBJECT_TOKEN_TYPE1} or ${OIDC_SUBJECT_TOKEN_TYPE2}.`); - } - this.subjectToken = responseJson.id_token; - } - } - else { - // Both code and message must be provided for unsuccessful responses. - if (!responseJson.code) { - throw new InvalidCodeFieldError("Executable response must contain a 'code' field when unsuccessful."); - } - if (!responseJson.message) { - throw new InvalidMessageFieldError("Executable response must contain a 'message' field when unsuccessful."); - } - this.errorCode = responseJson.code; - this.errorMessage = responseJson.message; - } - } - /** - * @return A boolean representing if the response has a valid token. Returns - * true when the response was successful and the token is not expired. - */ - isValid() { - return !this.isExpired() && this.success; - } - /** - * @return A boolean representing if the response is expired. Returns true if the - * provided timeout has passed. - */ - isExpired() { - return (this.expirationTime !== undefined && - this.expirationTime < Math.round(Date.now() / 1000)); - } -} -exports.ExecutableResponse = ExecutableResponse; -/** - * An error thrown by the ExecutableResponse class. - */ -class ExecutableResponseError extends Error { - constructor(message) { - super(message); - Object.setPrototypeOf(this, new.target.prototype); - } -} -exports.ExecutableResponseError = ExecutableResponseError; -/** - * An error thrown when the 'version' field in an executable response is missing or invalid. - */ -class InvalidVersionFieldError extends ExecutableResponseError { -} -exports.InvalidVersionFieldError = InvalidVersionFieldError; -/** - * An error thrown when the 'success' field in an executable response is missing or invalid. - */ -class InvalidSuccessFieldError extends ExecutableResponseError { -} -exports.InvalidSuccessFieldError = InvalidSuccessFieldError; -/** - * An error thrown when the 'expiration_time' field in an executable response is missing or invalid. - */ -class InvalidExpirationTimeFieldError extends ExecutableResponseError { -} -exports.InvalidExpirationTimeFieldError = InvalidExpirationTimeFieldError; -/** - * An error thrown when the 'token_type' field in an executable response is missing or invalid. - */ -class InvalidTokenTypeFieldError extends ExecutableResponseError { -} -exports.InvalidTokenTypeFieldError = InvalidTokenTypeFieldError; -/** - * An error thrown when the 'code' field in an executable response is missing or invalid. - */ -class InvalidCodeFieldError extends ExecutableResponseError { -} -exports.InvalidCodeFieldError = InvalidCodeFieldError; -/** - * An error thrown when the 'message' field in an executable response is missing or invalid. - */ -class InvalidMessageFieldError extends ExecutableResponseError { -} -exports.InvalidMessageFieldError = InvalidMessageFieldError; -/** - * An error thrown when the subject token in an executable response is missing or invalid. - */ -class InvalidSubjectTokenError extends ExecutableResponseError { -} -exports.InvalidSubjectTokenError = InvalidSubjectTokenError; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js deleted file mode 100644 index b7147a3d..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/externalAccountAuthorizedUserClient.js +++ /dev/null @@ -1,239 +0,0 @@ -"use strict"; -// Copyright 2023 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ExternalAccountAuthorizedUserClient = exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = void 0; -const authclient_1 = require("./authclient"); -const oauth2common_1 = require("./oauth2common"); -const gaxios_1 = require("gaxios"); -const stream = require("stream"); -const baseexternalclient_1 = require("./baseexternalclient"); -/** - * The credentials JSON file type for external account authorized user clients. - */ -exports.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE = 'external_account_authorized_user'; -const DEFAULT_TOKEN_URL = 'https://sts.{universeDomain}/v1/oauthtoken'; -/** - * Handler for token refresh requests sent to the token_url endpoint for external - * authorized user credentials. - */ -class ExternalAccountAuthorizedUserHandler extends oauth2common_1.OAuthClientAuthHandler { - /** - * Initializes an ExternalAccountAuthorizedUserHandler instance. - * @param url The URL of the token refresh endpoint. - * @param transporter The transporter to use for the refresh request. - * @param clientAuthentication The client authentication credentials to use - * for the refresh request. - */ - constructor(url, transporter, clientAuthentication) { - super(clientAuthentication); - this.url = url; - this.transporter = transporter; - } - /** - * Requests a new access token from the token_url endpoint using the provided - * refresh token. - * @param refreshToken The refresh token to use to generate a new access token. - * @param additionalHeaders Optional additional headers to pass along the - * request. - * @return A promise that resolves with the token refresh response containing - * the requested access token and its expiration time. - */ - async refreshToken(refreshToken, additionalHeaders) { - const values = new URLSearchParams({ - grant_type: 'refresh_token', - refresh_token: refreshToken, - }); - const headers = { - 'Content-Type': 'application/x-www-form-urlencoded', - ...additionalHeaders, - }; - const opts = { - ...ExternalAccountAuthorizedUserHandler.RETRY_CONFIG, - url: this.url, - method: 'POST', - headers, - data: values.toString(), - responseType: 'json', - }; - // Apply OAuth client authentication. - this.applyClientAuthenticationOptions(opts); - try { - const response = await this.transporter.request(opts); - // Successful response. - const tokenRefreshResponse = response.data; - tokenRefreshResponse.res = response; - return tokenRefreshResponse; - } - catch (error) { - // Translate error to OAuthError. - if (error instanceof gaxios_1.GaxiosError && error.response) { - throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, - // Preserve other fields from the original error. - error); - } - // Request could fail before the server responds. - throw error; - } - } -} -/** - * External Account Authorized User Client. This is used for OAuth2 credentials - * sourced using external identities through Workforce Identity Federation. - * Obtaining the initial access and refresh token can be done through the - * Google Cloud CLI. - */ -class ExternalAccountAuthorizedUserClient extends authclient_1.AuthClient { - /** - * Instantiates an ExternalAccountAuthorizedUserClient instances using the - * provided JSON object loaded from a credentials files. - * An error is throws if the credential is not valid. - * @param options The external account authorized user option object typically - * from the external accoutn authorized user JSON credential file. - * @param additionalOptions **DEPRECATED, all options are available in the - * `options` parameter.** Optional additional behavior customization options. - * These currently customize expiration threshold time and whether to retry - * on 401/403 API request errors. - */ - constructor(options, additionalOptions) { - var _a; - super({ ...options, ...additionalOptions }); - if (options.universe_domain) { - this.universeDomain = options.universe_domain; - } - this.refreshToken = options.refresh_token; - const clientAuth = { - confidentialClientType: 'basic', - clientId: options.client_id, - clientSecret: options.client_secret, - }; - this.externalAccountAuthorizedUserHandler = - new ExternalAccountAuthorizedUserHandler((_a = options.token_url) !== null && _a !== void 0 ? _a : DEFAULT_TOKEN_URL.replace('{universeDomain}', this.universeDomain), this.transporter, clientAuth); - this.cachedAccessToken = null; - this.quotaProjectId = options.quota_project_id; - // As threshold could be zero, - // eagerRefreshThresholdMillis || EXPIRATION_TIME_OFFSET will override the - // zero value. - if (typeof (additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.eagerRefreshThresholdMillis) !== 'number') { - this.eagerRefreshThresholdMillis = baseexternalclient_1.EXPIRATION_TIME_OFFSET; - } - else { - this.eagerRefreshThresholdMillis = additionalOptions - .eagerRefreshThresholdMillis; - } - this.forceRefreshOnFailure = !!(additionalOptions === null || additionalOptions === void 0 ? void 0 : additionalOptions.forceRefreshOnFailure); - } - async getAccessToken() { - // If cached access token is unavailable or expired, force refresh. - if (!this.cachedAccessToken || this.isExpired(this.cachedAccessToken)) { - await this.refreshAccessTokenAsync(); - } - // Return GCP access token in GetAccessTokenResponse format. - return { - token: this.cachedAccessToken.access_token, - res: this.cachedAccessToken.res, - }; - } - async getRequestHeaders() { - const accessTokenResponse = await this.getAccessToken(); - const headers = { - Authorization: `Bearer ${accessTokenResponse.token}`, - }; - return this.addSharedMetadataHeaders(headers); - } - request(opts, callback) { - if (callback) { - this.requestAsync(opts).then(r => callback(null, r), e => { - return callback(e, e.response); - }); - } - else { - return this.requestAsync(opts); - } - } - /** - * Authenticates the provided HTTP request, processes it and resolves with the - * returned response. - * @param opts The HTTP request options. - * @param reAuthRetried Whether the current attempt is a retry after a failed attempt due to an auth failure. - * @return A promise that resolves with the successful response. - */ - async requestAsync(opts, reAuthRetried = false) { - let response; - try { - const requestHeaders = await this.getRequestHeaders(); - opts.headers = opts.headers || {}; - if (requestHeaders && requestHeaders['x-goog-user-project']) { - opts.headers['x-goog-user-project'] = - requestHeaders['x-goog-user-project']; - } - if (requestHeaders && requestHeaders.Authorization) { - opts.headers.Authorization = requestHeaders.Authorization; - } - response = await this.transporter.request(opts); - } - catch (e) { - const res = e.response; - if (res) { - const statusCode = res.status; - // Retry the request for metadata if the following criteria are true: - // - We haven't already retried. It only makes sense to retry once. - // - The response was a 401 or a 403 - // - The request didn't send a readableStream - // - forceRefreshOnFailure is true - const isReadableStream = res.config.data instanceof stream.Readable; - const isAuthErr = statusCode === 401 || statusCode === 403; - if (!reAuthRetried && - isAuthErr && - !isReadableStream && - this.forceRefreshOnFailure) { - await this.refreshAccessTokenAsync(); - return await this.requestAsync(opts, true); - } - } - throw e; - } - return response; - } - /** - * Forces token refresh, even if unexpired tokens are currently cached. - * @return A promise that resolves with the refreshed credential. - */ - async refreshAccessTokenAsync() { - // Refresh the access token using the refresh token. - const refreshResponse = await this.externalAccountAuthorizedUserHandler.refreshToken(this.refreshToken); - this.cachedAccessToken = { - access_token: refreshResponse.access_token, - expiry_date: new Date().getTime() + refreshResponse.expires_in * 1000, - res: refreshResponse.res, - }; - if (refreshResponse.refresh_token !== undefined) { - this.refreshToken = refreshResponse.refresh_token; - } - return this.cachedAccessToken; - } - /** - * Returns whether the provided credentials are expired or not. - * If there is no expiry time, assumes the token is not expired or expiring. - * @param credentials The credentials to check for expiration. - * @return Whether the credentials are expired or not. - */ - isExpired(credentials) { - const now = new Date().getTime(); - return credentials.expiry_date - ? now >= credentials.expiry_date - this.eagerRefreshThresholdMillis - : false; - } -} -exports.ExternalAccountAuthorizedUserClient = ExternalAccountAuthorizedUserClient; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/externalclient.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/externalclient.js deleted file mode 100644 index 54860ead..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/externalclient.js +++ /dev/null @@ -1,64 +0,0 @@ -"use strict"; -// Copyright 2021 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.ExternalAccountClient = void 0; -const baseexternalclient_1 = require("./baseexternalclient"); -const identitypoolclient_1 = require("./identitypoolclient"); -const awsclient_1 = require("./awsclient"); -const pluggable_auth_client_1 = require("./pluggable-auth-client"); -/** - * Dummy class with no constructor. Developers are expected to use fromJSON. - */ -class ExternalAccountClient { - constructor() { - throw new Error('ExternalAccountClients should be initialized via: ' + - 'ExternalAccountClient.fromJSON(), ' + - 'directly via explicit constructors, eg. ' + - 'new AwsClient(options), new IdentityPoolClient(options), new' + - 'PluggableAuthClientOptions, or via ' + - 'new GoogleAuth(options).getClient()'); - } - /** - * This static method will instantiate the - * corresponding type of external account credential depending on the - * underlying credential source. - * @param options The external account options object typically loaded - * from the external account JSON credential file. - * @param additionalOptions **DEPRECATED, all options are available in the - * `options` parameter.** Optional additional behavior customization options. - * These currently customize expiration threshold time and whether to retry - * on 401/403 API request errors. - * @return A BaseExternalAccountClient instance or null if the options - * provided do not correspond to an external account credential. - */ - static fromJSON(options, additionalOptions) { - var _a, _b; - if (options && options.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { - if ((_a = options.credential_source) === null || _a === void 0 ? void 0 : _a.environment_id) { - return new awsclient_1.AwsClient(options, additionalOptions); - } - else if ((_b = options.credential_source) === null || _b === void 0 ? void 0 : _b.executable) { - return new pluggable_auth_client_1.PluggableAuthClient(options, additionalOptions); - } - else { - return new identitypoolclient_1.IdentityPoolClient(options, additionalOptions); - } - } - else { - return null; - } - } -} -exports.ExternalAccountClient = ExternalAccountClient; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js deleted file mode 100644 index abf9bed1..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/filesubjecttokensupplier.js +++ /dev/null @@ -1,81 +0,0 @@ -"use strict"; -// Copyright 2024 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -var _a, _b, _c; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.FileSubjectTokenSupplier = void 0; -const util_1 = require("util"); -const fs = require("fs"); -// fs.readfile is undefined in browser karma tests causing -// `npm run browser-test` to fail as test.oauth2.ts imports this file via -// src/index.ts. -// Fallback to void function to avoid promisify throwing a TypeError. -const readFile = (0, util_1.promisify)((_a = fs.readFile) !== null && _a !== void 0 ? _a : (() => { })); -const realpath = (0, util_1.promisify)((_b = fs.realpath) !== null && _b !== void 0 ? _b : (() => { })); -const lstat = (0, util_1.promisify)((_c = fs.lstat) !== null && _c !== void 0 ? _c : (() => { })); -/** - * Internal subject token supplier implementation used when a file location - * is configured in the credential configuration used to build an {@link IdentityPoolClient} - */ -class FileSubjectTokenSupplier { - /** - * Instantiates a new file based subject token supplier. - * @param opts The file subject token supplier options to build the supplier - * with. - */ - constructor(opts) { - this.filePath = opts.filePath; - this.formatType = opts.formatType; - this.subjectTokenFieldName = opts.subjectTokenFieldName; - } - /** - * Returns the subject token stored at the file specified in the constructor. - * @param context {@link ExternalAccountSupplierContext} from the calling - * {@link IdentityPoolClient}, contains the requested audience and subject - * token type for the external account identity. Not used. - */ - async getSubjectToken(context) { - // Make sure there is a file at the path. lstatSync will throw if there is - // nothing there. - let parsedFilePath = this.filePath; - try { - // Resolve path to actual file in case of symlink. Expect a thrown error - // if not resolvable. - parsedFilePath = await realpath(parsedFilePath); - if (!(await lstat(parsedFilePath)).isFile()) { - throw new Error(); - } - } - catch (err) { - if (err instanceof Error) { - err.message = `The file at ${parsedFilePath} does not exist, or it is not a file. ${err.message}`; - } - throw err; - } - let subjectToken; - const rawText = await readFile(parsedFilePath, { encoding: 'utf8' }); - if (this.formatType === 'text') { - subjectToken = rawText; - } - else if (this.formatType === 'json' && this.subjectTokenFieldName) { - const json = JSON.parse(rawText); - subjectToken = json[this.subjectTokenFieldName]; - } - if (!subjectToken) { - throw new Error('Unable to parse the subject_token from the credential_source file'); - } - return subjectToken; - } -} -exports.FileSubjectTokenSupplier = FileSubjectTokenSupplier; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/googleauth.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/googleauth.js deleted file mode 100644 index 1f68a8d7..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/googleauth.js +++ /dev/null @@ -1,841 +0,0 @@ -"use strict"; -// Copyright 2019 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var _GoogleAuth_instances, _GoogleAuth_pendingAuthClient, _GoogleAuth_prepareAndCacheClient, _GoogleAuth_determineClient; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.GoogleAuth = exports.GoogleAuthExceptionMessages = exports.CLOUD_SDK_CLIENT_ID = void 0; -const child_process_1 = require("child_process"); -const fs = require("fs"); -const gcpMetadata = require("gcp-metadata"); -const os = require("os"); -const path = require("path"); -const crypto_1 = require("../crypto/crypto"); -const transporters_1 = require("../transporters"); -const computeclient_1 = require("./computeclient"); -const idtokenclient_1 = require("./idtokenclient"); -const envDetect_1 = require("./envDetect"); -const jwtclient_1 = require("./jwtclient"); -const refreshclient_1 = require("./refreshclient"); -const impersonated_1 = require("./impersonated"); -const externalclient_1 = require("./externalclient"); -const baseexternalclient_1 = require("./baseexternalclient"); -const authclient_1 = require("./authclient"); -const externalAccountAuthorizedUserClient_1 = require("./externalAccountAuthorizedUserClient"); -const util_1 = require("../util"); -exports.CLOUD_SDK_CLIENT_ID = '764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com'; -exports.GoogleAuthExceptionMessages = { - API_KEY_WITH_CREDENTIALS: 'API Keys and Credentials are mutually exclusive authentication methods and cannot be used together.', - NO_PROJECT_ID_FOUND: 'Unable to detect a Project Id in the current environment. \n' + - 'To learn more about authentication and Google APIs, visit: \n' + - 'https://cloud.google.com/docs/authentication/getting-started', - NO_CREDENTIALS_FOUND: 'Unable to find credentials in current environment. \n' + - 'To learn more about authentication and Google APIs, visit: \n' + - 'https://cloud.google.com/docs/authentication/getting-started', - NO_ADC_FOUND: 'Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.', - NO_UNIVERSE_DOMAIN_FOUND: 'Unable to detect a Universe Domain in the current environment.\n' + - 'To learn more about Universe Domain retrieval, visit: \n' + - 'https://cloud.google.com/compute/docs/metadata/predefined-metadata-keys', -}; -class GoogleAuth { - // Note: this properly is only public to satisfy unit tests. - // https://github.com/Microsoft/TypeScript/issues/5228 - get isGCE() { - return this.checkIsGCE; - } - /** - * Configuration is resolved in the following order of precedence: - * - {@link GoogleAuthOptions.credentials `credentials`} - * - {@link GoogleAuthOptions.keyFilename `keyFilename`} - * - {@link GoogleAuthOptions.keyFile `keyFile`} - * - * {@link GoogleAuthOptions.clientOptions `clientOptions`} are passed to the - * {@link AuthClient `AuthClient`s}. - * - * @param opts - */ - constructor(opts = {}) { - _GoogleAuth_instances.add(this); - /** - * Caches a value indicating whether the auth layer is running on Google - * Compute Engine. - * @private - */ - this.checkIsGCE = undefined; - // To save the contents of the JSON credential file - this.jsonContent = null; - this.cachedCredential = null; - /** - * A pending {@link AuthClient}. Used for concurrent {@link GoogleAuth.getClient} calls. - */ - _GoogleAuth_pendingAuthClient.set(this, null); - this.clientOptions = {}; - this._cachedProjectId = opts.projectId || null; - this.cachedCredential = opts.authClient || null; - this.keyFilename = opts.keyFilename || opts.keyFile; - this.scopes = opts.scopes; - this.clientOptions = opts.clientOptions || {}; - this.jsonContent = opts.credentials || null; - this.apiKey = opts.apiKey || this.clientOptions.apiKey || null; - // Cannot use both API Key + Credentials - if (this.apiKey && (this.jsonContent || this.clientOptions.credentials)) { - throw new RangeError(exports.GoogleAuthExceptionMessages.API_KEY_WITH_CREDENTIALS); - } - if (opts.universeDomain) { - this.clientOptions.universeDomain = opts.universeDomain; - } - } - // GAPIC client libraries should always use self-signed JWTs. The following - // variables are set on the JWT client in order to indicate the type of library, - // and sign the JWT with the correct audience and scopes (if not supplied). - setGapicJWTValues(client) { - client.defaultServicePath = this.defaultServicePath; - client.useJWTAccessWithScope = this.useJWTAccessWithScope; - client.defaultScopes = this.defaultScopes; - } - getProjectId(callback) { - if (callback) { - this.getProjectIdAsync().then(r => callback(null, r), callback); - } - else { - return this.getProjectIdAsync(); - } - } - /** - * A temporary method for internal `getProjectId` usages where `null` is - * acceptable. In a future major release, `getProjectId` should return `null` - * (as the `Promise` base signature describes) and this private - * method should be removed. - * - * @returns Promise that resolves with project id (or `null`) - */ - async getProjectIdOptional() { - try { - return await this.getProjectId(); - } - catch (e) { - if (e instanceof Error && - e.message === exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND) { - return null; - } - else { - throw e; - } - } - } - /** - * A private method for finding and caching a projectId. - * - * Supports environments in order of precedence: - * - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable - * - GOOGLE_APPLICATION_CREDENTIALS JSON file - * - Cloud SDK: `gcloud config config-helper --format json` - * - GCE project ID from metadata server - * - * @returns projectId - */ - async findAndCacheProjectId() { - let projectId = null; - projectId || (projectId = await this.getProductionProjectId()); - projectId || (projectId = await this.getFileProjectId()); - projectId || (projectId = await this.getDefaultServiceProjectId()); - projectId || (projectId = await this.getGCEProjectId()); - projectId || (projectId = await this.getExternalAccountClientProjectId()); - if (projectId) { - this._cachedProjectId = projectId; - return projectId; - } - else { - throw new Error(exports.GoogleAuthExceptionMessages.NO_PROJECT_ID_FOUND); - } - } - async getProjectIdAsync() { - if (this._cachedProjectId) { - return this._cachedProjectId; - } - if (!this._findProjectIdPromise) { - this._findProjectIdPromise = this.findAndCacheProjectId(); - } - return this._findProjectIdPromise; - } - /** - * Retrieves a universe domain from the metadata server via - * {@link gcpMetadata.universe}. - * - * @returns a universe domain - */ - async getUniverseDomainFromMetadataServer() { - var _a; - let universeDomain; - try { - universeDomain = await gcpMetadata.universe('universe-domain'); - universeDomain || (universeDomain = authclient_1.DEFAULT_UNIVERSE); - } - catch (e) { - if (e && ((_a = e === null || e === void 0 ? void 0 : e.response) === null || _a === void 0 ? void 0 : _a.status) === 404) { - universeDomain = authclient_1.DEFAULT_UNIVERSE; - } - else { - throw e; - } - } - return universeDomain; - } - /** - * Retrieves, caches, and returns the universe domain in the following order - * of precedence: - * - The universe domain in {@link GoogleAuth.clientOptions} - * - An existing or ADC {@link AuthClient}'s universe domain - * - {@link gcpMetadata.universe}, if {@link Compute} client - * - * @returns The universe domain - */ - async getUniverseDomain() { - let universeDomain = (0, util_1.originalOrCamelOptions)(this.clientOptions).get('universe_domain'); - try { - universeDomain !== null && universeDomain !== void 0 ? universeDomain : (universeDomain = (await this.getClient()).universeDomain); - } - catch (_a) { - // client or ADC is not available - universeDomain !== null && universeDomain !== void 0 ? universeDomain : (universeDomain = authclient_1.DEFAULT_UNIVERSE); - } - return universeDomain; - } - /** - * @returns Any scopes (user-specified or default scopes specified by the - * client library) that need to be set on the current Auth client. - */ - getAnyScopes() { - return this.scopes || this.defaultScopes; - } - getApplicationDefault(optionsOrCallback = {}, callback) { - let options; - if (typeof optionsOrCallback === 'function') { - callback = optionsOrCallback; - } - else { - options = optionsOrCallback; - } - if (callback) { - this.getApplicationDefaultAsync(options).then(r => callback(null, r.credential, r.projectId), callback); - } - else { - return this.getApplicationDefaultAsync(options); - } - } - async getApplicationDefaultAsync(options = {}) { - // If we've already got a cached credential, return it. - // This will also preserve one's configured quota project, in case they - // set one directly on the credential previously. - if (this.cachedCredential) { - // cache, while preserving existing quota project preferences - return await __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, this.cachedCredential, null); - } - let credential; - // Check for the existence of a local environment variable pointing to the - // location of the credential file. This is typically used in local - // developer scenarios. - credential = - await this._tryGetApplicationCredentialsFromEnvironmentVariable(options); - if (credential) { - if (credential instanceof jwtclient_1.JWT) { - credential.scopes = this.scopes; - } - else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) { - credential.scopes = this.getAnyScopes(); - } - return await __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, credential); - } - // Look in the well-known credential file location. - credential = - await this._tryGetApplicationCredentialsFromWellKnownFile(options); - if (credential) { - if (credential instanceof jwtclient_1.JWT) { - credential.scopes = this.scopes; - } - else if (credential instanceof baseexternalclient_1.BaseExternalAccountClient) { - credential.scopes = this.getAnyScopes(); - } - return await __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, credential); - } - // Determine if we're running on GCE. - if (await this._checkIsGCE()) { - options.scopes = this.getAnyScopes(); - return await __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, new computeclient_1.Compute(options)); - } - throw new Error(exports.GoogleAuthExceptionMessages.NO_ADC_FOUND); - } - /** - * Determines whether the auth layer is running on Google Compute Engine. - * Checks for GCP Residency, then fallback to checking if metadata server - * is available. - * - * @returns A promise that resolves with the boolean. - * @api private - */ - async _checkIsGCE() { - if (this.checkIsGCE === undefined) { - this.checkIsGCE = - gcpMetadata.getGCPResidency() || (await gcpMetadata.isAvailable()); - } - return this.checkIsGCE; - } - /** - * Attempts to load default credentials from the environment variable path.. - * @returns Promise that resolves with the OAuth2Client or null. - * @api private - */ - async _tryGetApplicationCredentialsFromEnvironmentVariable(options) { - const credentialsPath = process.env['GOOGLE_APPLICATION_CREDENTIALS'] || - process.env['google_application_credentials']; - if (!credentialsPath || credentialsPath.length === 0) { - return null; - } - try { - return this._getApplicationCredentialsFromFilePath(credentialsPath, options); - } - catch (e) { - if (e instanceof Error) { - e.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e.message}`; - } - throw e; - } - } - /** - * Attempts to load default credentials from a well-known file location - * @return Promise that resolves with the OAuth2Client or null. - * @api private - */ - async _tryGetApplicationCredentialsFromWellKnownFile(options) { - // First, figure out the location of the file, depending upon the OS type. - let location = null; - if (this._isWindows()) { - // Windows - location = process.env['APPDATA']; - } - else { - // Linux or Mac - const home = process.env['HOME']; - if (home) { - location = path.join(home, '.config'); - } - } - // If we found the root path, expand it. - if (location) { - location = path.join(location, 'gcloud', 'application_default_credentials.json'); - if (!fs.existsSync(location)) { - location = null; - } - } - // The file does not exist. - if (!location) { - return null; - } - // The file seems to exist. Try to use it. - const client = await this._getApplicationCredentialsFromFilePath(location, options); - return client; - } - /** - * Attempts to load default credentials from a file at the given path.. - * @param filePath The path to the file to read. - * @returns Promise that resolves with the OAuth2Client - * @api private - */ - async _getApplicationCredentialsFromFilePath(filePath, options = {}) { - // Make sure the path looks like a string. - if (!filePath || filePath.length === 0) { - throw new Error('The file path is invalid.'); - } - // Make sure there is a file at the path. lstatSync will throw if there is - // nothing there. - try { - // Resolve path to actual file in case of symlink. Expect a thrown error - // if not resolvable. - filePath = fs.realpathSync(filePath); - if (!fs.lstatSync(filePath).isFile()) { - throw new Error(); - } - } - catch (err) { - if (err instanceof Error) { - err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`; - } - throw err; - } - // Now open a read stream on the file, and parse it. - const readStream = fs.createReadStream(filePath); - return this.fromStream(readStream, options); - } - /** - * Create a credentials instance using a given impersonated input options. - * @param json The impersonated input object. - * @returns JWT or UserRefresh Client with data - */ - fromImpersonatedJSON(json) { - var _a, _b, _c, _d; - if (!json) { - throw new Error('Must pass in a JSON object containing an impersonated refresh token'); - } - if (json.type !== impersonated_1.IMPERSONATED_ACCOUNT_TYPE) { - throw new Error(`The incoming JSON object does not have the "${impersonated_1.IMPERSONATED_ACCOUNT_TYPE}" type`); - } - if (!json.source_credentials) { - throw new Error('The incoming JSON object does not contain a source_credentials field'); - } - if (!json.service_account_impersonation_url) { - throw new Error('The incoming JSON object does not contain a service_account_impersonation_url field'); - } - const sourceClient = this.fromJSON(json.source_credentials); - if (((_a = json.service_account_impersonation_url) === null || _a === void 0 ? void 0 : _a.length) > 256) { - /** - * Prevents DOS attacks. - * @see {@link https://github.com/googleapis/google-auth-library-nodejs/security/code-scanning/85} - **/ - throw new RangeError(`Target principal is too long: ${json.service_account_impersonation_url}`); - } - // Extract service account from service_account_impersonation_url - const targetPrincipal = (_c = (_b = /(?[^/]+):(generateAccessToken|generateIdToken)$/.exec(json.service_account_impersonation_url)) === null || _b === void 0 ? void 0 : _b.groups) === null || _c === void 0 ? void 0 : _c.target; - if (!targetPrincipal) { - throw new RangeError(`Cannot extract target principal from ${json.service_account_impersonation_url}`); - } - const targetScopes = (_d = this.getAnyScopes()) !== null && _d !== void 0 ? _d : []; - return new impersonated_1.Impersonated({ - ...json, - sourceClient, - targetPrincipal, - targetScopes: Array.isArray(targetScopes) ? targetScopes : [targetScopes], - }); - } - /** - * Create a credentials instance using the given input options. - * This client is not cached. - * - * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}. - * - * @param json The input object. - * @param options The JWT or UserRefresh options for the client - * @returns JWT or UserRefresh Client with data - */ - fromJSON(json, options = {}) { - let client; - // user's preferred universe domain - const preferredUniverseDomain = (0, util_1.originalOrCamelOptions)(options).get('universe_domain'); - if (json.type === refreshclient_1.USER_REFRESH_ACCOUNT_TYPE) { - client = new refreshclient_1.UserRefreshClient(options); - client.fromJSON(json); - } - else if (json.type === impersonated_1.IMPERSONATED_ACCOUNT_TYPE) { - client = this.fromImpersonatedJSON(json); - } - else if (json.type === baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { - client = externalclient_1.ExternalAccountClient.fromJSON(json, options); - client.scopes = this.getAnyScopes(); - } - else if (json.type === externalAccountAuthorizedUserClient_1.EXTERNAL_ACCOUNT_AUTHORIZED_USER_TYPE) { - client = new externalAccountAuthorizedUserClient_1.ExternalAccountAuthorizedUserClient(json, options); - } - else { - options.scopes = this.scopes; - client = new jwtclient_1.JWT(options); - this.setGapicJWTValues(client); - client.fromJSON(json); - } - if (preferredUniverseDomain) { - client.universeDomain = preferredUniverseDomain; - } - return client; - } - /** - * Return a JWT or UserRefreshClient from JavaScript object, caching both the - * object used to instantiate and the client. - * @param json The input object. - * @param options The JWT or UserRefresh options for the client - * @returns JWT or UserRefresh Client with data - */ - _cacheClientFromJSON(json, options) { - const client = this.fromJSON(json, options); - // cache both raw data used to instantiate client and client itself. - this.jsonContent = json; - this.cachedCredential = client; - return client; - } - fromStream(inputStream, optionsOrCallback = {}, callback) { - let options = {}; - if (typeof optionsOrCallback === 'function') { - callback = optionsOrCallback; - } - else { - options = optionsOrCallback; - } - if (callback) { - this.fromStreamAsync(inputStream, options).then(r => callback(null, r), callback); - } - else { - return this.fromStreamAsync(inputStream, options); - } - } - fromStreamAsync(inputStream, options) { - return new Promise((resolve, reject) => { - if (!inputStream) { - throw new Error('Must pass in a stream containing the Google auth settings.'); - } - const chunks = []; - inputStream - .setEncoding('utf8') - .on('error', reject) - .on('data', chunk => chunks.push(chunk)) - .on('end', () => { - try { - try { - const data = JSON.parse(chunks.join('')); - const r = this._cacheClientFromJSON(data, options); - return resolve(r); - } - catch (err) { - // If we failed parsing this.keyFileName, assume that it - // is a PEM or p12 certificate: - if (!this.keyFilename) - throw err; - const client = new jwtclient_1.JWT({ - ...this.clientOptions, - keyFile: this.keyFilename, - }); - this.cachedCredential = client; - this.setGapicJWTValues(client); - return resolve(client); - } - } - catch (err) { - return reject(err); - } - }); - }); - } - /** - * Create a credentials instance using the given API key string. - * The created client is not cached. In order to create and cache it use the {@link GoogleAuth.getClient `getClient`} method after first providing an {@link GoogleAuth.apiKey `apiKey`}. - * - * @param apiKey The API key string - * @param options An optional options object. - * @returns A JWT loaded from the key - */ - fromAPIKey(apiKey, options = {}) { - return new jwtclient_1.JWT({ ...options, apiKey }); - } - /** - * Determines whether the current operating system is Windows. - * @api private - */ - _isWindows() { - const sys = os.platform(); - if (sys && sys.length >= 3) { - if (sys.substring(0, 3).toLowerCase() === 'win') { - return true; - } - } - return false; - } - /** - * Run the Google Cloud SDK command that prints the default project ID - */ - async getDefaultServiceProjectId() { - return new Promise(resolve => { - (0, child_process_1.exec)('gcloud config config-helper --format json', (err, stdout) => { - if (!err && stdout) { - try { - const projectId = JSON.parse(stdout).configuration.properties.core.project; - resolve(projectId); - return; - } - catch (e) { - // ignore errors - } - } - resolve(null); - }); - }); - } - /** - * Loads the project id from environment variables. - * @api private - */ - getProductionProjectId() { - return (process.env['GCLOUD_PROJECT'] || - process.env['GOOGLE_CLOUD_PROJECT'] || - process.env['gcloud_project'] || - process.env['google_cloud_project']); - } - /** - * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file. - * @api private - */ - async getFileProjectId() { - if (this.cachedCredential) { - // Try to read the project ID from the cached credentials file - return this.cachedCredential.projectId; - } - // Ensure the projectId is loaded from the keyFile if available. - if (this.keyFilename) { - const creds = await this.getClient(); - if (creds && creds.projectId) { - return creds.projectId; - } - } - // Try to load a credentials file and read its project ID - const r = await this._tryGetApplicationCredentialsFromEnvironmentVariable(); - if (r) { - return r.projectId; - } - else { - return null; - } - } - /** - * Gets the project ID from external account client if available. - */ - async getExternalAccountClientProjectId() { - if (!this.jsonContent || this.jsonContent.type !== baseexternalclient_1.EXTERNAL_ACCOUNT_TYPE) { - return null; - } - const creds = await this.getClient(); - // Do not suppress the underlying error, as the error could contain helpful - // information for debugging and fixing. This is especially true for - // external account creds as in order to get the project ID, the following - // operations have to succeed: - // 1. Valid credentials file should be supplied. - // 2. Ability to retrieve access tokens from STS token exchange API. - // 3. Ability to exchange for service account impersonated credentials (if - // enabled). - // 4. Ability to get project info using the access token from step 2 or 3. - // Without surfacing the error, it is harder for developers to determine - // which step went wrong. - return await creds.getProjectId(); - } - /** - * Gets the Compute Engine project ID if it can be inferred. - */ - async getGCEProjectId() { - try { - const r = await gcpMetadata.project('project-id'); - return r; - } - catch (e) { - // Ignore any errors - return null; - } - } - getCredentials(callback) { - if (callback) { - this.getCredentialsAsync().then(r => callback(null, r), callback); - } - else { - return this.getCredentialsAsync(); - } - } - async getCredentialsAsync() { - const client = await this.getClient(); - if (client instanceof impersonated_1.Impersonated) { - return { client_email: client.getTargetPrincipal() }; - } - if (client instanceof baseexternalclient_1.BaseExternalAccountClient) { - const serviceAccountEmail = client.getServiceAccountEmail(); - if (serviceAccountEmail) { - return { - client_email: serviceAccountEmail, - universe_domain: client.universeDomain, - }; - } - } - if (this.jsonContent) { - return { - client_email: this.jsonContent.client_email, - private_key: this.jsonContent.private_key, - universe_domain: this.jsonContent.universe_domain, - }; - } - if (await this._checkIsGCE()) { - const [client_email, universe_domain] = await Promise.all([ - gcpMetadata.instance('service-accounts/default/email'), - this.getUniverseDomain(), - ]); - return { client_email, universe_domain }; - } - throw new Error(exports.GoogleAuthExceptionMessages.NO_CREDENTIALS_FOUND); - } - /** - * Automatically obtain an {@link AuthClient `AuthClient`} based on the - * provided configuration. If no options were passed, use Application - * Default Credentials. - */ - async getClient() { - if (this.cachedCredential) { - return this.cachedCredential; - } - // Use an existing auth client request, or cache a new one - __classPrivateFieldSet(this, _GoogleAuth_pendingAuthClient, __classPrivateFieldGet(this, _GoogleAuth_pendingAuthClient, "f") || __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_determineClient).call(this), "f"); - try { - return await __classPrivateFieldGet(this, _GoogleAuth_pendingAuthClient, "f"); - } - finally { - // reset the pending auth client in case it is changed later - __classPrivateFieldSet(this, _GoogleAuth_pendingAuthClient, null, "f"); - } - } - /** - * Creates a client which will fetch an ID token for authorization. - * @param targetAudience the audience for the fetched ID token. - * @returns IdTokenClient for making HTTP calls authenticated with ID tokens. - */ - async getIdTokenClient(targetAudience) { - const client = await this.getClient(); - if (!('fetchIdToken' in client)) { - throw new Error('Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.'); - } - return new idtokenclient_1.IdTokenClient({ targetAudience, idTokenProvider: client }); - } - /** - * Automatically obtain application default credentials, and return - * an access token for making requests. - */ - async getAccessToken() { - const client = await this.getClient(); - return (await client.getAccessToken()).token; - } - /** - * Obtain the HTTP headers that will provide authorization for a given - * request. - */ - async getRequestHeaders(url) { - const client = await this.getClient(); - return client.getRequestHeaders(url); - } - /** - * Obtain credentials for a request, then attach the appropriate headers to - * the request options. - * @param opts Axios or Request options on which to attach the headers - */ - async authorizeRequest(opts) { - opts = opts || {}; - const url = opts.url || opts.uri; - const client = await this.getClient(); - const headers = await client.getRequestHeaders(url); - opts.headers = Object.assign(opts.headers || {}, headers); - return opts; - } - /** - * Automatically obtain application default credentials, and make an - * HTTP request using the given options. - * @param opts Axios request options for the HTTP request. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - async request(opts) { - const client = await this.getClient(); - return client.request(opts); - } - /** - * Determine the compute environment in which the code is running. - */ - getEnv() { - return (0, envDetect_1.getEnv)(); - } - /** - * Sign the given data with the current private key, or go out - * to the IAM API to sign it. - * @param data The data to be signed. - * @param endpoint A custom endpoint to use. - * - * @example - * ``` - * sign('data', 'https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/'); - * ``` - */ - async sign(data, endpoint) { - const client = await this.getClient(); - const universe = await this.getUniverseDomain(); - endpoint = - endpoint || - `https://iamcredentials.${universe}/v1/projects/-/serviceAccounts/`; - if (client instanceof impersonated_1.Impersonated) { - const signed = await client.sign(data); - return signed.signedBlob; - } - const crypto = (0, crypto_1.createCrypto)(); - if (client instanceof jwtclient_1.JWT && client.key) { - const sign = await crypto.sign(client.key, data); - return sign; - } - const creds = await this.getCredentials(); - if (!creds.client_email) { - throw new Error('Cannot sign data without `client_email`.'); - } - return this.signBlob(crypto, creds.client_email, data, endpoint); - } - async signBlob(crypto, emailOrUniqueId, data, endpoint) { - const url = new URL(endpoint + `${emailOrUniqueId}:signBlob`); - const res = await this.request({ - method: 'POST', - url: url.href, - data: { - payload: crypto.encodeBase64StringUtf8(data), - }, - retry: true, - retryConfig: { - httpMethodsToRetry: ['POST'], - }, - }); - return res.data.signedBlob; - } -} -exports.GoogleAuth = GoogleAuth; -_GoogleAuth_pendingAuthClient = new WeakMap(), _GoogleAuth_instances = new WeakSet(), _GoogleAuth_prepareAndCacheClient = async function _GoogleAuth_prepareAndCacheClient(credential, quotaProjectIdOverride = process.env['GOOGLE_CLOUD_QUOTA_PROJECT'] || null) { - const projectId = await this.getProjectIdOptional(); - if (quotaProjectIdOverride) { - credential.quotaProjectId = quotaProjectIdOverride; - } - this.cachedCredential = credential; - return { credential, projectId }; -}, _GoogleAuth_determineClient = async function _GoogleAuth_determineClient() { - if (this.jsonContent) { - return this._cacheClientFromJSON(this.jsonContent, this.clientOptions); - } - else if (this.keyFilename) { - const filePath = path.resolve(this.keyFilename); - const stream = fs.createReadStream(filePath); - return await this.fromStreamAsync(stream, this.clientOptions); - } - else if (this.apiKey) { - const client = await this.fromAPIKey(this.apiKey, this.clientOptions); - client.scopes = this.scopes; - const { credential } = await __classPrivateFieldGet(this, _GoogleAuth_instances, "m", _GoogleAuth_prepareAndCacheClient).call(this, client); - return credential; - } - else { - const { credential } = await this.getApplicationDefaultAsync(this.clientOptions); - return credential; - } -}; -/** - * Export DefaultTransporter as a static property of the class. - */ -GoogleAuth.DefaultTransporter = transporters_1.DefaultTransporter; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/iam.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/iam.js deleted file mode 100644 index e837114f..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/iam.js +++ /dev/null @@ -1,41 +0,0 @@ -"use strict"; -// Copyright 2014 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.IAMAuth = void 0; -class IAMAuth { - /** - * IAM credentials. - * - * @param selector the iam authority selector - * @param token the token - * @constructor - */ - constructor(selector, token) { - this.selector = selector; - this.token = token; - this.selector = selector; - this.token = token; - } - /** - * Acquire the HTTP headers required to make an authenticated request. - */ - getRequestHeaders() { - return { - 'x-goog-iam-authority-selector': this.selector, - 'x-goog-iam-authorization-token': this.token, - }; - } -} -exports.IAMAuth = IAMAuth; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/identitypoolclient.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/identitypoolclient.js deleted file mode 100644 index c2e23074..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/identitypoolclient.js +++ /dev/null @@ -1,107 +0,0 @@ -"use strict"; -// Copyright 2021 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.IdentityPoolClient = void 0; -const baseexternalclient_1 = require("./baseexternalclient"); -const util_1 = require("../util"); -const filesubjecttokensupplier_1 = require("./filesubjecttokensupplier"); -const urlsubjecttokensupplier_1 = require("./urlsubjecttokensupplier"); -/** - * Defines the Url-sourced and file-sourced external account clients mainly - * used for K8s and Azure workloads. - */ -class IdentityPoolClient extends baseexternalclient_1.BaseExternalAccountClient { - /** - * Instantiate an IdentityPoolClient instance using the provided JSON - * object loaded from an external account credentials file. - * An error is thrown if the credential is not a valid file-sourced or - * url-sourced credential or a workforce pool user project is provided - * with a non workforce audience. - * @param options The external account options object typically loaded - * from the external account JSON credential file. The camelCased options - * are aliases for the snake_cased options. - * @param additionalOptions **DEPRECATED, all options are available in the - * `options` parameter.** Optional additional behavior customization options. - * These currently customize expiration threshold time and whether to retry - * on 401/403 API request errors. - */ - constructor(options, additionalOptions) { - super(options, additionalOptions); - const opts = (0, util_1.originalOrCamelOptions)(options); - const credentialSource = opts.get('credential_source'); - const subjectTokenSupplier = opts.get('subject_token_supplier'); - // Validate credential sourcing configuration. - if (!credentialSource && !subjectTokenSupplier) { - throw new Error('A credential source or subject token supplier must be specified.'); - } - if (credentialSource && subjectTokenSupplier) { - throw new Error('Only one of credential source or subject token supplier can be specified.'); - } - if (subjectTokenSupplier) { - this.subjectTokenSupplier = subjectTokenSupplier; - this.credentialSourceType = 'programmatic'; - } - else { - const credentialSourceOpts = (0, util_1.originalOrCamelOptions)(credentialSource); - const formatOpts = (0, util_1.originalOrCamelOptions)(credentialSourceOpts.get('format')); - // Text is the default format type. - const formatType = formatOpts.get('type') || 'text'; - const formatSubjectTokenFieldName = formatOpts.get('subject_token_field_name'); - if (formatType !== 'json' && formatType !== 'text') { - throw new Error(`Invalid credential_source format "${formatType}"`); - } - if (formatType === 'json' && !formatSubjectTokenFieldName) { - throw new Error('Missing subject_token_field_name for JSON credential_source format'); - } - const file = credentialSourceOpts.get('file'); - const url = credentialSourceOpts.get('url'); - const headers = credentialSourceOpts.get('headers'); - if (file && url) { - throw new Error('No valid Identity Pool "credential_source" provided, must be either file or url.'); - } - else if (file && !url) { - this.credentialSourceType = 'file'; - this.subjectTokenSupplier = new filesubjecttokensupplier_1.FileSubjectTokenSupplier({ - filePath: file, - formatType: formatType, - subjectTokenFieldName: formatSubjectTokenFieldName, - }); - } - else if (!file && url) { - this.credentialSourceType = 'url'; - this.subjectTokenSupplier = new urlsubjecttokensupplier_1.UrlSubjectTokenSupplier({ - url: url, - formatType: formatType, - subjectTokenFieldName: formatSubjectTokenFieldName, - headers: headers, - additionalGaxiosOptions: IdentityPoolClient.RETRY_CONFIG, - }); - } - else { - throw new Error('No valid Identity Pool "credential_source" provided, must be either file or url.'); - } - } - } - /** - * Triggered when a external subject token is needed to be exchanged for a GCP - * access token via GCP STS endpoint. Gets a subject token by calling - * the configured {@link SubjectTokenSupplier} - * @return A promise that resolves with the external subject token. - */ - async retrieveSubjectToken() { - return this.subjectTokenSupplier.getSubjectToken(this.supplierContext); - } -} -exports.IdentityPoolClient = IdentityPoolClient; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/idtokenclient.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/idtokenclient.js deleted file mode 100644 index 77e6fa3c..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/idtokenclient.js +++ /dev/null @@ -1,55 +0,0 @@ -"use strict"; -// Copyright 2020 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.IdTokenClient = void 0; -const oauth2client_1 = require("./oauth2client"); -class IdTokenClient extends oauth2client_1.OAuth2Client { - /** - * Google ID Token client - * - * Retrieve ID token from the metadata server. - * See: https://cloud.google.com/docs/authentication/get-id-token#metadata-server - */ - constructor(options) { - super(options); - this.targetAudience = options.targetAudience; - this.idTokenProvider = options.idTokenProvider; - } - async getRequestMetadataAsync( - // eslint-disable-next-line @typescript-eslint/no-unused-vars - url) { - if (!this.credentials.id_token || - !this.credentials.expiry_date || - this.isTokenExpiring()) { - const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience); - this.credentials = { - id_token: idToken, - expiry_date: this.getIdTokenExpiryDate(idToken), - }; - } - const headers = { - Authorization: 'Bearer ' + this.credentials.id_token, - }; - return { headers }; - } - getIdTokenExpiryDate(idToken) { - const payloadB64 = idToken.split('.')[1]; - if (payloadB64) { - const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('ascii')); - return payload.exp * 1000; - } - } -} -exports.IdTokenClient = IdTokenClient; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/impersonated.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/impersonated.js deleted file mode 100644 index 46c07c98..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/impersonated.js +++ /dev/null @@ -1,186 +0,0 @@ -"use strict"; -/** - * Copyright 2021 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Impersonated = exports.IMPERSONATED_ACCOUNT_TYPE = void 0; -const oauth2client_1 = require("./oauth2client"); -const gaxios_1 = require("gaxios"); -const util_1 = require("../util"); -exports.IMPERSONATED_ACCOUNT_TYPE = 'impersonated_service_account'; -class Impersonated extends oauth2client_1.OAuth2Client { - /** - * Impersonated service account credentials. - * - * Create a new access token by impersonating another service account. - * - * Impersonated Credentials allowing credentials issued to a user or - * service account to impersonate another. The source project using - * Impersonated Credentials must enable the "IAMCredentials" API. - * Also, the target service account must grant the orginating principal - * the "Service Account Token Creator" IAM role. - * - * @param {object} options - The configuration object. - * @param {object} [options.sourceClient] the source credential used as to - * acquire the impersonated credentials. - * @param {string} [options.targetPrincipal] the service account to - * impersonate. - * @param {string[]} [options.delegates] the chained list of delegates - * required to grant the final access_token. If set, the sequence of - * identities must have "Service Account Token Creator" capability granted to - * the preceding identity. For example, if set to [serviceAccountB, - * serviceAccountC], the sourceCredential must have the Token Creator role on - * serviceAccountB. serviceAccountB must have the Token Creator on - * serviceAccountC. Finally, C must have Token Creator on target_principal. - * If left unset, sourceCredential must have that role on targetPrincipal. - * @param {string[]} [options.targetScopes] scopes to request during the - * authorization grant. - * @param {number} [options.lifetime] number of seconds the delegated - * credential should be valid for up to 3600 seconds by default, or 43,200 - * seconds by extending the token's lifetime, see: - * https://cloud.google.com/iam/docs/creating-short-lived-service-account-credentials#sa-credentials-oauth - * @param {string} [options.endpoint] api endpoint override. - */ - constructor(options = {}) { - var _a, _b, _c, _d, _e, _f; - super(options); - // Start with an expired refresh token, which will automatically be - // refreshed before the first API call is made. - this.credentials = { - expiry_date: 1, - refresh_token: 'impersonated-placeholder', - }; - this.sourceClient = (_a = options.sourceClient) !== null && _a !== void 0 ? _a : new oauth2client_1.OAuth2Client(); - this.targetPrincipal = (_b = options.targetPrincipal) !== null && _b !== void 0 ? _b : ''; - this.delegates = (_c = options.delegates) !== null && _c !== void 0 ? _c : []; - this.targetScopes = (_d = options.targetScopes) !== null && _d !== void 0 ? _d : []; - this.lifetime = (_e = options.lifetime) !== null && _e !== void 0 ? _e : 3600; - const usingExplicitUniverseDomain = !!(0, util_1.originalOrCamelOptions)(options).get('universe_domain'); - if (!usingExplicitUniverseDomain) { - // override the default universe with the source's universe - this.universeDomain = this.sourceClient.universeDomain; - } - else if (this.sourceClient.universeDomain !== this.universeDomain) { - // non-default universe and is not matching the source - this could be a credential leak - throw new RangeError(`Universe domain ${this.sourceClient.universeDomain} in source credentials does not match ${this.universeDomain} universe domain set for impersonated credentials.`); - } - this.endpoint = - (_f = options.endpoint) !== null && _f !== void 0 ? _f : `https://iamcredentials.${this.universeDomain}`; - } - /** - * Signs some bytes. - * - * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/signBlob Reference Documentation} - * @param blobToSign String to sign. - * - * @returns A {@link SignBlobResponse} denoting the keyID and signedBlob in base64 string - */ - async sign(blobToSign) { - await this.sourceClient.getAccessToken(); - const name = `projects/-/serviceAccounts/${this.targetPrincipal}`; - const u = `${this.endpoint}/v1/${name}:signBlob`; - const body = { - delegates: this.delegates, - payload: Buffer.from(blobToSign).toString('base64'), - }; - const res = await this.sourceClient.request({ - ...Impersonated.RETRY_CONFIG, - url: u, - data: body, - method: 'POST', - }); - return res.data; - } - /** The service account email to be impersonated. */ - getTargetPrincipal() { - return this.targetPrincipal; - } - /** - * Refreshes the access token. - */ - async refreshToken() { - var _a, _b, _c, _d, _e, _f; - try { - await this.sourceClient.getAccessToken(); - const name = 'projects/-/serviceAccounts/' + this.targetPrincipal; - const u = `${this.endpoint}/v1/${name}:generateAccessToken`; - const body = { - delegates: this.delegates, - scope: this.targetScopes, - lifetime: this.lifetime + 's', - }; - const res = await this.sourceClient.request({ - ...Impersonated.RETRY_CONFIG, - url: u, - data: body, - method: 'POST', - }); - const tokenResponse = res.data; - this.credentials.access_token = tokenResponse.accessToken; - this.credentials.expiry_date = Date.parse(tokenResponse.expireTime); - return { - tokens: this.credentials, - res, - }; - } - catch (error) { - if (!(error instanceof Error)) - throw error; - let status = 0; - let message = ''; - if (error instanceof gaxios_1.GaxiosError) { - status = (_c = (_b = (_a = error === null || error === void 0 ? void 0 : error.response) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.error) === null || _c === void 0 ? void 0 : _c.status; - message = (_f = (_e = (_d = error === null || error === void 0 ? void 0 : error.response) === null || _d === void 0 ? void 0 : _d.data) === null || _e === void 0 ? void 0 : _e.error) === null || _f === void 0 ? void 0 : _f.message; - } - if (status && message) { - error.message = `${status}: unable to impersonate: ${message}`; - throw error; - } - else { - error.message = `unable to impersonate: ${error}`; - throw error; - } - } - } - /** - * Generates an OpenID Connect ID token for a service account. - * - * {@link https://cloud.google.com/iam/docs/reference/credentials/rest/v1/projects.serviceAccounts/generateIdToken Reference Documentation} - * - * @param targetAudience the audience for the fetched ID token. - * @param options the for the request - * @return an OpenID Connect ID token - */ - async fetchIdToken(targetAudience, options) { - var _a, _b; - await this.sourceClient.getAccessToken(); - const name = `projects/-/serviceAccounts/${this.targetPrincipal}`; - const u = `${this.endpoint}/v1/${name}:generateIdToken`; - const body = { - delegates: this.delegates, - audience: targetAudience, - includeEmail: (_a = options === null || options === void 0 ? void 0 : options.includeEmail) !== null && _a !== void 0 ? _a : true, - useEmailAzp: (_b = options === null || options === void 0 ? void 0 : options.includeEmail) !== null && _b !== void 0 ? _b : true, - }; - const res = await this.sourceClient.request({ - ...Impersonated.RETRY_CONFIG, - url: u, - data: body, - method: 'POST', - }); - return res.data.token; - } -} -exports.Impersonated = Impersonated; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/jwtaccess.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/jwtaccess.js deleted file mode 100644 index 664387b5..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/jwtaccess.js +++ /dev/null @@ -1,192 +0,0 @@ -"use strict"; -// Copyright 2015 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.JWTAccess = void 0; -const jws = require("jws"); -const util_1 = require("../util"); -const DEFAULT_HEADER = { - alg: 'RS256', - typ: 'JWT', -}; -class JWTAccess { - /** - * JWTAccess service account credentials. - * - * Create a new access token by using the credential to create a new JWT token - * that's recognized as the access token. - * - * @param email the service account email address. - * @param key the private key that will be used to sign the token. - * @param keyId the ID of the private key used to sign the token. - */ - constructor(email, key, keyId, eagerRefreshThresholdMillis) { - this.cache = new util_1.LRUCache({ - capacity: 500, - maxAge: 60 * 60 * 1000, - }); - this.email = email; - this.key = key; - this.keyId = keyId; - this.eagerRefreshThresholdMillis = - eagerRefreshThresholdMillis !== null && eagerRefreshThresholdMillis !== void 0 ? eagerRefreshThresholdMillis : 5 * 60 * 1000; - } - /** - * Ensures that we're caching a key appropriately, giving precedence to scopes vs. url - * - * @param url The URI being authorized. - * @param scopes The scope or scopes being authorized - * @returns A string that returns the cached key. - */ - getCachedKey(url, scopes) { - let cacheKey = url; - if (scopes && Array.isArray(scopes) && scopes.length) { - cacheKey = url ? `${url}_${scopes.join('_')}` : `${scopes.join('_')}`; - } - else if (typeof scopes === 'string') { - cacheKey = url ? `${url}_${scopes}` : scopes; - } - if (!cacheKey) { - throw Error('Scopes or url must be provided'); - } - return cacheKey; - } - /** - * Get a non-expired access token, after refreshing if necessary. - * - * @param url The URI being authorized. - * @param additionalClaims An object with a set of additional claims to - * include in the payload. - * @returns An object that includes the authorization header. - */ - getRequestHeaders(url, additionalClaims, scopes) { - // Return cached authorization headers, unless we are within - // eagerRefreshThresholdMillis ms of them expiring: - const key = this.getCachedKey(url, scopes); - const cachedToken = this.cache.get(key); - const now = Date.now(); - if (cachedToken && - cachedToken.expiration - now > this.eagerRefreshThresholdMillis) { - return cachedToken.headers; - } - const iat = Math.floor(Date.now() / 1000); - const exp = JWTAccess.getExpirationTime(iat); - let defaultClaims; - // Turn scopes into space-separated string - if (Array.isArray(scopes)) { - scopes = scopes.join(' '); - } - // If scopes are specified, sign with scopes - if (scopes) { - defaultClaims = { - iss: this.email, - sub: this.email, - scope: scopes, - exp, - iat, - }; - } - else { - defaultClaims = { - iss: this.email, - sub: this.email, - aud: url, - exp, - iat, - }; - } - // if additionalClaims are provided, ensure they do not collide with - // other required claims. - if (additionalClaims) { - for (const claim in defaultClaims) { - if (additionalClaims[claim]) { - throw new Error(`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`); - } - } - } - const header = this.keyId - ? { ...DEFAULT_HEADER, kid: this.keyId } - : DEFAULT_HEADER; - const payload = Object.assign(defaultClaims, additionalClaims); - // Sign the jwt and add it to the cache - const signedJWT = jws.sign({ header, payload, secret: this.key }); - const headers = { Authorization: `Bearer ${signedJWT}` }; - this.cache.set(key, { - expiration: exp * 1000, - headers, - }); - return headers; - } - /** - * Returns an expiration time for the JWT token. - * - * @param iat The issued at time for the JWT. - * @returns An expiration time for the JWT. - */ - static getExpirationTime(iat) { - const exp = iat + 3600; // 3600 seconds = 1 hour - return exp; - } - /** - * Create a JWTAccess credentials instance using the given input options. - * @param json The input object. - */ - fromJSON(json) { - if (!json) { - throw new Error('Must pass in a JSON object containing the service account auth settings.'); - } - if (!json.client_email) { - throw new Error('The incoming JSON object does not contain a client_email field'); - } - if (!json.private_key) { - throw new Error('The incoming JSON object does not contain a private_key field'); - } - // Extract the relevant information from the json key file. - this.email = json.client_email; - this.key = json.private_key; - this.keyId = json.private_key_id; - this.projectId = json.project_id; - } - fromStream(inputStream, callback) { - if (callback) { - this.fromStreamAsync(inputStream).then(() => callback(), callback); - } - else { - return this.fromStreamAsync(inputStream); - } - } - fromStreamAsync(inputStream) { - return new Promise((resolve, reject) => { - if (!inputStream) { - reject(new Error('Must pass in a stream containing the service account auth settings.')); - } - let s = ''; - inputStream - .setEncoding('utf8') - .on('data', chunk => (s += chunk)) - .on('error', reject) - .on('end', () => { - try { - const data = JSON.parse(s); - this.fromJSON(data); - resolve(); - } - catch (err) { - reject(err); - } - }); - }); - } -} -exports.JWTAccess = JWTAccess; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/jwtclient.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/jwtclient.js deleted file mode 100644 index d068b7d2..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/jwtclient.js +++ /dev/null @@ -1,284 +0,0 @@ -"use strict"; -// Copyright 2013 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.JWT = void 0; -const gtoken_1 = require("gtoken"); -const jwtaccess_1 = require("./jwtaccess"); -const oauth2client_1 = require("./oauth2client"); -const authclient_1 = require("./authclient"); -class JWT extends oauth2client_1.OAuth2Client { - constructor(optionsOrEmail, keyFile, key, scopes, subject, keyId) { - const opts = optionsOrEmail && typeof optionsOrEmail === 'object' - ? optionsOrEmail - : { email: optionsOrEmail, keyFile, key, keyId, scopes, subject }; - super(opts); - this.email = opts.email; - this.keyFile = opts.keyFile; - this.key = opts.key; - this.keyId = opts.keyId; - this.scopes = opts.scopes; - this.subject = opts.subject; - this.additionalClaims = opts.additionalClaims; - // Start with an expired refresh token, which will automatically be - // refreshed before the first API call is made. - this.credentials = { refresh_token: 'jwt-placeholder', expiry_date: 1 }; - } - /** - * Creates a copy of the credential with the specified scopes. - * @param scopes List of requested scopes or a single scope. - * @return The cloned instance. - */ - createScoped(scopes) { - const jwt = new JWT(this); - jwt.scopes = scopes; - return jwt; - } - /** - * Obtains the metadata to be sent with the request. - * - * @param url the URI being authorized. - */ - async getRequestMetadataAsync(url) { - url = this.defaultServicePath ? `https://${this.defaultServicePath}/` : url; - const useSelfSignedJWT = (!this.hasUserScopes() && url) || - (this.useJWTAccessWithScope && this.hasAnyScopes()) || - this.universeDomain !== authclient_1.DEFAULT_UNIVERSE; - if (this.subject && this.universeDomain !== authclient_1.DEFAULT_UNIVERSE) { - throw new RangeError(`Service Account user is configured for the credential. Domain-wide delegation is not supported in universes other than ${authclient_1.DEFAULT_UNIVERSE}`); - } - if (!this.apiKey && useSelfSignedJWT) { - if (this.additionalClaims && - this.additionalClaims.target_audience) { - const { tokens } = await this.refreshToken(); - return { - headers: this.addSharedMetadataHeaders({ - Authorization: `Bearer ${tokens.id_token}`, - }), - }; - } - else { - // no scopes have been set, but a uri has been provided. Use JWTAccess - // credentials. - if (!this.access) { - this.access = new jwtaccess_1.JWTAccess(this.email, this.key, this.keyId, this.eagerRefreshThresholdMillis); - } - let scopes; - if (this.hasUserScopes()) { - scopes = this.scopes; - } - else if (!url) { - scopes = this.defaultScopes; - } - const useScopes = this.useJWTAccessWithScope || - this.universeDomain !== authclient_1.DEFAULT_UNIVERSE; - const headers = await this.access.getRequestHeaders(url !== null && url !== void 0 ? url : undefined, this.additionalClaims, - // Scopes take precedent over audience for signing, - // so we only provide them if `useJWTAccessWithScope` is on or - // if we are in a non-default universe - useScopes ? scopes : undefined); - return { headers: this.addSharedMetadataHeaders(headers) }; - } - } - else if (this.hasAnyScopes() || this.apiKey) { - return super.getRequestMetadataAsync(url); - } - else { - // If no audience, apiKey, or scopes are provided, we should not attempt - // to populate any headers: - return { headers: {} }; - } - } - /** - * Fetches an ID token. - * @param targetAudience the audience for the fetched ID token. - */ - async fetchIdToken(targetAudience) { - // Create a new gToken for fetching an ID token - const gtoken = new gtoken_1.GoogleToken({ - iss: this.email, - sub: this.subject, - scope: this.scopes || this.defaultScopes, - keyFile: this.keyFile, - key: this.key, - additionalClaims: { target_audience: targetAudience }, - transporter: this.transporter, - }); - await gtoken.getToken({ - forceRefresh: true, - }); - if (!gtoken.idToken) { - throw new Error('Unknown error: Failed to fetch ID token'); - } - return gtoken.idToken; - } - /** - * Determine if there are currently scopes available. - */ - hasUserScopes() { - if (!this.scopes) { - return false; - } - return this.scopes.length > 0; - } - /** - * Are there any default or user scopes defined. - */ - hasAnyScopes() { - if (this.scopes && this.scopes.length > 0) - return true; - if (this.defaultScopes && this.defaultScopes.length > 0) - return true; - return false; - } - authorize(callback) { - if (callback) { - this.authorizeAsync().then(r => callback(null, r), callback); - } - else { - return this.authorizeAsync(); - } - } - async authorizeAsync() { - const result = await this.refreshToken(); - if (!result) { - throw new Error('No result returned'); - } - this.credentials = result.tokens; - this.credentials.refresh_token = 'jwt-placeholder'; - this.key = this.gtoken.key; - this.email = this.gtoken.iss; - return result.tokens; - } - /** - * Refreshes the access token. - * @param refreshToken ignored - * @private - */ - async refreshTokenNoCache( - // eslint-disable-next-line @typescript-eslint/no-unused-vars - refreshToken) { - const gtoken = this.createGToken(); - const token = await gtoken.getToken({ - forceRefresh: this.isTokenExpiring(), - }); - const tokens = { - access_token: token.access_token, - token_type: 'Bearer', - expiry_date: gtoken.expiresAt, - id_token: gtoken.idToken, - }; - this.emit('tokens', tokens); - return { res: null, tokens }; - } - /** - * Create a gToken if it doesn't already exist. - */ - createGToken() { - if (!this.gtoken) { - this.gtoken = new gtoken_1.GoogleToken({ - iss: this.email, - sub: this.subject, - scope: this.scopes || this.defaultScopes, - keyFile: this.keyFile, - key: this.key, - additionalClaims: this.additionalClaims, - transporter: this.transporter, - }); - } - return this.gtoken; - } - /** - * Create a JWT credentials instance using the given input options. - * @param json The input object. - * - * @remarks - * - * **Important**: If you accept a credential configuration (credential JSON/File/Stream) from an external source for authentication to Google Cloud, you must validate it before providing it to any Google API or library. Providing an unvalidated credential configuration to Google APIs can compromise the security of your systems and data. For more information, refer to {@link https://cloud.google.com/docs/authentication/external/externally-sourced-credentials Validate credential configurations from external sources}. - */ - fromJSON(json) { - if (!json) { - throw new Error('Must pass in a JSON object containing the service account auth settings.'); - } - if (!json.client_email) { - throw new Error('The incoming JSON object does not contain a client_email field'); - } - if (!json.private_key) { - throw new Error('The incoming JSON object does not contain a private_key field'); - } - // Extract the relevant information from the json key file. - this.email = json.client_email; - this.key = json.private_key; - this.keyId = json.private_key_id; - this.projectId = json.project_id; - this.quotaProjectId = json.quota_project_id; - this.universeDomain = json.universe_domain || this.universeDomain; - } - fromStream(inputStream, callback) { - if (callback) { - this.fromStreamAsync(inputStream).then(() => callback(), callback); - } - else { - return this.fromStreamAsync(inputStream); - } - } - fromStreamAsync(inputStream) { - return new Promise((resolve, reject) => { - if (!inputStream) { - throw new Error('Must pass in a stream containing the service account auth settings.'); - } - let s = ''; - inputStream - .setEncoding('utf8') - .on('error', reject) - .on('data', chunk => (s += chunk)) - .on('end', () => { - try { - const data = JSON.parse(s); - this.fromJSON(data); - resolve(); - } - catch (e) { - reject(e); - } - }); - }); - } - /** - * Creates a JWT credentials instance using an API Key for authentication. - * @param apiKey The API Key in string form. - */ - fromAPIKey(apiKey) { - if (typeof apiKey !== 'string') { - throw new Error('Must provide an API Key string.'); - } - this.apiKey = apiKey; - } - /** - * Using the key or keyFile on the JWT client, obtain an object that contains - * the key and the client email. - */ - async getCredentials() { - if (this.key) { - return { private_key: this.key, client_email: this.email }; - } - else if (this.keyFile) { - const gtoken = this.createGToken(); - const creds = await gtoken.getCredentials(this.keyFile); - return { private_key: creds.privateKey, client_email: creds.clientEmail }; - } - throw new Error('A key or a keyFile must be provided to getCredentials.'); - } -} -exports.JWT = JWT; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/loginticket.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/loginticket.js deleted file mode 100644 index 9a1687b6..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/loginticket.js +++ /dev/null @@ -1,57 +0,0 @@ -"use strict"; -// Copyright 2014 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.LoginTicket = void 0; -class LoginTicket { - /** - * Create a simple class to extract user ID from an ID Token - * - * @param {string} env Envelope of the jwt - * @param {TokenPayload} pay Payload of the jwt - * @constructor - */ - constructor(env, pay) { - this.envelope = env; - this.payload = pay; - } - getEnvelope() { - return this.envelope; - } - getPayload() { - return this.payload; - } - /** - * Create a simple class to extract user ID from an ID Token - * - * @return The user ID - */ - getUserId() { - const payload = this.getPayload(); - if (payload && payload.sub) { - return payload.sub; - } - return null; - } - /** - * Returns attributes from the login ticket. This can contain - * various information about the user session. - * - * @return The envelope and payload - */ - getAttributes() { - return { envelope: this.getEnvelope(), payload: this.getPayload() }; - } -} -exports.LoginTicket = LoginTicket; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/oauth2client.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/oauth2client.js deleted file mode 100644 index 3764bda9..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/oauth2client.js +++ /dev/null @@ -1,794 +0,0 @@ -"use strict"; -// Copyright 2019 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OAuth2Client = exports.ClientAuthentication = exports.CertificateFormat = exports.CodeChallengeMethod = void 0; -const gaxios_1 = require("gaxios"); -const querystring = require("querystring"); -const stream = require("stream"); -const formatEcdsa = require("ecdsa-sig-formatter"); -const crypto_1 = require("../crypto/crypto"); -const authclient_1 = require("./authclient"); -const loginticket_1 = require("./loginticket"); -var CodeChallengeMethod; -(function (CodeChallengeMethod) { - CodeChallengeMethod["Plain"] = "plain"; - CodeChallengeMethod["S256"] = "S256"; -})(CodeChallengeMethod || (exports.CodeChallengeMethod = CodeChallengeMethod = {})); -var CertificateFormat; -(function (CertificateFormat) { - CertificateFormat["PEM"] = "PEM"; - CertificateFormat["JWK"] = "JWK"; -})(CertificateFormat || (exports.CertificateFormat = CertificateFormat = {})); -/** - * The client authentication type. Supported values are basic, post, and none. - * https://datatracker.ietf.org/doc/html/rfc7591#section-2 - */ -var ClientAuthentication; -(function (ClientAuthentication) { - ClientAuthentication["ClientSecretPost"] = "ClientSecretPost"; - ClientAuthentication["ClientSecretBasic"] = "ClientSecretBasic"; - ClientAuthentication["None"] = "None"; -})(ClientAuthentication || (exports.ClientAuthentication = ClientAuthentication = {})); -class OAuth2Client extends authclient_1.AuthClient { - constructor(optionsOrClientId, clientSecret, redirectUri) { - const opts = optionsOrClientId && typeof optionsOrClientId === 'object' - ? optionsOrClientId - : { clientId: optionsOrClientId, clientSecret, redirectUri }; - super(opts); - this.certificateCache = {}; - this.certificateExpiry = null; - this.certificateCacheFormat = CertificateFormat.PEM; - this.refreshTokenPromises = new Map(); - this._clientId = opts.clientId; - this._clientSecret = opts.clientSecret; - this.redirectUri = opts.redirectUri; - this.endpoints = { - tokenInfoUrl: 'https://oauth2.googleapis.com/tokeninfo', - oauth2AuthBaseUrl: 'https://accounts.google.com/o/oauth2/v2/auth', - oauth2TokenUrl: 'https://oauth2.googleapis.com/token', - oauth2RevokeUrl: 'https://oauth2.googleapis.com/revoke', - oauth2FederatedSignonPemCertsUrl: 'https://www.googleapis.com/oauth2/v1/certs', - oauth2FederatedSignonJwkCertsUrl: 'https://www.googleapis.com/oauth2/v3/certs', - oauth2IapPublicKeyUrl: 'https://www.gstatic.com/iap/verify/public_key', - ...opts.endpoints, - }; - this.clientAuthentication = - opts.clientAuthentication || ClientAuthentication.ClientSecretPost; - this.issuers = opts.issuers || [ - 'accounts.google.com', - 'https://accounts.google.com', - this.universeDomain, - ]; - } - /** - * Generates URL for consent page landing. - * @param opts Options. - * @return URL to consent page. - */ - generateAuthUrl(opts = {}) { - if (opts.code_challenge_method && !opts.code_challenge) { - throw new Error('If a code_challenge_method is provided, code_challenge must be included.'); - } - opts.response_type = opts.response_type || 'code'; - opts.client_id = opts.client_id || this._clientId; - opts.redirect_uri = opts.redirect_uri || this.redirectUri; - // Allow scopes to be passed either as array or a string - if (Array.isArray(opts.scope)) { - opts.scope = opts.scope.join(' '); - } - const rootUrl = this.endpoints.oauth2AuthBaseUrl.toString(); - return (rootUrl + - '?' + - querystring.stringify(opts)); - } - generateCodeVerifier() { - // To make the code compatible with browser SubtleCrypto we need to make - // this method async. - throw new Error('generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.'); - } - /** - * Convenience method to automatically generate a code_verifier, and its - * resulting SHA256. If used, this must be paired with a S256 - * code_challenge_method. - * - * For a full example see: - * https://github.com/googleapis/google-auth-library-nodejs/blob/main/samples/oauth2-codeVerifier.js - */ - async generateCodeVerifierAsync() { - // base64 encoding uses 6 bits per character, and we want to generate128 - // characters. 6*128/8 = 96. - const crypto = (0, crypto_1.createCrypto)(); - const randomString = crypto.randomBytesBase64(96); - // The valid characters in the code_verifier are [A-Z]/[a-z]/[0-9]/ - // "-"/"."/"_"/"~". Base64 encoded strings are pretty close, so we're just - // swapping out a few chars. - const codeVerifier = randomString - .replace(/\+/g, '~') - .replace(/=/g, '_') - .replace(/\//g, '-'); - // Generate the base64 encoded SHA256 - const unencodedCodeChallenge = await crypto.sha256DigestBase64(codeVerifier); - // We need to use base64UrlEncoding instead of standard base64 - const codeChallenge = unencodedCodeChallenge - .split('=')[0] - .replace(/\+/g, '-') - .replace(/\//g, '_'); - return { codeVerifier, codeChallenge }; - } - getToken(codeOrOptions, callback) { - const options = typeof codeOrOptions === 'string' ? { code: codeOrOptions } : codeOrOptions; - if (callback) { - this.getTokenAsync(options).then(r => callback(null, r.tokens, r.res), e => callback(e, null, e.response)); - } - else { - return this.getTokenAsync(options); - } - } - async getTokenAsync(options) { - const url = this.endpoints.oauth2TokenUrl.toString(); - const headers = { - 'Content-Type': 'application/x-www-form-urlencoded', - }; - const values = { - client_id: options.client_id || this._clientId, - code_verifier: options.codeVerifier, - code: options.code, - grant_type: 'authorization_code', - redirect_uri: options.redirect_uri || this.redirectUri, - }; - if (this.clientAuthentication === ClientAuthentication.ClientSecretBasic) { - const basic = Buffer.from(`${this._clientId}:${this._clientSecret}`); - headers['Authorization'] = `Basic ${basic.toString('base64')}`; - } - if (this.clientAuthentication === ClientAuthentication.ClientSecretPost) { - values.client_secret = this._clientSecret; - } - const res = await this.transporter.request({ - ...OAuth2Client.RETRY_CONFIG, - method: 'POST', - url, - data: querystring.stringify(values), - headers, - }); - const tokens = res.data; - if (res.data && res.data.expires_in) { - tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000; - delete tokens.expires_in; - } - this.emit('tokens', tokens); - return { tokens, res }; - } - /** - * Refreshes the access token. - * @param refresh_token Existing refresh token. - * @private - */ - async refreshToken(refreshToken) { - if (!refreshToken) { - return this.refreshTokenNoCache(refreshToken); - } - // If a request to refresh using the same token has started, - // return the same promise. - if (this.refreshTokenPromises.has(refreshToken)) { - return this.refreshTokenPromises.get(refreshToken); - } - const p = this.refreshTokenNoCache(refreshToken).then(r => { - this.refreshTokenPromises.delete(refreshToken); - return r; - }, e => { - this.refreshTokenPromises.delete(refreshToken); - throw e; - }); - this.refreshTokenPromises.set(refreshToken, p); - return p; - } - async refreshTokenNoCache(refreshToken) { - var _a; - if (!refreshToken) { - throw new Error('No refresh token is set.'); - } - const url = this.endpoints.oauth2TokenUrl.toString(); - const data = { - refresh_token: refreshToken, - client_id: this._clientId, - client_secret: this._clientSecret, - grant_type: 'refresh_token', - }; - let res; - try { - // request for new token - res = await this.transporter.request({ - ...OAuth2Client.RETRY_CONFIG, - method: 'POST', - url, - data: querystring.stringify(data), - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, - }); - } - catch (e) { - if (e instanceof gaxios_1.GaxiosError && - e.message === 'invalid_grant' && - ((_a = e.response) === null || _a === void 0 ? void 0 : _a.data) && - /ReAuth/i.test(e.response.data.error_description)) { - e.message = JSON.stringify(e.response.data); - } - throw e; - } - const tokens = res.data; - // TODO: de-duplicate this code from a few spots - if (res.data && res.data.expires_in) { - tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000; - delete tokens.expires_in; - } - this.emit('tokens', tokens); - return { tokens, res }; - } - refreshAccessToken(callback) { - if (callback) { - this.refreshAccessTokenAsync().then(r => callback(null, r.credentials, r.res), callback); - } - else { - return this.refreshAccessTokenAsync(); - } - } - async refreshAccessTokenAsync() { - const r = await this.refreshToken(this.credentials.refresh_token); - const tokens = r.tokens; - tokens.refresh_token = this.credentials.refresh_token; - this.credentials = tokens; - return { credentials: this.credentials, res: r.res }; - } - getAccessToken(callback) { - if (callback) { - this.getAccessTokenAsync().then(r => callback(null, r.token, r.res), callback); - } - else { - return this.getAccessTokenAsync(); - } - } - async getAccessTokenAsync() { - const shouldRefresh = !this.credentials.access_token || this.isTokenExpiring(); - if (shouldRefresh) { - if (!this.credentials.refresh_token) { - if (this.refreshHandler) { - const refreshedAccessToken = await this.processAndValidateRefreshHandler(); - if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) { - this.setCredentials(refreshedAccessToken); - return { token: this.credentials.access_token }; - } - } - else { - throw new Error('No refresh token or refresh handler callback is set.'); - } - } - const r = await this.refreshAccessTokenAsync(); - if (!r.credentials || (r.credentials && !r.credentials.access_token)) { - throw new Error('Could not refresh access token.'); - } - return { token: r.credentials.access_token, res: r.res }; - } - else { - return { token: this.credentials.access_token }; - } - } - /** - * The main authentication interface. It takes an optional url which when - * present is the endpoint being accessed, and returns a Promise which - * resolves with authorization header fields. - * - * In OAuth2Client, the result has the form: - * { Authorization: 'Bearer ' } - * @param url The optional url being authorized - */ - async getRequestHeaders(url) { - const headers = (await this.getRequestMetadataAsync(url)).headers; - return headers; - } - async getRequestMetadataAsync( - // eslint-disable-next-line @typescript-eslint/no-unused-vars - url) { - const thisCreds = this.credentials; - if (!thisCreds.access_token && - !thisCreds.refresh_token && - !this.apiKey && - !this.refreshHandler) { - throw new Error('No access, refresh token, API key or refresh handler callback is set.'); - } - if (thisCreds.access_token && !this.isTokenExpiring()) { - thisCreds.token_type = thisCreds.token_type || 'Bearer'; - const headers = { - Authorization: thisCreds.token_type + ' ' + thisCreds.access_token, - }; - return { headers: this.addSharedMetadataHeaders(headers) }; - } - // If refreshHandler exists, call processAndValidateRefreshHandler(). - if (this.refreshHandler) { - const refreshedAccessToken = await this.processAndValidateRefreshHandler(); - if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) { - this.setCredentials(refreshedAccessToken); - const headers = { - Authorization: 'Bearer ' + this.credentials.access_token, - }; - return { headers: this.addSharedMetadataHeaders(headers) }; - } - } - if (this.apiKey) { - return { headers: { 'X-Goog-Api-Key': this.apiKey } }; - } - let r = null; - let tokens = null; - try { - r = await this.refreshToken(thisCreds.refresh_token); - tokens = r.tokens; - } - catch (err) { - const e = err; - if (e.response && - (e.response.status === 403 || e.response.status === 404)) { - e.message = `Could not refresh access token: ${e.message}`; - } - throw e; - } - const credentials = this.credentials; - credentials.token_type = credentials.token_type || 'Bearer'; - tokens.refresh_token = credentials.refresh_token; - this.credentials = tokens; - const headers = { - Authorization: credentials.token_type + ' ' + tokens.access_token, - }; - return { headers: this.addSharedMetadataHeaders(headers), res: r.res }; - } - /** - * Generates an URL to revoke the given token. - * @param token The existing token to be revoked. - * - * @deprecated use instance method {@link OAuth2Client.getRevokeTokenURL} - */ - static getRevokeTokenUrl(token) { - return new OAuth2Client().getRevokeTokenURL(token).toString(); - } - /** - * Generates a URL to revoke the given token. - * - * @param token The existing token to be revoked. - */ - getRevokeTokenURL(token) { - const url = new URL(this.endpoints.oauth2RevokeUrl); - url.searchParams.append('token', token); - return url; - } - revokeToken(token, callback) { - const opts = { - ...OAuth2Client.RETRY_CONFIG, - url: this.getRevokeTokenURL(token).toString(), - method: 'POST', - }; - if (callback) { - this.transporter - .request(opts) - .then(r => callback(null, r), callback); - } - else { - return this.transporter.request(opts); - } - } - revokeCredentials(callback) { - if (callback) { - this.revokeCredentialsAsync().then(res => callback(null, res), callback); - } - else { - return this.revokeCredentialsAsync(); - } - } - async revokeCredentialsAsync() { - const token = this.credentials.access_token; - this.credentials = {}; - if (token) { - return this.revokeToken(token); - } - else { - throw new Error('No access token to revoke.'); - } - } - request(opts, callback) { - if (callback) { - this.requestAsync(opts).then(r => callback(null, r), e => { - return callback(e, e.response); - }); - } - else { - return this.requestAsync(opts); - } - } - async requestAsync(opts, reAuthRetried = false) { - let r2; - try { - const r = await this.getRequestMetadataAsync(opts.url); - opts.headers = opts.headers || {}; - if (r.headers && r.headers['x-goog-user-project']) { - opts.headers['x-goog-user-project'] = r.headers['x-goog-user-project']; - } - if (r.headers && r.headers.Authorization) { - opts.headers.Authorization = r.headers.Authorization; - } - if (this.apiKey) { - opts.headers['X-Goog-Api-Key'] = this.apiKey; - } - r2 = await this.transporter.request(opts); - } - catch (e) { - const res = e.response; - if (res) { - const statusCode = res.status; - // Retry the request for metadata if the following criteria are true: - // - We haven't already retried. It only makes sense to retry once. - // - The response was a 401 or a 403 - // - The request didn't send a readableStream - // - An access_token and refresh_token were available, but either no - // expiry_date was available or the forceRefreshOnFailure flag is set. - // The absent expiry_date case can happen when developers stash the - // access_token and refresh_token for later use, but the access_token - // fails on the first try because it's expired. Some developers may - // choose to enable forceRefreshOnFailure to mitigate time-related - // errors. - // Or the following criteria are true: - // - We haven't already retried. It only makes sense to retry once. - // - The response was a 401 or a 403 - // - The request didn't send a readableStream - // - No refresh_token was available - // - An access_token and a refreshHandler callback were available, but - // either no expiry_date was available or the forceRefreshOnFailure - // flag is set. The access_token fails on the first try because it's - // expired. Some developers may choose to enable forceRefreshOnFailure - // to mitigate time-related errors. - const mayRequireRefresh = this.credentials && - this.credentials.access_token && - this.credentials.refresh_token && - (!this.credentials.expiry_date || this.forceRefreshOnFailure); - const mayRequireRefreshWithNoRefreshToken = this.credentials && - this.credentials.access_token && - !this.credentials.refresh_token && - (!this.credentials.expiry_date || this.forceRefreshOnFailure) && - this.refreshHandler; - const isReadableStream = res.config.data instanceof stream.Readable; - const isAuthErr = statusCode === 401 || statusCode === 403; - if (!reAuthRetried && - isAuthErr && - !isReadableStream && - mayRequireRefresh) { - await this.refreshAccessTokenAsync(); - return this.requestAsync(opts, true); - } - else if (!reAuthRetried && - isAuthErr && - !isReadableStream && - mayRequireRefreshWithNoRefreshToken) { - const refreshedAccessToken = await this.processAndValidateRefreshHandler(); - if (refreshedAccessToken === null || refreshedAccessToken === void 0 ? void 0 : refreshedAccessToken.access_token) { - this.setCredentials(refreshedAccessToken); - } - return this.requestAsync(opts, true); - } - } - throw e; - } - return r2; - } - verifyIdToken(options, callback) { - // This function used to accept two arguments instead of an options object. - // Check the types to help users upgrade with less pain. - // This check can be removed after a 2.0 release. - if (callback && typeof callback !== 'function') { - throw new Error('This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.'); - } - if (callback) { - this.verifyIdTokenAsync(options).then(r => callback(null, r), callback); - } - else { - return this.verifyIdTokenAsync(options); - } - } - async verifyIdTokenAsync(options) { - if (!options.idToken) { - throw new Error('The verifyIdToken method requires an ID Token'); - } - const response = await this.getFederatedSignonCertsAsync(); - const login = await this.verifySignedJwtWithCertsAsync(options.idToken, response.certs, options.audience, this.issuers, options.maxExpiry); - return login; - } - /** - * Obtains information about the provisioned access token. Especially useful - * if you want to check the scopes that were provisioned to a given token. - * - * @param accessToken Required. The Access Token for which you want to get - * user info. - */ - async getTokenInfo(accessToken) { - const { data } = await this.transporter.request({ - ...OAuth2Client.RETRY_CONFIG, - method: 'POST', - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - Authorization: `Bearer ${accessToken}`, - }, - url: this.endpoints.tokenInfoUrl.toString(), - }); - const info = Object.assign({ - expiry_date: new Date().getTime() + data.expires_in * 1000, - scopes: data.scope.split(' '), - }, data); - delete info.expires_in; - delete info.scope; - return info; - } - getFederatedSignonCerts(callback) { - if (callback) { - this.getFederatedSignonCertsAsync().then(r => callback(null, r.certs, r.res), callback); - } - else { - return this.getFederatedSignonCertsAsync(); - } - } - async getFederatedSignonCertsAsync() { - const nowTime = new Date().getTime(); - const format = (0, crypto_1.hasBrowserCrypto)() - ? CertificateFormat.JWK - : CertificateFormat.PEM; - if (this.certificateExpiry && - nowTime < this.certificateExpiry.getTime() && - this.certificateCacheFormat === format) { - return { certs: this.certificateCache, format }; - } - let res; - let url; - switch (format) { - case CertificateFormat.PEM: - url = this.endpoints.oauth2FederatedSignonPemCertsUrl.toString(); - break; - case CertificateFormat.JWK: - url = this.endpoints.oauth2FederatedSignonJwkCertsUrl.toString(); - break; - default: - throw new Error(`Unsupported certificate format ${format}`); - } - try { - res = await this.transporter.request({ - ...OAuth2Client.RETRY_CONFIG, - url, - }); - } - catch (e) { - if (e instanceof Error) { - e.message = `Failed to retrieve verification certificates: ${e.message}`; - } - throw e; - } - const cacheControl = res ? res.headers['cache-control'] : undefined; - let cacheAge = -1; - if (cacheControl) { - const pattern = new RegExp('max-age=([0-9]*)'); - const regexResult = pattern.exec(cacheControl); - if (regexResult && regexResult.length === 2) { - // Cache results with max-age (in seconds) - cacheAge = Number(regexResult[1]) * 1000; // milliseconds - } - } - let certificates = {}; - switch (format) { - case CertificateFormat.PEM: - certificates = res.data; - break; - case CertificateFormat.JWK: - for (const key of res.data.keys) { - certificates[key.kid] = key; - } - break; - default: - throw new Error(`Unsupported certificate format ${format}`); - } - const now = new Date(); - this.certificateExpiry = - cacheAge === -1 ? null : new Date(now.getTime() + cacheAge); - this.certificateCache = certificates; - this.certificateCacheFormat = format; - return { certs: certificates, format, res }; - } - getIapPublicKeys(callback) { - if (callback) { - this.getIapPublicKeysAsync().then(r => callback(null, r.pubkeys, r.res), callback); - } - else { - return this.getIapPublicKeysAsync(); - } - } - async getIapPublicKeysAsync() { - let res; - const url = this.endpoints.oauth2IapPublicKeyUrl.toString(); - try { - res = await this.transporter.request({ - ...OAuth2Client.RETRY_CONFIG, - url, - }); - } - catch (e) { - if (e instanceof Error) { - e.message = `Failed to retrieve verification certificates: ${e.message}`; - } - throw e; - } - return { pubkeys: res.data, res }; - } - verifySignedJwtWithCerts() { - // To make the code compatible with browser SubtleCrypto we need to make - // this method async. - throw new Error('verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.'); - } - /** - * Verify the id token is signed with the correct certificate - * and is from the correct audience. - * @param jwt The jwt to verify (The ID Token in this case). - * @param certs The array of certs to test the jwt against. - * @param requiredAudience The audience to test the jwt against. - * @param issuers The allowed issuers of the jwt (Optional). - * @param maxExpiry The max expiry the certificate can be (Optional). - * @return Returns a promise resolving to LoginTicket on verification. - */ - async verifySignedJwtWithCertsAsync(jwt, certs, requiredAudience, issuers, maxExpiry) { - const crypto = (0, crypto_1.createCrypto)(); - if (!maxExpiry) { - maxExpiry = OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_; - } - const segments = jwt.split('.'); - if (segments.length !== 3) { - throw new Error('Wrong number of segments in token: ' + jwt); - } - const signed = segments[0] + '.' + segments[1]; - let signature = segments[2]; - let envelope; - let payload; - try { - envelope = JSON.parse(crypto.decodeBase64StringUtf8(segments[0])); - } - catch (err) { - if (err instanceof Error) { - err.message = `Can't parse token envelope: ${segments[0]}': ${err.message}`; - } - throw err; - } - if (!envelope) { - throw new Error("Can't parse token envelope: " + segments[0]); - } - try { - payload = JSON.parse(crypto.decodeBase64StringUtf8(segments[1])); - } - catch (err) { - if (err instanceof Error) { - err.message = `Can't parse token payload '${segments[0]}`; - } - throw err; - } - if (!payload) { - throw new Error("Can't parse token payload: " + segments[1]); - } - if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) { - // If this is not present, then there's no reason to attempt verification - throw new Error('No pem found for envelope: ' + JSON.stringify(envelope)); - } - const cert = certs[envelope.kid]; - if (envelope.alg === 'ES256') { - signature = formatEcdsa.joseToDer(signature, 'ES256').toString('base64'); - } - const verified = await crypto.verify(cert, signed, signature); - if (!verified) { - throw new Error('Invalid token signature: ' + jwt); - } - if (!payload.iat) { - throw new Error('No issue time in token: ' + JSON.stringify(payload)); - } - if (!payload.exp) { - throw new Error('No expiration time in token: ' + JSON.stringify(payload)); - } - const iat = Number(payload.iat); - if (isNaN(iat)) - throw new Error('iat field using invalid format'); - const exp = Number(payload.exp); - if (isNaN(exp)) - throw new Error('exp field using invalid format'); - const now = new Date().getTime() / 1000; - if (exp >= now + maxExpiry) { - throw new Error('Expiration time too far in future: ' + JSON.stringify(payload)); - } - const earliest = iat - OAuth2Client.CLOCK_SKEW_SECS_; - const latest = exp + OAuth2Client.CLOCK_SKEW_SECS_; - if (now < earliest) { - throw new Error('Token used too early, ' + - now + - ' < ' + - earliest + - ': ' + - JSON.stringify(payload)); - } - if (now > latest) { - throw new Error('Token used too late, ' + - now + - ' > ' + - latest + - ': ' + - JSON.stringify(payload)); - } - if (issuers && issuers.indexOf(payload.iss) < 0) { - throw new Error('Invalid issuer, expected one of [' + - issuers + - '], but got ' + - payload.iss); - } - // Check the audience matches if we have one - if (typeof requiredAudience !== 'undefined' && requiredAudience !== null) { - const aud = payload.aud; - let audVerified = false; - // If the requiredAudience is an array, check if it contains token - // audience - if (requiredAudience.constructor === Array) { - audVerified = requiredAudience.indexOf(aud) > -1; - } - else { - audVerified = aud === requiredAudience; - } - if (!audVerified) { - throw new Error('Wrong recipient, payload audience != requiredAudience'); - } - } - return new loginticket_1.LoginTicket(envelope, payload); - } - /** - * Returns a promise that resolves with AccessTokenResponse type if - * refreshHandler is defined. - * If not, nothing is returned. - */ - async processAndValidateRefreshHandler() { - if (this.refreshHandler) { - const accessTokenResponse = await this.refreshHandler(); - if (!accessTokenResponse.access_token) { - throw new Error('No access token is returned by the refreshHandler callback.'); - } - return accessTokenResponse; - } - return; - } - /** - * Returns true if a token is expired or will expire within - * eagerRefreshThresholdMillismilliseconds. - * If there is no expiry time, assumes the token is not expired or expiring. - */ - isTokenExpiring() { - const expiryDate = this.credentials.expiry_date; - return expiryDate - ? expiryDate <= new Date().getTime() + this.eagerRefreshThresholdMillis - : false; - } -} -exports.OAuth2Client = OAuth2Client; -/** - * @deprecated use instance's {@link OAuth2Client.endpoints} - */ -OAuth2Client.GOOGLE_TOKEN_INFO_URL = 'https://oauth2.googleapis.com/tokeninfo'; -/** - * Clock skew - five minutes in seconds - */ -OAuth2Client.CLOCK_SKEW_SECS_ = 300; -/** - * The default max Token Lifetime is one day in seconds - */ -OAuth2Client.DEFAULT_MAX_TOKEN_LIFETIME_SECS_ = 86400; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/oauth2common.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/oauth2common.js deleted file mode 100644 index f580c1e3..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/oauth2common.js +++ /dev/null @@ -1,192 +0,0 @@ -"use strict"; -// Copyright 2021 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.OAuthClientAuthHandler = void 0; -exports.getErrorFromOAuthErrorResponse = getErrorFromOAuthErrorResponse; -const querystring = require("querystring"); -const crypto_1 = require("../crypto/crypto"); -/** List of HTTP methods that accept request bodies. */ -const METHODS_SUPPORTING_REQUEST_BODY = ['PUT', 'POST', 'PATCH']; -/** - * Abstract class for handling client authentication in OAuth-based - * operations. - * When request-body client authentication is used, only application/json and - * application/x-www-form-urlencoded content types for HTTP methods that support - * request bodies are supported. - */ -class OAuthClientAuthHandler { - /** - * Instantiates an OAuth client authentication handler. - * @param clientAuthentication The client auth credentials. - */ - constructor(clientAuthentication) { - this.clientAuthentication = clientAuthentication; - this.crypto = (0, crypto_1.createCrypto)(); - } - /** - * Applies client authentication on the OAuth request's headers or POST - * body but does not process the request. - * @param opts The GaxiosOptions whose headers or data are to be modified - * depending on the client authentication mechanism to be used. - * @param bearerToken The optional bearer token to use for authentication. - * When this is used, no client authentication credentials are needed. - */ - applyClientAuthenticationOptions(opts, bearerToken) { - // Inject authenticated header. - this.injectAuthenticatedHeaders(opts, bearerToken); - // Inject authenticated request body. - if (!bearerToken) { - this.injectAuthenticatedRequestBody(opts); - } - } - /** - * Applies client authentication on the request's header if either - * basic authentication or bearer token authentication is selected. - * - * @param opts The GaxiosOptions whose headers or data are to be modified - * depending on the client authentication mechanism to be used. - * @param bearerToken The optional bearer token to use for authentication. - * When this is used, no client authentication credentials are needed. - */ - injectAuthenticatedHeaders(opts, bearerToken) { - var _a; - // Bearer token prioritized higher than basic Auth. - if (bearerToken) { - opts.headers = opts.headers || {}; - Object.assign(opts.headers, { - Authorization: `Bearer ${bearerToken}}`, - }); - } - else if (((_a = this.clientAuthentication) === null || _a === void 0 ? void 0 : _a.confidentialClientType) === 'basic') { - opts.headers = opts.headers || {}; - const clientId = this.clientAuthentication.clientId; - const clientSecret = this.clientAuthentication.clientSecret || ''; - const base64EncodedCreds = this.crypto.encodeBase64StringUtf8(`${clientId}:${clientSecret}`); - Object.assign(opts.headers, { - Authorization: `Basic ${base64EncodedCreds}`, - }); - } - } - /** - * Applies client authentication on the request's body if request-body - * client authentication is selected. - * - * @param opts The GaxiosOptions whose headers or data are to be modified - * depending on the client authentication mechanism to be used. - */ - injectAuthenticatedRequestBody(opts) { - var _a; - if (((_a = this.clientAuthentication) === null || _a === void 0 ? void 0 : _a.confidentialClientType) === 'request-body') { - const method = (opts.method || 'GET').toUpperCase(); - // Inject authenticated request body. - if (METHODS_SUPPORTING_REQUEST_BODY.indexOf(method) !== -1) { - // Get content-type. - let contentType; - const headers = opts.headers || {}; - for (const key in headers) { - if (key.toLowerCase() === 'content-type' && headers[key]) { - contentType = headers[key].toLowerCase(); - break; - } - } - if (contentType === 'application/x-www-form-urlencoded') { - opts.data = opts.data || ''; - const data = querystring.parse(opts.data); - Object.assign(data, { - client_id: this.clientAuthentication.clientId, - client_secret: this.clientAuthentication.clientSecret || '', - }); - opts.data = querystring.stringify(data); - } - else if (contentType === 'application/json') { - opts.data = opts.data || {}; - Object.assign(opts.data, { - client_id: this.clientAuthentication.clientId, - client_secret: this.clientAuthentication.clientSecret || '', - }); - } - else { - throw new Error(`${contentType} content-types are not supported with ` + - `${this.clientAuthentication.confidentialClientType} ` + - 'client authentication'); - } - } - else { - throw new Error(`${method} HTTP method does not support ` + - `${this.clientAuthentication.confidentialClientType} ` + - 'client authentication'); - } - } - } - /** - * Retry config for Auth-related requests. - * - * @remarks - * - * This is not a part of the default {@link AuthClient.transporter transporter/gaxios} - * config as some downstream APIs would prefer if customers explicitly enable retries, - * such as GCS. - */ - static get RETRY_CONFIG() { - return { - retry: true, - retryConfig: { - httpMethodsToRetry: ['GET', 'PUT', 'POST', 'HEAD', 'OPTIONS', 'DELETE'], - }, - }; - } -} -exports.OAuthClientAuthHandler = OAuthClientAuthHandler; -/** - * Converts an OAuth error response to a native JavaScript Error. - * @param resp The OAuth error response to convert to a native Error object. - * @param err The optional original error. If provided, the error properties - * will be copied to the new error. - * @return The converted native Error object. - */ -function getErrorFromOAuthErrorResponse(resp, err) { - // Error response. - const errorCode = resp.error; - const errorDescription = resp.error_description; - const errorUri = resp.error_uri; - let message = `Error code ${errorCode}`; - if (typeof errorDescription !== 'undefined') { - message += `: ${errorDescription}`; - } - if (typeof errorUri !== 'undefined') { - message += ` - ${errorUri}`; - } - const newError = new Error(message); - // Copy properties from original error to newly generated error. - if (err) { - const keys = Object.keys(err); - if (err.stack) { - // Copy error.stack if available. - keys.push('stack'); - } - keys.forEach(key => { - // Do not overwrite the message field. - if (key !== 'message') { - Object.defineProperty(newError, key, { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - value: err[key], - writable: false, - enumerable: true, - }); - } - }); - } - return newError; -} diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/passthrough.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/passthrough.js deleted file mode 100644 index 07e9812b..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/passthrough.js +++ /dev/null @@ -1,61 +0,0 @@ -"use strict"; -// Copyright 2024 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PassThroughClient = void 0; -const authclient_1 = require("./authclient"); -/** - * An AuthClient without any Authentication information. Useful for: - * - Anonymous access - * - Local Emulators - * - Testing Environments - * - */ -class PassThroughClient extends authclient_1.AuthClient { - /** - * Creates a request without any authentication headers or checks. - * - * @remarks - * - * In testing environments it may be useful to change the provided - * {@link AuthClient.transporter} for any desired request overrides/handling. - * - * @param opts - * @returns The response of the request. - */ - async request(opts) { - return this.transporter.request(opts); - } - /** - * A required method of the base class. - * Always will return an empty object. - * - * @returns {} - */ - async getAccessToken() { - return {}; - } - /** - * A required method of the base class. - * Always will return an empty object. - * - * @returns {} - */ - async getRequestHeaders() { - return {}; - } -} -exports.PassThroughClient = PassThroughClient; -const a = new PassThroughClient(); -a.getAccessToken(); diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js deleted file mode 100644 index acb299d3..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/pluggable-auth-client.js +++ /dev/null @@ -1,215 +0,0 @@ -"use strict"; -// Copyright 2022 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PluggableAuthClient = exports.ExecutableError = void 0; -const baseexternalclient_1 = require("./baseexternalclient"); -const executable_response_1 = require("./executable-response"); -const pluggable_auth_handler_1 = require("./pluggable-auth-handler"); -/** - * Error thrown from the executable run by PluggableAuthClient. - */ -class ExecutableError extends Error { - constructor(message, code) { - super(`The executable failed with exit code: ${code} and error message: ${message}.`); - this.code = code; - Object.setPrototypeOf(this, new.target.prototype); - } -} -exports.ExecutableError = ExecutableError; -/** - * The default executable timeout when none is provided, in milliseconds. - */ -const DEFAULT_EXECUTABLE_TIMEOUT_MILLIS = 30 * 1000; -/** - * The minimum allowed executable timeout in milliseconds. - */ -const MINIMUM_EXECUTABLE_TIMEOUT_MILLIS = 5 * 1000; -/** - * The maximum allowed executable timeout in milliseconds. - */ -const MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS = 120 * 1000; -/** - * The environment variable to check to see if executable can be run. - * Value must be set to '1' for the executable to run. - */ -const GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES = 'GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES'; -/** - * The maximum currently supported executable version. - */ -const MAXIMUM_EXECUTABLE_VERSION = 1; -/** - * PluggableAuthClient enables the exchange of workload identity pool external credentials for - * Google access tokens by retrieving 3rd party tokens through a user supplied executable. These - * scripts/executables are completely independent of the Google Cloud Auth libraries. These - * credentials plug into ADC and will call the specified executable to retrieve the 3rd party token - * to be exchanged for a Google access token. - * - *

    To use these credentials, the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment variable - * must be set to '1'. This is for security reasons. - * - *

    Both OIDC and SAML are supported. The executable must adhere to a specific response format - * defined below. - * - *

    The executable must print out the 3rd party token to STDOUT in JSON format. When an - * output_file is specified in the credential configuration, the executable must also handle writing the - * JSON response to this file. - * - *

    - * OIDC response sample:
    - * {
    - *   "version": 1,
    - *   "success": true,
    - *   "token_type": "urn:ietf:params:oauth:token-type:id_token",
    - *   "id_token": "HEADER.PAYLOAD.SIGNATURE",
    - *   "expiration_time": 1620433341
    - * }
    - *
    - * SAML2 response sample:
    - * {
    - *   "version": 1,
    - *   "success": true,
    - *   "token_type": "urn:ietf:params:oauth:token-type:saml2",
    - *   "saml_response": "...",
    - *   "expiration_time": 1620433341
    - * }
    - *
    - * Error response sample:
    - * {
    - *   "version": 1,
    - *   "success": false,
    - *   "code": "401",
    - *   "message": "Error message."
    - * }
    - * 
    - * - *

    The "expiration_time" field in the JSON response is only required for successful - * responses when an output file was specified in the credential configuration - * - *

    The auth libraries will populate certain environment variables that will be accessible by the - * executable, such as: GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE, GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE, - * GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE, GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL, and - * GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE. - * - *

    Please see this repositories README for a complete executable request/response specification. - */ -class PluggableAuthClient extends baseexternalclient_1.BaseExternalAccountClient { - /** - * Instantiates a PluggableAuthClient instance using the provided JSON - * object loaded from an external account credentials file. - * An error is thrown if the credential is not a valid pluggable auth credential. - * @param options The external account options object typically loaded from - * the external account JSON credential file. - * @param additionalOptions **DEPRECATED, all options are available in the - * `options` parameter.** Optional additional behavior customization options. - * These currently customize expiration threshold time and whether to retry - * on 401/403 API request errors. - */ - constructor(options, additionalOptions) { - super(options, additionalOptions); - if (!options.credential_source.executable) { - throw new Error('No valid Pluggable Auth "credential_source" provided.'); - } - this.command = options.credential_source.executable.command; - if (!this.command) { - throw new Error('No valid Pluggable Auth "credential_source" provided.'); - } - // Check if the provided timeout exists and if it is valid. - if (options.credential_source.executable.timeout_millis === undefined) { - this.timeoutMillis = DEFAULT_EXECUTABLE_TIMEOUT_MILLIS; - } - else { - this.timeoutMillis = options.credential_source.executable.timeout_millis; - if (this.timeoutMillis < MINIMUM_EXECUTABLE_TIMEOUT_MILLIS || - this.timeoutMillis > MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS) { - throw new Error(`Timeout must be between ${MINIMUM_EXECUTABLE_TIMEOUT_MILLIS} and ` + - `${MAXIMUM_EXECUTABLE_TIMEOUT_MILLIS} milliseconds.`); - } - } - this.outputFile = options.credential_source.executable.output_file; - this.handler = new pluggable_auth_handler_1.PluggableAuthHandler({ - command: this.command, - timeoutMillis: this.timeoutMillis, - outputFile: this.outputFile, - }); - this.credentialSourceType = 'executable'; - } - /** - * Triggered when an external subject token is needed to be exchanged for a - * GCP access token via GCP STS endpoint. - * This uses the `options.credential_source` object to figure out how - * to retrieve the token using the current environment. In this case, - * this calls a user provided executable which returns the subject token. - * The logic is summarized as: - * 1. Validated that the executable is allowed to run. The - * GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment must be set to - * 1 for security reasons. - * 2. If an output file is specified by the user, check the file location - * for a response. If the file exists and contains a valid response, - * return the subject token from the file. - * 3. Call the provided executable and return response. - * @return A promise that resolves with the external subject token. - */ - async retrieveSubjectToken() { - // Check if the executable is allowed to run. - if (process.env[GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES] !== '1') { - throw new Error('Pluggable Auth executables need to be explicitly allowed to run by ' + - 'setting the GOOGLE_EXTERNAL_ACCOUNT_ALLOW_EXECUTABLES environment ' + - 'Variable to 1.'); - } - let executableResponse = undefined; - // Try to get cached executable response from output file. - if (this.outputFile) { - executableResponse = await this.handler.retrieveCachedResponse(); - } - // If no response from output file, call the executable. - if (!executableResponse) { - // Set up environment map with required values for the executable. - const envMap = new Map(); - envMap.set('GOOGLE_EXTERNAL_ACCOUNT_AUDIENCE', this.audience); - envMap.set('GOOGLE_EXTERNAL_ACCOUNT_TOKEN_TYPE', this.subjectTokenType); - // Always set to 0 because interactive mode is not supported. - envMap.set('GOOGLE_EXTERNAL_ACCOUNT_INTERACTIVE', '0'); - if (this.outputFile) { - envMap.set('GOOGLE_EXTERNAL_ACCOUNT_OUTPUT_FILE', this.outputFile); - } - const serviceAccountEmail = this.getServiceAccountEmail(); - if (serviceAccountEmail) { - envMap.set('GOOGLE_EXTERNAL_ACCOUNT_IMPERSONATED_EMAIL', serviceAccountEmail); - } - executableResponse = - await this.handler.retrieveResponseFromExecutable(envMap); - } - if (executableResponse.version > MAXIMUM_EXECUTABLE_VERSION) { - throw new Error(`Version of executable is not currently supported, maximum supported version is ${MAXIMUM_EXECUTABLE_VERSION}.`); - } - // Check that response was successful. - if (!executableResponse.success) { - throw new ExecutableError(executableResponse.errorMessage, executableResponse.errorCode); - } - // Check that response contains expiration time if output file was specified. - if (this.outputFile) { - if (!executableResponse.expirationTime) { - throw new executable_response_1.InvalidExpirationTimeFieldError('The executable response must contain the `expiration_time` field for successful responses when an output_file has been specified in the configuration.'); - } - } - // Check that response is not expired. - if (executableResponse.isExpired()) { - throw new Error('Executable response is expired.'); - } - // Return subject token from response. - return executableResponse.subjectToken; - } -} -exports.PluggableAuthClient = PluggableAuthClient; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js deleted file mode 100644 index 47fa2769..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/pluggable-auth-handler.js +++ /dev/null @@ -1,156 +0,0 @@ -"use strict"; -// Copyright 2022 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.PluggableAuthHandler = void 0; -const pluggable_auth_client_1 = require("./pluggable-auth-client"); -const executable_response_1 = require("./executable-response"); -const childProcess = require("child_process"); -const fs = require("fs"); -/** - * A handler used to retrieve 3rd party token responses from user defined - * executables and cached file output for the PluggableAuthClient class. - */ -class PluggableAuthHandler { - /** - * Instantiates a PluggableAuthHandler instance using the provided - * PluggableAuthHandlerOptions object. - */ - constructor(options) { - if (!options.command) { - throw new Error('No command provided.'); - } - this.commandComponents = PluggableAuthHandler.parseCommand(options.command); - this.timeoutMillis = options.timeoutMillis; - if (!this.timeoutMillis) { - throw new Error('No timeoutMillis provided.'); - } - this.outputFile = options.outputFile; - } - /** - * Calls user provided executable to get a 3rd party subject token and - * returns the response. - * @param envMap a Map of additional Environment Variables required for - * the executable. - * @return A promise that resolves with the executable response. - */ - retrieveResponseFromExecutable(envMap) { - return new Promise((resolve, reject) => { - // Spawn process to run executable using added environment variables. - const child = childProcess.spawn(this.commandComponents[0], this.commandComponents.slice(1), { - env: { ...process.env, ...Object.fromEntries(envMap) }, - }); - let output = ''; - // Append stdout to output as executable runs. - child.stdout.on('data', (data) => { - output += data; - }); - // Append stderr as executable runs. - child.stderr.on('data', (err) => { - output += err; - }); - // Set up a timeout to end the child process and throw an error. - const timeout = setTimeout(() => { - // Kill child process and remove listeners so 'close' event doesn't get - // read after child process is killed. - child.removeAllListeners(); - child.kill(); - return reject(new Error('The executable failed to finish within the timeout specified.')); - }, this.timeoutMillis); - child.on('close', (code) => { - // Cancel timeout if executable closes before timeout is reached. - clearTimeout(timeout); - if (code === 0) { - // If the executable completed successfully, try to return the parsed response. - try { - const responseJson = JSON.parse(output); - const response = new executable_response_1.ExecutableResponse(responseJson); - return resolve(response); - } - catch (error) { - if (error instanceof executable_response_1.ExecutableResponseError) { - return reject(error); - } - return reject(new executable_response_1.ExecutableResponseError(`The executable returned an invalid response: ${output}`)); - } - } - else { - return reject(new pluggable_auth_client_1.ExecutableError(output, code.toString())); - } - }); - }); - } - /** - * Checks user provided output file for response from previous run of - * executable and return the response if it exists, is formatted correctly, and is not expired. - */ - async retrieveCachedResponse() { - if (!this.outputFile || this.outputFile.length === 0) { - return undefined; - } - let filePath; - try { - filePath = await fs.promises.realpath(this.outputFile); - } - catch (_a) { - // If file path cannot be resolved, return undefined. - return undefined; - } - if (!(await fs.promises.lstat(filePath)).isFile()) { - // If path does not lead to file, return undefined. - return undefined; - } - const responseString = await fs.promises.readFile(filePath, { - encoding: 'utf8', - }); - if (responseString === '') { - return undefined; - } - try { - const responseJson = JSON.parse(responseString); - const response = new executable_response_1.ExecutableResponse(responseJson); - // Check if response is successful and unexpired. - if (response.isValid()) { - return new executable_response_1.ExecutableResponse(responseJson); - } - return undefined; - } - catch (error) { - if (error instanceof executable_response_1.ExecutableResponseError) { - throw error; - } - throw new executable_response_1.ExecutableResponseError(`The output file contained an invalid response: ${responseString}`); - } - } - /** - * Parses given command string into component array, splitting on spaces unless - * spaces are between quotation marks. - */ - static parseCommand(command) { - // Split the command into components by splitting on spaces, - // unless spaces are contained in quotation marks. - const components = command.match(/(?:[^\s"]+|"[^"]*")+/g); - if (!components) { - throw new Error(`Provided command: "${command}" could not be parsed.`); - } - // Remove quotation marks from the beginning and end of each component if they are present. - for (let i = 0; i < components.length; i++) { - if (components[i][0] === '"' && components[i].slice(-1) === '"') { - components[i] = components[i].slice(1, -1); - } - } - return components; - } -} -exports.PluggableAuthHandler = PluggableAuthHandler; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/refreshclient.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/refreshclient.js deleted file mode 100644 index 85a5f181..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/refreshclient.js +++ /dev/null @@ -1,132 +0,0 @@ -"use strict"; -// Copyright 2015 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.UserRefreshClient = exports.USER_REFRESH_ACCOUNT_TYPE = void 0; -const oauth2client_1 = require("./oauth2client"); -const querystring_1 = require("querystring"); -exports.USER_REFRESH_ACCOUNT_TYPE = 'authorized_user'; -class UserRefreshClient extends oauth2client_1.OAuth2Client { - constructor(optionsOrClientId, clientSecret, refreshToken, eagerRefreshThresholdMillis, forceRefreshOnFailure) { - const opts = optionsOrClientId && typeof optionsOrClientId === 'object' - ? optionsOrClientId - : { - clientId: optionsOrClientId, - clientSecret, - refreshToken, - eagerRefreshThresholdMillis, - forceRefreshOnFailure, - }; - super(opts); - this._refreshToken = opts.refreshToken; - this.credentials.refresh_token = opts.refreshToken; - } - /** - * Refreshes the access token. - * @param refreshToken An ignored refreshToken.. - * @param callback Optional callback. - */ - async refreshTokenNoCache( - // eslint-disable-next-line @typescript-eslint/no-unused-vars - refreshToken) { - return super.refreshTokenNoCache(this._refreshToken); - } - async fetchIdToken(targetAudience) { - const res = await this.transporter.request({ - ...UserRefreshClient.RETRY_CONFIG, - url: this.endpoints.oauth2TokenUrl, - headers: { - 'Content-Type': 'application/x-www-form-urlencoded', - }, - method: 'POST', - data: (0, querystring_1.stringify)({ - client_id: this._clientId, - client_secret: this._clientSecret, - grant_type: 'refresh_token', - refresh_token: this._refreshToken, - target_audience: targetAudience, - }), - }); - return res.data.id_token; - } - /** - * Create a UserRefreshClient credentials instance using the given input - * options. - * @param json The input object. - */ - fromJSON(json) { - if (!json) { - throw new Error('Must pass in a JSON object containing the user refresh token'); - } - if (json.type !== 'authorized_user') { - throw new Error('The incoming JSON object does not have the "authorized_user" type'); - } - if (!json.client_id) { - throw new Error('The incoming JSON object does not contain a client_id field'); - } - if (!json.client_secret) { - throw new Error('The incoming JSON object does not contain a client_secret field'); - } - if (!json.refresh_token) { - throw new Error('The incoming JSON object does not contain a refresh_token field'); - } - this._clientId = json.client_id; - this._clientSecret = json.client_secret; - this._refreshToken = json.refresh_token; - this.credentials.refresh_token = json.refresh_token; - this.quotaProjectId = json.quota_project_id; - this.universeDomain = json.universe_domain || this.universeDomain; - } - fromStream(inputStream, callback) { - if (callback) { - this.fromStreamAsync(inputStream).then(() => callback(), callback); - } - else { - return this.fromStreamAsync(inputStream); - } - } - async fromStreamAsync(inputStream) { - return new Promise((resolve, reject) => { - if (!inputStream) { - return reject(new Error('Must pass in a stream containing the user refresh token.')); - } - let s = ''; - inputStream - .setEncoding('utf8') - .on('error', reject) - .on('data', chunk => (s += chunk)) - .on('end', () => { - try { - const data = JSON.parse(s); - this.fromJSON(data); - return resolve(); - } - catch (err) { - return reject(err); - } - }); - }); - } - /** - * Create a UserRefreshClient credentials instance using the given input - * options. - * @param json The input object. - */ - static fromJSON(json) { - const client = new UserRefreshClient(); - client.fromJSON(json); - return client; - } -} -exports.UserRefreshClient = UserRefreshClient; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/stscredentials.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/stscredentials.js deleted file mode 100644 index 46edef1c..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/stscredentials.js +++ /dev/null @@ -1,109 +0,0 @@ -"use strict"; -// Copyright 2021 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.StsCredentials = void 0; -const gaxios_1 = require("gaxios"); -const querystring = require("querystring"); -const transporters_1 = require("../transporters"); -const oauth2common_1 = require("./oauth2common"); -/** - * Implements the OAuth 2.0 token exchange based on - * https://tools.ietf.org/html/rfc8693 - */ -class StsCredentials extends oauth2common_1.OAuthClientAuthHandler { - /** - * Initializes an STS credentials instance. - * @param tokenExchangeEndpoint The token exchange endpoint. - * @param clientAuthentication The client authentication credentials if - * available. - */ - constructor(tokenExchangeEndpoint, clientAuthentication) { - super(clientAuthentication); - this.tokenExchangeEndpoint = tokenExchangeEndpoint; - this.transporter = new transporters_1.DefaultTransporter(); - } - /** - * Exchanges the provided token for another type of token based on the - * rfc8693 spec. - * @param stsCredentialsOptions The token exchange options used to populate - * the token exchange request. - * @param additionalHeaders Optional additional headers to pass along the - * request. - * @param options Optional additional GCP-specific non-spec defined options - * to send with the request. - * Example: `&options=${encodeUriComponent(JSON.stringified(options))}` - * @return A promise that resolves with the token exchange response containing - * the requested token and its expiration time. - */ - async exchangeToken(stsCredentialsOptions, additionalHeaders, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - options) { - var _a, _b, _c; - const values = { - grant_type: stsCredentialsOptions.grantType, - resource: stsCredentialsOptions.resource, - audience: stsCredentialsOptions.audience, - scope: (_a = stsCredentialsOptions.scope) === null || _a === void 0 ? void 0 : _a.join(' '), - requested_token_type: stsCredentialsOptions.requestedTokenType, - subject_token: stsCredentialsOptions.subjectToken, - subject_token_type: stsCredentialsOptions.subjectTokenType, - actor_token: (_b = stsCredentialsOptions.actingParty) === null || _b === void 0 ? void 0 : _b.actorToken, - actor_token_type: (_c = stsCredentialsOptions.actingParty) === null || _c === void 0 ? void 0 : _c.actorTokenType, - // Non-standard GCP-specific options. - options: options && JSON.stringify(options), - }; - // Remove undefined fields. - Object.keys(values).forEach(key => { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (typeof values[key] === 'undefined') { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - delete values[key]; - } - }); - const headers = { - 'Content-Type': 'application/x-www-form-urlencoded', - }; - // Inject additional STS headers if available. - Object.assign(headers, additionalHeaders || {}); - const opts = { - ...StsCredentials.RETRY_CONFIG, - url: this.tokenExchangeEndpoint.toString(), - method: 'POST', - headers, - data: querystring.stringify(values), - responseType: 'json', - }; - // Apply OAuth client authentication. - this.applyClientAuthenticationOptions(opts); - try { - const response = await this.transporter.request(opts); - // Successful response. - const stsSuccessfulResponse = response.data; - stsSuccessfulResponse.res = response; - return stsSuccessfulResponse; - } - catch (error) { - // Translate error to OAuthError. - if (error instanceof gaxios_1.GaxiosError && error.response) { - throw (0, oauth2common_1.getErrorFromOAuthErrorResponse)(error.response.data, - // Preserve other fields from the original error. - error); - } - // Request could fail before the server responds. - throw error; - } - } -} -exports.StsCredentials = StsCredentials; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js b/claude-code-source/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js deleted file mode 100644 index 317736e5..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/auth/urlsubjecttokensupplier.js +++ /dev/null @@ -1,63 +0,0 @@ -"use strict"; -// Copyright 2024 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.UrlSubjectTokenSupplier = void 0; -/** - * Internal subject token supplier implementation used when a URL - * is configured in the credential configuration used to build an {@link IdentityPoolClient} - */ -class UrlSubjectTokenSupplier { - /** - * Instantiates a URL subject token supplier. - * @param opts The URL subject token supplier options to build the supplier with. - */ - constructor(opts) { - this.url = opts.url; - this.formatType = opts.formatType; - this.subjectTokenFieldName = opts.subjectTokenFieldName; - this.headers = opts.headers; - this.additionalGaxiosOptions = opts.additionalGaxiosOptions; - } - /** - * Sends a GET request to the URL provided in the constructor and resolves - * with the returned external subject token. - * @param context {@link ExternalAccountSupplierContext} from the calling - * {@link IdentityPoolClient}, contains the requested audience and subject - * token type for the external account identity. Not used. - */ - async getSubjectToken(context) { - const opts = { - ...this.additionalGaxiosOptions, - url: this.url, - method: 'GET', - headers: this.headers, - responseType: this.formatType, - }; - let subjectToken; - if (this.formatType === 'text') { - const response = await context.transporter.request(opts); - subjectToken = response.data; - } - else if (this.formatType === 'json' && this.subjectTokenFieldName) { - const response = await context.transporter.request(opts); - subjectToken = response.data[this.subjectTokenFieldName]; - } - if (!subjectToken) { - throw new Error('Unable to parse the subject_token from the credential_source URL'); - } - return subjectToken; - } -} -exports.UrlSubjectTokenSupplier = UrlSubjectTokenSupplier; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/crypto/browser/crypto.js b/claude-code-source/node_modules/google-auth-library/build/src/crypto/browser/crypto.js deleted file mode 100644 index ccc6b571..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/crypto/browser/crypto.js +++ /dev/null @@ -1,126 +0,0 @@ -"use strict"; -// Copyright 2019 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -/* global window */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.BrowserCrypto = void 0; -// This file implements crypto functions we need using in-browser -// SubtleCrypto interface `window.crypto.subtle`. -const base64js = require("base64-js"); -const crypto_1 = require("../crypto"); -class BrowserCrypto { - constructor() { - if (typeof window === 'undefined' || - window.crypto === undefined || - window.crypto.subtle === undefined) { - throw new Error("SubtleCrypto not found. Make sure it's an https:// website."); - } - } - async sha256DigestBase64(str) { - // SubtleCrypto digest() method is async, so we must make - // this method async as well. - // To calculate SHA256 digest using SubtleCrypto, we first - // need to convert an input string to an ArrayBuffer: - const inputBuffer = new TextEncoder().encode(str); - // Result is ArrayBuffer as well. - const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer); - return base64js.fromByteArray(new Uint8Array(outputBuffer)); - } - randomBytesBase64(count) { - const array = new Uint8Array(count); - window.crypto.getRandomValues(array); - return base64js.fromByteArray(array); - } - static padBase64(base64) { - // base64js requires padding, so let's add some '=' - while (base64.length % 4 !== 0) { - base64 += '='; - } - return base64; - } - async verify(pubkey, data, signature) { - const algo = { - name: 'RSASSA-PKCS1-v1_5', - hash: { name: 'SHA-256' }, - }; - const dataArray = new TextEncoder().encode(data); - const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature)); - const cryptoKey = await window.crypto.subtle.importKey('jwk', pubkey, algo, true, ['verify']); - // SubtleCrypto's verify method is async so we must make - // this method async as well. - const result = await window.crypto.subtle.verify(algo, cryptoKey, signatureArray, dataArray); - return result; - } - async sign(privateKey, data) { - const algo = { - name: 'RSASSA-PKCS1-v1_5', - hash: { name: 'SHA-256' }, - }; - const dataArray = new TextEncoder().encode(data); - const cryptoKey = await window.crypto.subtle.importKey('jwk', privateKey, algo, true, ['sign']); - // SubtleCrypto's sign method is async so we must make - // this method async as well. - const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray); - return base64js.fromByteArray(new Uint8Array(result)); - } - decodeBase64StringUtf8(base64) { - const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64)); - const result = new TextDecoder().decode(uint8array); - return result; - } - encodeBase64StringUtf8(text) { - const uint8array = new TextEncoder().encode(text); - const result = base64js.fromByteArray(uint8array); - return result; - } - /** - * Computes the SHA-256 hash of the provided string. - * @param str The plain text string to hash. - * @return A promise that resolves with the SHA-256 hash of the provided - * string in hexadecimal encoding. - */ - async sha256DigestHex(str) { - // SubtleCrypto digest() method is async, so we must make - // this method async as well. - // To calculate SHA256 digest using SubtleCrypto, we first - // need to convert an input string to an ArrayBuffer: - const inputBuffer = new TextEncoder().encode(str); - // Result is ArrayBuffer as well. - const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer); - return (0, crypto_1.fromArrayBufferToHex)(outputBuffer); - } - /** - * Computes the HMAC hash of a message using the provided crypto key and the - * SHA-256 algorithm. - * @param key The secret crypto key in utf-8 or ArrayBuffer format. - * @param msg The plain text message. - * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer - * format. - */ - async signWithHmacSha256(key, msg) { - // Convert key, if provided in ArrayBuffer format, to string. - const rawKey = typeof key === 'string' - ? key - : String.fromCharCode(...new Uint16Array(key)); - const enc = new TextEncoder(); - const cryptoKey = await window.crypto.subtle.importKey('raw', enc.encode(rawKey), { - name: 'HMAC', - hash: { - name: 'SHA-256', - }, - }, false, ['sign']); - return window.crypto.subtle.sign('HMAC', cryptoKey, enc.encode(msg)); - } -} -exports.BrowserCrypto = BrowserCrypto; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/crypto/crypto.js b/claude-code-source/node_modules/google-auth-library/build/src/crypto/crypto.js deleted file mode 100644 index b66fddae..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/crypto/crypto.js +++ /dev/null @@ -1,47 +0,0 @@ -"use strict"; -// Copyright 2019 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -/* global window */ -Object.defineProperty(exports, "__esModule", { value: true }); -exports.createCrypto = createCrypto; -exports.hasBrowserCrypto = hasBrowserCrypto; -exports.fromArrayBufferToHex = fromArrayBufferToHex; -const crypto_1 = require("./browser/crypto"); -const crypto_2 = require("./node/crypto"); -function createCrypto() { - if (hasBrowserCrypto()) { - return new crypto_1.BrowserCrypto(); - } - return new crypto_2.NodeCrypto(); -} -function hasBrowserCrypto() { - return (typeof window !== 'undefined' && - typeof window.crypto !== 'undefined' && - typeof window.crypto.subtle !== 'undefined'); -} -/** - * Converts an ArrayBuffer to a hexadecimal string. - * @param arrayBuffer The ArrayBuffer to convert to hexadecimal string. - * @return The hexadecimal encoding of the ArrayBuffer. - */ -function fromArrayBufferToHex(arrayBuffer) { - // Convert buffer to byte array. - const byteArray = Array.from(new Uint8Array(arrayBuffer)); - // Convert bytes to hex string. - return byteArray - .map(byte => { - return byte.toString(16).padStart(2, '0'); - }) - .join(''); -} diff --git a/claude-code-source/node_modules/google-auth-library/build/src/crypto/node/crypto.js b/claude-code-source/node_modules/google-auth-library/build/src/crypto/node/crypto.js deleted file mode 100644 index 26ede463..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/crypto/node/crypto.js +++ /dev/null @@ -1,82 +0,0 @@ -"use strict"; -// Copyright 2019 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.NodeCrypto = void 0; -const crypto = require("crypto"); -class NodeCrypto { - async sha256DigestBase64(str) { - return crypto.createHash('sha256').update(str).digest('base64'); - } - randomBytesBase64(count) { - return crypto.randomBytes(count).toString('base64'); - } - async verify(pubkey, data, signature) { - const verifier = crypto.createVerify('RSA-SHA256'); - verifier.update(data); - verifier.end(); - return verifier.verify(pubkey, signature, 'base64'); - } - async sign(privateKey, data) { - const signer = crypto.createSign('RSA-SHA256'); - signer.update(data); - signer.end(); - return signer.sign(privateKey, 'base64'); - } - decodeBase64StringUtf8(base64) { - return Buffer.from(base64, 'base64').toString('utf-8'); - } - encodeBase64StringUtf8(text) { - return Buffer.from(text, 'utf-8').toString('base64'); - } - /** - * Computes the SHA-256 hash of the provided string. - * @param str The plain text string to hash. - * @return A promise that resolves with the SHA-256 hash of the provided - * string in hexadecimal encoding. - */ - async sha256DigestHex(str) { - return crypto.createHash('sha256').update(str).digest('hex'); - } - /** - * Computes the HMAC hash of a message using the provided crypto key and the - * SHA-256 algorithm. - * @param key The secret crypto key in utf-8 or ArrayBuffer format. - * @param msg The plain text message. - * @return A promise that resolves with the HMAC-SHA256 hash in ArrayBuffer - * format. - */ - async signWithHmacSha256(key, msg) { - const cryptoKey = typeof key === 'string' ? key : toBuffer(key); - return toArrayBuffer(crypto.createHmac('sha256', cryptoKey).update(msg).digest()); - } -} -exports.NodeCrypto = NodeCrypto; -/** - * Converts a Node.js Buffer to an ArrayBuffer. - * https://stackoverflow.com/questions/8609289/convert-a-binary-nodejs-buffer-to-javascript-arraybuffer - * @param buffer The Buffer input to covert. - * @return The ArrayBuffer representation of the input. - */ -function toArrayBuffer(buffer) { - return buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength); -} -/** - * Converts an ArrayBuffer to a Node.js Buffer. - * @param arrayBuffer The ArrayBuffer input to covert. - * @return The Buffer representation of the input. - */ -function toBuffer(arrayBuffer) { - return Buffer.from(arrayBuffer); -} diff --git a/claude-code-source/node_modules/google-auth-library/build/src/index.js b/claude-code-source/node_modules/google-auth-library/build/src/index.js deleted file mode 100644 index e0691c2d..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/index.js +++ /dev/null @@ -1,68 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.GoogleAuth = exports.auth = exports.DefaultTransporter = exports.PassThroughClient = exports.ExecutableError = exports.PluggableAuthClient = exports.DownscopedClient = exports.BaseExternalAccountClient = exports.ExternalAccountClient = exports.IdentityPoolClient = exports.AwsRequestSigner = exports.AwsClient = exports.UserRefreshClient = exports.LoginTicket = exports.ClientAuthentication = exports.OAuth2Client = exports.CodeChallengeMethod = exports.Impersonated = exports.JWT = exports.JWTAccess = exports.IdTokenClient = exports.IAMAuth = exports.GCPEnv = exports.Compute = exports.DEFAULT_UNIVERSE = exports.AuthClient = exports.gaxios = exports.gcpMetadata = void 0; -// Copyright 2017 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -const googleauth_1 = require("./auth/googleauth"); -Object.defineProperty(exports, "GoogleAuth", { enumerable: true, get: function () { return googleauth_1.GoogleAuth; } }); -// Export common deps to ensure types/instances are the exact match. Useful -// for consistently configuring the library across versions. -exports.gcpMetadata = require("gcp-metadata"); -exports.gaxios = require("gaxios"); -var authclient_1 = require("./auth/authclient"); -Object.defineProperty(exports, "AuthClient", { enumerable: true, get: function () { return authclient_1.AuthClient; } }); -Object.defineProperty(exports, "DEFAULT_UNIVERSE", { enumerable: true, get: function () { return authclient_1.DEFAULT_UNIVERSE; } }); -var computeclient_1 = require("./auth/computeclient"); -Object.defineProperty(exports, "Compute", { enumerable: true, get: function () { return computeclient_1.Compute; } }); -var envDetect_1 = require("./auth/envDetect"); -Object.defineProperty(exports, "GCPEnv", { enumerable: true, get: function () { return envDetect_1.GCPEnv; } }); -var iam_1 = require("./auth/iam"); -Object.defineProperty(exports, "IAMAuth", { enumerable: true, get: function () { return iam_1.IAMAuth; } }); -var idtokenclient_1 = require("./auth/idtokenclient"); -Object.defineProperty(exports, "IdTokenClient", { enumerable: true, get: function () { return idtokenclient_1.IdTokenClient; } }); -var jwtaccess_1 = require("./auth/jwtaccess"); -Object.defineProperty(exports, "JWTAccess", { enumerable: true, get: function () { return jwtaccess_1.JWTAccess; } }); -var jwtclient_1 = require("./auth/jwtclient"); -Object.defineProperty(exports, "JWT", { enumerable: true, get: function () { return jwtclient_1.JWT; } }); -var impersonated_1 = require("./auth/impersonated"); -Object.defineProperty(exports, "Impersonated", { enumerable: true, get: function () { return impersonated_1.Impersonated; } }); -var oauth2client_1 = require("./auth/oauth2client"); -Object.defineProperty(exports, "CodeChallengeMethod", { enumerable: true, get: function () { return oauth2client_1.CodeChallengeMethod; } }); -Object.defineProperty(exports, "OAuth2Client", { enumerable: true, get: function () { return oauth2client_1.OAuth2Client; } }); -Object.defineProperty(exports, "ClientAuthentication", { enumerable: true, get: function () { return oauth2client_1.ClientAuthentication; } }); -var loginticket_1 = require("./auth/loginticket"); -Object.defineProperty(exports, "LoginTicket", { enumerable: true, get: function () { return loginticket_1.LoginTicket; } }); -var refreshclient_1 = require("./auth/refreshclient"); -Object.defineProperty(exports, "UserRefreshClient", { enumerable: true, get: function () { return refreshclient_1.UserRefreshClient; } }); -var awsclient_1 = require("./auth/awsclient"); -Object.defineProperty(exports, "AwsClient", { enumerable: true, get: function () { return awsclient_1.AwsClient; } }); -var awsrequestsigner_1 = require("./auth/awsrequestsigner"); -Object.defineProperty(exports, "AwsRequestSigner", { enumerable: true, get: function () { return awsrequestsigner_1.AwsRequestSigner; } }); -var identitypoolclient_1 = require("./auth/identitypoolclient"); -Object.defineProperty(exports, "IdentityPoolClient", { enumerable: true, get: function () { return identitypoolclient_1.IdentityPoolClient; } }); -var externalclient_1 = require("./auth/externalclient"); -Object.defineProperty(exports, "ExternalAccountClient", { enumerable: true, get: function () { return externalclient_1.ExternalAccountClient; } }); -var baseexternalclient_1 = require("./auth/baseexternalclient"); -Object.defineProperty(exports, "BaseExternalAccountClient", { enumerable: true, get: function () { return baseexternalclient_1.BaseExternalAccountClient; } }); -var downscopedclient_1 = require("./auth/downscopedclient"); -Object.defineProperty(exports, "DownscopedClient", { enumerable: true, get: function () { return downscopedclient_1.DownscopedClient; } }); -var pluggable_auth_client_1 = require("./auth/pluggable-auth-client"); -Object.defineProperty(exports, "PluggableAuthClient", { enumerable: true, get: function () { return pluggable_auth_client_1.PluggableAuthClient; } }); -Object.defineProperty(exports, "ExecutableError", { enumerable: true, get: function () { return pluggable_auth_client_1.ExecutableError; } }); -var passthrough_1 = require("./auth/passthrough"); -Object.defineProperty(exports, "PassThroughClient", { enumerable: true, get: function () { return passthrough_1.PassThroughClient; } }); -var transporters_1 = require("./transporters"); -Object.defineProperty(exports, "DefaultTransporter", { enumerable: true, get: function () { return transporters_1.DefaultTransporter; } }); -const auth = new googleauth_1.GoogleAuth(); -exports.auth = auth; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/options.js b/claude-code-source/node_modules/google-auth-library/build/src/options.js deleted file mode 100644 index a6db1a6f..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/options.js +++ /dev/null @@ -1,34 +0,0 @@ -"use strict"; -// Copyright 2017 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.validate = validate; -// Accepts an options object passed from the user to the API. In the -// previous version of the API, it referred to a `Request` options object. -// Now it refers to an Axiox Request Config object. This is here to help -// ensure users don't pass invalid options when they upgrade from 0.x to 1.x. -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function validate(options) { - const vpairs = [ - { invalid: 'uri', expected: 'url' }, - { invalid: 'json', expected: 'data' }, - { invalid: 'qs', expected: 'params' }, - ]; - for (const pair of vpairs) { - if (options[pair.invalid]) { - const e = `'${pair.invalid}' is not a valid configuration option. Please use '${pair.expected}' instead. This library is using Axios for requests. Please see https://github.com/axios/axios to learn more about the valid request options.`; - throw new Error(e); - } - } -} diff --git a/claude-code-source/node_modules/google-auth-library/build/src/transporters.js b/claude-code-source/node_modules/google-auth-library/build/src/transporters.js deleted file mode 100644 index 7e9d072e..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/transporters.js +++ /dev/null @@ -1,110 +0,0 @@ -"use strict"; -// Copyright 2019 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.DefaultTransporter = void 0; -const gaxios_1 = require("gaxios"); -const options_1 = require("./options"); -// eslint-disable-next-line @typescript-eslint/no-var-requires -const pkg = require('../../package.json'); -const PRODUCT_NAME = 'google-api-nodejs-client'; -class DefaultTransporter { - constructor() { - /** - * A configurable, replacable `Gaxios` instance. - */ - this.instance = new gaxios_1.Gaxios(); - } - /** - * Configures request options before making a request. - * @param opts GaxiosOptions options. - * @return Configured options. - */ - configure(opts = {}) { - opts.headers = opts.headers || {}; - if (typeof window === 'undefined') { - // set transporter user agent if not in browser - const uaValue = opts.headers['User-Agent']; - if (!uaValue) { - opts.headers['User-Agent'] = DefaultTransporter.USER_AGENT; - } - else if (!uaValue.includes(`${PRODUCT_NAME}/`)) { - opts.headers['User-Agent'] = - `${uaValue} ${DefaultTransporter.USER_AGENT}`; - } - // track google-auth-library-nodejs version: - if (!opts.headers['x-goog-api-client']) { - const nodeVersion = process.version.replace(/^v/, ''); - opts.headers['x-goog-api-client'] = `gl-node/${nodeVersion}`; - } - } - return opts; - } - /** - * Makes a request using Gaxios with given options. - * @param opts GaxiosOptions options. - * @param callback optional callback that contains GaxiosResponse object. - * @return GaxiosPromise, assuming no callback is passed. - */ - request(opts) { - // ensure the user isn't passing in request-style options - opts = this.configure(opts); - (0, options_1.validate)(opts); - return this.instance.request(opts).catch(e => { - throw this.processError(e); - }); - } - get defaults() { - return this.instance.defaults; - } - set defaults(opts) { - this.instance.defaults = opts; - } - /** - * Changes the error to include details from the body. - */ - processError(e) { - const res = e.response; - const err = e; - const body = res ? res.data : null; - if (res && body && body.error && res.status !== 200) { - if (typeof body.error === 'string') { - err.message = body.error; - err.status = res.status; - } - else if (Array.isArray(body.error.errors)) { - err.message = body.error.errors - .map((err2) => err2.message) - .join('\n'); - err.code = body.error.code; - err.errors = body.error.errors; - } - else { - err.message = body.error.message; - err.code = body.error.code; - } - } - else if (res && res.status >= 400) { - // Consider all 4xx and 5xx responses errors. - err.message = body; - err.status = res.status; - } - return err; - } -} -exports.DefaultTransporter = DefaultTransporter; -/** - * Default user agent. - */ -DefaultTransporter.USER_AGENT = `${PRODUCT_NAME}/${pkg.version}`; diff --git a/claude-code-source/node_modules/google-auth-library/build/src/util.js b/claude-code-source/node_modules/google-auth-library/build/src/util.js deleted file mode 100644 index 856b7051..00000000 --- a/claude-code-source/node_modules/google-auth-library/build/src/util.js +++ /dev/null @@ -1,125 +0,0 @@ -"use strict"; -// Copyright 2023 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var _LRUCache_instances, _LRUCache_cache, _LRUCache_moveToEnd, _LRUCache_evict; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.LRUCache = void 0; -exports.snakeToCamel = snakeToCamel; -exports.originalOrCamelOptions = originalOrCamelOptions; -/** - * Returns the camel case of a provided string. - * - * @remarks - * - * Match any `_` and not `_` pair, then return the uppercase of the not `_` - * character. - * - * @internal - * - * @param str the string to convert - * @returns the camelCase'd string - */ -function snakeToCamel(str) { - return str.replace(/([_][^_])/g, match => match.slice(1).toUpperCase()); -} -/** - * Get the value of `obj[key]` or `obj[camelCaseKey]`, with a preference - * for original, non-camelCase key. - * - * @param obj object to lookup a value in - * @returns a `get` function for getting `obj[key || snakeKey]`, if available - */ -function originalOrCamelOptions(obj) { - /** - * - * @param key an index of object, preferably snake_case - * @returns the value `obj[key || snakeKey]`, if available - */ - function get(key) { - var _a; - const o = (obj || {}); - return (_a = o[key]) !== null && _a !== void 0 ? _a : o[snakeToCamel(key)]; - } - return { get }; -} -/** - * A simple LRU cache utility. - * Not meant for external usage. - * - * @experimental - * @internal - */ -class LRUCache { - constructor(options) { - _LRUCache_instances.add(this); - /** - * Maps are in order. Thus, the older item is the first item. - * - * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map} - */ - _LRUCache_cache.set(this, new Map()); - this.capacity = options.capacity; - this.maxAge = options.maxAge; - } - /** - * Add an item to the cache. - * - * @param key the key to upsert - * @param value the value of the key - */ - set(key, value) { - __classPrivateFieldGet(this, _LRUCache_instances, "m", _LRUCache_moveToEnd).call(this, key, value); - __classPrivateFieldGet(this, _LRUCache_instances, "m", _LRUCache_evict).call(this); - } - /** - * Get an item from the cache. - * - * @param key the key to retrieve - */ - get(key) { - const item = __classPrivateFieldGet(this, _LRUCache_cache, "f").get(key); - if (!item) - return; - __classPrivateFieldGet(this, _LRUCache_instances, "m", _LRUCache_moveToEnd).call(this, key, item.value); - __classPrivateFieldGet(this, _LRUCache_instances, "m", _LRUCache_evict).call(this); - return item.value; - } -} -exports.LRUCache = LRUCache; -_LRUCache_cache = new WeakMap(), _LRUCache_instances = new WeakSet(), _LRUCache_moveToEnd = function _LRUCache_moveToEnd(key, value) { - __classPrivateFieldGet(this, _LRUCache_cache, "f").delete(key); - __classPrivateFieldGet(this, _LRUCache_cache, "f").set(key, { - value, - lastAccessed: Date.now(), - }); -}, _LRUCache_evict = function _LRUCache_evict() { - const cutoffDate = this.maxAge ? Date.now() - this.maxAge : 0; - /** - * Because we know Maps are in order, this item is both the - * last item in the list (capacity) and oldest (maxAge). - */ - let oldestItem = __classPrivateFieldGet(this, _LRUCache_cache, "f").entries().next(); - while (!oldestItem.done && - (__classPrivateFieldGet(this, _LRUCache_cache, "f").size > this.capacity || // too many - oldestItem.value[1].lastAccessed < cutoffDate) // too old - ) { - __classPrivateFieldGet(this, _LRUCache_cache, "f").delete(oldestItem.value[0]); - oldestItem = __classPrivateFieldGet(this, _LRUCache_cache, "f").entries().next(); - } -}; diff --git a/claude-code-source/node_modules/google-logging-utils/build/src/colours.js b/claude-code-source/node_modules/google-logging-utils/build/src/colours.js deleted file mode 100644 index 5132d72d..00000000 --- a/claude-code-source/node_modules/google-logging-utils/build/src/colours.js +++ /dev/null @@ -1,80 +0,0 @@ -"use strict"; -// Copyright 2024 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -Object.defineProperty(exports, "__esModule", { value: true }); -exports.Colours = void 0; -/** - * Handles figuring out if we can use ANSI colours and handing out the escape codes. - * - * This is for package-internal use only, and may change at any time. - * - * @private - * @internal - */ -class Colours { - /** - * @param stream The stream (e.g. process.stderr) - * @returns true if the stream should have colourization enabled - */ - static isEnabled(stream) { - return (stream.isTTY && - (typeof stream.getColorDepth === 'function' - ? stream.getColorDepth() > 2 - : true)); - } - static refresh() { - Colours.enabled = Colours.isEnabled(process.stderr); - if (!this.enabled) { - Colours.reset = ''; - Colours.bright = ''; - Colours.dim = ''; - Colours.red = ''; - Colours.green = ''; - Colours.yellow = ''; - Colours.blue = ''; - Colours.magenta = ''; - Colours.cyan = ''; - Colours.white = ''; - Colours.grey = ''; - } - else { - Colours.reset = '\u001b[0m'; - Colours.bright = '\u001b[1m'; - Colours.dim = '\u001b[2m'; - Colours.red = '\u001b[31m'; - Colours.green = '\u001b[32m'; - Colours.yellow = '\u001b[33m'; - Colours.blue = '\u001b[34m'; - Colours.magenta = '\u001b[35m'; - Colours.cyan = '\u001b[36m'; - Colours.white = '\u001b[37m'; - Colours.grey = '\u001b[90m'; - } - } -} -exports.Colours = Colours; -Colours.enabled = false; -Colours.reset = ''; -Colours.bright = ''; -Colours.dim = ''; -Colours.red = ''; -Colours.green = ''; -Colours.yellow = ''; -Colours.blue = ''; -Colours.magenta = ''; -Colours.cyan = ''; -Colours.white = ''; -Colours.grey = ''; -Colours.refresh(); -//# sourceMappingURL=colours.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/google-logging-utils/build/src/index.js b/claude-code-source/node_modules/google-logging-utils/build/src/index.js deleted file mode 100644 index a2d5d17a..00000000 --- a/claude-code-source/node_modules/google-logging-utils/build/src/index.js +++ /dev/null @@ -1,31 +0,0 @@ -"use strict"; -// Copyright 2024 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -__exportStar(require("./logging-utils"), exports); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/google-logging-utils/build/src/logging-utils.js b/claude-code-source/node_modules/google-logging-utils/build/src/logging-utils.js deleted file mode 100644 index 1f205b9c..00000000 --- a/claude-code-source/node_modules/google-logging-utils/build/src/logging-utils.js +++ /dev/null @@ -1,406 +0,0 @@ -"use strict"; -// Copyright 2021-2024 Google LLC -// -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// https://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.env = exports.DebugLogBackendBase = exports.placeholder = exports.AdhocDebugLogger = exports.LogSeverity = void 0; -exports.getNodeBackend = getNodeBackend; -exports.getDebugBackend = getDebugBackend; -exports.getStructuredBackend = getStructuredBackend; -exports.setBackend = setBackend; -exports.log = log; -const node_events_1 = require("node:events"); -const process = __importStar(require("node:process")); -const util = __importStar(require("node:util")); -const colours_1 = require("./colours"); -// Some functions (as noted) are based on the Node standard library, from -// the following file: -// -// https://github.com/nodejs/node/blob/main/lib/internal/util/debuglog.js -/** - * This module defines an ad-hoc debug logger for Google Cloud Platform - * client libraries in Node. An ad-hoc debug logger is a tool which lets - * users use an external, unified interface (in this case, environment - * variables) to determine what logging they want to see at runtime. This - * isn't necessarily fed into the console, but is meant to be under the - * control of the user. The kind of logging that will be produced by this - * is more like "call retry happened", not "event you'd want to record - * in Cloud Logger". - * - * More for Googlers implementing libraries with it: - * go/cloud-client-logging-design - */ -/** - * Possible log levels. These are a subset of Cloud Observability levels. - * https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#LogSeverity - */ -var LogSeverity; -(function (LogSeverity) { - LogSeverity["DEFAULT"] = "DEFAULT"; - LogSeverity["DEBUG"] = "DEBUG"; - LogSeverity["INFO"] = "INFO"; - LogSeverity["WARNING"] = "WARNING"; - LogSeverity["ERROR"] = "ERROR"; -})(LogSeverity || (exports.LogSeverity = LogSeverity = {})); -/** - * Our logger instance. This actually contains the meat of dealing - * with log lines, including EventEmitter. This contains the function - * that will be passed back to users of the package. - */ -class AdhocDebugLogger extends node_events_1.EventEmitter { - /** - * @param upstream The backend will pass a function that will be - * called whenever our logger function is invoked. - */ - constructor(namespace, upstream) { - super(); - this.namespace = namespace; - this.upstream = upstream; - this.func = Object.assign(this.invoke.bind(this), { - // Also add an instance pointer back to us. - instance: this, - // And pull over the EventEmitter functionality. - on: (event, listener) => this.on(event, listener), - }); - // Convenience methods for log levels. - this.func.debug = (...args) => this.invokeSeverity(LogSeverity.DEBUG, ...args); - this.func.info = (...args) => this.invokeSeverity(LogSeverity.INFO, ...args); - this.func.warn = (...args) => this.invokeSeverity(LogSeverity.WARNING, ...args); - this.func.error = (...args) => this.invokeSeverity(LogSeverity.ERROR, ...args); - this.func.sublog = (namespace) => log(namespace, this.func); - } - invoke(fields, ...args) { - // Push out any upstream logger first. - if (this.upstream) { - this.upstream(fields, ...args); - } - // Emit sink events. - this.emit('log', fields, args); - } - invokeSeverity(severity, ...args) { - this.invoke({ severity }, ...args); - } -} -exports.AdhocDebugLogger = AdhocDebugLogger; -/** - * This can be used in place of a real logger while waiting for Promises or disabling logging. - */ -exports.placeholder = new AdhocDebugLogger('', () => { }).func; -/** - * The base class for debug logging backends. It's possible to use this, but the - * same non-guarantees above still apply (unstable interface, etc). - * - * @private - * @internal - */ -class DebugLogBackendBase { - constructor() { - var _a; - this.cached = new Map(); - this.filters = []; - this.filtersSet = false; - // Look for the Node config variable for what systems to enable. We'll store - // these for the log method below, which will call setFilters() once. - let nodeFlag = (_a = process.env[exports.env.nodeEnables]) !== null && _a !== void 0 ? _a : '*'; - if (nodeFlag === 'all') { - nodeFlag = '*'; - } - this.filters = nodeFlag.split(','); - } - log(namespace, fields, ...args) { - try { - if (!this.filtersSet) { - this.setFilters(); - this.filtersSet = true; - } - let logger = this.cached.get(namespace); - if (!logger) { - logger = this.makeLogger(namespace); - this.cached.set(namespace, logger); - } - logger(fields, ...args); - } - catch (e) { - // Silently ignore all errors; we don't want them to interfere with - // the user's running app. - // e; - console.error(e); - } - } -} -exports.DebugLogBackendBase = DebugLogBackendBase; -// The basic backend. This one definitely works, but it's less feature-filled. -// -// Rather than using util.debuglog, this implements the same basic logic directly. -// The reason for this decision is that debuglog checks the value of the -// NODE_DEBUG environment variable before any user code runs; we therefore -// can't pipe our own enables into it (and util.debuglog will never print unless -// the user duplicates it into NODE_DEBUG, which isn't reasonable). -// -class NodeBackend extends DebugLogBackendBase { - constructor() { - super(...arguments); - // Default to allowing all systems, since we gate earlier based on whether the - // variable is empty. - this.enabledRegexp = /.*/g; - } - isEnabled(namespace) { - return this.enabledRegexp.test(namespace); - } - makeLogger(namespace) { - if (!this.enabledRegexp.test(namespace)) { - return () => { }; - } - return (fields, ...args) => { - var _a; - // TODO: `fields` needs to be turned into a string here, one way or another. - const nscolour = `${colours_1.Colours.green}${namespace}${colours_1.Colours.reset}`; - const pid = `${colours_1.Colours.yellow}${process.pid}${colours_1.Colours.reset}`; - let level; - switch (fields.severity) { - case LogSeverity.ERROR: - level = `${colours_1.Colours.red}${fields.severity}${colours_1.Colours.reset}`; - break; - case LogSeverity.INFO: - level = `${colours_1.Colours.magenta}${fields.severity}${colours_1.Colours.reset}`; - break; - case LogSeverity.WARNING: - level = `${colours_1.Colours.yellow}${fields.severity}${colours_1.Colours.reset}`; - break; - default: - level = (_a = fields.severity) !== null && _a !== void 0 ? _a : LogSeverity.DEFAULT; - break; - } - const msg = util.formatWithOptions({ colors: colours_1.Colours.enabled }, ...args); - const filteredFields = Object.assign({}, fields); - delete filteredFields.severity; - const fieldsJson = Object.getOwnPropertyNames(filteredFields).length - ? JSON.stringify(filteredFields) - : ''; - const fieldsColour = fieldsJson - ? `${colours_1.Colours.grey}${fieldsJson}${colours_1.Colours.reset}` - : ''; - console.error('%s [%s|%s] %s%s', pid, nscolour, level, msg, fieldsJson ? ` ${fieldsColour}` : ''); - }; - } - // Regexp patterns below are from here: - // https://github.com/nodejs/node/blob/c0aebed4b3395bd65d54b18d1fd00f071002ac20/lib/internal/util/debuglog.js#L36 - setFilters() { - const totalFilters = this.filters.join(','); - const regexp = totalFilters - .replace(/[|\\{}()[\]^$+?.]/g, '\\$&') - .replace(/\*/g, '.*') - .replace(/,/g, '$|^'); - this.enabledRegexp = new RegExp(`^${regexp}$`, 'i'); - } -} -/** - * @returns A backend based on Node util.debuglog; this is the default. - */ -function getNodeBackend() { - return new NodeBackend(); -} -class DebugBackend extends DebugLogBackendBase { - constructor(pkg) { - super(); - this.debugPkg = pkg; - } - makeLogger(namespace) { - const debugLogger = this.debugPkg(namespace); - return (fields, ...args) => { - // TODO: `fields` needs to be turned into a string here. - debugLogger(args[0], ...args.slice(1)); - }; - } - setFilters() { - var _a; - const existingFilters = (_a = process.env['NODE_DEBUG']) !== null && _a !== void 0 ? _a : ''; - process.env['NODE_DEBUG'] = `${existingFilters}${existingFilters ? ',' : ''}${this.filters.join(',')}`; - } -} -/** - * Creates a "debug" package backend. The user must call require('debug') and pass - * the resulting object to this function. - * - * ``` - * setBackend(getDebugBackend(require('debug'))) - * ``` - * - * https://www.npmjs.com/package/debug - * - * Note: Google does not explicitly endorse or recommend this package; it's just - * being provided as an option. - * - * @returns A backend based on the npm "debug" package. - */ -function getDebugBackend(debugPkg) { - return new DebugBackend(debugPkg); -} -/** - * This pretty much works like the Node logger, but it outputs structured - * logging JSON matching Google Cloud's ingestion specs. Rather than handling - * its own output, it wraps another backend. The passed backend must be a subclass - * of `DebugLogBackendBase` (any of the backends exposed by this package will work). - */ -class StructuredBackend extends DebugLogBackendBase { - constructor(upstream) { - var _a; - super(); - this.upstream = (_a = upstream) !== null && _a !== void 0 ? _a : new NodeBackend(); - } - makeLogger(namespace) { - const debugLogger = this.upstream.makeLogger(namespace); - return (fields, ...args) => { - var _a; - const severity = (_a = fields.severity) !== null && _a !== void 0 ? _a : LogSeverity.INFO; - const json = Object.assign({ - severity, - message: util.format(...args), - }, fields); - const jsonString = JSON.stringify(json); - debugLogger(fields, jsonString); - }; - } - setFilters() { - this.upstream.setFilters(); - } -} -/** - * Creates a "structured logging" backend. This pretty much works like the - * Node logger, but it outputs structured logging JSON matching Google - * Cloud's ingestion specs instead of plain text. - * - * ``` - * setBackend(getStructuredBackend()) - * ``` - * - * @param upstream If you want to use something besides the Node backend to - * write the actual log lines into, pass that here. - * @returns A backend based on Google Cloud structured logging. - */ -function getStructuredBackend(upstream) { - return new StructuredBackend(upstream); -} -/** - * The environment variables that we standardized on, for all ad-hoc logging. - */ -exports.env = { - /** - * Filter wildcards specific to the Node syntax, and similar to the built-in - * utils.debuglog() environment variable. If missing, disables logging. - */ - nodeEnables: 'GOOGLE_SDK_NODE_LOGGING', -}; -// Keep a copy of all namespaced loggers so users can reliably .on() them. -// Note that these cached functions will need to deal with changes in the backend. -const loggerCache = new Map(); -// Our current global backend. This might be: -let cachedBackend = undefined; -/** - * Set the backend to use for our log output. - * - A backend object - * - null to disable logging - * - undefined for "nothing yet", defaults to the Node backend - * - * @param backend Results from one of the get*Backend() functions. - */ -function setBackend(backend) { - cachedBackend = backend; - loggerCache.clear(); -} -/** - * Creates a logging function. Multiple calls to this with the same namespace - * will produce the same logger, with the same event emitter hooks. - * - * Namespaces can be a simple string ("system" name), or a qualified string - * (system:subsystem), which can be used for filtering, or for "system:*". - * - * @param namespace The namespace, a descriptive text string. - * @returns A function you can call that works similar to console.log(). - */ -function log(namespace, parent) { - // If the enable flag isn't set, do nothing. - const enablesFlag = process.env[exports.env.nodeEnables]; - if (!enablesFlag) { - return exports.placeholder; - } - // This might happen mostly if the typings are dropped in a user's code, - // or if they're calling from JavaScript. - if (!namespace) { - return exports.placeholder; - } - // Handle sub-loggers. - if (parent) { - namespace = `${parent.instance.namespace}:${namespace}`; - } - // Reuse loggers so things like event sinks are persistent. - const existing = loggerCache.get(namespace); - if (existing) { - return existing.func; - } - // Do we have a backend yet? - if (cachedBackend === null) { - // Explicitly disabled. - return exports.placeholder; - } - else if (cachedBackend === undefined) { - // One hasn't been made yet, so default to Node. - cachedBackend = getNodeBackend(); - } - // The logger is further wrapped so we can handle the backend changing out. - const logger = (() => { - let previousBackend = undefined; - const newLogger = new AdhocDebugLogger(namespace, (fields, ...args) => { - if (previousBackend !== cachedBackend) { - // Did the user pass a custom backend? - if (cachedBackend === null) { - // Explicitly disabled. - return; - } - else if (cachedBackend === undefined) { - // One hasn't been made yet, so default to Node. - cachedBackend = getNodeBackend(); - } - previousBackend = cachedBackend; - } - cachedBackend === null || cachedBackend === void 0 ? void 0 : cachedBackend.log(namespace, fields, ...args); - }); - return newLogger; - })(); - loggerCache.set(namespace, logger); - return logger.func; -} -//# sourceMappingURL=logging-utils.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/gopd/gOPD.js b/claude-code-source/node_modules/gopd/gOPD.js deleted file mode 100644 index cf9616c4..00000000 --- a/claude-code-source/node_modules/gopd/gOPD.js +++ /dev/null @@ -1,4 +0,0 @@ -'use strict'; - -/** @type {import('./gOPD')} */ -module.exports = Object.getOwnPropertyDescriptor; diff --git a/claude-code-source/node_modules/gopd/index.js b/claude-code-source/node_modules/gopd/index.js deleted file mode 100644 index a4081b01..00000000 --- a/claude-code-source/node_modules/gopd/index.js +++ /dev/null @@ -1,15 +0,0 @@ -'use strict'; - -/** @type {import('.')} */ -var $gOPD = require('./gOPD'); - -if ($gOPD) { - try { - $gOPD([], 'length'); - } catch (e) { - // IE 8 has a broken gOPD - $gOPD = null; - } -} - -module.exports = $gOPD; diff --git a/claude-code-source/node_modules/graceful-fs/clone.js b/claude-code-source/node_modules/graceful-fs/clone.js deleted file mode 100644 index dff3cc8c..00000000 --- a/claude-code-source/node_modules/graceful-fs/clone.js +++ /dev/null @@ -1,23 +0,0 @@ -'use strict' - -module.exports = clone - -var getPrototypeOf = Object.getPrototypeOf || function (obj) { - return obj.__proto__ -} - -function clone (obj) { - if (obj === null || typeof obj !== 'object') - return obj - - if (obj instanceof Object) - var copy = { __proto__: getPrototypeOf(obj) } - else - var copy = Object.create(null) - - Object.getOwnPropertyNames(obj).forEach(function (key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) - }) - - return copy -} diff --git a/claude-code-source/node_modules/graceful-fs/graceful-fs.js b/claude-code-source/node_modules/graceful-fs/graceful-fs.js deleted file mode 100644 index 8d5b89e4..00000000 --- a/claude-code-source/node_modules/graceful-fs/graceful-fs.js +++ /dev/null @@ -1,448 +0,0 @@ -var fs = require('fs') -var polyfills = require('./polyfills.js') -var legacy = require('./legacy-streams.js') -var clone = require('./clone.js') - -var util = require('util') - -/* istanbul ignore next - node 0.x polyfill */ -var gracefulQueue -var previousSymbol - -/* istanbul ignore else - node 0.x polyfill */ -if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { - gracefulQueue = Symbol.for('graceful-fs.queue') - // This is used in testing by future versions - previousSymbol = Symbol.for('graceful-fs.previous') -} else { - gracefulQueue = '___graceful-fs.queue' - previousSymbol = '___graceful-fs.previous' -} - -function noop () {} - -function publishQueue(context, queue) { - Object.defineProperty(context, gracefulQueue, { - get: function() { - return queue - } - }) -} - -var debug = noop -if (util.debuglog) - debug = util.debuglog('gfs4') -else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) - debug = function() { - var m = util.format.apply(util, arguments) - m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') - console.error(m) - } - -// Once time initialization -if (!fs[gracefulQueue]) { - // This queue can be shared by multiple loaded instances - var queue = global[gracefulQueue] || [] - publishQueue(fs, queue) - - // Patch fs.close/closeSync to shared queue version, because we need - // to retry() whenever a close happens *anywhere* in the program. - // This is essential when multiple graceful-fs instances are - // in play at the same time. - fs.close = (function (fs$close) { - function close (fd, cb) { - return fs$close.call(fs, fd, function (err) { - // This function uses the graceful-fs shared queue - if (!err) { - resetQueue() - } - - if (typeof cb === 'function') - cb.apply(this, arguments) - }) - } - - Object.defineProperty(close, previousSymbol, { - value: fs$close - }) - return close - })(fs.close) - - fs.closeSync = (function (fs$closeSync) { - function closeSync (fd) { - // This function uses the graceful-fs shared queue - fs$closeSync.apply(fs, arguments) - resetQueue() - } - - Object.defineProperty(closeSync, previousSymbol, { - value: fs$closeSync - }) - return closeSync - })(fs.closeSync) - - if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { - process.on('exit', function() { - debug(fs[gracefulQueue]) - require('assert').equal(fs[gracefulQueue].length, 0) - }) - } -} - -if (!global[gracefulQueue]) { - publishQueue(global, fs[gracefulQueue]); -} - -module.exports = patch(clone(fs)) -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { - module.exports = patch(fs) - fs.__patched = true; -} - -function patch (fs) { - // Everything that references the open() function needs to be in here - polyfills(fs) - fs.gracefulify = patch - - fs.createReadStream = createReadStream - fs.createWriteStream = createWriteStream - var fs$readFile = fs.readFile - fs.readFile = readFile - function readFile (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null - - return go$readFile(path, options, cb) - - function go$readFile (path, options, cb, startTime) { - return fs$readFile(path, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } - - var fs$writeFile = fs.writeFile - fs.writeFile = writeFile - function writeFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null - - return go$writeFile(path, data, options, cb) - - function go$writeFile (path, data, options, cb, startTime) { - return fs$writeFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } - - var fs$appendFile = fs.appendFile - if (fs$appendFile) - fs.appendFile = appendFile - function appendFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null - - return go$appendFile(path, data, options, cb) - - function go$appendFile (path, data, options, cb, startTime) { - return fs$appendFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } - - var fs$copyFile = fs.copyFile - if (fs$copyFile) - fs.copyFile = copyFile - function copyFile (src, dest, flags, cb) { - if (typeof flags === 'function') { - cb = flags - flags = 0 - } - return go$copyFile(src, dest, flags, cb) - - function go$copyFile (src, dest, flags, cb, startTime) { - return fs$copyFile(src, dest, flags, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } - - var fs$readdir = fs.readdir - fs.readdir = readdir - var noReaddirOptionVersions = /^v[0-5]\./ - function readdir (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null - - var go$readdir = noReaddirOptionVersions.test(process.version) - ? function go$readdir (path, options, cb, startTime) { - return fs$readdir(path, fs$readdirCallback( - path, options, cb, startTime - )) - } - : function go$readdir (path, options, cb, startTime) { - return fs$readdir(path, options, fs$readdirCallback( - path, options, cb, startTime - )) - } - - return go$readdir(path, options, cb) - - function fs$readdirCallback (path, options, cb, startTime) { - return function (err, files) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([ - go$readdir, - [path, options, cb], - err, - startTime || Date.now(), - Date.now() - ]) - else { - if (files && files.sort) - files.sort() - - if (typeof cb === 'function') - cb.call(this, err, files) - } - } - } - } - - if (process.version.substr(0, 4) === 'v0.8') { - var legStreams = legacy(fs) - ReadStream = legStreams.ReadStream - WriteStream = legStreams.WriteStream - } - - var fs$ReadStream = fs.ReadStream - if (fs$ReadStream) { - ReadStream.prototype = Object.create(fs$ReadStream.prototype) - ReadStream.prototype.open = ReadStream$open - } - - var fs$WriteStream = fs.WriteStream - if (fs$WriteStream) { - WriteStream.prototype = Object.create(fs$WriteStream.prototype) - WriteStream.prototype.open = WriteStream$open - } - - Object.defineProperty(fs, 'ReadStream', { - get: function () { - return ReadStream - }, - set: function (val) { - ReadStream = val - }, - enumerable: true, - configurable: true - }) - Object.defineProperty(fs, 'WriteStream', { - get: function () { - return WriteStream - }, - set: function (val) { - WriteStream = val - }, - enumerable: true, - configurable: true - }) - - // legacy names - var FileReadStream = ReadStream - Object.defineProperty(fs, 'FileReadStream', { - get: function () { - return FileReadStream - }, - set: function (val) { - FileReadStream = val - }, - enumerable: true, - configurable: true - }) - var FileWriteStream = WriteStream - Object.defineProperty(fs, 'FileWriteStream', { - get: function () { - return FileWriteStream - }, - set: function (val) { - FileWriteStream = val - }, - enumerable: true, - configurable: true - }) - - function ReadStream (path, options) { - if (this instanceof ReadStream) - return fs$ReadStream.apply(this, arguments), this - else - return ReadStream.apply(Object.create(ReadStream.prototype), arguments) - } - - function ReadStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - if (that.autoClose) - that.destroy() - - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - that.read() - } - }) - } - - function WriteStream (path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments) - } - - function WriteStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - that.destroy() - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - } - }) - } - - function createReadStream (path, options) { - return new fs.ReadStream(path, options) - } - - function createWriteStream (path, options) { - return new fs.WriteStream(path, options) - } - - var fs$open = fs.open - fs.open = open - function open (path, flags, mode, cb) { - if (typeof mode === 'function') - cb = mode, mode = null - - return go$open(path, flags, mode, cb) - - function go$open (path, flags, mode, cb, startTime) { - return fs$open(path, flags, mode, function (err, fd) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } - - return fs -} - -function enqueue (elem) { - debug('ENQUEUE', elem[0].name, elem[1]) - fs[gracefulQueue].push(elem) - retry() -} - -// keep track of the timeout between retry() calls -var retryTimer - -// reset the startTime and lastTime to now -// this resets the start of the 60 second overall timeout as well as the -// delay between attempts so that we'll retry these jobs sooner -function resetQueue () { - var now = Date.now() - for (var i = 0; i < fs[gracefulQueue].length; ++i) { - // entries that are only a length of 2 are from an older version, don't - // bother modifying those since they'll be retried anyway. - if (fs[gracefulQueue][i].length > 2) { - fs[gracefulQueue][i][3] = now // startTime - fs[gracefulQueue][i][4] = now // lastTime - } - } - // call retry to make sure we're actively processing the queue - retry() -} - -function retry () { - // clear the timer and remove it to help prevent unintended concurrency - clearTimeout(retryTimer) - retryTimer = undefined - - if (fs[gracefulQueue].length === 0) - return - - var elem = fs[gracefulQueue].shift() - var fn = elem[0] - var args = elem[1] - // these items may be unset if they were added by an older graceful-fs - var err = elem[2] - var startTime = elem[3] - var lastTime = elem[4] - - // if we don't have a startTime we have no way of knowing if we've waited - // long enough, so go ahead and retry this item now - if (startTime === undefined) { - debug('RETRY', fn.name, args) - fn.apply(null, args) - } else if (Date.now() - startTime >= 60000) { - // it's been more than 60 seconds total, bail now - debug('TIMEOUT', fn.name, args) - var cb = args.pop() - if (typeof cb === 'function') - cb.call(null, err) - } else { - // the amount of time between the last attempt and right now - var sinceAttempt = Date.now() - lastTime - // the amount of time between when we first tried, and when we last tried - // rounded up to at least 1 - var sinceStart = Math.max(lastTime - startTime, 1) - // backoff. wait longer than the total time we've been retrying, but only - // up to a maximum of 100ms - var desiredDelay = Math.min(sinceStart * 1.2, 100) - // it's been long enough since the last retry, do it again - if (sinceAttempt >= desiredDelay) { - debug('RETRY', fn.name, args) - fn.apply(null, args.concat([startTime])) - } else { - // if we can't do this job yet, push it to the end of the queue - // and let the next iteration check again - fs[gracefulQueue].push(elem) - } - } - - // schedule our next run if one isn't already scheduled - if (retryTimer === undefined) { - retryTimer = setTimeout(retry, 0) - } -} diff --git a/claude-code-source/node_modules/graceful-fs/legacy-streams.js b/claude-code-source/node_modules/graceful-fs/legacy-streams.js deleted file mode 100644 index d617b50f..00000000 --- a/claude-code-source/node_modules/graceful-fs/legacy-streams.js +++ /dev/null @@ -1,118 +0,0 @@ -var Stream = require('stream').Stream - -module.exports = legacy - -function legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream - } - - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); - - Stream.call(this); - - var self = this; - - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; - - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; - - options = options || {}; - - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } - - if (this.encoding) this.setEncoding(this.encoding); - - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); - } - - if (this.start > this.end) { - throw new Error('start must be <= end'); - } - - this.pos = this.start; - } - - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; - } - - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; - } - - self.fd = fd; - self.emit('open', fd); - self._read(); - }) - } - - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); - - Stream.call(this); - - this.path = path; - this.fd = null; - this.writable = true; - - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; - - options = options || {}; - - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } - - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.start < 0) { - throw new Error('start must be >= zero'); - } - - this.pos = this.start; - } - - this.busy = false; - this._queue = []; - - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); - } - } -} diff --git a/claude-code-source/node_modules/graceful-fs/polyfills.js b/claude-code-source/node_modules/graceful-fs/polyfills.js deleted file mode 100644 index 453f1a9e..00000000 --- a/claude-code-source/node_modules/graceful-fs/polyfills.js +++ /dev/null @@ -1,355 +0,0 @@ -var constants = require('constants') - -var origCwd = process.cwd -var cwd = null - -var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform - -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd -} -try { - process.cwd() -} catch (er) {} - -// This check is needed until node.js 12 is required -if (typeof process.chdir === 'function') { - var chdir = process.chdir - process.chdir = function (d) { - cwd = null - chdir.call(process, d) - } - if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) -} - -module.exports = patch - -function patch (fs) { - // (re-)implement some things that are known busted or missing. - - // lchmod, broken prior to 0.6.2 - // back-port the fix here. - if (constants.hasOwnProperty('O_SYMLINK') && - process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs) - } - - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) - } - - // https://github.com/isaacs/node-graceful-fs/issues/4 - // Chown should not fail on einval or eperm if non-root. - // It should not fail on enosys ever, as this just indicates - // that a fs doesn't support the intended operation. - - fs.chown = chownFix(fs.chown) - fs.fchown = chownFix(fs.fchown) - fs.lchown = chownFix(fs.lchown) - - fs.chmod = chmodFix(fs.chmod) - fs.fchmod = chmodFix(fs.fchmod) - fs.lchmod = chmodFix(fs.lchmod) - - fs.chownSync = chownFixSync(fs.chownSync) - fs.fchownSync = chownFixSync(fs.fchownSync) - fs.lchownSync = chownFixSync(fs.lchownSync) - - fs.chmodSync = chmodFixSync(fs.chmodSync) - fs.fchmodSync = chmodFixSync(fs.fchmodSync) - fs.lchmodSync = chmodFixSync(fs.lchmodSync) - - fs.stat = statFix(fs.stat) - fs.fstat = statFix(fs.fstat) - fs.lstat = statFix(fs.lstat) - - fs.statSync = statFixSync(fs.statSync) - fs.fstatSync = statFixSync(fs.fstatSync) - fs.lstatSync = statFixSync(fs.lstatSync) - - // if lchmod/lchown do not exist, then make them no-ops - if (fs.chmod && !fs.lchmod) { - fs.lchmod = function (path, mode, cb) { - if (cb) process.nextTick(cb) - } - fs.lchmodSync = function () {} - } - if (fs.chown && !fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb) - } - fs.lchownSync = function () {} - } - - // on Windows, A/V software can lock the directory, causing this - // to fail with an EACCES or EPERM if the directory contains newly - // created files. Try again on failure, for up to 60 seconds. - - // Set the timeout this long because some Windows Anti-Virus, such as Parity - // bit9, may lock files for up to a minute, causing npm package install - // failures. Also, take care to yield the scheduler. Windows scheduling gives - // CPU to a busy looping process, which can cause the program causing the lock - // contention to be starved of CPU by node, so the contention doesn't resolve. - if (platform === "win32") { - fs.rename = typeof fs.rename !== 'function' ? fs.rename - : (function (fs$rename) { - function rename (from, to, cb) { - var start = Date.now() - var backoff = 0; - fs$rename(from, to, function CB (er) { - if (er - && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") - && Date.now() - start < 60000) { - setTimeout(function() { - fs.stat(to, function (stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er) - }) - }, backoff) - if (backoff < 100) - backoff += 10; - return; - } - if (cb) cb(er) - }) - } - if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename) - return rename - })(fs.rename) - } - - // if read() returns EAGAIN, then just try it again. - fs.read = typeof fs.read !== 'function' ? fs.read - : (function (fs$read) { - function read (fd, buffer, offset, length, position, callback_) { - var callback - if (callback_ && typeof callback_ === 'function') { - var eagCounter = 0 - callback = function (er, _, __) { - if (er && er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - callback_.apply(this, arguments) - } - } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - - // This ensures `util.promisify` works as it does for native `fs.read`. - if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) - return read - })(fs.read) - - fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync - : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { - var eagCounter = 0 - while (true) { - try { - return fs$readSync.call(fs, fd, buffer, offset, length, position) - } catch (er) { - if (er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - continue - } - throw er - } - } - }})(fs.readSync) - - function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return - } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) - } - - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) - - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true - var ret - try { - ret = fs.fchmodSync(fd, mode) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } - } - - function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er) - return - } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2) - }) - }) - }) - } - - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - var ret - var threw = true - try { - ret = fs.futimesSync(fd, at, mt) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } - - } else if (fs.futimes) { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} - } - } - - function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } - - function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } - - - function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } - - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } - - function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } - function callback (er, stats) { - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - if (cb) cb.apply(this, arguments) - } - return options ? orig.call(fs, target, options, callback) - : orig.call(fs, target, callback) - } - } - - function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options) { - var stats = options ? orig.call(fs, target, options) - : orig.call(fs, target) - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - return stats; - } - } - - // ENOSYS means that the fs doesn't support the op. Just ignore - // that, because it doesn't matter. - // - // if there's no getuid, or if getuid() is something other - // than 0, and the error is EINVAL or EPERM, then just ignore - // it. - // - // This specific case is a silent failure in cp, install, tar, - // and most other unix tools that manage permissions. - // - // When running as root, or if other types of errors are - // encountered, then it's strict. - function chownErOk (er) { - if (!er) - return true - - if (er.code === "ENOSYS") - return true - - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true - } - - return false - } -} diff --git a/claude-code-source/node_modules/gtoken/build/src/index.js b/claude-code-source/node_modules/gtoken/build/src/index.js deleted file mode 100644 index bf450423..00000000 --- a/claude-code-source/node_modules/gtoken/build/src/index.js +++ /dev/null @@ -1,276 +0,0 @@ -"use strict"; -/** - * Copyright 2018 Google LLC - * - * Distributed under MIT license. - * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT - */ -var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -}; -var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { - if (kind === "m") throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; -}; -var _GoogleToken_instances, _GoogleToken_inFlightRequest, _GoogleToken_getTokenAsync, _GoogleToken_getTokenAsyncInner, _GoogleToken_ensureEmail, _GoogleToken_revokeTokenAsync, _GoogleToken_configure, _GoogleToken_requestToken; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.GoogleToken = void 0; -const fs = require("fs"); -const gaxios_1 = require("gaxios"); -const jws = require("jws"); -const path = require("path"); -const util_1 = require("util"); -const readFile = fs.readFile - ? (0, util_1.promisify)(fs.readFile) - : async () => { - // if running in the web-browser, fs.readFile may not have been shimmed. - throw new ErrorWithCode('use key rather than keyFile.', 'MISSING_CREDENTIALS'); - }; -const GOOGLE_TOKEN_URL = 'https://www.googleapis.com/oauth2/v4/token'; -const GOOGLE_REVOKE_TOKEN_URL = 'https://accounts.google.com/o/oauth2/revoke?token='; -class ErrorWithCode extends Error { - constructor(message, code) { - super(message); - this.code = code; - } -} -class GoogleToken { - get accessToken() { - return this.rawToken ? this.rawToken.access_token : undefined; - } - get idToken() { - return this.rawToken ? this.rawToken.id_token : undefined; - } - get tokenType() { - return this.rawToken ? this.rawToken.token_type : undefined; - } - get refreshToken() { - return this.rawToken ? this.rawToken.refresh_token : undefined; - } - /** - * Create a GoogleToken. - * - * @param options Configuration object. - */ - constructor(options) { - _GoogleToken_instances.add(this); - this.transporter = { - request: opts => (0, gaxios_1.request)(opts), - }; - _GoogleToken_inFlightRequest.set(this, void 0); - __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_configure).call(this, options); - } - /** - * Returns whether the token has expired. - * - * @return true if the token has expired, false otherwise. - */ - hasExpired() { - const now = new Date().getTime(); - if (this.rawToken && this.expiresAt) { - return now >= this.expiresAt; - } - else { - return true; - } - } - /** - * Returns whether the token will expire within eagerRefreshThresholdMillis - * - * @return true if the token will be expired within eagerRefreshThresholdMillis, false otherwise. - */ - isTokenExpiring() { - var _a; - const now = new Date().getTime(); - const eagerRefreshThresholdMillis = (_a = this.eagerRefreshThresholdMillis) !== null && _a !== void 0 ? _a : 0; - if (this.rawToken && this.expiresAt) { - return this.expiresAt <= now + eagerRefreshThresholdMillis; - } - else { - return true; - } - } - getToken(callback, opts = {}) { - if (typeof callback === 'object') { - opts = callback; - callback = undefined; - } - opts = Object.assign({ - forceRefresh: false, - }, opts); - if (callback) { - const cb = callback; - __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsync).call(this, opts).then(t => cb(null, t), callback); - return; - } - return __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsync).call(this, opts); - } - /** - * Given a keyFile, extract the key and client email if available - * @param keyFile Path to a json, pem, or p12 file that contains the key. - * @returns an object with privateKey and clientEmail properties - */ - async getCredentials(keyFile) { - const ext = path.extname(keyFile); - switch (ext) { - case '.json': { - const key = await readFile(keyFile, 'utf8'); - const body = JSON.parse(key); - const privateKey = body.private_key; - const clientEmail = body.client_email; - if (!privateKey || !clientEmail) { - throw new ErrorWithCode('private_key and client_email are required.', 'MISSING_CREDENTIALS'); - } - return { privateKey, clientEmail }; - } - case '.der': - case '.crt': - case '.pem': { - const privateKey = await readFile(keyFile, 'utf8'); - return { privateKey }; - } - case '.p12': - case '.pfx': { - throw new ErrorWithCode('*.p12 certificates are not supported after v6.1.2. ' + - 'Consider utilizing *.json format or converting *.p12 to *.pem using the OpenSSL CLI.', 'UNKNOWN_CERTIFICATE_TYPE'); - } - default: - throw new ErrorWithCode('Unknown certificate type. Type is determined based on file extension. ' + - 'Current supported extensions are *.json, and *.pem.', 'UNKNOWN_CERTIFICATE_TYPE'); - } - } - revokeToken(callback) { - if (callback) { - __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_revokeTokenAsync).call(this).then(() => callback(), callback); - return; - } - return __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_revokeTokenAsync).call(this); - } -} -exports.GoogleToken = GoogleToken; -_GoogleToken_inFlightRequest = new WeakMap(), _GoogleToken_instances = new WeakSet(), _GoogleToken_getTokenAsync = async function _GoogleToken_getTokenAsync(opts) { - if (__classPrivateFieldGet(this, _GoogleToken_inFlightRequest, "f") && !opts.forceRefresh) { - return __classPrivateFieldGet(this, _GoogleToken_inFlightRequest, "f"); - } - try { - return await (__classPrivateFieldSet(this, _GoogleToken_inFlightRequest, __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_getTokenAsyncInner).call(this, opts), "f")); - } - finally { - __classPrivateFieldSet(this, _GoogleToken_inFlightRequest, undefined, "f"); - } -}, _GoogleToken_getTokenAsyncInner = async function _GoogleToken_getTokenAsyncInner(opts) { - if (this.isTokenExpiring() === false && opts.forceRefresh === false) { - return Promise.resolve(this.rawToken); - } - if (!this.key && !this.keyFile) { - throw new Error('No key or keyFile set.'); - } - if (!this.key && this.keyFile) { - const creds = await this.getCredentials(this.keyFile); - this.key = creds.privateKey; - this.iss = creds.clientEmail || this.iss; - if (!creds.clientEmail) { - __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_ensureEmail).call(this); - } - } - return __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_requestToken).call(this); -}, _GoogleToken_ensureEmail = function _GoogleToken_ensureEmail() { - if (!this.iss) { - throw new ErrorWithCode('email is required.', 'MISSING_CREDENTIALS'); - } -}, _GoogleToken_revokeTokenAsync = async function _GoogleToken_revokeTokenAsync() { - if (!this.accessToken) { - throw new Error('No token to revoke.'); - } - const url = GOOGLE_REVOKE_TOKEN_URL + this.accessToken; - await this.transporter.request({ - url, - retry: true, - }); - __classPrivateFieldGet(this, _GoogleToken_instances, "m", _GoogleToken_configure).call(this, { - email: this.iss, - sub: this.sub, - key: this.key, - keyFile: this.keyFile, - scope: this.scope, - additionalClaims: this.additionalClaims, - }); -}, _GoogleToken_configure = function _GoogleToken_configure(options = {}) { - this.keyFile = options.keyFile; - this.key = options.key; - this.rawToken = undefined; - this.iss = options.email || options.iss; - this.sub = options.sub; - this.additionalClaims = options.additionalClaims; - if (typeof options.scope === 'object') { - this.scope = options.scope.join(' '); - } - else { - this.scope = options.scope; - } - this.eagerRefreshThresholdMillis = options.eagerRefreshThresholdMillis; - if (options.transporter) { - this.transporter = options.transporter; - } -}, _GoogleToken_requestToken = -/** - * Request the token from Google. - */ -async function _GoogleToken_requestToken() { - var _a, _b; - const iat = Math.floor(new Date().getTime() / 1000); - const additionalClaims = this.additionalClaims || {}; - const payload = Object.assign({ - iss: this.iss, - scope: this.scope, - aud: GOOGLE_TOKEN_URL, - exp: iat + 3600, - iat, - sub: this.sub, - }, additionalClaims); - const signedJWT = jws.sign({ - header: { alg: 'RS256' }, - payload, - secret: this.key, - }); - try { - const r = await this.transporter.request({ - method: 'POST', - url: GOOGLE_TOKEN_URL, - data: { - grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', - assertion: signedJWT, - }, - headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, - responseType: 'json', - retryConfig: { - httpMethodsToRetry: ['POST'], - }, - }); - this.rawToken = r.data; - this.expiresAt = - r.data.expires_in === null || r.data.expires_in === undefined - ? undefined - : (iat + r.data.expires_in) * 1000; - return this.rawToken; - } - catch (e) { - this.rawToken = undefined; - this.tokenExpires = undefined; - const body = e.response && ((_a = e.response) === null || _a === void 0 ? void 0 : _a.data) - ? (_b = e.response) === null || _b === void 0 ? void 0 : _b.data - : {}; - if (body.error) { - const desc = body.error_description - ? `: ${body.error_description}` - : ''; - e.message = `${body.error}${desc}`; - } - throw e; - } -}; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/claude-code-source/node_modules/has-flag/index.js b/claude-code-source/node_modules/has-flag/index.js deleted file mode 100644 index b6f80b1f..00000000 --- a/claude-code-source/node_modules/has-flag/index.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; - -module.exports = (flag, argv = process.argv) => { - const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf('--'); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); -}; diff --git a/claude-code-source/node_modules/has-symbols/index.js b/claude-code-source/node_modules/has-symbols/index.js deleted file mode 100644 index fa65265a..00000000 --- a/claude-code-source/node_modules/has-symbols/index.js +++ /dev/null @@ -1,14 +0,0 @@ -'use strict'; - -var origSymbol = typeof Symbol !== 'undefined' && Symbol; -var hasSymbolSham = require('./shams'); - -/** @type {import('.')} */ -module.exports = function hasNativeSymbols() { - if (typeof origSymbol !== 'function') { return false; } - if (typeof Symbol !== 'function') { return false; } - if (typeof origSymbol('foo') !== 'symbol') { return false; } - if (typeof Symbol('bar') !== 'symbol') { return false; } - - return hasSymbolSham(); -}; diff --git a/claude-code-source/node_modules/has-symbols/shams.js b/claude-code-source/node_modules/has-symbols/shams.js deleted file mode 100644 index f97b4741..00000000 --- a/claude-code-source/node_modules/has-symbols/shams.js +++ /dev/null @@ -1,45 +0,0 @@ -'use strict'; - -/** @type {import('./shams')} */ -/* eslint complexity: [2, 18], max-statements: [2, 33] */ -module.exports = function hasSymbols() { - if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } - if (typeof Symbol.iterator === 'symbol') { return true; } - - /** @type {{ [k in symbol]?: unknown }} */ - var obj = {}; - var sym = Symbol('test'); - var symObj = Object(sym); - if (typeof sym === 'string') { return false; } - - if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } - if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } - - // temp disabled per https://github.com/ljharb/object.assign/issues/17 - // if (sym instanceof Symbol) { return false; } - // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 - // if (!(symObj instanceof Symbol)) { return false; } - - // if (typeof Symbol.prototype.toString !== 'function') { return false; } - // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } - - var symVal = 42; - obj[sym] = symVal; - for (var _ in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop - if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } - - if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } - - var syms = Object.getOwnPropertySymbols(obj); - if (syms.length !== 1 || syms[0] !== sym) { return false; } - - if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } - - if (typeof Object.getOwnPropertyDescriptor === 'function') { - // eslint-disable-next-line no-extra-parens - var descriptor = /** @type {PropertyDescriptor} */ (Object.getOwnPropertyDescriptor(obj, sym)); - if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } - } - - return true; -}; diff --git a/claude-code-source/node_modules/has-tostringtag/shams.js b/claude-code-source/node_modules/has-tostringtag/shams.js deleted file mode 100644 index 809580db..00000000 --- a/claude-code-source/node_modules/has-tostringtag/shams.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; - -var hasSymbols = require('has-symbols/shams'); - -/** @type {import('.')} */ -module.exports = function hasToStringTagShams() { - return hasSymbols() && !!Symbol.toStringTag; -}; diff --git a/claude-code-source/node_modules/hasown/index.js b/claude-code-source/node_modules/hasown/index.js deleted file mode 100644 index 34e60591..00000000 --- a/claude-code-source/node_modules/hasown/index.js +++ /dev/null @@ -1,8 +0,0 @@ -'use strict'; - -var call = Function.prototype.call; -var $hasOwn = Object.prototype.hasOwnProperty; -var bind = require('function-bind'); - -/** @type {import('.')} */ -module.exports = bind.call(call, $hasOwn); diff --git a/claude-code-source/node_modules/highlight.js/lib/core.js b/claude-code-source/node_modules/highlight.js/lib/core.js deleted file mode 100644 index 824ef942..00000000 --- a/claude-code-source/node_modules/highlight.js/lib/core.js +++ /dev/null @@ -1,2517 +0,0 @@ -function deepFreeze(obj) { - if (obj instanceof Map) { - obj.clear = obj.delete = obj.set = function () { - throw new Error('map is read-only'); - }; - } else if (obj instanceof Set) { - obj.add = obj.clear = obj.delete = function () { - throw new Error('set is read-only'); - }; - } - - // Freeze self - Object.freeze(obj); - - Object.getOwnPropertyNames(obj).forEach(function (name) { - var prop = obj[name]; - - // Freeze prop if it is an object - if (typeof prop == 'object' && !Object.isFrozen(prop)) { - deepFreeze(prop); - } - }); - - return obj; -} - -var deepFreezeEs6 = deepFreeze; -var _default = deepFreeze; -deepFreezeEs6.default = _default; - -/** @implements CallbackResponse */ -class Response { - /** - * @param {CompiledMode} mode - */ - constructor(mode) { - // eslint-disable-next-line no-undefined - if (mode.data === undefined) mode.data = {}; - - this.data = mode.data; - this.isMatchIgnored = false; - } - - ignoreMatch() { - this.isMatchIgnored = true; - } -} - -/** - * @param {string} value - * @returns {string} - */ -function escapeHTML(value) { - return value - .replace(/&/g, '&') - .replace(//g, '>') - .replace(/"/g, '"') - .replace(/'/g, '''); -} - -/** - * performs a shallow merge of multiple objects into one - * - * @template T - * @param {T} original - * @param {Record[]} objects - * @returns {T} a single new object - */ -function inherit(original, ...objects) { - /** @type Record */ - const result = Object.create(null); - - for (const key in original) { - result[key] = original[key]; - } - objects.forEach(function(obj) { - for (const key in obj) { - result[key] = obj[key]; - } - }); - return /** @type {T} */ (result); -} - -/** - * @typedef {object} Renderer - * @property {(text: string) => void} addText - * @property {(node: Node) => void} openNode - * @property {(node: Node) => void} closeNode - * @property {() => string} value - */ - -/** @typedef {{kind?: string, sublanguage?: boolean}} Node */ -/** @typedef {{walk: (r: Renderer) => void}} Tree */ -/** */ - -const SPAN_CLOSE = ''; - -/** - * Determines if a node needs to be wrapped in - * - * @param {Node} node */ -const emitsWrappingTags = (node) => { - return !!node.kind; -}; - -/** @type {Renderer} */ -class HTMLRenderer { - /** - * Creates a new HTMLRenderer - * - * @param {Tree} parseTree - the parse tree (must support `walk` API) - * @param {{classPrefix: string}} options - */ - constructor(parseTree, options) { - this.buffer = ""; - this.classPrefix = options.classPrefix; - parseTree.walk(this); - } - - /** - * Adds texts to the output stream - * - * @param {string} text */ - addText(text) { - this.buffer += escapeHTML(text); - } - - /** - * Adds a node open to the output stream (if needed) - * - * @param {Node} node */ - openNode(node) { - if (!emitsWrappingTags(node)) return; - - let className = node.kind; - if (!node.sublanguage) { - className = `${this.classPrefix}${className}`; - } - this.span(className); - } - - /** - * Adds a node close to the output stream (if needed) - * - * @param {Node} node */ - closeNode(node) { - if (!emitsWrappingTags(node)) return; - - this.buffer += SPAN_CLOSE; - } - - /** - * returns the accumulated buffer - */ - value() { - return this.buffer; - } - - // helpers - - /** - * Builds a span element - * - * @param {string} className */ - span(className) { - this.buffer += ``; - } -} - -/** @typedef {{kind?: string, sublanguage?: boolean, children: Node[]} | string} Node */ -/** @typedef {{kind?: string, sublanguage?: boolean, children: Node[]} } DataNode */ -/** */ - -class TokenTree { - constructor() { - /** @type DataNode */ - this.rootNode = { children: [] }; - this.stack = [this.rootNode]; - } - - get top() { - return this.stack[this.stack.length - 1]; - } - - get root() { return this.rootNode; } - - /** @param {Node} node */ - add(node) { - this.top.children.push(node); - } - - /** @param {string} kind */ - openNode(kind) { - /** @type Node */ - const node = { kind, children: [] }; - this.add(node); - this.stack.push(node); - } - - closeNode() { - if (this.stack.length > 1) { - return this.stack.pop(); - } - // eslint-disable-next-line no-undefined - return undefined; - } - - closeAllNodes() { - while (this.closeNode()); - } - - toJSON() { - return JSON.stringify(this.rootNode, null, 4); - } - - /** - * @typedef { import("./html_renderer").Renderer } Renderer - * @param {Renderer} builder - */ - walk(builder) { - // this does not - return this.constructor._walk(builder, this.rootNode); - // this works - // return TokenTree._walk(builder, this.rootNode); - } - - /** - * @param {Renderer} builder - * @param {Node} node - */ - static _walk(builder, node) { - if (typeof node === "string") { - builder.addText(node); - } else if (node.children) { - builder.openNode(node); - node.children.forEach((child) => this._walk(builder, child)); - builder.closeNode(node); - } - return builder; - } - - /** - * @param {Node} node - */ - static _collapse(node) { - if (typeof node === "string") return; - if (!node.children) return; - - if (node.children.every(el => typeof el === "string")) { - // node.text = node.children.join(""); - // delete node.children; - node.children = [node.children.join("")]; - } else { - node.children.forEach((child) => { - TokenTree._collapse(child); - }); - } - } -} - -/** - Currently this is all private API, but this is the minimal API necessary - that an Emitter must implement to fully support the parser. - - Minimal interface: - - - addKeyword(text, kind) - - addText(text) - - addSublanguage(emitter, subLanguageName) - - finalize() - - openNode(kind) - - closeNode() - - closeAllNodes() - - toHTML() - -*/ - -/** - * @implements {Emitter} - */ -class TokenTreeEmitter extends TokenTree { - /** - * @param {*} options - */ - constructor(options) { - super(); - this.options = options; - } - - /** - * @param {string} text - * @param {string} kind - */ - addKeyword(text, kind) { - if (text === "") { return; } - - this.openNode(kind); - this.addText(text); - this.closeNode(); - } - - /** - * @param {string} text - */ - addText(text) { - if (text === "") { return; } - - this.add(text); - } - - /** - * @param {Emitter & {root: DataNode}} emitter - * @param {string} name - */ - addSublanguage(emitter, name) { - /** @type DataNode */ - const node = emitter.root; - node.kind = name; - node.sublanguage = true; - this.add(node); - } - - toHTML() { - const renderer = new HTMLRenderer(this, this.options); - return renderer.value(); - } - - finalize() { - return true; - } -} - -/** - * @param {string} value - * @returns {RegExp} - * */ -function escape(value) { - return new RegExp(value.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'), 'm'); -} - -/** - * @param {RegExp | string } re - * @returns {string} - */ -function source(re) { - if (!re) return null; - if (typeof re === "string") return re; - - return re.source; -} - -/** - * @param {...(RegExp | string) } args - * @returns {string} - */ -function concat(...args) { - const joined = args.map((x) => source(x)).join(""); - return joined; -} - -/** - * Any of the passed expresssions may match - * - * Creates a huge this | this | that | that match - * @param {(RegExp | string)[] } args - * @returns {string} - */ -function either(...args) { - const joined = '(' + args.map((x) => source(x)).join("|") + ")"; - return joined; -} - -/** - * @param {RegExp} re - * @returns {number} - */ -function countMatchGroups(re) { - return (new RegExp(re.toString() + '|')).exec('').length - 1; -} - -/** - * Does lexeme start with a regular expression match at the beginning - * @param {RegExp} re - * @param {string} lexeme - */ -function startsWith(re, lexeme) { - const match = re && re.exec(lexeme); - return match && match.index === 0; -} - -// BACKREF_RE matches an open parenthesis or backreference. To avoid -// an incorrect parse, it additionally matches the following: -// - [...] elements, where the meaning of parentheses and escapes change -// - other escape sequences, so we do not misparse escape sequences as -// interesting elements -// - non-matching or lookahead parentheses, which do not capture. These -// follow the '(' with a '?'. -const BACKREF_RE = /\[(?:[^\\\]]|\\.)*\]|\(\??|\\([1-9][0-9]*)|\\./; - -// join logically computes regexps.join(separator), but fixes the -// backreferences so they continue to match. -// it also places each individual regular expression into it's own -// match group, keeping track of the sequencing of those match groups -// is currently an exercise for the caller. :-) -/** - * @param {(string | RegExp)[]} regexps - * @param {string} separator - * @returns {string} - */ -function join(regexps, separator = "|") { - let numCaptures = 0; - - return regexps.map((regex) => { - numCaptures += 1; - const offset = numCaptures; - let re = source(regex); - let out = ''; - - while (re.length > 0) { - const match = BACKREF_RE.exec(re); - if (!match) { - out += re; - break; - } - out += re.substring(0, match.index); - re = re.substring(match.index + match[0].length); - if (match[0][0] === '\\' && match[1]) { - // Adjust the backreference. - out += '\\' + String(Number(match[1]) + offset); - } else { - out += match[0]; - if (match[0] === '(') { - numCaptures++; - } - } - } - return out; - }).map(re => `(${re})`).join(separator); -} - -// Common regexps -const MATCH_NOTHING_RE = /\b\B/; -const IDENT_RE = '[a-zA-Z]\\w*'; -const UNDERSCORE_IDENT_RE = '[a-zA-Z_]\\w*'; -const NUMBER_RE = '\\b\\d+(\\.\\d+)?'; -const C_NUMBER_RE = '(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)'; // 0x..., 0..., decimal, float -const BINARY_NUMBER_RE = '\\b(0b[01]+)'; // 0b... -const RE_STARTERS_RE = '!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~'; - -/** -* @param { Partial & {binary?: string | RegExp} } opts -*/ -const SHEBANG = (opts = {}) => { - const beginShebang = /^#![ ]*\//; - if (opts.binary) { - opts.begin = concat( - beginShebang, - /.*\b/, - opts.binary, - /\b.*/); - } - return inherit({ - className: 'meta', - begin: beginShebang, - end: /$/, - relevance: 0, - /** @type {ModeCallback} */ - "on:begin": (m, resp) => { - if (m.index !== 0) resp.ignoreMatch(); - } - }, opts); -}; - -// Common modes -const BACKSLASH_ESCAPE = { - begin: '\\\\[\\s\\S]', relevance: 0 -}; -const APOS_STRING_MODE = { - className: 'string', - begin: '\'', - end: '\'', - illegal: '\\n', - contains: [BACKSLASH_ESCAPE] -}; -const QUOTE_STRING_MODE = { - className: 'string', - begin: '"', - end: '"', - illegal: '\\n', - contains: [BACKSLASH_ESCAPE] -}; -const PHRASAL_WORDS_MODE = { - begin: /\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/ -}; -/** - * Creates a comment mode - * - * @param {string | RegExp} begin - * @param {string | RegExp} end - * @param {Mode | {}} [modeOptions] - * @returns {Partial} - */ -const COMMENT = function(begin, end, modeOptions = {}) { - const mode = inherit( - { - className: 'comment', - begin, - end, - contains: [] - }, - modeOptions - ); - mode.contains.push(PHRASAL_WORDS_MODE); - mode.contains.push({ - className: 'doctag', - begin: '(?:TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):', - relevance: 0 - }); - return mode; -}; -const C_LINE_COMMENT_MODE = COMMENT('//', '$'); -const C_BLOCK_COMMENT_MODE = COMMENT('/\\*', '\\*/'); -const HASH_COMMENT_MODE = COMMENT('#', '$'); -const NUMBER_MODE = { - className: 'number', - begin: NUMBER_RE, - relevance: 0 -}; -const C_NUMBER_MODE = { - className: 'number', - begin: C_NUMBER_RE, - relevance: 0 -}; -const BINARY_NUMBER_MODE = { - className: 'number', - begin: BINARY_NUMBER_RE, - relevance: 0 -}; -const CSS_NUMBER_MODE = { - className: 'number', - begin: NUMBER_RE + '(' + - '%|em|ex|ch|rem' + - '|vw|vh|vmin|vmax' + - '|cm|mm|in|pt|pc|px' + - '|deg|grad|rad|turn' + - '|s|ms' + - '|Hz|kHz' + - '|dpi|dpcm|dppx' + - ')?', - relevance: 0 -}; -const REGEXP_MODE = { - // this outer rule makes sure we actually have a WHOLE regex and not simply - // an expression such as: - // - // 3 / something - // - // (which will then blow up when regex's `illegal` sees the newline) - begin: /(?=\/[^/\n]*\/)/, - contains: [{ - className: 'regexp', - begin: /\//, - end: /\/[gimuy]*/, - illegal: /\n/, - contains: [ - BACKSLASH_ESCAPE, - { - begin: /\[/, - end: /\]/, - relevance: 0, - contains: [BACKSLASH_ESCAPE] - } - ] - }] -}; -const TITLE_MODE = { - className: 'title', - begin: IDENT_RE, - relevance: 0 -}; -const UNDERSCORE_TITLE_MODE = { - className: 'title', - begin: UNDERSCORE_IDENT_RE, - relevance: 0 -}; -const METHOD_GUARD = { - // excludes method names from keyword processing - begin: '\\.\\s*' + UNDERSCORE_IDENT_RE, - relevance: 0 -}; - -/** - * Adds end same as begin mechanics to a mode - * - * Your mode must include at least a single () match group as that first match - * group is what is used for comparison - * @param {Partial} mode - */ -const END_SAME_AS_BEGIN = function(mode) { - return Object.assign(mode, - { - /** @type {ModeCallback} */ - 'on:begin': (m, resp) => { resp.data._beginMatch = m[1]; }, - /** @type {ModeCallback} */ - 'on:end': (m, resp) => { if (resp.data._beginMatch !== m[1]) resp.ignoreMatch(); } - }); -}; - -var MODES = /*#__PURE__*/Object.freeze({ - __proto__: null, - MATCH_NOTHING_RE: MATCH_NOTHING_RE, - IDENT_RE: IDENT_RE, - UNDERSCORE_IDENT_RE: UNDERSCORE_IDENT_RE, - NUMBER_RE: NUMBER_RE, - C_NUMBER_RE: C_NUMBER_RE, - BINARY_NUMBER_RE: BINARY_NUMBER_RE, - RE_STARTERS_RE: RE_STARTERS_RE, - SHEBANG: SHEBANG, - BACKSLASH_ESCAPE: BACKSLASH_ESCAPE, - APOS_STRING_MODE: APOS_STRING_MODE, - QUOTE_STRING_MODE: QUOTE_STRING_MODE, - PHRASAL_WORDS_MODE: PHRASAL_WORDS_MODE, - COMMENT: COMMENT, - C_LINE_COMMENT_MODE: C_LINE_COMMENT_MODE, - C_BLOCK_COMMENT_MODE: C_BLOCK_COMMENT_MODE, - HASH_COMMENT_MODE: HASH_COMMENT_MODE, - NUMBER_MODE: NUMBER_MODE, - C_NUMBER_MODE: C_NUMBER_MODE, - BINARY_NUMBER_MODE: BINARY_NUMBER_MODE, - CSS_NUMBER_MODE: CSS_NUMBER_MODE, - REGEXP_MODE: REGEXP_MODE, - TITLE_MODE: TITLE_MODE, - UNDERSCORE_TITLE_MODE: UNDERSCORE_TITLE_MODE, - METHOD_GUARD: METHOD_GUARD, - END_SAME_AS_BEGIN: END_SAME_AS_BEGIN -}); - -// Grammar extensions / plugins -// See: https://github.com/highlightjs/highlight.js/issues/2833 - -// Grammar extensions allow "syntactic sugar" to be added to the grammar modes -// without requiring any underlying changes to the compiler internals. - -// `compileMatch` being the perfect small example of now allowing a grammar -// author to write `match` when they desire to match a single expression rather -// than being forced to use `begin`. The extension then just moves `match` into -// `begin` when it runs. Ie, no features have been added, but we've just made -// the experience of writing (and reading grammars) a little bit nicer. - -// ------ - -// TODO: We need negative look-behind support to do this properly -/** - * Skip a match if it has a preceding dot - * - * This is used for `beginKeywords` to prevent matching expressions such as - * `bob.keyword.do()`. The mode compiler automatically wires this up as a - * special _internal_ 'on:begin' callback for modes with `beginKeywords` - * @param {RegExpMatchArray} match - * @param {CallbackResponse} response - */ -function skipIfhasPrecedingDot(match, response) { - const before = match.input[match.index - 1]; - if (before === ".") { - response.ignoreMatch(); - } -} - - -/** - * `beginKeywords` syntactic sugar - * @type {CompilerExt} - */ -function beginKeywords(mode, parent) { - if (!parent) return; - if (!mode.beginKeywords) return; - - // for languages with keywords that include non-word characters checking for - // a word boundary is not sufficient, so instead we check for a word boundary - // or whitespace - this does no harm in any case since our keyword engine - // doesn't allow spaces in keywords anyways and we still check for the boundary - // first - mode.begin = '\\b(' + mode.beginKeywords.split(' ').join('|') + ')(?!\\.)(?=\\b|\\s)'; - mode.__beforeBegin = skipIfhasPrecedingDot; - mode.keywords = mode.keywords || mode.beginKeywords; - delete mode.beginKeywords; - - // prevents double relevance, the keywords themselves provide - // relevance, the mode doesn't need to double it - // eslint-disable-next-line no-undefined - if (mode.relevance === undefined) mode.relevance = 0; -} - -/** - * Allow `illegal` to contain an array of illegal values - * @type {CompilerExt} - */ -function compileIllegal(mode, _parent) { - if (!Array.isArray(mode.illegal)) return; - - mode.illegal = either(...mode.illegal); -} - -/** - * `match` to match a single expression for readability - * @type {CompilerExt} - */ -function compileMatch(mode, _parent) { - if (!mode.match) return; - if (mode.begin || mode.end) throw new Error("begin & end are not supported with match"); - - mode.begin = mode.match; - delete mode.match; -} - -/** - * provides the default 1 relevance to all modes - * @type {CompilerExt} - */ -function compileRelevance(mode, _parent) { - // eslint-disable-next-line no-undefined - if (mode.relevance === undefined) mode.relevance = 1; -} - -// keywords that should have no default relevance value -const COMMON_KEYWORDS = [ - 'of', - 'and', - 'for', - 'in', - 'not', - 'or', - 'if', - 'then', - 'parent', // common variable name - 'list', // common variable name - 'value' // common variable name -]; - -const DEFAULT_KEYWORD_CLASSNAME = "keyword"; - -/** - * Given raw keywords from a language definition, compile them. - * - * @param {string | Record | Array} rawKeywords - * @param {boolean} caseInsensitive - */ -function compileKeywords(rawKeywords, caseInsensitive, className = DEFAULT_KEYWORD_CLASSNAME) { - /** @type KeywordDict */ - const compiledKeywords = {}; - - // input can be a string of keywords, an array of keywords, or a object with - // named keys representing className (which can then point to a string or array) - if (typeof rawKeywords === 'string') { - compileList(className, rawKeywords.split(" ")); - } else if (Array.isArray(rawKeywords)) { - compileList(className, rawKeywords); - } else { - Object.keys(rawKeywords).forEach(function(className) { - // collapse all our objects back into the parent object - Object.assign( - compiledKeywords, - compileKeywords(rawKeywords[className], caseInsensitive, className) - ); - }); - } - return compiledKeywords; - - // --- - - /** - * Compiles an individual list of keywords - * - * Ex: "for if when while|5" - * - * @param {string} className - * @param {Array} keywordList - */ - function compileList(className, keywordList) { - if (caseInsensitive) { - keywordList = keywordList.map(x => x.toLowerCase()); - } - keywordList.forEach(function(keyword) { - const pair = keyword.split('|'); - compiledKeywords[pair[0]] = [className, scoreForKeyword(pair[0], pair[1])]; - }); - } -} - -/** - * Returns the proper score for a given keyword - * - * Also takes into account comment keywords, which will be scored 0 UNLESS - * another score has been manually assigned. - * @param {string} keyword - * @param {string} [providedScore] - */ -function scoreForKeyword(keyword, providedScore) { - // manual scores always win over common keywords - // so you can force a score of 1 if you really insist - if (providedScore) { - return Number(providedScore); - } - - return commonKeyword(keyword) ? 0 : 1; -} - -/** - * Determines if a given keyword is common or not - * - * @param {string} keyword */ -function commonKeyword(keyword) { - return COMMON_KEYWORDS.includes(keyword.toLowerCase()); -} - -// compilation - -/** - * Compiles a language definition result - * - * Given the raw result of a language definition (Language), compiles this so - * that it is ready for highlighting code. - * @param {Language} language - * @param {{plugins: HLJSPlugin[]}} opts - * @returns {CompiledLanguage} - */ -function compileLanguage(language, { plugins }) { - /** - * Builds a regex with the case sensativility of the current language - * - * @param {RegExp | string} value - * @param {boolean} [global] - */ - function langRe(value, global) { - return new RegExp( - source(value), - 'm' + (language.case_insensitive ? 'i' : '') + (global ? 'g' : '') - ); - } - - /** - Stores multiple regular expressions and allows you to quickly search for - them all in a string simultaneously - returning the first match. It does - this by creating a huge (a|b|c) regex - each individual item wrapped with () - and joined by `|` - using match groups to track position. When a match is - found checking which position in the array has content allows us to figure - out which of the original regexes / match groups triggered the match. - - The match object itself (the result of `Regex.exec`) is returned but also - enhanced by merging in any meta-data that was registered with the regex. - This is how we keep track of which mode matched, and what type of rule - (`illegal`, `begin`, end, etc). - */ - class MultiRegex { - constructor() { - this.matchIndexes = {}; - // @ts-ignore - this.regexes = []; - this.matchAt = 1; - this.position = 0; - } - - // @ts-ignore - addRule(re, opts) { - opts.position = this.position++; - // @ts-ignore - this.matchIndexes[this.matchAt] = opts; - this.regexes.push([opts, re]); - this.matchAt += countMatchGroups(re) + 1; - } - - compile() { - if (this.regexes.length === 0) { - // avoids the need to check length every time exec is called - // @ts-ignore - this.exec = () => null; - } - const terminators = this.regexes.map(el => el[1]); - this.matcherRe = langRe(join(terminators), true); - this.lastIndex = 0; - } - - /** @param {string} s */ - exec(s) { - this.matcherRe.lastIndex = this.lastIndex; - const match = this.matcherRe.exec(s); - if (!match) { return null; } - - // eslint-disable-next-line no-undefined - const i = match.findIndex((el, i) => i > 0 && el !== undefined); - // @ts-ignore - const matchData = this.matchIndexes[i]; - // trim off any earlier non-relevant match groups (ie, the other regex - // match groups that make up the multi-matcher) - match.splice(0, i); - - return Object.assign(match, matchData); - } - } - - /* - Created to solve the key deficiently with MultiRegex - there is no way to - test for multiple matches at a single location. Why would we need to do - that? In the future a more dynamic engine will allow certain matches to be - ignored. An example: if we matched say the 3rd regex in a large group but - decided to ignore it - we'd need to started testing again at the 4th - regex... but MultiRegex itself gives us no real way to do that. - - So what this class creates MultiRegexs on the fly for whatever search - position they are needed. - - NOTE: These additional MultiRegex objects are created dynamically. For most - grammars most of the time we will never actually need anything more than the - first MultiRegex - so this shouldn't have too much overhead. - - Say this is our search group, and we match regex3, but wish to ignore it. - - regex1 | regex2 | regex3 | regex4 | regex5 ' ie, startAt = 0 - - What we need is a new MultiRegex that only includes the remaining - possibilities: - - regex4 | regex5 ' ie, startAt = 3 - - This class wraps all that complexity up in a simple API... `startAt` decides - where in the array of expressions to start doing the matching. It - auto-increments, so if a match is found at position 2, then startAt will be - set to 3. If the end is reached startAt will return to 0. - - MOST of the time the parser will be setting startAt manually to 0. - */ - class ResumableMultiRegex { - constructor() { - // @ts-ignore - this.rules = []; - // @ts-ignore - this.multiRegexes = []; - this.count = 0; - - this.lastIndex = 0; - this.regexIndex = 0; - } - - // @ts-ignore - getMatcher(index) { - if (this.multiRegexes[index]) return this.multiRegexes[index]; - - const matcher = new MultiRegex(); - this.rules.slice(index).forEach(([re, opts]) => matcher.addRule(re, opts)); - matcher.compile(); - this.multiRegexes[index] = matcher; - return matcher; - } - - resumingScanAtSamePosition() { - return this.regexIndex !== 0; - } - - considerAll() { - this.regexIndex = 0; - } - - // @ts-ignore - addRule(re, opts) { - this.rules.push([re, opts]); - if (opts.type === "begin") this.count++; - } - - /** @param {string} s */ - exec(s) { - const m = this.getMatcher(this.regexIndex); - m.lastIndex = this.lastIndex; - let result = m.exec(s); - - // The following is because we have no easy way to say "resume scanning at the - // existing position but also skip the current rule ONLY". What happens is - // all prior rules are also skipped which can result in matching the wrong - // thing. Example of matching "booger": - - // our matcher is [string, "booger", number] - // - // ....booger.... - - // if "booger" is ignored then we'd really need a regex to scan from the - // SAME position for only: [string, number] but ignoring "booger" (if it - // was the first match), a simple resume would scan ahead who knows how - // far looking only for "number", ignoring potential string matches (or - // future "booger" matches that might be valid.) - - // So what we do: We execute two matchers, one resuming at the same - // position, but the second full matcher starting at the position after: - - // /--- resume first regex match here (for [number]) - // |/---- full match here for [string, "booger", number] - // vv - // ....booger.... - - // Which ever results in a match first is then used. So this 3-4 step - // process essentially allows us to say "match at this position, excluding - // a prior rule that was ignored". - // - // 1. Match "booger" first, ignore. Also proves that [string] does non match. - // 2. Resume matching for [number] - // 3. Match at index + 1 for [string, "booger", number] - // 4. If #2 and #3 result in matches, which came first? - if (this.resumingScanAtSamePosition()) { - if (result && result.index === this.lastIndex) ; else { // use the second matcher result - const m2 = this.getMatcher(0); - m2.lastIndex = this.lastIndex + 1; - result = m2.exec(s); - } - } - - if (result) { - this.regexIndex += result.position + 1; - if (this.regexIndex === this.count) { - // wrap-around to considering all matches again - this.considerAll(); - } - } - - return result; - } - } - - /** - * Given a mode, builds a huge ResumableMultiRegex that can be used to walk - * the content and find matches. - * - * @param {CompiledMode} mode - * @returns {ResumableMultiRegex} - */ - function buildModeRegex(mode) { - const mm = new ResumableMultiRegex(); - - mode.contains.forEach(term => mm.addRule(term.begin, { rule: term, type: "begin" })); - - if (mode.terminatorEnd) { - mm.addRule(mode.terminatorEnd, { type: "end" }); - } - if (mode.illegal) { - mm.addRule(mode.illegal, { type: "illegal" }); - } - - return mm; - } - - /** skip vs abort vs ignore - * - * @skip - The mode is still entered and exited normally (and contains rules apply), - * but all content is held and added to the parent buffer rather than being - * output when the mode ends. Mostly used with `sublanguage` to build up - * a single large buffer than can be parsed by sublanguage. - * - * - The mode begin ands ends normally. - * - Content matched is added to the parent mode buffer. - * - The parser cursor is moved forward normally. - * - * @abort - A hack placeholder until we have ignore. Aborts the mode (as if it - * never matched) but DOES NOT continue to match subsequent `contains` - * modes. Abort is bad/suboptimal because it can result in modes - * farther down not getting applied because an earlier rule eats the - * content but then aborts. - * - * - The mode does not begin. - * - Content matched by `begin` is added to the mode buffer. - * - The parser cursor is moved forward accordingly. - * - * @ignore - Ignores the mode (as if it never matched) and continues to match any - * subsequent `contains` modes. Ignore isn't technically possible with - * the current parser implementation. - * - * - The mode does not begin. - * - Content matched by `begin` is ignored. - * - The parser cursor is not moved forward. - */ - - /** - * Compiles an individual mode - * - * This can raise an error if the mode contains certain detectable known logic - * issues. - * @param {Mode} mode - * @param {CompiledMode | null} [parent] - * @returns {CompiledMode | never} - */ - function compileMode(mode, parent) { - const cmode = /** @type CompiledMode */ (mode); - if (mode.isCompiled) return cmode; - - [ - // do this early so compiler extensions generally don't have to worry about - // the distinction between match/begin - compileMatch - ].forEach(ext => ext(mode, parent)); - - language.compilerExtensions.forEach(ext => ext(mode, parent)); - - // __beforeBegin is considered private API, internal use only - mode.__beforeBegin = null; - - [ - beginKeywords, - // do this later so compiler extensions that come earlier have access to the - // raw array if they wanted to perhaps manipulate it, etc. - compileIllegal, - // default to 1 relevance if not specified - compileRelevance - ].forEach(ext => ext(mode, parent)); - - mode.isCompiled = true; - - let keywordPattern = null; - if (typeof mode.keywords === "object") { - keywordPattern = mode.keywords.$pattern; - delete mode.keywords.$pattern; - } - - if (mode.keywords) { - mode.keywords = compileKeywords(mode.keywords, language.case_insensitive); - } - - // both are not allowed - if (mode.lexemes && keywordPattern) { - throw new Error("ERR: Prefer `keywords.$pattern` to `mode.lexemes`, BOTH are not allowed. (see mode reference) "); - } - - // `mode.lexemes` was the old standard before we added and now recommend - // using `keywords.$pattern` to pass the keyword pattern - keywordPattern = keywordPattern || mode.lexemes || /\w+/; - cmode.keywordPatternRe = langRe(keywordPattern, true); - - if (parent) { - if (!mode.begin) mode.begin = /\B|\b/; - cmode.beginRe = langRe(mode.begin); - if (mode.endSameAsBegin) mode.end = mode.begin; - if (!mode.end && !mode.endsWithParent) mode.end = /\B|\b/; - if (mode.end) cmode.endRe = langRe(mode.end); - cmode.terminatorEnd = source(mode.end) || ''; - if (mode.endsWithParent && parent.terminatorEnd) { - cmode.terminatorEnd += (mode.end ? '|' : '') + parent.terminatorEnd; - } - } - if (mode.illegal) cmode.illegalRe = langRe(/** @type {RegExp | string} */ (mode.illegal)); - if (!mode.contains) mode.contains = []; - - mode.contains = [].concat(...mode.contains.map(function(c) { - return expandOrCloneMode(c === 'self' ? mode : c); - })); - mode.contains.forEach(function(c) { compileMode(/** @type Mode */ (c), cmode); }); - - if (mode.starts) { - compileMode(mode.starts, parent); - } - - cmode.matcher = buildModeRegex(cmode); - return cmode; - } - - if (!language.compilerExtensions) language.compilerExtensions = []; - - // self is not valid at the top-level - if (language.contains && language.contains.includes('self')) { - throw new Error("ERR: contains `self` is not supported at the top-level of a language. See documentation."); - } - - // we need a null object, which inherit will guarantee - language.classNameAliases = inherit(language.classNameAliases || {}); - - return compileMode(/** @type Mode */ (language)); -} - -/** - * Determines if a mode has a dependency on it's parent or not - * - * If a mode does have a parent dependency then often we need to clone it if - * it's used in multiple places so that each copy points to the correct parent, - * where-as modes without a parent can often safely be re-used at the bottom of - * a mode chain. - * - * @param {Mode | null} mode - * @returns {boolean} - is there a dependency on the parent? - * */ -function dependencyOnParent(mode) { - if (!mode) return false; - - return mode.endsWithParent || dependencyOnParent(mode.starts); -} - -/** - * Expands a mode or clones it if necessary - * - * This is necessary for modes with parental dependenceis (see notes on - * `dependencyOnParent`) and for nodes that have `variants` - which must then be - * exploded into their own individual modes at compile time. - * - * @param {Mode} mode - * @returns {Mode | Mode[]} - * */ -function expandOrCloneMode(mode) { - if (mode.variants && !mode.cachedVariants) { - mode.cachedVariants = mode.variants.map(function(variant) { - return inherit(mode, { variants: null }, variant); - }); - } - - // EXPAND - // if we have variants then essentially "replace" the mode with the variants - // this happens in compileMode, where this function is called from - if (mode.cachedVariants) { - return mode.cachedVariants; - } - - // CLONE - // if we have dependencies on parents then we need a unique - // instance of ourselves, so we can be reused with many - // different parents without issue - if (dependencyOnParent(mode)) { - return inherit(mode, { starts: mode.starts ? inherit(mode.starts) : null }); - } - - if (Object.isFrozen(mode)) { - return inherit(mode); - } - - // no special dependency issues, just return ourselves - return mode; -} - -var version = "10.7.3"; - -// @ts-nocheck - -function hasValueOrEmptyAttribute(value) { - return Boolean(value || value === ""); -} - -function BuildVuePlugin(hljs) { - const Component = { - props: ["language", "code", "autodetect"], - data: function() { - return { - detectedLanguage: "", - unknownLanguage: false - }; - }, - computed: { - className() { - if (this.unknownLanguage) return ""; - - return "hljs " + this.detectedLanguage; - }, - highlighted() { - // no idea what language to use, return raw code - if (!this.autoDetect && !hljs.getLanguage(this.language)) { - console.warn(`The language "${this.language}" you specified could not be found.`); - this.unknownLanguage = true; - return escapeHTML(this.code); - } - - let result = {}; - if (this.autoDetect) { - result = hljs.highlightAuto(this.code); - this.detectedLanguage = result.language; - } else { - result = hljs.highlight(this.language, this.code, this.ignoreIllegals); - this.detectedLanguage = this.language; - } - return result.value; - }, - autoDetect() { - return !this.language || hasValueOrEmptyAttribute(this.autodetect); - }, - ignoreIllegals() { - return true; - } - }, - // this avoids needing to use a whole Vue compilation pipeline just - // to build Highlight.js - render(createElement) { - return createElement("pre", {}, [ - createElement("code", { - class: this.className, - domProps: { innerHTML: this.highlighted } - }) - ]); - } - // template: `

    ` - }; - - const VuePlugin = { - install(Vue) { - Vue.component('highlightjs', Component); - } - }; - - return { Component, VuePlugin }; -} - -/* plugin itself */ - -/** @type {HLJSPlugin} */ -const mergeHTMLPlugin = { - "after:highlightElement": ({ el, result, text }) => { - const originalStream = nodeStream(el); - if (!originalStream.length) return; - - const resultNode = document.createElement('div'); - resultNode.innerHTML = result.value; - result.value = mergeStreams(originalStream, nodeStream(resultNode), text); - } -}; - -/* Stream merging support functions */ - -/** - * @typedef Event - * @property {'start'|'stop'} event - * @property {number} offset - * @property {Node} node - */ - -/** - * @param {Node} node - */ -function tag(node) { - return node.nodeName.toLowerCase(); -} - -/** - * @param {Node} node - */ -function nodeStream(node) { - /** @type Event[] */ - const result = []; - (function _nodeStream(node, offset) { - for (let child = node.firstChild; child; child = child.nextSibling) { - if (child.nodeType === 3) { - offset += child.nodeValue.length; - } else if (child.nodeType === 1) { - result.push({ - event: 'start', - offset: offset, - node: child - }); - offset = _nodeStream(child, offset); - // Prevent void elements from having an end tag that would actually - // double them in the output. There are more void elements in HTML - // but we list only those realistically expected in code display. - if (!tag(child).match(/br|hr|img|input/)) { - result.push({ - event: 'stop', - offset: offset, - node: child - }); - } - } - } - return offset; - })(node, 0); - return result; -} - -/** - * @param {any} original - the original stream - * @param {any} highlighted - stream of the highlighted source - * @param {string} value - the original source itself - */ -function mergeStreams(original, highlighted, value) { - let processed = 0; - let result = ''; - const nodeStack = []; - - function selectStream() { - if (!original.length || !highlighted.length) { - return original.length ? original : highlighted; - } - if (original[0].offset !== highlighted[0].offset) { - return (original[0].offset < highlighted[0].offset) ? original : highlighted; - } - - /* - To avoid starting the stream just before it should stop the order is - ensured that original always starts first and closes last: - - if (event1 == 'start' && event2 == 'start') - return original; - if (event1 == 'start' && event2 == 'stop') - return highlighted; - if (event1 == 'stop' && event2 == 'start') - return original; - if (event1 == 'stop' && event2 == 'stop') - return highlighted; - - ... which is collapsed to: - */ - return highlighted[0].event === 'start' ? original : highlighted; - } - - /** - * @param {Node} node - */ - function open(node) { - /** @param {Attr} attr */ - function attributeString(attr) { - return ' ' + attr.nodeName + '="' + escapeHTML(attr.value) + '"'; - } - // @ts-ignore - result += '<' + tag(node) + [].map.call(node.attributes, attributeString).join('') + '>'; - } - - /** - * @param {Node} node - */ - function close(node) { - result += ''; - } - - /** - * @param {Event} event - */ - function render(event) { - (event.event === 'start' ? open : close)(event.node); - } - - while (original.length || highlighted.length) { - let stream = selectStream(); - result += escapeHTML(value.substring(processed, stream[0].offset)); - processed = stream[0].offset; - if (stream === original) { - /* - On any opening or closing tag of the original markup we first close - the entire highlighted node stack, then render the original tag along - with all the following original tags at the same offset and then - reopen all the tags on the highlighted stack. - */ - nodeStack.reverse().forEach(close); - do { - render(stream.splice(0, 1)[0]); - stream = selectStream(); - } while (stream === original && stream.length && stream[0].offset === processed); - nodeStack.reverse().forEach(open); - } else { - if (stream[0].event === 'start') { - nodeStack.push(stream[0].node); - } else { - nodeStack.pop(); - } - render(stream.splice(0, 1)[0]); - } - } - return result + escapeHTML(value.substr(processed)); -} - -/* - -For the reasoning behind this please see: -https://github.com/highlightjs/highlight.js/issues/2880#issuecomment-747275419 - -*/ - -/** - * @type {Record} - */ -const seenDeprecations = {}; - -/** - * @param {string} message - */ -const error = (message) => { - console.error(message); -}; - -/** - * @param {string} message - * @param {any} args - */ -const warn = (message, ...args) => { - console.log(`WARN: ${message}`, ...args); -}; - -/** - * @param {string} version - * @param {string} message - */ -const deprecated = (version, message) => { - if (seenDeprecations[`${version}/${message}`]) return; - - console.log(`Deprecated as of ${version}. ${message}`); - seenDeprecations[`${version}/${message}`] = true; -}; - -/* -Syntax highlighting with language autodetection. -https://highlightjs.org/ -*/ - -const escape$1 = escapeHTML; -const inherit$1 = inherit; -const NO_MATCH = Symbol("nomatch"); - -/** - * @param {any} hljs - object that is extended (legacy) - * @returns {HLJSApi} - */ -const HLJS = function(hljs) { - // Global internal variables used within the highlight.js library. - /** @type {Record} */ - const languages = Object.create(null); - /** @type {Record} */ - const aliases = Object.create(null); - /** @type {HLJSPlugin[]} */ - const plugins = []; - - // safe/production mode - swallows more errors, tries to keep running - // even if a single syntax or parse hits a fatal error - let SAFE_MODE = true; - const fixMarkupRe = /(^(<[^>]+>|\t|)+|\n)/gm; - const LANGUAGE_NOT_FOUND = "Could not find the language '{}', did you forget to load/include a language module?"; - /** @type {Language} */ - const PLAINTEXT_LANGUAGE = { disableAutodetect: true, name: 'Plain text', contains: [] }; - - // Global options used when within external APIs. This is modified when - // calling the `hljs.configure` function. - /** @type HLJSOptions */ - let options = { - noHighlightRe: /^(no-?highlight)$/i, - languageDetectRe: /\blang(?:uage)?-([\w-]+)\b/i, - classPrefix: 'hljs-', - tabReplace: null, - useBR: false, - languages: null, - // beta configuration options, subject to change, welcome to discuss - // https://github.com/highlightjs/highlight.js/issues/1086 - __emitter: TokenTreeEmitter - }; - - /* Utility functions */ - - /** - * Tests a language name to see if highlighting should be skipped - * @param {string} languageName - */ - function shouldNotHighlight(languageName) { - return options.noHighlightRe.test(languageName); - } - - /** - * @param {HighlightedHTMLElement} block - the HTML element to determine language for - */ - function blockLanguage(block) { - let classes = block.className + ' '; - - classes += block.parentNode ? block.parentNode.className : ''; - - // language-* takes precedence over non-prefixed class names. - const match = options.languageDetectRe.exec(classes); - if (match) { - const language = getLanguage(match[1]); - if (!language) { - warn(LANGUAGE_NOT_FOUND.replace("{}", match[1])); - warn("Falling back to no-highlight mode for this block.", block); - } - return language ? match[1] : 'no-highlight'; - } - - return classes - .split(/\s+/) - .find((_class) => shouldNotHighlight(_class) || getLanguage(_class)); - } - - /** - * Core highlighting function. - * - * OLD API - * highlight(lang, code, ignoreIllegals, continuation) - * - * NEW API - * highlight(code, {lang, ignoreIllegals}) - * - * @param {string} codeOrlanguageName - the language to use for highlighting - * @param {string | HighlightOptions} optionsOrCode - the code to highlight - * @param {boolean} [ignoreIllegals] - whether to ignore illegal matches, default is to bail - * @param {CompiledMode} [continuation] - current continuation mode, if any - * - * @returns {HighlightResult} Result - an object that represents the result - * @property {string} language - the language name - * @property {number} relevance - the relevance score - * @property {string} value - the highlighted HTML code - * @property {string} code - the original raw code - * @property {CompiledMode} top - top of the current mode stack - * @property {boolean} illegal - indicates whether any illegal matches were found - */ - function highlight(codeOrlanguageName, optionsOrCode, ignoreIllegals, continuation) { - let code = ""; - let languageName = ""; - if (typeof optionsOrCode === "object") { - code = codeOrlanguageName; - ignoreIllegals = optionsOrCode.ignoreIllegals; - languageName = optionsOrCode.language; - // continuation not supported at all via the new API - // eslint-disable-next-line no-undefined - continuation = undefined; - } else { - // old API - deprecated("10.7.0", "highlight(lang, code, ...args) has been deprecated."); - deprecated("10.7.0", "Please use highlight(code, options) instead.\nhttps://github.com/highlightjs/highlight.js/issues/2277"); - languageName = codeOrlanguageName; - code = optionsOrCode; - } - - /** @type {BeforeHighlightContext} */ - const context = { - code, - language: languageName - }; - // the plugin can change the desired language or the code to be highlighted - // just be changing the object it was passed - fire("before:highlight", context); - - // a before plugin can usurp the result completely by providing it's own - // in which case we don't even need to call highlight - const result = context.result - ? context.result - : _highlight(context.language, context.code, ignoreIllegals, continuation); - - result.code = context.code; - // the plugin can change anything in result to suite it - fire("after:highlight", result); - - return result; - } - - /** - * private highlight that's used internally and does not fire callbacks - * - * @param {string} languageName - the language to use for highlighting - * @param {string} codeToHighlight - the code to highlight - * @param {boolean?} [ignoreIllegals] - whether to ignore illegal matches, default is to bail - * @param {CompiledMode?} [continuation] - current continuation mode, if any - * @returns {HighlightResult} - result of the highlight operation - */ - function _highlight(languageName, codeToHighlight, ignoreIllegals, continuation) { - /** - * Return keyword data if a match is a keyword - * @param {CompiledMode} mode - current mode - * @param {RegExpMatchArray} match - regexp match data - * @returns {KeywordData | false} - */ - function keywordData(mode, match) { - const matchText = language.case_insensitive ? match[0].toLowerCase() : match[0]; - return Object.prototype.hasOwnProperty.call(mode.keywords, matchText) && mode.keywords[matchText]; - } - - function processKeywords() { - if (!top.keywords) { - emitter.addText(modeBuffer); - return; - } - - let lastIndex = 0; - top.keywordPatternRe.lastIndex = 0; - let match = top.keywordPatternRe.exec(modeBuffer); - let buf = ""; - - while (match) { - buf += modeBuffer.substring(lastIndex, match.index); - const data = keywordData(top, match); - if (data) { - const [kind, keywordRelevance] = data; - emitter.addText(buf); - buf = ""; - - relevance += keywordRelevance; - if (kind.startsWith("_")) { - // _ implied for relevance only, do not highlight - // by applying a class name - buf += match[0]; - } else { - const cssClass = language.classNameAliases[kind] || kind; - emitter.addKeyword(match[0], cssClass); - } - } else { - buf += match[0]; - } - lastIndex = top.keywordPatternRe.lastIndex; - match = top.keywordPatternRe.exec(modeBuffer); - } - buf += modeBuffer.substr(lastIndex); - emitter.addText(buf); - } - - function processSubLanguage() { - if (modeBuffer === "") return; - /** @type HighlightResult */ - let result = null; - - if (typeof top.subLanguage === 'string') { - if (!languages[top.subLanguage]) { - emitter.addText(modeBuffer); - return; - } - result = _highlight(top.subLanguage, modeBuffer, true, continuations[top.subLanguage]); - continuations[top.subLanguage] = /** @type {CompiledMode} */ (result.top); - } else { - result = highlightAuto(modeBuffer, top.subLanguage.length ? top.subLanguage : null); - } - - // Counting embedded language score towards the host language may be disabled - // with zeroing the containing mode relevance. Use case in point is Markdown that - // allows XML everywhere and makes every XML snippet to have a much larger Markdown - // score. - if (top.relevance > 0) { - relevance += result.relevance; - } - emitter.addSublanguage(result.emitter, result.language); - } - - function processBuffer() { - if (top.subLanguage != null) { - processSubLanguage(); - } else { - processKeywords(); - } - modeBuffer = ''; - } - - /** - * @param {Mode} mode - new mode to start - */ - function startNewMode(mode) { - if (mode.className) { - emitter.openNode(language.classNameAliases[mode.className] || mode.className); - } - top = Object.create(mode, { parent: { value: top } }); - return top; - } - - /** - * @param {CompiledMode } mode - the mode to potentially end - * @param {RegExpMatchArray} match - the latest match - * @param {string} matchPlusRemainder - match plus remainder of content - * @returns {CompiledMode | void} - the next mode, or if void continue on in current mode - */ - function endOfMode(mode, match, matchPlusRemainder) { - let matched = startsWith(mode.endRe, matchPlusRemainder); - - if (matched) { - if (mode["on:end"]) { - const resp = new Response(mode); - mode["on:end"](match, resp); - if (resp.isMatchIgnored) matched = false; - } - - if (matched) { - while (mode.endsParent && mode.parent) { - mode = mode.parent; - } - return mode; - } - } - // even if on:end fires an `ignore` it's still possible - // that we might trigger the end node because of a parent mode - if (mode.endsWithParent) { - return endOfMode(mode.parent, match, matchPlusRemainder); - } - } - - /** - * Handle matching but then ignoring a sequence of text - * - * @param {string} lexeme - string containing full match text - */ - function doIgnore(lexeme) { - if (top.matcher.regexIndex === 0) { - // no more regexs to potentially match here, so we move the cursor forward one - // space - modeBuffer += lexeme[0]; - return 1; - } else { - // no need to move the cursor, we still have additional regexes to try and - // match at this very spot - resumeScanAtSamePosition = true; - return 0; - } - } - - /** - * Handle the start of a new potential mode match - * - * @param {EnhancedMatch} match - the current match - * @returns {number} how far to advance the parse cursor - */ - function doBeginMatch(match) { - const lexeme = match[0]; - const newMode = match.rule; - - const resp = new Response(newMode); - // first internal before callbacks, then the public ones - const beforeCallbacks = [newMode.__beforeBegin, newMode["on:begin"]]; - for (const cb of beforeCallbacks) { - if (!cb) continue; - cb(match, resp); - if (resp.isMatchIgnored) return doIgnore(lexeme); - } - - if (newMode && newMode.endSameAsBegin) { - newMode.endRe = escape(lexeme); - } - - if (newMode.skip) { - modeBuffer += lexeme; - } else { - if (newMode.excludeBegin) { - modeBuffer += lexeme; - } - processBuffer(); - if (!newMode.returnBegin && !newMode.excludeBegin) { - modeBuffer = lexeme; - } - } - startNewMode(newMode); - // if (mode["after:begin"]) { - // let resp = new Response(mode); - // mode["after:begin"](match, resp); - // } - return newMode.returnBegin ? 0 : lexeme.length; - } - - /** - * Handle the potential end of mode - * - * @param {RegExpMatchArray} match - the current match - */ - function doEndMatch(match) { - const lexeme = match[0]; - const matchPlusRemainder = codeToHighlight.substr(match.index); - - const endMode = endOfMode(top, match, matchPlusRemainder); - if (!endMode) { return NO_MATCH; } - - const origin = top; - if (origin.skip) { - modeBuffer += lexeme; - } else { - if (!(origin.returnEnd || origin.excludeEnd)) { - modeBuffer += lexeme; - } - processBuffer(); - if (origin.excludeEnd) { - modeBuffer = lexeme; - } - } - do { - if (top.className) { - emitter.closeNode(); - } - if (!top.skip && !top.subLanguage) { - relevance += top.relevance; - } - top = top.parent; - } while (top !== endMode.parent); - if (endMode.starts) { - if (endMode.endSameAsBegin) { - endMode.starts.endRe = endMode.endRe; - } - startNewMode(endMode.starts); - } - return origin.returnEnd ? 0 : lexeme.length; - } - - function processContinuations() { - const list = []; - for (let current = top; current !== language; current = current.parent) { - if (current.className) { - list.unshift(current.className); - } - } - list.forEach(item => emitter.openNode(item)); - } - - /** @type {{type?: MatchType, index?: number, rule?: Mode}}} */ - let lastMatch = {}; - - /** - * Process an individual match - * - * @param {string} textBeforeMatch - text preceeding the match (since the last match) - * @param {EnhancedMatch} [match] - the match itself - */ - function processLexeme(textBeforeMatch, match) { - const lexeme = match && match[0]; - - // add non-matched text to the current mode buffer - modeBuffer += textBeforeMatch; - - if (lexeme == null) { - processBuffer(); - return 0; - } - - // we've found a 0 width match and we're stuck, so we need to advance - // this happens when we have badly behaved rules that have optional matchers to the degree that - // sometimes they can end up matching nothing at all - // Ref: https://github.com/highlightjs/highlight.js/issues/2140 - if (lastMatch.type === "begin" && match.type === "end" && lastMatch.index === match.index && lexeme === "") { - // spit the "skipped" character that our regex choked on back into the output sequence - modeBuffer += codeToHighlight.slice(match.index, match.index + 1); - if (!SAFE_MODE) { - /** @type {AnnotatedError} */ - const err = new Error('0 width match regex'); - err.languageName = languageName; - err.badRule = lastMatch.rule; - throw err; - } - return 1; - } - lastMatch = match; - - if (match.type === "begin") { - return doBeginMatch(match); - } else if (match.type === "illegal" && !ignoreIllegals) { - // illegal match, we do not continue processing - /** @type {AnnotatedError} */ - const err = new Error('Illegal lexeme "' + lexeme + '" for mode "' + (top.className || '') + '"'); - err.mode = top; - throw err; - } else if (match.type === "end") { - const processed = doEndMatch(match); - if (processed !== NO_MATCH) { - return processed; - } - } - - // edge case for when illegal matches $ (end of line) which is technically - // a 0 width match but not a begin/end match so it's not caught by the - // first handler (when ignoreIllegals is true) - if (match.type === "illegal" && lexeme === "") { - // advance so we aren't stuck in an infinite loop - return 1; - } - - // infinite loops are BAD, this is a last ditch catch all. if we have a - // decent number of iterations yet our index (cursor position in our - // parsing) still 3x behind our index then something is very wrong - // so we bail - if (iterations > 100000 && iterations > match.index * 3) { - const err = new Error('potential infinite loop, way more iterations than matches'); - throw err; - } - - /* - Why might be find ourselves here? Only one occasion now. An end match that was - triggered but could not be completed. When might this happen? When an `endSameasBegin` - rule sets the end rule to a specific match. Since the overall mode termination rule that's - being used to scan the text isn't recompiled that means that any match that LOOKS like - the end (but is not, because it is not an exact match to the beginning) will - end up here. A definite end match, but when `doEndMatch` tries to "reapply" - the end rule and fails to match, we wind up here, and just silently ignore the end. - - This causes no real harm other than stopping a few times too many. - */ - - modeBuffer += lexeme; - return lexeme.length; - } - - const language = getLanguage(languageName); - if (!language) { - error(LANGUAGE_NOT_FOUND.replace("{}", languageName)); - throw new Error('Unknown language: "' + languageName + '"'); - } - - const md = compileLanguage(language, { plugins }); - let result = ''; - /** @type {CompiledMode} */ - let top = continuation || md; - /** @type Record */ - const continuations = {}; // keep continuations for sub-languages - const emitter = new options.__emitter(options); - processContinuations(); - let modeBuffer = ''; - let relevance = 0; - let index = 0; - let iterations = 0; - let resumeScanAtSamePosition = false; - - try { - top.matcher.considerAll(); - - for (;;) { - iterations++; - if (resumeScanAtSamePosition) { - // only regexes not matched previously will now be - // considered for a potential match - resumeScanAtSamePosition = false; - } else { - top.matcher.considerAll(); - } - top.matcher.lastIndex = index; - - const match = top.matcher.exec(codeToHighlight); - // console.log("match", match[0], match.rule && match.rule.begin) - - if (!match) break; - - const beforeMatch = codeToHighlight.substring(index, match.index); - const processedCount = processLexeme(beforeMatch, match); - index = match.index + processedCount; - } - processLexeme(codeToHighlight.substr(index)); - emitter.closeAllNodes(); - emitter.finalize(); - result = emitter.toHTML(); - - return { - // avoid possible breakage with v10 clients expecting - // this to always be an integer - relevance: Math.floor(relevance), - value: result, - language: languageName, - illegal: false, - emitter: emitter, - top: top - }; - } catch (err) { - if (err.message && err.message.includes('Illegal')) { - return { - illegal: true, - illegalBy: { - msg: err.message, - context: codeToHighlight.slice(index - 100, index + 100), - mode: err.mode - }, - sofar: result, - relevance: 0, - value: escape$1(codeToHighlight), - emitter: emitter - }; - } else if (SAFE_MODE) { - return { - illegal: false, - relevance: 0, - value: escape$1(codeToHighlight), - emitter: emitter, - language: languageName, - top: top, - errorRaised: err - }; - } else { - throw err; - } - } - } - - /** - * returns a valid highlight result, without actually doing any actual work, - * auto highlight starts with this and it's possible for small snippets that - * auto-detection may not find a better match - * @param {string} code - * @returns {HighlightResult} - */ - function justTextHighlightResult(code) { - const result = { - relevance: 0, - emitter: new options.__emitter(options), - value: escape$1(code), - illegal: false, - top: PLAINTEXT_LANGUAGE - }; - result.emitter.addText(code); - return result; - } - - /** - Highlighting with language detection. Accepts a string with the code to - highlight. Returns an object with the following properties: - - - language (detected language) - - relevance (int) - - value (an HTML string with highlighting markup) - - second_best (object with the same structure for second-best heuristically - detected language, may be absent) - - @param {string} code - @param {Array} [languageSubset] - @returns {AutoHighlightResult} - */ - function highlightAuto(code, languageSubset) { - languageSubset = languageSubset || options.languages || Object.keys(languages); - const plaintext = justTextHighlightResult(code); - - const results = languageSubset.filter(getLanguage).filter(autoDetection).map(name => - _highlight(name, code, false) - ); - results.unshift(plaintext); // plaintext is always an option - - const sorted = results.sort((a, b) => { - // sort base on relevance - if (a.relevance !== b.relevance) return b.relevance - a.relevance; - - // always award the tie to the base language - // ie if C++ and Arduino are tied, it's more likely to be C++ - if (a.language && b.language) { - if (getLanguage(a.language).supersetOf === b.language) { - return 1; - } else if (getLanguage(b.language).supersetOf === a.language) { - return -1; - } - } - - // otherwise say they are equal, which has the effect of sorting on - // relevance while preserving the original ordering - which is how ties - // have historically been settled, ie the language that comes first always - // wins in the case of a tie - return 0; - }); - - const [best, secondBest] = sorted; - - /** @type {AutoHighlightResult} */ - const result = best; - result.second_best = secondBest; - - return result; - } - - /** - Post-processing of the highlighted markup: - - - replace TABs with something more useful - - replace real line-breaks with '
    ' for non-pre containers - - @param {string} html - @returns {string} - */ - function fixMarkup(html) { - if (!(options.tabReplace || options.useBR)) { - return html; - } - - return html.replace(fixMarkupRe, match => { - if (match === '\n') { - return options.useBR ? '
    ' : match; - } else if (options.tabReplace) { - return match.replace(/\t/g, options.tabReplace); - } - return match; - }); - } - - /** - * Builds new class name for block given the language name - * - * @param {HTMLElement} element - * @param {string} [currentLang] - * @param {string} [resultLang] - */ - function updateClassName(element, currentLang, resultLang) { - const language = currentLang ? aliases[currentLang] : resultLang; - - element.classList.add("hljs"); - if (language) element.classList.add(language); - } - - /** @type {HLJSPlugin} */ - const brPlugin = { - "before:highlightElement": ({ el }) => { - if (options.useBR) { - el.innerHTML = el.innerHTML.replace(/\n/g, '').replace(//g, '\n'); - } - }, - "after:highlightElement": ({ result }) => { - if (options.useBR) { - result.value = result.value.replace(/\n/g, "
    "); - } - } - }; - - const TAB_REPLACE_RE = /^(<[^>]+>|\t)+/gm; - /** @type {HLJSPlugin} */ - const tabReplacePlugin = { - "after:highlightElement": ({ result }) => { - if (options.tabReplace) { - result.value = result.value.replace(TAB_REPLACE_RE, (m) => - m.replace(/\t/g, options.tabReplace) - ); - } - } - }; - - /** - * Applies highlighting to a DOM node containing code. Accepts a DOM node and - * two optional parameters for fixMarkup. - * - * @param {HighlightedHTMLElement} element - the HTML element to highlight - */ - function highlightElement(element) { - /** @type HTMLElement */ - let node = null; - const language = blockLanguage(element); - - if (shouldNotHighlight(language)) return; - - // support for v10 API - fire("before:highlightElement", - { el: element, language: language }); - - node = element; - const text = node.textContent; - const result = language ? highlight(text, { language, ignoreIllegals: true }) : highlightAuto(text); - - // support for v10 API - fire("after:highlightElement", { el: element, result, text }); - - element.innerHTML = result.value; - updateClassName(element, language, result.language); - element.result = { - language: result.language, - // TODO: remove with version 11.0 - re: result.relevance, - relavance: result.relevance - }; - if (result.second_best) { - element.second_best = { - language: result.second_best.language, - // TODO: remove with version 11.0 - re: result.second_best.relevance, - relavance: result.second_best.relevance - }; - } - } - - /** - * Updates highlight.js global options with the passed options - * - * @param {Partial} userOptions - */ - function configure(userOptions) { - if (userOptions.useBR) { - deprecated("10.3.0", "'useBR' will be removed entirely in v11.0"); - deprecated("10.3.0", "Please see https://github.com/highlightjs/highlight.js/issues/2559"); - } - options = inherit$1(options, userOptions); - } - - /** - * Highlights to all
     blocks on a page
    -   *
    -   * @type {Function & {called?: boolean}}
    -   */
    -  // TODO: remove v12, deprecated
    -  const initHighlighting = () => {
    -    if (initHighlighting.called) return;
    -    initHighlighting.called = true;
    -
    -    deprecated("10.6.0", "initHighlighting() is deprecated.  Use highlightAll() instead.");
    -
    -    const blocks = document.querySelectorAll('pre code');
    -    blocks.forEach(highlightElement);
    -  };
    -
    -  // Higlights all when DOMContentLoaded fires
    -  // TODO: remove v12, deprecated
    -  function initHighlightingOnLoad() {
    -    deprecated("10.6.0", "initHighlightingOnLoad() is deprecated.  Use highlightAll() instead.");
    -    wantsHighlight = true;
    -  }
    -
    -  let wantsHighlight = false;
    -
    -  /**
    -   * auto-highlights all pre>code elements on the page
    -   */
    -  function highlightAll() {
    -    // if we are called too early in the loading process
    -    if (document.readyState === "loading") {
    -      wantsHighlight = true;
    -      return;
    -    }
    -
    -    const blocks = document.querySelectorAll('pre code');
    -    blocks.forEach(highlightElement);
    -  }
    -
    -  function boot() {
    -    // if a highlight was requested before DOM was loaded, do now
    -    if (wantsHighlight) highlightAll();
    -  }
    -
    -  // make sure we are in the browser environment
    -  if (typeof window !== 'undefined' && window.addEventListener) {
    -    window.addEventListener('DOMContentLoaded', boot, false);
    -  }
    -
    -  /**
    -   * Register a language grammar module
    -   *
    -   * @param {string} languageName
    -   * @param {LanguageFn} languageDefinition
    -   */
    -  function registerLanguage(languageName, languageDefinition) {
    -    let lang = null;
    -    try {
    -      lang = languageDefinition(hljs);
    -    } catch (error$1) {
    -      error("Language definition for '{}' could not be registered.".replace("{}", languageName));
    -      // hard or soft error
    -      if (!SAFE_MODE) { throw error$1; } else { error(error$1); }
    -      // languages that have serious errors are replaced with essentially a
    -      // "plaintext" stand-in so that the code blocks will still get normal
    -      // css classes applied to them - and one bad language won't break the
    -      // entire highlighter
    -      lang = PLAINTEXT_LANGUAGE;
    -    }
    -    // give it a temporary name if it doesn't have one in the meta-data
    -    if (!lang.name) lang.name = languageName;
    -    languages[languageName] = lang;
    -    lang.rawDefinition = languageDefinition.bind(null, hljs);
    -
    -    if (lang.aliases) {
    -      registerAliases(lang.aliases, { languageName });
    -    }
    -  }
    -
    -  /**
    -   * Remove a language grammar module
    -   *
    -   * @param {string} languageName
    -   */
    -  function unregisterLanguage(languageName) {
    -    delete languages[languageName];
    -    for (const alias of Object.keys(aliases)) {
    -      if (aliases[alias] === languageName) {
    -        delete aliases[alias];
    -      }
    -    }
    -  }
    -
    -  /**
    -   * @returns {string[]} List of language internal names
    -   */
    -  function listLanguages() {
    -    return Object.keys(languages);
    -  }
    -
    -  /**
    -    intended usage: When one language truly requires another
    -
    -    Unlike `getLanguage`, this will throw when the requested language
    -    is not available.
    -
    -    @param {string} name - name of the language to fetch/require
    -    @returns {Language | never}
    -  */
    -  function requireLanguage(name) {
    -    deprecated("10.4.0", "requireLanguage will be removed entirely in v11.");
    -    deprecated("10.4.0", "Please see https://github.com/highlightjs/highlight.js/pull/2844");
    -
    -    const lang = getLanguage(name);
    -    if (lang) { return lang; }
    -
    -    const err = new Error('The \'{}\' language is required, but not loaded.'.replace('{}', name));
    -    throw err;
    -  }
    -
    -  /**
    -   * @param {string} name - name of the language to retrieve
    -   * @returns {Language | undefined}
    -   */
    -  function getLanguage(name) {
    -    name = (name || '').toLowerCase();
    -    return languages[name] || languages[aliases[name]];
    -  }
    -
    -  /**
    -   *
    -   * @param {string|string[]} aliasList - single alias or list of aliases
    -   * @param {{languageName: string}} opts
    -   */
    -  function registerAliases(aliasList, { languageName }) {
    -    if (typeof aliasList === 'string') {
    -      aliasList = [aliasList];
    -    }
    -    aliasList.forEach(alias => { aliases[alias.toLowerCase()] = languageName; });
    -  }
    -
    -  /**
    -   * Determines if a given language has auto-detection enabled
    -   * @param {string} name - name of the language
    -   */
    -  function autoDetection(name) {
    -    const lang = getLanguage(name);
    -    return lang && !lang.disableAutodetect;
    -  }
    -
    -  /**
    -   * Upgrades the old highlightBlock plugins to the new
    -   * highlightElement API
    -   * @param {HLJSPlugin} plugin
    -   */
    -  function upgradePluginAPI(plugin) {
    -    // TODO: remove with v12
    -    if (plugin["before:highlightBlock"] && !plugin["before:highlightElement"]) {
    -      plugin["before:highlightElement"] = (data) => {
    -        plugin["before:highlightBlock"](
    -          Object.assign({ block: data.el }, data)
    -        );
    -      };
    -    }
    -    if (plugin["after:highlightBlock"] && !plugin["after:highlightElement"]) {
    -      plugin["after:highlightElement"] = (data) => {
    -        plugin["after:highlightBlock"](
    -          Object.assign({ block: data.el }, data)
    -        );
    -      };
    -    }
    -  }
    -
    -  /**
    -   * @param {HLJSPlugin} plugin
    -   */
    -  function addPlugin(plugin) {
    -    upgradePluginAPI(plugin);
    -    plugins.push(plugin);
    -  }
    -
    -  /**
    -   *
    -   * @param {PluginEvent} event
    -   * @param {any} args
    -   */
    -  function fire(event, args) {
    -    const cb = event;
    -    plugins.forEach(function(plugin) {
    -      if (plugin[cb]) {
    -        plugin[cb](args);
    -      }
    -    });
    -  }
    -
    -  /**
    -  Note: fixMarkup is deprecated and will be removed entirely in v11
    -
    -  @param {string} arg
    -  @returns {string}
    -  */
    -  function deprecateFixMarkup(arg) {
    -    deprecated("10.2.0", "fixMarkup will be removed entirely in v11.0");
    -    deprecated("10.2.0", "Please see https://github.com/highlightjs/highlight.js/issues/2534");
    -
    -    return fixMarkup(arg);
    -  }
    -
    -  /**
    -   *
    -   * @param {HighlightedHTMLElement} el
    -   */
    -  function deprecateHighlightBlock(el) {
    -    deprecated("10.7.0", "highlightBlock will be removed entirely in v12.0");
    -    deprecated("10.7.0", "Please use highlightElement now.");
    -
    -    return highlightElement(el);
    -  }
    -
    -  /* Interface definition */
    -  Object.assign(hljs, {
    -    highlight,
    -    highlightAuto,
    -    highlightAll,
    -    fixMarkup: deprecateFixMarkup,
    -    highlightElement,
    -    // TODO: Remove with v12 API
    -    highlightBlock: deprecateHighlightBlock,
    -    configure,
    -    initHighlighting,
    -    initHighlightingOnLoad,
    -    registerLanguage,
    -    unregisterLanguage,
    -    listLanguages,
    -    getLanguage,
    -    registerAliases,
    -    requireLanguage,
    -    autoDetection,
    -    inherit: inherit$1,
    -    addPlugin,
    -    // plugins for frameworks
    -    vuePlugin: BuildVuePlugin(hljs).VuePlugin
    -  });
    -
    -  hljs.debugMode = function() { SAFE_MODE = false; };
    -  hljs.safeMode = function() { SAFE_MODE = true; };
    -  hljs.versionString = version;
    -
    -  for (const key in MODES) {
    -    // @ts-ignore
    -    if (typeof MODES[key] === "object") {
    -      // @ts-ignore
    -      deepFreezeEs6(MODES[key]);
    -    }
    -  }
    -
    -  // merge all the modes/regexs into our main object
    -  Object.assign(hljs, MODES);
    -
    -  // built-in plugins, likely to be moved out of core in the future
    -  hljs.addPlugin(brPlugin); // slated to be removed in v11
    -  hljs.addPlugin(mergeHTMLPlugin);
    -  hljs.addPlugin(tabReplacePlugin);
    -  return hljs;
    -};
    -
    -// export an "instance" of the highlighter
    -var highlight = HLJS({});
    -
    -module.exports = highlight;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/index.js b/claude-code-source/node_modules/highlight.js/lib/index.js
    deleted file mode 100644
    index 052d0732..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/index.js
    +++ /dev/null
    @@ -1,195 +0,0 @@
    -var hljs = require('./core');
    -
    -hljs.registerLanguage('1c', require('./languages/1c'));
    -hljs.registerLanguage('abnf', require('./languages/abnf'));
    -hljs.registerLanguage('accesslog', require('./languages/accesslog'));
    -hljs.registerLanguage('actionscript', require('./languages/actionscript'));
    -hljs.registerLanguage('ada', require('./languages/ada'));
    -hljs.registerLanguage('angelscript', require('./languages/angelscript'));
    -hljs.registerLanguage('apache', require('./languages/apache'));
    -hljs.registerLanguage('applescript', require('./languages/applescript'));
    -hljs.registerLanguage('arcade', require('./languages/arcade'));
    -hljs.registerLanguage('arduino', require('./languages/arduino'));
    -hljs.registerLanguage('armasm', require('./languages/armasm'));
    -hljs.registerLanguage('xml', require('./languages/xml'));
    -hljs.registerLanguage('asciidoc', require('./languages/asciidoc'));
    -hljs.registerLanguage('aspectj', require('./languages/aspectj'));
    -hljs.registerLanguage('autohotkey', require('./languages/autohotkey'));
    -hljs.registerLanguage('autoit', require('./languages/autoit'));
    -hljs.registerLanguage('avrasm', require('./languages/avrasm'));
    -hljs.registerLanguage('awk', require('./languages/awk'));
    -hljs.registerLanguage('axapta', require('./languages/axapta'));
    -hljs.registerLanguage('bash', require('./languages/bash'));
    -hljs.registerLanguage('basic', require('./languages/basic'));
    -hljs.registerLanguage('bnf', require('./languages/bnf'));
    -hljs.registerLanguage('brainfuck', require('./languages/brainfuck'));
    -hljs.registerLanguage('c-like', require('./languages/c-like'));
    -hljs.registerLanguage('c', require('./languages/c'));
    -hljs.registerLanguage('cal', require('./languages/cal'));
    -hljs.registerLanguage('capnproto', require('./languages/capnproto'));
    -hljs.registerLanguage('ceylon', require('./languages/ceylon'));
    -hljs.registerLanguage('clean', require('./languages/clean'));
    -hljs.registerLanguage('clojure', require('./languages/clojure'));
    -hljs.registerLanguage('clojure-repl', require('./languages/clojure-repl'));
    -hljs.registerLanguage('cmake', require('./languages/cmake'));
    -hljs.registerLanguage('coffeescript', require('./languages/coffeescript'));
    -hljs.registerLanguage('coq', require('./languages/coq'));
    -hljs.registerLanguage('cos', require('./languages/cos'));
    -hljs.registerLanguage('cpp', require('./languages/cpp'));
    -hljs.registerLanguage('crmsh', require('./languages/crmsh'));
    -hljs.registerLanguage('crystal', require('./languages/crystal'));
    -hljs.registerLanguage('csharp', require('./languages/csharp'));
    -hljs.registerLanguage('csp', require('./languages/csp'));
    -hljs.registerLanguage('css', require('./languages/css'));
    -hljs.registerLanguage('d', require('./languages/d'));
    -hljs.registerLanguage('markdown', require('./languages/markdown'));
    -hljs.registerLanguage('dart', require('./languages/dart'));
    -hljs.registerLanguage('delphi', require('./languages/delphi'));
    -hljs.registerLanguage('diff', require('./languages/diff'));
    -hljs.registerLanguage('django', require('./languages/django'));
    -hljs.registerLanguage('dns', require('./languages/dns'));
    -hljs.registerLanguage('dockerfile', require('./languages/dockerfile'));
    -hljs.registerLanguage('dos', require('./languages/dos'));
    -hljs.registerLanguage('dsconfig', require('./languages/dsconfig'));
    -hljs.registerLanguage('dts', require('./languages/dts'));
    -hljs.registerLanguage('dust', require('./languages/dust'));
    -hljs.registerLanguage('ebnf', require('./languages/ebnf'));
    -hljs.registerLanguage('elixir', require('./languages/elixir'));
    -hljs.registerLanguage('elm', require('./languages/elm'));
    -hljs.registerLanguage('ruby', require('./languages/ruby'));
    -hljs.registerLanguage('erb', require('./languages/erb'));
    -hljs.registerLanguage('erlang-repl', require('./languages/erlang-repl'));
    -hljs.registerLanguage('erlang', require('./languages/erlang'));
    -hljs.registerLanguage('excel', require('./languages/excel'));
    -hljs.registerLanguage('fix', require('./languages/fix'));
    -hljs.registerLanguage('flix', require('./languages/flix'));
    -hljs.registerLanguage('fortran', require('./languages/fortran'));
    -hljs.registerLanguage('fsharp', require('./languages/fsharp'));
    -hljs.registerLanguage('gams', require('./languages/gams'));
    -hljs.registerLanguage('gauss', require('./languages/gauss'));
    -hljs.registerLanguage('gcode', require('./languages/gcode'));
    -hljs.registerLanguage('gherkin', require('./languages/gherkin'));
    -hljs.registerLanguage('glsl', require('./languages/glsl'));
    -hljs.registerLanguage('gml', require('./languages/gml'));
    -hljs.registerLanguage('go', require('./languages/go'));
    -hljs.registerLanguage('golo', require('./languages/golo'));
    -hljs.registerLanguage('gradle', require('./languages/gradle'));
    -hljs.registerLanguage('groovy', require('./languages/groovy'));
    -hljs.registerLanguage('haml', require('./languages/haml'));
    -hljs.registerLanguage('handlebars', require('./languages/handlebars'));
    -hljs.registerLanguage('haskell', require('./languages/haskell'));
    -hljs.registerLanguage('haxe', require('./languages/haxe'));
    -hljs.registerLanguage('hsp', require('./languages/hsp'));
    -hljs.registerLanguage('htmlbars', require('./languages/htmlbars'));
    -hljs.registerLanguage('http', require('./languages/http'));
    -hljs.registerLanguage('hy', require('./languages/hy'));
    -hljs.registerLanguage('inform7', require('./languages/inform7'));
    -hljs.registerLanguage('ini', require('./languages/ini'));
    -hljs.registerLanguage('irpf90', require('./languages/irpf90'));
    -hljs.registerLanguage('isbl', require('./languages/isbl'));
    -hljs.registerLanguage('java', require('./languages/java'));
    -hljs.registerLanguage('javascript', require('./languages/javascript'));
    -hljs.registerLanguage('jboss-cli', require('./languages/jboss-cli'));
    -hljs.registerLanguage('json', require('./languages/json'));
    -hljs.registerLanguage('julia', require('./languages/julia'));
    -hljs.registerLanguage('julia-repl', require('./languages/julia-repl'));
    -hljs.registerLanguage('kotlin', require('./languages/kotlin'));
    -hljs.registerLanguage('lasso', require('./languages/lasso'));
    -hljs.registerLanguage('latex', require('./languages/latex'));
    -hljs.registerLanguage('ldif', require('./languages/ldif'));
    -hljs.registerLanguage('leaf', require('./languages/leaf'));
    -hljs.registerLanguage('less', require('./languages/less'));
    -hljs.registerLanguage('lisp', require('./languages/lisp'));
    -hljs.registerLanguage('livecodeserver', require('./languages/livecodeserver'));
    -hljs.registerLanguage('livescript', require('./languages/livescript'));
    -hljs.registerLanguage('llvm', require('./languages/llvm'));
    -hljs.registerLanguage('lsl', require('./languages/lsl'));
    -hljs.registerLanguage('lua', require('./languages/lua'));
    -hljs.registerLanguage('makefile', require('./languages/makefile'));
    -hljs.registerLanguage('mathematica', require('./languages/mathematica'));
    -hljs.registerLanguage('matlab', require('./languages/matlab'));
    -hljs.registerLanguage('maxima', require('./languages/maxima'));
    -hljs.registerLanguage('mel', require('./languages/mel'));
    -hljs.registerLanguage('mercury', require('./languages/mercury'));
    -hljs.registerLanguage('mipsasm', require('./languages/mipsasm'));
    -hljs.registerLanguage('mizar', require('./languages/mizar'));
    -hljs.registerLanguage('perl', require('./languages/perl'));
    -hljs.registerLanguage('mojolicious', require('./languages/mojolicious'));
    -hljs.registerLanguage('monkey', require('./languages/monkey'));
    -hljs.registerLanguage('moonscript', require('./languages/moonscript'));
    -hljs.registerLanguage('n1ql', require('./languages/n1ql'));
    -hljs.registerLanguage('nginx', require('./languages/nginx'));
    -hljs.registerLanguage('nim', require('./languages/nim'));
    -hljs.registerLanguage('nix', require('./languages/nix'));
    -hljs.registerLanguage('node-repl', require('./languages/node-repl'));
    -hljs.registerLanguage('nsis', require('./languages/nsis'));
    -hljs.registerLanguage('objectivec', require('./languages/objectivec'));
    -hljs.registerLanguage('ocaml', require('./languages/ocaml'));
    -hljs.registerLanguage('openscad', require('./languages/openscad'));
    -hljs.registerLanguage('oxygene', require('./languages/oxygene'));
    -hljs.registerLanguage('parser3', require('./languages/parser3'));
    -hljs.registerLanguage('pf', require('./languages/pf'));
    -hljs.registerLanguage('pgsql', require('./languages/pgsql'));
    -hljs.registerLanguage('php', require('./languages/php'));
    -hljs.registerLanguage('php-template', require('./languages/php-template'));
    -hljs.registerLanguage('plaintext', require('./languages/plaintext'));
    -hljs.registerLanguage('pony', require('./languages/pony'));
    -hljs.registerLanguage('powershell', require('./languages/powershell'));
    -hljs.registerLanguage('processing', require('./languages/processing'));
    -hljs.registerLanguage('profile', require('./languages/profile'));
    -hljs.registerLanguage('prolog', require('./languages/prolog'));
    -hljs.registerLanguage('properties', require('./languages/properties'));
    -hljs.registerLanguage('protobuf', require('./languages/protobuf'));
    -hljs.registerLanguage('puppet', require('./languages/puppet'));
    -hljs.registerLanguage('purebasic', require('./languages/purebasic'));
    -hljs.registerLanguage('python', require('./languages/python'));
    -hljs.registerLanguage('python-repl', require('./languages/python-repl'));
    -hljs.registerLanguage('q', require('./languages/q'));
    -hljs.registerLanguage('qml', require('./languages/qml'));
    -hljs.registerLanguage('r', require('./languages/r'));
    -hljs.registerLanguage('reasonml', require('./languages/reasonml'));
    -hljs.registerLanguage('rib', require('./languages/rib'));
    -hljs.registerLanguage('roboconf', require('./languages/roboconf'));
    -hljs.registerLanguage('routeros', require('./languages/routeros'));
    -hljs.registerLanguage('rsl', require('./languages/rsl'));
    -hljs.registerLanguage('ruleslanguage', require('./languages/ruleslanguage'));
    -hljs.registerLanguage('rust', require('./languages/rust'));
    -hljs.registerLanguage('sas', require('./languages/sas'));
    -hljs.registerLanguage('scala', require('./languages/scala'));
    -hljs.registerLanguage('scheme', require('./languages/scheme'));
    -hljs.registerLanguage('scilab', require('./languages/scilab'));
    -hljs.registerLanguage('scss', require('./languages/scss'));
    -hljs.registerLanguage('shell', require('./languages/shell'));
    -hljs.registerLanguage('smali', require('./languages/smali'));
    -hljs.registerLanguage('smalltalk', require('./languages/smalltalk'));
    -hljs.registerLanguage('sml', require('./languages/sml'));
    -hljs.registerLanguage('sqf', require('./languages/sqf'));
    -hljs.registerLanguage('sql_more', require('./languages/sql_more'));
    -hljs.registerLanguage('sql', require('./languages/sql'));
    -hljs.registerLanguage('stan', require('./languages/stan'));
    -hljs.registerLanguage('stata', require('./languages/stata'));
    -hljs.registerLanguage('step21', require('./languages/step21'));
    -hljs.registerLanguage('stylus', require('./languages/stylus'));
    -hljs.registerLanguage('subunit', require('./languages/subunit'));
    -hljs.registerLanguage('swift', require('./languages/swift'));
    -hljs.registerLanguage('taggerscript', require('./languages/taggerscript'));
    -hljs.registerLanguage('yaml', require('./languages/yaml'));
    -hljs.registerLanguage('tap', require('./languages/tap'));
    -hljs.registerLanguage('tcl', require('./languages/tcl'));
    -hljs.registerLanguage('thrift', require('./languages/thrift'));
    -hljs.registerLanguage('tp', require('./languages/tp'));
    -hljs.registerLanguage('twig', require('./languages/twig'));
    -hljs.registerLanguage('typescript', require('./languages/typescript'));
    -hljs.registerLanguage('vala', require('./languages/vala'));
    -hljs.registerLanguage('vbnet', require('./languages/vbnet'));
    -hljs.registerLanguage('vbscript', require('./languages/vbscript'));
    -hljs.registerLanguage('vbscript-html', require('./languages/vbscript-html'));
    -hljs.registerLanguage('verilog', require('./languages/verilog'));
    -hljs.registerLanguage('vhdl', require('./languages/vhdl'));
    -hljs.registerLanguage('vim', require('./languages/vim'));
    -hljs.registerLanguage('x86asm', require('./languages/x86asm'));
    -hljs.registerLanguage('xl', require('./languages/xl'));
    -hljs.registerLanguage('xquery', require('./languages/xquery'));
    -hljs.registerLanguage('zephir', require('./languages/zephir'));
    -
    -module.exports = hljs;
    \ No newline at end of file
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/1c.js b/claude-code-source/node_modules/highlight.js/lib/languages/1c.js
    deleted file mode 100644
    index 4a2e3526..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/1c.js
    +++ /dev/null
    @@ -1,521 +0,0 @@
    -/*
    -Language: 1C:Enterprise
    -Author: Stanislav Belov 
    -Description: built-in language 1C:Enterprise (v7, v8)
    -Category: enterprise
    -*/
    -
    -function _1c(hljs) {
    -
    -  // общий паттерн для определения идентификаторов
    -  var UNDERSCORE_IDENT_RE = '[A-Za-zА-Яа-яёЁ_][A-Za-zА-Яа-яёЁ_0-9]+';
    -
    -  // v7 уникальные ключевые слова, отсутствующие в v8 ==> keyword
    -  var v7_keywords =
    -  'далее ';
    -
    -  // v8 ключевые слова ==> keyword
    -  var v8_keywords =
    -  'возврат вызватьисключение выполнить для если и из или иначе иначеесли исключение каждого конецесли ' +
    -  'конецпопытки конеццикла не новый перейти перем по пока попытка прервать продолжить тогда цикл экспорт ';
    -
    -  // keyword : ключевые слова
    -  var KEYWORD = v7_keywords + v8_keywords;
    -
    -  // v7 уникальные директивы, отсутствующие в v8 ==> meta-keyword
    -  var v7_meta_keywords =
    -  'загрузитьизфайла ';
    -
    -  // v8 ключевые слова в инструкциях препроцессора, директивах компиляции, аннотациях ==> meta-keyword
    -  var v8_meta_keywords =
    -  'вебклиент вместо внешнеесоединение клиент конецобласти мобильноеприложениеклиент мобильноеприложениесервер ' +
    -  'наклиенте наклиентенасервере наклиентенасерверебезконтекста насервере насерверебезконтекста область перед ' +
    -  'после сервер толстыйклиентобычноеприложение толстыйклиентуправляемоеприложение тонкийклиент ';
    -
    -  // meta-keyword : ключевые слова в инструкциях препроцессора, директивах компиляции, аннотациях
    -  var METAKEYWORD = v7_meta_keywords + v8_meta_keywords;
    -
    -  // v7 системные константы ==> built_in
    -  var v7_system_constants =
    -  'разделительстраниц разделительстрок символтабуляции ';
    -
    -  // v7 уникальные методы глобального контекста, отсутствующие в v8 ==> built_in
    -  var v7_global_context_methods =
    -  'ansitooem oemtoansi ввестивидсубконто ввестиперечисление ввестипериод ввестиплансчетов выбранныйплансчетов ' +
    -  'датагод датамесяц датачисло заголовоксистемы значениевстроку значениеизстроки каталогиб каталогпользователя ' +
    -  'кодсимв конгода конецпериодаби конецрассчитанногопериодаби конецстандартногоинтервала конквартала конмесяца ' +
    -  'коннедели лог лог10 максимальноеколичествосубконто названиеинтерфейса названиенабораправ назначитьвид ' +
    -  'назначитьсчет найтиссылки началопериодаби началостандартногоинтервала начгода начквартала начмесяца ' +
    -  'начнедели номерднягода номерднянедели номернеделигода обработкаожидания основнойжурналрасчетов ' +
    -  'основнойплансчетов основнойязык очиститьокносообщений периодстр получитьвремята получитьдатута ' +
    -  'получитьдокументта получитьзначенияотбора получитьпозициюта получитьпустоезначение получитьта ' +
    -  'префиксавтонумерации пропись пустоезначение разм разобратьпозициюдокумента рассчитатьрегистрына ' +
    -  'рассчитатьрегистрыпо симв создатьобъект статусвозврата стрколичествострок сформироватьпозициюдокумента ' +
    -  'счетпокоду текущеевремя типзначения типзначениястр установитьтана установитьтапо фиксшаблон шаблон ';
    -
    -  // v8 методы глобального контекста ==> built_in
    -  var v8_global_context_methods =
    -  'acos asin atan base64значение base64строка cos exp log log10 pow sin sqrt tan xmlзначение xmlстрока ' +
    -  'xmlтип xmlтипзнч активноеокно безопасныйрежим безопасныйрежимразделенияданных булево ввестидату ввестизначение ' +
    -  'ввестистроку ввестичисло возможностьчтенияxml вопрос восстановитьзначение врег выгрузитьжурналрегистрации ' +
    -  'выполнитьобработкуоповещения выполнитьпроверкуправдоступа вычислить год данныеформывзначение дата день деньгода ' +
    -  'деньнедели добавитьмесяц заблокироватьданныедляредактирования заблокироватьработупользователя завершитьработусистемы ' +
    -  'загрузитьвнешнююкомпоненту закрытьсправку записатьjson записатьxml записатьдатуjson записьжурналарегистрации ' +
    -  'заполнитьзначениясвойств запроситьразрешениепользователя запуститьприложение запуститьсистему зафиксироватьтранзакцию ' +
    -  'значениевданныеформы значениевстрокувнутр значениевфайл значениезаполнено значениеизстрокивнутр значениеизфайла ' +
    -  'изxmlтипа импортмоделиxdto имякомпьютера имяпользователя инициализироватьпредопределенныеданные информацияобошибке ' +
    -  'каталогбиблиотекимобильногоустройства каталогвременныхфайлов каталогдокументов каталогпрограммы кодироватьстроку ' +
    -  'кодлокализацииинформационнойбазы кодсимвола командасистемы конецгода конецдня конецквартала конецмесяца конецминуты ' +
    -  'конецнедели конецчаса конфигурациябазыданныхизмененадинамически конфигурацияизменена копироватьданныеформы ' +
    -  'копироватьфайл краткоепредставлениеошибки лев макс местноевремя месяц мин минута монопольныйрежим найти ' +
    -  'найтинедопустимыесимволыxml найтиокнопонавигационнойссылке найтипомеченныенаудаление найтипоссылкам найтифайлы ' +
    -  'началогода началодня началоквартала началомесяца началоминуты началонедели началочаса начатьзапросразрешенияпользователя ' +
    -  'начатьзапускприложения начатькопированиефайла начатьперемещениефайла начатьподключениевнешнейкомпоненты ' +
    -  'начатьподключениерасширенияработыскриптографией начатьподключениерасширенияработысфайлами начатьпоискфайлов ' +
    -  'начатьполучениекаталогавременныхфайлов начатьполучениекаталогадокументов начатьполучениерабочегокаталогаданныхпользователя ' +
    -  'начатьполучениефайлов начатьпомещениефайла начатьпомещениефайлов начатьсозданиедвоичныхданныхизфайла начатьсозданиекаталога ' +
    -  'начатьтранзакцию начатьудалениефайлов начатьустановкувнешнейкомпоненты начатьустановкурасширенияработыскриптографией ' +
    -  'начатьустановкурасширенияработысфайлами неделягода необходимостьзавершениясоединения номерсеансаинформационнойбазы ' +
    -  'номерсоединенияинформационнойбазы нрег нстр обновитьинтерфейс обновитьнумерациюобъектов обновитьповторноиспользуемыезначения ' +
    -  'обработкапрерыванияпользователя объединитьфайлы окр описаниеошибки оповестить оповеститьобизменении ' +
    -  'отключитьобработчикзапросанастроекклиенталицензирования отключитьобработчикожидания отключитьобработчикоповещения ' +
    -  'открытьзначение открытьиндекссправки открытьсодержаниесправки открытьсправку открытьформу открытьформумодально ' +
    -  'отменитьтранзакцию очиститьжурналрегистрации очиститьнастройкипользователя очиститьсообщения параметрыдоступа ' +
    -  'перейтипонавигационнойссылке переместитьфайл подключитьвнешнююкомпоненту ' +
    -  'подключитьобработчикзапросанастроекклиенталицензирования подключитьобработчикожидания подключитьобработчикоповещения ' +
    -  'подключитьрасширениеработыскриптографией подключитьрасширениеработысфайлами подробноепредставлениеошибки ' +
    -  'показатьвводдаты показатьвводзначения показатьвводстроки показатьвводчисла показатьвопрос показатьзначение ' +
    -  'показатьинформациюобошибке показатьнакарте показатьоповещениепользователя показатьпредупреждение полноеимяпользователя ' +
    -  'получитьcomобъект получитьxmlтип получитьадреспоместоположению получитьблокировкусеансов получитьвремязавершенияспящегосеанса ' +
    -  'получитьвремязасыпанияпассивногосеанса получитьвремяожиданияблокировкиданных получитьданныевыбора ' +
    -  'получитьдополнительныйпараметрклиенталицензирования получитьдопустимыекодылокализации получитьдопустимыечасовыепояса ' +
    -  'получитьзаголовокклиентскогоприложения получитьзаголовоксистемы получитьзначенияотборажурналарегистрации ' +
    -  'получитьидентификаторконфигурации получитьизвременногохранилища получитьимявременногофайла ' +
    -  'получитьимяклиенталицензирования получитьинформациюэкрановклиента получитьиспользованиежурналарегистрации ' +
    -  'получитьиспользованиесобытияжурналарегистрации получитькраткийзаголовокприложения получитьмакетоформления ' +
    -  'получитьмаскувсефайлы получитьмаскувсефайлыклиента получитьмаскувсефайлысервера получитьместоположениепоадресу ' +
    -  'получитьминимальнуюдлинупаролейпользователей получитьнавигационнуюссылку получитьнавигационнуюссылкуинформационнойбазы ' +
    -  'получитьобновлениеконфигурациибазыданных получитьобновлениепредопределенныхданныхинформационнойбазы получитьобщиймакет ' +
    -  'получитьобщуюформу получитьокна получитьоперативнуюотметкувремени получитьотключениебезопасногорежима ' +
    -  'получитьпараметрыфункциональныхопцийинтерфейса получитьполноеимяпредопределенногозначения ' +
    -  'получитьпредставлениянавигационныхссылок получитьпроверкусложностипаролейпользователей получитьразделительпути ' +
    -  'получитьразделительпутиклиента получитьразделительпутисервера получитьсеансыинформационнойбазы ' +
    -  'получитьскоростьклиентскогосоединения получитьсоединенияинформационнойбазы получитьсообщенияпользователю ' +
    -  'получитьсоответствиеобъектаиформы получитьсоставстандартногоинтерфейсаodata получитьструктурухранениябазыданных ' +
    -  'получитьтекущийсеансинформационнойбазы получитьфайл получитьфайлы получитьформу получитьфункциональнуюопцию ' +
    -  'получитьфункциональнуюопциюинтерфейса получитьчасовойпоясинформационнойбазы пользователиос поместитьвовременноехранилище ' +
    -  'поместитьфайл поместитьфайлы прав праводоступа предопределенноезначение представлениекодалокализации представлениепериода ' +
    -  'представлениеправа представлениеприложения представлениесобытияжурналарегистрации представлениечасовогопояса предупреждение ' +
    -  'прекратитьработусистемы привилегированныйрежим продолжитьвызов прочитатьjson прочитатьxml прочитатьдатуjson пустаястрока ' +
    -  'рабочийкаталогданныхпользователя разблокироватьданныедляредактирования разделитьфайл разорватьсоединениесвнешнимисточникомданных ' +
    -  'раскодироватьстроку рольдоступна секунда сигнал символ скопироватьжурналрегистрации смещениелетнеговремени ' +
    -  'смещениестандартноговремени соединитьбуферыдвоичныхданных создатькаталог создатьфабрикуxdto сокрл сокрлп сокрп сообщить ' +
    -  'состояние сохранитьзначение сохранитьнастройкипользователя сред стрдлина стрзаканчиваетсяна стрзаменить стрнайти стрначинаетсяс ' +
    -  'строка строкасоединенияинформационнойбазы стрполучитьстроку стрразделить стрсоединить стрсравнить стрчисловхождений '+
    -  'стрчислострок стршаблон текущаядата текущаядатасеанса текущаяуниверсальнаядата текущаяуниверсальнаядатавмиллисекундах ' +
    -  'текущийвариантинтерфейсаклиентскогоприложения текущийвариантосновногошрифтаклиентскогоприложения текущийкодлокализации ' +
    -  'текущийрежимзапуска текущийязык текущийязыксистемы тип типзнч транзакцияактивна трег удалитьданныеинформационнойбазы ' +
    -  'удалитьизвременногохранилища удалитьобъекты удалитьфайлы универсальноевремя установитьбезопасныйрежим ' +
    -  'установитьбезопасныйрежимразделенияданных установитьблокировкусеансов установитьвнешнююкомпоненту ' +
    -  'установитьвремязавершенияспящегосеанса установитьвремязасыпанияпассивногосеанса установитьвремяожиданияблокировкиданных ' +
    -  'установитьзаголовокклиентскогоприложения установитьзаголовоксистемы установитьиспользованиежурналарегистрации ' +
    -  'установитьиспользованиесобытияжурналарегистрации установитькраткийзаголовокприложения ' +
    -  'установитьминимальнуюдлинупаролейпользователей установитьмонопольныйрежим установитьнастройкиклиенталицензирования ' +
    -  'установитьобновлениепредопределенныхданныхинформационнойбазы установитьотключениебезопасногорежима ' +
    -  'установитьпараметрыфункциональныхопцийинтерфейса установитьпривилегированныйрежим ' +
    -  'установитьпроверкусложностипаролейпользователей установитьрасширениеработыскриптографией ' +
    -  'установитьрасширениеработысфайлами установитьсоединениесвнешнимисточникомданных установитьсоответствиеобъектаиформы ' +
    -  'установитьсоставстандартногоинтерфейсаodata установитьчасовойпоясинформационнойбазы установитьчасовойпояссеанса ' +
    -  'формат цел час часовойпояс часовойпояссеанса число числопрописью этоадресвременногохранилища ';
    -
    -  // v8 свойства глобального контекста ==> built_in
    -  var v8_global_context_property =
    -  'wsссылки библиотекакартинок библиотекамакетовоформлениякомпоновкиданных библиотекастилей бизнеспроцессы ' +
    -  'внешниеисточникиданных внешниеобработки внешниеотчеты встроенныепокупки главныйинтерфейс главныйстиль ' +
    -  'документы доставляемыеуведомления журналыдокументов задачи информацияобинтернетсоединении использованиерабочейдаты ' +
    -  'историяработыпользователя константы критерииотбора метаданные обработки отображениерекламы отправкадоставляемыхуведомлений ' +
    -  'отчеты панельзадачос параметрзапуска параметрысеанса перечисления планывидоврасчета планывидовхарактеристик ' +
    -  'планыобмена планысчетов полнотекстовыйпоиск пользователиинформационнойбазы последовательности проверкавстроенныхпокупок ' +
    -  'рабочаядата расширенияконфигурации регистрыбухгалтерии регистрынакопления регистрырасчета регистрысведений ' +
    -  'регламентныезадания сериализаторxdto справочники средствагеопозиционирования средствакриптографии средствамультимедиа ' +
    -  'средстваотображениярекламы средствапочты средствателефонии фабрикаxdto файловыепотоки фоновыезадания хранилищанастроек ' +
    -  'хранилищевариантовотчетов хранилищенастроекданныхформ хранилищеобщихнастроек хранилищепользовательскихнастроекдинамическихсписков ' +
    -  'хранилищепользовательскихнастроекотчетов хранилищесистемныхнастроек ';
    -
    -  // built_in : встроенные или библиотечные объекты (константы, классы, функции)
    -  var BUILTIN =
    -  v7_system_constants +
    -  v7_global_context_methods + v8_global_context_methods +
    -  v8_global_context_property;
    -
    -  // v8 системные наборы значений ==> class
    -  var v8_system_sets_of_values =
    -  'webцвета windowsцвета windowsшрифты библиотекакартинок рамкистиля символы цветастиля шрифтыстиля ';
    -
    -  // v8 системные перечисления - интерфейсные ==> class
    -  var v8_system_enums_interface =
    -  'автоматическоесохранениеданныхформывнастройках автонумерациявформе автораздвижениесерий ' +
    -  'анимациядиаграммы вариантвыравниванияэлементовизаголовков вариантуправлениявысотойтаблицы ' +
    -  'вертикальнаяпрокруткаформы вертикальноеположение вертикальноеположениеэлемента видгруппыформы ' +
    -  'виддекорацииформы виддополненияэлементаформы видизмененияданных видкнопкиформы видпереключателя ' +
    -  'видподписейкдиаграмме видполяформы видфлажка влияниеразмеранапузырекдиаграммы горизонтальноеположение ' +
    -  'горизонтальноеположениеэлемента группировкаколонок группировкаподчиненныхэлементовформы ' +
    -  'группыиэлементы действиеперетаскивания дополнительныйрежимотображения допустимыедействияперетаскивания ' +
    -  'интервалмеждуэлементамиформы использованиевывода использованиеполосыпрокрутки ' +
    -  'используемоезначениеточкибиржевойдиаграммы историявыборапривводе источникзначенийоситочекдиаграммы ' +
    -  'источникзначенияразмерапузырькадиаграммы категориягруппыкоманд максимумсерий начальноеотображениедерева ' +
    -  'начальноеотображениесписка обновлениетекстаредактирования ориентациядендрограммы ориентациядиаграммы ' +
    -  'ориентацияметокдиаграммы ориентацияметоксводнойдиаграммы ориентацияэлементаформы отображениевдиаграмме ' +
    -  'отображениевлегендедиаграммы отображениегруппыкнопок отображениезаголовкашкалыдиаграммы ' +
    -  'отображениезначенийсводнойдиаграммы отображениезначенияизмерительнойдиаграммы ' +
    -  'отображениеинтерваладиаграммыганта отображениекнопки отображениекнопкивыбора отображениеобсужденийформы ' +
    -  'отображениеобычнойгруппы отображениеотрицательныхзначенийпузырьковойдиаграммы отображениепанелипоиска ' +
    -  'отображениеподсказки отображениепредупрежденияприредактировании отображениеразметкиполосырегулирования ' +
    -  'отображениестраницформы отображениетаблицы отображениетекстазначениядиаграммыганта ' +
    -  'отображениеуправленияобычнойгруппы отображениефигурыкнопки палитрацветовдиаграммы поведениеобычнойгруппы ' +
    -  'поддержкамасштабадендрограммы поддержкамасштабадиаграммыганта поддержкамасштабасводнойдиаграммы ' +
    -  'поисквтаблицепривводе положениезаголовкаэлементаформы положениекартинкикнопкиформы ' +
    -  'положениекартинкиэлементаграфическойсхемы положениекоманднойпанелиформы положениекоманднойпанелиэлементаформы ' +
    -  'положениеопорнойточкиотрисовки положениеподписейкдиаграмме положениеподписейшкалызначенийизмерительнойдиаграммы ' +
    -  'положениесостоянияпросмотра положениестрокипоиска положениетекстасоединительнойлинии положениеуправленияпоиском ' +
    -  'положениешкалывремени порядокотображенияточекгоризонтальнойгистограммы порядоксерийвлегендедиаграммы ' +
    -  'размеркартинки расположениезаголовкашкалыдиаграммы растягиваниеповертикалидиаграммыганта ' +
    -  'режимавтоотображениясостояния режимвводастроктаблицы режимвыборанезаполненного режимвыделениядаты ' +
    -  'режимвыделениястрокитаблицы режимвыделениятаблицы режимизмененияразмера режимизменениясвязанногозначения ' +
    -  'режимиспользованиядиалогапечати режимиспользованияпараметракоманды режиммасштабированияпросмотра ' +
    -  'режимосновногоокнаклиентскогоприложения режимоткрытияокнаформы режимотображениявыделения ' +
    -  'режимотображениягеографическойсхемы режимотображениязначенийсерии режимотрисовкисеткиграфическойсхемы ' +
    -  'режимполупрозрачностидиаграммы режимпробеловдиаграммы режимразмещениянастранице режимредактированияколонки ' +
    -  'режимсглаживаниядиаграммы режимсглаживанияиндикатора режимсписказадач сквозноевыравнивание ' +
    -  'сохранениеданныхформывнастройках способзаполнениятекстазаголовкашкалыдиаграммы ' +
    -  'способопределенияограничивающегозначениядиаграммы стандартнаягруппакоманд стандартноеоформление ' +
    -  'статусоповещенияпользователя стильстрелки типаппроксимациилиниитрендадиаграммы типдиаграммы ' +
    -  'типединицышкалывремени типимпортасерийслоягеографическойсхемы типлиниигеографическойсхемы типлиниидиаграммы ' +
    -  'типмаркерагеографическойсхемы типмаркерадиаграммы типобластиоформления ' +
    -  'типорганизацииисточникаданныхгеографическойсхемы типотображениясериислоягеографическойсхемы ' +
    -  'типотображенияточечногообъектагеографическойсхемы типотображенияшкалыэлементалегендыгеографическойсхемы ' +
    -  'типпоискаобъектовгеографическойсхемы типпроекциигеографическойсхемы типразмещенияизмерений ' +
    -  'типразмещенияреквизитовизмерений типрамкиэлементауправления типсводнойдиаграммы ' +
    -  'типсвязидиаграммыганта типсоединениязначенийпосериямдиаграммы типсоединенияточекдиаграммы ' +
    -  'типсоединительнойлинии типстороныэлементаграфическойсхемы типформыотчета типшкалырадарнойдиаграммы ' +
    -  'факторлиниитрендадиаграммы фигуракнопки фигурыграфическойсхемы фиксациявтаблице форматдняшкалывремени ' +
    -  'форматкартинки ширинаподчиненныхэлементовформы ';
    -
    -  // v8 системные перечисления - свойства прикладных объектов ==> class
    -  var v8_system_enums_objects_properties =
    -  'виддвижениябухгалтерии виддвижениянакопления видпериодарегистрарасчета видсчета видточкимаршрутабизнеспроцесса ' +
    -  'использованиеагрегатарегистранакопления использованиегруппиэлементов использованиережимапроведения ' +
    -  'использованиесреза периодичностьагрегатарегистранакопления режимавтовремя режимзаписидокумента режимпроведениядокумента ';
    -
    -  // v8 системные перечисления - планы обмена ==> class
    -  var v8_system_enums_exchange_plans =
    -  'авторегистрацияизменений допустимыйномерсообщения отправкаэлементаданных получениеэлементаданных ';
    -
    -  // v8 системные перечисления - табличный документ ==> class
    -  var v8_system_enums_tabular_document =
    -  'использованиерасшифровкитабличногодокумента ориентациястраницы положениеитоговколоноксводнойтаблицы ' +
    -  'положениеитоговстроксводнойтаблицы положениетекстаотносительнокартинки расположениезаголовкагруппировкитабличногодокумента ' +
    -  'способчтениязначенийтабличногодокумента типдвустороннейпечати типзаполненияобластитабличногодокумента ' +
    -  'типкурсоровтабличногодокумента типлиниирисункатабличногодокумента типлинииячейкитабличногодокумента ' +
    -  'типнаправленияпереходатабличногодокумента типотображениявыделениятабличногодокумента типотображениялинийсводнойтаблицы ' +
    -  'типразмещениятекстатабличногодокумента типрисункатабличногодокумента типсмещениятабличногодокумента ' +
    -  'типузоратабличногодокумента типфайлатабличногодокумента точностьпечати чередованиерасположениястраниц ';
    -
    -  // v8 системные перечисления - планировщик ==> class
    -  var v8_system_enums_sheduler =
    -  'отображениевремениэлементовпланировщика ';
    -
    -  // v8 системные перечисления - форматированный документ ==> class
    -  var v8_system_enums_formatted_document =
    -  'типфайлаформатированногодокумента ';
    -
    -  // v8 системные перечисления - запрос ==> class
    -  var v8_system_enums_query =
    -  'обходрезультатазапроса типзаписизапроса ';
    -
    -  // v8 системные перечисления - построитель отчета ==> class
    -  var v8_system_enums_report_builder =
    -  'видзаполнениярасшифровкипостроителяотчета типдобавленияпредставлений типизмеренияпостроителяотчета типразмещенияитогов ';
    -
    -  // v8 системные перечисления - работа с файлами ==> class
    -  var v8_system_enums_files =
    -  'доступкфайлу режимдиалогавыборафайла режимоткрытияфайла ';
    -
    -  // v8 системные перечисления - построитель запроса ==> class
    -  var v8_system_enums_query_builder =
    -  'типизмеренияпостроителязапроса ';
    -
    -  // v8 системные перечисления - анализ данных ==> class
    -  var v8_system_enums_data_analysis =
    -  'видданныханализа методкластеризации типединицыинтервалавременианализаданных типзаполнениятаблицырезультатаанализаданных ' +
    -  'типиспользованиячисловыхзначенийанализаданных типисточникаданныхпоискаассоциаций типколонкианализаданныхдереворешений ' +
    -  'типколонкианализаданныхкластеризация типколонкианализаданныхобщаястатистика типколонкианализаданныхпоискассоциаций ' +
    -  'типколонкианализаданныхпоискпоследовательностей типколонкимоделипрогноза типмерырасстоянияанализаданных ' +
    -  'типотсеченияправилассоциации типполяанализаданных типстандартизациианализаданных типупорядочиванияправилассоциациианализаданных ' +
    -  'типупорядочиванияшаблоновпоследовательностейанализаданных типупрощениядереварешений ';
    -
    -  // v8 системные перечисления - xml, json, xs, dom, xdto, web-сервисы ==> class
    -  var v8_system_enums_xml_json_xs_dom_xdto_ws =
    -  'wsнаправлениепараметра вариантxpathxs вариантзаписидатыjson вариантпростоготипаxs видгруппымоделиxs видфасетаxdto ' +
    -  'действиепостроителяdom завершенностьпростоготипаxs завершенностьсоставноготипаxs завершенностьсхемыxs запрещенныеподстановкиxs ' +
    -  'исключениягруппподстановкиxs категорияиспользованияатрибутаxs категорияограниченияидентичностиxs категорияограниченияпространствименxs ' +
    -  'методнаследованияxs модельсодержимогоxs назначениетипаxml недопустимыеподстановкиxs обработкапробельныхсимволовxs обработкасодержимогоxs ' +
    -  'ограничениезначенияxs параметрыотбораузловdom переносстрокjson позициявдокументеdom пробельныесимволыxml типатрибутаxml типзначенияjson ' +
    -  'типканоническогоxml типкомпонентыxs типпроверкиxml типрезультатаdomxpath типузлаdom типузлаxml формаxml формапредставленияxs ' +
    -  'форматдатыjson экранированиесимволовjson ';
    -
    -  // v8 системные перечисления - система компоновки данных ==> class
    -  var v8_system_enums_data_composition_system =
    -  'видсравнениякомпоновкиданных действиеобработкирасшифровкикомпоновкиданных направлениесортировкикомпоновкиданных ' +
    -  'расположениевложенныхэлементоврезультатакомпоновкиданных расположениеитоговкомпоновкиданных расположениегруппировкикомпоновкиданных ' +
    -  'расположениеполейгруппировкикомпоновкиданных расположениеполякомпоновкиданных расположениереквизитовкомпоновкиданных ' +
    -  'расположениересурсовкомпоновкиданных типбухгалтерскогоостаткакомпоновкиданных типвыводатекстакомпоновкиданных ' +
    -  'типгруппировкикомпоновкиданных типгруппыэлементовотборакомпоновкиданных типдополненияпериодакомпоновкиданных ' +
    -  'типзаголовкаполейкомпоновкиданных типмакетагруппировкикомпоновкиданных типмакетаобластикомпоновкиданных типостаткакомпоновкиданных ' +
    -  'типпериодакомпоновкиданных типразмещениятекстакомпоновкиданных типсвязинаборовданныхкомпоновкиданных типэлементарезультатакомпоновкиданных ' +
    -  'расположениелегендыдиаграммыкомпоновкиданных типпримененияотборакомпоновкиданных режимотображенияэлементанастройкикомпоновкиданных ' +
    -  'режимотображениянастроеккомпоновкиданных состояниеэлементанастройкикомпоновкиданных способвосстановлениянастроеккомпоновкиданных ' +
    -  'режимкомпоновкирезультата использованиепараметракомпоновкиданных автопозицияресурсовкомпоновкиданных '+
    -  'вариантиспользованиягруппировкикомпоновкиданных расположениересурсоввдиаграммекомпоновкиданных фиксациякомпоновкиданных ' +
    -  'использованиеусловногооформлениякомпоновкиданных ';
    -
    -  // v8 системные перечисления - почта ==> class
    -  var v8_system_enums_email =
    -  'важностьинтернетпочтовогосообщения обработкатекстаинтернетпочтовогосообщения способкодированияинтернетпочтовоговложения ' +
    -  'способкодированиянеasciiсимволовинтернетпочтовогосообщения типтекстапочтовогосообщения протоколинтернетпочты ' +
    -  'статусразборапочтовогосообщения ';
    -
    -  // v8 системные перечисления - журнал регистрации ==> class
    -  var v8_system_enums_logbook =
    -  'режимтранзакциизаписижурналарегистрации статустранзакциизаписижурналарегистрации уровеньжурналарегистрации ';
    -
    -  // v8 системные перечисления - криптография ==> class
    -  var v8_system_enums_cryptography =
    -  'расположениехранилищасертификатовкриптографии режимвключениясертификатовкриптографии режимпроверкисертификатакриптографии ' +
    -  'типхранилищасертификатовкриптографии ';
    -
    -  // v8 системные перечисления - ZIP ==> class
    -  var v8_system_enums_zip =
    -  'кодировкаименфайловвzipфайле методсжатияzip методшифрованияzip режимвосстановленияпутейфайловzip режимобработкиподкаталоговzip ' +
    -  'режимсохраненияпутейzip уровеньсжатияzip ';
    -
    -  // v8 системные перечисления -
    -  // Блокировка данных, Фоновые задания, Автоматизированное тестирование,
    -  // Доставляемые уведомления, Встроенные покупки, Интернет, Работа с двоичными данными ==> class
    -  var v8_system_enums_other =
    -  'звуковоеоповещение направлениепереходакстроке позициявпотоке порядокбайтов режимблокировкиданных режимуправленияблокировкойданных ' +
    -  'сервисвстроенныхпокупок состояниефоновогозадания типподписчикадоставляемыхуведомлений уровеньиспользованиязащищенногосоединенияftp ';
    -
    -  // v8 системные перечисления - схема запроса ==> class
    -  var v8_system_enums_request_schema =
    -  'направлениепорядкасхемызапроса типдополненияпериодамисхемызапроса типконтрольнойточкисхемызапроса типобъединениясхемызапроса ' +
    -  'типпараметрадоступнойтаблицысхемызапроса типсоединениясхемызапроса ';
    -
    -  // v8 системные перечисления - свойства объектов метаданных ==> class
    -  var v8_system_enums_properties_of_metadata_objects =
    -  'httpметод автоиспользованиеобщегореквизита автопрефиксномеразадачи вариантвстроенногоязыка видиерархии видрегистранакопления ' +
    -  'видтаблицывнешнегоисточникаданных записьдвиженийприпроведении заполнениепоследовательностей индексирование ' +
    -  'использованиебазыпланавидоврасчета использованиебыстроговыбора использованиеобщегореквизита использованиеподчинения ' +
    -  'использованиеполнотекстовогопоиска использованиеразделяемыхданныхобщегореквизита использованиереквизита ' +
    -  'назначениеиспользованияприложения назначениерасширенияконфигурации направлениепередачи обновлениепредопределенныхданных ' +
    -  'оперативноепроведение основноепредставлениевидарасчета основноепредставлениевидахарактеристики основноепредставлениезадачи ' +
    -  'основноепредставлениепланаобмена основноепредставлениесправочника основноепредставлениесчета перемещениеграницыприпроведении ' +
    -  'периодичностьномерабизнеспроцесса периодичностьномерадокумента периодичностьрегистрарасчета периодичностьрегистрасведений ' +
    -  'повторноеиспользованиевозвращаемыхзначений полнотекстовыйпоискпривводепостроке принадлежностьобъекта проведение ' +
    -  'разделениеаутентификацииобщегореквизита разделениеданныхобщегореквизита разделениерасширенийконфигурацииобщегореквизита '+
    -  'режимавтонумерацииобъектов режимзаписирегистра режимиспользованиямодальности ' +
    -  'режимиспользованиясинхронныхвызововрасширенийплатформыивнешнихкомпонент режимповторногоиспользованиясеансов ' +
    -  'режимполученияданныхвыборапривводепостроке режимсовместимости режимсовместимостиинтерфейса ' +
    -  'режимуправленияблокировкойданныхпоумолчанию сериикодовпланавидовхарактеристик сериикодовпланасчетов ' +
    -  'сериикодовсправочника созданиепривводе способвыбора способпоискастрокипривводепостроке способредактирования ' +
    -  'типданныхтаблицывнешнегоисточникаданных типкодапланавидоврасчета типкодасправочника типмакета типномерабизнеспроцесса ' +
    -  'типномерадокумента типномеразадачи типформы удалениедвижений ';
    -
    -  // v8 системные перечисления - разные ==> class
    -  var v8_system_enums_differents =
    -  'важностьпроблемыприменениярасширенияконфигурации вариантинтерфейсаклиентскогоприложения вариантмасштабаформклиентскогоприложения ' +
    -  'вариантосновногошрифтаклиентскогоприложения вариантстандартногопериода вариантстандартнойдатыначала видграницы видкартинки ' +
    -  'видотображенияполнотекстовогопоиска видрамки видсравнения видцвета видчисловогозначения видшрифта допустимаядлина допустимыйзнак ' +
    -  'использованиеbyteordermark использованиеметаданныхполнотекстовогопоиска источникрасширенийконфигурации клавиша кодвозвратадиалога ' +
    -  'кодировкаxbase кодировкатекста направлениепоиска направлениесортировки обновлениепредопределенныхданных обновлениеприизмененииданных ' +
    -  'отображениепанелиразделов проверказаполнения режимдиалогавопрос режимзапускаклиентскогоприложения режимокругления режимоткрытияформприложения ' +
    -  'режимполнотекстовогопоиска скоростьклиентскогосоединения состояниевнешнегоисточникаданных состояниеобновленияконфигурациибазыданных ' +
    -  'способвыборасертификатаwindows способкодированиястроки статуссообщения типвнешнейкомпоненты типплатформы типповеденияклавишиenter ' +
    -  'типэлементаинформацииовыполненииобновленияконфигурациибазыданных уровеньизоляциитранзакций хешфункция частидаты';
    -
    -  // class: встроенные наборы значений, системные перечисления (содержат дочерние значения, обращения к которым через разыменование)
    -  var CLASS =
    -  v8_system_sets_of_values +
    -  v8_system_enums_interface +
    -  v8_system_enums_objects_properties +
    -  v8_system_enums_exchange_plans +
    -  v8_system_enums_tabular_document +
    -  v8_system_enums_sheduler +
    -  v8_system_enums_formatted_document +
    -  v8_system_enums_query +
    -  v8_system_enums_report_builder +
    -  v8_system_enums_files +
    -  v8_system_enums_query_builder +
    -  v8_system_enums_data_analysis +
    -  v8_system_enums_xml_json_xs_dom_xdto_ws +
    -  v8_system_enums_data_composition_system +
    -  v8_system_enums_email +
    -  v8_system_enums_logbook +
    -  v8_system_enums_cryptography +
    -  v8_system_enums_zip +
    -  v8_system_enums_other +
    -  v8_system_enums_request_schema +
    -  v8_system_enums_properties_of_metadata_objects +
    -  v8_system_enums_differents;
    -
    -  // v8 общие объекты (у объектов есть конструктор, экземпляры создаются методом НОВЫЙ) ==> type
    -  var v8_shared_object =
    -  'comобъект ftpсоединение httpзапрос httpсервисответ httpсоединение wsопределения wsпрокси xbase анализданных аннотацияxs ' +
    -  'блокировкаданных буфердвоичныхданных включениеxs выражениекомпоновкиданных генераторслучайныхчисел географическаясхема ' +
    -  'географическиекоординаты графическаясхема группамоделиxs данныерасшифровкикомпоновкиданных двоичныеданные дендрограмма ' +
    -  'диаграмма диаграммаганта диалогвыборафайла диалогвыборацвета диалогвыборашрифта диалограсписаниярегламентногозадания ' +
    -  'диалогредактированиястандартногопериода диапазон документdom документhtml документацияxs доставляемоеуведомление ' +
    -  'записьdom записьfastinfoset записьhtml записьjson записьxml записьzipфайла записьданных записьтекста записьузловdom ' +
    -  'запрос защищенноесоединениеopenssl значенияполейрасшифровкикомпоновкиданных извлечениетекста импортxs интернетпочта ' +
    -  'интернетпочтовоесообщение интернетпочтовыйпрофиль интернетпрокси интернетсоединение информациядляприложенияxs ' +
    -  'использованиеатрибутаxs использованиесобытияжурналарегистрации источникдоступныхнастроеккомпоновкиданных ' +
    -  'итераторузловdom картинка квалификаторыдаты квалификаторыдвоичныхданных квалификаторыстроки квалификаторычисла ' +
    -  'компоновщикмакетакомпоновкиданных компоновщикнастроеккомпоновкиданных конструктормакетаоформлениякомпоновкиданных ' +
    -  'конструкторнастроеккомпоновкиданных конструкторформатнойстроки линия макеткомпоновкиданных макетобластикомпоновкиданных ' +
    -  'макетоформлениякомпоновкиданных маскаxs менеджеркриптографии наборсхемxml настройкикомпоновкиданных настройкисериализацииjson ' +
    -  'обработкакартинок обработкарасшифровкикомпоновкиданных обходдереваdom объявлениеатрибутаxs объявлениенотацииxs ' +
    -  'объявлениеэлементаxs описаниеиспользованиясобытиядоступжурналарегистрации ' +
    -  'описаниеиспользованиясобытияотказвдоступежурналарегистрации описаниеобработкирасшифровкикомпоновкиданных ' +
    -  'описаниепередаваемогофайла описаниетипов определениегруппыатрибутовxs определениегруппымоделиxs ' +
    -  'определениеограниченияидентичностиxs определениепростоготипаxs определениесоставноготипаxs определениетипадокументаdom ' +
    -  'определенияxpathxs отборкомпоновкиданных пакетотображаемыхдокументов параметрвыбора параметркомпоновкиданных ' +
    -  'параметрызаписиjson параметрызаписиxml параметрычтенияxml переопределениеxs планировщик полеанализаданных ' +
    -  'полекомпоновкиданных построительdom построительзапроса построительотчета построительотчетаанализаданных ' +
    -  'построительсхемxml поток потоквпамяти почта почтовоесообщение преобразованиеxsl преобразованиекканоническомуxml ' +
    -  'процессорвыводарезультатакомпоновкиданныхвколлекциюзначений процессорвыводарезультатакомпоновкиданныхвтабличныйдокумент ' +
    -  'процессоркомпоновкиданных разыменовательпространствименdom рамка расписаниерегламентногозадания расширенноеимяxml ' +
    -  'результатчтенияданных своднаядиаграмма связьпараметравыбора связьпотипу связьпотипукомпоновкиданных сериализаторxdto ' +
    -  'сертификатклиентаwindows сертификатклиентафайл сертификаткриптографии сертификатыудостоверяющихцентровwindows ' +
    -  'сертификатыудостоверяющихцентровфайл сжатиеданных системнаяинформация сообщениепользователю сочетаниеклавиш ' +
    -  'сравнениезначений стандартнаядатаначала стандартныйпериод схемаxml схемакомпоновкиданных табличныйдокумент ' +
    -  'текстовыйдокумент тестируемоеприложение типданныхxml уникальныйидентификатор фабрикаxdto файл файловыйпоток ' +
    -  'фасетдлиныxs фасетколичестваразрядовдробнойчастиxs фасетмаксимальноговключающегозначенияxs ' +
    -  'фасетмаксимальногоисключающегозначенияxs фасетмаксимальнойдлиныxs фасетминимальноговключающегозначенияxs ' +
    -  'фасетминимальногоисключающегозначенияxs фасетминимальнойдлиныxs фасетобразцаxs фасетобщегоколичестваразрядовxs ' +
    -  'фасетперечисленияxs фасетпробельныхсимволовxs фильтрузловdom форматированнаястрока форматированныйдокумент ' +
    -  'фрагментxs хешированиеданных хранилищезначения цвет чтениеfastinfoset чтениеhtml чтениеjson чтениеxml чтениеzipфайла ' +
    -  'чтениеданных чтениетекста чтениеузловdom шрифт элементрезультатакомпоновкиданных ';
    -
    -  // v8 универсальные коллекции значений ==> type
    -  var v8_universal_collection =
    -  'comsafearray деревозначений массив соответствие списокзначений структура таблицазначений фиксированнаяструктура ' +
    -  'фиксированноесоответствие фиксированныймассив ';
    -
    -  // type : встроенные типы
    -  var TYPE =
    -  v8_shared_object +
    -  v8_universal_collection;
    -
    -  // literal : примитивные типы
    -  var LITERAL = 'null истина ложь неопределено';
    -
    -  // number : числа
    -  var NUMBERS = hljs.inherit(hljs.NUMBER_MODE);
    -
    -  // string : строки
    -  var STRINGS = {
    -    className: 'string',
    -    begin: '"|\\|', end: '"|$',
    -    contains: [{begin: '""'}]
    -  };
    -
    -  // number : даты
    -  var DATE = {
    -    begin: "'", end: "'", excludeBegin: true, excludeEnd: true,
    -    contains: [
    -      {
    -        className: 'number',
    -        begin: '\\d{4}([\\.\\\\/:-]?\\d{2}){0,5}'
    -      }
    -    ]
    -  };
    -
    -  // comment : комментарии
    -  var COMMENTS = hljs.inherit(hljs.C_LINE_COMMENT_MODE);
    -
    -  // meta : инструкции препроцессора, директивы компиляции
    -  var META = {
    -    className: 'meta',
    -
    -    begin: '#|&', end: '$',
    -    keywords: {
    -      $pattern: UNDERSCORE_IDENT_RE,
    -      'meta-keyword': KEYWORD + METAKEYWORD
    -    },
    -    contains: [
    -      COMMENTS
    -    ]
    -  };
    -
    -  // symbol : метка goto
    -  var SYMBOL = {
    -    className: 'symbol',
    -    begin: '~', end: ';|:', excludeEnd: true
    -  };
    -
    -  // function : объявление процедур и функций
    -  var FUNCTION = {
    -    className: 'function',
    -    variants: [
    -      {begin: 'процедура|функция', end: '\\)', keywords: 'процедура функция'},
    -      {begin: 'конецпроцедуры|конецфункции', keywords: 'конецпроцедуры конецфункции'}
    -    ],
    -    contains: [
    -      {
    -        begin: '\\(', end: '\\)', endsParent : true,
    -        contains: [
    -          {
    -            className: 'params',
    -            begin: UNDERSCORE_IDENT_RE, end: ',', excludeEnd: true, endsWithParent: true,
    -            keywords: {
    -              $pattern: UNDERSCORE_IDENT_RE,
    -              keyword: 'знач',
    -              literal: LITERAL
    -            },
    -            contains: [
    -              NUMBERS,
    -              STRINGS,
    -              DATE
    -            ]
    -          },
    -          COMMENTS
    -        ]
    -      },
    -      hljs.inherit(hljs.TITLE_MODE, {begin: UNDERSCORE_IDENT_RE})
    -    ]
    -  };
    -
    -  return {
    -    name: '1C:Enterprise',
    -    case_insensitive: true,
    -    keywords: {
    -      $pattern: UNDERSCORE_IDENT_RE,
    -      keyword: KEYWORD,
    -      built_in: BUILTIN,
    -      class: CLASS,
    -      type: TYPE,
    -      literal: LITERAL
    -    },
    -    contains: [
    -      META,
    -      FUNCTION,
    -      COMMENTS,
    -      SYMBOL,
    -      NUMBERS,
    -      STRINGS,
    -      DATE
    -    ]
    -  };
    -}
    -
    -module.exports = _1c;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/abnf.js b/claude-code-source/node_modules/highlight.js/lib/languages/abnf.js
    deleted file mode 100644
    index 630fa21d..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/abnf.js
    +++ /dev/null
    @@ -1,103 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: Augmented Backus-Naur Form
    -Author: Alex McKibben 
    -Website: https://tools.ietf.org/html/rfc5234
    -Audit: 2020
    -*/
    -
    -/** @type LanguageFn */
    -function abnf(hljs) {
    -  const regexes = {
    -    ruleDeclaration: /^[a-zA-Z][a-zA-Z0-9-]*/,
    -    unexpectedChars: /[!@#$^&',?+~`|:]/
    -  };
    -
    -  const keywords = [
    -    "ALPHA",
    -    "BIT",
    -    "CHAR",
    -    "CR",
    -    "CRLF",
    -    "CTL",
    -    "DIGIT",
    -    "DQUOTE",
    -    "HEXDIG",
    -    "HTAB",
    -    "LF",
    -    "LWSP",
    -    "OCTET",
    -    "SP",
    -    "VCHAR",
    -    "WSP"
    -  ];
    -
    -  const commentMode = hljs.COMMENT(/;/, /$/);
    -
    -  const terminalBinaryMode = {
    -    className: "symbol",
    -    begin: /%b[0-1]+(-[0-1]+|(\.[0-1]+)+){0,1}/
    -  };
    -
    -  const terminalDecimalMode = {
    -    className: "symbol",
    -    begin: /%d[0-9]+(-[0-9]+|(\.[0-9]+)+){0,1}/
    -  };
    -
    -  const terminalHexadecimalMode = {
    -    className: "symbol",
    -    begin: /%x[0-9A-F]+(-[0-9A-F]+|(\.[0-9A-F]+)+){0,1}/
    -  };
    -
    -  const caseSensitivityIndicatorMode = {
    -    className: "symbol",
    -    begin: /%[si]/
    -  };
    -
    -  const ruleDeclarationMode = {
    -    className: "attribute",
    -    begin: concat(regexes.ruleDeclaration, /(?=\s*=)/)
    -  };
    -
    -  return {
    -    name: 'Augmented Backus-Naur Form',
    -    illegal: regexes.unexpectedChars,
    -    keywords: keywords,
    -    contains: [
    -      ruleDeclarationMode,
    -      commentMode,
    -      terminalBinaryMode,
    -      terminalDecimalMode,
    -      terminalHexadecimalMode,
    -      caseSensitivityIndicatorMode,
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.NUMBER_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = abnf;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/accesslog.js b/claude-code-source/node_modules/highlight.js/lib/languages/accesslog.js
    deleted file mode 100644
    index 6e0f45e4..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/accesslog.js
    +++ /dev/null
    @@ -1,127 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/**
    - * Any of the passed expresssions may match
    - *
    - * Creates a huge this | this | that | that match
    - * @param {(RegExp | string)[] } args
    - * @returns {string}
    - */
    -function either(...args) {
    -  const joined = '(' + args.map((x) => source(x)).join("|") + ")";
    -  return joined;
    -}
    -
    -/*
    - Language: Apache Access Log
    - Author: Oleg Efimov 
    - Description: Apache/Nginx Access Logs
    - Website: https://httpd.apache.org/docs/2.4/logs.html#accesslog
    - Audit: 2020
    - */
    -
    -/** @type LanguageFn */
    -function accesslog(_hljs) {
    -  // https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
    -  const HTTP_VERBS = [
    -    "GET",
    -    "POST",
    -    "HEAD",
    -    "PUT",
    -    "DELETE",
    -    "CONNECT",
    -    "OPTIONS",
    -    "PATCH",
    -    "TRACE"
    -  ];
    -  return {
    -    name: 'Apache Access Log',
    -    contains: [
    -      // IP
    -      {
    -        className: 'number',
    -        begin: /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d{1,5})?\b/,
    -        relevance: 5
    -      },
    -      // Other numbers
    -      {
    -        className: 'number',
    -        begin: /\b\d+\b/,
    -        relevance: 0
    -      },
    -      // Requests
    -      {
    -        className: 'string',
    -        begin: concat(/"/, either(...HTTP_VERBS)),
    -        end: /"/,
    -        keywords: HTTP_VERBS,
    -        illegal: /\n/,
    -        relevance: 5,
    -        contains: [
    -          {
    -            begin: /HTTP\/[12]\.\d'/,
    -            relevance: 5
    -          }
    -        ]
    -      },
    -      // Dates
    -      {
    -        className: 'string',
    -        // dates must have a certain length, this prevents matching
    -        // simple array accesses a[123] and [] and other common patterns
    -        // found in other languages
    -        begin: /\[\d[^\]\n]{8,}\]/,
    -        illegal: /\n/,
    -        relevance: 1
    -      },
    -      {
    -        className: 'string',
    -        begin: /\[/,
    -        end: /\]/,
    -        illegal: /\n/,
    -        relevance: 0
    -      },
    -      // User agent / relevance boost
    -      {
    -        className: 'string',
    -        begin: /"Mozilla\/\d\.\d \(/,
    -        end: /"/,
    -        illegal: /\n/,
    -        relevance: 3
    -      },
    -      // Strings
    -      {
    -        className: 'string',
    -        begin: /"/,
    -        end: /"/,
    -        illegal: /\n/,
    -        relevance: 0
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = accesslog;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/actionscript.js b/claude-code-source/node_modules/highlight.js/lib/languages/actionscript.js
    deleted file mode 100644
    index 8539e60f..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/actionscript.js
    +++ /dev/null
    @@ -1,113 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: ActionScript
    -Author: Alexander Myadzel 
    -Category: scripting
    -Audit: 2020
    -*/
    -
    -/** @type LanguageFn */
    -function actionscript(hljs) {
    -  const IDENT_RE = /[a-zA-Z_$][a-zA-Z0-9_$]*/;
    -  const IDENT_FUNC_RETURN_TYPE_RE = /([*]|[a-zA-Z_$][a-zA-Z0-9_$]*)/;
    -
    -  const AS3_REST_ARG_MODE = {
    -    className: 'rest_arg',
    -    begin: /[.]{3}/,
    -    end: IDENT_RE,
    -    relevance: 10
    -  };
    -
    -  return {
    -    name: 'ActionScript',
    -    aliases: [ 'as' ],
    -    keywords: {
    -      keyword: 'as break case catch class const continue default delete do dynamic each ' +
    -        'else extends final finally for function get if implements import in include ' +
    -        'instanceof interface internal is namespace native new override package private ' +
    -        'protected public return set static super switch this throw try typeof use var void ' +
    -        'while with',
    -      literal: 'true false null undefined'
    -    },
    -    contains: [
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.C_NUMBER_MODE,
    -      {
    -        className: 'class',
    -        beginKeywords: 'package',
    -        end: /\{/,
    -        contains: [ hljs.TITLE_MODE ]
    -      },
    -      {
    -        className: 'class',
    -        beginKeywords: 'class interface',
    -        end: /\{/,
    -        excludeEnd: true,
    -        contains: [
    -          { beginKeywords: 'extends implements' },
    -          hljs.TITLE_MODE
    -        ]
    -      },
    -      {
    -        className: 'meta',
    -        beginKeywords: 'import include',
    -        end: /;/,
    -        keywords: { 'meta-keyword': 'import include' }
    -      },
    -      {
    -        className: 'function',
    -        beginKeywords: 'function',
    -        end: /[{;]/,
    -        excludeEnd: true,
    -        illegal: /\S/,
    -        contains: [
    -          hljs.TITLE_MODE,
    -          {
    -            className: 'params',
    -            begin: /\(/,
    -            end: /\)/,
    -            contains: [
    -              hljs.APOS_STRING_MODE,
    -              hljs.QUOTE_STRING_MODE,
    -              hljs.C_LINE_COMMENT_MODE,
    -              hljs.C_BLOCK_COMMENT_MODE,
    -              AS3_REST_ARG_MODE
    -            ]
    -          },
    -          { begin: concat(/:\s*/, IDENT_FUNC_RETURN_TYPE_RE) }
    -        ]
    -      },
    -      hljs.METHOD_GUARD
    -    ],
    -    illegal: /#/
    -  };
    -}
    -
    -module.exports = actionscript;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/ada.js b/claude-code-source/node_modules/highlight.js/lib/languages/ada.js
    deleted file mode 100644
    index f427c65f..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/ada.js
    +++ /dev/null
    @@ -1,194 +0,0 @@
    -/*
    -Language: Ada
    -Author: Lars Schulna 
    -Description: Ada is a general-purpose programming language that has great support for saftey critical and real-time applications.
    -             It has been developed by the DoD and thus has been used in military and safety-critical applications (like civil aviation).
    -             The first version appeared in the 80s, but it's still actively developed today with
    -             the newest standard being Ada2012.
    -*/
    -
    -// We try to support full Ada2012
    -//
    -// We highlight all appearances of types, keywords, literals (string, char, number, bool)
    -// and titles (user defined function/procedure/package)
    -// CSS classes are set accordingly
    -//
    -// Languages causing problems for language detection:
    -// xml (broken by Foo : Bar type), elm (broken by Foo : Bar type), vbscript-html (broken by body keyword)
    -// sql (ada default.txt has a lot of sql keywords)
    -
    -/** @type LanguageFn */
    -function ada(hljs) {
    -  // Regular expression for Ada numeric literals.
    -  // stolen form the VHDL highlighter
    -
    -  // Decimal literal:
    -  const INTEGER_RE = '\\d(_|\\d)*';
    -  const EXPONENT_RE = '[eE][-+]?' + INTEGER_RE;
    -  const DECIMAL_LITERAL_RE = INTEGER_RE + '(\\.' + INTEGER_RE + ')?' + '(' + EXPONENT_RE + ')?';
    -
    -  // Based literal:
    -  const BASED_INTEGER_RE = '\\w+';
    -  const BASED_LITERAL_RE = INTEGER_RE + '#' + BASED_INTEGER_RE + '(\\.' + BASED_INTEGER_RE + ')?' + '#' + '(' + EXPONENT_RE + ')?';
    -
    -  const NUMBER_RE = '\\b(' + BASED_LITERAL_RE + '|' + DECIMAL_LITERAL_RE + ')';
    -
    -  // Identifier regex
    -  const ID_REGEX = '[A-Za-z](_?[A-Za-z0-9.])*';
    -
    -  // bad chars, only allowed in literals
    -  const BAD_CHARS = `[]\\{\\}%#'"`;
    -
    -  // Ada doesn't have block comments, only line comments
    -  const COMMENTS = hljs.COMMENT('--', '$');
    -
    -  // variable declarations of the form
    -  // Foo : Bar := Baz;
    -  // where only Bar will be highlighted
    -  const VAR_DECLS = {
    -    // TODO: These spaces are not required by the Ada syntax
    -    // however, I have yet to see handwritten Ada code where
    -    // someone does not put spaces around :
    -    begin: '\\s+:\\s+',
    -    end: '\\s*(:=|;|\\)|=>|$)',
    -    // endsWithParent: true,
    -    // returnBegin: true,
    -    illegal: BAD_CHARS,
    -    contains: [
    -      {
    -        // workaround to avoid highlighting
    -        // named loops and declare blocks
    -        beginKeywords: 'loop for declare others',
    -        endsParent: true
    -      },
    -      {
    -        // properly highlight all modifiers
    -        className: 'keyword',
    -        beginKeywords: 'not null constant access function procedure in out aliased exception'
    -      },
    -      {
    -        className: 'type',
    -        begin: ID_REGEX,
    -        endsParent: true,
    -        relevance: 0
    -      }
    -    ]
    -  };
    -
    -  return {
    -    name: 'Ada',
    -    case_insensitive: true,
    -    keywords: {
    -      keyword:
    -                'abort else new return abs elsif not reverse abstract end ' +
    -                'accept entry select access exception of separate aliased exit or some ' +
    -                'all others subtype and for out synchronized array function overriding ' +
    -                'at tagged generic package task begin goto pragma terminate ' +
    -                'body private then if procedure type case in protected constant interface ' +
    -                'is raise use declare range delay limited record when delta loop rem while ' +
    -                'digits renames with do mod requeue xor',
    -      literal:
    -                'True False'
    -    },
    -    contains: [
    -      COMMENTS,
    -      // strings "foobar"
    -      {
    -        className: 'string',
    -        begin: /"/,
    -        end: /"/,
    -        contains: [{
    -          begin: /""/,
    -          relevance: 0
    -        }]
    -      },
    -      // characters ''
    -      {
    -        // character literals always contain one char
    -        className: 'string',
    -        begin: /'.'/
    -      },
    -      {
    -        // number literals
    -        className: 'number',
    -        begin: NUMBER_RE,
    -        relevance: 0
    -      },
    -      {
    -        // Attributes
    -        className: 'symbol',
    -        begin: "'" + ID_REGEX
    -      },
    -      {
    -        // package definition, maybe inside generic
    -        className: 'title',
    -        begin: '(\\bwith\\s+)?(\\bprivate\\s+)?\\bpackage\\s+(\\bbody\\s+)?',
    -        end: '(is|$)',
    -        keywords: 'package body',
    -        excludeBegin: true,
    -        excludeEnd: true,
    -        illegal: BAD_CHARS
    -      },
    -      {
    -        // function/procedure declaration/definition
    -        // maybe inside generic
    -        begin: '(\\b(with|overriding)\\s+)?\\b(function|procedure)\\s+',
    -        end: '(\\bis|\\bwith|\\brenames|\\)\\s*;)',
    -        keywords: 'overriding function procedure with is renames return',
    -        // we need to re-match the 'function' keyword, so that
    -        // the title mode below matches only exactly once
    -        returnBegin: true,
    -        contains:
    -                [
    -                  COMMENTS,
    -                  {
    -                    // name of the function/procedure
    -                    className: 'title',
    -                    begin: '(\\bwith\\s+)?\\b(function|procedure)\\s+',
    -                    end: '(\\(|\\s+|$)',
    -                    excludeBegin: true,
    -                    excludeEnd: true,
    -                    illegal: BAD_CHARS
    -                  },
    -                  // 'self'
    -                  // // parameter types
    -                  VAR_DECLS,
    -                  {
    -                    // return type
    -                    className: 'type',
    -                    begin: '\\breturn\\s+',
    -                    end: '(\\s+|;|$)',
    -                    keywords: 'return',
    -                    excludeBegin: true,
    -                    excludeEnd: true,
    -                    // we are done with functions
    -                    endsParent: true,
    -                    illegal: BAD_CHARS
    -
    -                  }
    -                ]
    -      },
    -      {
    -        // new type declarations
    -        // maybe inside generic
    -        className: 'type',
    -        begin: '\\b(sub)?type\\s+',
    -        end: '\\s+',
    -        keywords: 'type',
    -        excludeBegin: true,
    -        illegal: BAD_CHARS
    -      },
    -
    -      // see comment above the definition
    -      VAR_DECLS
    -
    -      // no markup
    -      // relevance boosters for small snippets
    -      // {begin: '\\s*=>\\s*'},
    -      // {begin: '\\s*:=\\s*'},
    -      // {begin: '\\s+:=\\s+'},
    -    ]
    -  };
    -}
    -
    -module.exports = ada;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/angelscript.js b/claude-code-source/node_modules/highlight.js/lib/languages/angelscript.js
    deleted file mode 100644
    index ddbafbee..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/angelscript.js
    +++ /dev/null
    @@ -1,123 +0,0 @@
    -/*
    -Language: AngelScript
    -Author: Melissa Geels 
    -Category: scripting
    -Website: https://www.angelcode.com/angelscript/
    -*/
    -
    -/** @type LanguageFn */
    -function angelscript(hljs) {
    -  var builtInTypeMode = {
    -    className: 'built_in',
    -    begin: '\\b(void|bool|int|int8|int16|int32|int64|uint|uint8|uint16|uint32|uint64|string|ref|array|double|float|auto|dictionary)'
    -  };
    -
    -  var objectHandleMode = {
    -    className: 'symbol',
    -    begin: '[a-zA-Z0-9_]+@'
    -  };
    -
    -  var genericMode = {
    -    className: 'keyword',
    -    begin: '<', end: '>',
    -    contains: [ builtInTypeMode, objectHandleMode ]
    -  };
    -
    -  builtInTypeMode.contains = [ genericMode ];
    -  objectHandleMode.contains = [ genericMode ];
    -
    -  return {
    -    name: 'AngelScript',
    -    aliases: ['asc'],
    -
    -    keywords:
    -      'for in|0 break continue while do|0 return if else case switch namespace is cast ' +
    -      'or and xor not get|0 in inout|10 out override set|0 private public const default|0 ' +
    -      'final shared external mixin|10 enum typedef funcdef this super import from interface ' +
    -      'abstract|0 try catch protected explicit property',
    -
    -    // avoid close detection with C# and JS
    -    illegal: '(^using\\s+[A-Za-z0-9_\\.]+;$|\\bfunction\\s*[^\\(])',
    -
    -    contains: [
    -      { // 'strings'
    -        className: 'string',
    -        begin: '\'', end: '\'',
    -        illegal: '\\n',
    -        contains: [ hljs.BACKSLASH_ESCAPE ],
    -        relevance: 0
    -      },
    -
    -      // """heredoc strings"""
    -      {
    -        className: 'string',
    -        begin: '"""', end: '"""'
    -      },
    -
    -      { // "strings"
    -        className: 'string',
    -        begin: '"', end: '"',
    -        illegal: '\\n',
    -        contains: [ hljs.BACKSLASH_ESCAPE ],
    -        relevance: 0
    -      },
    -
    -      hljs.C_LINE_COMMENT_MODE, // single-line comments
    -      hljs.C_BLOCK_COMMENT_MODE, // comment blocks
    -
    -      { // metadata
    -        className: 'string',
    -        begin: '^\\s*\\[', end: '\\]',
    -      },
    -
    -      { // interface or namespace declaration
    -        beginKeywords: 'interface namespace', end: /\{/,
    -        illegal: '[;.\\-]',
    -        contains: [
    -          { // interface or namespace name
    -            className: 'symbol',
    -            begin: '[a-zA-Z0-9_]+'
    -          }
    -        ]
    -      },
    -
    -      { // class declaration
    -        beginKeywords: 'class', end: /\{/,
    -        illegal: '[;.\\-]',
    -        contains: [
    -          { // class name
    -            className: 'symbol',
    -            begin: '[a-zA-Z0-9_]+',
    -            contains: [
    -              {
    -                begin: '[:,]\\s*',
    -                contains: [
    -                  {
    -                    className: 'symbol',
    -                    begin: '[a-zA-Z0-9_]+'
    -                  }
    -                ]
    -              }
    -            ]
    -          }
    -        ]
    -      },
    -
    -      builtInTypeMode, // built-in types
    -      objectHandleMode, // object handles
    -
    -      { // literals
    -        className: 'literal',
    -        begin: '\\b(null|true|false)'
    -      },
    -
    -      { // numbers
    -        className: 'number',
    -        relevance: 0,
    -        begin: '(-?)(\\b0[xXbBoOdD][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?f?|\\.\\d+f?)([eE][-+]?\\d+f?)?)'
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = angelscript;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/apache.js b/claude-code-source/node_modules/highlight.js/lib/languages/apache.js
    deleted file mode 100644
    index 730e7e13..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/apache.js
    +++ /dev/null
    @@ -1,89 +0,0 @@
    -/*
    -Language: Apache config
    -Author: Ruslan Keba 
    -Contributors: Ivan Sagalaev 
    -Website: https://httpd.apache.org
    -Description: language definition for Apache configuration files (httpd.conf & .htaccess)
    -Category: common, config
    -Audit: 2020
    -*/
    -
    -/** @type LanguageFn */
    -function apache(hljs) {
    -  const NUMBER_REF = {
    -    className: 'number',
    -    begin: /[$%]\d+/
    -  };
    -  const NUMBER = {
    -    className: 'number',
    -    begin: /\d+/
    -  };
    -  const IP_ADDRESS = {
    -    className: "number",
    -    begin: /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d{1,5})?/
    -  };
    -  const PORT_NUMBER = {
    -    className: "number",
    -    begin: /:\d{1,5}/
    -  };
    -  return {
    -    name: 'Apache config',
    -    aliases: [ 'apacheconf' ],
    -    case_insensitive: true,
    -    contains: [
    -      hljs.HASH_COMMENT_MODE,
    -      {
    -        className: 'section',
    -        begin: /<\/?/,
    -        end: />/,
    -        contains: [
    -          IP_ADDRESS,
    -          PORT_NUMBER,
    -          // low relevance prevents us from claming XML/HTML where this rule would
    -          // match strings inside of XML tags
    -          hljs.inherit(hljs.QUOTE_STRING_MODE, { relevance: 0 })
    -        ]
    -      },
    -      {
    -        className: 'attribute',
    -        begin: /\w+/,
    -        relevance: 0,
    -        // keywords aren’t needed for highlighting per se, they only boost relevance
    -        // for a very generally defined mode (starts with a word, ends with line-end
    -        keywords: {
    -          nomarkup:
    -            'order deny allow setenv rewriterule rewriteengine rewritecond documentroot ' +
    -            'sethandler errordocument loadmodule options header listen serverroot ' +
    -            'servername'
    -        },
    -        starts: {
    -          end: /$/,
    -          relevance: 0,
    -          keywords: { literal: 'on off all deny allow' },
    -          contains: [
    -            {
    -              className: 'meta',
    -              begin: /\s\[/,
    -              end: /\]$/
    -            },
    -            {
    -              className: 'variable',
    -              begin: /[\$%]\{/,
    -              end: /\}/,
    -              contains: [
    -                'self',
    -                NUMBER_REF
    -              ]
    -            },
    -            IP_ADDRESS,
    -            NUMBER,
    -            hljs.QUOTE_STRING_MODE
    -          ]
    -        }
    -      }
    -    ],
    -    illegal: /\S/
    -  };
    -}
    -
    -module.exports = apache;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/applescript.js b/claude-code-source/node_modules/highlight.js/lib/languages/applescript.js
    deleted file mode 100644
    index f4615075..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/applescript.js
    +++ /dev/null
    @@ -1,189 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/**
    - * Any of the passed expresssions may match
    - *
    - * Creates a huge this | this | that | that match
    - * @param {(RegExp | string)[] } args
    - * @returns {string}
    - */
    -function either(...args) {
    -  const joined = '(' + args.map((x) => source(x)).join("|") + ")";
    -  return joined;
    -}
    -
    -/*
    -Language: AppleScript
    -Authors: Nathan Grigg , Dr. Drang 
    -Category: scripting
    -Website: https://developer.apple.com/library/archive/documentation/AppleScript/Conceptual/AppleScriptLangGuide/introduction/ASLR_intro.html
    -Audit: 2020
    -*/
    -
    -/** @type LanguageFn */
    -function applescript(hljs) {
    -  const STRING = hljs.inherit(
    -    hljs.QUOTE_STRING_MODE, {
    -      illegal: null
    -    });
    -  const PARAMS = {
    -    className: 'params',
    -    begin: /\(/,
    -    end: /\)/,
    -    contains: [
    -      'self',
    -      hljs.C_NUMBER_MODE,
    -      STRING
    -    ]
    -  };
    -  const COMMENT_MODE_1 = hljs.COMMENT(/--/, /$/);
    -  const COMMENT_MODE_2 = hljs.COMMENT(
    -    /\(\*/,
    -    /\*\)/,
    -    {
    -      contains: [
    -        'self', // allow nesting
    -        COMMENT_MODE_1
    -      ]
    -    }
    -  );
    -  const COMMENTS = [
    -    COMMENT_MODE_1,
    -    COMMENT_MODE_2,
    -    hljs.HASH_COMMENT_MODE
    -  ];
    -
    -  const KEYWORD_PATTERNS = [
    -    /apart from/,
    -    /aside from/,
    -    /instead of/,
    -    /out of/,
    -    /greater than/,
    -    /isn't|(doesn't|does not) (equal|come before|come after|contain)/,
    -    /(greater|less) than( or equal)?/,
    -    /(starts?|ends|begins?) with/,
    -    /contained by/,
    -    /comes (before|after)/,
    -    /a (ref|reference)/,
    -    /POSIX (file|path)/,
    -    /(date|time) string/,
    -    /quoted form/
    -  ];
    -
    -  const BUILT_IN_PATTERNS = [
    -    /clipboard info/,
    -    /the clipboard/,
    -    /info for/,
    -    /list (disks|folder)/,
    -    /mount volume/,
    -    /path to/,
    -    /(close|open for) access/,
    -    /(get|set) eof/,
    -    /current date/,
    -    /do shell script/,
    -    /get volume settings/,
    -    /random number/,
    -    /set volume/,
    -    /system attribute/,
    -    /system info/,
    -    /time to GMT/,
    -    /(load|run|store) script/,
    -    /scripting components/,
    -    /ASCII (character|number)/,
    -    /localized string/,
    -    /choose (application|color|file|file name|folder|from list|remote application|URL)/,
    -    /display (alert|dialog)/
    -  ];
    -
    -  return {
    -    name: 'AppleScript',
    -    aliases: [ 'osascript' ],
    -    keywords: {
    -      keyword:
    -        'about above after against and around as at back before beginning ' +
    -        'behind below beneath beside between but by considering ' +
    -        'contain contains continue copy div does eighth else end equal ' +
    -        'equals error every exit fifth first for fourth from front ' +
    -        'get given global if ignoring in into is it its last local me ' +
    -        'middle mod my ninth not of on onto or over prop property put ref ' +
    -        'reference repeat returning script second set seventh since ' +
    -        'sixth some tell tenth that the|0 then third through thru ' +
    -        'timeout times to transaction try until where while whose with ' +
    -        'without',
    -      literal:
    -        'AppleScript false linefeed return pi quote result space tab true',
    -      built_in:
    -        'alias application boolean class constant date file integer list ' +
    -        'number real record string text ' +
    -        'activate beep count delay launch log offset read round ' +
    -        'run say summarize write ' +
    -        'character characters contents day frontmost id item length ' +
    -        'month name paragraph paragraphs rest reverse running time version ' +
    -        'weekday word words year'
    -    },
    -    contains: [
    -      STRING,
    -      hljs.C_NUMBER_MODE,
    -      {
    -        className: 'built_in',
    -        begin: concat(
    -          /\b/,
    -          either(...BUILT_IN_PATTERNS),
    -          /\b/
    -        )
    -      },
    -      {
    -        className: 'built_in',
    -        begin: /^\s*return\b/
    -      },
    -      {
    -        className: 'literal',
    -        begin:
    -          /\b(text item delimiters|current application|missing value)\b/
    -      },
    -      {
    -        className: 'keyword',
    -        begin: concat(
    -          /\b/,
    -          either(...KEYWORD_PATTERNS),
    -          /\b/
    -        )
    -      },
    -      {
    -        beginKeywords: 'on',
    -        illegal: /[${=;\n]/,
    -        contains: [
    -          hljs.UNDERSCORE_TITLE_MODE,
    -          PARAMS
    -        ]
    -      },
    -      ...COMMENTS
    -    ],
    -    illegal: /\/\/|->|=>|\[\[/
    -  };
    -}
    -
    -module.exports = applescript;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/arcade.js b/claude-code-source/node_modules/highlight.js/lib/languages/arcade.js
    deleted file mode 100644
    index d1fbe8c9..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/arcade.js
    +++ /dev/null
    @@ -1,165 +0,0 @@
    -/*
    - Language: ArcGIS Arcade
    - Category: scripting
    - Author: John Foster 
    - Website: https://developers.arcgis.com/arcade/
    - Description: ArcGIS Arcade is an expression language used in many Esri ArcGIS products such as Pro, Online, Server, Runtime, JavaScript, and Python
    -*/
    -
    -/** @type LanguageFn */
    -function arcade(hljs) {
    -  const IDENT_RE = '[A-Za-z_][0-9A-Za-z_]*';
    -  const KEYWORDS = {
    -    keyword:
    -      'if for while var new function do return void else break',
    -    literal:
    -      'BackSlash DoubleQuote false ForwardSlash Infinity NaN NewLine null PI SingleQuote Tab TextFormatting true undefined',
    -    built_in:
    -      'Abs Acos Angle Attachments Area AreaGeodetic Asin Atan Atan2 Average Bearing Boolean Buffer BufferGeodetic ' +
    -      'Ceil Centroid Clip Console Constrain Contains Cos Count Crosses Cut Date DateAdd ' +
    -      'DateDiff Day Decode DefaultValue Dictionary Difference Disjoint Distance DistanceGeodetic Distinct ' +
    -      'DomainCode DomainName Equals Exp Extent Feature FeatureSet FeatureSetByAssociation FeatureSetById FeatureSetByPortalItem ' +
    -      'FeatureSetByRelationshipName FeatureSetByTitle FeatureSetByUrl Filter First Floor Geometry GroupBy Guid HasKey Hour IIf IndexOf ' +
    -      'Intersection Intersects IsEmpty IsNan IsSelfIntersecting Length LengthGeodetic Log Max Mean Millisecond Min Minute Month ' +
    -      'MultiPartToSinglePart Multipoint NextSequenceValue Now Number OrderBy Overlaps Point Polygon ' +
    -      'Polyline Portal Pow Random Relate Reverse RingIsClockWise Round Second SetGeometry Sin Sort Sqrt Stdev Sum ' +
    -      'SymmetricDifference Tan Text Timestamp Today ToLocal Top Touches ToUTC TrackCurrentTime ' +
    -      'TrackGeometryWindow TrackIndex TrackStartTime TrackWindow TypeOf Union UrlEncode Variance ' +
    -      'Weekday When Within Year '
    -  };
    -  const SYMBOL = {
    -    className: 'symbol',
    -    begin: '\\$[datastore|feature|layer|map|measure|sourcefeature|sourcelayer|targetfeature|targetlayer|value|view]+'
    -  };
    -  const NUMBER = {
    -    className: 'number',
    -    variants: [
    -      {
    -        begin: '\\b(0[bB][01]+)'
    -      },
    -      {
    -        begin: '\\b(0[oO][0-7]+)'
    -      },
    -      {
    -        begin: hljs.C_NUMBER_RE
    -      }
    -    ],
    -    relevance: 0
    -  };
    -  const SUBST = {
    -    className: 'subst',
    -    begin: '\\$\\{',
    -    end: '\\}',
    -    keywords: KEYWORDS,
    -    contains: [] // defined later
    -  };
    -  const TEMPLATE_STRING = {
    -    className: 'string',
    -    begin: '`',
    -    end: '`',
    -    contains: [
    -      hljs.BACKSLASH_ESCAPE,
    -      SUBST
    -    ]
    -  };
    -  SUBST.contains = [
    -    hljs.APOS_STRING_MODE,
    -    hljs.QUOTE_STRING_MODE,
    -    TEMPLATE_STRING,
    -    NUMBER,
    -    hljs.REGEXP_MODE
    -  ];
    -  const PARAMS_CONTAINS = SUBST.contains.concat([
    -    hljs.C_BLOCK_COMMENT_MODE,
    -    hljs.C_LINE_COMMENT_MODE
    -  ]);
    -
    -  return {
    -    name: 'ArcGIS Arcade',
    -    keywords: KEYWORDS,
    -    contains: [
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      TEMPLATE_STRING,
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      SYMBOL,
    -      NUMBER,
    -      { // object attr container
    -        begin: /[{,]\s*/,
    -        relevance: 0,
    -        contains: [{
    -          begin: IDENT_RE + '\\s*:',
    -          returnBegin: true,
    -          relevance: 0,
    -          contains: [{
    -            className: 'attr',
    -            begin: IDENT_RE,
    -            relevance: 0
    -          }]
    -        }]
    -      },
    -      { // "value" container
    -        begin: '(' + hljs.RE_STARTERS_RE + '|\\b(return)\\b)\\s*',
    -        keywords: 'return',
    -        contains: [
    -          hljs.C_LINE_COMMENT_MODE,
    -          hljs.C_BLOCK_COMMENT_MODE,
    -          hljs.REGEXP_MODE,
    -          {
    -            className: 'function',
    -            begin: '(\\(.*?\\)|' + IDENT_RE + ')\\s*=>',
    -            returnBegin: true,
    -            end: '\\s*=>',
    -            contains: [{
    -              className: 'params',
    -              variants: [
    -                {
    -                  begin: IDENT_RE
    -                },
    -                {
    -                  begin: /\(\s*\)/
    -                },
    -                {
    -                  begin: /\(/,
    -                  end: /\)/,
    -                  excludeBegin: true,
    -                  excludeEnd: true,
    -                  keywords: KEYWORDS,
    -                  contains: PARAMS_CONTAINS
    -                }
    -              ]
    -            }]
    -          }
    -        ],
    -        relevance: 0
    -      },
    -      {
    -        className: 'function',
    -        beginKeywords: 'function',
    -        end: /\{/,
    -        excludeEnd: true,
    -        contains: [
    -          hljs.inherit(hljs.TITLE_MODE, {
    -            begin: IDENT_RE
    -          }),
    -          {
    -            className: 'params',
    -            begin: /\(/,
    -            end: /\)/,
    -            excludeBegin: true,
    -            excludeEnd: true,
    -            contains: PARAMS_CONTAINS
    -          }
    -        ],
    -        illegal: /\[|%/
    -      },
    -      {
    -        begin: /\$[(.]/
    -      }
    -    ],
    -    illegal: /#(?!!)/
    -  };
    -}
    -
    -module.exports = arcade;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/arduino.js b/claude-code-source/node_modules/highlight.js/lib/languages/arduino.js
    deleted file mode 100644
    index f4a09091..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/arduino.js
    +++ /dev/null
    @@ -1,576 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function lookahead(re) {
    -  return concat('(?=', re, ')');
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function optional(re) {
    -  return concat('(', re, ')?');
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: C++
    -Category: common, system
    -Website: https://isocpp.org
    -*/
    -
    -/** @type LanguageFn */
    -function cPlusPlus(hljs) {
    -  // added for historic reasons because `hljs.C_LINE_COMMENT_MODE` does
    -  // not include such support nor can we be sure all the grammars depending
    -  // on it would desire this behavior
    -  const C_LINE_COMMENT_MODE = hljs.COMMENT('//', '$', {
    -    contains: [
    -      {
    -        begin: /\\\n/
    -      }
    -    ]
    -  });
    -  const DECLTYPE_AUTO_RE = 'decltype\\(auto\\)';
    -  const NAMESPACE_RE = '[a-zA-Z_]\\w*::';
    -  const TEMPLATE_ARGUMENT_RE = '<[^<>]+>';
    -  const FUNCTION_TYPE_RE = '(' +
    -    DECLTYPE_AUTO_RE + '|' +
    -    optional(NAMESPACE_RE) +
    -    '[a-zA-Z_]\\w*' + optional(TEMPLATE_ARGUMENT_RE) +
    -  ')';
    -  const CPP_PRIMITIVE_TYPES = {
    -    className: 'keyword',
    -    begin: '\\b[a-z\\d_]*_t\\b'
    -  };
    -
    -  // https://en.cppreference.com/w/cpp/language/escape
    -  // \\ \x \xFF \u2837 \u00323747 \374
    -  const CHARACTER_ESCAPES = '\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)';
    -  const STRINGS = {
    -    className: 'string',
    -    variants: [
    -      {
    -        begin: '(u8?|U|L)?"',
    -        end: '"',
    -        illegal: '\\n',
    -        contains: [ hljs.BACKSLASH_ESCAPE ]
    -      },
    -      {
    -        begin: '(u8?|U|L)?\'(' + CHARACTER_ESCAPES + "|.)",
    -        end: '\'',
    -        illegal: '.'
    -      },
    -      hljs.END_SAME_AS_BEGIN({
    -        begin: /(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,
    -        end: /\)([^()\\ ]{0,16})"/
    -      })
    -    ]
    -  };
    -
    -  const NUMBERS = {
    -    className: 'number',
    -    variants: [
    -      {
    -        begin: '\\b(0b[01\']+)'
    -      },
    -      {
    -        begin: '(-?)\\b([\\d\']+(\\.[\\d\']*)?|\\.[\\d\']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)'
    -      },
    -      {
    -        begin: '(-?)(\\b0[xX][a-fA-F0-9\']+|(\\b[\\d\']+(\\.[\\d\']*)?|\\.[\\d\']+)([eE][-+]?[\\d\']+)?)'
    -      }
    -    ],
    -    relevance: 0
    -  };
    -
    -  const PREPROCESSOR = {
    -    className: 'meta',
    -    begin: /#\s*[a-z]+\b/,
    -    end: /$/,
    -    keywords: {
    -      'meta-keyword':
    -        'if else elif endif define undef warning error line ' +
    -        'pragma _Pragma ifdef ifndef include'
    -    },
    -    contains: [
    -      {
    -        begin: /\\\n/,
    -        relevance: 0
    -      },
    -      hljs.inherit(STRINGS, {
    -        className: 'meta-string'
    -      }),
    -      {
    -        className: 'meta-string',
    -        begin: /<.*?>/
    -      },
    -      C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE
    -    ]
    -  };
    -
    -  const TITLE_MODE = {
    -    className: 'title',
    -    begin: optional(NAMESPACE_RE) + hljs.IDENT_RE,
    -    relevance: 0
    -  };
    -
    -  const FUNCTION_TITLE = optional(NAMESPACE_RE) + hljs.IDENT_RE + '\\s*\\(';
    -
    -  const COMMON_CPP_HINTS = [
    -    'asin',
    -    'atan2',
    -    'atan',
    -    'calloc',
    -    'ceil',
    -    'cosh',
    -    'cos',
    -    'exit',
    -    'exp',
    -    'fabs',
    -    'floor',
    -    'fmod',
    -    'fprintf',
    -    'fputs',
    -    'free',
    -    'frexp',
    -    'auto_ptr',
    -    'deque',
    -    'list',
    -    'queue',
    -    'stack',
    -    'vector',
    -    'map',
    -    'set',
    -    'pair',
    -    'bitset',
    -    'multiset',
    -    'multimap',
    -    'unordered_set',
    -    'fscanf',
    -    'future',
    -    'isalnum',
    -    'isalpha',
    -    'iscntrl',
    -    'isdigit',
    -    'isgraph',
    -    'islower',
    -    'isprint',
    -    'ispunct',
    -    'isspace',
    -    'isupper',
    -    'isxdigit',
    -    'tolower',
    -    'toupper',
    -    'labs',
    -    'ldexp',
    -    'log10',
    -    'log',
    -    'malloc',
    -    'realloc',
    -    'memchr',
    -    'memcmp',
    -    'memcpy',
    -    'memset',
    -    'modf',
    -    'pow',
    -    'printf',
    -    'putchar',
    -    'puts',
    -    'scanf',
    -    'sinh',
    -    'sin',
    -    'snprintf',
    -    'sprintf',
    -    'sqrt',
    -    'sscanf',
    -    'strcat',
    -    'strchr',
    -    'strcmp',
    -    'strcpy',
    -    'strcspn',
    -    'strlen',
    -    'strncat',
    -    'strncmp',
    -    'strncpy',
    -    'strpbrk',
    -    'strrchr',
    -    'strspn',
    -    'strstr',
    -    'tanh',
    -    'tan',
    -    'unordered_map',
    -    'unordered_multiset',
    -    'unordered_multimap',
    -    'priority_queue',
    -    'make_pair',
    -    'array',
    -    'shared_ptr',
    -    'abort',
    -    'terminate',
    -    'abs',
    -    'acos',
    -    'vfprintf',
    -    'vprintf',
    -    'vsprintf',
    -    'endl',
    -    'initializer_list',
    -    'unique_ptr',
    -    'complex',
    -    'imaginary',
    -    'std',
    -    'string',
    -    'wstring',
    -    'cin',
    -    'cout',
    -    'cerr',
    -    'clog',
    -    'stdin',
    -    'stdout',
    -    'stderr',
    -    'stringstream',
    -    'istringstream',
    -    'ostringstream'
    -  ];
    -
    -  const CPP_KEYWORDS = {
    -    keyword: 'int float while private char char8_t char16_t char32_t catch import module export virtual operator sizeof ' +
    -      'dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace ' +
    -      'unsigned long volatile static protected bool template mutable if public friend ' +
    -      'do goto auto void enum else break extern using asm case typeid wchar_t ' +
    -      'short reinterpret_cast|10 default double register explicit signed typename try this ' +
    -      'switch continue inline delete alignas alignof constexpr consteval constinit decltype ' +
    -      'concept co_await co_return co_yield requires ' +
    -      'noexcept static_assert thread_local restrict final override ' +
    -      'atomic_bool atomic_char atomic_schar ' +
    -      'atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong ' +
    -      'atomic_ullong new throw return ' +
    -      'and and_eq bitand bitor compl not not_eq or or_eq xor xor_eq',
    -    built_in: '_Bool _Complex _Imaginary',
    -    _relevance_hints: COMMON_CPP_HINTS,
    -    literal: 'true false nullptr NULL'
    -  };
    -
    -  const FUNCTION_DISPATCH = {
    -    className: "function.dispatch",
    -    relevance: 0,
    -    keywords: CPP_KEYWORDS,
    -    begin: concat(
    -      /\b/,
    -      /(?!decltype)/,
    -      /(?!if)/,
    -      /(?!for)/,
    -      /(?!while)/,
    -      hljs.IDENT_RE,
    -      lookahead(/\s*\(/))
    -  };
    -
    -  const EXPRESSION_CONTAINS = [
    -    FUNCTION_DISPATCH,
    -    PREPROCESSOR,
    -    CPP_PRIMITIVE_TYPES,
    -    C_LINE_COMMENT_MODE,
    -    hljs.C_BLOCK_COMMENT_MODE,
    -    NUMBERS,
    -    STRINGS
    -  ];
    -
    -
    -  const EXPRESSION_CONTEXT = {
    -    // This mode covers expression context where we can't expect a function
    -    // definition and shouldn't highlight anything that looks like one:
    -    // `return some()`, `else if()`, `(x*sum(1, 2))`
    -    variants: [
    -      {
    -        begin: /=/,
    -        end: /;/
    -      },
    -      {
    -        begin: /\(/,
    -        end: /\)/
    -      },
    -      {
    -        beginKeywords: 'new throw return else',
    -        end: /;/
    -      }
    -    ],
    -    keywords: CPP_KEYWORDS,
    -    contains: EXPRESSION_CONTAINS.concat([
    -      {
    -        begin: /\(/,
    -        end: /\)/,
    -        keywords: CPP_KEYWORDS,
    -        contains: EXPRESSION_CONTAINS.concat([ 'self' ]),
    -        relevance: 0
    -      }
    -    ]),
    -    relevance: 0
    -  };
    -
    -  const FUNCTION_DECLARATION = {
    -    className: 'function',
    -    begin: '(' + FUNCTION_TYPE_RE + '[\\*&\\s]+)+' + FUNCTION_TITLE,
    -    returnBegin: true,
    -    end: /[{;=]/,
    -    excludeEnd: true,
    -    keywords: CPP_KEYWORDS,
    -    illegal: /[^\w\s\*&:<>.]/,
    -    contains: [
    -      { // to prevent it from being confused as the function title
    -        begin: DECLTYPE_AUTO_RE,
    -        keywords: CPP_KEYWORDS,
    -        relevance: 0
    -      },
    -      {
    -        begin: FUNCTION_TITLE,
    -        returnBegin: true,
    -        contains: [ TITLE_MODE ],
    -        relevance: 0
    -      },
    -      // needed because we do not have look-behind on the below rule
    -      // to prevent it from grabbing the final : in a :: pair
    -      {
    -        begin: /::/,
    -        relevance: 0
    -      },
    -      // initializers
    -      {
    -        begin: /:/,
    -        endsWithParent: true,
    -        contains: [
    -          STRINGS,
    -          NUMBERS
    -        ]
    -      },
    -      {
    -        className: 'params',
    -        begin: /\(/,
    -        end: /\)/,
    -        keywords: CPP_KEYWORDS,
    -        relevance: 0,
    -        contains: [
    -          C_LINE_COMMENT_MODE,
    -          hljs.C_BLOCK_COMMENT_MODE,
    -          STRINGS,
    -          NUMBERS,
    -          CPP_PRIMITIVE_TYPES,
    -          // Count matching parentheses.
    -          {
    -            begin: /\(/,
    -            end: /\)/,
    -            keywords: CPP_KEYWORDS,
    -            relevance: 0,
    -            contains: [
    -              'self',
    -              C_LINE_COMMENT_MODE,
    -              hljs.C_BLOCK_COMMENT_MODE,
    -              STRINGS,
    -              NUMBERS,
    -              CPP_PRIMITIVE_TYPES
    -            ]
    -          }
    -        ]
    -      },
    -      CPP_PRIMITIVE_TYPES,
    -      C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      PREPROCESSOR
    -    ]
    -  };
    -
    -  return {
    -    name: 'C++',
    -    aliases: [
    -      'cc',
    -      'c++',
    -      'h++',
    -      'hpp',
    -      'hh',
    -      'hxx',
    -      'cxx'
    -    ],
    -    keywords: CPP_KEYWORDS,
    -    illegal: ' rooms (9);`
    -          begin: '\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<',
    -          end: '>',
    -          keywords: CPP_KEYWORDS,
    -          contains: [
    -            'self',
    -            CPP_PRIMITIVE_TYPES
    -          ]
    -        },
    -        {
    -          begin: hljs.IDENT_RE + '::',
    -          keywords: CPP_KEYWORDS
    -        },
    -        {
    -          className: 'class',
    -          beginKeywords: 'enum class struct union',
    -          end: /[{;:<>=]/,
    -          contains: [
    -            {
    -              beginKeywords: "final class struct"
    -            },
    -            hljs.TITLE_MODE
    -          ]
    -        }
    -      ]),
    -    exports: {
    -      preprocessor: PREPROCESSOR,
    -      strings: STRINGS,
    -      keywords: CPP_KEYWORDS
    -    }
    -  };
    -}
    -
    -/*
    -Language: Arduino
    -Author: Stefania Mellai 
    -Description: The Arduino® Language is a superset of C++. This rules are designed to highlight the Arduino® source code. For info about language see http://www.arduino.cc.
    -Website: https://www.arduino.cc
    -*/
    -
    -/** @type LanguageFn */
    -function arduino(hljs) {
    -  const ARDUINO_KW = {
    -    keyword:
    -      'boolean byte word String',
    -    built_in:
    -      'KeyboardController MouseController SoftwareSerial ' +
    -      'EthernetServer EthernetClient LiquidCrystal ' +
    -      'RobotControl GSMVoiceCall EthernetUDP EsploraTFT ' +
    -      'HttpClient RobotMotor WiFiClient GSMScanner ' +
    -      'FileSystem Scheduler GSMServer YunClient YunServer ' +
    -      'IPAddress GSMClient GSMModem Keyboard Ethernet ' +
    -      'Console GSMBand Esplora Stepper Process ' +
    -      'WiFiUDP GSM_SMS Mailbox USBHost Firmata PImage ' +
    -      'Client Server GSMPIN FileIO Bridge Serial ' +
    -      'EEPROM Stream Mouse Audio Servo File Task ' +
    -      'GPRS WiFi Wire TFT GSM SPI SD ',
    -    _:
    -      'setup loop ' +
    -      'runShellCommandAsynchronously analogWriteResolution ' +
    -      'retrieveCallingNumber printFirmwareVersion ' +
    -      'analogReadResolution sendDigitalPortPair ' +
    -      'noListenOnLocalhost readJoystickButton setFirmwareVersion ' +
    -      'readJoystickSwitch scrollDisplayRight getVoiceCallStatus ' +
    -      'scrollDisplayLeft writeMicroseconds delayMicroseconds ' +
    -      'beginTransmission getSignalStrength runAsynchronously ' +
    -      'getAsynchronously listenOnLocalhost getCurrentCarrier ' +
    -      'readAccelerometer messageAvailable sendDigitalPorts ' +
    -      'lineFollowConfig countryNameWrite runShellCommand ' +
    -      'readStringUntil rewindDirectory readTemperature ' +
    -      'setClockDivider readLightSensor endTransmission ' +
    -      'analogReference detachInterrupt countryNameRead ' +
    -      'attachInterrupt encryptionType readBytesUntil ' +
    -      'robotNameWrite readMicrophone robotNameRead cityNameWrite ' +
    -      'userNameWrite readJoystickY readJoystickX mouseReleased ' +
    -      'openNextFile scanNetworks noInterrupts digitalWrite ' +
    -      'beginSpeaker mousePressed isActionDone mouseDragged ' +
    -      'displayLogos noAutoscroll addParameter remoteNumber ' +
    -      'getModifiers keyboardRead userNameRead waitContinue ' +
    -      'processInput parseCommand printVersion readNetworks ' +
    -      'writeMessage blinkVersion cityNameRead readMessage ' +
    -      'setDataMode parsePacket isListening setBitOrder ' +
    -      'beginPacket isDirectory motorsWrite drawCompass ' +
    -      'digitalRead clearScreen serialEvent rightToLeft ' +
    -      'setTextSize leftToRight requestFrom keyReleased ' +
    -      'compassRead analogWrite interrupts WiFiServer ' +
    -      'disconnect playMelody parseFloat autoscroll ' +
    -      'getPINUsed setPINUsed setTimeout sendAnalog ' +
    -      'readSlider analogRead beginWrite createChar ' +
    -      'motorsStop keyPressed tempoWrite readButton ' +
    -      'subnetMask debugPrint macAddress writeGreen ' +
    -      'randomSeed attachGPRS readString sendString ' +
    -      'remotePort releaseAll mouseMoved background ' +
    -      'getXChange getYChange answerCall getResult ' +
    -      'voiceCall endPacket constrain getSocket writeJSON ' +
    -      'getButton available connected findUntil readBytes ' +
    -      'exitValue readGreen writeBlue startLoop IPAddress ' +
    -      'isPressed sendSysex pauseMode gatewayIP setCursor ' +
    -      'getOemKey tuneWrite noDisplay loadImage switchPIN ' +
    -      'onRequest onReceive changePIN playFile noBuffer ' +
    -      'parseInt overflow checkPIN knobRead beginTFT ' +
    -      'bitClear updateIR bitWrite position writeRGB ' +
    -      'highByte writeRed setSpeed readBlue noStroke ' +
    -      'remoteIP transfer shutdown hangCall beginSMS ' +
    -      'endWrite attached maintain noCursor checkReg ' +
    -      'checkPUK shiftOut isValid shiftIn pulseIn ' +
    -      'connect println localIP pinMode getIMEI ' +
    -      'display noBlink process getBand running beginSD ' +
    -      'drawBMP lowByte setBand release bitRead prepare ' +
    -      'pointTo readRed setMode noFill remove listen ' +
    -      'stroke detach attach noTone exists buffer ' +
    -      'height bitSet circle config cursor random ' +
    -      'IRread setDNS endSMS getKey micros ' +
    -      'millis begin print write ready flush width ' +
    -      'isPIN blink clear press mkdir rmdir close ' +
    -      'point yield image BSSID click delay ' +
    -      'read text move peek beep rect line open ' +
    -      'seek fill size turn stop home find ' +
    -      'step tone sqrt RSSI SSID ' +
    -      'end bit tan cos sin pow map abs max ' +
    -      'min get run put',
    -    literal:
    -      'DIGITAL_MESSAGE FIRMATA_STRING ANALOG_MESSAGE ' +
    -      'REPORT_DIGITAL REPORT_ANALOG INPUT_PULLUP ' +
    -      'SET_PIN_MODE INTERNAL2V56 SYSTEM_RESET LED_BUILTIN ' +
    -      'INTERNAL1V1 SYSEX_START INTERNAL EXTERNAL ' +
    -      'DEFAULT OUTPUT INPUT HIGH LOW'
    -  };
    -
    -  const ARDUINO = cPlusPlus(hljs);
    -
    -  const kws = /** @type {Record} */ (ARDUINO.keywords);
    -
    -  kws.keyword += ' ' + ARDUINO_KW.keyword;
    -  kws.literal += ' ' + ARDUINO_KW.literal;
    -  kws.built_in += ' ' + ARDUINO_KW.built_in;
    -  kws._ += ' ' + ARDUINO_KW._;
    -
    -  ARDUINO.name = 'Arduino';
    -  ARDUINO.aliases = ['ino'];
    -  ARDUINO.supersetOf = "cpp";
    -
    -  return ARDUINO;
    -}
    -
    -module.exports = arduino;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/armasm.js b/claude-code-source/node_modules/highlight.js/lib/languages/armasm.js
    deleted file mode 100644
    index 9b6dac3a..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/armasm.js
    +++ /dev/null
    @@ -1,131 +0,0 @@
    -/*
    -Language: ARM Assembly
    -Author: Dan Panzarella 
    -Description: ARM Assembly including Thumb and Thumb2 instructions
    -Category: assembler
    -*/
    -
    -/** @type LanguageFn */
    -function armasm(hljs) {
    -  // local labels: %?[FB]?[AT]?\d{1,2}\w+
    -
    -  const COMMENT = {
    -    variants: [
    -      hljs.COMMENT('^[ \\t]*(?=#)', '$', {
    -        relevance: 0,
    -        excludeBegin: true
    -      }),
    -      hljs.COMMENT('[;@]', '$', {
    -        relevance: 0
    -      }),
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE
    -    ]
    -  };
    -
    -  return {
    -    name: 'ARM Assembly',
    -    case_insensitive: true,
    -    aliases: ['arm'],
    -    keywords: {
    -      $pattern: '\\.?' + hljs.IDENT_RE,
    -      meta:
    -        // GNU preprocs
    -        '.2byte .4byte .align .ascii .asciz .balign .byte .code .data .else .end .endif .endm .endr .equ .err .exitm .extern .global .hword .if .ifdef .ifndef .include .irp .long .macro .rept .req .section .set .skip .space .text .word .arm .thumb .code16 .code32 .force_thumb .thumb_func .ltorg ' +
    -        // ARM directives
    -        'ALIAS ALIGN ARM AREA ASSERT ATTR CN CODE CODE16 CODE32 COMMON CP DATA DCB DCD DCDU DCDO DCFD DCFDU DCI DCQ DCQU DCW DCWU DN ELIF ELSE END ENDFUNC ENDIF ENDP ENTRY EQU EXPORT EXPORTAS EXTERN FIELD FILL FUNCTION GBLA GBLL GBLS GET GLOBAL IF IMPORT INCBIN INCLUDE INFO KEEP LCLA LCLL LCLS LTORG MACRO MAP MEND MEXIT NOFP OPT PRESERVE8 PROC QN READONLY RELOC REQUIRE REQUIRE8 RLIST FN ROUT SETA SETL SETS SN SPACE SUBT THUMB THUMBX TTL WHILE WEND ',
    -      built_in:
    -        'r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 ' + // standard registers
    -        'pc lr sp ip sl sb fp ' + // typical regs plus backward compatibility
    -        'a1 a2 a3 a4 v1 v2 v3 v4 v5 v6 v7 v8 f0 f1 f2 f3 f4 f5 f6 f7 ' + // more regs and fp
    -        'p0 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 ' + // coprocessor regs
    -        'c0 c1 c2 c3 c4 c5 c6 c7 c8 c9 c10 c11 c12 c13 c14 c15 ' + // more coproc
    -        'q0 q1 q2 q3 q4 q5 q6 q7 q8 q9 q10 q11 q12 q13 q14 q15 ' + // advanced SIMD NEON regs
    -
    -        // program status registers
    -        'cpsr_c cpsr_x cpsr_s cpsr_f cpsr_cx cpsr_cxs cpsr_xs cpsr_xsf cpsr_sf cpsr_cxsf ' +
    -        'spsr_c spsr_x spsr_s spsr_f spsr_cx spsr_cxs spsr_xs spsr_xsf spsr_sf spsr_cxsf ' +
    -
    -        // NEON and VFP registers
    -        's0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15 ' +
    -        's16 s17 s18 s19 s20 s21 s22 s23 s24 s25 s26 s27 s28 s29 s30 s31 ' +
    -        'd0 d1 d2 d3 d4 d5 d6 d7 d8 d9 d10 d11 d12 d13 d14 d15 ' +
    -        'd16 d17 d18 d19 d20 d21 d22 d23 d24 d25 d26 d27 d28 d29 d30 d31 ' +
    -
    -        '{PC} {VAR} {TRUE} {FALSE} {OPT} {CONFIG} {ENDIAN} {CODESIZE} {CPU} {FPU} {ARCHITECTURE} {PCSTOREOFFSET} {ARMASM_VERSION} {INTER} {ROPI} {RWPI} {SWST} {NOSWST} . @'
    -    },
    -    contains: [
    -      {
    -        className: 'keyword',
    -        begin: '\\b(' + // mnemonics
    -            'adc|' +
    -            '(qd?|sh?|u[qh]?)?add(8|16)?|usada?8|(q|sh?|u[qh]?)?(as|sa)x|' +
    -            'and|adrl?|sbc|rs[bc]|asr|b[lx]?|blx|bxj|cbn?z|tb[bh]|bic|' +
    -            'bfc|bfi|[su]bfx|bkpt|cdp2?|clz|clrex|cmp|cmn|cpsi[ed]|cps|' +
    -            'setend|dbg|dmb|dsb|eor|isb|it[te]{0,3}|lsl|lsr|ror|rrx|' +
    -            'ldm(([id][ab])|f[ds])?|ldr((s|ex)?[bhd])?|movt?|mvn|mra|mar|' +
    -            'mul|[us]mull|smul[bwt][bt]|smu[as]d|smmul|smmla|' +
    -            'mla|umlaal|smlal?([wbt][bt]|d)|mls|smlsl?[ds]|smc|svc|sev|' +
    -            'mia([bt]{2}|ph)?|mrr?c2?|mcrr2?|mrs|msr|orr|orn|pkh(tb|bt)|rbit|' +
    -            'rev(16|sh)?|sel|[su]sat(16)?|nop|pop|push|rfe([id][ab])?|' +
    -            'stm([id][ab])?|str(ex)?[bhd]?|(qd?)?sub|(sh?|q|u[qh]?)?sub(8|16)|' +
    -            '[su]xt(a?h|a?b(16)?)|srs([id][ab])?|swpb?|swi|smi|tst|teq|' +
    -            'wfe|wfi|yield' +
    -        ')' +
    -        '(eq|ne|cs|cc|mi|pl|vs|vc|hi|ls|ge|lt|gt|le|al|hs|lo)?' + // condition codes
    -        '[sptrx]?' + // legal postfixes
    -        '(?=\\s)' // followed by space
    -      },
    -      COMMENT,
    -      hljs.QUOTE_STRING_MODE,
    -      {
    -        className: 'string',
    -        begin: '\'',
    -        end: '[^\\\\]\'',
    -        relevance: 0
    -      },
    -      {
    -        className: 'title',
    -        begin: '\\|',
    -        end: '\\|',
    -        illegal: '\\n',
    -        relevance: 0
    -      },
    -      {
    -        className: 'number',
    -        variants: [
    -          { // hex
    -            begin: '[#$=]?0x[0-9a-f]+'
    -          },
    -          { // bin
    -            begin: '[#$=]?0b[01]+'
    -          },
    -          { // literal
    -            begin: '[#$=]\\d+'
    -          },
    -          { // bare number
    -            begin: '\\b\\d+'
    -          }
    -        ],
    -        relevance: 0
    -      },
    -      {
    -        className: 'symbol',
    -        variants: [
    -          { // GNU ARM syntax
    -            begin: '^[ \\t]*[a-z_\\.\\$][a-z0-9_\\.\\$]+:'
    -          },
    -          { // ARM syntax
    -            begin: '^[a-z_\\.\\$][a-z0-9_\\.\\$]+'
    -          },
    -          { // label reference
    -            begin: '[=#]\\w+'
    -          }
    -        ],
    -        relevance: 0
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = armasm;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/asciidoc.js b/claude-code-source/node_modules/highlight.js/lib/languages/asciidoc.js
    deleted file mode 100644
    index bd5c261c..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/asciidoc.js
    +++ /dev/null
    @@ -1,303 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: AsciiDoc
    -Requires: xml.js
    -Author: Dan Allen 
    -Website: http://asciidoc.org
    -Description: A semantic, text-based document format that can be exported to HTML, DocBook and other backends.
    -Category: markup
    -*/
    -
    -/** @type LanguageFn */
    -function asciidoc(hljs) {
    -  const HORIZONTAL_RULE = {
    -    begin: '^\'{3,}[ \\t]*$',
    -    relevance: 10
    -  };
    -  const ESCAPED_FORMATTING = [
    -    // escaped constrained formatting marks (i.e., \* \_ or \`)
    -    {
    -      begin: /\\[*_`]/
    -    },
    -    // escaped unconstrained formatting marks (i.e., \\** \\__ or \\``)
    -    // must ignore until the next formatting marks
    -    // this rule might not be 100% compliant with Asciidoctor 2.0 but we are entering undefined behavior territory...
    -    {
    -      begin: /\\\\\*{2}[^\n]*?\*{2}/
    -    },
    -    {
    -      begin: /\\\\_{2}[^\n]*_{2}/
    -    },
    -    {
    -      begin: /\\\\`{2}[^\n]*`{2}/
    -    },
    -    // guard: constrained formatting mark may not be preceded by ":", ";" or
    -    // "}". match these so the constrained rule doesn't see them
    -    {
    -      begin: /[:;}][*_`](?![*_`])/
    -    }
    -  ];
    -  const STRONG = [
    -    // inline unconstrained strong (single line)
    -    {
    -      className: 'strong',
    -      begin: /\*{2}([^\n]+?)\*{2}/
    -    },
    -    // inline unconstrained strong (multi-line)
    -    {
    -      className: 'strong',
    -      begin: concat(
    -        /\*\*/,
    -        /((\*(?!\*)|\\[^\n]|[^*\n\\])+\n)+/,
    -        /(\*(?!\*)|\\[^\n]|[^*\n\\])*/,
    -        /\*\*/
    -      ),
    -      relevance: 0
    -    },
    -    // inline constrained strong (single line)
    -    {
    -      className: 'strong',
    -      // must not precede or follow a word character
    -      begin: /\B\*(\S|\S[^\n]*?\S)\*(?!\w)/
    -    },
    -    // inline constrained strong (multi-line)
    -    {
    -      className: 'strong',
    -      // must not precede or follow a word character
    -      begin: /\*[^\s]([^\n]+\n)+([^\n]+)\*/
    -    }
    -  ];
    -  const EMPHASIS = [
    -    // inline unconstrained emphasis (single line)
    -    {
    -      className: 'emphasis',
    -      begin: /_{2}([^\n]+?)_{2}/
    -    },
    -    // inline unconstrained emphasis (multi-line)
    -    {
    -      className: 'emphasis',
    -      begin: concat(
    -        /__/,
    -        /((_(?!_)|\\[^\n]|[^_\n\\])+\n)+/,
    -        /(_(?!_)|\\[^\n]|[^_\n\\])*/,
    -        /__/
    -      ),
    -      relevance: 0
    -    },
    -    // inline constrained emphasis (single line)
    -    {
    -      className: 'emphasis',
    -      // must not precede or follow a word character
    -      begin: /\b_(\S|\S[^\n]*?\S)_(?!\w)/
    -    },
    -    // inline constrained emphasis (multi-line)
    -    {
    -      className: 'emphasis',
    -      // must not precede or follow a word character
    -      begin: /_[^\s]([^\n]+\n)+([^\n]+)_/
    -    },
    -    // inline constrained emphasis using single quote (legacy)
    -    {
    -      className: 'emphasis',
    -      // must not follow a word character or be followed by a single quote or space
    -      begin: '\\B\'(?![\'\\s])',
    -      end: '(\\n{2}|\')',
    -      // allow escaped single quote followed by word char
    -      contains: [{
    -        begin: '\\\\\'\\w',
    -        relevance: 0
    -      }],
    -      relevance: 0
    -    }
    -  ];
    -  const ADMONITION = {
    -    className: 'symbol',
    -    begin: '^(NOTE|TIP|IMPORTANT|WARNING|CAUTION):\\s+',
    -    relevance: 10
    -  };
    -  const BULLET_LIST = {
    -    className: 'bullet',
    -    begin: '^(\\*+|-+|\\.+|[^\\n]+?::)\\s+'
    -  };
    -
    -  return {
    -    name: 'AsciiDoc',
    -    aliases: ['adoc'],
    -    contains: [
    -      // block comment
    -      hljs.COMMENT(
    -        '^/{4,}\\n',
    -        '\\n/{4,}$',
    -        // can also be done as...
    -        // '^/{4,}$',
    -        // '^/{4,}$',
    -        {
    -          relevance: 10
    -        }
    -      ),
    -      // line comment
    -      hljs.COMMENT(
    -        '^//',
    -        '$',
    -        {
    -          relevance: 0
    -        }
    -      ),
    -      // title
    -      {
    -        className: 'title',
    -        begin: '^\\.\\w.*$'
    -      },
    -      // example, admonition & sidebar blocks
    -      {
    -        begin: '^[=\\*]{4,}\\n',
    -        end: '\\n^[=\\*]{4,}$',
    -        relevance: 10
    -      },
    -      // headings
    -      {
    -        className: 'section',
    -        relevance: 10,
    -        variants: [
    -          {
    -            begin: '^(={1,6})[ \t].+?([ \t]\\1)?$'
    -          },
    -          {
    -            begin: '^[^\\[\\]\\n]+?\\n[=\\-~\\^\\+]{2,}$'
    -          }
    -        ]
    -      },
    -      // document attributes
    -      {
    -        className: 'meta',
    -        begin: '^:.+?:',
    -        end: '\\s',
    -        excludeEnd: true,
    -        relevance: 10
    -      },
    -      // block attributes
    -      {
    -        className: 'meta',
    -        begin: '^\\[.+?\\]$',
    -        relevance: 0
    -      },
    -      // quoteblocks
    -      {
    -        className: 'quote',
    -        begin: '^_{4,}\\n',
    -        end: '\\n_{4,}$',
    -        relevance: 10
    -      },
    -      // listing and literal blocks
    -      {
    -        className: 'code',
    -        begin: '^[\\-\\.]{4,}\\n',
    -        end: '\\n[\\-\\.]{4,}$',
    -        relevance: 10
    -      },
    -      // passthrough blocks
    -      {
    -        begin: '^\\+{4,}\\n',
    -        end: '\\n\\+{4,}$',
    -        contains: [{
    -          begin: '<',
    -          end: '>',
    -          subLanguage: 'xml',
    -          relevance: 0
    -        }],
    -        relevance: 10
    -      },
    -
    -      BULLET_LIST,
    -      ADMONITION,
    -      ...ESCAPED_FORMATTING,
    -      ...STRONG,
    -      ...EMPHASIS,
    -
    -      // inline smart quotes
    -      {
    -        className: 'string',
    -        variants: [
    -          {
    -            begin: "``.+?''"
    -          },
    -          {
    -            begin: "`.+?'"
    -          }
    -        ]
    -      },
    -      // inline unconstrained emphasis
    -      {
    -        className: 'code',
    -        begin: /`{2}/,
    -        end: /(\n{2}|`{2})/
    -      },
    -      // inline code snippets (TODO should get same treatment as strong and emphasis)
    -      {
    -        className: 'code',
    -        begin: '(`.+?`|\\+.+?\\+)',
    -        relevance: 0
    -      },
    -      // indented literal block
    -      {
    -        className: 'code',
    -        begin: '^[ \\t]',
    -        end: '$',
    -        relevance: 0
    -      },
    -      HORIZONTAL_RULE,
    -      // images and links
    -      {
    -        begin: '(link:)?(http|https|ftp|file|irc|image:?):\\S+?\\[[^[]*?\\]',
    -        returnBegin: true,
    -        contains: [
    -          {
    -            begin: '(link|image:?):',
    -            relevance: 0
    -          },
    -          {
    -            className: 'link',
    -            begin: '\\w',
    -            end: '[^\\[]+',
    -            relevance: 0
    -          },
    -          {
    -            className: 'string',
    -            begin: '\\[',
    -            end: '\\]',
    -            excludeBegin: true,
    -            excludeEnd: true,
    -            relevance: 0
    -          }
    -        ],
    -        relevance: 10
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = asciidoc;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/aspectj.js b/claude-code-source/node_modules/highlight.js/lib/languages/aspectj.js
    deleted file mode 100644
    index 843df471..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/aspectj.js
    +++ /dev/null
    @@ -1,186 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: AspectJ
    -Author: Hakan Ozler 
    -Website: https://www.eclipse.org/aspectj/
    -Description: Syntax Highlighting for the AspectJ Language which is a general-purpose aspect-oriented extension to the Java programming language.
    -Audit: 2020
    -*/
    -
    -/** @type LanguageFn */
    -function aspectj(hljs) {
    -  const KEYWORDS =
    -    'false synchronized int abstract float private char boolean static null if const ' +
    -    'for true while long throw strictfp finally protected import native final return void ' +
    -    'enum else extends implements break transient new catch instanceof byte super volatile case ' +
    -    'assert short package default double public try this switch continue throws privileged ' +
    -    'aspectOf adviceexecution proceed cflowbelow cflow initialization preinitialization ' +
    -    'staticinitialization withincode target within execution getWithinTypeName handler ' +
    -    'thisJoinPoint thisJoinPointStaticPart thisEnclosingJoinPointStaticPart declare parents ' +
    -    'warning error soft precedence thisAspectInstance';
    -  const SHORTKEYS = 'get set args call';
    -
    -  return {
    -    name: 'AspectJ',
    -    keywords: KEYWORDS,
    -    illegal: /<\/|#/,
    -    contains: [
    -      hljs.COMMENT(
    -        /\/\*\*/,
    -        /\*\//,
    -        {
    -          relevance: 0,
    -          contains: [
    -            {
    -              // eat up @'s in emails to prevent them to be recognized as doctags
    -              begin: /\w+@/,
    -              relevance: 0
    -            },
    -            {
    -              className: 'doctag',
    -              begin: /@[A-Za-z]+/
    -            }
    -          ]
    -        }
    -      ),
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      {
    -        className: 'class',
    -        beginKeywords: 'aspect',
    -        end: /[{;=]/,
    -        excludeEnd: true,
    -        illegal: /[:;"\[\]]/,
    -        contains: [
    -          {
    -            beginKeywords: 'extends implements pertypewithin perthis pertarget percflowbelow percflow issingleton'
    -          },
    -          hljs.UNDERSCORE_TITLE_MODE,
    -          {
    -            begin: /\([^\)]*/,
    -            end: /[)]+/,
    -            keywords: KEYWORDS + ' ' + SHORTKEYS,
    -            excludeEnd: false
    -          }
    -        ]
    -      },
    -      {
    -        className: 'class',
    -        beginKeywords: 'class interface',
    -        end: /[{;=]/,
    -        excludeEnd: true,
    -        relevance: 0,
    -        keywords: 'class interface',
    -        illegal: /[:"\[\]]/,
    -        contains: [
    -          {
    -            beginKeywords: 'extends implements'
    -          },
    -          hljs.UNDERSCORE_TITLE_MODE
    -        ]
    -      },
    -      {
    -        // AspectJ Constructs
    -        beginKeywords: 'pointcut after before around throwing returning',
    -        end: /[)]/,
    -        excludeEnd: false,
    -        illegal: /["\[\]]/,
    -        contains: [
    -          {
    -            begin: concat(hljs.UNDERSCORE_IDENT_RE, /\s*\(/),
    -            returnBegin: true,
    -            contains: [ hljs.UNDERSCORE_TITLE_MODE ]
    -          }
    -        ]
    -      },
    -      {
    -        begin: /[:]/,
    -        returnBegin: true,
    -        end: /[{;]/,
    -        relevance: 0,
    -        excludeEnd: false,
    -        keywords: KEYWORDS,
    -        illegal: /["\[\]]/,
    -        contains: [
    -          {
    -            begin: concat(hljs.UNDERSCORE_IDENT_RE, /\s*\(/),
    -            keywords: KEYWORDS + ' ' + SHORTKEYS,
    -            relevance: 0
    -          },
    -          hljs.QUOTE_STRING_MODE
    -        ]
    -      },
    -      {
    -        // this prevents 'new Name(...), or throw ...' from being recognized as a function definition
    -        beginKeywords: 'new throw',
    -        relevance: 0
    -      },
    -      {
    -        // the function class is a bit different for AspectJ compared to the Java language
    -        className: 'function',
    -        begin: /\w+ +\w+(\.\w+)?\s*\([^\)]*\)\s*((throws)[\w\s,]+)?[\{;]/,
    -        returnBegin: true,
    -        end: /[{;=]/,
    -        keywords: KEYWORDS,
    -        excludeEnd: true,
    -        contains: [
    -          {
    -            begin: concat(hljs.UNDERSCORE_IDENT_RE, /\s*\(/),
    -            returnBegin: true,
    -            relevance: 0,
    -            contains: [ hljs.UNDERSCORE_TITLE_MODE ]
    -          },
    -          {
    -            className: 'params',
    -            begin: /\(/,
    -            end: /\)/,
    -            relevance: 0,
    -            keywords: KEYWORDS,
    -            contains: [
    -              hljs.APOS_STRING_MODE,
    -              hljs.QUOTE_STRING_MODE,
    -              hljs.C_NUMBER_MODE,
    -              hljs.C_BLOCK_COMMENT_MODE
    -            ]
    -          },
    -          hljs.C_LINE_COMMENT_MODE,
    -          hljs.C_BLOCK_COMMENT_MODE
    -        ]
    -      },
    -      hljs.C_NUMBER_MODE,
    -      {
    -        // annotation is also used in this language
    -        className: 'meta',
    -        begin: /@[A-Za-z]+/
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = aspectj;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/autohotkey.js b/claude-code-source/node_modules/highlight.js/lib/languages/autohotkey.js
    deleted file mode 100644
    index 8dda10b9..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/autohotkey.js
    +++ /dev/null
    @@ -1,84 +0,0 @@
    -/*
    -Language: AutoHotkey
    -Author: Seongwon Lee 
    -Description: AutoHotkey language definition
    -Category: scripting
    -*/
    -
    -/** @type LanguageFn */
    -function autohotkey(hljs) {
    -  const BACKTICK_ESCAPE = {
    -    begin: '`[\\s\\S]'
    -  };
    -
    -  return {
    -    name: 'AutoHotkey',
    -    case_insensitive: true,
    -    aliases: ['ahk'],
    -    keywords: {
    -      keyword: 'Break Continue Critical Exit ExitApp Gosub Goto New OnExit Pause return SetBatchLines SetTimer Suspend Thread Throw Until ahk_id ahk_class ahk_pid ahk_exe ahk_group',
    -      literal: 'true false NOT AND OR',
    -      built_in: 'ComSpec Clipboard ClipboardAll ErrorLevel'
    -    },
    -    contains: [
    -      BACKTICK_ESCAPE,
    -      hljs.inherit(hljs.QUOTE_STRING_MODE, {
    -        contains: [BACKTICK_ESCAPE]
    -      }),
    -      hljs.COMMENT(';', '$', {
    -        relevance: 0
    -      }),
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      {
    -        className: 'number',
    -        begin: hljs.NUMBER_RE,
    -        relevance: 0
    -      },
    -      {
    -        // subst would be the most accurate however fails the point of
    -        // highlighting. variable is comparably the most accurate that actually
    -        // has some effect
    -        className: 'variable',
    -        begin: '%[a-zA-Z0-9#_$@]+%'
    -      },
    -      {
    -        className: 'built_in',
    -        begin: '^\\s*\\w+\\s*(,|%)'
    -        // I don't really know if this is totally relevant
    -      },
    -      {
    -        // symbol would be most accurate however is highlighted just like
    -        // built_in and that makes up a lot of AutoHotkey code meaning that it
    -        // would fail to highlight anything
    -        className: 'title',
    -        variants: [
    -          {
    -            begin: '^[^\\n";]+::(?!=)'
    -          },
    -          {
    -            begin: '^[^\\n";]+:(?!=)',
    -            // zero relevance as it catches a lot of things
    -            // followed by a single ':' in many languages
    -            relevance: 0
    -          }
    -        ]
    -      },
    -      {
    -        className: 'meta',
    -        begin: '^\\s*#\\w+',
    -        end: '$',
    -        relevance: 0
    -      },
    -      {
    -        className: 'built_in',
    -        begin: 'A_[a-zA-Z0-9]+'
    -      },
    -      {
    -        // consecutive commas, not for highlighting but just for relevance
    -        begin: ',\\s*,'
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = autohotkey;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/autoit.js b/claude-code-source/node_modules/highlight.js/lib/languages/autoit.js
    deleted file mode 100644
    index c732c76f..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/autoit.js
    +++ /dev/null
    @@ -1,183 +0,0 @@
    -/*
    -Language: AutoIt
    -Author: Manh Tuan 
    -Description: AutoIt language definition
    -Category: scripting
    -*/
    -
    -/** @type LanguageFn */
    -function autoit(hljs) {
    -  const KEYWORDS = 'ByRef Case Const ContinueCase ContinueLoop ' +
    -        'Dim Do Else ElseIf EndFunc EndIf EndSelect ' +
    -        'EndSwitch EndWith Enum Exit ExitLoop For Func ' +
    -        'Global If In Local Next ReDim Return Select Static ' +
    -        'Step Switch Then To Until Volatile WEnd While With';
    -
    -  const DIRECTIVES = [
    -    "EndRegion",
    -    "forcedef",
    -    "forceref",
    -    "ignorefunc",
    -    "include",
    -    "include-once",
    -    "NoTrayIcon",
    -    "OnAutoItStartRegister",
    -    "pragma",
    -    "Region",
    -    "RequireAdmin",
    -    "Tidy_Off",
    -    "Tidy_On",
    -    "Tidy_Parameters"
    -  ];
    -  
    -  const LITERAL = 'True False And Null Not Or Default';
    -
    -  const BUILT_IN
    -          = 'Abs ACos AdlibRegister AdlibUnRegister Asc AscW ASin Assign ATan AutoItSetOption AutoItWinGetTitle AutoItWinSetTitle Beep Binary BinaryLen BinaryMid BinaryToString BitAND BitNOT BitOR BitRotate BitShift BitXOR BlockInput Break Call CDTray Ceiling Chr ChrW ClipGet ClipPut ConsoleRead ConsoleWrite ConsoleWriteError ControlClick ControlCommand ControlDisable ControlEnable ControlFocus ControlGetFocus ControlGetHandle ControlGetPos ControlGetText ControlHide ControlListView ControlMove ControlSend ControlSetText ControlShow ControlTreeView Cos Dec DirCopy DirCreate DirGetSize DirMove DirRemove DllCall DllCallAddress DllCallbackFree DllCallbackGetPtr DllCallbackRegister DllClose DllOpen DllStructCreate DllStructGetData DllStructGetPtr DllStructGetSize DllStructSetData DriveGetDrive DriveGetFileSystem DriveGetLabel DriveGetSerial DriveGetType DriveMapAdd DriveMapDel DriveMapGet DriveSetLabel DriveSpaceFree DriveSpaceTotal DriveStatus EnvGet EnvSet EnvUpdate Eval Execute Exp FileChangeDir FileClose FileCopy FileCreateNTFSLink FileCreateShortcut FileDelete FileExists FileFindFirstFile FileFindNextFile FileFlush FileGetAttrib FileGetEncoding FileGetLongName FileGetPos FileGetShortcut FileGetShortName FileGetSize FileGetTime FileGetVersion FileInstall FileMove FileOpen FileOpenDialog FileRead FileReadLine FileReadToArray FileRecycle FileRecycleEmpty FileSaveDialog FileSelectFolder FileSetAttrib FileSetEnd FileSetPos FileSetTime FileWrite FileWriteLine Floor FtpSetProxy FuncName GUICreate GUICtrlCreateAvi GUICtrlCreateButton GUICtrlCreateCheckbox GUICtrlCreateCombo GUICtrlCreateContextMenu GUICtrlCreateDate GUICtrlCreateDummy GUICtrlCreateEdit GUICtrlCreateGraphic GUICtrlCreateGroup GUICtrlCreateIcon GUICtrlCreateInput GUICtrlCreateLabel GUICtrlCreateList GUICtrlCreateListView GUICtrlCreateListViewItem GUICtrlCreateMenu GUICtrlCreateMenuItem GUICtrlCreateMonthCal GUICtrlCreateObj GUICtrlCreatePic GUICtrlCreateProgress GUICtrlCreateRadio GUICtrlCreateSlider GUICtrlCreateTab GUICtrlCreateTabItem GUICtrlCreateTreeView GUICtrlCreateTreeViewItem GUICtrlCreateUpdown GUICtrlDelete GUICtrlGetHandle GUICtrlGetState GUICtrlRead GUICtrlRecvMsg GUICtrlRegisterListViewSort GUICtrlSendMsg GUICtrlSendToDummy GUICtrlSetBkColor GUICtrlSetColor GUICtrlSetCursor GUICtrlSetData GUICtrlSetDefBkColor GUICtrlSetDefColor GUICtrlSetFont GUICtrlSetGraphic GUICtrlSetImage GUICtrlSetLimit GUICtrlSetOnEvent GUICtrlSetPos GUICtrlSetResizing GUICtrlSetState GUICtrlSetStyle GUICtrlSetTip GUIDelete GUIGetCursorInfo GUIGetMsg GUIGetStyle GUIRegisterMsg GUISetAccelerators GUISetBkColor GUISetCoord GUISetCursor GUISetFont GUISetHelp GUISetIcon GUISetOnEvent GUISetState GUISetStyle GUIStartGroup GUISwitch Hex HotKeySet HttpSetProxy HttpSetUserAgent HWnd InetClose InetGet InetGetInfo InetGetSize InetRead IniDelete IniRead IniReadSection IniReadSectionNames IniRenameSection IniWrite IniWriteSection InputBox Int IsAdmin IsArray IsBinary IsBool IsDeclared IsDllStruct IsFloat IsFunc IsHWnd IsInt IsKeyword IsNumber IsObj IsPtr IsString Log MemGetStats Mod MouseClick MouseClickDrag MouseDown MouseGetCursor MouseGetPos MouseMove MouseUp MouseWheel MsgBox Number ObjCreate ObjCreateInterface ObjEvent ObjGet ObjName OnAutoItExitRegister OnAutoItExitUnRegister Ping PixelChecksum PixelGetColor PixelSearch ProcessClose ProcessExists ProcessGetStats ProcessList ProcessSetPriority ProcessWait ProcessWaitClose ProgressOff ProgressOn ProgressSet Ptr Random RegDelete RegEnumKey RegEnumVal RegRead RegWrite Round Run RunAs RunAsWait RunWait Send SendKeepActive SetError SetExtended ShellExecute ShellExecuteWait Shutdown Sin Sleep SoundPlay SoundSetWaveVolume SplashImageOn SplashOff SplashTextOn Sqrt SRandom StatusbarGetText StderrRead StdinWrite StdioClose StdoutRead String StringAddCR StringCompare StringFormat StringFromASCIIArray StringInStr StringIsAlNum StringIsAlpha StringIsASCII StringIsDigit StringIsFloat StringIsInt StringIsLower StringIsSpace StringIsUpper StringIsXDigit StringLeft StringLen StringLower StringMid StringRegExp StringRegExpReplace StringReplace StringReverse StringRight StringSplit StringStripCR StringStripWS StringToASCIIArray StringToBinary StringTrimLeft StringTrimRight StringUpper Tan TCPAccept TCPCloseSocket TCPConnect TCPListen TCPNameToIP TCPRecv TCPSend TCPShutdown, UDPShutdown TCPStartup, UDPStartup TimerDiff TimerInit ToolTip TrayCreateItem TrayCreateMenu TrayGetMsg TrayItemDelete TrayItemGetHandle TrayItemGetState TrayItemGetText TrayItemSetOnEvent TrayItemSetState TrayItemSetText TraySetClick TraySetIcon TraySetOnEvent TraySetPauseIcon TraySetState TraySetToolTip TrayTip UBound UDPBind UDPCloseSocket UDPOpen UDPRecv UDPSend VarGetType WinActivate WinActive WinClose WinExists WinFlash WinGetCaretPos WinGetClassList WinGetClientSize WinGetHandle WinGetPos WinGetProcess WinGetState WinGetText WinGetTitle WinKill WinList WinMenuSelectItem WinMinimizeAll WinMinimizeAllUndo WinMove WinSetOnTop WinSetState WinSetTitle WinSetTrans WinWait WinWaitActive WinWaitClose WinWaitNotActive';
    -
    -  const COMMENT = {
    -    variants: [
    -      hljs.COMMENT(';', '$', {
    -        relevance: 0
    -      }),
    -      hljs.COMMENT('#cs', '#ce'),
    -      hljs.COMMENT('#comments-start', '#comments-end')
    -    ]
    -  };
    -
    -  const VARIABLE = {
    -    begin: '\\$[A-z0-9_]+'
    -  };
    -
    -  const STRING = {
    -    className: 'string',
    -    variants: [
    -      {
    -        begin: /"/,
    -        end: /"/,
    -        contains: [{
    -          begin: /""/,
    -          relevance: 0
    -        }]
    -      },
    -      {
    -        begin: /'/,
    -        end: /'/,
    -        contains: [{
    -          begin: /''/,
    -          relevance: 0
    -        }]
    -      }
    -    ]
    -  };
    -
    -  const NUMBER = {
    -    variants: [
    -      hljs.BINARY_NUMBER_MODE,
    -      hljs.C_NUMBER_MODE
    -    ]
    -  };
    -
    -  const PREPROCESSOR = {
    -    className: 'meta',
    -    begin: '#',
    -    end: '$',
    -    keywords: {
    -      'meta-keyword': DIRECTIVES
    -    },
    -    contains: [
    -      {
    -        begin: /\\\n/,
    -        relevance: 0
    -      },
    -      {
    -        beginKeywords: 'include',
    -        keywords: {
    -          'meta-keyword': 'include'
    -        },
    -        end: '$',
    -        contains: [
    -          STRING,
    -          {
    -            className: 'meta-string',
    -            variants: [
    -              {
    -                begin: '<',
    -                end: '>'
    -              },
    -              {
    -                begin: /"/,
    -                end: /"/,
    -                contains: [{
    -                  begin: /""/,
    -                  relevance: 0
    -                }]
    -              },
    -              {
    -                begin: /'/,
    -                end: /'/,
    -                contains: [{
    -                  begin: /''/,
    -                  relevance: 0
    -                }]
    -              }
    -            ]
    -          }
    -        ]
    -      },
    -      STRING,
    -      COMMENT
    -    ]
    -  };
    -
    -  const CONSTANT = {
    -    className: 'symbol',
    -    // begin: '@',
    -    // end: '$',
    -    // keywords: 'AppDataCommonDir AppDataDir AutoItExe AutoItPID AutoItVersion AutoItX64 COM_EventObj CommonFilesDir Compiled ComputerName ComSpec CPUArch CR CRLF DesktopCommonDir DesktopDepth DesktopDir DesktopHeight DesktopRefresh DesktopWidth DocumentsCommonDir error exitCode exitMethod extended FavoritesCommonDir FavoritesDir GUI_CtrlHandle GUI_CtrlId GUI_DragFile GUI_DragId GUI_DropId GUI_WinHandle HomeDrive HomePath HomeShare HotKeyPressed HOUR IPAddress1 IPAddress2 IPAddress3 IPAddress4 KBLayout LF LocalAppDataDir LogonDNSDomain LogonDomain LogonServer MDAY MIN MON MSEC MUILang MyDocumentsDir NumParams OSArch OSBuild OSLang OSServicePack OSType OSVersion ProgramFilesDir ProgramsCommonDir ProgramsDir ScriptDir ScriptFullPath ScriptLineNumber ScriptName SEC StartMenuCommonDir StartMenuDir StartupCommonDir StartupDir SW_DISABLE SW_ENABLE SW_HIDE SW_LOCK SW_MAXIMIZE SW_MINIMIZE SW_RESTORE SW_SHOW SW_SHOWDEFAULT SW_SHOWMAXIMIZED SW_SHOWMINIMIZED SW_SHOWMINNOACTIVE SW_SHOWNA SW_SHOWNOACTIVATE SW_SHOWNORMAL SW_UNLOCK SystemDir TAB TempDir TRAY_ID TrayIconFlashing TrayIconVisible UserName UserProfileDir WDAY WindowsDir WorkingDir YDAY YEAR',
    -    // relevance: 5
    -    begin: '@[A-z0-9_]+'
    -  };
    -
    -  const FUNCTION = {
    -    className: 'function',
    -    beginKeywords: 'Func',
    -    end: '$',
    -    illegal: '\\$|\\[|%',
    -    contains: [
    -      hljs.UNDERSCORE_TITLE_MODE,
    -      {
    -        className: 'params',
    -        begin: '\\(',
    -        end: '\\)',
    -        contains: [
    -          VARIABLE,
    -          STRING,
    -          NUMBER
    -        ]
    -      }
    -    ]
    -  };
    -
    -  return {
    -    name: 'AutoIt',
    -    case_insensitive: true,
    -    illegal: /\/\*/,
    -    keywords: {
    -      keyword: KEYWORDS,
    -      built_in: BUILT_IN,
    -      literal: LITERAL
    -    },
    -    contains: [
    -      COMMENT,
    -      VARIABLE,
    -      STRING,
    -      NUMBER,
    -      PREPROCESSOR,
    -      CONSTANT,
    -      FUNCTION
    -    ]
    -  };
    -}
    -
    -module.exports = autoit;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/avrasm.js b/claude-code-source/node_modules/highlight.js/lib/languages/avrasm.js
    deleted file mode 100644
    index 0f3b7627..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/avrasm.js
    +++ /dev/null
    @@ -1,80 +0,0 @@
    -/*
    -Language: AVR Assembly
    -Author: Vladimir Ermakov 
    -Category: assembler
    -Website: https://www.microchip.com/webdoc/avrassembler/avrassembler.wb_instruction_list.html
    -*/
    -
    -/** @type LanguageFn */
    -function avrasm(hljs) {
    -  return {
    -    name: 'AVR Assembly',
    -    case_insensitive: true,
    -    keywords: {
    -      $pattern: '\\.?' + hljs.IDENT_RE,
    -      keyword:
    -        /* mnemonic */
    -        'adc add adiw and andi asr bclr bld brbc brbs brcc brcs break breq brge brhc brhs ' +
    -        'brid brie brlo brlt brmi brne brpl brsh brtc brts brvc brvs bset bst call cbi cbr ' +
    -        'clc clh cli cln clr cls clt clv clz com cp cpc cpi cpse dec eicall eijmp elpm eor ' +
    -        'fmul fmuls fmulsu icall ijmp in inc jmp ld ldd ldi lds lpm lsl lsr mov movw mul ' +
    -        'muls mulsu neg nop or ori out pop push rcall ret reti rjmp rol ror sbc sbr sbrc sbrs ' +
    -        'sec seh sbi sbci sbic sbis sbiw sei sen ser ses set sev sez sleep spm st std sts sub ' +
    -        'subi swap tst wdr',
    -      built_in:
    -        /* general purpose registers */
    -        'r0 r1 r2 r3 r4 r5 r6 r7 r8 r9 r10 r11 r12 r13 r14 r15 r16 r17 r18 r19 r20 r21 r22 ' +
    -        'r23 r24 r25 r26 r27 r28 r29 r30 r31 x|0 xh xl y|0 yh yl z|0 zh zl ' +
    -        /* IO Registers (ATMega128) */
    -        'ucsr1c udr1 ucsr1a ucsr1b ubrr1l ubrr1h ucsr0c ubrr0h tccr3c tccr3a tccr3b tcnt3h ' +
    -        'tcnt3l ocr3ah ocr3al ocr3bh ocr3bl ocr3ch ocr3cl icr3h icr3l etimsk etifr tccr1c ' +
    -        'ocr1ch ocr1cl twcr twdr twar twsr twbr osccal xmcra xmcrb eicra spmcsr spmcr portg ' +
    -        'ddrg ping portf ddrf sreg sph spl xdiv rampz eicrb eimsk gimsk gicr eifr gifr timsk ' +
    -        'tifr mcucr mcucsr tccr0 tcnt0 ocr0 assr tccr1a tccr1b tcnt1h tcnt1l ocr1ah ocr1al ' +
    -        'ocr1bh ocr1bl icr1h icr1l tccr2 tcnt2 ocr2 ocdr wdtcr sfior eearh eearl eedr eecr ' +
    -        'porta ddra pina portb ddrb pinb portc ddrc pinc portd ddrd pind spdr spsr spcr udr0 ' +
    -        'ucsr0a ucsr0b ubrr0l acsr admux adcsr adch adcl porte ddre pine pinf',
    -      meta:
    -        '.byte .cseg .db .def .device .dseg .dw .endmacro .equ .eseg .exit .include .list ' +
    -        '.listmac .macro .nolist .org .set'
    -    },
    -    contains: [
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.COMMENT(
    -        ';',
    -        '$',
    -        {
    -          relevance: 0
    -        }
    -      ),
    -      hljs.C_NUMBER_MODE, // 0x..., decimal, float
    -      hljs.BINARY_NUMBER_MODE, // 0b...
    -      {
    -        className: 'number',
    -        begin: '\\b(\\$[a-zA-Z0-9]+|0o[0-7]+)' // $..., 0o...
    -      },
    -      hljs.QUOTE_STRING_MODE,
    -      {
    -        className: 'string',
    -        begin: '\'',
    -        end: '[^\\\\]\'',
    -        illegal: '[^\\\\][^\']'
    -      },
    -      {
    -        className: 'symbol',
    -        begin: '^[A-Za-z0-9_.$]+:'
    -      },
    -      {
    -        className: 'meta',
    -        begin: '#',
    -        end: '$'
    -      },
    -      { // substitution within a macro
    -        className: 'subst',
    -        begin: '@[0-9]+'
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = avrasm;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/awk.js b/claude-code-source/node_modules/highlight.js/lib/languages/awk.js
    deleted file mode 100644
    index 228e0cc8..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/awk.js
    +++ /dev/null
    @@ -1,73 +0,0 @@
    -/*
    -Language: Awk
    -Author: Matthew Daly 
    -Website: https://www.gnu.org/software/gawk/manual/gawk.html
    -Description: language definition for Awk scripts
    -*/
    -
    -/** @type LanguageFn */
    -function awk(hljs) {
    -  const VARIABLE = {
    -    className: 'variable',
    -    variants: [
    -      {
    -        begin: /\$[\w\d#@][\w\d_]*/
    -      },
    -      {
    -        begin: /\$\{(.*?)\}/
    -      }
    -    ]
    -  };
    -  const KEYWORDS = 'BEGIN END if else while do for in break continue delete next nextfile function func exit|10';
    -  const STRING = {
    -    className: 'string',
    -    contains: [hljs.BACKSLASH_ESCAPE],
    -    variants: [
    -      {
    -        begin: /(u|b)?r?'''/,
    -        end: /'''/,
    -        relevance: 10
    -      },
    -      {
    -        begin: /(u|b)?r?"""/,
    -        end: /"""/,
    -        relevance: 10
    -      },
    -      {
    -        begin: /(u|r|ur)'/,
    -        end: /'/,
    -        relevance: 10
    -      },
    -      {
    -        begin: /(u|r|ur)"/,
    -        end: /"/,
    -        relevance: 10
    -      },
    -      {
    -        begin: /(b|br)'/,
    -        end: /'/
    -      },
    -      {
    -        begin: /(b|br)"/,
    -        end: /"/
    -      },
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE
    -    ]
    -  };
    -  return {
    -    name: 'Awk',
    -    keywords: {
    -      keyword: KEYWORDS
    -    },
    -    contains: [
    -      VARIABLE,
    -      STRING,
    -      hljs.REGEXP_MODE,
    -      hljs.HASH_COMMENT_MODE,
    -      hljs.NUMBER_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = awk;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/axapta.js b/claude-code-source/node_modules/highlight.js/lib/languages/axapta.js
    deleted file mode 100644
    index 6c44cb20..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/axapta.js
    +++ /dev/null
    @@ -1,179 +0,0 @@
    -/*
    -Language: Microsoft X++
    -Description: X++ is a language used in Microsoft Dynamics 365, Dynamics AX, and Axapta.
    -Author: Dmitri Roudakov 
    -Website: https://dynamics.microsoft.com/en-us/ax-overview/
    -Category: enterprise
    -*/
    -
    -/** @type LanguageFn */
    -function axapta(hljs) {
    -  const BUILT_IN_KEYWORDS = [
    -    'anytype',
    -    'boolean',
    -    'byte',
    -    'char',
    -    'container',
    -    'date',
    -    'double',
    -    'enum',
    -    'guid',
    -    'int',
    -    'int64',
    -    'long',
    -    'real',
    -    'short',
    -    'str',
    -    'utcdatetime',
    -    'var'
    -  ];
    -
    -  const LITERAL_KEYWORDS = [
    -    'default',
    -    'false',
    -    'null',
    -    'true'
    -  ];
    -
    -  const NORMAL_KEYWORDS = [
    -    'abstract',
    -    'as',
    -    'asc',
    -    'avg',
    -    'break',
    -    'breakpoint',
    -    'by',
    -    'byref',
    -    'case',
    -    'catch',
    -    'changecompany',
    -    'class',
    -    'client',
    -    'client',
    -    'common',
    -    'const',
    -    'continue',
    -    'count',
    -    'crosscompany',
    -    'delegate',
    -    'delete_from',
    -    'desc',
    -    'display',
    -    'div',
    -    'do',
    -    'edit',
    -    'else',
    -    'eventhandler',
    -    'exists',
    -    'extends',
    -    'final',
    -    'finally',
    -    'firstfast',
    -    'firstonly',
    -    'firstonly1',
    -    'firstonly10',
    -    'firstonly100',
    -    'firstonly1000',
    -    'flush',
    -    'for',
    -    'forceliterals',
    -    'forcenestedloop',
    -    'forceplaceholders',
    -    'forceselectorder',
    -    'forupdate',
    -    'from',
    -    'generateonly',
    -    'group',
    -    'hint',
    -    'if',
    -    'implements',
    -    'in',
    -    'index',
    -    'insert_recordset',
    -    'interface',
    -    'internal',
    -    'is',
    -    'join',
    -    'like',
    -    'maxof',
    -    'minof',
    -    'mod',
    -    'namespace',
    -    'new',
    -    'next',
    -    'nofetch',
    -    'notexists',
    -    'optimisticlock',
    -    'order',
    -    'outer',
    -    'pessimisticlock',
    -    'print',
    -    'private',
    -    'protected',
    -    'public',
    -    'readonly',
    -    'repeatableread',
    -    'retry',
    -    'return',
    -    'reverse',
    -    'select',
    -    'server',
    -    'setting',
    -    'static',
    -    'sum',
    -    'super',
    -    'switch',
    -    'this',
    -    'throw',
    -    'try',
    -    'ttsabort',
    -    'ttsbegin',
    -    'ttscommit',
    -    'unchecked',
    -    'update_recordset',
    -    'using',
    -    'validtimestate',
    -    'void',
    -    'where',
    -    'while'
    -  ];
    -
    -  const KEYWORDS = {
    -    keyword: NORMAL_KEYWORDS,
    -    built_in: BUILT_IN_KEYWORDS,
    -    literal: LITERAL_KEYWORDS
    -  };
    -
    -  return {
    -    name: 'X++',
    -    aliases: ['x++'],
    -    keywords: KEYWORDS,
    -    contains: [
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.C_NUMBER_MODE,
    -      {
    -        className: 'meta',
    -        begin: '#',
    -        end: '$'
    -      },
    -      {
    -        className: 'class',
    -        beginKeywords: 'class interface',
    -        end: /\{/,
    -        excludeEnd: true,
    -        illegal: ':',
    -        contains: [
    -          {
    -            beginKeywords: 'extends implements'
    -          },
    -          hljs.UNDERSCORE_TITLE_MODE
    -        ]
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = axapta;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/bash.js b/claude-code-source/node_modules/highlight.js/lib/languages/bash.js
    deleted file mode 100644
    index bfbf4d15..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/bash.js
    +++ /dev/null
    @@ -1,169 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: Bash
    -Author: vah 
    -Contributrors: Benjamin Pannell 
    -Website: https://www.gnu.org/software/bash/
    -Category: common
    -*/
    -
    -/** @type LanguageFn */
    -function bash(hljs) {
    -  const VAR = {};
    -  const BRACED_VAR = {
    -    begin: /\$\{/,
    -    end:/\}/,
    -    contains: [
    -      "self",
    -      {
    -        begin: /:-/,
    -        contains: [ VAR ]
    -      } // default values
    -    ]
    -  };
    -  Object.assign(VAR,{
    -    className: 'variable',
    -    variants: [
    -      {begin: concat(/\$[\w\d#@][\w\d_]*/,
    -        // negative look-ahead tries to avoid matching patterns that are not
    -        // Perl at all like $ident$, @ident@, etc.
    -        `(?![\\w\\d])(?![$])`) },
    -      BRACED_VAR
    -    ]
    -  });
    -
    -  const SUBST = {
    -    className: 'subst',
    -    begin: /\$\(/, end: /\)/,
    -    contains: [hljs.BACKSLASH_ESCAPE]
    -  };
    -  const HERE_DOC = {
    -    begin: /<<-?\s*(?=\w+)/,
    -    starts: {
    -      contains: [
    -        hljs.END_SAME_AS_BEGIN({
    -          begin: /(\w+)/,
    -          end: /(\w+)/,
    -          className: 'string'
    -        })
    -      ]
    -    }
    -  };
    -  const QUOTE_STRING = {
    -    className: 'string',
    -    begin: /"/, end: /"/,
    -    contains: [
    -      hljs.BACKSLASH_ESCAPE,
    -      VAR,
    -      SUBST
    -    ]
    -  };
    -  SUBST.contains.push(QUOTE_STRING);
    -  const ESCAPED_QUOTE = {
    -    className: '',
    -    begin: /\\"/
    -
    -  };
    -  const APOS_STRING = {
    -    className: 'string',
    -    begin: /'/, end: /'/
    -  };
    -  const ARITHMETIC = {
    -    begin: /\$\(\(/,
    -    end: /\)\)/,
    -    contains: [
    -      { begin: /\d+#[0-9a-f]+/, className: "number" },
    -      hljs.NUMBER_MODE,
    -      VAR
    -    ]
    -  };
    -  const SH_LIKE_SHELLS = [
    -    "fish",
    -    "bash",
    -    "zsh",
    -    "sh",
    -    "csh",
    -    "ksh",
    -    "tcsh",
    -    "dash",
    -    "scsh",
    -  ];
    -  const KNOWN_SHEBANG = hljs.SHEBANG({
    -    binary: `(${SH_LIKE_SHELLS.join("|")})`,
    -    relevance: 10
    -  });
    -  const FUNCTION = {
    -    className: 'function',
    -    begin: /\w[\w\d_]*\s*\(\s*\)\s*\{/,
    -    returnBegin: true,
    -    contains: [hljs.inherit(hljs.TITLE_MODE, {begin: /\w[\w\d_]*/})],
    -    relevance: 0
    -  };
    -
    -  return {
    -    name: 'Bash',
    -    aliases: ['sh', 'zsh'],
    -    keywords: {
    -      $pattern: /\b[a-z._-]+\b/,
    -      keyword:
    -        'if then else elif fi for while in do done case esac function',
    -      literal:
    -        'true false',
    -      built_in:
    -        // Shell built-ins
    -        // http://www.gnu.org/software/bash/manual/html_node/Shell-Builtin-Commands.html
    -        'break cd continue eval exec exit export getopts hash pwd readonly return shift test times ' +
    -        'trap umask unset ' +
    -        // Bash built-ins
    -        'alias bind builtin caller command declare echo enable help let local logout mapfile printf ' +
    -        'read readarray source type typeset ulimit unalias ' +
    -        // Shell modifiers
    -        'set shopt ' +
    -        // Zsh built-ins
    -        'autoload bg bindkey bye cap chdir clone comparguments compcall compctl compdescribe compfiles ' +
    -        'compgroups compquote comptags comptry compvalues dirs disable disown echotc echoti emulate ' +
    -        'fc fg float functions getcap getln history integer jobs kill limit log noglob popd print ' +
    -        'pushd pushln rehash sched setcap setopt stat suspend ttyctl unfunction unhash unlimit ' +
    -        'unsetopt vared wait whence where which zcompile zformat zftp zle zmodload zparseopts zprof ' +
    -        'zpty zregexparse zsocket zstyle ztcp'
    -    },
    -    contains: [
    -      KNOWN_SHEBANG, // to catch known shells and boost relevancy
    -      hljs.SHEBANG(), // to catch unknown shells but still highlight the shebang
    -      FUNCTION,
    -      ARITHMETIC,
    -      hljs.HASH_COMMENT_MODE,
    -      HERE_DOC,
    -      QUOTE_STRING,
    -      ESCAPED_QUOTE,
    -      APOS_STRING,
    -      VAR
    -    ]
    -  };
    -}
    -
    -module.exports = bash;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/basic.js b/claude-code-source/node_modules/highlight.js/lib/languages/basic.js
    deleted file mode 100644
    index 75442b99..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/basic.js
    +++ /dev/null
    @@ -1,65 +0,0 @@
    -/*
    -Language: BASIC
    -Author: Raphaël Assénat 
    -Description: Based on the BASIC reference from the Tandy 1000 guide
    -Website: https://en.wikipedia.org/wiki/Tandy_1000
    -*/
    -
    -/** @type LanguageFn */
    -function basic(hljs) {
    -  return {
    -    name: 'BASIC',
    -    case_insensitive: true,
    -    illegal: '^\.',
    -    // Support explicitly typed variables that end with $%! or #.
    -    keywords: {
    -      $pattern: '[a-zA-Z][a-zA-Z0-9_$%!#]*',
    -      keyword:
    -        'ABS ASC AND ATN AUTO|0 BEEP BLOAD|10 BSAVE|10 CALL CALLS CDBL CHAIN CHDIR CHR$|10 CINT CIRCLE ' +
    -        'CLEAR CLOSE CLS COLOR COM COMMON CONT COS CSNG CSRLIN CVD CVI CVS DATA DATE$ ' +
    -        'DEFDBL DEFINT DEFSNG DEFSTR DEF|0 SEG USR DELETE DIM DRAW EDIT END ENVIRON ENVIRON$ ' +
    -        'EOF EQV ERASE ERDEV ERDEV$ ERL ERR ERROR EXP FIELD FILES FIX FOR|0 FRE GET GOSUB|10 GOTO ' +
    -        'HEX$ IF THEN ELSE|0 INKEY$ INP INPUT INPUT# INPUT$ INSTR IMP INT IOCTL IOCTL$ KEY ON ' +
    -        'OFF LIST KILL LEFT$ LEN LET LINE LLIST LOAD LOC LOCATE LOF LOG LPRINT USING LSET ' +
    -        'MERGE MID$ MKDIR MKD$ MKI$ MKS$ MOD NAME NEW NEXT NOISE NOT OCT$ ON OR PEN PLAY STRIG OPEN OPTION ' +
    -        'BASE OUT PAINT PALETTE PCOPY PEEK PMAP POINT POKE POS PRINT PRINT] PSET PRESET ' +
    -        'PUT RANDOMIZE READ REM RENUM RESET|0 RESTORE RESUME RETURN|0 RIGHT$ RMDIR RND RSET ' +
    -        'RUN SAVE SCREEN SGN SHELL SIN SOUND SPACE$ SPC SQR STEP STICK STOP STR$ STRING$ SWAP ' +
    -        'SYSTEM TAB TAN TIME$ TIMER TROFF TRON TO USR VAL VARPTR VARPTR$ VIEW WAIT WHILE ' +
    -        'WEND WIDTH WINDOW WRITE XOR'
    -    },
    -    contains: [
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.COMMENT('REM', '$', {
    -        relevance: 10
    -      }),
    -      hljs.COMMENT('\'', '$', {
    -        relevance: 0
    -      }),
    -      {
    -        // Match line numbers
    -        className: 'symbol',
    -        begin: '^[0-9]+ ',
    -        relevance: 10
    -      },
    -      {
    -        // Match typed numeric constants (1000, 12.34!, 1.2e5, 1.5#, 1.2D2)
    -        className: 'number',
    -        begin: '\\b\\d+(\\.\\d+)?([edED]\\d+)?[#\!]?',
    -        relevance: 0
    -      },
    -      {
    -        // Match hexadecimal numbers (&Hxxxx)
    -        className: 'number',
    -        begin: '(&[hH][0-9a-fA-F]{1,4})'
    -      },
    -      {
    -        // Match octal numbers (&Oxxxxxx)
    -        className: 'number',
    -        begin: '(&[oO][0-7]{1,6})'
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = basic;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/bnf.js b/claude-code-source/node_modules/highlight.js/lib/languages/bnf.js
    deleted file mode 100644
    index 5c8673cc..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/bnf.js
    +++ /dev/null
    @@ -1,38 +0,0 @@
    -/*
    -Language: Backus–Naur Form
    -Website: https://en.wikipedia.org/wiki/Backus–Naur_form
    -Author: Oleg Efimov 
    -*/
    -
    -/** @type LanguageFn */
    -function bnf(hljs) {
    -  return {
    -    name: 'Backus–Naur Form',
    -    contains: [
    -      // Attribute
    -      {
    -        className: 'attribute',
    -        begin: //
    -      },
    -      // Specific
    -      {
    -        begin: /::=/,
    -        end: /$/,
    -        contains: [
    -          {
    -            begin: //
    -          },
    -          // Common
    -          hljs.C_LINE_COMMENT_MODE,
    -          hljs.C_BLOCK_COMMENT_MODE,
    -          hljs.APOS_STRING_MODE,
    -          hljs.QUOTE_STRING_MODE
    -        ]
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = bnf;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/brainfuck.js b/claude-code-source/node_modules/highlight.js/lib/languages/brainfuck.js
    deleted file mode 100644
    index 3726b99c..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/brainfuck.js
    +++ /dev/null
    @@ -1,46 +0,0 @@
    -/*
    -Language: Brainfuck
    -Author: Evgeny Stepanischev 
    -Website: https://esolangs.org/wiki/Brainfuck
    -*/
    -
    -/** @type LanguageFn */
    -function brainfuck(hljs) {
    -  const LITERAL = {
    -    className: 'literal',
    -    begin: /[+-]/,
    -    relevance: 0
    -  };
    -  return {
    -    name: 'Brainfuck',
    -    aliases: ['bf'],
    -    contains: [
    -      hljs.COMMENT(
    -        '[^\\[\\]\\.,\\+\\-<> \r\n]',
    -        '[\\[\\]\\.,\\+\\-<> \r\n]',
    -        {
    -          returnEnd: true,
    -          relevance: 0
    -        }
    -      ),
    -      {
    -        className: 'title',
    -        begin: '[\\[\\]]',
    -        relevance: 0
    -      },
    -      {
    -        className: 'string',
    -        begin: '[\\.,]',
    -        relevance: 0
    -      },
    -      {
    -        // this mode works as the only relevance counter
    -        begin: /(?:\+\+|--)/,
    -        contains: [LITERAL]
    -      },
    -      LITERAL
    -    ]
    -  };
    -}
    -
    -module.exports = brainfuck;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/c-like.js b/claude-code-source/node_modules/highlight.js/lib/languages/c-like.js
    deleted file mode 100644
    index 9639d476..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/c-like.js
    +++ /dev/null
    @@ -1,501 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function lookahead(re) {
    -  return concat('(?=', re, ')');
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function optional(re) {
    -  return concat('(', re, ')?');
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: C++
    -Category: common, system
    -Website: https://isocpp.org
    -*/
    -
    -/** @type LanguageFn */
    -function cPlusPlus(hljs) {
    -  // added for historic reasons because `hljs.C_LINE_COMMENT_MODE` does
    -  // not include such support nor can we be sure all the grammars depending
    -  // on it would desire this behavior
    -  const C_LINE_COMMENT_MODE = hljs.COMMENT('//', '$', {
    -    contains: [
    -      {
    -        begin: /\\\n/
    -      }
    -    ]
    -  });
    -  const DECLTYPE_AUTO_RE = 'decltype\\(auto\\)';
    -  const NAMESPACE_RE = '[a-zA-Z_]\\w*::';
    -  const TEMPLATE_ARGUMENT_RE = '<[^<>]+>';
    -  const FUNCTION_TYPE_RE = '(' +
    -    DECLTYPE_AUTO_RE + '|' +
    -    optional(NAMESPACE_RE) +
    -    '[a-zA-Z_]\\w*' + optional(TEMPLATE_ARGUMENT_RE) +
    -  ')';
    -  const CPP_PRIMITIVE_TYPES = {
    -    className: 'keyword',
    -    begin: '\\b[a-z\\d_]*_t\\b'
    -  };
    -
    -  // https://en.cppreference.com/w/cpp/language/escape
    -  // \\ \x \xFF \u2837 \u00323747 \374
    -  const CHARACTER_ESCAPES = '\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)';
    -  const STRINGS = {
    -    className: 'string',
    -    variants: [
    -      {
    -        begin: '(u8?|U|L)?"',
    -        end: '"',
    -        illegal: '\\n',
    -        contains: [ hljs.BACKSLASH_ESCAPE ]
    -      },
    -      {
    -        begin: '(u8?|U|L)?\'(' + CHARACTER_ESCAPES + "|.)",
    -        end: '\'',
    -        illegal: '.'
    -      },
    -      hljs.END_SAME_AS_BEGIN({
    -        begin: /(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,
    -        end: /\)([^()\\ ]{0,16})"/
    -      })
    -    ]
    -  };
    -
    -  const NUMBERS = {
    -    className: 'number',
    -    variants: [
    -      {
    -        begin: '\\b(0b[01\']+)'
    -      },
    -      {
    -        begin: '(-?)\\b([\\d\']+(\\.[\\d\']*)?|\\.[\\d\']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)'
    -      },
    -      {
    -        begin: '(-?)(\\b0[xX][a-fA-F0-9\']+|(\\b[\\d\']+(\\.[\\d\']*)?|\\.[\\d\']+)([eE][-+]?[\\d\']+)?)'
    -      }
    -    ],
    -    relevance: 0
    -  };
    -
    -  const PREPROCESSOR = {
    -    className: 'meta',
    -    begin: /#\s*[a-z]+\b/,
    -    end: /$/,
    -    keywords: {
    -      'meta-keyword':
    -        'if else elif endif define undef warning error line ' +
    -        'pragma _Pragma ifdef ifndef include'
    -    },
    -    contains: [
    -      {
    -        begin: /\\\n/,
    -        relevance: 0
    -      },
    -      hljs.inherit(STRINGS, {
    -        className: 'meta-string'
    -      }),
    -      {
    -        className: 'meta-string',
    -        begin: /<.*?>/
    -      },
    -      C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE
    -    ]
    -  };
    -
    -  const TITLE_MODE = {
    -    className: 'title',
    -    begin: optional(NAMESPACE_RE) + hljs.IDENT_RE,
    -    relevance: 0
    -  };
    -
    -  const FUNCTION_TITLE = optional(NAMESPACE_RE) + hljs.IDENT_RE + '\\s*\\(';
    -
    -  const COMMON_CPP_HINTS = [
    -    'asin',
    -    'atan2',
    -    'atan',
    -    'calloc',
    -    'ceil',
    -    'cosh',
    -    'cos',
    -    'exit',
    -    'exp',
    -    'fabs',
    -    'floor',
    -    'fmod',
    -    'fprintf',
    -    'fputs',
    -    'free',
    -    'frexp',
    -    'auto_ptr',
    -    'deque',
    -    'list',
    -    'queue',
    -    'stack',
    -    'vector',
    -    'map',
    -    'set',
    -    'pair',
    -    'bitset',
    -    'multiset',
    -    'multimap',
    -    'unordered_set',
    -    'fscanf',
    -    'future',
    -    'isalnum',
    -    'isalpha',
    -    'iscntrl',
    -    'isdigit',
    -    'isgraph',
    -    'islower',
    -    'isprint',
    -    'ispunct',
    -    'isspace',
    -    'isupper',
    -    'isxdigit',
    -    'tolower',
    -    'toupper',
    -    'labs',
    -    'ldexp',
    -    'log10',
    -    'log',
    -    'malloc',
    -    'realloc',
    -    'memchr',
    -    'memcmp',
    -    'memcpy',
    -    'memset',
    -    'modf',
    -    'pow',
    -    'printf',
    -    'putchar',
    -    'puts',
    -    'scanf',
    -    'sinh',
    -    'sin',
    -    'snprintf',
    -    'sprintf',
    -    'sqrt',
    -    'sscanf',
    -    'strcat',
    -    'strchr',
    -    'strcmp',
    -    'strcpy',
    -    'strcspn',
    -    'strlen',
    -    'strncat',
    -    'strncmp',
    -    'strncpy',
    -    'strpbrk',
    -    'strrchr',
    -    'strspn',
    -    'strstr',
    -    'tanh',
    -    'tan',
    -    'unordered_map',
    -    'unordered_multiset',
    -    'unordered_multimap',
    -    'priority_queue',
    -    'make_pair',
    -    'array',
    -    'shared_ptr',
    -    'abort',
    -    'terminate',
    -    'abs',
    -    'acos',
    -    'vfprintf',
    -    'vprintf',
    -    'vsprintf',
    -    'endl',
    -    'initializer_list',
    -    'unique_ptr',
    -    'complex',
    -    'imaginary',
    -    'std',
    -    'string',
    -    'wstring',
    -    'cin',
    -    'cout',
    -    'cerr',
    -    'clog',
    -    'stdin',
    -    'stdout',
    -    'stderr',
    -    'stringstream',
    -    'istringstream',
    -    'ostringstream'
    -  ];
    -
    -  const CPP_KEYWORDS = {
    -    keyword: 'int float while private char char8_t char16_t char32_t catch import module export virtual operator sizeof ' +
    -      'dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace ' +
    -      'unsigned long volatile static protected bool template mutable if public friend ' +
    -      'do goto auto void enum else break extern using asm case typeid wchar_t ' +
    -      'short reinterpret_cast|10 default double register explicit signed typename try this ' +
    -      'switch continue inline delete alignas alignof constexpr consteval constinit decltype ' +
    -      'concept co_await co_return co_yield requires ' +
    -      'noexcept static_assert thread_local restrict final override ' +
    -      'atomic_bool atomic_char atomic_schar ' +
    -      'atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong ' +
    -      'atomic_ullong new throw return ' +
    -      'and and_eq bitand bitor compl not not_eq or or_eq xor xor_eq',
    -    built_in: '_Bool _Complex _Imaginary',
    -    _relevance_hints: COMMON_CPP_HINTS,
    -    literal: 'true false nullptr NULL'
    -  };
    -
    -  const FUNCTION_DISPATCH = {
    -    className: "function.dispatch",
    -    relevance: 0,
    -    keywords: CPP_KEYWORDS,
    -    begin: concat(
    -      /\b/,
    -      /(?!decltype)/,
    -      /(?!if)/,
    -      /(?!for)/,
    -      /(?!while)/,
    -      hljs.IDENT_RE,
    -      lookahead(/\s*\(/))
    -  };
    -
    -  const EXPRESSION_CONTAINS = [
    -    FUNCTION_DISPATCH,
    -    PREPROCESSOR,
    -    CPP_PRIMITIVE_TYPES,
    -    C_LINE_COMMENT_MODE,
    -    hljs.C_BLOCK_COMMENT_MODE,
    -    NUMBERS,
    -    STRINGS
    -  ];
    -
    -
    -  const EXPRESSION_CONTEXT = {
    -    // This mode covers expression context where we can't expect a function
    -    // definition and shouldn't highlight anything that looks like one:
    -    // `return some()`, `else if()`, `(x*sum(1, 2))`
    -    variants: [
    -      {
    -        begin: /=/,
    -        end: /;/
    -      },
    -      {
    -        begin: /\(/,
    -        end: /\)/
    -      },
    -      {
    -        beginKeywords: 'new throw return else',
    -        end: /;/
    -      }
    -    ],
    -    keywords: CPP_KEYWORDS,
    -    contains: EXPRESSION_CONTAINS.concat([
    -      {
    -        begin: /\(/,
    -        end: /\)/,
    -        keywords: CPP_KEYWORDS,
    -        contains: EXPRESSION_CONTAINS.concat([ 'self' ]),
    -        relevance: 0
    -      }
    -    ]),
    -    relevance: 0
    -  };
    -
    -  const FUNCTION_DECLARATION = {
    -    className: 'function',
    -    begin: '(' + FUNCTION_TYPE_RE + '[\\*&\\s]+)+' + FUNCTION_TITLE,
    -    returnBegin: true,
    -    end: /[{;=]/,
    -    excludeEnd: true,
    -    keywords: CPP_KEYWORDS,
    -    illegal: /[^\w\s\*&:<>.]/,
    -    contains: [
    -      { // to prevent it from being confused as the function title
    -        begin: DECLTYPE_AUTO_RE,
    -        keywords: CPP_KEYWORDS,
    -        relevance: 0
    -      },
    -      {
    -        begin: FUNCTION_TITLE,
    -        returnBegin: true,
    -        contains: [ TITLE_MODE ],
    -        relevance: 0
    -      },
    -      // needed because we do not have look-behind on the below rule
    -      // to prevent it from grabbing the final : in a :: pair
    -      {
    -        begin: /::/,
    -        relevance: 0
    -      },
    -      // initializers
    -      {
    -        begin: /:/,
    -        endsWithParent: true,
    -        contains: [
    -          STRINGS,
    -          NUMBERS
    -        ]
    -      },
    -      {
    -        className: 'params',
    -        begin: /\(/,
    -        end: /\)/,
    -        keywords: CPP_KEYWORDS,
    -        relevance: 0,
    -        contains: [
    -          C_LINE_COMMENT_MODE,
    -          hljs.C_BLOCK_COMMENT_MODE,
    -          STRINGS,
    -          NUMBERS,
    -          CPP_PRIMITIVE_TYPES,
    -          // Count matching parentheses.
    -          {
    -            begin: /\(/,
    -            end: /\)/,
    -            keywords: CPP_KEYWORDS,
    -            relevance: 0,
    -            contains: [
    -              'self',
    -              C_LINE_COMMENT_MODE,
    -              hljs.C_BLOCK_COMMENT_MODE,
    -              STRINGS,
    -              NUMBERS,
    -              CPP_PRIMITIVE_TYPES
    -            ]
    -          }
    -        ]
    -      },
    -      CPP_PRIMITIVE_TYPES,
    -      C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      PREPROCESSOR
    -    ]
    -  };
    -
    -  return {
    -    name: 'C++',
    -    aliases: [
    -      'cc',
    -      'c++',
    -      'h++',
    -      'hpp',
    -      'hh',
    -      'hxx',
    -      'cxx'
    -    ],
    -    keywords: CPP_KEYWORDS,
    -    illegal: ' rooms (9);`
    -          begin: '\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<',
    -          end: '>',
    -          keywords: CPP_KEYWORDS,
    -          contains: [
    -            'self',
    -            CPP_PRIMITIVE_TYPES
    -          ]
    -        },
    -        {
    -          begin: hljs.IDENT_RE + '::',
    -          keywords: CPP_KEYWORDS
    -        },
    -        {
    -          className: 'class',
    -          beginKeywords: 'enum class struct union',
    -          end: /[{;:<>=]/,
    -          contains: [
    -            {
    -              beginKeywords: "final class struct"
    -            },
    -            hljs.TITLE_MODE
    -          ]
    -        }
    -      ]),
    -    exports: {
    -      preprocessor: PREPROCESSOR,
    -      strings: STRINGS,
    -      keywords: CPP_KEYWORDS
    -    }
    -  };
    -}
    -
    -/*
    -Language: C-like (deprecated, use C and C++ instead)
    -Author: Ivan Sagalaev 
    -Contributors: Evgeny Stepanischev , Zaven Muradyan , Roel Deckers , Sam Wu , Jordi Petit , Pieter Vantorre , Google Inc. (David Benjamin) 
    -*/
    -
    -/** @type LanguageFn */
    -function cLike(hljs) {
    -  const lang = cPlusPlus(hljs);
    -
    -  const C_ALIASES = [
    -    "c",
    -    "h"
    -  ];
    -
    -  const CPP_ALIASES = [
    -    'cc',
    -    'c++',
    -    'h++',
    -    'hpp',
    -    'hh',
    -    'hxx',
    -    'cxx'
    -  ];
    -
    -  lang.disableAutodetect = true;
    -  lang.aliases = [];
    -  // support users only loading c-like (legacy)
    -  if (!hljs.getLanguage("c")) lang.aliases.push(...C_ALIASES);
    -  if (!hljs.getLanguage("cpp")) lang.aliases.push(...CPP_ALIASES);
    -
    -  // if c and cpp are loaded after then they will reclaim these
    -  // aliases for themselves
    -
    -  return lang;
    -}
    -
    -module.exports = cLike;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/c.js b/claude-code-source/node_modules/highlight.js/lib/languages/c.js
    deleted file mode 100644
    index d7271088..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/c.js
    +++ /dev/null
    @@ -1,309 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function optional(re) {
    -  return concat('(', re, ')?');
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: C
    -Category: common, system
    -Website: https://en.wikipedia.org/wiki/C_(programming_language)
    -*/
    -
    -/** @type LanguageFn */
    -function c(hljs) {
    -  // added for historic reasons because `hljs.C_LINE_COMMENT_MODE` does
    -  // not include such support nor can we be sure all the grammars depending
    -  // on it would desire this behavior
    -  const C_LINE_COMMENT_MODE = hljs.COMMENT('//', '$', {
    -    contains: [
    -      {
    -        begin: /\\\n/
    -      }
    -    ]
    -  });
    -  const DECLTYPE_AUTO_RE = 'decltype\\(auto\\)';
    -  const NAMESPACE_RE = '[a-zA-Z_]\\w*::';
    -  const TEMPLATE_ARGUMENT_RE = '<[^<>]+>';
    -  const FUNCTION_TYPE_RE = '(' +
    -    DECLTYPE_AUTO_RE + '|' +
    -    optional(NAMESPACE_RE) +
    -    '[a-zA-Z_]\\w*' + optional(TEMPLATE_ARGUMENT_RE) +
    -  ')';
    -  const CPP_PRIMITIVE_TYPES = {
    -    className: 'keyword',
    -    begin: '\\b[a-z\\d_]*_t\\b'
    -  };
    -
    -  // https://en.cppreference.com/w/cpp/language/escape
    -  // \\ \x \xFF \u2837 \u00323747 \374
    -  const CHARACTER_ESCAPES = '\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)';
    -  const STRINGS = {
    -    className: 'string',
    -    variants: [
    -      {
    -        begin: '(u8?|U|L)?"',
    -        end: '"',
    -        illegal: '\\n',
    -        contains: [ hljs.BACKSLASH_ESCAPE ]
    -      },
    -      {
    -        begin: '(u8?|U|L)?\'(' + CHARACTER_ESCAPES + "|.)",
    -        end: '\'',
    -        illegal: '.'
    -      },
    -      hljs.END_SAME_AS_BEGIN({
    -        begin: /(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,
    -        end: /\)([^()\\ ]{0,16})"/
    -      })
    -    ]
    -  };
    -
    -  const NUMBERS = {
    -    className: 'number',
    -    variants: [
    -      {
    -        begin: '\\b(0b[01\']+)'
    -      },
    -      {
    -        begin: '(-?)\\b([\\d\']+(\\.[\\d\']*)?|\\.[\\d\']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)'
    -      },
    -      {
    -        begin: '(-?)(\\b0[xX][a-fA-F0-9\']+|(\\b[\\d\']+(\\.[\\d\']*)?|\\.[\\d\']+)([eE][-+]?[\\d\']+)?)'
    -      }
    -    ],
    -    relevance: 0
    -  };
    -
    -  const PREPROCESSOR = {
    -    className: 'meta',
    -    begin: /#\s*[a-z]+\b/,
    -    end: /$/,
    -    keywords: {
    -      'meta-keyword':
    -        'if else elif endif define undef warning error line ' +
    -        'pragma _Pragma ifdef ifndef include'
    -    },
    -    contains: [
    -      {
    -        begin: /\\\n/,
    -        relevance: 0
    -      },
    -      hljs.inherit(STRINGS, {
    -        className: 'meta-string'
    -      }),
    -      {
    -        className: 'meta-string',
    -        begin: /<.*?>/
    -      },
    -      C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE
    -    ]
    -  };
    -
    -  const TITLE_MODE = {
    -    className: 'title',
    -    begin: optional(NAMESPACE_RE) + hljs.IDENT_RE,
    -    relevance: 0
    -  };
    -
    -  const FUNCTION_TITLE = optional(NAMESPACE_RE) + hljs.IDENT_RE + '\\s*\\(';
    -
    -  const CPP_KEYWORDS = {
    -    keyword: 'int float while private char char8_t char16_t char32_t catch import module export virtual operator sizeof ' +
    -      'dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace ' +
    -      'unsigned long volatile static protected bool template mutable if public friend ' +
    -      'do goto auto void enum else break extern using asm case typeid wchar_t ' +
    -      'short reinterpret_cast|10 default double register explicit signed typename try this ' +
    -      'switch continue inline delete alignas alignof constexpr consteval constinit decltype ' +
    -      'concept co_await co_return co_yield requires ' +
    -      'noexcept static_assert thread_local restrict final override ' +
    -      'atomic_bool atomic_char atomic_schar ' +
    -      'atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong ' +
    -      'atomic_ullong new throw return ' +
    -      'and and_eq bitand bitor compl not not_eq or or_eq xor xor_eq',
    -    built_in: 'std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream ' +
    -      'auto_ptr deque list queue stack vector map set pair bitset multiset multimap unordered_set ' +
    -      'unordered_map unordered_multiset unordered_multimap priority_queue make_pair array shared_ptr abort terminate abs acos ' +
    -      'asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp ' +
    -      'fscanf future isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper ' +
    -      'isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow ' +
    -      'printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp ' +
    -      'strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan ' +
    -      'vfprintf vprintf vsprintf endl initializer_list unique_ptr _Bool complex _Complex imaginary _Imaginary',
    -    literal: 'true false nullptr NULL'
    -  };
    -
    -  const EXPRESSION_CONTAINS = [
    -    PREPROCESSOR,
    -    CPP_PRIMITIVE_TYPES,
    -    C_LINE_COMMENT_MODE,
    -    hljs.C_BLOCK_COMMENT_MODE,
    -    NUMBERS,
    -    STRINGS
    -  ];
    -
    -  const EXPRESSION_CONTEXT = {
    -    // This mode covers expression context where we can't expect a function
    -    // definition and shouldn't highlight anything that looks like one:
    -    // `return some()`, `else if()`, `(x*sum(1, 2))`
    -    variants: [
    -      {
    -        begin: /=/,
    -        end: /;/
    -      },
    -      {
    -        begin: /\(/,
    -        end: /\)/
    -      },
    -      {
    -        beginKeywords: 'new throw return else',
    -        end: /;/
    -      }
    -    ],
    -    keywords: CPP_KEYWORDS,
    -    contains: EXPRESSION_CONTAINS.concat([
    -      {
    -        begin: /\(/,
    -        end: /\)/,
    -        keywords: CPP_KEYWORDS,
    -        contains: EXPRESSION_CONTAINS.concat([ 'self' ]),
    -        relevance: 0
    -      }
    -    ]),
    -    relevance: 0
    -  };
    -
    -  const FUNCTION_DECLARATION = {
    -    className: 'function',
    -    begin: '(' + FUNCTION_TYPE_RE + '[\\*&\\s]+)+' + FUNCTION_TITLE,
    -    returnBegin: true,
    -    end: /[{;=]/,
    -    excludeEnd: true,
    -    keywords: CPP_KEYWORDS,
    -    illegal: /[^\w\s\*&:<>.]/,
    -    contains: [
    -      { // to prevent it from being confused as the function title
    -        begin: DECLTYPE_AUTO_RE,
    -        keywords: CPP_KEYWORDS,
    -        relevance: 0
    -      },
    -      {
    -        begin: FUNCTION_TITLE,
    -        returnBegin: true,
    -        contains: [ TITLE_MODE ],
    -        relevance: 0
    -      },
    -      {
    -        className: 'params',
    -        begin: /\(/,
    -        end: /\)/,
    -        keywords: CPP_KEYWORDS,
    -        relevance: 0,
    -        contains: [
    -          C_LINE_COMMENT_MODE,
    -          hljs.C_BLOCK_COMMENT_MODE,
    -          STRINGS,
    -          NUMBERS,
    -          CPP_PRIMITIVE_TYPES,
    -          // Count matching parentheses.
    -          {
    -            begin: /\(/,
    -            end: /\)/,
    -            keywords: CPP_KEYWORDS,
    -            relevance: 0,
    -            contains: [
    -              'self',
    -              C_LINE_COMMENT_MODE,
    -              hljs.C_BLOCK_COMMENT_MODE,
    -              STRINGS,
    -              NUMBERS,
    -              CPP_PRIMITIVE_TYPES
    -            ]
    -          }
    -        ]
    -      },
    -      CPP_PRIMITIVE_TYPES,
    -      C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      PREPROCESSOR
    -    ]
    -  };
    -
    -  return {
    -    name: "C",
    -    aliases: [
    -      'h'
    -    ],
    -    keywords: CPP_KEYWORDS,
    -    // Until differentiations are added between `c` and `cpp`, `c` will
    -    // not be auto-detected to avoid auto-detect conflicts between C and C++
    -    disableAutodetect: true,
    -    illegal: ' rooms (9);`
    -          begin: '\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<',
    -          end: '>',
    -          keywords: CPP_KEYWORDS,
    -          contains: [
    -            'self',
    -            CPP_PRIMITIVE_TYPES
    -          ]
    -        },
    -        {
    -          begin: hljs.IDENT_RE + '::',
    -          keywords: CPP_KEYWORDS
    -        },
    -        {
    -          className: 'class',
    -          beginKeywords: 'enum class struct union',
    -          end: /[{;:<>=]/,
    -          contains: [
    -            {
    -              beginKeywords: "final class struct"
    -            },
    -            hljs.TITLE_MODE
    -          ]
    -        }
    -      ]),
    -    exports: {
    -      preprocessor: PREPROCESSOR,
    -      strings: STRINGS,
    -      keywords: CPP_KEYWORDS
    -    }
    -  };
    -}
    -
    -module.exports = c;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/cal.js b/claude-code-source/node_modules/highlight.js/lib/languages/cal.js
    deleted file mode 100644
    index 0cb44a36..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/cal.js
    +++ /dev/null
    @@ -1,104 +0,0 @@
    -/*
    -Language: C/AL
    -Author: Kenneth Fuglsang Christensen 
    -Description: Provides highlighting of Microsoft Dynamics NAV C/AL code files
    -Website: https://docs.microsoft.com/en-us/dynamics-nav/programming-in-c-al
    -*/
    -
    -/** @type LanguageFn */
    -function cal(hljs) {
    -  const KEYWORDS =
    -    'div mod in and or not xor asserterror begin case do downto else end exit for if of repeat then to ' +
    -    'until while with var';
    -  const LITERALS = 'false true';
    -  const COMMENT_MODES = [
    -    hljs.C_LINE_COMMENT_MODE,
    -    hljs.COMMENT(
    -      /\{/,
    -      /\}/,
    -      {
    -        relevance: 0
    -      }
    -    ),
    -    hljs.COMMENT(
    -      /\(\*/,
    -      /\*\)/,
    -      {
    -        relevance: 10
    -      }
    -    )
    -  ];
    -  const STRING = {
    -    className: 'string',
    -    begin: /'/,
    -    end: /'/,
    -    contains: [{
    -      begin: /''/
    -    }]
    -  };
    -  const CHAR_STRING = {
    -    className: 'string',
    -    begin: /(#\d+)+/
    -  };
    -  const DATE = {
    -    className: 'number',
    -    begin: '\\b\\d+(\\.\\d+)?(DT|D|T)',
    -    relevance: 0
    -  };
    -  const DBL_QUOTED_VARIABLE = {
    -    className: 'string', // not a string technically but makes sense to be highlighted in the same style
    -    begin: '"',
    -    end: '"'
    -  };
    -
    -  const PROCEDURE = {
    -    className: 'function',
    -    beginKeywords: 'procedure',
    -    end: /[:;]/,
    -    keywords: 'procedure|10',
    -    contains: [
    -      hljs.TITLE_MODE,
    -      {
    -        className: 'params',
    -        begin: /\(/,
    -        end: /\)/,
    -        keywords: KEYWORDS,
    -        contains: [
    -          STRING,
    -          CHAR_STRING
    -        ]
    -      }
    -    ].concat(COMMENT_MODES)
    -  };
    -
    -  const OBJECT = {
    -    className: 'class',
    -    begin: 'OBJECT (Table|Form|Report|Dataport|Codeunit|XMLport|MenuSuite|Page|Query) (\\d+) ([^\\r\\n]+)',
    -    returnBegin: true,
    -    contains: [
    -      hljs.TITLE_MODE,
    -      PROCEDURE
    -    ]
    -  };
    -
    -  return {
    -    name: 'C/AL',
    -    case_insensitive: true,
    -    keywords: {
    -      keyword: KEYWORDS,
    -      literal: LITERALS
    -    },
    -    illegal: /\/\*/,
    -    contains: [
    -      STRING,
    -      CHAR_STRING,
    -      DATE,
    -      DBL_QUOTED_VARIABLE,
    -      hljs.NUMBER_MODE,
    -      OBJECT,
    -      PROCEDURE
    -    ]
    -  };
    -}
    -
    -module.exports = cal;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/capnproto.js b/claude-code-source/node_modules/highlight.js/lib/languages/capnproto.js
    deleted file mode 100644
    index 013fe6b8..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/capnproto.js
    +++ /dev/null
    @@ -1,64 +0,0 @@
    -/*
    -Language: Cap’n Proto
    -Author: Oleg Efimov 
    -Description: Cap’n Proto message definition format
    -Website: https://capnproto.org/capnp-tool.html
    -Category: protocols
    -*/
    -
    -/** @type LanguageFn */
    -function capnproto(hljs) {
    -  return {
    -    name: 'Cap’n Proto',
    -    aliases: ['capnp'],
    -    keywords: {
    -      keyword:
    -        'struct enum interface union group import using const annotation extends in of on as with from fixed',
    -      built_in:
    -        'Void Bool Int8 Int16 Int32 Int64 UInt8 UInt16 UInt32 UInt64 Float32 Float64 ' +
    -        'Text Data AnyPointer AnyStruct Capability List',
    -      literal:
    -        'true false'
    -    },
    -    contains: [
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.NUMBER_MODE,
    -      hljs.HASH_COMMENT_MODE,
    -      {
    -        className: 'meta',
    -        begin: /@0x[\w\d]{16};/,
    -        illegal: /\n/
    -      },
    -      {
    -        className: 'symbol',
    -        begin: /@\d+\b/
    -      },
    -      {
    -        className: 'class',
    -        beginKeywords: 'struct enum',
    -        end: /\{/,
    -        illegal: /\n/,
    -        contains: [hljs.inherit(hljs.TITLE_MODE, {
    -          starts: {
    -            endsWithParent: true,
    -            excludeEnd: true
    -          } // hack: eating everything after the first title
    -        })]
    -      },
    -      {
    -        className: 'class',
    -        beginKeywords: 'interface',
    -        end: /\{/,
    -        illegal: /\n/,
    -        contains: [hljs.inherit(hljs.TITLE_MODE, {
    -          starts: {
    -            endsWithParent: true,
    -            excludeEnd: true
    -          } // hack: eating everything after the first title
    -        })]
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = capnproto;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/ceylon.js b/claude-code-source/node_modules/highlight.js/lib/languages/ceylon.js
    deleted file mode 100644
    index ec62e245..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/ceylon.js
    +++ /dev/null
    @@ -1,82 +0,0 @@
    -/*
    -Language: Ceylon
    -Author: Lucas Werkmeister 
    -Website: https://ceylon-lang.org
    -*/
    -
    -/** @type LanguageFn */
    -function ceylon(hljs) {
    -  // 2.3. Identifiers and keywords
    -  const KEYWORDS =
    -    'assembly module package import alias class interface object given value ' +
    -    'assign void function new of extends satisfies abstracts in out return ' +
    -    'break continue throw assert dynamic if else switch case for while try ' +
    -    'catch finally then let this outer super is exists nonempty';
    -  // 7.4.1 Declaration Modifiers
    -  const DECLARATION_MODIFIERS =
    -    'shared abstract formal default actual variable late native deprecated ' +
    -    'final sealed annotation suppressWarnings small';
    -  // 7.4.2 Documentation
    -  const DOCUMENTATION =
    -    'doc by license see throws tagged';
    -  const SUBST = {
    -    className: 'subst',
    -    excludeBegin: true,
    -    excludeEnd: true,
    -    begin: /``/,
    -    end: /``/,
    -    keywords: KEYWORDS,
    -    relevance: 10
    -  };
    -  const EXPRESSIONS = [
    -    {
    -      // verbatim string
    -      className: 'string',
    -      begin: '"""',
    -      end: '"""',
    -      relevance: 10
    -    },
    -    {
    -      // string literal or template
    -      className: 'string',
    -      begin: '"',
    -      end: '"',
    -      contains: [SUBST]
    -    },
    -    {
    -      // character literal
    -      className: 'string',
    -      begin: "'",
    -      end: "'"
    -    },
    -    {
    -      // numeric literal
    -      className: 'number',
    -      begin: '#[0-9a-fA-F_]+|\\$[01_]+|[0-9_]+(?:\\.[0-9_](?:[eE][+-]?\\d+)?)?[kMGTPmunpf]?',
    -      relevance: 0
    -    }
    -  ];
    -  SUBST.contains = EXPRESSIONS;
    -
    -  return {
    -    name: 'Ceylon',
    -    keywords: {
    -      keyword: KEYWORDS + ' ' + DECLARATION_MODIFIERS,
    -      meta: DOCUMENTATION
    -    },
    -    illegal: '\\$[^01]|#[^0-9a-fA-F]',
    -    contains: [
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.COMMENT('/\\*', '\\*/', {
    -        contains: ['self']
    -      }),
    -      {
    -        // compiler annotation
    -        className: 'meta',
    -        begin: '@[a-z]\\w*(?::"[^"]*")?'
    -      }
    -    ].concat(EXPRESSIONS)
    -  };
    -}
    -
    -module.exports = ceylon;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/clean.js b/claude-code-source/node_modules/highlight.js/lib/languages/clean.js
    deleted file mode 100644
    index bf46cb9e..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/clean.js
    +++ /dev/null
    @@ -1,40 +0,0 @@
    -/*
    -Language: Clean
    -Author: Camil Staps 
    -Category: functional
    -Website: http://clean.cs.ru.nl
    -*/
    -
    -/** @type LanguageFn */
    -function clean(hljs) {
    -  return {
    -    name: 'Clean',
    -    aliases: [
    -      'icl',
    -      'dcl'
    -    ],
    -    keywords: {
    -      keyword:
    -        'if let in with where case of class instance otherwise ' +
    -        'implementation definition system module from import qualified as ' +
    -        'special code inline foreign export ccall stdcall generic derive ' +
    -        'infix infixl infixr',
    -      built_in:
    -        'Int Real Char Bool',
    -      literal:
    -        'True False'
    -    },
    -    contains: [
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.C_NUMBER_MODE,
    -      { // relevance booster
    -        begin: '->|<-[|:]?|#!?|>>=|\\{\\||\\|\\}|:==|=:|<>'
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = clean;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/clojure-repl.js b/claude-code-source/node_modules/highlight.js/lib/languages/clojure-repl.js
    deleted file mode 100644
    index 3e93a7ab..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/clojure-repl.js
    +++ /dev/null
    @@ -1,27 +0,0 @@
    -/*
    -Language: Clojure REPL
    -Description: Clojure REPL sessions
    -Author: Ivan Sagalaev 
    -Requires: clojure.js
    -Website: https://clojure.org
    -Category: lisp
    -*/
    -
    -/** @type LanguageFn */
    -function clojureRepl(hljs) {
    -  return {
    -    name: 'Clojure REPL',
    -    contains: [
    -      {
    -        className: 'meta',
    -        begin: /^([\w.-]+|\s*#_)?=>/,
    -        starts: {
    -          end: /$/,
    -          subLanguage: 'clojure'
    -        }
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = clojureRepl;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/clojure.js b/claude-code-source/node_modules/highlight.js/lib/languages/clojure.js
    deleted file mode 100644
    index df27efc5..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/clojure.js
    +++ /dev/null
    @@ -1,158 +0,0 @@
    -/*
    -Language: Clojure
    -Description: Clojure syntax (based on lisp.js)
    -Author: mfornos
    -Website: https://clojure.org
    -Category: lisp
    -*/
    -
    -/** @type LanguageFn */
    -function clojure(hljs) {
    -  const SYMBOLSTART = 'a-zA-Z_\\-!.?+*=<>&#\'';
    -  const SYMBOL_RE = '[' + SYMBOLSTART + '][' + SYMBOLSTART + '0-9/;:]*';
    -  const globals = 'def defonce defprotocol defstruct defmulti defmethod defn- defn defmacro deftype defrecord';
    -  const keywords = {
    -    $pattern: SYMBOL_RE,
    -    'builtin-name':
    -      // Clojure keywords
    -      globals + ' ' +
    -      'cond apply if-not if-let if not not= =|0 <|0 >|0 <=|0 >=|0 ==|0 +|0 /|0 *|0 -|0 rem ' +
    -      'quot neg? pos? delay? symbol? keyword? true? false? integer? empty? coll? list? ' +
    -      'set? ifn? fn? associative? sequential? sorted? counted? reversible? number? decimal? ' +
    -      'class? distinct? isa? float? rational? reduced? ratio? odd? even? char? seq? vector? ' +
    -      'string? map? nil? contains? zero? instance? not-every? not-any? libspec? -> ->> .. . ' +
    -      'inc compare do dotimes mapcat take remove take-while drop letfn drop-last take-last ' +
    -      'drop-while while intern condp case reduced cycle split-at split-with repeat replicate ' +
    -      'iterate range merge zipmap declare line-seq sort comparator sort-by dorun doall nthnext ' +
    -      'nthrest partition eval doseq await await-for let agent atom send send-off release-pending-sends ' +
    -      'add-watch mapv filterv remove-watch agent-error restart-agent set-error-handler error-handler ' +
    -      'set-error-mode! error-mode shutdown-agents quote var fn loop recur throw try monitor-enter ' +
    -      'monitor-exit macroexpand macroexpand-1 for dosync and or ' +
    -      'when when-not when-let comp juxt partial sequence memoize constantly complement identity assert ' +
    -      'peek pop doto proxy first rest cons cast coll last butlast ' +
    -      'sigs reify second ffirst fnext nfirst nnext meta with-meta ns in-ns create-ns import ' +
    -      'refer keys select-keys vals key val rseq name namespace promise into transient persistent! conj! ' +
    -      'assoc! dissoc! pop! disj! use class type num float double short byte boolean bigint biginteger ' +
    -      'bigdec print-method print-dup throw-if printf format load compile get-in update-in pr pr-on newline ' +
    -      'flush read slurp read-line subvec with-open memfn time re-find re-groups rand-int rand mod locking ' +
    -      'assert-valid-fdecl alias resolve ref deref refset swap! reset! set-validator! compare-and-set! alter-meta! ' +
    -      'reset-meta! commute get-validator alter ref-set ref-history-count ref-min-history ref-max-history ensure sync io! ' +
    -      'new next conj set! to-array future future-call into-array aset gen-class reduce map filter find empty ' +
    -      'hash-map hash-set sorted-map sorted-map-by sorted-set sorted-set-by vec vector seq flatten reverse assoc dissoc list ' +
    -      'disj get union difference intersection extend extend-type extend-protocol int nth delay count concat chunk chunk-buffer ' +
    -      'chunk-append chunk-first chunk-rest max min dec unchecked-inc-int unchecked-inc unchecked-dec-inc unchecked-dec unchecked-negate ' +
    -      'unchecked-add-int unchecked-add unchecked-subtract-int unchecked-subtract chunk-next chunk-cons chunked-seq? prn vary-meta ' +
    -      'lazy-seq spread list* str find-keyword keyword symbol gensym force rationalize'
    -  };
    -
    -  const SIMPLE_NUMBER_RE = '[-+]?\\d+(\\.\\d+)?';
    -
    -  const SYMBOL = {
    -    begin: SYMBOL_RE,
    -    relevance: 0
    -  };
    -  const NUMBER = {
    -    className: 'number',
    -    begin: SIMPLE_NUMBER_RE,
    -    relevance: 0
    -  };
    -  const STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, {
    -    illegal: null
    -  });
    -  const COMMENT = hljs.COMMENT(
    -    ';',
    -    '$',
    -    {
    -      relevance: 0
    -    }
    -  );
    -  const LITERAL = {
    -    className: 'literal',
    -    begin: /\b(true|false|nil)\b/
    -  };
    -  const COLLECTION = {
    -    begin: '[\\[\\{]',
    -    end: '[\\]\\}]'
    -  };
    -  const HINT = {
    -    className: 'comment',
    -    begin: '\\^' + SYMBOL_RE
    -  };
    -  const HINT_COL = hljs.COMMENT('\\^\\{', '\\}');
    -  const KEY = {
    -    className: 'symbol',
    -    begin: '[:]{1,2}' + SYMBOL_RE
    -  };
    -  const LIST = {
    -    begin: '\\(',
    -    end: '\\)'
    -  };
    -  const BODY = {
    -    endsWithParent: true,
    -    relevance: 0
    -  };
    -  const NAME = {
    -    keywords: keywords,
    -    className: 'name',
    -    begin: SYMBOL_RE,
    -    relevance: 0,
    -    starts: BODY
    -  };
    -  const DEFAULT_CONTAINS = [
    -    LIST,
    -    STRING,
    -    HINT,
    -    HINT_COL,
    -    COMMENT,
    -    KEY,
    -    COLLECTION,
    -    NUMBER,
    -    LITERAL,
    -    SYMBOL
    -  ];
    -
    -  const GLOBAL = {
    -    beginKeywords: globals,
    -    lexemes: SYMBOL_RE,
    -    end: '(\\[|#|\\d|"|:|\\{|\\)|\\(|$)',
    -    contains: [
    -      {
    -        className: 'title',
    -        begin: SYMBOL_RE,
    -        relevance: 0,
    -        excludeEnd: true,
    -        // we can only have a single title
    -        endsParent: true
    -      }
    -    ].concat(DEFAULT_CONTAINS)
    -  };
    -
    -  LIST.contains = [
    -    hljs.COMMENT('comment', ''),
    -    GLOBAL,
    -    NAME,
    -    BODY
    -  ];
    -  BODY.contains = DEFAULT_CONTAINS;
    -  COLLECTION.contains = DEFAULT_CONTAINS;
    -  HINT_COL.contains = [ COLLECTION ];
    -
    -  return {
    -    name: 'Clojure',
    -    aliases: [ 'clj' ],
    -    illegal: /\S/,
    -    contains: [
    -      LIST,
    -      STRING,
    -      HINT,
    -      HINT_COL,
    -      COMMENT,
    -      KEY,
    -      COLLECTION,
    -      NUMBER,
    -      LITERAL
    -    ]
    -  };
    -}
    -
    -module.exports = clojure;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/cmake.js b/claude-code-source/node_modules/highlight.js/lib/languages/cmake.js
    deleted file mode 100644
    index c5519da5..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/cmake.js
    +++ /dev/null
    @@ -1,64 +0,0 @@
    -/*
    -Language: CMake
    -Description: CMake is an open-source cross-platform system for build automation.
    -Author: Igor Kalnitsky 
    -Website: https://cmake.org
    -*/
    -
    -/** @type LanguageFn */
    -function cmake(hljs) {
    -  return {
    -    name: 'CMake',
    -    aliases: ['cmake.in'],
    -    case_insensitive: true,
    -    keywords: {
    -      keyword:
    -        // scripting commands
    -        'break cmake_host_system_information cmake_minimum_required cmake_parse_arguments ' +
    -        'cmake_policy configure_file continue elseif else endforeach endfunction endif endmacro ' +
    -        'endwhile execute_process file find_file find_library find_package find_path ' +
    -        'find_program foreach function get_cmake_property get_directory_property ' +
    -        'get_filename_component get_property if include include_guard list macro ' +
    -        'mark_as_advanced math message option return separate_arguments ' +
    -        'set_directory_properties set_property set site_name string unset variable_watch while ' +
    -        // project commands
    -        'add_compile_definitions add_compile_options add_custom_command add_custom_target ' +
    -        'add_definitions add_dependencies add_executable add_library add_link_options ' +
    -        'add_subdirectory add_test aux_source_directory build_command create_test_sourcelist ' +
    -        'define_property enable_language enable_testing export fltk_wrap_ui ' +
    -        'get_source_file_property get_target_property get_test_property include_directories ' +
    -        'include_external_msproject include_regular_expression install link_directories ' +
    -        'link_libraries load_cache project qt_wrap_cpp qt_wrap_ui remove_definitions ' +
    -        'set_source_files_properties set_target_properties set_tests_properties source_group ' +
    -        'target_compile_definitions target_compile_features target_compile_options ' +
    -        'target_include_directories target_link_directories target_link_libraries ' +
    -        'target_link_options target_sources try_compile try_run ' +
    -        // CTest commands
    -        'ctest_build ctest_configure ctest_coverage ctest_empty_binary_directory ctest_memcheck ' +
    -        'ctest_read_custom_files ctest_run_script ctest_sleep ctest_start ctest_submit ' +
    -        'ctest_test ctest_update ctest_upload ' +
    -        // deprecated commands
    -        'build_name exec_program export_library_dependencies install_files install_programs ' +
    -        'install_targets load_command make_directory output_required_files remove ' +
    -        'subdir_depends subdirs use_mangled_mesa utility_source variable_requires write_file ' +
    -        'qt5_use_modules qt5_use_package qt5_wrap_cpp ' +
    -        // core keywords
    -        'on off true false and or not command policy target test exists is_newer_than ' +
    -        'is_directory is_symlink is_absolute matches less greater equal less_equal ' +
    -        'greater_equal strless strgreater strequal strless_equal strgreater_equal version_less ' +
    -        'version_greater version_equal version_less_equal version_greater_equal in_list defined'
    -    },
    -    contains: [
    -      {
    -        className: 'variable',
    -        begin: /\$\{/,
    -        end: /\}/
    -      },
    -      hljs.HASH_COMMENT_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.NUMBER_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = cmake;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/coffeescript.js b/claude-code-source/node_modules/highlight.js/lib/languages/coffeescript.js
    deleted file mode 100644
    index a91e012f..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/coffeescript.js
    +++ /dev/null
    @@ -1,356 +0,0 @@
    -const KEYWORDS = [
    -  "as", // for exports
    -  "in",
    -  "of",
    -  "if",
    -  "for",
    -  "while",
    -  "finally",
    -  "var",
    -  "new",
    -  "function",
    -  "do",
    -  "return",
    -  "void",
    -  "else",
    -  "break",
    -  "catch",
    -  "instanceof",
    -  "with",
    -  "throw",
    -  "case",
    -  "default",
    -  "try",
    -  "switch",
    -  "continue",
    -  "typeof",
    -  "delete",
    -  "let",
    -  "yield",
    -  "const",
    -  "class",
    -  // JS handles these with a special rule
    -  // "get",
    -  // "set",
    -  "debugger",
    -  "async",
    -  "await",
    -  "static",
    -  "import",
    -  "from",
    -  "export",
    -  "extends"
    -];
    -const LITERALS = [
    -  "true",
    -  "false",
    -  "null",
    -  "undefined",
    -  "NaN",
    -  "Infinity"
    -];
    -
    -const TYPES = [
    -  "Intl",
    -  "DataView",
    -  "Number",
    -  "Math",
    -  "Date",
    -  "String",
    -  "RegExp",
    -  "Object",
    -  "Function",
    -  "Boolean",
    -  "Error",
    -  "Symbol",
    -  "Set",
    -  "Map",
    -  "WeakSet",
    -  "WeakMap",
    -  "Proxy",
    -  "Reflect",
    -  "JSON",
    -  "Promise",
    -  "Float64Array",
    -  "Int16Array",
    -  "Int32Array",
    -  "Int8Array",
    -  "Uint16Array",
    -  "Uint32Array",
    -  "Float32Array",
    -  "Array",
    -  "Uint8Array",
    -  "Uint8ClampedArray",
    -  "ArrayBuffer",
    -  "BigInt64Array",
    -  "BigUint64Array",
    -  "BigInt"
    -];
    -
    -const ERROR_TYPES = [
    -  "EvalError",
    -  "InternalError",
    -  "RangeError",
    -  "ReferenceError",
    -  "SyntaxError",
    -  "TypeError",
    -  "URIError"
    -];
    -
    -const BUILT_IN_GLOBALS = [
    -  "setInterval",
    -  "setTimeout",
    -  "clearInterval",
    -  "clearTimeout",
    -
    -  "require",
    -  "exports",
    -
    -  "eval",
    -  "isFinite",
    -  "isNaN",
    -  "parseFloat",
    -  "parseInt",
    -  "decodeURI",
    -  "decodeURIComponent",
    -  "encodeURI",
    -  "encodeURIComponent",
    -  "escape",
    -  "unescape"
    -];
    -
    -const BUILT_IN_VARIABLES = [
    -  "arguments",
    -  "this",
    -  "super",
    -  "console",
    -  "window",
    -  "document",
    -  "localStorage",
    -  "module",
    -  "global" // Node.js
    -];
    -
    -const BUILT_INS = [].concat(
    -  BUILT_IN_GLOBALS,
    -  BUILT_IN_VARIABLES,
    -  TYPES,
    -  ERROR_TYPES
    -);
    -
    -/*
    -Language: CoffeeScript
    -Author: Dmytrii Nagirniak 
    -Contributors: Oleg Efimov , Cédric Néhémie 
    -Description: CoffeeScript is a programming language that transcompiles to JavaScript. For info about language see http://coffeescript.org/
    -Category: common, scripting
    -Website: https://coffeescript.org
    -*/
    -
    -/** @type LanguageFn */
    -function coffeescript(hljs) {
    -  const COFFEE_BUILT_INS = [
    -    'npm',
    -    'print'
    -  ];
    -  const COFFEE_LITERALS = [
    -    'yes',
    -    'no',
    -    'on',
    -    'off'
    -  ];
    -  const COFFEE_KEYWORDS = [
    -    'then',
    -    'unless',
    -    'until',
    -    'loop',
    -    'by',
    -    'when',
    -    'and',
    -    'or',
    -    'is',
    -    'isnt',
    -    'not'
    -  ];
    -  const NOT_VALID_KEYWORDS = [
    -    "var",
    -    "const",
    -    "let",
    -    "function",
    -    "static"
    -  ];
    -  const excluding = (list) =>
    -    (kw) => !list.includes(kw);
    -  const KEYWORDS$1 = {
    -    keyword: KEYWORDS.concat(COFFEE_KEYWORDS).filter(excluding(NOT_VALID_KEYWORDS)),
    -    literal: LITERALS.concat(COFFEE_LITERALS),
    -    built_in: BUILT_INS.concat(COFFEE_BUILT_INS)
    -  };
    -  const JS_IDENT_RE = '[A-Za-z$_][0-9A-Za-z$_]*';
    -  const SUBST = {
    -    className: 'subst',
    -    begin: /#\{/,
    -    end: /\}/,
    -    keywords: KEYWORDS$1
    -  };
    -  const EXPRESSIONS = [
    -    hljs.BINARY_NUMBER_MODE,
    -    hljs.inherit(hljs.C_NUMBER_MODE, {
    -      starts: {
    -        end: '(\\s*/)?',
    -        relevance: 0
    -      }
    -    }), // a number tries to eat the following slash to prevent treating it as a regexp
    -    {
    -      className: 'string',
    -      variants: [
    -        {
    -          begin: /'''/,
    -          end: /'''/,
    -          contains: [hljs.BACKSLASH_ESCAPE]
    -        },
    -        {
    -          begin: /'/,
    -          end: /'/,
    -          contains: [hljs.BACKSLASH_ESCAPE]
    -        },
    -        {
    -          begin: /"""/,
    -          end: /"""/,
    -          contains: [
    -            hljs.BACKSLASH_ESCAPE,
    -            SUBST
    -          ]
    -        },
    -        {
    -          begin: /"/,
    -          end: /"/,
    -          contains: [
    -            hljs.BACKSLASH_ESCAPE,
    -            SUBST
    -          ]
    -        }
    -      ]
    -    },
    -    {
    -      className: 'regexp',
    -      variants: [
    -        {
    -          begin: '///',
    -          end: '///',
    -          contains: [
    -            SUBST,
    -            hljs.HASH_COMMENT_MODE
    -          ]
    -        },
    -        {
    -          begin: '//[gim]{0,3}(?=\\W)',
    -          relevance: 0
    -        },
    -        {
    -          // regex can't start with space to parse x / 2 / 3 as two divisions
    -          // regex can't start with *, and it supports an "illegal" in the main mode
    -          begin: /\/(?![ *]).*?(?![\\]).\/[gim]{0,3}(?=\W)/
    -        }
    -      ]
    -    },
    -    {
    -      begin: '@' + JS_IDENT_RE // relevance booster
    -    },
    -    {
    -      subLanguage: 'javascript',
    -      excludeBegin: true,
    -      excludeEnd: true,
    -      variants: [
    -        {
    -          begin: '```',
    -          end: '```'
    -        },
    -        {
    -          begin: '`',
    -          end: '`'
    -        }
    -      ]
    -    }
    -  ];
    -  SUBST.contains = EXPRESSIONS;
    -
    -  const TITLE = hljs.inherit(hljs.TITLE_MODE, {
    -    begin: JS_IDENT_RE
    -  });
    -  const POSSIBLE_PARAMS_RE = '(\\(.*\\)\\s*)?\\B[-=]>';
    -  const PARAMS = {
    -    className: 'params',
    -    begin: '\\([^\\(]',
    -    returnBegin: true,
    -    /* We need another contained nameless mode to not have every nested
    -    pair of parens to be called "params" */
    -    contains: [{
    -      begin: /\(/,
    -      end: /\)/,
    -      keywords: KEYWORDS$1,
    -      contains: ['self'].concat(EXPRESSIONS)
    -    }]
    -  };
    -
    -  return {
    -    name: 'CoffeeScript',
    -    aliases: [
    -      'coffee',
    -      'cson',
    -      'iced'
    -    ],
    -    keywords: KEYWORDS$1,
    -    illegal: /\/\*/,
    -    contains: EXPRESSIONS.concat([
    -      hljs.COMMENT('###', '###'),
    -      hljs.HASH_COMMENT_MODE,
    -      {
    -        className: 'function',
    -        begin: '^\\s*' + JS_IDENT_RE + '\\s*=\\s*' + POSSIBLE_PARAMS_RE,
    -        end: '[-=]>',
    -        returnBegin: true,
    -        contains: [
    -          TITLE,
    -          PARAMS
    -        ]
    -      },
    -      {
    -        // anonymous function start
    -        begin: /[:\(,=]\s*/,
    -        relevance: 0,
    -        contains: [{
    -          className: 'function',
    -          begin: POSSIBLE_PARAMS_RE,
    -          end: '[-=]>',
    -          returnBegin: true,
    -          contains: [PARAMS]
    -        }]
    -      },
    -      {
    -        className: 'class',
    -        beginKeywords: 'class',
    -        end: '$',
    -        illegal: /[:="\[\]]/,
    -        contains: [
    -          {
    -            beginKeywords: 'extends',
    -            endsWithParent: true,
    -            illegal: /[:="\[\]]/,
    -            contains: [TITLE]
    -          },
    -          TITLE
    -        ]
    -      },
    -      {
    -        begin: JS_IDENT_RE + ':',
    -        end: ':',
    -        returnBegin: true,
    -        returnEnd: true,
    -        relevance: 0
    -      }
    -    ])
    -  };
    -}
    -
    -module.exports = coffeescript;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/coq.js b/claude-code-source/node_modules/highlight.js/lib/languages/coq.js
    deleted file mode 100644
    index 79957eab..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/coq.js
    +++ /dev/null
    @@ -1,79 +0,0 @@
    -/*
    -Language: Coq
    -Author: Stephan Boyer 
    -Category: functional
    -Website: https://coq.inria.fr
    -*/
    -
    -/** @type LanguageFn */
    -function coq(hljs) {
    -  return {
    -    name: 'Coq',
    -    keywords: {
    -      keyword:
    -        '_|0 as at cofix else end exists exists2 fix for forall fun if IF in let ' +
    -        'match mod Prop return Set then Type using where with ' +
    -        'Abort About Add Admit Admitted All Arguments Assumptions Axiom Back BackTo ' +
    -        'Backtrack Bind Blacklist Canonical Cd Check Class Classes Close Coercion ' +
    -        'Coercions CoFixpoint CoInductive Collection Combined Compute Conjecture ' +
    -        'Conjectures Constant constr Constraint Constructors Context Corollary ' +
    -        'CreateHintDb Cut Declare Defined Definition Delimit Dependencies Dependent ' +
    -        'Derive Drop eauto End Equality Eval Example Existential Existentials ' +
    -        'Existing Export exporting Extern Extract Extraction Fact Field Fields File ' +
    -        'Fixpoint Focus for From Function Functional Generalizable Global Goal Grab ' +
    -        'Grammar Graph Guarded Heap Hint HintDb Hints Hypotheses Hypothesis ident ' +
    -        'Identity If Immediate Implicit Import Include Inductive Infix Info Initial ' +
    -        'Inline Inspect Instance Instances Intro Intros Inversion Inversion_clear ' +
    -        'Language Left Lemma Let Libraries Library Load LoadPath Local Locate Ltac ML ' +
    -        'Mode Module Modules Monomorphic Morphism Next NoInline Notation Obligation ' +
    -        'Obligations Opaque Open Optimize Options Parameter Parameters Parametric ' +
    -        'Path Paths pattern Polymorphic Preterm Print Printing Program Projections ' +
    -        'Proof Proposition Pwd Qed Quit Rec Record Recursive Redirect Relation Remark ' +
    -        'Remove Require Reserved Reset Resolve Restart Rewrite Right Ring Rings Save ' +
    -        'Scheme Scope Scopes Script Search SearchAbout SearchHead SearchPattern ' +
    -        'SearchRewrite Section Separate Set Setoid Show Solve Sorted Step Strategies ' +
    -        'Strategy Structure SubClass Table Tables Tactic Term Test Theorem Time ' +
    -        'Timeout Transparent Type Typeclasses Types Undelimit Undo Unfocus Unfocused ' +
    -        'Unfold Universe Universes Unset Unshelve using Variable Variables Variant ' +
    -        'Verbose Visibility where with',
    -      built_in:
    -        'abstract absurd admit after apply as assert assumption at auto autorewrite ' +
    -        'autounfold before bottom btauto by case case_eq cbn cbv change ' +
    -        'classical_left classical_right clear clearbody cofix compare compute ' +
    -        'congruence constr_eq constructor contradict contradiction cut cutrewrite ' +
    -        'cycle decide decompose dependent destruct destruction dintuition ' +
    -        'discriminate discrR do double dtauto eapply eassumption eauto ecase ' +
    -        'econstructor edestruct ediscriminate eelim eexact eexists einduction ' +
    -        'einjection eleft elim elimtype enough equality erewrite eright ' +
    -        'esimplify_eq esplit evar exact exactly_once exfalso exists f_equal fail ' +
    -        'field field_simplify field_simplify_eq first firstorder fix fold fourier ' +
    -        'functional generalize generalizing gfail give_up has_evar hnf idtac in ' +
    -        'induction injection instantiate intro intro_pattern intros intuition ' +
    -        'inversion inversion_clear is_evar is_var lapply lazy left lia lra move ' +
    -        'native_compute nia nsatz omega once pattern pose progress proof psatz quote ' +
    -        'record red refine reflexivity remember rename repeat replace revert ' +
    -        'revgoals rewrite rewrite_strat right ring ring_simplify rtauto set ' +
    -        'setoid_reflexivity setoid_replace setoid_rewrite setoid_symmetry ' +
    -        'setoid_transitivity shelve shelve_unifiable simpl simple simplify_eq solve ' +
    -        'specialize split split_Rabs split_Rmult stepl stepr subst sum swap ' +
    -        'symmetry tactic tauto time timeout top transitivity trivial try tryif ' +
    -        'unfold unify until using vm_compute with'
    -    },
    -    contains: [
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.COMMENT('\\(\\*', '\\*\\)'),
    -      hljs.C_NUMBER_MODE,
    -      {
    -        className: 'type',
    -        excludeBegin: true,
    -        begin: '\\|\\s*',
    -        end: '\\w+'
    -      },
    -      { // relevance booster
    -        begin: /[-=]>/
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = coq;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/cos.js b/claude-code-source/node_modules/highlight.js/lib/languages/cos.js
    deleted file mode 100644
    index 1d9fded7..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/cos.js
    +++ /dev/null
    @@ -1,138 +0,0 @@
    -/*
    -Language: Caché Object Script
    -Author: Nikita Savchenko 
    -Category: enterprise, scripting
    -Website: https://cedocs.intersystems.com/latest/csp/docbook/DocBook.UI.Page.cls
    -*/
    -
    -/** @type LanguageFn */
    -function cos(hljs) {
    -  const STRINGS = {
    -    className: 'string',
    -    variants: [{
    -      begin: '"',
    -      end: '"',
    -      contains: [{ // escaped
    -        begin: "\"\"",
    -        relevance: 0
    -      }]
    -    }]
    -  };
    -
    -  const NUMBERS = {
    -    className: "number",
    -    begin: "\\b(\\d+(\\.\\d*)?|\\.\\d+)",
    -    relevance: 0
    -  };
    -
    -  const COS_KEYWORDS =
    -    'property parameter class classmethod clientmethod extends as break ' +
    -    'catch close continue do d|0 else elseif for goto halt hang h|0 if job ' +
    -    'j|0 kill k|0 lock l|0 merge new open quit q|0 read r|0 return set s|0 ' +
    -    'tcommit throw trollback try tstart use view while write w|0 xecute x|0 ' +
    -    'zkill znspace zn ztrap zwrite zw zzdump zzwrite print zbreak zinsert ' +
    -    'zload zprint zremove zsave zzprint mv mvcall mvcrt mvdim mvprint zquit ' +
    -    'zsync ascii';
    -
    -  // registered function - no need in them due to all functions are highlighted,
    -  // but I'll just leave this here.
    -
    -  // "$bit", "$bitcount",
    -  // "$bitfind", "$bitlogic", "$case", "$char", "$classmethod", "$classname",
    -  // "$compile", "$data", "$decimal", "$double", "$extract", "$factor",
    -  // "$find", "$fnumber", "$get", "$increment", "$inumber", "$isobject",
    -  // "$isvaliddouble", "$isvalidnum", "$justify", "$length", "$list",
    -  // "$listbuild", "$listdata", "$listfind", "$listfromstring", "$listget",
    -  // "$listlength", "$listnext", "$listsame", "$listtostring", "$listvalid",
    -  // "$locate", "$match", "$method", "$name", "$nconvert", "$next",
    -  // "$normalize", "$now", "$number", "$order", "$parameter", "$piece",
    -  // "$prefetchoff", "$prefetchon", "$property", "$qlength", "$qsubscript",
    -  // "$query", "$random", "$replace", "$reverse", "$sconvert", "$select",
    -  // "$sortbegin", "$sortend", "$stack", "$text", "$translate", "$view",
    -  // "$wascii", "$wchar", "$wextract", "$wfind", "$wiswide", "$wlength",
    -  // "$wreverse", "$xecute", "$zabs", "$zarccos", "$zarcsin", "$zarctan",
    -  // "$zcos", "$zcot", "$zcsc", "$zdate", "$zdateh", "$zdatetime",
    -  // "$zdatetimeh", "$zexp", "$zhex", "$zln", "$zlog", "$zpower", "$zsec",
    -  // "$zsin", "$zsqr", "$ztan", "$ztime", "$ztimeh", "$zboolean",
    -  // "$zconvert", "$zcrc", "$zcyc", "$zdascii", "$zdchar", "$zf",
    -  // "$ziswide", "$zlascii", "$zlchar", "$zname", "$zposition", "$zqascii",
    -  // "$zqchar", "$zsearch", "$zseek", "$zstrip", "$zwascii", "$zwchar",
    -  // "$zwidth", "$zwpack", "$zwbpack", "$zwunpack", "$zwbunpack", "$zzenkaku",
    -  // "$change", "$mv", "$mvat", "$mvfmt", "$mvfmts", "$mviconv",
    -  // "$mviconvs", "$mvinmat", "$mvlover", "$mvoconv", "$mvoconvs", "$mvraise",
    -  // "$mvtrans", "$mvv", "$mvname", "$zbitand", "$zbitcount", "$zbitfind",
    -  // "$zbitget", "$zbitlen", "$zbitnot", "$zbitor", "$zbitset", "$zbitstr",
    -  // "$zbitxor", "$zincrement", "$znext", "$zorder", "$zprevious", "$zsort",
    -  // "device", "$ecode", "$estack", "$etrap", "$halt", "$horolog",
    -  // "$io", "$job", "$key", "$namespace", "$principal", "$quit", "$roles",
    -  // "$storage", "$system", "$test", "$this", "$tlevel", "$username",
    -  // "$x", "$y", "$za", "$zb", "$zchild", "$zeof", "$zeos", "$zerror",
    -  // "$zhorolog", "$zio", "$zjob", "$zmode", "$znspace", "$zparent", "$zpi",
    -  // "$zpos", "$zreference", "$zstorage", "$ztimestamp", "$ztimezone",
    -  // "$ztrap", "$zversion"
    -
    -  return {
    -    name: 'Caché Object Script',
    -    case_insensitive: true,
    -    aliases: [
    -      "cls"
    -    ],
    -    keywords: COS_KEYWORDS,
    -    contains: [
    -      NUMBERS,
    -      STRINGS,
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      {
    -        className: "comment",
    -        begin: /;/,
    -        end: "$",
    -        relevance: 0
    -      },
    -      { // Functions and user-defined functions: write $ztime(60*60*3), $$myFunc(10), $$^Val(1)
    -        className: "built_in",
    -        begin: /(?:\$\$?|\.\.)\^?[a-zA-Z]+/
    -      },
    -      { // Macro command: quit $$$OK
    -        className: "built_in",
    -        begin: /\$\$\$[a-zA-Z]+/
    -      },
    -      { // Special (global) variables: write %request.Content; Built-in classes: %Library.Integer
    -        className: "built_in",
    -        begin: /%[a-z]+(?:\.[a-z]+)*/
    -      },
    -      { // Global variable: set ^globalName = 12 write ^globalName
    -        className: "symbol",
    -        begin: /\^%?[a-zA-Z][\w]*/
    -      },
    -      { // Some control constructions: do ##class(Package.ClassName).Method(), ##super()
    -        className: "keyword",
    -        begin: /##class|##super|#define|#dim/
    -      },
    -      // sub-languages: are not fully supported by hljs by 11/15/2015
    -      // left for the future implementation.
    -      {
    -        begin: /&sql\(/,
    -        end: /\)/,
    -        excludeBegin: true,
    -        excludeEnd: true,
    -        subLanguage: "sql"
    -      },
    -      {
    -        begin: /&(js|jscript|javascript)/,
    -        excludeBegin: true,
    -        excludeEnd: true,
    -        subLanguage: "javascript"
    -      },
    -      {
    -        // this brakes first and last tag, but this is the only way to embed a valid html
    -        begin: /&html<\s*\s*>/,
    -        subLanguage: "xml"
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = cos;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/cpp.js b/claude-code-source/node_modules/highlight.js/lib/languages/cpp.js
    deleted file mode 100644
    index 745e5d1e..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/cpp.js
    +++ /dev/null
    @@ -1,464 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function lookahead(re) {
    -  return concat('(?=', re, ')');
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function optional(re) {
    -  return concat('(', re, ')?');
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: C++
    -Category: common, system
    -Website: https://isocpp.org
    -*/
    -
    -/** @type LanguageFn */
    -function cpp(hljs) {
    -  // added for historic reasons because `hljs.C_LINE_COMMENT_MODE` does
    -  // not include such support nor can we be sure all the grammars depending
    -  // on it would desire this behavior
    -  const C_LINE_COMMENT_MODE = hljs.COMMENT('//', '$', {
    -    contains: [
    -      {
    -        begin: /\\\n/
    -      }
    -    ]
    -  });
    -  const DECLTYPE_AUTO_RE = 'decltype\\(auto\\)';
    -  const NAMESPACE_RE = '[a-zA-Z_]\\w*::';
    -  const TEMPLATE_ARGUMENT_RE = '<[^<>]+>';
    -  const FUNCTION_TYPE_RE = '(' +
    -    DECLTYPE_AUTO_RE + '|' +
    -    optional(NAMESPACE_RE) +
    -    '[a-zA-Z_]\\w*' + optional(TEMPLATE_ARGUMENT_RE) +
    -  ')';
    -  const CPP_PRIMITIVE_TYPES = {
    -    className: 'keyword',
    -    begin: '\\b[a-z\\d_]*_t\\b'
    -  };
    -
    -  // https://en.cppreference.com/w/cpp/language/escape
    -  // \\ \x \xFF \u2837 \u00323747 \374
    -  const CHARACTER_ESCAPES = '\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)';
    -  const STRINGS = {
    -    className: 'string',
    -    variants: [
    -      {
    -        begin: '(u8?|U|L)?"',
    -        end: '"',
    -        illegal: '\\n',
    -        contains: [ hljs.BACKSLASH_ESCAPE ]
    -      },
    -      {
    -        begin: '(u8?|U|L)?\'(' + CHARACTER_ESCAPES + "|.)",
    -        end: '\'',
    -        illegal: '.'
    -      },
    -      hljs.END_SAME_AS_BEGIN({
    -        begin: /(?:u8?|U|L)?R"([^()\\ ]{0,16})\(/,
    -        end: /\)([^()\\ ]{0,16})"/
    -      })
    -    ]
    -  };
    -
    -  const NUMBERS = {
    -    className: 'number',
    -    variants: [
    -      {
    -        begin: '\\b(0b[01\']+)'
    -      },
    -      {
    -        begin: '(-?)\\b([\\d\']+(\\.[\\d\']*)?|\\.[\\d\']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)'
    -      },
    -      {
    -        begin: '(-?)(\\b0[xX][a-fA-F0-9\']+|(\\b[\\d\']+(\\.[\\d\']*)?|\\.[\\d\']+)([eE][-+]?[\\d\']+)?)'
    -      }
    -    ],
    -    relevance: 0
    -  };
    -
    -  const PREPROCESSOR = {
    -    className: 'meta',
    -    begin: /#\s*[a-z]+\b/,
    -    end: /$/,
    -    keywords: {
    -      'meta-keyword':
    -        'if else elif endif define undef warning error line ' +
    -        'pragma _Pragma ifdef ifndef include'
    -    },
    -    contains: [
    -      {
    -        begin: /\\\n/,
    -        relevance: 0
    -      },
    -      hljs.inherit(STRINGS, {
    -        className: 'meta-string'
    -      }),
    -      {
    -        className: 'meta-string',
    -        begin: /<.*?>/
    -      },
    -      C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE
    -    ]
    -  };
    -
    -  const TITLE_MODE = {
    -    className: 'title',
    -    begin: optional(NAMESPACE_RE) + hljs.IDENT_RE,
    -    relevance: 0
    -  };
    -
    -  const FUNCTION_TITLE = optional(NAMESPACE_RE) + hljs.IDENT_RE + '\\s*\\(';
    -
    -  const COMMON_CPP_HINTS = [
    -    'asin',
    -    'atan2',
    -    'atan',
    -    'calloc',
    -    'ceil',
    -    'cosh',
    -    'cos',
    -    'exit',
    -    'exp',
    -    'fabs',
    -    'floor',
    -    'fmod',
    -    'fprintf',
    -    'fputs',
    -    'free',
    -    'frexp',
    -    'auto_ptr',
    -    'deque',
    -    'list',
    -    'queue',
    -    'stack',
    -    'vector',
    -    'map',
    -    'set',
    -    'pair',
    -    'bitset',
    -    'multiset',
    -    'multimap',
    -    'unordered_set',
    -    'fscanf',
    -    'future',
    -    'isalnum',
    -    'isalpha',
    -    'iscntrl',
    -    'isdigit',
    -    'isgraph',
    -    'islower',
    -    'isprint',
    -    'ispunct',
    -    'isspace',
    -    'isupper',
    -    'isxdigit',
    -    'tolower',
    -    'toupper',
    -    'labs',
    -    'ldexp',
    -    'log10',
    -    'log',
    -    'malloc',
    -    'realloc',
    -    'memchr',
    -    'memcmp',
    -    'memcpy',
    -    'memset',
    -    'modf',
    -    'pow',
    -    'printf',
    -    'putchar',
    -    'puts',
    -    'scanf',
    -    'sinh',
    -    'sin',
    -    'snprintf',
    -    'sprintf',
    -    'sqrt',
    -    'sscanf',
    -    'strcat',
    -    'strchr',
    -    'strcmp',
    -    'strcpy',
    -    'strcspn',
    -    'strlen',
    -    'strncat',
    -    'strncmp',
    -    'strncpy',
    -    'strpbrk',
    -    'strrchr',
    -    'strspn',
    -    'strstr',
    -    'tanh',
    -    'tan',
    -    'unordered_map',
    -    'unordered_multiset',
    -    'unordered_multimap',
    -    'priority_queue',
    -    'make_pair',
    -    'array',
    -    'shared_ptr',
    -    'abort',
    -    'terminate',
    -    'abs',
    -    'acos',
    -    'vfprintf',
    -    'vprintf',
    -    'vsprintf',
    -    'endl',
    -    'initializer_list',
    -    'unique_ptr',
    -    'complex',
    -    'imaginary',
    -    'std',
    -    'string',
    -    'wstring',
    -    'cin',
    -    'cout',
    -    'cerr',
    -    'clog',
    -    'stdin',
    -    'stdout',
    -    'stderr',
    -    'stringstream',
    -    'istringstream',
    -    'ostringstream'
    -  ];
    -
    -  const CPP_KEYWORDS = {
    -    keyword: 'int float while private char char8_t char16_t char32_t catch import module export virtual operator sizeof ' +
    -      'dynamic_cast|10 typedef const_cast|10 const for static_cast|10 union namespace ' +
    -      'unsigned long volatile static protected bool template mutable if public friend ' +
    -      'do goto auto void enum else break extern using asm case typeid wchar_t ' +
    -      'short reinterpret_cast|10 default double register explicit signed typename try this ' +
    -      'switch continue inline delete alignas alignof constexpr consteval constinit decltype ' +
    -      'concept co_await co_return co_yield requires ' +
    -      'noexcept static_assert thread_local restrict final override ' +
    -      'atomic_bool atomic_char atomic_schar ' +
    -      'atomic_uchar atomic_short atomic_ushort atomic_int atomic_uint atomic_long atomic_ulong atomic_llong ' +
    -      'atomic_ullong new throw return ' +
    -      'and and_eq bitand bitor compl not not_eq or or_eq xor xor_eq',
    -    built_in: '_Bool _Complex _Imaginary',
    -    _relevance_hints: COMMON_CPP_HINTS,
    -    literal: 'true false nullptr NULL'
    -  };
    -
    -  const FUNCTION_DISPATCH = {
    -    className: "function.dispatch",
    -    relevance: 0,
    -    keywords: CPP_KEYWORDS,
    -    begin: concat(
    -      /\b/,
    -      /(?!decltype)/,
    -      /(?!if)/,
    -      /(?!for)/,
    -      /(?!while)/,
    -      hljs.IDENT_RE,
    -      lookahead(/\s*\(/))
    -  };
    -
    -  const EXPRESSION_CONTAINS = [
    -    FUNCTION_DISPATCH,
    -    PREPROCESSOR,
    -    CPP_PRIMITIVE_TYPES,
    -    C_LINE_COMMENT_MODE,
    -    hljs.C_BLOCK_COMMENT_MODE,
    -    NUMBERS,
    -    STRINGS
    -  ];
    -
    -
    -  const EXPRESSION_CONTEXT = {
    -    // This mode covers expression context where we can't expect a function
    -    // definition and shouldn't highlight anything that looks like one:
    -    // `return some()`, `else if()`, `(x*sum(1, 2))`
    -    variants: [
    -      {
    -        begin: /=/,
    -        end: /;/
    -      },
    -      {
    -        begin: /\(/,
    -        end: /\)/
    -      },
    -      {
    -        beginKeywords: 'new throw return else',
    -        end: /;/
    -      }
    -    ],
    -    keywords: CPP_KEYWORDS,
    -    contains: EXPRESSION_CONTAINS.concat([
    -      {
    -        begin: /\(/,
    -        end: /\)/,
    -        keywords: CPP_KEYWORDS,
    -        contains: EXPRESSION_CONTAINS.concat([ 'self' ]),
    -        relevance: 0
    -      }
    -    ]),
    -    relevance: 0
    -  };
    -
    -  const FUNCTION_DECLARATION = {
    -    className: 'function',
    -    begin: '(' + FUNCTION_TYPE_RE + '[\\*&\\s]+)+' + FUNCTION_TITLE,
    -    returnBegin: true,
    -    end: /[{;=]/,
    -    excludeEnd: true,
    -    keywords: CPP_KEYWORDS,
    -    illegal: /[^\w\s\*&:<>.]/,
    -    contains: [
    -      { // to prevent it from being confused as the function title
    -        begin: DECLTYPE_AUTO_RE,
    -        keywords: CPP_KEYWORDS,
    -        relevance: 0
    -      },
    -      {
    -        begin: FUNCTION_TITLE,
    -        returnBegin: true,
    -        contains: [ TITLE_MODE ],
    -        relevance: 0
    -      },
    -      // needed because we do not have look-behind on the below rule
    -      // to prevent it from grabbing the final : in a :: pair
    -      {
    -        begin: /::/,
    -        relevance: 0
    -      },
    -      // initializers
    -      {
    -        begin: /:/,
    -        endsWithParent: true,
    -        contains: [
    -          STRINGS,
    -          NUMBERS
    -        ]
    -      },
    -      {
    -        className: 'params',
    -        begin: /\(/,
    -        end: /\)/,
    -        keywords: CPP_KEYWORDS,
    -        relevance: 0,
    -        contains: [
    -          C_LINE_COMMENT_MODE,
    -          hljs.C_BLOCK_COMMENT_MODE,
    -          STRINGS,
    -          NUMBERS,
    -          CPP_PRIMITIVE_TYPES,
    -          // Count matching parentheses.
    -          {
    -            begin: /\(/,
    -            end: /\)/,
    -            keywords: CPP_KEYWORDS,
    -            relevance: 0,
    -            contains: [
    -              'self',
    -              C_LINE_COMMENT_MODE,
    -              hljs.C_BLOCK_COMMENT_MODE,
    -              STRINGS,
    -              NUMBERS,
    -              CPP_PRIMITIVE_TYPES
    -            ]
    -          }
    -        ]
    -      },
    -      CPP_PRIMITIVE_TYPES,
    -      C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      PREPROCESSOR
    -    ]
    -  };
    -
    -  return {
    -    name: 'C++',
    -    aliases: [
    -      'cc',
    -      'c++',
    -      'h++',
    -      'hpp',
    -      'hh',
    -      'hxx',
    -      'cxx'
    -    ],
    -    keywords: CPP_KEYWORDS,
    -    illegal: ' rooms (9);`
    -          begin: '\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array)\\s*<',
    -          end: '>',
    -          keywords: CPP_KEYWORDS,
    -          contains: [
    -            'self',
    -            CPP_PRIMITIVE_TYPES
    -          ]
    -        },
    -        {
    -          begin: hljs.IDENT_RE + '::',
    -          keywords: CPP_KEYWORDS
    -        },
    -        {
    -          className: 'class',
    -          beginKeywords: 'enum class struct union',
    -          end: /[{;:<>=]/,
    -          contains: [
    -            {
    -              beginKeywords: "final class struct"
    -            },
    -            hljs.TITLE_MODE
    -          ]
    -        }
    -      ]),
    -    exports: {
    -      preprocessor: PREPROCESSOR,
    -      strings: STRINGS,
    -      keywords: CPP_KEYWORDS
    -    }
    -  };
    -}
    -
    -module.exports = cpp;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/crmsh.js b/claude-code-source/node_modules/highlight.js/lib/languages/crmsh.js
    deleted file mode 100644
    index 78c951cf..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/crmsh.js
    +++ /dev/null
    @@ -1,102 +0,0 @@
    -/*
    -Language: crmsh
    -Author: Kristoffer Gronlund 
    -Website: http://crmsh.github.io
    -Description: Syntax Highlighting for the crmsh DSL
    -Category: config
    -*/
    -
    -/** @type LanguageFn */
    -function crmsh(hljs) {
    -  const RESOURCES = 'primitive rsc_template';
    -  const COMMANDS = 'group clone ms master location colocation order fencing_topology ' +
    -      'rsc_ticket acl_target acl_group user role ' +
    -      'tag xml';
    -  const PROPERTY_SETS = 'property rsc_defaults op_defaults';
    -  const KEYWORDS = 'params meta operations op rule attributes utilization';
    -  const OPERATORS = 'read write deny defined not_defined in_range date spec in ' +
    -      'ref reference attribute type xpath version and or lt gt tag ' +
    -      'lte gte eq ne \\';
    -  const TYPES = 'number string';
    -  const LITERALS = 'Master Started Slave Stopped start promote demote stop monitor true false';
    -
    -  return {
    -    name: 'crmsh',
    -    aliases: [
    -      'crm',
    -      'pcmk'
    -    ],
    -    case_insensitive: true,
    -    keywords: {
    -      keyword: KEYWORDS + ' ' + OPERATORS + ' ' + TYPES,
    -      literal: LITERALS
    -    },
    -    contains: [
    -      hljs.HASH_COMMENT_MODE,
    -      {
    -        beginKeywords: 'node',
    -        starts: {
    -          end: '\\s*([\\w_-]+:)?',
    -          starts: {
    -            className: 'title',
    -            end: '\\s*[\\$\\w_][\\w_-]*'
    -          }
    -        }
    -      },
    -      {
    -        beginKeywords: RESOURCES,
    -        starts: {
    -          className: 'title',
    -          end: '\\s*[\\$\\w_][\\w_-]*',
    -          starts: {
    -            end: '\\s*@?[\\w_][\\w_\\.:-]*'
    -          }
    -        }
    -      },
    -      {
    -        begin: '\\b(' + COMMANDS.split(' ').join('|') + ')\\s+',
    -        keywords: COMMANDS,
    -        starts: {
    -          className: 'title',
    -          end: '[\\$\\w_][\\w_-]*'
    -        }
    -      },
    -      {
    -        beginKeywords: PROPERTY_SETS,
    -        starts: {
    -          className: 'title',
    -          end: '\\s*([\\w_-]+:)?'
    -        }
    -      },
    -      hljs.QUOTE_STRING_MODE,
    -      {
    -        className: 'meta',
    -        begin: '(ocf|systemd|service|lsb):[\\w_:-]+',
    -        relevance: 0
    -      },
    -      {
    -        className: 'number',
    -        begin: '\\b\\d+(\\.\\d+)?(ms|s|h|m)?',
    -        relevance: 0
    -      },
    -      {
    -        className: 'literal',
    -        begin: '[-]?(infinity|inf)',
    -        relevance: 0
    -      },
    -      {
    -        className: 'attr',
    -        begin: /([A-Za-z$_#][\w_-]+)=/,
    -        relevance: 0
    -      },
    -      {
    -        className: 'tag',
    -        begin: '',
    -        relevance: 0
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = crmsh;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/crystal.js b/claude-code-source/node_modules/highlight.js/lib/languages/crystal.js
    deleted file mode 100644
    index 35a89942..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/crystal.js
    +++ /dev/null
    @@ -1,326 +0,0 @@
    -/*
    -Language: Crystal
    -Author: TSUYUSATO Kitsune 
    -Website: https://crystal-lang.org
    -*/
    -
    -/** @type LanguageFn */
    -function crystal(hljs) {
    -  const INT_SUFFIX = '(_?[ui](8|16|32|64|128))?';
    -  const FLOAT_SUFFIX = '(_?f(32|64))?';
    -  const CRYSTAL_IDENT_RE = '[a-zA-Z_]\\w*[!?=]?';
    -  const CRYSTAL_METHOD_RE = '[a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|[=!]~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~|]|//|//=|&[-+*]=?|&\\*\\*|\\[\\][=?]?';
    -  const CRYSTAL_PATH_RE = '[A-Za-z_]\\w*(::\\w+)*(\\?|!)?';
    -  const CRYSTAL_KEYWORDS = {
    -    $pattern: CRYSTAL_IDENT_RE,
    -    keyword:
    -      'abstract alias annotation as as? asm begin break case class def do else elsif end ensure enum extend for fun if ' +
    -      'include instance_sizeof is_a? lib macro module next nil? of out pointerof private protected rescue responds_to? ' +
    -      'return require select self sizeof struct super then type typeof union uninitialized unless until verbatim when while with yield ' +
    -      '__DIR__ __END_LINE__ __FILE__ __LINE__',
    -    literal: 'false nil true'
    -  };
    -  const SUBST = {
    -    className: 'subst',
    -    begin: /#\{/,
    -    end: /\}/,
    -    keywords: CRYSTAL_KEYWORDS
    -  };
    -  const EXPANSION = {
    -    className: 'template-variable',
    -    variants: [
    -      {
    -        begin: '\\{\\{',
    -        end: '\\}\\}'
    -      },
    -      {
    -        begin: '\\{%',
    -        end: '%\\}'
    -      }
    -    ],
    -    keywords: CRYSTAL_KEYWORDS
    -  };
    -
    -  function recursiveParen(begin, end) {
    -    const
    -        contains = [
    -          {
    -            begin: begin,
    -            end: end
    -          }
    -        ];
    -    contains[0].contains = contains;
    -    return contains;
    -  }
    -  const STRING = {
    -    className: 'string',
    -    contains: [
    -      hljs.BACKSLASH_ESCAPE,
    -      SUBST
    -    ],
    -    variants: [
    -      {
    -        begin: /'/,
    -        end: /'/
    -      },
    -      {
    -        begin: /"/,
    -        end: /"/
    -      },
    -      {
    -        begin: /`/,
    -        end: /`/
    -      },
    -      {
    -        begin: '%[Qwi]?\\(',
    -        end: '\\)',
    -        contains: recursiveParen('\\(', '\\)')
    -      },
    -      {
    -        begin: '%[Qwi]?\\[',
    -        end: '\\]',
    -        contains: recursiveParen('\\[', '\\]')
    -      },
    -      {
    -        begin: '%[Qwi]?\\{',
    -        end: /\}/,
    -        contains: recursiveParen(/\{/, /\}/)
    -      },
    -      {
    -        begin: '%[Qwi]?<',
    -        end: '>',
    -        contains: recursiveParen('<', '>')
    -      },
    -      {
    -        begin: '%[Qwi]?\\|',
    -        end: '\\|'
    -      },
    -      {
    -        begin: /<<-\w+$/,
    -        end: /^\s*\w+$/
    -      }
    -    ],
    -    relevance: 0
    -  };
    -  const Q_STRING = {
    -    className: 'string',
    -    variants: [
    -      {
    -        begin: '%q\\(',
    -        end: '\\)',
    -        contains: recursiveParen('\\(', '\\)')
    -      },
    -      {
    -        begin: '%q\\[',
    -        end: '\\]',
    -        contains: recursiveParen('\\[', '\\]')
    -      },
    -      {
    -        begin: '%q\\{',
    -        end: /\}/,
    -        contains: recursiveParen(/\{/, /\}/)
    -      },
    -      {
    -        begin: '%q<',
    -        end: '>',
    -        contains: recursiveParen('<', '>')
    -      },
    -      {
    -        begin: '%q\\|',
    -        end: '\\|'
    -      },
    -      {
    -        begin: /<<-'\w+'$/,
    -        end: /^\s*\w+$/
    -      }
    -    ],
    -    relevance: 0
    -  };
    -  const REGEXP = {
    -    begin: '(?!%\\})(' + hljs.RE_STARTERS_RE + '|\\n|\\b(case|if|select|unless|until|when|while)\\b)\\s*',
    -    keywords: 'case if select unless until when while',
    -    contains: [
    -      {
    -        className: 'regexp',
    -        contains: [
    -          hljs.BACKSLASH_ESCAPE,
    -          SUBST
    -        ],
    -        variants: [
    -          {
    -            begin: '//[a-z]*',
    -            relevance: 0
    -          },
    -          {
    -            begin: '/(?!\\/)',
    -            end: '/[a-z]*'
    -          }
    -        ]
    -      }
    -    ],
    -    relevance: 0
    -  };
    -  const REGEXP2 = {
    -    className: 'regexp',
    -    contains: [
    -      hljs.BACKSLASH_ESCAPE,
    -      SUBST
    -    ],
    -    variants: [
    -      {
    -        begin: '%r\\(',
    -        end: '\\)',
    -        contains: recursiveParen('\\(', '\\)')
    -      },
    -      {
    -        begin: '%r\\[',
    -        end: '\\]',
    -        contains: recursiveParen('\\[', '\\]')
    -      },
    -      {
    -        begin: '%r\\{',
    -        end: /\}/,
    -        contains: recursiveParen(/\{/, /\}/)
    -      },
    -      {
    -        begin: '%r<',
    -        end: '>',
    -        contains: recursiveParen('<', '>')
    -      },
    -      {
    -        begin: '%r\\|',
    -        end: '\\|'
    -      }
    -    ],
    -    relevance: 0
    -  };
    -  const ATTRIBUTE = {
    -    className: 'meta',
    -    begin: '@\\[',
    -    end: '\\]',
    -    contains: [
    -      hljs.inherit(hljs.QUOTE_STRING_MODE, {
    -        className: 'meta-string'
    -      })
    -    ]
    -  };
    -  const CRYSTAL_DEFAULT_CONTAINS = [
    -    EXPANSION,
    -    STRING,
    -    Q_STRING,
    -    REGEXP2,
    -    REGEXP,
    -    ATTRIBUTE,
    -    hljs.HASH_COMMENT_MODE,
    -    {
    -      className: 'class',
    -      beginKeywords: 'class module struct',
    -      end: '$|;',
    -      illegal: /=/,
    -      contains: [
    -        hljs.HASH_COMMENT_MODE,
    -        hljs.inherit(hljs.TITLE_MODE, {
    -          begin: CRYSTAL_PATH_RE
    -        }),
    -        { // relevance booster for inheritance
    -          begin: '<'
    -        }
    -      ]
    -    },
    -    {
    -      className: 'class',
    -      beginKeywords: 'lib enum union',
    -      end: '$|;',
    -      illegal: /=/,
    -      contains: [
    -        hljs.HASH_COMMENT_MODE,
    -        hljs.inherit(hljs.TITLE_MODE, {
    -          begin: CRYSTAL_PATH_RE
    -        })
    -      ]
    -    },
    -    {
    -      beginKeywords: 'annotation',
    -      end: '$|;',
    -      illegal: /=/,
    -      contains: [
    -        hljs.HASH_COMMENT_MODE,
    -        hljs.inherit(hljs.TITLE_MODE, {
    -          begin: CRYSTAL_PATH_RE
    -        })
    -      ],
    -      relevance: 2
    -    },
    -    {
    -      className: 'function',
    -      beginKeywords: 'def',
    -      end: /\B\b/,
    -      contains: [
    -        hljs.inherit(hljs.TITLE_MODE, {
    -          begin: CRYSTAL_METHOD_RE,
    -          endsParent: true
    -        })
    -      ]
    -    },
    -    {
    -      className: 'function',
    -      beginKeywords: 'fun macro',
    -      end: /\B\b/,
    -      contains: [
    -        hljs.inherit(hljs.TITLE_MODE, {
    -          begin: CRYSTAL_METHOD_RE,
    -          endsParent: true
    -        })
    -      ],
    -      relevance: 2
    -    },
    -    {
    -      className: 'symbol',
    -      begin: hljs.UNDERSCORE_IDENT_RE + '(!|\\?)?:',
    -      relevance: 0
    -    },
    -    {
    -      className: 'symbol',
    -      begin: ':',
    -      contains: [
    -        STRING,
    -        {
    -          begin: CRYSTAL_METHOD_RE
    -        }
    -      ],
    -      relevance: 0
    -    },
    -    {
    -      className: 'number',
    -      variants: [
    -        {
    -          begin: '\\b0b([01_]+)' + INT_SUFFIX
    -        },
    -        {
    -          begin: '\\b0o([0-7_]+)' + INT_SUFFIX
    -        },
    -        {
    -          begin: '\\b0x([A-Fa-f0-9_]+)' + INT_SUFFIX
    -        },
    -        {
    -          begin: '\\b([1-9][0-9_]*[0-9]|[0-9])(\\.[0-9][0-9_]*)?([eE]_?[-+]?[0-9_]*)?' + FLOAT_SUFFIX + '(?!_)'
    -        },
    -        {
    -          begin: '\\b([1-9][0-9_]*|0)' + INT_SUFFIX
    -        }
    -      ],
    -      relevance: 0
    -    }
    -  ];
    -  SUBST.contains = CRYSTAL_DEFAULT_CONTAINS;
    -  EXPANSION.contains = CRYSTAL_DEFAULT_CONTAINS.slice(1); // without EXPANSION
    -
    -  return {
    -    name: 'Crystal',
    -    aliases: [ 'cr' ],
    -    keywords: CRYSTAL_KEYWORDS,
    -    contains: CRYSTAL_DEFAULT_CONTAINS
    -  };
    -}
    -
    -module.exports = crystal;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/csharp.js b/claude-code-source/node_modules/highlight.js/lib/languages/csharp.js
    deleted file mode 100644
    index b708731f..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/csharp.js
    +++ /dev/null
    @@ -1,441 +0,0 @@
    -/*
    -Language: C#
    -Author: Jason Diamond 
    -Contributor: Nicolas LLOBERA , Pieter Vantorre , David Pine 
    -Website: https://docs.microsoft.com/en-us/dotnet/csharp/
    -Category: common
    -*/
    -
    -/** @type LanguageFn */
    -function csharp(hljs) {
    -  const BUILT_IN_KEYWORDS = [
    -    'bool',
    -    'byte',
    -    'char',
    -    'decimal',
    -    'delegate',
    -    'double',
    -    'dynamic',
    -    'enum',
    -    'float',
    -    'int',
    -    'long',
    -    'nint',
    -    'nuint',
    -    'object',
    -    'sbyte',
    -    'short',
    -    'string',
    -    'ulong',
    -    'uint',
    -    'ushort'
    -  ];
    -  const FUNCTION_MODIFIERS = [
    -    'public',
    -    'private',
    -    'protected',
    -    'static',
    -    'internal',
    -    'protected',
    -    'abstract',
    -    'async',
    -    'extern',
    -    'override',
    -    'unsafe',
    -    'virtual',
    -    'new',
    -    'sealed',
    -    'partial'
    -  ];
    -  const LITERAL_KEYWORDS = [
    -    'default',
    -    'false',
    -    'null',
    -    'true'
    -  ];
    -  const NORMAL_KEYWORDS = [
    -    'abstract',
    -    'as',
    -    'base',
    -    'break',
    -    'case',
    -    'class',
    -    'const',
    -    'continue',
    -    'do',
    -    'else',
    -    'event',
    -    'explicit',
    -    'extern',
    -    'finally',
    -    'fixed',
    -    'for',
    -    'foreach',
    -    'goto',
    -    'if',
    -    'implicit',
    -    'in',
    -    'interface',
    -    'internal',
    -    'is',
    -    'lock',
    -    'namespace',
    -    'new',
    -    'operator',
    -    'out',
    -    'override',
    -    'params',
    -    'private',
    -    'protected',
    -    'public',
    -    'readonly',
    -    'record',
    -    'ref',
    -    'return',
    -    'sealed',
    -    'sizeof',
    -    'stackalloc',
    -    'static',
    -    'struct',
    -    'switch',
    -    'this',
    -    'throw',
    -    'try',
    -    'typeof',
    -    'unchecked',
    -    'unsafe',
    -    'using',
    -    'virtual',
    -    'void',
    -    'volatile',
    -    'while'
    -  ];
    -  const CONTEXTUAL_KEYWORDS = [
    -    'add',
    -    'alias',
    -    'and',
    -    'ascending',
    -    'async',
    -    'await',
    -    'by',
    -    'descending',
    -    'equals',
    -    'from',
    -    'get',
    -    'global',
    -    'group',
    -    'init',
    -    'into',
    -    'join',
    -    'let',
    -    'nameof',
    -    'not',
    -    'notnull',
    -    'on',
    -    'or',
    -    'orderby',
    -    'partial',
    -    'remove',
    -    'select',
    -    'set',
    -    'unmanaged',
    -    'value|0',
    -    'var',
    -    'when',
    -    'where',
    -    'with',
    -    'yield'
    -  ];
    -
    -  const KEYWORDS = {
    -    keyword: NORMAL_KEYWORDS.concat(CONTEXTUAL_KEYWORDS),
    -    built_in: BUILT_IN_KEYWORDS,
    -    literal: LITERAL_KEYWORDS
    -  };
    -  const TITLE_MODE = hljs.inherit(hljs.TITLE_MODE, {
    -    begin: '[a-zA-Z](\\.?\\w)*'
    -  });
    -  const NUMBERS = {
    -    className: 'number',
    -    variants: [
    -      {
    -        begin: '\\b(0b[01\']+)'
    -      },
    -      {
    -        begin: '(-?)\\b([\\d\']+(\\.[\\d\']*)?|\\.[\\d\']+)(u|U|l|L|ul|UL|f|F|b|B)'
    -      },
    -      {
    -        begin: '(-?)(\\b0[xX][a-fA-F0-9\']+|(\\b[\\d\']+(\\.[\\d\']*)?|\\.[\\d\']+)([eE][-+]?[\\d\']+)?)'
    -      }
    -    ],
    -    relevance: 0
    -  };
    -  const VERBATIM_STRING = {
    -    className: 'string',
    -    begin: '@"',
    -    end: '"',
    -    contains: [
    -      {
    -        begin: '""'
    -      }
    -    ]
    -  };
    -  const VERBATIM_STRING_NO_LF = hljs.inherit(VERBATIM_STRING, {
    -    illegal: /\n/
    -  });
    -  const SUBST = {
    -    className: 'subst',
    -    begin: /\{/,
    -    end: /\}/,
    -    keywords: KEYWORDS
    -  };
    -  const SUBST_NO_LF = hljs.inherit(SUBST, {
    -    illegal: /\n/
    -  });
    -  const INTERPOLATED_STRING = {
    -    className: 'string',
    -    begin: /\$"/,
    -    end: '"',
    -    illegal: /\n/,
    -    contains: [
    -      {
    -        begin: /\{\{/
    -      },
    -      {
    -        begin: /\}\}/
    -      },
    -      hljs.BACKSLASH_ESCAPE,
    -      SUBST_NO_LF
    -    ]
    -  };
    -  const INTERPOLATED_VERBATIM_STRING = {
    -    className: 'string',
    -    begin: /\$@"/,
    -    end: '"',
    -    contains: [
    -      {
    -        begin: /\{\{/
    -      },
    -      {
    -        begin: /\}\}/
    -      },
    -      {
    -        begin: '""'
    -      },
    -      SUBST
    -    ]
    -  };
    -  const INTERPOLATED_VERBATIM_STRING_NO_LF = hljs.inherit(INTERPOLATED_VERBATIM_STRING, {
    -    illegal: /\n/,
    -    contains: [
    -      {
    -        begin: /\{\{/
    -      },
    -      {
    -        begin: /\}\}/
    -      },
    -      {
    -        begin: '""'
    -      },
    -      SUBST_NO_LF
    -    ]
    -  });
    -  SUBST.contains = [
    -    INTERPOLATED_VERBATIM_STRING,
    -    INTERPOLATED_STRING,
    -    VERBATIM_STRING,
    -    hljs.APOS_STRING_MODE,
    -    hljs.QUOTE_STRING_MODE,
    -    NUMBERS,
    -    hljs.C_BLOCK_COMMENT_MODE
    -  ];
    -  SUBST_NO_LF.contains = [
    -    INTERPOLATED_VERBATIM_STRING_NO_LF,
    -    INTERPOLATED_STRING,
    -    VERBATIM_STRING_NO_LF,
    -    hljs.APOS_STRING_MODE,
    -    hljs.QUOTE_STRING_MODE,
    -    NUMBERS,
    -    hljs.inherit(hljs.C_BLOCK_COMMENT_MODE, {
    -      illegal: /\n/
    -    })
    -  ];
    -  const STRING = {
    -    variants: [
    -      INTERPOLATED_VERBATIM_STRING,
    -      INTERPOLATED_STRING,
    -      VERBATIM_STRING,
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE
    -    ]
    -  };
    -
    -  const GENERIC_MODIFIER = {
    -    begin: "<",
    -    end: ">",
    -    contains: [
    -      {
    -        beginKeywords: "in out"
    -      },
    -      TITLE_MODE
    -    ]
    -  };
    -  const TYPE_IDENT_RE = hljs.IDENT_RE + '(<' + hljs.IDENT_RE + '(\\s*,\\s*' + hljs.IDENT_RE + ')*>)?(\\[\\])?';
    -  const AT_IDENTIFIER = {
    -    // prevents expressions like `@class` from incorrect flagging
    -    // `class` as a keyword
    -    begin: "@" + hljs.IDENT_RE,
    -    relevance: 0
    -  };
    -
    -  return {
    -    name: 'C#',
    -    aliases: [
    -      'cs',
    -      'c#'
    -    ],
    -    keywords: KEYWORDS,
    -    illegal: /::/,
    -    contains: [
    -      hljs.COMMENT(
    -        '///',
    -        '$',
    -        {
    -          returnBegin: true,
    -          contains: [
    -            {
    -              className: 'doctag',
    -              variants: [
    -                {
    -                  begin: '///',
    -                  relevance: 0
    -                },
    -                {
    -                  begin: ''
    -                },
    -                {
    -                  begin: ''
    -                }
    -              ]
    -            }
    -          ]
    -        }
    -      ),
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      {
    -        className: 'meta',
    -        begin: '#',
    -        end: '$',
    -        keywords: {
    -          'meta-keyword': 'if else elif endif define undef warning error line region endregion pragma checksum'
    -        }
    -      },
    -      STRING,
    -      NUMBERS,
    -      {
    -        beginKeywords: 'class interface',
    -        relevance: 0,
    -        end: /[{;=]/,
    -        illegal: /[^\s:,]/,
    -        contains: [
    -          {
    -            beginKeywords: "where class"
    -          },
    -          TITLE_MODE,
    -          GENERIC_MODIFIER,
    -          hljs.C_LINE_COMMENT_MODE,
    -          hljs.C_BLOCK_COMMENT_MODE
    -        ]
    -      },
    -      {
    -        beginKeywords: 'namespace',
    -        relevance: 0,
    -        end: /[{;=]/,
    -        illegal: /[^\s:]/,
    -        contains: [
    -          TITLE_MODE,
    -          hljs.C_LINE_COMMENT_MODE,
    -          hljs.C_BLOCK_COMMENT_MODE
    -        ]
    -      },
    -      {
    -        beginKeywords: 'record',
    -        relevance: 0,
    -        end: /[{;=]/,
    -        illegal: /[^\s:]/,
    -        contains: [
    -          TITLE_MODE,
    -          GENERIC_MODIFIER,
    -          hljs.C_LINE_COMMENT_MODE,
    -          hljs.C_BLOCK_COMMENT_MODE
    -        ]
    -      },
    -      {
    -        // [Attributes("")]
    -        className: 'meta',
    -        begin: '^\\s*\\[',
    -        excludeBegin: true,
    -        end: '\\]',
    -        excludeEnd: true,
    -        contains: [
    -          {
    -            className: 'meta-string',
    -            begin: /"/,
    -            end: /"/
    -          }
    -        ]
    -      },
    -      {
    -        // Expression keywords prevent 'keyword Name(...)' from being
    -        // recognized as a function definition
    -        beginKeywords: 'new return throw await else',
    -        relevance: 0
    -      },
    -      {
    -        className: 'function',
    -        begin: '(' + TYPE_IDENT_RE + '\\s+)+' + hljs.IDENT_RE + '\\s*(<.+>\\s*)?\\(',
    -        returnBegin: true,
    -        end: /\s*[{;=]/,
    -        excludeEnd: true,
    -        keywords: KEYWORDS,
    -        contains: [
    -          // prevents these from being highlighted `title`
    -          {
    -            beginKeywords: FUNCTION_MODIFIERS.join(" "),
    -            relevance: 0
    -          },
    -          {
    -            begin: hljs.IDENT_RE + '\\s*(<.+>\\s*)?\\(',
    -            returnBegin: true,
    -            contains: [
    -              hljs.TITLE_MODE,
    -              GENERIC_MODIFIER
    -            ],
    -            relevance: 0
    -          },
    -          {
    -            className: 'params',
    -            begin: /\(/,
    -            end: /\)/,
    -            excludeBegin: true,
    -            excludeEnd: true,
    -            keywords: KEYWORDS,
    -            relevance: 0,
    -            contains: [
    -              STRING,
    -              NUMBERS,
    -              hljs.C_BLOCK_COMMENT_MODE
    -            ]
    -          },
    -          hljs.C_LINE_COMMENT_MODE,
    -          hljs.C_BLOCK_COMMENT_MODE
    -        ]
    -      },
    -      AT_IDENTIFIER
    -    ]
    -  };
    -}
    -
    -module.exports = csharp;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/csp.js b/claude-code-source/node_modules/highlight.js/lib/languages/csp.js
    deleted file mode 100644
    index 6539c47b..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/csp.js
    +++ /dev/null
    @@ -1,37 +0,0 @@
    -/*
    -Language: CSP
    -Description: Content Security Policy definition highlighting
    -Author: Taras 
    -Website: https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP
    -
    -vim: ts=2 sw=2 st=2
    -*/
    -
    -/** @type LanguageFn */
    -function csp(hljs) {
    -  return {
    -    name: 'CSP',
    -    case_insensitive: false,
    -    keywords: {
    -      $pattern: '[a-zA-Z][a-zA-Z0-9_-]*',
    -      keyword: 'base-uri child-src connect-src default-src font-src form-action ' +
    -        'frame-ancestors frame-src img-src media-src object-src plugin-types ' +
    -        'report-uri sandbox script-src style-src'
    -    },
    -    contains: [
    -      {
    -        className: 'string',
    -        begin: "'",
    -        end: "'"
    -      },
    -      {
    -        className: 'attribute',
    -        begin: '^Content',
    -        end: ':',
    -        excludeEnd: true
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = csp;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/css.js b/claude-code-source/node_modules/highlight.js/lib/languages/css.js
    deleted file mode 100644
    index b0e21b6a..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/css.js
    +++ /dev/null
    @@ -1,608 +0,0 @@
    -const MODES = (hljs) => {
    -  return {
    -    IMPORTANT: {
    -      className: 'meta',
    -      begin: '!important'
    -    },
    -    HEXCOLOR: {
    -      className: 'number',
    -      begin: '#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})'
    -    },
    -    ATTRIBUTE_SELECTOR_MODE: {
    -      className: 'selector-attr',
    -      begin: /\[/,
    -      end: /\]/,
    -      illegal: '$',
    -      contains: [
    -        hljs.APOS_STRING_MODE,
    -        hljs.QUOTE_STRING_MODE
    -      ]
    -    }
    -  };
    -};
    -
    -const TAGS = [
    -  'a',
    -  'abbr',
    -  'address',
    -  'article',
    -  'aside',
    -  'audio',
    -  'b',
    -  'blockquote',
    -  'body',
    -  'button',
    -  'canvas',
    -  'caption',
    -  'cite',
    -  'code',
    -  'dd',
    -  'del',
    -  'details',
    -  'dfn',
    -  'div',
    -  'dl',
    -  'dt',
    -  'em',
    -  'fieldset',
    -  'figcaption',
    -  'figure',
    -  'footer',
    -  'form',
    -  'h1',
    -  'h2',
    -  'h3',
    -  'h4',
    -  'h5',
    -  'h6',
    -  'header',
    -  'hgroup',
    -  'html',
    -  'i',
    -  'iframe',
    -  'img',
    -  'input',
    -  'ins',
    -  'kbd',
    -  'label',
    -  'legend',
    -  'li',
    -  'main',
    -  'mark',
    -  'menu',
    -  'nav',
    -  'object',
    -  'ol',
    -  'p',
    -  'q',
    -  'quote',
    -  'samp',
    -  'section',
    -  'span',
    -  'strong',
    -  'summary',
    -  'sup',
    -  'table',
    -  'tbody',
    -  'td',
    -  'textarea',
    -  'tfoot',
    -  'th',
    -  'thead',
    -  'time',
    -  'tr',
    -  'ul',
    -  'var',
    -  'video'
    -];
    -
    -const MEDIA_FEATURES = [
    -  'any-hover',
    -  'any-pointer',
    -  'aspect-ratio',
    -  'color',
    -  'color-gamut',
    -  'color-index',
    -  'device-aspect-ratio',
    -  'device-height',
    -  'device-width',
    -  'display-mode',
    -  'forced-colors',
    -  'grid',
    -  'height',
    -  'hover',
    -  'inverted-colors',
    -  'monochrome',
    -  'orientation',
    -  'overflow-block',
    -  'overflow-inline',
    -  'pointer',
    -  'prefers-color-scheme',
    -  'prefers-contrast',
    -  'prefers-reduced-motion',
    -  'prefers-reduced-transparency',
    -  'resolution',
    -  'scan',
    -  'scripting',
    -  'update',
    -  'width',
    -  // TODO: find a better solution?
    -  'min-width',
    -  'max-width',
    -  'min-height',
    -  'max-height'
    -];
    -
    -// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes
    -const PSEUDO_CLASSES = [
    -  'active',
    -  'any-link',
    -  'blank',
    -  'checked',
    -  'current',
    -  'default',
    -  'defined',
    -  'dir', // dir()
    -  'disabled',
    -  'drop',
    -  'empty',
    -  'enabled',
    -  'first',
    -  'first-child',
    -  'first-of-type',
    -  'fullscreen',
    -  'future',
    -  'focus',
    -  'focus-visible',
    -  'focus-within',
    -  'has', // has()
    -  'host', // host or host()
    -  'host-context', // host-context()
    -  'hover',
    -  'indeterminate',
    -  'in-range',
    -  'invalid',
    -  'is', // is()
    -  'lang', // lang()
    -  'last-child',
    -  'last-of-type',
    -  'left',
    -  'link',
    -  'local-link',
    -  'not', // not()
    -  'nth-child', // nth-child()
    -  'nth-col', // nth-col()
    -  'nth-last-child', // nth-last-child()
    -  'nth-last-col', // nth-last-col()
    -  'nth-last-of-type', //nth-last-of-type()
    -  'nth-of-type', //nth-of-type()
    -  'only-child',
    -  'only-of-type',
    -  'optional',
    -  'out-of-range',
    -  'past',
    -  'placeholder-shown',
    -  'read-only',
    -  'read-write',
    -  'required',
    -  'right',
    -  'root',
    -  'scope',
    -  'target',
    -  'target-within',
    -  'user-invalid',
    -  'valid',
    -  'visited',
    -  'where' // where()
    -];
    -
    -// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements
    -const PSEUDO_ELEMENTS = [
    -  'after',
    -  'backdrop',
    -  'before',
    -  'cue',
    -  'cue-region',
    -  'first-letter',
    -  'first-line',
    -  'grammar-error',
    -  'marker',
    -  'part',
    -  'placeholder',
    -  'selection',
    -  'slotted',
    -  'spelling-error'
    -];
    -
    -const ATTRIBUTES = [
    -  'align-content',
    -  'align-items',
    -  'align-self',
    -  'animation',
    -  'animation-delay',
    -  'animation-direction',
    -  'animation-duration',
    -  'animation-fill-mode',
    -  'animation-iteration-count',
    -  'animation-name',
    -  'animation-play-state',
    -  'animation-timing-function',
    -  'auto',
    -  'backface-visibility',
    -  'background',
    -  'background-attachment',
    -  'background-clip',
    -  'background-color',
    -  'background-image',
    -  'background-origin',
    -  'background-position',
    -  'background-repeat',
    -  'background-size',
    -  'border',
    -  'border-bottom',
    -  'border-bottom-color',
    -  'border-bottom-left-radius',
    -  'border-bottom-right-radius',
    -  'border-bottom-style',
    -  'border-bottom-width',
    -  'border-collapse',
    -  'border-color',
    -  'border-image',
    -  'border-image-outset',
    -  'border-image-repeat',
    -  'border-image-slice',
    -  'border-image-source',
    -  'border-image-width',
    -  'border-left',
    -  'border-left-color',
    -  'border-left-style',
    -  'border-left-width',
    -  'border-radius',
    -  'border-right',
    -  'border-right-color',
    -  'border-right-style',
    -  'border-right-width',
    -  'border-spacing',
    -  'border-style',
    -  'border-top',
    -  'border-top-color',
    -  'border-top-left-radius',
    -  'border-top-right-radius',
    -  'border-top-style',
    -  'border-top-width',
    -  'border-width',
    -  'bottom',
    -  'box-decoration-break',
    -  'box-shadow',
    -  'box-sizing',
    -  'break-after',
    -  'break-before',
    -  'break-inside',
    -  'caption-side',
    -  'clear',
    -  'clip',
    -  'clip-path',
    -  'color',
    -  'column-count',
    -  'column-fill',
    -  'column-gap',
    -  'column-rule',
    -  'column-rule-color',
    -  'column-rule-style',
    -  'column-rule-width',
    -  'column-span',
    -  'column-width',
    -  'columns',
    -  'content',
    -  'counter-increment',
    -  'counter-reset',
    -  'cursor',
    -  'direction',
    -  'display',
    -  'empty-cells',
    -  'filter',
    -  'flex',
    -  'flex-basis',
    -  'flex-direction',
    -  'flex-flow',
    -  'flex-grow',
    -  'flex-shrink',
    -  'flex-wrap',
    -  'float',
    -  'font',
    -  'font-display',
    -  'font-family',
    -  'font-feature-settings',
    -  'font-kerning',
    -  'font-language-override',
    -  'font-size',
    -  'font-size-adjust',
    -  'font-smoothing',
    -  'font-stretch',
    -  'font-style',
    -  'font-variant',
    -  'font-variant-ligatures',
    -  'font-variation-settings',
    -  'font-weight',
    -  'height',
    -  'hyphens',
    -  'icon',
    -  'image-orientation',
    -  'image-rendering',
    -  'image-resolution',
    -  'ime-mode',
    -  'inherit',
    -  'initial',
    -  'justify-content',
    -  'left',
    -  'letter-spacing',
    -  'line-height',
    -  'list-style',
    -  'list-style-image',
    -  'list-style-position',
    -  'list-style-type',
    -  'margin',
    -  'margin-bottom',
    -  'margin-left',
    -  'margin-right',
    -  'margin-top',
    -  'marks',
    -  'mask',
    -  'max-height',
    -  'max-width',
    -  'min-height',
    -  'min-width',
    -  'nav-down',
    -  'nav-index',
    -  'nav-left',
    -  'nav-right',
    -  'nav-up',
    -  'none',
    -  'normal',
    -  'object-fit',
    -  'object-position',
    -  'opacity',
    -  'order',
    -  'orphans',
    -  'outline',
    -  'outline-color',
    -  'outline-offset',
    -  'outline-style',
    -  'outline-width',
    -  'overflow',
    -  'overflow-wrap',
    -  'overflow-x',
    -  'overflow-y',
    -  'padding',
    -  'padding-bottom',
    -  'padding-left',
    -  'padding-right',
    -  'padding-top',
    -  'page-break-after',
    -  'page-break-before',
    -  'page-break-inside',
    -  'perspective',
    -  'perspective-origin',
    -  'pointer-events',
    -  'position',
    -  'quotes',
    -  'resize',
    -  'right',
    -  'src', // @font-face
    -  'tab-size',
    -  'table-layout',
    -  'text-align',
    -  'text-align-last',
    -  'text-decoration',
    -  'text-decoration-color',
    -  'text-decoration-line',
    -  'text-decoration-style',
    -  'text-indent',
    -  'text-overflow',
    -  'text-rendering',
    -  'text-shadow',
    -  'text-transform',
    -  'text-underline-position',
    -  'top',
    -  'transform',
    -  'transform-origin',
    -  'transform-style',
    -  'transition',
    -  'transition-delay',
    -  'transition-duration',
    -  'transition-property',
    -  'transition-timing-function',
    -  'unicode-bidi',
    -  'vertical-align',
    -  'visibility',
    -  'white-space',
    -  'widows',
    -  'width',
    -  'word-break',
    -  'word-spacing',
    -  'word-wrap',
    -  'z-index'
    -  // reverse makes sure longer attributes `font-weight` are matched fully
    -  // instead of getting false positives on say `font`
    -].reverse();
    -
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function lookahead(re) {
    -  return concat('(?=', re, ')');
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: CSS
    -Category: common, css
    -Website: https://developer.mozilla.org/en-US/docs/Web/CSS
    -*/
    -
    -/** @type LanguageFn */
    -function css(hljs) {
    -  const modes = MODES(hljs);
    -  const FUNCTION_DISPATCH = {
    -    className: "built_in",
    -    begin: /[\w-]+(?=\()/
    -  };
    -  const VENDOR_PREFIX = {
    -    begin: /-(webkit|moz|ms|o)-(?=[a-z])/
    -  };
    -  const AT_MODIFIERS = "and or not only";
    -  const AT_PROPERTY_RE = /@-?\w[\w]*(-\w+)*/; // @-webkit-keyframes
    -  const IDENT_RE = '[a-zA-Z-][a-zA-Z0-9_-]*';
    -  const STRINGS = [
    -    hljs.APOS_STRING_MODE,
    -    hljs.QUOTE_STRING_MODE
    -  ];
    -
    -  return {
    -    name: 'CSS',
    -    case_insensitive: true,
    -    illegal: /[=|'\$]/,
    -    keywords: {
    -      keyframePosition: "from to"
    -    },
    -    classNameAliases: {
    -      // for visual continuity with `tag {}` and because we
    -      // don't have a great class for this?
    -      keyframePosition: "selector-tag"
    -    },
    -    contains: [
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      VENDOR_PREFIX,
    -      // to recognize keyframe 40% etc which are outside the scope of our
    -      // attribute value mode
    -      hljs.CSS_NUMBER_MODE,
    -      {
    -        className: 'selector-id',
    -        begin: /#[A-Za-z0-9_-]+/,
    -        relevance: 0
    -      },
    -      {
    -        className: 'selector-class',
    -        begin: '\\.' + IDENT_RE,
    -        relevance: 0
    -      },
    -      modes.ATTRIBUTE_SELECTOR_MODE,
    -      {
    -        className: 'selector-pseudo',
    -        variants: [
    -          {
    -            begin: ':(' + PSEUDO_CLASSES.join('|') + ')'
    -          },
    -          {
    -            begin: '::(' + PSEUDO_ELEMENTS.join('|') + ')'
    -          }
    -        ]
    -      },
    -      // we may actually need this (12/2020)
    -      // { // pseudo-selector params
    -      //   begin: /\(/,
    -      //   end: /\)/,
    -      //   contains: [ hljs.CSS_NUMBER_MODE ]
    -      // },
    -      {
    -        className: 'attribute',
    -        begin: '\\b(' + ATTRIBUTES.join('|') + ')\\b'
    -      },
    -      // attribute values
    -      {
    -        begin: ':',
    -        end: '[;}]',
    -        contains: [
    -          modes.HEXCOLOR,
    -          modes.IMPORTANT,
    -          hljs.CSS_NUMBER_MODE,
    -          ...STRINGS,
    -          // needed to highlight these as strings and to avoid issues with
    -          // illegal characters that might be inside urls that would tigger the
    -          // languages illegal stack
    -          {
    -            begin: /(url|data-uri)\(/,
    -            end: /\)/,
    -            relevance: 0, // from keywords
    -            keywords: {
    -              built_in: "url data-uri"
    -            },
    -            contains: [
    -              {
    -                className: "string",
    -                // any character other than `)` as in `url()` will be the start
    -                // of a string, which ends with `)` (from the parent mode)
    -                begin: /[^)]/,
    -                endsWithParent: true,
    -                excludeEnd: true
    -              }
    -            ]
    -          },
    -          FUNCTION_DISPATCH
    -        ]
    -      },
    -      {
    -        begin: lookahead(/@/),
    -        end: '[{;]',
    -        relevance: 0,
    -        illegal: /:/, // break on Less variables @var: ...
    -        contains: [
    -          {
    -            className: 'keyword',
    -            begin: AT_PROPERTY_RE
    -          },
    -          {
    -            begin: /\s/,
    -            endsWithParent: true,
    -            excludeEnd: true,
    -            relevance: 0,
    -            keywords: {
    -              $pattern: /[a-z-]+/,
    -              keyword: AT_MODIFIERS,
    -              attribute: MEDIA_FEATURES.join(" ")
    -            },
    -            contains: [
    -              {
    -                begin: /[a-z-]+(?=:)/,
    -                className: "attribute"
    -              },
    -              ...STRINGS,
    -              hljs.CSS_NUMBER_MODE
    -            ]
    -          }
    -        ]
    -      },
    -      {
    -        className: 'selector-tag',
    -        begin: '\\b(' + TAGS.join('|') + ')\\b'
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = css;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/d.js b/claude-code-source/node_modules/highlight.js/lib/languages/d.js
    deleted file mode 100644
    index f302283f..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/d.js
    +++ /dev/null
    @@ -1,271 +0,0 @@
    -/*
    -Language: D
    -Author: Aleksandar Ruzicic 
    -Description: D is a language with C-like syntax and static typing. It pragmatically combines efficiency, control, and modeling power, with safety and programmer productivity.
    -Version: 1.0a
    -Website: https://dlang.org
    -Date: 2012-04-08
    -*/
    -
    -/**
    - * Known issues:
    - *
    - * - invalid hex string literals will be recognized as a double quoted strings
    - *   but 'x' at the beginning of string will not be matched
    - *
    - * - delimited string literals are not checked for matching end delimiter
    - *   (not possible to do with js regexp)
    - *
    - * - content of token string is colored as a string (i.e. no keyword coloring inside a token string)
    - *   also, content of token string is not validated to contain only valid D tokens
    - *
    - * - special token sequence rule is not strictly following D grammar (anything following #line
    - *   up to the end of line is matched as special token sequence)
    - */
    -
    -/** @type LanguageFn */
    -function d(hljs) {
    -  /**
    -   * Language keywords
    -   *
    -   * @type {Object}
    -   */
    -  const D_KEYWORDS = {
    -    $pattern: hljs.UNDERSCORE_IDENT_RE,
    -    keyword:
    -      'abstract alias align asm assert auto body break byte case cast catch class ' +
    -      'const continue debug default delete deprecated do else enum export extern final ' +
    -      'finally for foreach foreach_reverse|10 goto if immutable import in inout int ' +
    -      'interface invariant is lazy macro mixin module new nothrow out override package ' +
    -      'pragma private protected public pure ref return scope shared static struct ' +
    -      'super switch synchronized template this throw try typedef typeid typeof union ' +
    -      'unittest version void volatile while with __FILE__ __LINE__ __gshared|10 ' +
    -      '__thread __traits __DATE__ __EOF__ __TIME__ __TIMESTAMP__ __VENDOR__ __VERSION__',
    -    built_in:
    -      'bool cdouble cent cfloat char creal dchar delegate double dstring float function ' +
    -      'idouble ifloat ireal long real short string ubyte ucent uint ulong ushort wchar ' +
    -      'wstring',
    -    literal:
    -      'false null true'
    -  };
    -
    -  /**
    -   * Number literal regexps
    -   *
    -   * @type {String}
    -   */
    -  const decimal_integer_re = '(0|[1-9][\\d_]*)';
    -  const decimal_integer_nosus_re = '(0|[1-9][\\d_]*|\\d[\\d_]*|[\\d_]+?\\d)';
    -  const binary_integer_re = '0[bB][01_]+';
    -  const hexadecimal_digits_re = '([\\da-fA-F][\\da-fA-F_]*|_[\\da-fA-F][\\da-fA-F_]*)';
    -  const hexadecimal_integer_re = '0[xX]' + hexadecimal_digits_re;
    -
    -  const decimal_exponent_re = '([eE][+-]?' + decimal_integer_nosus_re + ')';
    -  const decimal_float_re = '(' + decimal_integer_nosus_re + '(\\.\\d*|' + decimal_exponent_re + ')|' +
    -                '\\d+\\.' + decimal_integer_nosus_re + '|' +
    -                '\\.' + decimal_integer_re + decimal_exponent_re + '?' +
    -              ')';
    -  const hexadecimal_float_re = '(0[xX](' +
    -                  hexadecimal_digits_re + '\\.' + hexadecimal_digits_re + '|' +
    -                  '\\.?' + hexadecimal_digits_re +
    -                 ')[pP][+-]?' + decimal_integer_nosus_re + ')';
    -
    -  const integer_re = '(' +
    -      decimal_integer_re + '|' +
    -      binary_integer_re + '|' +
    -       hexadecimal_integer_re +
    -    ')';
    -
    -  const float_re = '(' +
    -      hexadecimal_float_re + '|' +
    -      decimal_float_re +
    -    ')';
    -
    -  /**
    -   * Escape sequence supported in D string and character literals
    -   *
    -   * @type {String}
    -   */
    -  const escape_sequence_re = '\\\\(' +
    -              '[\'"\\?\\\\abfnrtv]|' + // common escapes
    -              'u[\\dA-Fa-f]{4}|' + // four hex digit unicode codepoint
    -              '[0-7]{1,3}|' + // one to three octal digit ascii char code
    -              'x[\\dA-Fa-f]{2}|' + // two hex digit ascii char code
    -              'U[\\dA-Fa-f]{8}' + // eight hex digit unicode codepoint
    -              ')|' +
    -              '&[a-zA-Z\\d]{2,};'; // named character entity
    -
    -  /**
    -   * D integer number literals
    -   *
    -   * @type {Object}
    -   */
    -  const D_INTEGER_MODE = {
    -    className: 'number',
    -    begin: '\\b' + integer_re + '(L|u|U|Lu|LU|uL|UL)?',
    -    relevance: 0
    -  };
    -
    -  /**
    -   * [D_FLOAT_MODE description]
    -   * @type {Object}
    -   */
    -  const D_FLOAT_MODE = {
    -    className: 'number',
    -    begin: '\\b(' +
    -        float_re + '([fF]|L|i|[fF]i|Li)?|' +
    -        integer_re + '(i|[fF]i|Li)' +
    -      ')',
    -    relevance: 0
    -  };
    -
    -  /**
    -   * D character literal
    -   *
    -   * @type {Object}
    -   */
    -  const D_CHARACTER_MODE = {
    -    className: 'string',
    -    begin: '\'(' + escape_sequence_re + '|.)',
    -    end: '\'',
    -    illegal: '.'
    -  };
    -
    -  /**
    -   * D string escape sequence
    -   *
    -   * @type {Object}
    -   */
    -  const D_ESCAPE_SEQUENCE = {
    -    begin: escape_sequence_re,
    -    relevance: 0
    -  };
    -
    -  /**
    -   * D double quoted string literal
    -   *
    -   * @type {Object}
    -   */
    -  const D_STRING_MODE = {
    -    className: 'string',
    -    begin: '"',
    -    contains: [D_ESCAPE_SEQUENCE],
    -    end: '"[cwd]?'
    -  };
    -
    -  /**
    -   * D wysiwyg and delimited string literals
    -   *
    -   * @type {Object}
    -   */
    -  const D_WYSIWYG_DELIMITED_STRING_MODE = {
    -    className: 'string',
    -    begin: '[rq]"',
    -    end: '"[cwd]?',
    -    relevance: 5
    -  };
    -
    -  /**
    -   * D alternate wysiwyg string literal
    -   *
    -   * @type {Object}
    -   */
    -  const D_ALTERNATE_WYSIWYG_STRING_MODE = {
    -    className: 'string',
    -    begin: '`',
    -    end: '`[cwd]?'
    -  };
    -
    -  /**
    -   * D hexadecimal string literal
    -   *
    -   * @type {Object}
    -   */
    -  const D_HEX_STRING_MODE = {
    -    className: 'string',
    -    begin: 'x"[\\da-fA-F\\s\\n\\r]*"[cwd]?',
    -    relevance: 10
    -  };
    -
    -  /**
    -   * D delimited string literal
    -   *
    -   * @type {Object}
    -   */
    -  const D_TOKEN_STRING_MODE = {
    -    className: 'string',
    -    begin: 'q"\\{',
    -    end: '\\}"'
    -  };
    -
    -  /**
    -   * Hashbang support
    -   *
    -   * @type {Object}
    -   */
    -  const D_HASHBANG_MODE = {
    -    className: 'meta',
    -    begin: '^#!',
    -    end: '$',
    -    relevance: 5
    -  };
    -
    -  /**
    -   * D special token sequence
    -   *
    -   * @type {Object}
    -   */
    -  const D_SPECIAL_TOKEN_SEQUENCE_MODE = {
    -    className: 'meta',
    -    begin: '#(line)',
    -    end: '$',
    -    relevance: 5
    -  };
    -
    -  /**
    -   * D attributes
    -   *
    -   * @type {Object}
    -   */
    -  const D_ATTRIBUTE_MODE = {
    -    className: 'keyword',
    -    begin: '@[a-zA-Z_][a-zA-Z_\\d]*'
    -  };
    -
    -  /**
    -   * D nesting comment
    -   *
    -   * @type {Object}
    -   */
    -  const D_NESTING_COMMENT_MODE = hljs.COMMENT(
    -    '\\/\\+',
    -    '\\+\\/',
    -    {
    -      contains: ['self'],
    -      relevance: 10
    -    }
    -  );
    -
    -  return {
    -    name: 'D',
    -    keywords: D_KEYWORDS,
    -    contains: [
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      D_NESTING_COMMENT_MODE,
    -      D_HEX_STRING_MODE,
    -      D_STRING_MODE,
    -      D_WYSIWYG_DELIMITED_STRING_MODE,
    -      D_ALTERNATE_WYSIWYG_STRING_MODE,
    -      D_TOKEN_STRING_MODE,
    -      D_FLOAT_MODE,
    -      D_INTEGER_MODE,
    -      D_CHARACTER_MODE,
    -      D_HASHBANG_MODE,
    -      D_SPECIAL_TOKEN_SEQUENCE_MODE,
    -      D_ATTRIBUTE_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = d;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/dart.js b/claude-code-source/node_modules/highlight.js/lib/languages/dart.js
    deleted file mode 100644
    index e8961c89..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/dart.js
    +++ /dev/null
    @@ -1,199 +0,0 @@
    -/*
    -Language: Dart
    -Requires: markdown.js
    -Author: Maxim Dikun 
    -Description: Dart a modern, object-oriented language developed by Google. For more information see https://www.dartlang.org/
    -Website: https://dart.dev
    -Category: scripting
    -*/
    -
    -/** @type LanguageFn */
    -function dart(hljs) {
    -  const SUBST = {
    -    className: 'subst',
    -    variants: [{
    -      begin: '\\$[A-Za-z0-9_]+'
    -    }]
    -  };
    -
    -  const BRACED_SUBST = {
    -    className: 'subst',
    -    variants: [{
    -      begin: /\$\{/,
    -      end: /\}/
    -    }],
    -    keywords: 'true false null this is new super'
    -  };
    -
    -  const STRING = {
    -    className: 'string',
    -    variants: [
    -      {
    -        begin: 'r\'\'\'',
    -        end: '\'\'\''
    -      },
    -      {
    -        begin: 'r"""',
    -        end: '"""'
    -      },
    -      {
    -        begin: 'r\'',
    -        end: '\'',
    -        illegal: '\\n'
    -      },
    -      {
    -        begin: 'r"',
    -        end: '"',
    -        illegal: '\\n'
    -      },
    -      {
    -        begin: '\'\'\'',
    -        end: '\'\'\'',
    -        contains: [
    -          hljs.BACKSLASH_ESCAPE,
    -          SUBST,
    -          BRACED_SUBST
    -        ]
    -      },
    -      {
    -        begin: '"""',
    -        end: '"""',
    -        contains: [
    -          hljs.BACKSLASH_ESCAPE,
    -          SUBST,
    -          BRACED_SUBST
    -        ]
    -      },
    -      {
    -        begin: '\'',
    -        end: '\'',
    -        illegal: '\\n',
    -        contains: [
    -          hljs.BACKSLASH_ESCAPE,
    -          SUBST,
    -          BRACED_SUBST
    -        ]
    -      },
    -      {
    -        begin: '"',
    -        end: '"',
    -        illegal: '\\n',
    -        contains: [
    -          hljs.BACKSLASH_ESCAPE,
    -          SUBST,
    -          BRACED_SUBST
    -        ]
    -      }
    -    ]
    -  };
    -  BRACED_SUBST.contains = [
    -    hljs.C_NUMBER_MODE,
    -    STRING
    -  ];
    -
    -  const BUILT_IN_TYPES = [
    -    // dart:core
    -    'Comparable',
    -    'DateTime',
    -    'Duration',
    -    'Function',
    -    'Iterable',
    -    'Iterator',
    -    'List',
    -    'Map',
    -    'Match',
    -    'Object',
    -    'Pattern',
    -    'RegExp',
    -    'Set',
    -    'Stopwatch',
    -    'String',
    -    'StringBuffer',
    -    'StringSink',
    -    'Symbol',
    -    'Type',
    -    'Uri',
    -    'bool',
    -    'double',
    -    'int',
    -    'num',
    -    // dart:html
    -    'Element',
    -    'ElementList'
    -  ];
    -  const NULLABLE_BUILT_IN_TYPES = BUILT_IN_TYPES.map((e) => `${e}?`);
    -
    -  const KEYWORDS = {
    -    keyword: 'abstract as assert async await break case catch class const continue covariant default deferred do ' +
    -      'dynamic else enum export extends extension external factory false final finally for Function get hide if ' +
    -      'implements import in inferface is late library mixin new null on operator part required rethrow return set ' +
    -      'show static super switch sync this throw true try typedef var void while with yield',
    -    built_in:
    -      BUILT_IN_TYPES
    -        .concat(NULLABLE_BUILT_IN_TYPES)
    -        .concat([
    -          // dart:core
    -          'Never',
    -          'Null',
    -          'dynamic',
    -          'print',
    -          // dart:html
    -          'document',
    -          'querySelector',
    -          'querySelectorAll',
    -          'window'
    -        ]),
    -    $pattern: /[A-Za-z][A-Za-z0-9_]*\??/
    -  };
    -
    -  return {
    -    name: 'Dart',
    -    keywords: KEYWORDS,
    -    contains: [
    -      STRING,
    -      hljs.COMMENT(
    -        /\/\*\*(?!\/)/,
    -        /\*\//,
    -        {
    -          subLanguage: 'markdown',
    -          relevance: 0
    -        }
    -      ),
    -      hljs.COMMENT(
    -        /\/{3,} ?/,
    -        /$/, {
    -          contains: [{
    -            subLanguage: 'markdown',
    -            begin: '.',
    -            end: '$',
    -            relevance: 0
    -          }]
    -        }
    -      ),
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      {
    -        className: 'class',
    -        beginKeywords: 'class interface',
    -        end: /\{/,
    -        excludeEnd: true,
    -        contains: [
    -          {
    -            beginKeywords: 'extends implements'
    -          },
    -          hljs.UNDERSCORE_TITLE_MODE
    -        ]
    -      },
    -      hljs.C_NUMBER_MODE,
    -      {
    -        className: 'meta',
    -        begin: '@[A-Za-z]+'
    -      },
    -      {
    -        begin: '=>' // No markup, just a relevance booster
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = dart;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/delphi.js b/claude-code-source/node_modules/highlight.js/lib/languages/delphi.js
    deleted file mode 100644
    index 668b11bc..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/delphi.js
    +++ /dev/null
    @@ -1,126 +0,0 @@
    -/*
    -Language: Delphi
    -Website: https://www.embarcadero.com/products/delphi
    -*/
    -
    -/** @type LanguageFn */
    -function delphi(hljs) {
    -  const KEYWORDS =
    -    'exports register file shl array record property for mod while set ally label uses raise not ' +
    -    'stored class safecall var interface or private static exit index inherited to else stdcall ' +
    -    'override shr asm far resourcestring finalization packed virtual out and protected library do ' +
    -    'xorwrite goto near function end div overload object unit begin string on inline repeat until ' +
    -    'destructor write message program with read initialization except default nil if case cdecl in ' +
    -    'downto threadvar of try pascal const external constructor type public then implementation ' +
    -    'finally published procedure absolute reintroduce operator as is abstract alias assembler ' +
    -    'bitpacked break continue cppdecl cvar enumerator experimental platform deprecated ' +
    -    'unimplemented dynamic export far16 forward generic helper implements interrupt iochecks ' +
    -    'local name nodefault noreturn nostackframe oldfpccall otherwise saveregisters softfloat ' +
    -    'specialize strict unaligned varargs ';
    -  const COMMENT_MODES = [
    -    hljs.C_LINE_COMMENT_MODE,
    -    hljs.COMMENT(/\{/, /\}/, {
    -      relevance: 0
    -    }),
    -    hljs.COMMENT(/\(\*/, /\*\)/, {
    -      relevance: 10
    -    })
    -  ];
    -  const DIRECTIVE = {
    -    className: 'meta',
    -    variants: [
    -      {
    -        begin: /\{\$/,
    -        end: /\}/
    -      },
    -      {
    -        begin: /\(\*\$/,
    -        end: /\*\)/
    -      }
    -    ]
    -  };
    -  const STRING = {
    -    className: 'string',
    -    begin: /'/,
    -    end: /'/,
    -    contains: [{
    -      begin: /''/
    -    }]
    -  };
    -  const NUMBER = {
    -    className: 'number',
    -    relevance: 0,
    -    // Source: https://www.freepascal.org/docs-html/ref/refse6.html
    -    variants: [
    -      {
    -        // Hexadecimal notation, e.g., $7F.
    -        begin: '\\$[0-9A-Fa-f]+'
    -      },
    -      {
    -        // Octal notation, e.g., &42.
    -        begin: '&[0-7]+'
    -      },
    -      {
    -        // Binary notation, e.g., %1010.
    -        begin: '%[01]+'
    -      }
    -    ]
    -  };
    -  const CHAR_STRING = {
    -    className: 'string',
    -    begin: /(#\d+)+/
    -  };
    -  const CLASS = {
    -    begin: hljs.IDENT_RE + '\\s*=\\s*class\\s*\\(',
    -    returnBegin: true,
    -    contains: [hljs.TITLE_MODE]
    -  };
    -  const FUNCTION = {
    -    className: 'function',
    -    beginKeywords: 'function constructor destructor procedure',
    -    end: /[:;]/,
    -    keywords: 'function constructor|10 destructor|10 procedure|10',
    -    contains: [
    -      hljs.TITLE_MODE,
    -      {
    -        className: 'params',
    -        begin: /\(/,
    -        end: /\)/,
    -        keywords: KEYWORDS,
    -        contains: [
    -          STRING,
    -          CHAR_STRING,
    -          DIRECTIVE
    -        ].concat(COMMENT_MODES)
    -      },
    -      DIRECTIVE
    -    ].concat(COMMENT_MODES)
    -  };
    -  return {
    -    name: 'Delphi',
    -    aliases: [
    -      'dpr',
    -      'dfm',
    -      'pas',
    -      'pascal',
    -      'freepascal',
    -      'lazarus',
    -      'lpr',
    -      'lfm'
    -    ],
    -    case_insensitive: true,
    -    keywords: KEYWORDS,
    -    illegal: /"|\$[G-Zg-z]|\/\*|<\/|\|/,
    -    contains: [
    -      STRING,
    -      CHAR_STRING,
    -      hljs.NUMBER_MODE,
    -      NUMBER,
    -      CLASS,
    -      FUNCTION,
    -      DIRECTIVE
    -    ].concat(COMMENT_MODES)
    -  };
    -}
    -
    -module.exports = delphi;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/diff.js b/claude-code-source/node_modules/highlight.js/lib/languages/diff.js
    deleted file mode 100644
    index db2feb8f..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/diff.js
    +++ /dev/null
    @@ -1,85 +0,0 @@
    -/*
    -Language: Diff
    -Description: Unified and context diff
    -Author: Vasily Polovnyov 
    -Website: https://www.gnu.org/software/diffutils/
    -Category: common
    -*/
    -
    -/** @type LanguageFn */
    -function diff(hljs) {
    -  return {
    -    name: 'Diff',
    -    aliases: ['patch'],
    -    contains: [
    -      {
    -        className: 'meta',
    -        relevance: 10,
    -        variants: [
    -          {
    -            begin: /^@@ +-\d+,\d+ +\+\d+,\d+ +@@/
    -          },
    -          {
    -            begin: /^\*\*\* +\d+,\d+ +\*\*\*\*$/
    -          },
    -          {
    -            begin: /^--- +\d+,\d+ +----$/
    -          }
    -        ]
    -      },
    -      {
    -        className: 'comment',
    -        variants: [
    -          {
    -            begin: /Index: /,
    -            end: /$/
    -          },
    -          {
    -            begin: /^index/,
    -            end: /$/
    -          },
    -          {
    -            begin: /={3,}/,
    -            end: /$/
    -          },
    -          {
    -            begin: /^-{3}/,
    -            end: /$/
    -          },
    -          {
    -            begin: /^\*{3} /,
    -            end: /$/
    -          },
    -          {
    -            begin: /^\+{3}/,
    -            end: /$/
    -          },
    -          {
    -            begin: /^\*{15}$/
    -          },
    -          {
    -            begin: /^diff --git/,
    -            end: /$/
    -          }
    -        ]
    -      },
    -      {
    -        className: 'addition',
    -        begin: /^\+/,
    -        end: /$/
    -      },
    -      {
    -        className: 'deletion',
    -        begin: /^-/,
    -        end: /$/
    -      },
    -      {
    -        className: 'addition',
    -        begin: /^!/,
    -        end: /$/
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = diff;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/django.js b/claude-code-source/node_modules/highlight.js/lib/languages/django.js
    deleted file mode 100644
    index 4826c0f7..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/django.js
    +++ /dev/null
    @@ -1,77 +0,0 @@
    -/*
    -Language: Django
    -Description: Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design.
    -Requires: xml.js
    -Author: Ivan Sagalaev 
    -Contributors: Ilya Baryshev 
    -Website: https://www.djangoproject.com
    -Category: template
    -*/
    -
    -/** @type LanguageFn */
    -function django(hljs) {
    -  const FILTER = {
    -    begin: /\|[A-Za-z]+:?/,
    -    keywords: {
    -      name:
    -        'truncatewords removetags linebreaksbr yesno get_digit timesince random striptags ' +
    -        'filesizeformat escape linebreaks length_is ljust rjust cut urlize fix_ampersands ' +
    -        'title floatformat capfirst pprint divisibleby add make_list unordered_list urlencode ' +
    -        'timeuntil urlizetrunc wordcount stringformat linenumbers slice date dictsort ' +
    -        'dictsortreversed default_if_none pluralize lower join center default ' +
    -        'truncatewords_html upper length phone2numeric wordwrap time addslashes slugify first ' +
    -        'escapejs force_escape iriencode last safe safeseq truncatechars localize unlocalize ' +
    -        'localtime utc timezone'
    -    },
    -    contains: [
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.APOS_STRING_MODE
    -    ]
    -  };
    -
    -  return {
    -    name: 'Django',
    -    aliases: ['jinja'],
    -    case_insensitive: true,
    -    subLanguage: 'xml',
    -    contains: [
    -      hljs.COMMENT(/\{%\s*comment\s*%\}/, /\{%\s*endcomment\s*%\}/),
    -      hljs.COMMENT(/\{#/, /#\}/),
    -      {
    -        className: 'template-tag',
    -        begin: /\{%/,
    -        end: /%\}/,
    -        contains: [{
    -          className: 'name',
    -          begin: /\w+/,
    -          keywords: {
    -            name:
    -                'comment endcomment load templatetag ifchanged endifchanged if endif firstof for ' +
    -                'endfor ifnotequal endifnotequal widthratio extends include spaceless ' +
    -                'endspaceless regroup ifequal endifequal ssi now with cycle url filter ' +
    -                'endfilter debug block endblock else autoescape endautoescape csrf_token empty elif ' +
    -                'endwith static trans blocktrans endblocktrans get_static_prefix get_media_prefix ' +
    -                'plural get_current_language language get_available_languages ' +
    -                'get_current_language_bidi get_language_info get_language_info_list localize ' +
    -                'endlocalize localtime endlocaltime timezone endtimezone get_current_timezone ' +
    -                'verbatim'
    -          },
    -          starts: {
    -            endsWithParent: true,
    -            keywords: 'in by as',
    -            contains: [FILTER],
    -            relevance: 0
    -          }
    -        }]
    -      },
    -      {
    -        className: 'template-variable',
    -        begin: /\{\{/,
    -        end: /\}\}/,
    -        contains: [FILTER]
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = django;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/dns.js b/claude-code-source/node_modules/highlight.js/lib/languages/dns.js
    deleted file mode 100644
    index 0c3f4b6d..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/dns.js
    +++ /dev/null
    @@ -1,46 +0,0 @@
    -/*
    -Language: DNS Zone
    -Author: Tim Schumacher 
    -Category: config
    -Website: https://en.wikipedia.org/wiki/Zone_file
    -*/
    -
    -/** @type LanguageFn */
    -function dns(hljs) {
    -  return {
    -    name: 'DNS Zone',
    -    aliases: [
    -      'bind',
    -      'zone'
    -    ],
    -    keywords: {
    -      keyword:
    -        'IN A AAAA AFSDB APL CAA CDNSKEY CDS CERT CNAME DHCID DLV DNAME DNSKEY DS HIP IPSECKEY KEY KX ' +
    -        'LOC MX NAPTR NS NSEC NSEC3 NSEC3PARAM PTR RRSIG RP SIG SOA SRV SSHFP TA TKEY TLSA TSIG TXT'
    -    },
    -    contains: [
    -      hljs.COMMENT(';', '$', {
    -        relevance: 0
    -      }),
    -      {
    -        className: 'meta',
    -        begin: /^\$(TTL|GENERATE|INCLUDE|ORIGIN)\b/
    -      },
    -      // IPv6
    -      {
    -        className: 'number',
    -        begin: '((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)(\\.(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)){3}))|:)))\\b'
    -      },
    -      // IPv4
    -      {
    -        className: 'number',
    -        begin: '((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\b'
    -      },
    -      hljs.inherit(hljs.NUMBER_MODE, {
    -        begin: /\b\d+[dhwm]?/
    -      })
    -    ]
    -  };
    -}
    -
    -module.exports = dns;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/dockerfile.js b/claude-code-source/node_modules/highlight.js/lib/languages/dockerfile.js
    deleted file mode 100644
    index 73405bff..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/dockerfile.js
    +++ /dev/null
    @@ -1,34 +0,0 @@
    -/*
    -Language: Dockerfile
    -Requires: bash.js
    -Author: Alexis Hénaut 
    -Description: language definition for Dockerfile files
    -Website: https://docs.docker.com/engine/reference/builder/
    -Category: config
    -*/
    -
    -/** @type LanguageFn */
    -function dockerfile(hljs) {
    -  return {
    -    name: 'Dockerfile',
    -    aliases: ['docker'],
    -    case_insensitive: true,
    -    keywords: 'from maintainer expose env arg user onbuild stopsignal',
    -    contains: [
    -      hljs.HASH_COMMENT_MODE,
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.NUMBER_MODE,
    -      {
    -        beginKeywords: 'run cmd entrypoint volume add copy workdir label healthcheck shell',
    -        starts: {
    -          end: /[^\\]$/,
    -          subLanguage: 'bash'
    -        }
    -      }
    -    ],
    -    illegal: '
    -Contributors: Anton Kochkov 
    -Website: https://en.wikipedia.org/wiki/Batch_file
    -*/
    -
    -/** @type LanguageFn */
    -function dos(hljs) {
    -  const COMMENT = hljs.COMMENT(
    -    /^\s*@?rem\b/, /$/,
    -    {
    -      relevance: 10
    -    }
    -  );
    -  const LABEL = {
    -    className: 'symbol',
    -    begin: '^\\s*[A-Za-z._?][A-Za-z0-9_$#@~.?]*(:|\\s+label)',
    -    relevance: 0
    -  };
    -  return {
    -    name: 'Batch file (DOS)',
    -    aliases: [
    -      'bat',
    -      'cmd'
    -    ],
    -    case_insensitive: true,
    -    illegal: /\/\*/,
    -    keywords: {
    -      keyword:
    -        'if else goto for in do call exit not exist errorlevel defined ' +
    -        'equ neq lss leq gtr geq',
    -      built_in:
    -        'prn nul lpt3 lpt2 lpt1 con com4 com3 com2 com1 aux ' +
    -        'shift cd dir echo setlocal endlocal set pause copy ' +
    -        'append assoc at attrib break cacls cd chcp chdir chkdsk chkntfs cls cmd color ' +
    -        'comp compact convert date dir diskcomp diskcopy doskey erase fs ' +
    -        'find findstr format ftype graftabl help keyb label md mkdir mode more move path ' +
    -        'pause print popd pushd promt rd recover rem rename replace restore rmdir shift ' +
    -        'sort start subst time title tree type ver verify vol ' +
    -        // winutils
    -        'ping net ipconfig taskkill xcopy ren del'
    -    },
    -    contains: [
    -      {
    -        className: 'variable',
    -        begin: /%%[^ ]|%[^ ]+?%|![^ ]+?!/
    -      },
    -      {
    -        className: 'function',
    -        begin: LABEL.begin,
    -        end: 'goto:eof',
    -        contains: [
    -          hljs.inherit(hljs.TITLE_MODE, {
    -            begin: '([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*'
    -          }),
    -          COMMENT
    -        ]
    -      },
    -      {
    -        className: 'number',
    -        begin: '\\b\\d+',
    -        relevance: 0
    -      },
    -      COMMENT
    -    ]
    -  };
    -}
    -
    -module.exports = dos;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/dsconfig.js b/claude-code-source/node_modules/highlight.js/lib/languages/dsconfig.js
    deleted file mode 100644
    index b51d2e7d..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/dsconfig.js
    +++ /dev/null
    @@ -1,66 +0,0 @@
    -/*
    - Language: dsconfig
    - Description: dsconfig batch configuration language for LDAP directory servers
    - Contributors: Jacob Childress 
    - Category: enterprise, config
    - */
    -
    - /** @type LanguageFn */
    -function dsconfig(hljs) {
    -  const QUOTED_PROPERTY = {
    -    className: 'string',
    -    begin: /"/,
    -    end: /"/
    -  };
    -  const APOS_PROPERTY = {
    -    className: 'string',
    -    begin: /'/,
    -    end: /'/
    -  };
    -  const UNQUOTED_PROPERTY = {
    -    className: 'string',
    -    begin: /[\w\-?]+:\w+/,
    -    end: /\W/,
    -    relevance: 0
    -  };
    -  const VALUELESS_PROPERTY = {
    -    className: 'string',
    -    begin: /\w+(\-\w+)*/,
    -    end: /(?=\W)/,
    -    relevance: 0
    -  };
    -
    -  return {
    -    keywords: 'dsconfig',
    -    contains: [
    -      {
    -        className: 'keyword',
    -        begin: '^dsconfig',
    -        end: /\s/,
    -        excludeEnd: true,
    -        relevance: 10
    -      },
    -      {
    -        className: 'built_in',
    -        begin: /(list|create|get|set|delete)-(\w+)/,
    -        end: /\s/,
    -        excludeEnd: true,
    -        illegal: '!@#$%^&*()',
    -        relevance: 10
    -      },
    -      {
    -        className: 'built_in',
    -        begin: /--(\w+)/,
    -        end: /\s/,
    -        excludeEnd: true
    -      },
    -      QUOTED_PROPERTY,
    -      APOS_PROPERTY,
    -      UNQUOTED_PROPERTY,
    -      VALUELESS_PROPERTY,
    -      hljs.HASH_COMMENT_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = dsconfig;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/dts.js b/claude-code-source/node_modules/highlight.js/lib/languages/dts.js
    deleted file mode 100644
    index fc1a46e2..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/dts.js
    +++ /dev/null
    @@ -1,153 +0,0 @@
    -/*
    -Language: Device Tree
    -Description: *.dts files used in the Linux kernel
    -Author: Martin Braun , Moritz Fischer 
    -Website: https://elinux.org/Device_Tree_Reference
    -Category: config
    -*/
    -
    -/** @type LanguageFn */
    -function dts(hljs) {
    -  const STRINGS = {
    -    className: 'string',
    -    variants: [
    -      hljs.inherit(hljs.QUOTE_STRING_MODE, {
    -        begin: '((u8?|U)|L)?"'
    -      }),
    -      {
    -        begin: '(u8?|U)?R"',
    -        end: '"',
    -        contains: [hljs.BACKSLASH_ESCAPE]
    -      },
    -      {
    -        begin: '\'\\\\?.',
    -        end: '\'',
    -        illegal: '.'
    -      }
    -    ]
    -  };
    -
    -  const NUMBERS = {
    -    className: 'number',
    -    variants: [
    -      {
    -        begin: '\\b(\\d+(\\.\\d*)?|\\.\\d+)(u|U|l|L|ul|UL|f|F)'
    -      },
    -      {
    -        begin: hljs.C_NUMBER_RE
    -      }
    -    ],
    -    relevance: 0
    -  };
    -
    -  const PREPROCESSOR = {
    -    className: 'meta',
    -    begin: '#',
    -    end: '$',
    -    keywords: {
    -      'meta-keyword': 'if else elif endif define undef ifdef ifndef'
    -    },
    -    contains: [
    -      {
    -        begin: /\\\n/,
    -        relevance: 0
    -      },
    -      {
    -        beginKeywords: 'include',
    -        end: '$',
    -        keywords: {
    -          'meta-keyword': 'include'
    -        },
    -        contains: [
    -          hljs.inherit(STRINGS, {
    -            className: 'meta-string'
    -          }),
    -          {
    -            className: 'meta-string',
    -            begin: '<',
    -            end: '>',
    -            illegal: '\\n'
    -          }
    -        ]
    -      },
    -      STRINGS,
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE
    -    ]
    -  };
    -
    -  const DTS_REFERENCE = {
    -    className: 'variable',
    -    begin: /&[a-z\d_]*\b/
    -  };
    -
    -  const DTS_KEYWORD = {
    -    className: 'meta-keyword',
    -    begin: '/[a-z][a-z\\d-]*/'
    -  };
    -
    -  const DTS_LABEL = {
    -    className: 'symbol',
    -    begin: '^\\s*[a-zA-Z_][a-zA-Z\\d_]*:'
    -  };
    -
    -  const DTS_CELL_PROPERTY = {
    -    className: 'params',
    -    begin: '<',
    -    end: '>',
    -    contains: [
    -      NUMBERS,
    -      DTS_REFERENCE
    -    ]
    -  };
    -
    -  const DTS_NODE = {
    -    className: 'class',
    -    begin: /[a-zA-Z_][a-zA-Z\d_@]*\s\{/,
    -    end: /[{;=]/,
    -    returnBegin: true,
    -    excludeEnd: true
    -  };
    -
    -  const DTS_ROOT_NODE = {
    -    className: 'class',
    -    begin: '/\\s*\\{',
    -    end: /\};/,
    -    relevance: 10,
    -    contains: [
    -      DTS_REFERENCE,
    -      DTS_KEYWORD,
    -      DTS_LABEL,
    -      DTS_NODE,
    -      DTS_CELL_PROPERTY,
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      NUMBERS,
    -      STRINGS
    -    ]
    -  };
    -
    -  return {
    -    name: 'Device Tree',
    -    keywords: "",
    -    contains: [
    -      DTS_ROOT_NODE,
    -      DTS_REFERENCE,
    -      DTS_KEYWORD,
    -      DTS_LABEL,
    -      DTS_NODE,
    -      DTS_CELL_PROPERTY,
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      NUMBERS,
    -      STRINGS,
    -      PREPROCESSOR,
    -      {
    -        begin: hljs.IDENT_RE + '::',
    -        keywords: ""
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = dts;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/dust.js b/claude-code-source/node_modules/highlight.js/lib/languages/dust.js
    deleted file mode 100644
    index aa9d6da5..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/dust.js
    +++ /dev/null
    @@ -1,45 +0,0 @@
    -/*
    -Language: Dust
    -Requires: xml.js
    -Author: Michael Allen 
    -Description: Matcher for dust.js templates.
    -Website: https://www.dustjs.com
    -Category: template
    -*/
    -
    -/** @type LanguageFn */
    -function dust(hljs) {
    -  const EXPRESSION_KEYWORDS = 'if eq ne lt lte gt gte select default math sep';
    -  return {
    -    name: 'Dust',
    -    aliases: ['dst'],
    -    case_insensitive: true,
    -    subLanguage: 'xml',
    -    contains: [
    -      {
    -        className: 'template-tag',
    -        begin: /\{[#\/]/,
    -        end: /\}/,
    -        illegal: /;/,
    -        contains: [{
    -          className: 'name',
    -          begin: /[a-zA-Z\.-]+/,
    -          starts: {
    -            endsWithParent: true,
    -            relevance: 0,
    -            contains: [hljs.QUOTE_STRING_MODE]
    -          }
    -        }]
    -      },
    -      {
    -        className: 'template-variable',
    -        begin: /\{/,
    -        end: /\}/,
    -        illegal: /;/,
    -        keywords: EXPRESSION_KEYWORDS
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = dust;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/ebnf.js b/claude-code-source/node_modules/highlight.js/lib/languages/ebnf.js
    deleted file mode 100644
    index 192ded7b..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/ebnf.js
    +++ /dev/null
    @@ -1,53 +0,0 @@
    -/*
    -Language: Extended Backus-Naur Form
    -Author: Alex McKibben 
    -Website: https://en.wikipedia.org/wiki/Extended_Backus–Naur_form
    -*/
    -
    -/** @type LanguageFn */
    -function ebnf(hljs) {
    -  const commentMode = hljs.COMMENT(/\(\*/, /\*\)/);
    -
    -  const nonTerminalMode = {
    -    className: "attribute",
    -    begin: /^[ ]*[a-zA-Z]+([\s_-]+[a-zA-Z]+)*/
    -  };
    -
    -  const specialSequenceMode = {
    -    className: "meta",
    -    begin: /\?.*\?/
    -  };
    -
    -  const ruleBodyMode = {
    -    begin: /=/,
    -    end: /[.;]/,
    -    contains: [
    -      commentMode,
    -      specialSequenceMode,
    -      {
    -        // terminals
    -        className: 'string',
    -        variants: [
    -          hljs.APOS_STRING_MODE,
    -          hljs.QUOTE_STRING_MODE,
    -          {
    -            begin: '`',
    -            end: '`'
    -          }
    -        ]
    -      }
    -    ]
    -  };
    -
    -  return {
    -    name: 'Extended Backus-Naur Form',
    -    illegal: /\S/,
    -    contains: [
    -      commentMode,
    -      nonTerminalMode,
    -      ruleBodyMode
    -    ]
    -  };
    -}
    -
    -module.exports = ebnf;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/elixir.js b/claude-code-source/node_modules/highlight.js/lib/languages/elixir.js
    deleted file mode 100644
    index 758e107b..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/elixir.js
    +++ /dev/null
    @@ -1,259 +0,0 @@
    -/*
    -Language: Elixir
    -Author: Josh Adams 
    -Description: language definition for Elixir source code files (.ex and .exs).  Based on ruby language support.
    -Category: functional
    -Website: https://elixir-lang.org
    -*/
    -
    -/** @type LanguageFn */
    -function elixir(hljs) {
    -  const ELIXIR_IDENT_RE = '[a-zA-Z_][a-zA-Z0-9_.]*(!|\\?)?';
    -  const ELIXIR_METHOD_RE = '[a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?';
    -  const ELIXIR_KEYWORDS = {
    -    $pattern: ELIXIR_IDENT_RE,
    -    keyword: 'and false then defined module in return redo retry end for true self when ' +
    -    'next until do begin unless nil break not case cond alias while ensure or ' +
    -    'include use alias fn quote require import with|0'
    -  };
    -  const SUBST = {
    -    className: 'subst',
    -    begin: /#\{/,
    -    end: /\}/,
    -    keywords: ELIXIR_KEYWORDS
    -  };
    -  const NUMBER = {
    -    className: 'number',
    -    begin: '(\\b0o[0-7_]+)|(\\b0b[01_]+)|(\\b0x[0-9a-fA-F_]+)|(-?\\b[1-9][0-9_]*(\\.[0-9_]+([eE][-+]?[0-9]+)?)?)',
    -    relevance: 0
    -  };
    -  const SIGIL_DELIMITERS = '[/|([{<"\']';
    -  const LOWERCASE_SIGIL = {
    -    className: 'string',
    -    begin: '~[a-z]' + '(?=' + SIGIL_DELIMITERS + ')',
    -    contains: [
    -      {
    -        endsParent: true,
    -        contains: [
    -          {
    -            contains: [
    -              hljs.BACKSLASH_ESCAPE,
    -              SUBST
    -            ],
    -            variants: [
    -              {
    -                begin: /"/,
    -                end: /"/
    -              },
    -              {
    -                begin: /'/,
    -                end: /'/
    -              },
    -              {
    -                begin: /\//,
    -                end: /\//
    -              },
    -              {
    -                begin: /\|/,
    -                end: /\|/
    -              },
    -              {
    -                begin: /\(/,
    -                end: /\)/
    -              },
    -              {
    -                begin: /\[/,
    -                end: /\]/
    -              },
    -              {
    -                begin: /\{/,
    -                end: /\}/
    -              },
    -              {
    -                begin: //
    -              }
    -            ]
    -          }
    -        ]
    -      }
    -    ]
    -  };
    -
    -  const UPCASE_SIGIL = {
    -    className: 'string',
    -    begin: '~[A-Z]' + '(?=' + SIGIL_DELIMITERS + ')',
    -    contains: [
    -      {
    -        begin: /"/,
    -        end: /"/
    -      },
    -      {
    -        begin: /'/,
    -        end: /'/
    -      },
    -      {
    -        begin: /\//,
    -        end: /\//
    -      },
    -      {
    -        begin: /\|/,
    -        end: /\|/
    -      },
    -      {
    -        begin: /\(/,
    -        end: /\)/
    -      },
    -      {
    -        begin: /\[/,
    -        end: /\]/
    -      },
    -      {
    -        begin: /\{/,
    -        end: /\}/
    -      },
    -      {
    -        begin: //
    -      }
    -    ]
    -  };
    -
    -  const STRING = {
    -    className: 'string',
    -    contains: [
    -      hljs.BACKSLASH_ESCAPE,
    -      SUBST
    -    ],
    -    variants: [
    -      {
    -        begin: /"""/,
    -        end: /"""/
    -      },
    -      {
    -        begin: /'''/,
    -        end: /'''/
    -      },
    -      {
    -        begin: /~S"""/,
    -        end: /"""/,
    -        contains: [] // override default
    -      },
    -      {
    -        begin: /~S"/,
    -        end: /"/,
    -        contains: [] // override default
    -      },
    -      {
    -        begin: /~S'''/,
    -        end: /'''/,
    -        contains: [] // override default
    -      },
    -      {
    -        begin: /~S'/,
    -        end: /'/,
    -        contains: [] // override default
    -      },
    -      {
    -        begin: /'/,
    -        end: /'/
    -      },
    -      {
    -        begin: /"/,
    -        end: /"/
    -      }
    -    ]
    -  };
    -  const FUNCTION = {
    -    className: 'function',
    -    beginKeywords: 'def defp defmacro',
    -    end: /\B\b/, // the mode is ended by the title
    -    contains: [
    -      hljs.inherit(hljs.TITLE_MODE, {
    -        begin: ELIXIR_IDENT_RE,
    -        endsParent: true
    -      })
    -    ]
    -  };
    -  const CLASS = hljs.inherit(FUNCTION, {
    -    className: 'class',
    -    beginKeywords: 'defimpl defmodule defprotocol defrecord',
    -    end: /\bdo\b|$|;/
    -  });
    -  const ELIXIR_DEFAULT_CONTAINS = [
    -    STRING,
    -    UPCASE_SIGIL,
    -    LOWERCASE_SIGIL,
    -    hljs.HASH_COMMENT_MODE,
    -    CLASS,
    -    FUNCTION,
    -    {
    -      begin: '::'
    -    },
    -    {
    -      className: 'symbol',
    -      begin: ':(?![\\s:])',
    -      contains: [
    -        STRING,
    -        {
    -          begin: ELIXIR_METHOD_RE
    -        }
    -      ],
    -      relevance: 0
    -    },
    -    {
    -      className: 'symbol',
    -      begin: ELIXIR_IDENT_RE + ':(?!:)',
    -      relevance: 0
    -    },
    -    NUMBER,
    -    {
    -      className: 'variable',
    -      begin: '(\\$\\W)|((\\$|@@?)(\\w+))'
    -    },
    -    {
    -      begin: '->'
    -    },
    -    { // regexp container
    -      begin: '(' + hljs.RE_STARTERS_RE + ')\\s*',
    -      contains: [
    -        hljs.HASH_COMMENT_MODE,
    -        {
    -          // to prevent false regex triggers for the division function:
    -          // /:
    -          begin: /\/: (?=\d+\s*[,\]])/,
    -          relevance: 0,
    -          contains: [NUMBER]
    -        },
    -        {
    -          className: 'regexp',
    -          illegal: '\\n',
    -          contains: [
    -            hljs.BACKSLASH_ESCAPE,
    -            SUBST
    -          ],
    -          variants: [
    -            {
    -              begin: '/',
    -              end: '/[a-z]*'
    -            },
    -            {
    -              begin: '%r\\[',
    -              end: '\\][a-z]*'
    -            }
    -          ]
    -        }
    -      ],
    -      relevance: 0
    -    }
    -  ];
    -  SUBST.contains = ELIXIR_DEFAULT_CONTAINS;
    -
    -  return {
    -    name: 'Elixir',
    -    keywords: ELIXIR_KEYWORDS,
    -    contains: ELIXIR_DEFAULT_CONTAINS
    -  };
    -}
    -
    -module.exports = elixir;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/elm.js b/claude-code-source/node_modules/highlight.js/lib/languages/elm.js
    deleted file mode 100644
    index d986f7c4..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/elm.js
    +++ /dev/null
    @@ -1,129 +0,0 @@
    -/*
    -Language: Elm
    -Author: Janis Voigtlaender 
    -Website: https://elm-lang.org
    -Category: functional
    -*/
    -
    -/** @type LanguageFn */
    -function elm(hljs) {
    -  const COMMENT = {
    -    variants: [
    -      hljs.COMMENT('--', '$'),
    -      hljs.COMMENT(
    -        /\{-/,
    -        /-\}/,
    -        {
    -          contains: ['self']
    -        }
    -      )
    -    ]
    -  };
    -
    -  const CONSTRUCTOR = {
    -    className: 'type',
    -    begin: '\\b[A-Z][\\w\']*', // TODO: other constructors (built-in, infix).
    -    relevance: 0
    -  };
    -
    -  const LIST = {
    -    begin: '\\(',
    -    end: '\\)',
    -    illegal: '"',
    -    contains: [
    -      {
    -        className: 'type',
    -        begin: '\\b[A-Z][\\w]*(\\((\\.\\.|,|\\w+)\\))?'
    -      },
    -      COMMENT
    -    ]
    -  };
    -
    -  const RECORD = {
    -    begin: /\{/,
    -    end: /\}/,
    -    contains: LIST.contains
    -  };
    -
    -  const CHARACTER = {
    -    className: 'string',
    -    begin: '\'\\\\?.',
    -    end: '\'',
    -    illegal: '.'
    -  };
    -
    -  return {
    -    name: 'Elm',
    -    keywords:
    -      'let in if then else case of where module import exposing ' +
    -      'type alias as infix infixl infixr port effect command subscription',
    -    contains: [
    -
    -      // Top-level constructions.
    -
    -      {
    -        beginKeywords: 'port effect module',
    -        end: 'exposing',
    -        keywords: 'port effect module where command subscription exposing',
    -        contains: [
    -          LIST,
    -          COMMENT
    -        ],
    -        illegal: '\\W\\.|;'
    -      },
    -      {
    -        begin: 'import',
    -        end: '$',
    -        keywords: 'import as exposing',
    -        contains: [
    -          LIST,
    -          COMMENT
    -        ],
    -        illegal: '\\W\\.|;'
    -      },
    -      {
    -        begin: 'type',
    -        end: '$',
    -        keywords: 'type alias',
    -        contains: [
    -          CONSTRUCTOR,
    -          LIST,
    -          RECORD,
    -          COMMENT
    -        ]
    -      },
    -      {
    -        beginKeywords: 'infix infixl infixr',
    -        end: '$',
    -        contains: [
    -          hljs.C_NUMBER_MODE,
    -          COMMENT
    -        ]
    -      },
    -      {
    -        begin: 'port',
    -        end: '$',
    -        keywords: 'port',
    -        contains: [COMMENT]
    -      },
    -
    -      // Literals and names.
    -
    -      CHARACTER,
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.C_NUMBER_MODE,
    -      CONSTRUCTOR,
    -      hljs.inherit(hljs.TITLE_MODE, {
    -        begin: '^[_a-z][\\w\']*'
    -      }),
    -      COMMENT,
    -
    -      {
    -        begin: '->|<-'
    -      } // No markup, relevance booster
    -    ],
    -    illegal: /;/
    -  };
    -}
    -
    -module.exports = elm;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/erb.js b/claude-code-source/node_modules/highlight.js/lib/languages/erb.js
    deleted file mode 100644
    index 16649232..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/erb.js
    +++ /dev/null
    @@ -1,29 +0,0 @@
    -/*
    -Language: ERB (Embedded Ruby)
    -Requires: xml.js, ruby.js
    -Author: Lucas Mazza 
    -Contributors: Kassio Borges 
    -Description: "Bridge" language defining fragments of Ruby in HTML within <% .. %>
    -Website: https://ruby-doc.org/stdlib-2.6.5/libdoc/erb/rdoc/ERB.html
    -Category: template
    -*/
    -
    -/** @type LanguageFn */
    -function erb(hljs) {
    -  return {
    -    name: 'ERB',
    -    subLanguage: 'xml',
    -    contains: [
    -      hljs.COMMENT('<%#', '%>'),
    -      {
    -        begin: '<%[%=-]?',
    -        end: '[%-]?%>',
    -        subLanguage: 'ruby',
    -        excludeBegin: true,
    -        excludeEnd: true
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = erb;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/erlang-repl.js b/claude-code-source/node_modules/highlight.js/lib/languages/erlang-repl.js
    deleted file mode 100644
    index 17e153b6..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/erlang-repl.js
    +++ /dev/null
    @@ -1,86 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: Erlang REPL
    -Author: Sergey Ignatov 
    -Website: https://www.erlang.org
    -Category: functional
    -*/
    -
    -/** @type LanguageFn */
    -function erlangRepl(hljs) {
    -  return {
    -    name: 'Erlang REPL',
    -    keywords: {
    -      built_in:
    -        'spawn spawn_link self',
    -      keyword:
    -        'after and andalso|10 band begin bnot bor bsl bsr bxor case catch cond div end fun if ' +
    -        'let not of or orelse|10 query receive rem try when xor'
    -    },
    -    contains: [
    -      {
    -        className: 'meta',
    -        begin: '^[0-9]+> ',
    -        relevance: 10
    -      },
    -      hljs.COMMENT('%', '$'),
    -      {
    -        className: 'number',
    -        begin: '\\b(\\d+(_\\d+)*#[a-fA-F0-9]+(_[a-fA-F0-9]+)*|\\d+(_\\d+)*(\\.\\d+(_\\d+)*)?([eE][-+]?\\d+)?)',
    -        relevance: 0
    -      },
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      {
    -        begin: concat(
    -          /\?(::)?/,
    -          /([A-Z]\w*)/, // at least one identifier
    -          /((::)[A-Z]\w*)*/ // perhaps more
    -        )
    -      },
    -      {
    -        begin: '->'
    -      },
    -      {
    -        begin: 'ok'
    -      },
    -      {
    -        begin: '!'
    -      },
    -      {
    -        begin: '(\\b[a-z\'][a-zA-Z0-9_\']*:[a-z\'][a-zA-Z0-9_\']*)|(\\b[a-z\'][a-zA-Z0-9_\']*)',
    -        relevance: 0
    -      },
    -      {
    -        begin: '[A-Z][a-zA-Z0-9_\']*',
    -        relevance: 0
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = erlangRepl;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/erlang.js b/claude-code-source/node_modules/highlight.js/lib/languages/erlang.js
    deleted file mode 100644
    index 52feb68c..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/erlang.js
    +++ /dev/null
    @@ -1,199 +0,0 @@
    -/*
    -Language: Erlang
    -Description: Erlang is a general-purpose functional language, with strict evaluation, single assignment, and dynamic typing.
    -Author: Nikolay Zakharov , Dmitry Kovega 
    -Website: https://www.erlang.org
    -Category: functional
    -*/
    -
    -/** @type LanguageFn */
    -function erlang(hljs) {
    -  const BASIC_ATOM_RE = '[a-z\'][a-zA-Z0-9_\']*';
    -  const FUNCTION_NAME_RE = '(' + BASIC_ATOM_RE + ':' + BASIC_ATOM_RE + '|' + BASIC_ATOM_RE + ')';
    -  const ERLANG_RESERVED = {
    -    keyword:
    -      'after and andalso|10 band begin bnot bor bsl bzr bxor case catch cond div end fun if ' +
    -      'let not of orelse|10 query receive rem try when xor',
    -    literal:
    -      'false true'
    -  };
    -
    -  const COMMENT = hljs.COMMENT('%', '$');
    -  const NUMBER = {
    -    className: 'number',
    -    begin: '\\b(\\d+(_\\d+)*#[a-fA-F0-9]+(_[a-fA-F0-9]+)*|\\d+(_\\d+)*(\\.\\d+(_\\d+)*)?([eE][-+]?\\d+)?)',
    -    relevance: 0
    -  };
    -  const NAMED_FUN = {
    -    begin: 'fun\\s+' + BASIC_ATOM_RE + '/\\d+'
    -  };
    -  const FUNCTION_CALL = {
    -    begin: FUNCTION_NAME_RE + '\\(',
    -    end: '\\)',
    -    returnBegin: true,
    -    relevance: 0,
    -    contains: [
    -      {
    -        begin: FUNCTION_NAME_RE,
    -        relevance: 0
    -      },
    -      {
    -        begin: '\\(',
    -        end: '\\)',
    -        endsWithParent: true,
    -        returnEnd: true,
    -        relevance: 0
    -        // "contains" defined later
    -      }
    -    ]
    -  };
    -  const TUPLE = {
    -    begin: /\{/,
    -    end: /\}/,
    -    relevance: 0
    -    // "contains" defined later
    -  };
    -  const VAR1 = {
    -    begin: '\\b_([A-Z][A-Za-z0-9_]*)?',
    -    relevance: 0
    -  };
    -  const VAR2 = {
    -    begin: '[A-Z][a-zA-Z0-9_]*',
    -    relevance: 0
    -  };
    -  const RECORD_ACCESS = {
    -    begin: '#' + hljs.UNDERSCORE_IDENT_RE,
    -    relevance: 0,
    -    returnBegin: true,
    -    contains: [
    -      {
    -        begin: '#' + hljs.UNDERSCORE_IDENT_RE,
    -        relevance: 0
    -      },
    -      {
    -        begin: /\{/,
    -        end: /\}/,
    -        relevance: 0
    -        // "contains" defined later
    -      }
    -    ]
    -  };
    -
    -  const BLOCK_STATEMENTS = {
    -    beginKeywords: 'fun receive if try case',
    -    end: 'end',
    -    keywords: ERLANG_RESERVED
    -  };
    -  BLOCK_STATEMENTS.contains = [
    -    COMMENT,
    -    NAMED_FUN,
    -    hljs.inherit(hljs.APOS_STRING_MODE, {
    -      className: ''
    -    }),
    -    BLOCK_STATEMENTS,
    -    FUNCTION_CALL,
    -    hljs.QUOTE_STRING_MODE,
    -    NUMBER,
    -    TUPLE,
    -    VAR1,
    -    VAR2,
    -    RECORD_ACCESS
    -  ];
    -
    -  const BASIC_MODES = [
    -    COMMENT,
    -    NAMED_FUN,
    -    BLOCK_STATEMENTS,
    -    FUNCTION_CALL,
    -    hljs.QUOTE_STRING_MODE,
    -    NUMBER,
    -    TUPLE,
    -    VAR1,
    -    VAR2,
    -    RECORD_ACCESS
    -  ];
    -  FUNCTION_CALL.contains[1].contains = BASIC_MODES;
    -  TUPLE.contains = BASIC_MODES;
    -  RECORD_ACCESS.contains[1].contains = BASIC_MODES;
    -
    -  const DIRECTIVES = [
    -    "-module",
    -    "-record",
    -    "-undef",
    -    "-export",
    -    "-ifdef",
    -    "-ifndef",
    -    "-author",
    -    "-copyright",
    -    "-doc",
    -    "-vsn",
    -    "-import",
    -    "-include",
    -    "-include_lib",
    -    "-compile",
    -    "-define",
    -    "-else",
    -    "-endif",
    -    "-file",
    -    "-behaviour",
    -    "-behavior",
    -    "-spec"
    -  ];
    -
    -  const PARAMS = {
    -    className: 'params',
    -    begin: '\\(',
    -    end: '\\)',
    -    contains: BASIC_MODES
    -  };
    -  return {
    -    name: 'Erlang',
    -    aliases: ['erl'],
    -    keywords: ERLANG_RESERVED,
    -    illegal: '(',
    -        returnBegin: true,
    -        illegal: '\\(|#|//|/\\*|\\\\|:|;',
    -        contains: [
    -          PARAMS,
    -          hljs.inherit(hljs.TITLE_MODE, {
    -            begin: BASIC_ATOM_RE
    -          })
    -        ],
    -        starts: {
    -          end: ';|\\.',
    -          keywords: ERLANG_RESERVED,
    -          contains: BASIC_MODES
    -        }
    -      },
    -      COMMENT,
    -      {
    -        begin: '^-',
    -        end: '\\.',
    -        relevance: 0,
    -        excludeEnd: true,
    -        returnBegin: true,
    -        keywords: {
    -          $pattern: '-' + hljs.IDENT_RE,
    -          keyword: DIRECTIVES.map(x => `${x}|1.5`).join(" ")
    -        },
    -        contains: [PARAMS]
    -      },
    -      NUMBER,
    -      hljs.QUOTE_STRING_MODE,
    -      RECORD_ACCESS,
    -      VAR1,
    -      VAR2,
    -      TUPLE,
    -      {
    -        begin: /\.$/
    -      } // relevance booster
    -    ]
    -  };
    -}
    -
    -module.exports = erlang;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/excel.js b/claude-code-source/node_modules/highlight.js/lib/languages/excel.js
    deleted file mode 100644
    index 4f20fbcf..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/excel.js
    +++ /dev/null
    @@ -1,64 +0,0 @@
    -/*
    -Language: Excel formulae
    -Author: Victor Zhou 
    -Description: Excel formulae
    -Website: https://products.office.com/en-us/excel/
    -*/
    -
    -/** @type LanguageFn */
    -function excel(hljs) {
    -  return {
    -    name: 'Excel formulae',
    -    aliases: [
    -      'xlsx',
    -      'xls'
    -    ],
    -    case_insensitive: true,
    -    // built-in functions imported from https://web.archive.org/web/20160513042710/https://support.office.com/en-us/article/Excel-functions-alphabetical-b3944572-255d-4efb-bb96-c6d90033e188
    -    keywords: {
    -      $pattern: /[a-zA-Z][\w\.]*/,
    -      built_in: 'ABS ACCRINT ACCRINTM ACOS ACOSH ACOT ACOTH AGGREGATE ADDRESS AMORDEGRC AMORLINC AND ARABIC AREAS ASC ASIN ASINH ATAN ATAN2 ATANH AVEDEV AVERAGE AVERAGEA AVERAGEIF AVERAGEIFS BAHTTEXT BASE BESSELI BESSELJ BESSELK BESSELY BETADIST BETA.DIST BETAINV BETA.INV BIN2DEC BIN2HEX BIN2OCT BINOMDIST BINOM.DIST BINOM.DIST.RANGE BINOM.INV BITAND BITLSHIFT BITOR BITRSHIFT BITXOR CALL CEILING CEILING.MATH CEILING.PRECISE CELL CHAR CHIDIST CHIINV CHITEST CHISQ.DIST CHISQ.DIST.RT CHISQ.INV CHISQ.INV.RT CHISQ.TEST CHOOSE CLEAN CODE COLUMN COLUMNS COMBIN COMBINA COMPLEX CONCAT CONCATENATE CONFIDENCE CONFIDENCE.NORM CONFIDENCE.T CONVERT CORREL COS COSH COT COTH COUNT COUNTA COUNTBLANK COUNTIF COUNTIFS COUPDAYBS COUPDAYS COUPDAYSNC COUPNCD COUPNUM COUPPCD COVAR COVARIANCE.P COVARIANCE.S CRITBINOM CSC CSCH CUBEKPIMEMBER CUBEMEMBER CUBEMEMBERPROPERTY CUBERANKEDMEMBER CUBESET CUBESETCOUNT CUBEVALUE CUMIPMT CUMPRINC DATE DATEDIF DATEVALUE DAVERAGE DAY DAYS DAYS360 DB DBCS DCOUNT DCOUNTA DDB DEC2BIN DEC2HEX DEC2OCT DECIMAL DEGREES DELTA DEVSQ DGET DISC DMAX DMIN DOLLAR DOLLARDE DOLLARFR DPRODUCT DSTDEV DSTDEVP DSUM DURATION DVAR DVARP EDATE EFFECT ENCODEURL EOMONTH ERF ERF.PRECISE ERFC ERFC.PRECISE ERROR.TYPE EUROCONVERT EVEN EXACT EXP EXPON.DIST EXPONDIST FACT FACTDOUBLE FALSE|0 F.DIST FDIST F.DIST.RT FILTERXML FIND FINDB F.INV F.INV.RT FINV FISHER FISHERINV FIXED FLOOR FLOOR.MATH FLOOR.PRECISE FORECAST FORECAST.ETS FORECAST.ETS.CONFINT FORECAST.ETS.SEASONALITY FORECAST.ETS.STAT FORECAST.LINEAR FORMULATEXT FREQUENCY F.TEST FTEST FV FVSCHEDULE GAMMA GAMMA.DIST GAMMADIST GAMMA.INV GAMMAINV GAMMALN GAMMALN.PRECISE GAUSS GCD GEOMEAN GESTEP GETPIVOTDATA GROWTH HARMEAN HEX2BIN HEX2DEC HEX2OCT HLOOKUP HOUR HYPERLINK HYPGEOM.DIST HYPGEOMDIST IF IFERROR IFNA IFS IMABS IMAGINARY IMARGUMENT IMCONJUGATE IMCOS IMCOSH IMCOT IMCSC IMCSCH IMDIV IMEXP IMLN IMLOG10 IMLOG2 IMPOWER IMPRODUCT IMREAL IMSEC IMSECH IMSIN IMSINH IMSQRT IMSUB IMSUM IMTAN INDEX INDIRECT INFO INT INTERCEPT INTRATE IPMT IRR ISBLANK ISERR ISERROR ISEVEN ISFORMULA ISLOGICAL ISNA ISNONTEXT ISNUMBER ISODD ISREF ISTEXT ISO.CEILING ISOWEEKNUM ISPMT JIS KURT LARGE LCM LEFT LEFTB LEN LENB LINEST LN LOG LOG10 LOGEST LOGINV LOGNORM.DIST LOGNORMDIST LOGNORM.INV LOOKUP LOWER MATCH MAX MAXA MAXIFS MDETERM MDURATION MEDIAN MID MIDBs MIN MINIFS MINA MINUTE MINVERSE MIRR MMULT MOD MODE MODE.MULT MODE.SNGL MONTH MROUND MULTINOMIAL MUNIT N NA NEGBINOM.DIST NEGBINOMDIST NETWORKDAYS NETWORKDAYS.INTL NOMINAL NORM.DIST NORMDIST NORMINV NORM.INV NORM.S.DIST NORMSDIST NORM.S.INV NORMSINV NOT NOW NPER NPV NUMBERVALUE OCT2BIN OCT2DEC OCT2HEX ODD ODDFPRICE ODDFYIELD ODDLPRICE ODDLYIELD OFFSET OR PDURATION PEARSON PERCENTILE.EXC PERCENTILE.INC PERCENTILE PERCENTRANK.EXC PERCENTRANK.INC PERCENTRANK PERMUT PERMUTATIONA PHI PHONETIC PI PMT POISSON.DIST POISSON POWER PPMT PRICE PRICEDISC PRICEMAT PROB PRODUCT PROPER PV QUARTILE QUARTILE.EXC QUARTILE.INC QUOTIENT RADIANS RAND RANDBETWEEN RANK.AVG RANK.EQ RANK RATE RECEIVED REGISTER.ID REPLACE REPLACEB REPT RIGHT RIGHTB ROMAN ROUND ROUNDDOWN ROUNDUP ROW ROWS RRI RSQ RTD SEARCH SEARCHB SEC SECH SECOND SERIESSUM SHEET SHEETS SIGN SIN SINH SKEW SKEW.P SLN SLOPE SMALL SQL.REQUEST SQRT SQRTPI STANDARDIZE STDEV STDEV.P STDEV.S STDEVA STDEVP STDEVPA STEYX SUBSTITUTE SUBTOTAL SUM SUMIF SUMIFS SUMPRODUCT SUMSQ SUMX2MY2 SUMX2PY2 SUMXMY2 SWITCH SYD T TAN TANH TBILLEQ TBILLPRICE TBILLYIELD T.DIST T.DIST.2T T.DIST.RT TDIST TEXT TEXTJOIN TIME TIMEVALUE T.INV T.INV.2T TINV TODAY TRANSPOSE TREND TRIM TRIMMEAN TRUE|0 TRUNC T.TEST TTEST TYPE UNICHAR UNICODE UPPER VALUE VAR VAR.P VAR.S VARA VARP VARPA VDB VLOOKUP WEBSERVICE WEEKDAY WEEKNUM WEIBULL WEIBULL.DIST WORKDAY WORKDAY.INTL XIRR XNPV XOR YEAR YEARFRAC YIELD YIELDDISC YIELDMAT Z.TEST ZTEST'
    -    },
    -    contains: [
    -      {
    -        /* matches a beginning equal sign found in Excel formula examples */
    -        begin: /^=/,
    -        end: /[^=]/,
    -        returnEnd: true,
    -        illegal: /=/, /* only allow single equal sign at front of line */
    -        relevance: 10
    -      },
    -      /* technically, there can be more than 2 letters in column names, but this prevents conflict with some keywords */
    -      {
    -        /* matches a reference to a single cell */
    -        className: 'symbol',
    -        begin: /\b[A-Z]{1,2}\d+\b/,
    -        end: /[^\d]/,
    -        excludeEnd: true,
    -        relevance: 0
    -      },
    -      {
    -        /* matches a reference to a range of cells */
    -        className: 'symbol',
    -        begin: /[A-Z]{0,2}\d*:[A-Z]{0,2}\d*/,
    -        relevance: 0
    -      },
    -      hljs.BACKSLASH_ESCAPE,
    -      hljs.QUOTE_STRING_MODE,
    -      {
    -        className: 'number',
    -        begin: hljs.NUMBER_RE + '(%)?',
    -        relevance: 0
    -      },
    -      /* Excel formula comments are done by putting the comment in a function call to N() */
    -      hljs.COMMENT(/\bN\(/, /\)/,
    -        {
    -          excludeBegin: true,
    -          excludeEnd: true,
    -          illegal: /\n/
    -        })
    -    ]
    -  };
    -}
    -
    -module.exports = excel;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/fix.js b/claude-code-source/node_modules/highlight.js/lib/languages/fix.js
    deleted file mode 100644
    index 137015cf..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/fix.js
    +++ /dev/null
    @@ -1,37 +0,0 @@
    -/*
    -Language: FIX
    -Author: Brent Bradbury 
    -*/
    -
    -/** @type LanguageFn */
    -function fix(hljs) {
    -  return {
    -    name: 'FIX',
    -    contains: [{
    -      begin: /[^\u2401\u0001]+/,
    -      end: /[\u2401\u0001]/,
    -      excludeEnd: true,
    -      returnBegin: true,
    -      returnEnd: false,
    -      contains: [
    -        {
    -          begin: /([^\u2401\u0001=]+)/,
    -          end: /=([^\u2401\u0001=]+)/,
    -          returnEnd: true,
    -          returnBegin: false,
    -          className: 'attr'
    -        },
    -        {
    -          begin: /=/,
    -          end: /([\u2401\u0001])/,
    -          excludeEnd: true,
    -          excludeBegin: true,
    -          className: 'string'
    -        }
    -      ]
    -    }],
    -    case_insensitive: true
    -  };
    -}
    -
    -module.exports = fix;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/flix.js b/claude-code-source/node_modules/highlight.js/lib/languages/flix.js
    deleted file mode 100644
    index cca423e5..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/flix.js
    +++ /dev/null
    @@ -1,54 +0,0 @@
    -/*
    - Language: Flix
    - Category: functional
    - Author: Magnus Madsen 
    - Website: https://flix.dev/
    - */
    -
    - /** @type LanguageFn */
    -function flix(hljs) {
    -  const CHAR = {
    -    className: 'string',
    -    begin: /'(.|\\[xXuU][a-zA-Z0-9]+)'/
    -  };
    -
    -  const STRING = {
    -    className: 'string',
    -    variants: [{
    -      begin: '"',
    -      end: '"'
    -    }]
    -  };
    -
    -  const NAME = {
    -    className: 'title',
    -    relevance: 0,
    -    begin: /[^0-9\n\t "'(),.`{}\[\]:;][^\n\t "'(),.`{}\[\]:;]+|[^0-9\n\t "'(),.`{}\[\]:;=]/
    -  };
    -
    -  const METHOD = {
    -    className: 'function',
    -    beginKeywords: 'def',
    -    end: /[:={\[(\n;]/,
    -    excludeEnd: true,
    -    contains: [NAME]
    -  };
    -
    -  return {
    -    name: 'Flix',
    -    keywords: {
    -      literal: 'true false',
    -      keyword: 'case class def else enum if impl import in lat rel index let match namespace switch type yield with'
    -    },
    -    contains: [
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      CHAR,
    -      STRING,
    -      METHOD,
    -      hljs.C_NUMBER_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = flix;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/fortran.js b/claude-code-source/node_modules/highlight.js/lib/languages/fortran.js
    deleted file mode 100644
    index 06adc645..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/fortran.js
    +++ /dev/null
    @@ -1,159 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: Fortran
    -Author: Anthony Scemama 
    -Website: https://en.wikipedia.org/wiki/Fortran
    -Category: scientific
    -*/
    -
    -/** @type LanguageFn */
    -function fortran(hljs) {
    -  const PARAMS = {
    -    className: 'params',
    -    begin: '\\(',
    -    end: '\\)'
    -  };
    -
    -  const COMMENT = {
    -    variants: [
    -      hljs.COMMENT('!', '$', {
    -        relevance: 0
    -      }),
    -      // allow FORTRAN 77 style comments
    -      hljs.COMMENT('^C[ ]', '$', {
    -        relevance: 0
    -      }),
    -      hljs.COMMENT('^C$', '$', {
    -        relevance: 0
    -      })
    -    ]
    -  };
    -
    -  // regex in both fortran and irpf90 should match
    -  const OPTIONAL_NUMBER_SUFFIX = /(_[a-z_\d]+)?/;
    -  const OPTIONAL_NUMBER_EXP = /([de][+-]?\d+)?/;
    -  const NUMBER = {
    -    className: 'number',
    -    variants: [
    -      {
    -        begin: concat(/\b\d+/, /\.(\d*)/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX)
    -      },
    -      {
    -        begin: concat(/\b\d+/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX)
    -      },
    -      {
    -        begin: concat(/\.\d+/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX)
    -      }
    -    ],
    -    relevance: 0
    -  };
    -
    -  const FUNCTION_DEF = {
    -    className: 'function',
    -    beginKeywords: 'subroutine function program',
    -    illegal: '[${=\\n]',
    -    contains: [
    -      hljs.UNDERSCORE_TITLE_MODE,
    -      PARAMS
    -    ]
    -  };
    -
    -  const STRING = {
    -    className: 'string',
    -    relevance: 0,
    -    variants: [
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE
    -    ]
    -  };
    -
    -  const KEYWORDS = {
    -    literal: '.False. .True.',
    -    keyword: 'kind do concurrent local shared while private call intrinsic where elsewhere ' +
    -      'type endtype endmodule endselect endinterface end enddo endif if forall endforall only contains default return stop then block endblock endassociate ' +
    -      'public subroutine|10 function program .and. .or. .not. .le. .eq. .ge. .gt. .lt. ' +
    -      'goto save else use module select case ' +
    -      'access blank direct exist file fmt form formatted iostat name named nextrec number opened rec recl sequential status unformatted unit ' +
    -      'continue format pause cycle exit ' +
    -      'c_null_char c_alert c_backspace c_form_feed flush wait decimal round iomsg ' +
    -      'synchronous nopass non_overridable pass protected volatile abstract extends import ' +
    -      'non_intrinsic value deferred generic final enumerator class associate bind enum ' +
    -      'c_int c_short c_long c_long_long c_signed_char c_size_t c_int8_t c_int16_t c_int32_t c_int64_t c_int_least8_t c_int_least16_t ' +
    -      'c_int_least32_t c_int_least64_t c_int_fast8_t c_int_fast16_t c_int_fast32_t c_int_fast64_t c_intmax_t C_intptr_t c_float c_double ' +
    -      'c_long_double c_float_complex c_double_complex c_long_double_complex c_bool c_char c_null_ptr c_null_funptr ' +
    -      'c_new_line c_carriage_return c_horizontal_tab c_vertical_tab iso_c_binding c_loc c_funloc c_associated  c_f_pointer ' +
    -      'c_ptr c_funptr iso_fortran_env character_storage_size error_unit file_storage_size input_unit iostat_end iostat_eor ' +
    -      'numeric_storage_size output_unit c_f_procpointer ieee_arithmetic ieee_support_underflow_control ' +
    -      'ieee_get_underflow_mode ieee_set_underflow_mode newunit contiguous recursive ' +
    -      'pad position action delim readwrite eor advance nml interface procedure namelist include sequence elemental pure impure ' +
    -      'integer real character complex logical codimension dimension allocatable|10 parameter ' +
    -      'external implicit|10 none double precision assign intent optional pointer ' +
    -      'target in out common equivalence data',
    -    built_in: 'alog alog10 amax0 amax1 amin0 amin1 amod cabs ccos cexp clog csin csqrt dabs dacos dasin datan datan2 dcos dcosh ddim dexp dint ' +
    -      'dlog dlog10 dmax1 dmin1 dmod dnint dsign dsin dsinh dsqrt dtan dtanh float iabs idim idint idnint ifix isign max0 max1 min0 min1 sngl ' +
    -      'algama cdabs cdcos cdexp cdlog cdsin cdsqrt cqabs cqcos cqexp cqlog cqsin cqsqrt dcmplx dconjg derf derfc dfloat dgamma dimag dlgama ' +
    -      'iqint qabs qacos qasin qatan qatan2 qcmplx qconjg qcos qcosh qdim qerf qerfc qexp qgamma qimag qlgama qlog qlog10 qmax1 qmin1 qmod ' +
    -      'qnint qsign qsin qsinh qsqrt qtan qtanh abs acos aimag aint anint asin atan atan2 char cmplx conjg cos cosh exp ichar index int log ' +
    -      'log10 max min nint sign sin sinh sqrt tan tanh print write dim lge lgt lle llt mod nullify allocate deallocate ' +
    -      'adjustl adjustr all allocated any associated bit_size btest ceiling count cshift date_and_time digits dot_product ' +
    -      'eoshift epsilon exponent floor fraction huge iand ibclr ibits ibset ieor ior ishft ishftc lbound len_trim matmul ' +
    -      'maxexponent maxloc maxval merge minexponent minloc minval modulo mvbits nearest pack present product ' +
    -      'radix random_number random_seed range repeat reshape rrspacing scale scan selected_int_kind selected_real_kind ' +
    -      'set_exponent shape size spacing spread sum system_clock tiny transpose trim ubound unpack verify achar iachar transfer ' +
    -      'dble entry dprod cpu_time command_argument_count get_command get_command_argument get_environment_variable is_iostat_end ' +
    -      'ieee_arithmetic ieee_support_underflow_control ieee_get_underflow_mode ieee_set_underflow_mode ' +
    -      'is_iostat_eor move_alloc new_line selected_char_kind same_type_as extends_type_of ' +
    -      'acosh asinh atanh bessel_j0 bessel_j1 bessel_jn bessel_y0 bessel_y1 bessel_yn erf erfc erfc_scaled gamma log_gamma hypot norm2 ' +
    -      'atomic_define atomic_ref execute_command_line leadz trailz storage_size merge_bits ' +
    -      'bge bgt ble blt dshiftl dshiftr findloc iall iany iparity image_index lcobound ucobound maskl maskr ' +
    -      'num_images parity popcnt poppar shifta shiftl shiftr this_image sync change team co_broadcast co_max co_min co_sum co_reduce'
    -  };
    -  return {
    -    name: 'Fortran',
    -    case_insensitive: true,
    -    aliases: [
    -      'f90',
    -      'f95'
    -    ],
    -    keywords: KEYWORDS,
    -    illegal: /\/\*/,
    -    contains: [
    -      STRING,
    -      FUNCTION_DEF,
    -      // allow `C = value` for assignments so they aren't misdetected
    -      // as Fortran 77 style comments
    -      {
    -        begin: /^C\s*=(?!=)/,
    -        relevance: 0
    -      },
    -      COMMENT,
    -      NUMBER
    -    ]
    -  };
    -}
    -
    -module.exports = fortran;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/fsharp.js b/claude-code-source/node_modules/highlight.js/lib/languages/fsharp.js
    deleted file mode 100644
    index 89488a03..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/fsharp.js
    +++ /dev/null
    @@ -1,86 +0,0 @@
    -/*
    -Language: F#
    -Author: Jonas Follesø 
    -Contributors: Troy Kershaw , Henrik Feldt 
    -Website: https://docs.microsoft.com/en-us/dotnet/fsharp/
    -Category: functional
    -*/
    -
    -/** @type LanguageFn */
    -function fsharp(hljs) {
    -  const TYPEPARAM = {
    -    begin: '<',
    -    end: '>',
    -    contains: [
    -      hljs.inherit(hljs.TITLE_MODE, {
    -        begin: /'[a-zA-Z0-9_]+/
    -      })
    -    ]
    -  };
    -
    -  return {
    -    name: 'F#',
    -    aliases: ['fs'],
    -    keywords:
    -      'abstract and as assert base begin class default delegate do done ' +
    -      'downcast downto elif else end exception extern false finally for ' +
    -      'fun function global if in inherit inline interface internal lazy let ' +
    -      'match member module mutable namespace new null of open or ' +
    -      'override private public rec return sig static struct then to ' +
    -      'true try type upcast use val void when while with yield',
    -    illegal: /\/\*/,
    -    contains: [
    -      {
    -        // monad builder keywords (matches before non-bang kws)
    -        className: 'keyword',
    -        begin: /\b(yield|return|let|do)!/
    -      },
    -      {
    -        className: 'string',
    -        begin: '@"',
    -        end: '"',
    -        contains: [
    -          {
    -            begin: '""'
    -          }
    -        ]
    -      },
    -      {
    -        className: 'string',
    -        begin: '"""',
    -        end: '"""'
    -      },
    -      hljs.COMMENT('\\(\\*(\\s)', '\\*\\)', {
    -        contains: ["self"]
    -      }),
    -      {
    -        className: 'class',
    -        beginKeywords: 'type',
    -        end: '\\(|=|$',
    -        excludeEnd: true,
    -        contains: [
    -          hljs.UNDERSCORE_TITLE_MODE,
    -          TYPEPARAM
    -        ]
    -      },
    -      {
    -        className: 'meta',
    -        begin: '\\[<',
    -        end: '>\\]',
    -        relevance: 10
    -      },
    -      {
    -        className: 'symbol',
    -        begin: '\\B(\'[A-Za-z])\\b',
    -        contains: [hljs.BACKSLASH_ESCAPE]
    -      },
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.inherit(hljs.QUOTE_STRING_MODE, {
    -        illegal: null
    -      }),
    -      hljs.C_NUMBER_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = fsharp;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/gams.js b/claude-code-source/node_modules/highlight.js/lib/languages/gams.js
    deleted file mode 100644
    index 5398fdc3..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/gams.js
    +++ /dev/null
    @@ -1,208 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function anyNumberOfTimes(re) {
    -  return concat('(', re, ')*');
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/** @type LanguageFn */
    -function gams(hljs) {
    -  const KEYWORDS = {
    -    keyword:
    -      'abort acronym acronyms alias all and assign binary card diag display ' +
    -      'else eq file files for free ge gt if integer le loop lt maximizing ' +
    -      'minimizing model models ne negative no not option options or ord ' +
    -      'positive prod put putpage puttl repeat sameas semicont semiint smax ' +
    -      'smin solve sos1 sos2 sum system table then until using while xor yes',
    -    literal:
    -      'eps inf na',
    -    built_in:
    -      'abs arccos arcsin arctan arctan2 Beta betaReg binomial ceil centropy ' +
    -      'cos cosh cvPower div div0 eDist entropy errorf execSeed exp fact ' +
    -      'floor frac gamma gammaReg log logBeta logGamma log10 log2 mapVal max ' +
    -      'min mod ncpCM ncpF ncpVUpow ncpVUsin normal pi poly power ' +
    -      'randBinomial randLinear randTriangle round rPower sigmoid sign ' +
    -      'signPower sin sinh slexp sllog10 slrec sqexp sqlog10 sqr sqrec sqrt ' +
    -      'tan tanh trunc uniform uniformInt vcPower bool_and bool_eqv bool_imp ' +
    -      'bool_not bool_or bool_xor ifThen rel_eq rel_ge rel_gt rel_le rel_lt ' +
    -      'rel_ne gday gdow ghour gleap gmillisec gminute gmonth gsecond gyear ' +
    -      'jdate jnow jstart jtime errorLevel execError gamsRelease gamsVersion ' +
    -      'handleCollect handleDelete handleStatus handleSubmit heapFree ' +
    -      'heapLimit heapSize jobHandle jobKill jobStatus jobTerminate ' +
    -      'licenseLevel licenseStatus maxExecError sleep timeClose timeComp ' +
    -      'timeElapsed timeExec timeStart'
    -  };
    -  const PARAMS = {
    -    className: 'params',
    -    begin: /\(/,
    -    end: /\)/,
    -    excludeBegin: true,
    -    excludeEnd: true
    -  };
    -  const SYMBOLS = {
    -    className: 'symbol',
    -    variants: [
    -      {
    -        begin: /=[lgenxc]=/
    -      },
    -      {
    -        begin: /\$/
    -      }
    -    ]
    -  };
    -  const QSTR = { // One-line quoted comment string
    -    className: 'comment',
    -    variants: [
    -      {
    -        begin: '\'',
    -        end: '\''
    -      },
    -      {
    -        begin: '"',
    -        end: '"'
    -      }
    -    ],
    -    illegal: '\\n',
    -    contains: [hljs.BACKSLASH_ESCAPE]
    -  };
    -  const ASSIGNMENT = {
    -    begin: '/',
    -    end: '/',
    -    keywords: KEYWORDS,
    -    contains: [
    -      QSTR,
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.APOS_STRING_MODE,
    -      hljs.C_NUMBER_MODE
    -    ]
    -  };
    -  const COMMENT_WORD = /[a-z0-9&#*=?@\\><:,()$[\]_.{}!+%^-]+/;
    -  const DESCTEXT = { // Parameter/set/variable description text
    -    begin: /[a-z][a-z0-9_]*(\([a-z0-9_, ]*\))?[ \t]+/,
    -    excludeBegin: true,
    -    end: '$',
    -    endsWithParent: true,
    -    contains: [
    -      QSTR,
    -      ASSIGNMENT,
    -      {
    -        className: 'comment',
    -        // one comment word, then possibly more
    -        begin: concat(
    -          COMMENT_WORD,
    -          // [ ] because \s would be too broad (matching newlines)
    -          anyNumberOfTimes(concat(/[ ]+/, COMMENT_WORD))
    -        ),
    -        relevance: 0
    -      }
    -    ]
    -  };
    -
    -  return {
    -    name: 'GAMS',
    -    aliases: ['gms'],
    -    case_insensitive: true,
    -    keywords: KEYWORDS,
    -    contains: [
    -      hljs.COMMENT(/^\$ontext/, /^\$offtext/),
    -      {
    -        className: 'meta',
    -        begin: '^\\$[a-z0-9]+',
    -        end: '$',
    -        returnBegin: true,
    -        contains: [
    -          {
    -            className: 'meta-keyword',
    -            begin: '^\\$[a-z0-9]+'
    -          }
    -        ]
    -      },
    -      hljs.COMMENT('^\\*', '$'),
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.APOS_STRING_MODE,
    -      // Declarations
    -      {
    -        beginKeywords:
    -          'set sets parameter parameters variable variables ' +
    -          'scalar scalars equation equations',
    -        end: ';',
    -        contains: [
    -          hljs.COMMENT('^\\*', '$'),
    -          hljs.C_LINE_COMMENT_MODE,
    -          hljs.C_BLOCK_COMMENT_MODE,
    -          hljs.QUOTE_STRING_MODE,
    -          hljs.APOS_STRING_MODE,
    -          ASSIGNMENT,
    -          DESCTEXT
    -        ]
    -      },
    -      { // table environment
    -        beginKeywords: 'table',
    -        end: ';',
    -        returnBegin: true,
    -        contains: [
    -          { // table header row
    -            beginKeywords: 'table',
    -            end: '$',
    -            contains: [DESCTEXT]
    -          },
    -          hljs.COMMENT('^\\*', '$'),
    -          hljs.C_LINE_COMMENT_MODE,
    -          hljs.C_BLOCK_COMMENT_MODE,
    -          hljs.QUOTE_STRING_MODE,
    -          hljs.APOS_STRING_MODE,
    -          hljs.C_NUMBER_MODE
    -          // Table does not contain DESCTEXT or ASSIGNMENT
    -        ]
    -      },
    -      // Function definitions
    -      {
    -        className: 'function',
    -        begin: /^[a-z][a-z0-9_,\-+' ()$]+\.{2}/,
    -        returnBegin: true,
    -        contains: [
    -          { // Function title
    -            className: 'title',
    -            begin: /^[a-z0-9_]+/
    -          },
    -          PARAMS,
    -          SYMBOLS
    -        ]
    -      },
    -      hljs.C_NUMBER_MODE,
    -      SYMBOLS
    -    ]
    -  };
    -}
    -
    -module.exports = gams;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/gauss.js b/claude-code-source/node_modules/highlight.js/lib/languages/gauss.js
    deleted file mode 100644
    index 29254f00..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/gauss.js
    +++ /dev/null
    @@ -1,316 +0,0 @@
    -/*
    -Language: GAUSS
    -Author: Matt Evans 
    -Description: GAUSS Mathematical and Statistical language
    -Website: https://www.aptech.com
    -Category: scientific
    -*/
    -function gauss(hljs) {
    -  const KEYWORDS = {
    -    keyword: 'bool break call callexe checkinterrupt clear clearg closeall cls comlog compile ' +
    -              'continue create debug declare delete disable dlibrary dllcall do dos ed edit else ' +
    -              'elseif enable end endfor endif endp endo errorlog errorlogat expr external fn ' +
    -              'for format goto gosub graph if keyword let lib library line load loadarray loadexe ' +
    -              'loadf loadk loadm loadp loads loadx local locate loopnextindex lprint lpwidth lshow ' +
    -              'matrix msym ndpclex new open output outwidth plot plotsym pop prcsn print ' +
    -              'printdos proc push retp return rndcon rndmod rndmult rndseed run save saveall screen ' +
    -              'scroll setarray show sparse stop string struct system trace trap threadfor ' +
    -              'threadendfor threadbegin threadjoin threadstat threadend until use while winprint ' +
    -              'ne ge le gt lt and xor or not eq eqv',
    -    built_in: 'abs acf aconcat aeye amax amean AmericanBinomCall AmericanBinomCall_Greeks AmericanBinomCall_ImpVol ' +
    -              'AmericanBinomPut AmericanBinomPut_Greeks AmericanBinomPut_ImpVol AmericanBSCall AmericanBSCall_Greeks ' +
    -              'AmericanBSCall_ImpVol AmericanBSPut AmericanBSPut_Greeks AmericanBSPut_ImpVol amin amult annotationGetDefaults ' +
    -              'annotationSetBkd annotationSetFont annotationSetLineColor annotationSetLineStyle annotationSetLineThickness ' +
    -              'annualTradingDays arccos arcsin areshape arrayalloc arrayindex arrayinit arraytomat asciiload asclabel astd ' +
    -              'astds asum atan atan2 atranspose axmargin balance band bandchol bandcholsol bandltsol bandrv bandsolpd bar ' +
    -              'base10 begwind besselj bessely beta box boxcox cdfBeta cdfBetaInv cdfBinomial cdfBinomialInv cdfBvn cdfBvn2 ' +
    -              'cdfBvn2e cdfCauchy cdfCauchyInv cdfChic cdfChii cdfChinc cdfChincInv cdfExp cdfExpInv cdfFc cdfFnc cdfFncInv ' +
    -              'cdfGam cdfGenPareto cdfHyperGeo cdfLaplace cdfLaplaceInv cdfLogistic cdfLogisticInv cdfmControlCreate cdfMvn ' +
    -              'cdfMvn2e cdfMvnce cdfMvne cdfMvt2e cdfMvtce cdfMvte cdfN cdfN2 cdfNc cdfNegBinomial cdfNegBinomialInv cdfNi ' +
    -              'cdfPoisson cdfPoissonInv cdfRayleigh cdfRayleighInv cdfTc cdfTci cdfTnc cdfTvn cdfWeibull cdfWeibullInv cdir ' +
    -              'ceil ChangeDir chdir chiBarSquare chol choldn cholsol cholup chrs close code cols colsf combinate combinated ' +
    -              'complex con cond conj cons ConScore contour conv convertsatostr convertstrtosa corrm corrms corrvc corrx corrxs ' +
    -              'cos cosh counts countwts crossprd crout croutp csrcol csrlin csvReadM csvReadSA cumprodc cumsumc curve cvtos ' +
    -              'datacreate datacreatecomplex datalist dataload dataloop dataopen datasave date datestr datestring datestrymd ' +
    -              'dayinyr dayofweek dbAddDatabase dbClose dbCommit dbCreateQuery dbExecQuery dbGetConnectOptions dbGetDatabaseName ' +
    -              'dbGetDriverName dbGetDrivers dbGetHostName dbGetLastErrorNum dbGetLastErrorText dbGetNumericalPrecPolicy ' +
    -              'dbGetPassword dbGetPort dbGetTableHeaders dbGetTables dbGetUserName dbHasFeature dbIsDriverAvailable dbIsOpen ' +
    -              'dbIsOpenError dbOpen dbQueryBindValue dbQueryClear dbQueryCols dbQueryExecPrepared dbQueryFetchAllM dbQueryFetchAllSA ' +
    -              'dbQueryFetchOneM dbQueryFetchOneSA dbQueryFinish dbQueryGetBoundValue dbQueryGetBoundValues dbQueryGetField ' +
    -              'dbQueryGetLastErrorNum dbQueryGetLastErrorText dbQueryGetLastInsertID dbQueryGetLastQuery dbQueryGetPosition ' +
    -              'dbQueryIsActive dbQueryIsForwardOnly dbQueryIsNull dbQueryIsSelect dbQueryIsValid dbQueryPrepare dbQueryRows ' +
    -              'dbQuerySeek dbQuerySeekFirst dbQuerySeekLast dbQuerySeekNext dbQuerySeekPrevious dbQuerySetForwardOnly ' +
    -              'dbRemoveDatabase dbRollback dbSetConnectOptions dbSetDatabaseName dbSetHostName dbSetNumericalPrecPolicy ' +
    -              'dbSetPort dbSetUserName dbTransaction DeleteFile delif delrows denseToSp denseToSpRE denToZero design det detl ' +
    -              'dfft dffti diag diagrv digamma doswin DOSWinCloseall DOSWinOpen dotfeq dotfeqmt dotfge dotfgemt dotfgt dotfgtmt ' +
    -              'dotfle dotflemt dotflt dotfltmt dotfne dotfnemt draw drop dsCreate dstat dstatmt dstatmtControlCreate dtdate dtday ' +
    -              'dttime dttodtv dttostr dttoutc dtvnormal dtvtodt dtvtoutc dummy dummybr dummydn eig eigh eighv eigv elapsedTradingDays ' +
    -              'endwind envget eof eqSolve eqSolvemt eqSolvemtControlCreate eqSolvemtOutCreate eqSolveset erf erfc erfccplx erfcplx error ' +
    -              'etdays ethsec etstr EuropeanBinomCall EuropeanBinomCall_Greeks EuropeanBinomCall_ImpVol EuropeanBinomPut ' +
    -              'EuropeanBinomPut_Greeks EuropeanBinomPut_ImpVol EuropeanBSCall EuropeanBSCall_Greeks EuropeanBSCall_ImpVol ' +
    -              'EuropeanBSPut EuropeanBSPut_Greeks EuropeanBSPut_ImpVol exctsmpl exec execbg exp extern eye fcheckerr fclearerr feq ' +
    -              'feqmt fflush fft ffti fftm fftmi fftn fge fgemt fgets fgetsa fgetsat fgetst fgt fgtmt fileinfo filesa fle flemt ' +
    -              'floor flt fltmt fmod fne fnemt fonts fopen formatcv formatnv fputs fputst fseek fstrerror ftell ftocv ftos ftostrC ' +
    -              'gamma gammacplx gammaii gausset gdaAppend gdaCreate gdaDStat gdaDStatMat gdaGetIndex gdaGetName gdaGetNames gdaGetOrders ' +
    -              'gdaGetType gdaGetTypes gdaGetVarInfo gdaIsCplx gdaLoad gdaPack gdaRead gdaReadByIndex gdaReadSome gdaReadSparse ' +
    -              'gdaReadStruct gdaReportVarInfo gdaSave gdaUpdate gdaUpdateAndPack gdaVars gdaWrite gdaWrite32 gdaWriteSome getarray ' +
    -              'getdims getf getGAUSShome getmatrix getmatrix4D getname getnamef getNextTradingDay getNextWeekDay getnr getorders ' +
    -              'getpath getPreviousTradingDay getPreviousWeekDay getRow getscalar3D getscalar4D getTrRow getwind glm gradcplx gradMT ' +
    -              'gradMTm gradMTT gradMTTm gradp graphprt graphset hasimag header headermt hess hessMT hessMTg hessMTgw hessMTm ' +
    -              'hessMTmw hessMTT hessMTTg hessMTTgw hessMTTm hessMTw hessp hist histf histp hsec imag indcv indexcat indices indices2 ' +
    -              'indicesf indicesfn indnv indsav integrate1d integrateControlCreate intgrat2 intgrat3 inthp1 inthp2 inthp3 inthp4 ' +
    -              'inthpControlCreate intquad1 intquad2 intquad3 intrleav intrleavsa intrsect intsimp inv invpd invswp iscplx iscplxf ' +
    -              'isden isinfnanmiss ismiss key keyav keyw lag lag1 lagn lapEighb lapEighi lapEighvb lapEighvi lapgEig lapgEigh lapgEighv ' +
    -              'lapgEigv lapgSchur lapgSvdcst lapgSvds lapgSvdst lapSvdcusv lapSvds lapSvdusv ldlp ldlsol linSolve listwise ln lncdfbvn ' +
    -              'lncdfbvn2 lncdfmvn lncdfn lncdfn2 lncdfnc lnfact lngammacplx lnpdfmvn lnpdfmvt lnpdfn lnpdft loadd loadstruct loadwind ' +
    -              'loess loessmt loessmtControlCreate log loglog logx logy lower lowmat lowmat1 ltrisol lu lusol machEpsilon make makevars ' +
    -              'makewind margin matalloc matinit mattoarray maxbytes maxc maxindc maxv maxvec mbesselei mbesselei0 mbesselei1 mbesseli ' +
    -              'mbesseli0 mbesseli1 meanc median mergeby mergevar minc minindc minv miss missex missrv moment momentd movingave ' +
    -              'movingaveExpwgt movingaveWgt nextindex nextn nextnevn nextwind ntos null null1 numCombinations ols olsmt olsmtControlCreate ' +
    -              'olsqr olsqr2 olsqrmt ones optn optnevn orth outtyp pacf packedToSp packr parse pause pdfCauchy pdfChi pdfExp pdfGenPareto ' +
    -              'pdfHyperGeo pdfLaplace pdfLogistic pdfn pdfPoisson pdfRayleigh pdfWeibull pi pinv pinvmt plotAddArrow plotAddBar plotAddBox ' +
    -              'plotAddHist plotAddHistF plotAddHistP plotAddPolar plotAddScatter plotAddShape plotAddTextbox plotAddTS plotAddXY plotArea ' +
    -              'plotBar plotBox plotClearLayout plotContour plotCustomLayout plotGetDefaults plotHist plotHistF plotHistP plotLayout ' +
    -              'plotLogLog plotLogX plotLogY plotOpenWindow plotPolar plotSave plotScatter plotSetAxesPen plotSetBar plotSetBarFill ' +
    -              'plotSetBarStacked plotSetBkdColor plotSetFill plotSetGrid plotSetLegend plotSetLineColor plotSetLineStyle plotSetLineSymbol ' +
    -              'plotSetLineThickness plotSetNewWindow plotSetTitle plotSetWhichYAxis plotSetXAxisShow plotSetXLabel plotSetXRange ' +
    -              'plotSetXTicInterval plotSetXTicLabel plotSetYAxisShow plotSetYLabel plotSetYRange plotSetZAxisShow plotSetZLabel ' +
    -              'plotSurface plotTS plotXY polar polychar polyeval polygamma polyint polymake polymat polymroot polymult polyroot ' +
    -              'pqgwin previousindex princomp printfm printfmt prodc psi putarray putf putvals pvCreate pvGetIndex pvGetParNames ' +
    -              'pvGetParVector pvLength pvList pvPack pvPacki pvPackm pvPackmi pvPacks pvPacksi pvPacksm pvPacksmi pvPutParVector ' +
    -              'pvTest pvUnpack QNewton QNewtonmt QNewtonmtControlCreate QNewtonmtOutCreate QNewtonSet QProg QProgmt QProgmtInCreate ' +
    -              'qqr qqre qqrep qr qre qrep qrsol qrtsol qtyr qtyre qtyrep quantile quantiled qyr qyre qyrep qz rank rankindx readr ' +
    -              'real reclassify reclassifyCuts recode recserar recsercp recserrc rerun rescale reshape rets rev rfft rffti rfftip rfftn ' +
    -              'rfftnp rfftp rndBernoulli rndBeta rndBinomial rndCauchy rndChiSquare rndCon rndCreateState rndExp rndGamma rndGeo rndGumbel ' +
    -              'rndHyperGeo rndi rndKMbeta rndKMgam rndKMi rndKMn rndKMnb rndKMp rndKMu rndKMvm rndLaplace rndLCbeta rndLCgam rndLCi rndLCn ' +
    -              'rndLCnb rndLCp rndLCu rndLCvm rndLogNorm rndMTu rndMVn rndMVt rndn rndnb rndNegBinomial rndp rndPoisson rndRayleigh ' +
    -              'rndStateSkip rndu rndvm rndWeibull rndWishart rotater round rows rowsf rref sampleData satostrC saved saveStruct savewind ' +
    -              'scale scale3d scalerr scalinfnanmiss scalmiss schtoc schur searchsourcepath seekr select selif seqa seqm setdif setdifsa ' +
    -              'setvars setvwrmode setwind shell shiftr sin singleindex sinh sleep solpd sortc sortcc sortd sorthc sorthcc sortind ' +
    -              'sortindc sortmc sortr sortrc spBiconjGradSol spChol spConjGradSol spCreate spDenseSubmat spDiagRvMat spEigv spEye spLDL ' +
    -              'spline spLU spNumNZE spOnes spreadSheetReadM spreadSheetReadSA spreadSheetWrite spScale spSubmat spToDense spTrTDense ' +
    -              'spTScalar spZeros sqpSolve sqpSolveMT sqpSolveMTControlCreate sqpSolveMTlagrangeCreate sqpSolveMToutCreate sqpSolveSet ' +
    -              'sqrt statements stdc stdsc stocv stof strcombine strindx strlen strput strrindx strsect strsplit strsplitPad strtodt ' +
    -              'strtof strtofcplx strtriml strtrimr strtrunc strtruncl strtruncpad strtruncr submat subscat substute subvec sumc sumr ' +
    -              'surface svd svd1 svd2 svdcusv svds svdusv sysstate tab tan tanh tempname ' +
    -              'time timedt timestr timeutc title tkf2eps tkf2ps tocart todaydt toeplitz token topolar trapchk ' +
    -              'trigamma trimr trunc type typecv typef union unionsa uniqindx uniqindxsa unique uniquesa upmat upmat1 upper utctodt ' +
    -              'utctodtv utrisol vals varCovMS varCovXS varget vargetl varmall varmares varput varputl vartypef vcm vcms vcx vcxs ' +
    -              'vec vech vecr vector vget view viewxyz vlist vnamecv volume vput vread vtypecv wait waitc walkindex where window ' +
    -              'writer xlabel xlsGetSheetCount xlsGetSheetSize xlsGetSheetTypes xlsMakeRange xlsReadM xlsReadSA xlsWrite xlsWriteM ' +
    -              'xlsWriteSA xpnd xtics xy xyz ylabel ytics zeros zeta zlabel ztics cdfEmpirical dot h5create h5open h5read h5readAttribute ' +
    -              'h5write h5writeAttribute ldl plotAddErrorBar plotAddSurface plotCDFEmpirical plotSetColormap plotSetContourLabels ' +
    -              'plotSetLegendFont plotSetTextInterpreter plotSetXTicCount plotSetYTicCount plotSetZLevels powerm strjoin sylvester ' +
    -              'strtrim',
    -    literal: 'DB_AFTER_LAST_ROW DB_ALL_TABLES DB_BATCH_OPERATIONS DB_BEFORE_FIRST_ROW DB_BLOB DB_EVENT_NOTIFICATIONS ' +
    -             'DB_FINISH_QUERY DB_HIGH_PRECISION DB_LAST_INSERT_ID DB_LOW_PRECISION_DOUBLE DB_LOW_PRECISION_INT32 ' +
    -             'DB_LOW_PRECISION_INT64 DB_LOW_PRECISION_NUMBERS DB_MULTIPLE_RESULT_SETS DB_NAMED_PLACEHOLDERS ' +
    -             'DB_POSITIONAL_PLACEHOLDERS DB_PREPARED_QUERIES DB_QUERY_SIZE DB_SIMPLE_LOCKING DB_SYSTEM_TABLES DB_TABLES ' +
    -             'DB_TRANSACTIONS DB_UNICODE DB_VIEWS __STDIN __STDOUT __STDERR __FILE_DIR'
    -  };
    -
    -  const AT_COMMENT_MODE = hljs.COMMENT('@', '@');
    -
    -  const PREPROCESSOR =
    -  {
    -    className: 'meta',
    -    begin: '#',
    -    end: '$',
    -    keywords: {
    -      'meta-keyword': 'define definecs|10 undef ifdef ifndef iflight ifdllcall ifmac ifos2win ifunix else endif lineson linesoff srcfile srcline'
    -    },
    -    contains: [
    -      {
    -        begin: /\\\n/,
    -        relevance: 0
    -      },
    -      {
    -        beginKeywords: 'include',
    -        end: '$',
    -        keywords: {
    -          'meta-keyword': 'include'
    -        },
    -        contains: [
    -          {
    -            className: 'meta-string',
    -            begin: '"',
    -            end: '"',
    -            illegal: '\\n'
    -          }
    -        ]
    -      },
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      AT_COMMENT_MODE
    -    ]
    -  };
    -
    -  const STRUCT_TYPE =
    -  {
    -    begin: /\bstruct\s+/,
    -    end: /\s/,
    -    keywords: "struct",
    -    contains: [
    -      {
    -        className: "type",
    -        begin: hljs.UNDERSCORE_IDENT_RE,
    -        relevance: 0
    -      }
    -    ]
    -  };
    -
    -  // only for definitions
    -  const PARSE_PARAMS = [
    -    {
    -      className: 'params',
    -      begin: /\(/,
    -      end: /\)/,
    -      excludeBegin: true,
    -      excludeEnd: true,
    -      endsWithParent: true,
    -      relevance: 0,
    -      contains: [
    -        { // dots
    -          className: 'literal',
    -          begin: /\.\.\./
    -        },
    -        hljs.C_NUMBER_MODE,
    -        hljs.C_BLOCK_COMMENT_MODE,
    -        AT_COMMENT_MODE,
    -        STRUCT_TYPE
    -      ]
    -    }
    -  ];
    -
    -  const FUNCTION_DEF =
    -  {
    -    className: "title",
    -    begin: hljs.UNDERSCORE_IDENT_RE,
    -    relevance: 0
    -  };
    -
    -  const DEFINITION = function(beginKeywords, end, inherits) {
    -    const mode = hljs.inherit(
    -      {
    -        className: "function",
    -        beginKeywords: beginKeywords,
    -        end: end,
    -        excludeEnd: true,
    -        contains: [].concat(PARSE_PARAMS)
    -      },
    -      inherits || {}
    -    );
    -    mode.contains.push(FUNCTION_DEF);
    -    mode.contains.push(hljs.C_NUMBER_MODE);
    -    mode.contains.push(hljs.C_BLOCK_COMMENT_MODE);
    -    mode.contains.push(AT_COMMENT_MODE);
    -    return mode;
    -  };
    -
    -  const BUILT_IN_REF =
    -  { // these are explicitly named internal function calls
    -    className: 'built_in',
    -    begin: '\\b(' + KEYWORDS.built_in.split(' ').join('|') + ')\\b'
    -  };
    -
    -  const STRING_REF =
    -  {
    -    className: 'string',
    -    begin: '"',
    -    end: '"',
    -    contains: [hljs.BACKSLASH_ESCAPE],
    -    relevance: 0
    -  };
    -
    -  const FUNCTION_REF =
    -  {
    -    // className: "fn_ref",
    -    begin: hljs.UNDERSCORE_IDENT_RE + '\\s*\\(',
    -    returnBegin: true,
    -    keywords: KEYWORDS,
    -    relevance: 0,
    -    contains: [
    -      {
    -        beginKeywords: KEYWORDS.keyword
    -      },
    -      BUILT_IN_REF,
    -      { // ambiguously named function calls get a relevance of 0
    -        className: 'built_in',
    -        begin: hljs.UNDERSCORE_IDENT_RE,
    -        relevance: 0
    -      }
    -    ]
    -  };
    -
    -  const FUNCTION_REF_PARAMS =
    -  {
    -    // className: "fn_ref_params",
    -    begin: /\(/,
    -    end: /\)/,
    -    relevance: 0,
    -    keywords: {
    -      built_in: KEYWORDS.built_in,
    -      literal: KEYWORDS.literal
    -    },
    -    contains: [
    -      hljs.C_NUMBER_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      AT_COMMENT_MODE,
    -      BUILT_IN_REF,
    -      FUNCTION_REF,
    -      STRING_REF,
    -      'self'
    -    ]
    -  };
    -
    -  FUNCTION_REF.contains.push(FUNCTION_REF_PARAMS);
    -
    -  return {
    -    name: 'GAUSS',
    -    aliases: ['gss'],
    -    case_insensitive: true, // language is case-insensitive
    -    keywords: KEYWORDS,
    -    illegal: /(\{[%#]|[%#]\}| <- )/,
    -    contains: [
    -      hljs.C_NUMBER_MODE,
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      AT_COMMENT_MODE,
    -      STRING_REF,
    -      PREPROCESSOR,
    -      {
    -        className: 'keyword',
    -        begin: /\bexternal (matrix|string|array|sparse matrix|struct|proc|keyword|fn)/
    -      },
    -      DEFINITION('proc keyword', ';'),
    -      DEFINITION('fn', '='),
    -      {
    -        beginKeywords: 'for threadfor',
    -        end: /;/,
    -        // end: /\(/,
    -        relevance: 0,
    -        contains: [
    -          hljs.C_BLOCK_COMMENT_MODE,
    -          AT_COMMENT_MODE,
    -          FUNCTION_REF_PARAMS
    -        ]
    -      },
    -      { // custom method guard
    -        // excludes method names from keyword processing
    -        variants: [
    -          {
    -            begin: hljs.UNDERSCORE_IDENT_RE + '\\.' + hljs.UNDERSCORE_IDENT_RE
    -          },
    -          {
    -            begin: hljs.UNDERSCORE_IDENT_RE + '\\s*='
    -          }
    -        ],
    -        relevance: 0
    -      },
    -      FUNCTION_REF,
    -      STRUCT_TYPE
    -    ]
    -  };
    -}
    -
    -module.exports = gauss;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/gcode.js b/claude-code-source/node_modules/highlight.js/lib/languages/gcode.js
    deleted file mode 100644
    index 0f5cbe25..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/gcode.js
    +++ /dev/null
    @@ -1,88 +0,0 @@
    -/*
    - Language: G-code (ISO 6983)
    - Contributors: Adam Joseph Cook 
    - Description: G-code syntax highlighter for Fanuc and other common CNC machine tool controls.
    - Website: https://www.sis.se/api/document/preview/911952/
    - */
    -
    -function gcode(hljs) {
    -  const GCODE_IDENT_RE = '[A-Z_][A-Z0-9_.]*';
    -  const GCODE_CLOSE_RE = '%';
    -  const GCODE_KEYWORDS = {
    -    $pattern: GCODE_IDENT_RE,
    -    keyword: 'IF DO WHILE ENDWHILE CALL ENDIF SUB ENDSUB GOTO REPEAT ENDREPEAT ' +
    -      'EQ LT GT NE GE LE OR XOR'
    -  };
    -  const GCODE_START = {
    -    className: 'meta',
    -    begin: '([O])([0-9]+)'
    -  };
    -  const NUMBER = hljs.inherit(hljs.C_NUMBER_MODE, {
    -    begin: '([-+]?((\\.\\d+)|(\\d+)(\\.\\d*)?))|' + hljs.C_NUMBER_RE
    -  });
    -  const GCODE_CODE = [
    -    hljs.C_LINE_COMMENT_MODE,
    -    hljs.C_BLOCK_COMMENT_MODE,
    -    hljs.COMMENT(/\(/, /\)/),
    -    NUMBER,
    -    hljs.inherit(hljs.APOS_STRING_MODE, {
    -      illegal: null
    -    }),
    -    hljs.inherit(hljs.QUOTE_STRING_MODE, {
    -      illegal: null
    -    }),
    -    {
    -      className: 'name',
    -      begin: '([G])([0-9]+\\.?[0-9]?)'
    -    },
    -    {
    -      className: 'name',
    -      begin: '([M])([0-9]+\\.?[0-9]?)'
    -    },
    -    {
    -      className: 'attr',
    -      begin: '(VC|VS|#)',
    -      end: '(\\d+)'
    -    },
    -    {
    -      className: 'attr',
    -      begin: '(VZOFX|VZOFY|VZOFZ)'
    -    },
    -    {
    -      className: 'built_in',
    -      begin: '(ATAN|ABS|ACOS|ASIN|SIN|COS|EXP|FIX|FUP|ROUND|LN|TAN)(\\[)',
    -      contains: [
    -        NUMBER
    -      ],
    -      end: '\\]'
    -    },
    -    {
    -      className: 'symbol',
    -      variants: [
    -        {
    -          begin: 'N',
    -          end: '\\d+',
    -          illegal: '\\W'
    -        }
    -      ]
    -    }
    -  ];
    -
    -  return {
    -    name: 'G-code (ISO 6983)',
    -    aliases: ['nc'],
    -    // Some implementations (CNC controls) of G-code are interoperable with uppercase and lowercase letters seamlessly.
    -    // However, most prefer all uppercase and uppercase is customary.
    -    case_insensitive: true,
    -    keywords: GCODE_KEYWORDS,
    -    contains: [
    -      {
    -        className: 'meta',
    -        begin: GCODE_CLOSE_RE
    -      },
    -      GCODE_START
    -    ].concat(GCODE_CODE)
    -  };
    -}
    -
    -module.exports = gcode;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/gherkin.js b/claude-code-source/node_modules/highlight.js/lib/languages/gherkin.js
    deleted file mode 100644
    index 2cae1e28..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/gherkin.js
    +++ /dev/null
    @@ -1,49 +0,0 @@
    -/*
    - Language: Gherkin
    - Author: Sam Pikesley (@pikesley) 
    - Description: Gherkin is the format for cucumber specifications. It is a domain specific language which helps you to describe business behavior without the need to go into detail of implementation.
    - Website: https://cucumber.io/docs/gherkin/
    - */
    -
    -function gherkin(hljs) {
    -  return {
    -    name: 'Gherkin',
    -    aliases: ['feature'],
    -    keywords: 'Feature Background Ability Business\ Need Scenario Scenarios Scenario\ Outline Scenario\ Template Examples Given And Then But When',
    -    contains: [
    -      {
    -        className: 'symbol',
    -        begin: '\\*',
    -        relevance: 0
    -      },
    -      {
    -        className: 'meta',
    -        begin: '@[^@\\s]+'
    -      },
    -      {
    -        begin: '\\|',
    -        end: '\\|\\w*$',
    -        contains: [
    -          {
    -            className: 'string',
    -            begin: '[^|]+'
    -          }
    -        ]
    -      },
    -      {
    -        className: 'variable',
    -        begin: '<',
    -        end: '>'
    -      },
    -      hljs.HASH_COMMENT_MODE,
    -      {
    -        className: 'string',
    -        begin: '"""',
    -        end: '"""'
    -      },
    -      hljs.QUOTE_STRING_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = gherkin;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/glsl.js b/claude-code-source/node_modules/highlight.js/lib/languages/glsl.js
    deleted file mode 100644
    index 4f52116a..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/glsl.js
    +++ /dev/null
    @@ -1,128 +0,0 @@
    -/*
    -Language: GLSL
    -Description: OpenGL Shading Language
    -Author: Sergey Tikhomirov 
    -Website: https://en.wikipedia.org/wiki/OpenGL_Shading_Language
    -Category: graphics
    -*/
    -
    -function glsl(hljs) {
    -  return {
    -    name: 'GLSL',
    -    keywords: {
    -      keyword:
    -        // Statements
    -        'break continue discard do else for if return while switch case default ' +
    -        // Qualifiers
    -        'attribute binding buffer ccw centroid centroid varying coherent column_major const cw ' +
    -        'depth_any depth_greater depth_less depth_unchanged early_fragment_tests equal_spacing ' +
    -        'flat fractional_even_spacing fractional_odd_spacing highp in index inout invariant ' +
    -        'invocations isolines layout line_strip lines lines_adjacency local_size_x local_size_y ' +
    -        'local_size_z location lowp max_vertices mediump noperspective offset origin_upper_left ' +
    -        'out packed patch pixel_center_integer point_mode points precise precision quads r11f_g11f_b10f ' +
    -        'r16 r16_snorm r16f r16i r16ui r32f r32i r32ui r8 r8_snorm r8i r8ui readonly restrict ' +
    -        'rg16 rg16_snorm rg16f rg16i rg16ui rg32f rg32i rg32ui rg8 rg8_snorm rg8i rg8ui rgb10_a2 ' +
    -        'rgb10_a2ui rgba16 rgba16_snorm rgba16f rgba16i rgba16ui rgba32f rgba32i rgba32ui rgba8 ' +
    -        'rgba8_snorm rgba8i rgba8ui row_major sample shared smooth std140 std430 stream triangle_strip ' +
    -        'triangles triangles_adjacency uniform varying vertices volatile writeonly',
    -      type:
    -        'atomic_uint bool bvec2 bvec3 bvec4 dmat2 dmat2x2 dmat2x3 dmat2x4 dmat3 dmat3x2 dmat3x3 ' +
    -        'dmat3x4 dmat4 dmat4x2 dmat4x3 dmat4x4 double dvec2 dvec3 dvec4 float iimage1D iimage1DArray ' +
    -        'iimage2D iimage2DArray iimage2DMS iimage2DMSArray iimage2DRect iimage3D iimageBuffer ' +
    -        'iimageCube iimageCubeArray image1D image1DArray image2D image2DArray image2DMS image2DMSArray ' +
    -        'image2DRect image3D imageBuffer imageCube imageCubeArray int isampler1D isampler1DArray ' +
    -        'isampler2D isampler2DArray isampler2DMS isampler2DMSArray isampler2DRect isampler3D ' +
    -        'isamplerBuffer isamplerCube isamplerCubeArray ivec2 ivec3 ivec4 mat2 mat2x2 mat2x3 ' +
    -        'mat2x4 mat3 mat3x2 mat3x3 mat3x4 mat4 mat4x2 mat4x3 mat4x4 sampler1D sampler1DArray ' +
    -        'sampler1DArrayShadow sampler1DShadow sampler2D sampler2DArray sampler2DArrayShadow ' +
    -        'sampler2DMS sampler2DMSArray sampler2DRect sampler2DRectShadow sampler2DShadow sampler3D ' +
    -        'samplerBuffer samplerCube samplerCubeArray samplerCubeArrayShadow samplerCubeShadow ' +
    -        'image1D uimage1DArray uimage2D uimage2DArray uimage2DMS uimage2DMSArray uimage2DRect ' +
    -        'uimage3D uimageBuffer uimageCube uimageCubeArray uint usampler1D usampler1DArray ' +
    -        'usampler2D usampler2DArray usampler2DMS usampler2DMSArray usampler2DRect usampler3D ' +
    -        'samplerBuffer usamplerCube usamplerCubeArray uvec2 uvec3 uvec4 vec2 vec3 vec4 void',
    -      built_in:
    -        // Constants
    -        'gl_MaxAtomicCounterBindings gl_MaxAtomicCounterBufferSize gl_MaxClipDistances gl_MaxClipPlanes ' +
    -        'gl_MaxCombinedAtomicCounterBuffers gl_MaxCombinedAtomicCounters gl_MaxCombinedImageUniforms ' +
    -        'gl_MaxCombinedImageUnitsAndFragmentOutputs gl_MaxCombinedTextureImageUnits gl_MaxComputeAtomicCounterBuffers ' +
    -        'gl_MaxComputeAtomicCounters gl_MaxComputeImageUniforms gl_MaxComputeTextureImageUnits ' +
    -        'gl_MaxComputeUniformComponents gl_MaxComputeWorkGroupCount gl_MaxComputeWorkGroupSize ' +
    -        'gl_MaxDrawBuffers gl_MaxFragmentAtomicCounterBuffers gl_MaxFragmentAtomicCounters ' +
    -        'gl_MaxFragmentImageUniforms gl_MaxFragmentInputComponents gl_MaxFragmentInputVectors ' +
    -        'gl_MaxFragmentUniformComponents gl_MaxFragmentUniformVectors gl_MaxGeometryAtomicCounterBuffers ' +
    -        'gl_MaxGeometryAtomicCounters gl_MaxGeometryImageUniforms gl_MaxGeometryInputComponents ' +
    -        'gl_MaxGeometryOutputComponents gl_MaxGeometryOutputVertices gl_MaxGeometryTextureImageUnits ' +
    -        'gl_MaxGeometryTotalOutputComponents gl_MaxGeometryUniformComponents gl_MaxGeometryVaryingComponents ' +
    -        'gl_MaxImageSamples gl_MaxImageUnits gl_MaxLights gl_MaxPatchVertices gl_MaxProgramTexelOffset ' +
    -        'gl_MaxTessControlAtomicCounterBuffers gl_MaxTessControlAtomicCounters gl_MaxTessControlImageUniforms ' +
    -        'gl_MaxTessControlInputComponents gl_MaxTessControlOutputComponents gl_MaxTessControlTextureImageUnits ' +
    -        'gl_MaxTessControlTotalOutputComponents gl_MaxTessControlUniformComponents ' +
    -        'gl_MaxTessEvaluationAtomicCounterBuffers gl_MaxTessEvaluationAtomicCounters ' +
    -        'gl_MaxTessEvaluationImageUniforms gl_MaxTessEvaluationInputComponents gl_MaxTessEvaluationOutputComponents ' +
    -        'gl_MaxTessEvaluationTextureImageUnits gl_MaxTessEvaluationUniformComponents ' +
    -        'gl_MaxTessGenLevel gl_MaxTessPatchComponents gl_MaxTextureCoords gl_MaxTextureImageUnits ' +
    -        'gl_MaxTextureUnits gl_MaxVaryingComponents gl_MaxVaryingFloats gl_MaxVaryingVectors ' +
    -        'gl_MaxVertexAtomicCounterBuffers gl_MaxVertexAtomicCounters gl_MaxVertexAttribs gl_MaxVertexImageUniforms ' +
    -        'gl_MaxVertexOutputComponents gl_MaxVertexOutputVectors gl_MaxVertexTextureImageUnits ' +
    -        'gl_MaxVertexUniformComponents gl_MaxVertexUniformVectors gl_MaxViewports gl_MinProgramTexelOffset ' +
    -        // Variables
    -        'gl_BackColor gl_BackLightModelProduct gl_BackLightProduct gl_BackMaterial ' +
    -        'gl_BackSecondaryColor gl_ClipDistance gl_ClipPlane gl_ClipVertex gl_Color ' +
    -        'gl_DepthRange gl_EyePlaneQ gl_EyePlaneR gl_EyePlaneS gl_EyePlaneT gl_Fog gl_FogCoord ' +
    -        'gl_FogFragCoord gl_FragColor gl_FragCoord gl_FragData gl_FragDepth gl_FrontColor ' +
    -        'gl_FrontFacing gl_FrontLightModelProduct gl_FrontLightProduct gl_FrontMaterial ' +
    -        'gl_FrontSecondaryColor gl_GlobalInvocationID gl_InstanceID gl_InvocationID gl_Layer gl_LightModel ' +
    -        'gl_LightSource gl_LocalInvocationID gl_LocalInvocationIndex gl_ModelViewMatrix ' +
    -        'gl_ModelViewMatrixInverse gl_ModelViewMatrixInverseTranspose gl_ModelViewMatrixTranspose ' +
    -        'gl_ModelViewProjectionMatrix gl_ModelViewProjectionMatrixInverse gl_ModelViewProjectionMatrixInverseTranspose ' +
    -        'gl_ModelViewProjectionMatrixTranspose gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 ' +
    -        'gl_MultiTexCoord3 gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 ' +
    -        'gl_Normal gl_NormalMatrix gl_NormalScale gl_NumSamples gl_NumWorkGroups gl_ObjectPlaneQ ' +
    -        'gl_ObjectPlaneR gl_ObjectPlaneS gl_ObjectPlaneT gl_PatchVerticesIn gl_Point gl_PointCoord ' +
    -        'gl_PointSize gl_Position gl_PrimitiveID gl_PrimitiveIDIn gl_ProjectionMatrix gl_ProjectionMatrixInverse ' +
    -        'gl_ProjectionMatrixInverseTranspose gl_ProjectionMatrixTranspose gl_SampleID gl_SampleMask ' +
    -        'gl_SampleMaskIn gl_SamplePosition gl_SecondaryColor gl_TessCoord gl_TessLevelInner gl_TessLevelOuter ' +
    -        'gl_TexCoord gl_TextureEnvColor gl_TextureMatrix gl_TextureMatrixInverse gl_TextureMatrixInverseTranspose ' +
    -        'gl_TextureMatrixTranspose gl_Vertex gl_VertexID gl_ViewportIndex gl_WorkGroupID gl_WorkGroupSize gl_in gl_out ' +
    -        // Functions
    -        'EmitStreamVertex EmitVertex EndPrimitive EndStreamPrimitive abs acos acosh all any asin ' +
    -        'asinh atan atanh atomicAdd atomicAnd atomicCompSwap atomicCounter atomicCounterDecrement ' +
    -        'atomicCounterIncrement atomicExchange atomicMax atomicMin atomicOr atomicXor barrier ' +
    -        'bitCount bitfieldExtract bitfieldInsert bitfieldReverse ceil clamp cos cosh cross ' +
    -        'dFdx dFdy degrees determinant distance dot equal exp exp2 faceforward findLSB findMSB ' +
    -        'floatBitsToInt floatBitsToUint floor fma fract frexp ftransform fwidth greaterThan ' +
    -        'greaterThanEqual groupMemoryBarrier imageAtomicAdd imageAtomicAnd imageAtomicCompSwap ' +
    -        'imageAtomicExchange imageAtomicMax imageAtomicMin imageAtomicOr imageAtomicXor imageLoad ' +
    -        'imageSize imageStore imulExtended intBitsToFloat interpolateAtCentroid interpolateAtOffset ' +
    -        'interpolateAtSample inverse inversesqrt isinf isnan ldexp length lessThan lessThanEqual log ' +
    -        'log2 matrixCompMult max memoryBarrier memoryBarrierAtomicCounter memoryBarrierBuffer ' +
    -        'memoryBarrierImage memoryBarrierShared min mix mod modf noise1 noise2 noise3 noise4 ' +
    -        'normalize not notEqual outerProduct packDouble2x32 packHalf2x16 packSnorm2x16 packSnorm4x8 ' +
    -        'packUnorm2x16 packUnorm4x8 pow radians reflect refract round roundEven shadow1D shadow1DLod ' +
    -        'shadow1DProj shadow1DProjLod shadow2D shadow2DLod shadow2DProj shadow2DProjLod sign sin sinh ' +
    -        'smoothstep sqrt step tan tanh texelFetch texelFetchOffset texture texture1D texture1DLod ' +
    -        'texture1DProj texture1DProjLod texture2D texture2DLod texture2DProj texture2DProjLod ' +
    -        'texture3D texture3DLod texture3DProj texture3DProjLod textureCube textureCubeLod ' +
    -        'textureGather textureGatherOffset textureGatherOffsets textureGrad textureGradOffset ' +
    -        'textureLod textureLodOffset textureOffset textureProj textureProjGrad textureProjGradOffset ' +
    -        'textureProjLod textureProjLodOffset textureProjOffset textureQueryLevels textureQueryLod ' +
    -        'textureSize transpose trunc uaddCarry uintBitsToFloat umulExtended unpackDouble2x32 ' +
    -        'unpackHalf2x16 unpackSnorm2x16 unpackSnorm4x8 unpackUnorm2x16 unpackUnorm4x8 usubBorrow',
    -      literal: 'true false'
    -    },
    -    illegal: '"',
    -    contains: [
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.C_NUMBER_MODE,
    -      {
    -        className: 'meta',
    -        begin: '#',
    -        end: '$'
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = glsl;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/gml.js b/claude-code-source/node_modules/highlight.js/lib/languages/gml.js
    deleted file mode 100644
    index 52b01877..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/gml.js
    +++ /dev/null
    @@ -1,885 +0,0 @@
    -/*
    -Language: GML
    -Author: Meseta 
    -Description: Game Maker Language for GameMaker Studio 2
    -Website: https://docs2.yoyogames.com
    -Category: scripting
    -*/
    -
    -function gml(hljs) {
    -  const GML_KEYWORDS = {
    -    keyword: 'begin end if then else while do for break continue with until ' +
    -      'repeat exit and or xor not return mod div switch case default var ' +
    -      'globalvar enum function constructor delete #macro #region #endregion',
    -    built_in: 'is_real is_string is_array is_undefined is_int32 is_int64 is_ptr ' +
    -      'is_vec3 is_vec4 is_matrix is_bool is_method is_struct is_infinity is_nan ' +
    -      'is_numeric typeof variable_global_exists variable_global_get variable_global_set ' +
    -      'variable_instance_exists variable_instance_get variable_instance_set ' +
    -      'variable_instance_get_names variable_struct_exists variable_struct_get ' +
    -      'variable_struct_get_names variable_struct_names_count variable_struct_remove ' +
    -      'variable_struct_set array_delete array_insert array_length array_length_1d ' +
    -      'array_length_2d array_height_2d array_equals array_create ' +
    -      'array_copy array_pop array_push array_resize array_sort ' +
    -      'random random_range irandom irandom_range random_set_seed random_get_seed ' +
    -      'randomize randomise choose abs round floor ceil sign frac sqrt sqr ' +
    -      'exp ln log2 log10 sin cos tan arcsin arccos arctan arctan2 dsin dcos ' +
    -      'dtan darcsin darccos darctan darctan2 degtorad radtodeg power logn ' +
    -      'min max mean median clamp lerp dot_product dot_product_3d ' +
    -      'dot_product_normalised dot_product_3d_normalised ' +
    -      'dot_product_normalized dot_product_3d_normalized math_set_epsilon ' +
    -      'math_get_epsilon angle_difference point_distance_3d point_distance ' +
    -      'point_direction lengthdir_x lengthdir_y real string int64 ptr ' +
    -      'string_format chr ansi_char ord string_length string_byte_length ' +
    -      'string_pos string_copy string_char_at string_ord_at string_byte_at ' +
    -      'string_set_byte_at string_delete string_insert string_lower ' +
    -      'string_upper string_repeat string_letters string_digits ' +
    -      'string_lettersdigits string_replace string_replace_all string_count ' +
    -      'string_hash_to_newline clipboard_has_text clipboard_set_text ' +
    -      'clipboard_get_text date_current_datetime date_create_datetime ' +
    -      'date_valid_datetime date_inc_year date_inc_month date_inc_week ' +
    -      'date_inc_day date_inc_hour date_inc_minute date_inc_second ' +
    -      'date_get_year date_get_month date_get_week date_get_day ' +
    -      'date_get_hour date_get_minute date_get_second date_get_weekday ' +
    -      'date_get_day_of_year date_get_hour_of_year date_get_minute_of_year ' +
    -      'date_get_second_of_year date_year_span date_month_span ' +
    -      'date_week_span date_day_span date_hour_span date_minute_span ' +
    -      'date_second_span date_compare_datetime date_compare_date ' +
    -      'date_compare_time date_date_of date_time_of date_datetime_string ' +
    -      'date_date_string date_time_string date_days_in_month ' +
    -      'date_days_in_year date_leap_year date_is_today date_set_timezone ' +
    -      'date_get_timezone game_set_speed game_get_speed motion_set ' +
    -      'motion_add place_free place_empty place_meeting place_snapped ' +
    -      'move_random move_snap move_towards_point move_contact_solid ' +
    -      'move_contact_all move_outside_solid move_outside_all ' +
    -      'move_bounce_solid move_bounce_all move_wrap distance_to_point ' +
    -      'distance_to_object position_empty position_meeting path_start ' +
    -      'path_end mp_linear_step mp_potential_step mp_linear_step_object ' +
    -      'mp_potential_step_object mp_potential_settings mp_linear_path ' +
    -      'mp_potential_path mp_linear_path_object mp_potential_path_object ' +
    -      'mp_grid_create mp_grid_destroy mp_grid_clear_all mp_grid_clear_cell ' +
    -      'mp_grid_clear_rectangle mp_grid_add_cell mp_grid_get_cell ' +
    -      'mp_grid_add_rectangle mp_grid_add_instances mp_grid_path ' +
    -      'mp_grid_draw mp_grid_to_ds_grid collision_point collision_rectangle ' +
    -      'collision_circle collision_ellipse collision_line ' +
    -      'collision_point_list collision_rectangle_list collision_circle_list ' +
    -      'collision_ellipse_list collision_line_list instance_position_list ' +
    -      'instance_place_list point_in_rectangle ' +
    -      'point_in_triangle point_in_circle rectangle_in_rectangle ' +
    -      'rectangle_in_triangle rectangle_in_circle instance_find ' +
    -      'instance_exists instance_number instance_position instance_nearest ' +
    -      'instance_furthest instance_place instance_create_depth ' +
    -      'instance_create_layer instance_copy instance_change instance_destroy ' +
    -      'position_destroy position_change instance_id_get ' +
    -      'instance_deactivate_all instance_deactivate_object ' +
    -      'instance_deactivate_region instance_activate_all ' +
    -      'instance_activate_object instance_activate_region room_goto ' +
    -      'room_goto_previous room_goto_next room_previous room_next ' +
    -      'room_restart game_end game_restart game_load game_save ' +
    -      'game_save_buffer game_load_buffer event_perform event_user ' +
    -      'event_perform_object event_inherited show_debug_message ' +
    -      'show_debug_overlay debug_event debug_get_callstack alarm_get ' +
    -      'alarm_set font_texture_page_size keyboard_set_map keyboard_get_map ' +
    -      'keyboard_unset_map keyboard_check keyboard_check_pressed ' +
    -      'keyboard_check_released keyboard_check_direct keyboard_get_numlock ' +
    -      'keyboard_set_numlock keyboard_key_press keyboard_key_release ' +
    -      'keyboard_clear io_clear mouse_check_button ' +
    -      'mouse_check_button_pressed mouse_check_button_released ' +
    -      'mouse_wheel_up mouse_wheel_down mouse_clear draw_self draw_sprite ' +
    -      'draw_sprite_pos draw_sprite_ext draw_sprite_stretched ' +
    -      'draw_sprite_stretched_ext draw_sprite_tiled draw_sprite_tiled_ext ' +
    -      'draw_sprite_part draw_sprite_part_ext draw_sprite_general draw_clear ' +
    -      'draw_clear_alpha draw_point draw_line draw_line_width draw_rectangle ' +
    -      'draw_roundrect draw_roundrect_ext draw_triangle draw_circle ' +
    -      'draw_ellipse draw_set_circle_precision draw_arrow draw_button ' +
    -      'draw_path draw_healthbar draw_getpixel draw_getpixel_ext ' +
    -      'draw_set_colour draw_set_color draw_set_alpha draw_get_colour ' +
    -      'draw_get_color draw_get_alpha merge_colour make_colour_rgb ' +
    -      'make_colour_hsv colour_get_red colour_get_green colour_get_blue ' +
    -      'colour_get_hue colour_get_saturation colour_get_value merge_color ' +
    -      'make_color_rgb make_color_hsv color_get_red color_get_green ' +
    -      'color_get_blue color_get_hue color_get_saturation color_get_value ' +
    -      'merge_color screen_save screen_save_part draw_set_font ' +
    -      'draw_set_halign draw_set_valign draw_text draw_text_ext string_width ' +
    -      'string_height string_width_ext string_height_ext ' +
    -      'draw_text_transformed draw_text_ext_transformed draw_text_colour ' +
    -      'draw_text_ext_colour draw_text_transformed_colour ' +
    -      'draw_text_ext_transformed_colour draw_text_color draw_text_ext_color ' +
    -      'draw_text_transformed_color draw_text_ext_transformed_color ' +
    -      'draw_point_colour draw_line_colour draw_line_width_colour ' +
    -      'draw_rectangle_colour draw_roundrect_colour ' +
    -      'draw_roundrect_colour_ext draw_triangle_colour draw_circle_colour ' +
    -      'draw_ellipse_colour draw_point_color draw_line_color ' +
    -      'draw_line_width_color draw_rectangle_color draw_roundrect_color ' +
    -      'draw_roundrect_color_ext draw_triangle_color draw_circle_color ' +
    -      'draw_ellipse_color draw_primitive_begin draw_vertex ' +
    -      'draw_vertex_colour draw_vertex_color draw_primitive_end ' +
    -      'sprite_get_uvs font_get_uvs sprite_get_texture font_get_texture ' +
    -      'texture_get_width texture_get_height texture_get_uvs ' +
    -      'draw_primitive_begin_texture draw_vertex_texture ' +
    -      'draw_vertex_texture_colour draw_vertex_texture_color ' +
    -      'texture_global_scale surface_create surface_create_ext ' +
    -      'surface_resize surface_free surface_exists surface_get_width ' +
    -      'surface_get_height surface_get_texture surface_set_target ' +
    -      'surface_set_target_ext surface_reset_target surface_depth_disable ' +
    -      'surface_get_depth_disable draw_surface draw_surface_stretched ' +
    -      'draw_surface_tiled draw_surface_part draw_surface_ext ' +
    -      'draw_surface_stretched_ext draw_surface_tiled_ext ' +
    -      'draw_surface_part_ext draw_surface_general surface_getpixel ' +
    -      'surface_getpixel_ext surface_save surface_save_part surface_copy ' +
    -      'surface_copy_part application_surface_draw_enable ' +
    -      'application_get_position application_surface_enable ' +
    -      'application_surface_is_enabled display_get_width display_get_height ' +
    -      'display_get_orientation display_get_gui_width display_get_gui_height ' +
    -      'display_reset display_mouse_get_x display_mouse_get_y ' +
    -      'display_mouse_set display_set_ui_visibility ' +
    -      'window_set_fullscreen window_get_fullscreen ' +
    -      'window_set_caption window_set_min_width window_set_max_width ' +
    -      'window_set_min_height window_set_max_height window_get_visible_rects ' +
    -      'window_get_caption window_set_cursor window_get_cursor ' +
    -      'window_set_colour window_get_colour window_set_color ' +
    -      'window_get_color window_set_position window_set_size ' +
    -      'window_set_rectangle window_center window_get_x window_get_y ' +
    -      'window_get_width window_get_height window_mouse_get_x ' +
    -      'window_mouse_get_y window_mouse_set window_view_mouse_get_x ' +
    -      'window_view_mouse_get_y window_views_mouse_get_x ' +
    -      'window_views_mouse_get_y audio_listener_position ' +
    -      'audio_listener_velocity audio_listener_orientation ' +
    -      'audio_emitter_position audio_emitter_create audio_emitter_free ' +
    -      'audio_emitter_exists audio_emitter_pitch audio_emitter_velocity ' +
    -      'audio_emitter_falloff audio_emitter_gain audio_play_sound ' +
    -      'audio_play_sound_on audio_play_sound_at audio_stop_sound ' +
    -      'audio_resume_music audio_music_is_playing audio_resume_sound ' +
    -      'audio_pause_sound audio_pause_music audio_channel_num ' +
    -      'audio_sound_length audio_get_type audio_falloff_set_model ' +
    -      'audio_play_music audio_stop_music audio_master_gain audio_music_gain ' +
    -      'audio_sound_gain audio_sound_pitch audio_stop_all audio_resume_all ' +
    -      'audio_pause_all audio_is_playing audio_is_paused audio_exists ' +
    -      'audio_sound_set_track_position audio_sound_get_track_position ' +
    -      'audio_emitter_get_gain audio_emitter_get_pitch audio_emitter_get_x ' +
    -      'audio_emitter_get_y audio_emitter_get_z audio_emitter_get_vx ' +
    -      'audio_emitter_get_vy audio_emitter_get_vz ' +
    -      'audio_listener_set_position audio_listener_set_velocity ' +
    -      'audio_listener_set_orientation audio_listener_get_data ' +
    -      'audio_set_master_gain audio_get_master_gain audio_sound_get_gain ' +
    -      'audio_sound_get_pitch audio_get_name audio_sound_set_track_position ' +
    -      'audio_sound_get_track_position audio_create_stream ' +
    -      'audio_destroy_stream audio_create_sync_group ' +
    -      'audio_destroy_sync_group audio_play_in_sync_group ' +
    -      'audio_start_sync_group audio_stop_sync_group audio_pause_sync_group ' +
    -      'audio_resume_sync_group audio_sync_group_get_track_pos ' +
    -      'audio_sync_group_debug audio_sync_group_is_playing audio_debug ' +
    -      'audio_group_load audio_group_unload audio_group_is_loaded ' +
    -      'audio_group_load_progress audio_group_name audio_group_stop_all ' +
    -      'audio_group_set_gain audio_create_buffer_sound ' +
    -      'audio_free_buffer_sound audio_create_play_queue ' +
    -      'audio_free_play_queue audio_queue_sound audio_get_recorder_count ' +
    -      'audio_get_recorder_info audio_start_recording audio_stop_recording ' +
    -      'audio_sound_get_listener_mask audio_emitter_get_listener_mask ' +
    -      'audio_get_listener_mask audio_sound_set_listener_mask ' +
    -      'audio_emitter_set_listener_mask audio_set_listener_mask ' +
    -      'audio_get_listener_count audio_get_listener_info audio_system ' +
    -      'show_message show_message_async clickable_add clickable_add_ext ' +
    -      'clickable_change clickable_change_ext clickable_delete ' +
    -      'clickable_exists clickable_set_style show_question ' +
    -      'show_question_async get_integer get_string get_integer_async ' +
    -      'get_string_async get_login_async get_open_filename get_save_filename ' +
    -      'get_open_filename_ext get_save_filename_ext show_error ' +
    -      'highscore_clear highscore_add highscore_value highscore_name ' +
    -      'draw_highscore sprite_exists sprite_get_name sprite_get_number ' +
    -      'sprite_get_width sprite_get_height sprite_get_xoffset ' +
    -      'sprite_get_yoffset sprite_get_bbox_left sprite_get_bbox_right ' +
    -      'sprite_get_bbox_top sprite_get_bbox_bottom sprite_save ' +
    -      'sprite_save_strip sprite_set_cache_size sprite_set_cache_size_ext ' +
    -      'sprite_get_tpe sprite_prefetch sprite_prefetch_multi sprite_flush ' +
    -      'sprite_flush_multi sprite_set_speed sprite_get_speed_type ' +
    -      'sprite_get_speed font_exists font_get_name font_get_fontname ' +
    -      'font_get_bold font_get_italic font_get_first font_get_last ' +
    -      'font_get_size font_set_cache_size path_exists path_get_name ' +
    -      'path_get_length path_get_time path_get_kind path_get_closed ' +
    -      'path_get_precision path_get_number path_get_point_x path_get_point_y ' +
    -      'path_get_point_speed path_get_x path_get_y path_get_speed ' +
    -      'script_exists script_get_name timeline_add timeline_delete ' +
    -      'timeline_clear timeline_exists timeline_get_name ' +
    -      'timeline_moment_clear timeline_moment_add_script timeline_size ' +
    -      'timeline_max_moment object_exists object_get_name object_get_sprite ' +
    -      'object_get_solid object_get_visible object_get_persistent ' +
    -      'object_get_mask object_get_parent object_get_physics ' +
    -      'object_is_ancestor room_exists room_get_name sprite_set_offset ' +
    -      'sprite_duplicate sprite_assign sprite_merge sprite_add ' +
    -      'sprite_replace sprite_create_from_surface sprite_add_from_surface ' +
    -      'sprite_delete sprite_set_alpha_from_sprite sprite_collision_mask ' +
    -      'font_add_enable_aa font_add_get_enable_aa font_add font_add_sprite ' +
    -      'font_add_sprite_ext font_replace font_replace_sprite ' +
    -      'font_replace_sprite_ext font_delete path_set_kind path_set_closed ' +
    -      'path_set_precision path_add path_assign path_duplicate path_append ' +
    -      'path_delete path_add_point path_insert_point path_change_point ' +
    -      'path_delete_point path_clear_points path_reverse path_mirror ' +
    -      'path_flip path_rotate path_rescale path_shift script_execute ' +
    -      'object_set_sprite object_set_solid object_set_visible ' +
    -      'object_set_persistent object_set_mask room_set_width room_set_height ' +
    -      'room_set_persistent room_set_background_colour ' +
    -      'room_set_background_color room_set_view room_set_viewport ' +
    -      'room_get_viewport room_set_view_enabled room_add room_duplicate ' +
    -      'room_assign room_instance_add room_instance_clear room_get_camera ' +
    -      'room_set_camera asset_get_index asset_get_type ' +
    -      'file_text_open_from_string file_text_open_read file_text_open_write ' +
    -      'file_text_open_append file_text_close file_text_write_string ' +
    -      'file_text_write_real file_text_writeln file_text_read_string ' +
    -      'file_text_read_real file_text_readln file_text_eof file_text_eoln ' +
    -      'file_exists file_delete file_rename file_copy directory_exists ' +
    -      'directory_create directory_destroy file_find_first file_find_next ' +
    -      'file_find_close file_attributes filename_name filename_path ' +
    -      'filename_dir filename_drive filename_ext filename_change_ext ' +
    -      'file_bin_open file_bin_rewrite file_bin_close file_bin_position ' +
    -      'file_bin_size file_bin_seek file_bin_write_byte file_bin_read_byte ' +
    -      'parameter_count parameter_string environment_get_variable ' +
    -      'ini_open_from_string ini_open ini_close ini_read_string ' +
    -      'ini_read_real ini_write_string ini_write_real ini_key_exists ' +
    -      'ini_section_exists ini_key_delete ini_section_delete ' +
    -      'ds_set_precision ds_exists ds_stack_create ds_stack_destroy ' +
    -      'ds_stack_clear ds_stack_copy ds_stack_size ds_stack_empty ' +
    -      'ds_stack_push ds_stack_pop ds_stack_top ds_stack_write ds_stack_read ' +
    -      'ds_queue_create ds_queue_destroy ds_queue_clear ds_queue_copy ' +
    -      'ds_queue_size ds_queue_empty ds_queue_enqueue ds_queue_dequeue ' +
    -      'ds_queue_head ds_queue_tail ds_queue_write ds_queue_read ' +
    -      'ds_list_create ds_list_destroy ds_list_clear ds_list_copy ' +
    -      'ds_list_size ds_list_empty ds_list_add ds_list_insert ' +
    -      'ds_list_replace ds_list_delete ds_list_find_index ds_list_find_value ' +
    -      'ds_list_mark_as_list ds_list_mark_as_map ds_list_sort ' +
    -      'ds_list_shuffle ds_list_write ds_list_read ds_list_set ds_map_create ' +
    -      'ds_map_destroy ds_map_clear ds_map_copy ds_map_size ds_map_empty ' +
    -      'ds_map_add ds_map_add_list ds_map_add_map ds_map_replace ' +
    -      'ds_map_replace_map ds_map_replace_list ds_map_delete ds_map_exists ' +
    -      'ds_map_find_value ds_map_find_previous ds_map_find_next ' +
    -      'ds_map_find_first ds_map_find_last ds_map_write ds_map_read ' +
    -      'ds_map_secure_save ds_map_secure_load ds_map_secure_load_buffer ' +
    -      'ds_map_secure_save_buffer ds_map_set ds_priority_create ' +
    -      'ds_priority_destroy ds_priority_clear ds_priority_copy ' +
    -      'ds_priority_size ds_priority_empty ds_priority_add ' +
    -      'ds_priority_change_priority ds_priority_find_priority ' +
    -      'ds_priority_delete_value ds_priority_delete_min ds_priority_find_min ' +
    -      'ds_priority_delete_max ds_priority_find_max ds_priority_write ' +
    -      'ds_priority_read ds_grid_create ds_grid_destroy ds_grid_copy ' +
    -      'ds_grid_resize ds_grid_width ds_grid_height ds_grid_clear ' +
    -      'ds_grid_set ds_grid_add ds_grid_multiply ds_grid_set_region ' +
    -      'ds_grid_add_region ds_grid_multiply_region ds_grid_set_disk ' +
    -      'ds_grid_add_disk ds_grid_multiply_disk ds_grid_set_grid_region ' +
    -      'ds_grid_add_grid_region ds_grid_multiply_grid_region ds_grid_get ' +
    -      'ds_grid_get_sum ds_grid_get_max ds_grid_get_min ds_grid_get_mean ' +
    -      'ds_grid_get_disk_sum ds_grid_get_disk_min ds_grid_get_disk_max ' +
    -      'ds_grid_get_disk_mean ds_grid_value_exists ds_grid_value_x ' +
    -      'ds_grid_value_y ds_grid_value_disk_exists ds_grid_value_disk_x ' +
    -      'ds_grid_value_disk_y ds_grid_shuffle ds_grid_write ds_grid_read ' +
    -      'ds_grid_sort ds_grid_set ds_grid_get effect_create_below ' +
    -      'effect_create_above effect_clear part_type_create part_type_destroy ' +
    -      'part_type_exists part_type_clear part_type_shape part_type_sprite ' +
    -      'part_type_size part_type_scale part_type_orientation part_type_life ' +
    -      'part_type_step part_type_death part_type_speed part_type_direction ' +
    -      'part_type_gravity part_type_colour1 part_type_colour2 ' +
    -      'part_type_colour3 part_type_colour_mix part_type_colour_rgb ' +
    -      'part_type_colour_hsv part_type_color1 part_type_color2 ' +
    -      'part_type_color3 part_type_color_mix part_type_color_rgb ' +
    -      'part_type_color_hsv part_type_alpha1 part_type_alpha2 ' +
    -      'part_type_alpha3 part_type_blend part_system_create ' +
    -      'part_system_create_layer part_system_destroy part_system_exists ' +
    -      'part_system_clear part_system_draw_order part_system_depth ' +
    -      'part_system_position part_system_automatic_update ' +
    -      'part_system_automatic_draw part_system_update part_system_drawit ' +
    -      'part_system_get_layer part_system_layer part_particles_create ' +
    -      'part_particles_create_colour part_particles_create_color ' +
    -      'part_particles_clear part_particles_count part_emitter_create ' +
    -      'part_emitter_destroy part_emitter_destroy_all part_emitter_exists ' +
    -      'part_emitter_clear part_emitter_region part_emitter_burst ' +
    -      'part_emitter_stream external_call external_define external_free ' +
    -      'window_handle window_device matrix_get matrix_set ' +
    -      'matrix_build_identity matrix_build matrix_build_lookat ' +
    -      'matrix_build_projection_ortho matrix_build_projection_perspective ' +
    -      'matrix_build_projection_perspective_fov matrix_multiply ' +
    -      'matrix_transform_vertex matrix_stack_push matrix_stack_pop ' +
    -      'matrix_stack_multiply matrix_stack_set matrix_stack_clear ' +
    -      'matrix_stack_top matrix_stack_is_empty browser_input_capture ' +
    -      'os_get_config os_get_info os_get_language os_get_region ' +
    -      'os_lock_orientation display_get_dpi_x display_get_dpi_y ' +
    -      'display_set_gui_size display_set_gui_maximise ' +
    -      'display_set_gui_maximize device_mouse_dbclick_enable ' +
    -      'display_set_timing_method display_get_timing_method ' +
    -      'display_set_sleep_margin display_get_sleep_margin virtual_key_add ' +
    -      'virtual_key_hide virtual_key_delete virtual_key_show ' +
    -      'draw_enable_drawevent draw_enable_swf_aa draw_set_swf_aa_level ' +
    -      'draw_get_swf_aa_level draw_texture_flush draw_flush ' +
    -      'gpu_set_blendenable gpu_set_ztestenable gpu_set_zfunc ' +
    -      'gpu_set_zwriteenable gpu_set_lightingenable gpu_set_fog ' +
    -      'gpu_set_cullmode gpu_set_blendmode gpu_set_blendmode_ext ' +
    -      'gpu_set_blendmode_ext_sepalpha gpu_set_colorwriteenable ' +
    -      'gpu_set_colourwriteenable gpu_set_alphatestenable ' +
    -      'gpu_set_alphatestref gpu_set_alphatestfunc gpu_set_texfilter ' +
    -      'gpu_set_texfilter_ext gpu_set_texrepeat gpu_set_texrepeat_ext ' +
    -      'gpu_set_tex_filter gpu_set_tex_filter_ext gpu_set_tex_repeat ' +
    -      'gpu_set_tex_repeat_ext gpu_set_tex_mip_filter ' +
    -      'gpu_set_tex_mip_filter_ext gpu_set_tex_mip_bias ' +
    -      'gpu_set_tex_mip_bias_ext gpu_set_tex_min_mip gpu_set_tex_min_mip_ext ' +
    -      'gpu_set_tex_max_mip gpu_set_tex_max_mip_ext gpu_set_tex_max_aniso ' +
    -      'gpu_set_tex_max_aniso_ext gpu_set_tex_mip_enable ' +
    -      'gpu_set_tex_mip_enable_ext gpu_get_blendenable gpu_get_ztestenable ' +
    -      'gpu_get_zfunc gpu_get_zwriteenable gpu_get_lightingenable ' +
    -      'gpu_get_fog gpu_get_cullmode gpu_get_blendmode gpu_get_blendmode_ext ' +
    -      'gpu_get_blendmode_ext_sepalpha gpu_get_blendmode_src ' +
    -      'gpu_get_blendmode_dest gpu_get_blendmode_srcalpha ' +
    -      'gpu_get_blendmode_destalpha gpu_get_colorwriteenable ' +
    -      'gpu_get_colourwriteenable gpu_get_alphatestenable ' +
    -      'gpu_get_alphatestref gpu_get_alphatestfunc gpu_get_texfilter ' +
    -      'gpu_get_texfilter_ext gpu_get_texrepeat gpu_get_texrepeat_ext ' +
    -      'gpu_get_tex_filter gpu_get_tex_filter_ext gpu_get_tex_repeat ' +
    -      'gpu_get_tex_repeat_ext gpu_get_tex_mip_filter ' +
    -      'gpu_get_tex_mip_filter_ext gpu_get_tex_mip_bias ' +
    -      'gpu_get_tex_mip_bias_ext gpu_get_tex_min_mip gpu_get_tex_min_mip_ext ' +
    -      'gpu_get_tex_max_mip gpu_get_tex_max_mip_ext gpu_get_tex_max_aniso ' +
    -      'gpu_get_tex_max_aniso_ext gpu_get_tex_mip_enable ' +
    -      'gpu_get_tex_mip_enable_ext gpu_push_state gpu_pop_state ' +
    -      'gpu_get_state gpu_set_state draw_light_define_ambient ' +
    -      'draw_light_define_direction draw_light_define_point ' +
    -      'draw_light_enable draw_set_lighting draw_light_get_ambient ' +
    -      'draw_light_get draw_get_lighting shop_leave_rating url_get_domain ' +
    -      'url_open url_open_ext url_open_full get_timer achievement_login ' +
    -      'achievement_logout achievement_post achievement_increment ' +
    -      'achievement_post_score achievement_available ' +
    -      'achievement_show_achievements achievement_show_leaderboards ' +
    -      'achievement_load_friends achievement_load_leaderboard ' +
    -      'achievement_send_challenge achievement_load_progress ' +
    -      'achievement_reset achievement_login_status achievement_get_pic ' +
    -      'achievement_show_challenge_notifications achievement_get_challenges ' +
    -      'achievement_event achievement_show achievement_get_info ' +
    -      'cloud_file_save cloud_string_save cloud_synchronise ads_enable ' +
    -      'ads_disable ads_setup ads_engagement_launch ads_engagement_available ' +
    -      'ads_engagement_active ads_event ads_event_preload ' +
    -      'ads_set_reward_callback ads_get_display_height ads_get_display_width ' +
    -      'ads_move ads_interstitial_available ads_interstitial_display ' +
    -      'device_get_tilt_x device_get_tilt_y device_get_tilt_z ' +
    -      'device_is_keypad_open device_mouse_check_button ' +
    -      'device_mouse_check_button_pressed device_mouse_check_button_released ' +
    -      'device_mouse_x device_mouse_y device_mouse_raw_x device_mouse_raw_y ' +
    -      'device_mouse_x_to_gui device_mouse_y_to_gui iap_activate iap_status ' +
    -      'iap_enumerate_products iap_restore_all iap_acquire iap_consume ' +
    -      'iap_product_details iap_purchase_details facebook_init ' +
    -      'facebook_login facebook_status facebook_graph_request ' +
    -      'facebook_dialog facebook_logout facebook_launch_offerwall ' +
    -      'facebook_post_message facebook_send_invite facebook_user_id ' +
    -      'facebook_accesstoken facebook_check_permission ' +
    -      'facebook_request_read_permissions ' +
    -      'facebook_request_publish_permissions gamepad_is_supported ' +
    -      'gamepad_get_device_count gamepad_is_connected ' +
    -      'gamepad_get_description gamepad_get_button_threshold ' +
    -      'gamepad_set_button_threshold gamepad_get_axis_deadzone ' +
    -      'gamepad_set_axis_deadzone gamepad_button_count gamepad_button_check ' +
    -      'gamepad_button_check_pressed gamepad_button_check_released ' +
    -      'gamepad_button_value gamepad_axis_count gamepad_axis_value ' +
    -      'gamepad_set_vibration gamepad_set_colour gamepad_set_color ' +
    -      'os_is_paused window_has_focus code_is_compiled http_get ' +
    -      'http_get_file http_post_string http_request json_encode json_decode ' +
    -      'zip_unzip load_csv base64_encode base64_decode md5_string_unicode ' +
    -      'md5_string_utf8 md5_file os_is_network_connected sha1_string_unicode ' +
    -      'sha1_string_utf8 sha1_file os_powersave_enable analytics_event ' +
    -      'analytics_event_ext win8_livetile_tile_notification ' +
    -      'win8_livetile_tile_clear win8_livetile_badge_notification ' +
    -      'win8_livetile_badge_clear win8_livetile_queue_enable ' +
    -      'win8_secondarytile_pin win8_secondarytile_badge_notification ' +
    -      'win8_secondarytile_delete win8_livetile_notification_begin ' +
    -      'win8_livetile_notification_secondary_begin ' +
    -      'win8_livetile_notification_expiry win8_livetile_notification_tag ' +
    -      'win8_livetile_notification_text_add ' +
    -      'win8_livetile_notification_image_add win8_livetile_notification_end ' +
    -      'win8_appbar_enable win8_appbar_add_element ' +
    -      'win8_appbar_remove_element win8_settingscharm_add_entry ' +
    -      'win8_settingscharm_add_html_entry win8_settingscharm_add_xaml_entry ' +
    -      'win8_settingscharm_set_xaml_property ' +
    -      'win8_settingscharm_get_xaml_property win8_settingscharm_remove_entry ' +
    -      'win8_share_image win8_share_screenshot win8_share_file ' +
    -      'win8_share_url win8_share_text win8_search_enable ' +
    -      'win8_search_disable win8_search_add_suggestions ' +
    -      'win8_device_touchscreen_available win8_license_initialize_sandbox ' +
    -      'win8_license_trial_version winphone_license_trial_version ' +
    -      'winphone_tile_title winphone_tile_count winphone_tile_back_title ' +
    -      'winphone_tile_back_content winphone_tile_back_content_wide ' +
    -      'winphone_tile_front_image winphone_tile_front_image_small ' +
    -      'winphone_tile_front_image_wide winphone_tile_back_image ' +
    -      'winphone_tile_back_image_wide winphone_tile_background_colour ' +
    -      'winphone_tile_background_color winphone_tile_icon_image ' +
    -      'winphone_tile_small_icon_image winphone_tile_wide_content ' +
    -      'winphone_tile_cycle_images winphone_tile_small_background_image ' +
    -      'physics_world_create physics_world_gravity ' +
    -      'physics_world_update_speed physics_world_update_iterations ' +
    -      'physics_world_draw_debug physics_pause_enable physics_fixture_create ' +
    -      'physics_fixture_set_kinematic physics_fixture_set_density ' +
    -      'physics_fixture_set_awake physics_fixture_set_restitution ' +
    -      'physics_fixture_set_friction physics_fixture_set_collision_group ' +
    -      'physics_fixture_set_sensor physics_fixture_set_linear_damping ' +
    -      'physics_fixture_set_angular_damping physics_fixture_set_circle_shape ' +
    -      'physics_fixture_set_box_shape physics_fixture_set_edge_shape ' +
    -      'physics_fixture_set_polygon_shape physics_fixture_set_chain_shape ' +
    -      'physics_fixture_add_point physics_fixture_bind ' +
    -      'physics_fixture_bind_ext physics_fixture_delete physics_apply_force ' +
    -      'physics_apply_impulse physics_apply_angular_impulse ' +
    -      'physics_apply_local_force physics_apply_local_impulse ' +
    -      'physics_apply_torque physics_mass_properties physics_draw_debug ' +
    -      'physics_test_overlap physics_remove_fixture physics_set_friction ' +
    -      'physics_set_density physics_set_restitution physics_get_friction ' +
    -      'physics_get_density physics_get_restitution ' +
    -      'physics_joint_distance_create physics_joint_rope_create ' +
    -      'physics_joint_revolute_create physics_joint_prismatic_create ' +
    -      'physics_joint_pulley_create physics_joint_wheel_create ' +
    -      'physics_joint_weld_create physics_joint_friction_create ' +
    -      'physics_joint_gear_create physics_joint_enable_motor ' +
    -      'physics_joint_get_value physics_joint_set_value physics_joint_delete ' +
    -      'physics_particle_create physics_particle_delete ' +
    -      'physics_particle_delete_region_circle ' +
    -      'physics_particle_delete_region_box ' +
    -      'physics_particle_delete_region_poly physics_particle_set_flags ' +
    -      'physics_particle_set_category_flags physics_particle_draw ' +
    -      'physics_particle_draw_ext physics_particle_count ' +
    -      'physics_particle_get_data physics_particle_get_data_particle ' +
    -      'physics_particle_group_begin physics_particle_group_circle ' +
    -      'physics_particle_group_box physics_particle_group_polygon ' +
    -      'physics_particle_group_add_point physics_particle_group_end ' +
    -      'physics_particle_group_join physics_particle_group_delete ' +
    -      'physics_particle_group_count physics_particle_group_get_data ' +
    -      'physics_particle_group_get_mass physics_particle_group_get_inertia ' +
    -      'physics_particle_group_get_centre_x ' +
    -      'physics_particle_group_get_centre_y physics_particle_group_get_vel_x ' +
    -      'physics_particle_group_get_vel_y physics_particle_group_get_ang_vel ' +
    -      'physics_particle_group_get_x physics_particle_group_get_y ' +
    -      'physics_particle_group_get_angle physics_particle_set_group_flags ' +
    -      'physics_particle_get_group_flags physics_particle_get_max_count ' +
    -      'physics_particle_get_radius physics_particle_get_density ' +
    -      'physics_particle_get_damping physics_particle_get_gravity_scale ' +
    -      'physics_particle_set_max_count physics_particle_set_radius ' +
    -      'physics_particle_set_density physics_particle_set_damping ' +
    -      'physics_particle_set_gravity_scale network_create_socket ' +
    -      'network_create_socket_ext network_create_server ' +
    -      'network_create_server_raw network_connect network_connect_raw ' +
    -      'network_send_packet network_send_raw network_send_broadcast ' +
    -      'network_send_udp network_send_udp_raw network_set_timeout ' +
    -      'network_set_config network_resolve network_destroy buffer_create ' +
    -      'buffer_write buffer_read buffer_seek buffer_get_surface ' +
    -      'buffer_set_surface buffer_delete buffer_exists buffer_get_type ' +
    -      'buffer_get_alignment buffer_poke buffer_peek buffer_save ' +
    -      'buffer_save_ext buffer_load buffer_load_ext buffer_load_partial ' +
    -      'buffer_copy buffer_fill buffer_get_size buffer_tell buffer_resize ' +
    -      'buffer_md5 buffer_sha1 buffer_base64_encode buffer_base64_decode ' +
    -      'buffer_base64_decode_ext buffer_sizeof buffer_get_address ' +
    -      'buffer_create_from_vertex_buffer ' +
    -      'buffer_create_from_vertex_buffer_ext buffer_copy_from_vertex_buffer ' +
    -      'buffer_async_group_begin buffer_async_group_option ' +
    -      'buffer_async_group_end buffer_load_async buffer_save_async ' +
    -      'gml_release_mode gml_pragma steam_activate_overlay ' +
    -      'steam_is_overlay_enabled steam_is_overlay_activated ' +
    -      'steam_get_persona_name steam_initialised ' +
    -      'steam_is_cloud_enabled_for_app steam_is_cloud_enabled_for_account ' +
    -      'steam_file_persisted steam_get_quota_total steam_get_quota_free ' +
    -      'steam_file_write steam_file_write_file steam_file_read ' +
    -      'steam_file_delete steam_file_exists steam_file_size steam_file_share ' +
    -      'steam_is_screenshot_requested steam_send_screenshot ' +
    -      'steam_is_user_logged_on steam_get_user_steam_id steam_user_owns_dlc ' +
    -      'steam_user_installed_dlc steam_set_achievement steam_get_achievement ' +
    -      'steam_clear_achievement steam_set_stat_int steam_set_stat_float ' +
    -      'steam_set_stat_avg_rate steam_get_stat_int steam_get_stat_float ' +
    -      'steam_get_stat_avg_rate steam_reset_all_stats ' +
    -      'steam_reset_all_stats_achievements steam_stats_ready ' +
    -      'steam_create_leaderboard steam_upload_score steam_upload_score_ext ' +
    -      'steam_download_scores_around_user steam_download_scores ' +
    -      'steam_download_friends_scores steam_upload_score_buffer ' +
    -      'steam_upload_score_buffer_ext steam_current_game_language ' +
    -      'steam_available_languages steam_activate_overlay_browser ' +
    -      'steam_activate_overlay_user steam_activate_overlay_store ' +
    -      'steam_get_user_persona_name steam_get_app_id ' +
    -      'steam_get_user_account_id steam_ugc_download steam_ugc_create_item ' +
    -      'steam_ugc_start_item_update steam_ugc_set_item_title ' +
    -      'steam_ugc_set_item_description steam_ugc_set_item_visibility ' +
    -      'steam_ugc_set_item_tags steam_ugc_set_item_content ' +
    -      'steam_ugc_set_item_preview steam_ugc_submit_item_update ' +
    -      'steam_ugc_get_item_update_progress steam_ugc_subscribe_item ' +
    -      'steam_ugc_unsubscribe_item steam_ugc_num_subscribed_items ' +
    -      'steam_ugc_get_subscribed_items steam_ugc_get_item_install_info ' +
    -      'steam_ugc_get_item_update_info steam_ugc_request_item_details ' +
    -      'steam_ugc_create_query_user steam_ugc_create_query_user_ex ' +
    -      'steam_ugc_create_query_all steam_ugc_create_query_all_ex ' +
    -      'steam_ugc_query_set_cloud_filename_filter ' +
    -      'steam_ugc_query_set_match_any_tag steam_ugc_query_set_search_text ' +
    -      'steam_ugc_query_set_ranked_by_trend_days ' +
    -      'steam_ugc_query_add_required_tag steam_ugc_query_add_excluded_tag ' +
    -      'steam_ugc_query_set_return_long_description ' +
    -      'steam_ugc_query_set_return_total_only ' +
    -      'steam_ugc_query_set_allow_cached_response steam_ugc_send_query ' +
    -      'shader_set shader_get_name shader_reset shader_current ' +
    -      'shader_is_compiled shader_get_sampler_index shader_get_uniform ' +
    -      'shader_set_uniform_i shader_set_uniform_i_array shader_set_uniform_f ' +
    -      'shader_set_uniform_f_array shader_set_uniform_matrix ' +
    -      'shader_set_uniform_matrix_array shader_enable_corner_id ' +
    -      'texture_set_stage texture_get_texel_width texture_get_texel_height ' +
    -      'shaders_are_supported vertex_format_begin vertex_format_end ' +
    -      'vertex_format_delete vertex_format_add_position ' +
    -      'vertex_format_add_position_3d vertex_format_add_colour ' +
    -      'vertex_format_add_color vertex_format_add_normal ' +
    -      'vertex_format_add_texcoord vertex_format_add_textcoord ' +
    -      'vertex_format_add_custom vertex_create_buffer ' +
    -      'vertex_create_buffer_ext vertex_delete_buffer vertex_begin ' +
    -      'vertex_end vertex_position vertex_position_3d vertex_colour ' +
    -      'vertex_color vertex_argb vertex_texcoord vertex_normal vertex_float1 ' +
    -      'vertex_float2 vertex_float3 vertex_float4 vertex_ubyte4 ' +
    -      'vertex_submit vertex_freeze vertex_get_number vertex_get_buffer_size ' +
    -      'vertex_create_buffer_from_buffer ' +
    -      'vertex_create_buffer_from_buffer_ext push_local_notification ' +
    -      'push_get_first_local_notification push_get_next_local_notification ' +
    -      'push_cancel_local_notification skeleton_animation_set ' +
    -      'skeleton_animation_get skeleton_animation_mix ' +
    -      'skeleton_animation_set_ext skeleton_animation_get_ext ' +
    -      'skeleton_animation_get_duration skeleton_animation_get_frames ' +
    -      'skeleton_animation_clear skeleton_skin_set skeleton_skin_get ' +
    -      'skeleton_attachment_set skeleton_attachment_get ' +
    -      'skeleton_attachment_create skeleton_collision_draw_set ' +
    -      'skeleton_bone_data_get skeleton_bone_data_set ' +
    -      'skeleton_bone_state_get skeleton_bone_state_set skeleton_get_minmax ' +
    -      'skeleton_get_num_bounds skeleton_get_bounds ' +
    -      'skeleton_animation_get_frame skeleton_animation_set_frame ' +
    -      'draw_skeleton draw_skeleton_time draw_skeleton_instance ' +
    -      'draw_skeleton_collision skeleton_animation_list skeleton_skin_list ' +
    -      'skeleton_slot_data layer_get_id layer_get_id_at_depth ' +
    -      'layer_get_depth layer_create layer_destroy layer_destroy_instances ' +
    -      'layer_add_instance layer_has_instance layer_set_visible ' +
    -      'layer_get_visible layer_exists layer_x layer_y layer_get_x ' +
    -      'layer_get_y layer_hspeed layer_vspeed layer_get_hspeed ' +
    -      'layer_get_vspeed layer_script_begin layer_script_end layer_shader ' +
    -      'layer_get_script_begin layer_get_script_end layer_get_shader ' +
    -      'layer_set_target_room layer_get_target_room layer_reset_target_room ' +
    -      'layer_get_all layer_get_all_elements layer_get_name layer_depth ' +
    -      'layer_get_element_layer layer_get_element_type layer_element_move ' +
    -      'layer_force_draw_depth layer_is_draw_depth_forced ' +
    -      'layer_get_forced_depth layer_background_get_id ' +
    -      'layer_background_exists layer_background_create ' +
    -      'layer_background_destroy layer_background_visible ' +
    -      'layer_background_change layer_background_sprite ' +
    -      'layer_background_htiled layer_background_vtiled ' +
    -      'layer_background_stretch layer_background_yscale ' +
    -      'layer_background_xscale layer_background_blend ' +
    -      'layer_background_alpha layer_background_index layer_background_speed ' +
    -      'layer_background_get_visible layer_background_get_sprite ' +
    -      'layer_background_get_htiled layer_background_get_vtiled ' +
    -      'layer_background_get_stretch layer_background_get_yscale ' +
    -      'layer_background_get_xscale layer_background_get_blend ' +
    -      'layer_background_get_alpha layer_background_get_index ' +
    -      'layer_background_get_speed layer_sprite_get_id layer_sprite_exists ' +
    -      'layer_sprite_create layer_sprite_destroy layer_sprite_change ' +
    -      'layer_sprite_index layer_sprite_speed layer_sprite_xscale ' +
    -      'layer_sprite_yscale layer_sprite_angle layer_sprite_blend ' +
    -      'layer_sprite_alpha layer_sprite_x layer_sprite_y ' +
    -      'layer_sprite_get_sprite layer_sprite_get_index ' +
    -      'layer_sprite_get_speed layer_sprite_get_xscale ' +
    -      'layer_sprite_get_yscale layer_sprite_get_angle ' +
    -      'layer_sprite_get_blend layer_sprite_get_alpha layer_sprite_get_x ' +
    -      'layer_sprite_get_y layer_tilemap_get_id layer_tilemap_exists ' +
    -      'layer_tilemap_create layer_tilemap_destroy tilemap_tileset tilemap_x ' +
    -      'tilemap_y tilemap_set tilemap_set_at_pixel tilemap_get_tileset ' +
    -      'tilemap_get_tile_width tilemap_get_tile_height tilemap_get_width ' +
    -      'tilemap_get_height tilemap_get_x tilemap_get_y tilemap_get ' +
    -      'tilemap_get_at_pixel tilemap_get_cell_x_at_pixel ' +
    -      'tilemap_get_cell_y_at_pixel tilemap_clear draw_tilemap draw_tile ' +
    -      'tilemap_set_global_mask tilemap_get_global_mask tilemap_set_mask ' +
    -      'tilemap_get_mask tilemap_get_frame tile_set_empty tile_set_index ' +
    -      'tile_set_flip tile_set_mirror tile_set_rotate tile_get_empty ' +
    -      'tile_get_index tile_get_flip tile_get_mirror tile_get_rotate ' +
    -      'layer_tile_exists layer_tile_create layer_tile_destroy ' +
    -      'layer_tile_change layer_tile_xscale layer_tile_yscale ' +
    -      'layer_tile_blend layer_tile_alpha layer_tile_x layer_tile_y ' +
    -      'layer_tile_region layer_tile_visible layer_tile_get_sprite ' +
    -      'layer_tile_get_xscale layer_tile_get_yscale layer_tile_get_blend ' +
    -      'layer_tile_get_alpha layer_tile_get_x layer_tile_get_y ' +
    -      'layer_tile_get_region layer_tile_get_visible ' +
    -      'layer_instance_get_instance instance_activate_layer ' +
    -      'instance_deactivate_layer camera_create camera_create_view ' +
    -      'camera_destroy camera_apply camera_get_active camera_get_default ' +
    -      'camera_set_default camera_set_view_mat camera_set_proj_mat ' +
    -      'camera_set_update_script camera_set_begin_script ' +
    -      'camera_set_end_script camera_set_view_pos camera_set_view_size ' +
    -      'camera_set_view_speed camera_set_view_border camera_set_view_angle ' +
    -      'camera_set_view_target camera_get_view_mat camera_get_proj_mat ' +
    -      'camera_get_update_script camera_get_begin_script ' +
    -      'camera_get_end_script camera_get_view_x camera_get_view_y ' +
    -      'camera_get_view_width camera_get_view_height camera_get_view_speed_x ' +
    -      'camera_get_view_speed_y camera_get_view_border_x ' +
    -      'camera_get_view_border_y camera_get_view_angle ' +
    -      'camera_get_view_target view_get_camera view_get_visible ' +
    -      'view_get_xport view_get_yport view_get_wport view_get_hport ' +
    -      'view_get_surface_id view_set_camera view_set_visible view_set_xport ' +
    -      'view_set_yport view_set_wport view_set_hport view_set_surface_id ' +
    -      'gesture_drag_time gesture_drag_distance gesture_flick_speed ' +
    -      'gesture_double_tap_time gesture_double_tap_distance ' +
    -      'gesture_pinch_distance gesture_pinch_angle_towards ' +
    -      'gesture_pinch_angle_away gesture_rotate_time gesture_rotate_angle ' +
    -      'gesture_tap_count gesture_get_drag_time gesture_get_drag_distance ' +
    -      'gesture_get_flick_speed gesture_get_double_tap_time ' +
    -      'gesture_get_double_tap_distance gesture_get_pinch_distance ' +
    -      'gesture_get_pinch_angle_towards gesture_get_pinch_angle_away ' +
    -      'gesture_get_rotate_time gesture_get_rotate_angle ' +
    -      'gesture_get_tap_count keyboard_virtual_show keyboard_virtual_hide ' +
    -      'keyboard_virtual_status keyboard_virtual_height',
    -    literal: 'self other all noone global local undefined pointer_invalid ' +
    -      'pointer_null path_action_stop path_action_restart ' +
    -      'path_action_continue path_action_reverse true false pi GM_build_date ' +
    -      'GM_version GM_runtime_version  timezone_local timezone_utc ' +
    -      'gamespeed_fps gamespeed_microseconds  ev_create ev_destroy ev_step ' +
    -      'ev_alarm ev_keyboard ev_mouse ev_collision ev_other ev_draw ' +
    -      'ev_draw_begin ev_draw_end ev_draw_pre ev_draw_post ev_keypress ' +
    -      'ev_keyrelease ev_trigger ev_left_button ev_right_button ' +
    -      'ev_middle_button ev_no_button ev_left_press ev_right_press ' +
    -      'ev_middle_press ev_left_release ev_right_release ev_middle_release ' +
    -      'ev_mouse_enter ev_mouse_leave ev_mouse_wheel_up ev_mouse_wheel_down ' +
    -      'ev_global_left_button ev_global_right_button ev_global_middle_button ' +
    -      'ev_global_left_press ev_global_right_press ev_global_middle_press ' +
    -      'ev_global_left_release ev_global_right_release ' +
    -      'ev_global_middle_release ev_joystick1_left ev_joystick1_right ' +
    -      'ev_joystick1_up ev_joystick1_down ev_joystick1_button1 ' +
    -      'ev_joystick1_button2 ev_joystick1_button3 ev_joystick1_button4 ' +
    -      'ev_joystick1_button5 ev_joystick1_button6 ev_joystick1_button7 ' +
    -      'ev_joystick1_button8 ev_joystick2_left ev_joystick2_right ' +
    -      'ev_joystick2_up ev_joystick2_down ev_joystick2_button1 ' +
    -      'ev_joystick2_button2 ev_joystick2_button3 ev_joystick2_button4 ' +
    -      'ev_joystick2_button5 ev_joystick2_button6 ev_joystick2_button7 ' +
    -      'ev_joystick2_button8 ev_outside ev_boundary ev_game_start ' +
    -      'ev_game_end ev_room_start ev_room_end ev_no_more_lives ' +
    -      'ev_animation_end ev_end_of_path ev_no_more_health ev_close_button ' +
    -      'ev_user0 ev_user1 ev_user2 ev_user3 ev_user4 ev_user5 ev_user6 ' +
    -      'ev_user7 ev_user8 ev_user9 ev_user10 ev_user11 ev_user12 ev_user13 ' +
    -      'ev_user14 ev_user15 ev_step_normal ev_step_begin ev_step_end ev_gui ' +
    -      'ev_gui_begin ev_gui_end ev_cleanup ev_gesture ev_gesture_tap ' +
    -      'ev_gesture_double_tap ev_gesture_drag_start ev_gesture_dragging ' +
    -      'ev_gesture_drag_end ev_gesture_flick ev_gesture_pinch_start ' +
    -      'ev_gesture_pinch_in ev_gesture_pinch_out ev_gesture_pinch_end ' +
    -      'ev_gesture_rotate_start ev_gesture_rotating ev_gesture_rotate_end ' +
    -      'ev_global_gesture_tap ev_global_gesture_double_tap ' +
    -      'ev_global_gesture_drag_start ev_global_gesture_dragging ' +
    -      'ev_global_gesture_drag_end ev_global_gesture_flick ' +
    -      'ev_global_gesture_pinch_start ev_global_gesture_pinch_in ' +
    -      'ev_global_gesture_pinch_out ev_global_gesture_pinch_end ' +
    -      'ev_global_gesture_rotate_start ev_global_gesture_rotating ' +
    -      'ev_global_gesture_rotate_end vk_nokey vk_anykey vk_enter vk_return ' +
    -      'vk_shift vk_control vk_alt vk_escape vk_space vk_backspace vk_tab ' +
    -      'vk_pause vk_printscreen vk_left vk_right vk_up vk_down vk_home ' +
    -      'vk_end vk_delete vk_insert vk_pageup vk_pagedown vk_f1 vk_f2 vk_f3 ' +
    -      'vk_f4 vk_f5 vk_f6 vk_f7 vk_f8 vk_f9 vk_f10 vk_f11 vk_f12 vk_numpad0 ' +
    -      'vk_numpad1 vk_numpad2 vk_numpad3 vk_numpad4 vk_numpad5 vk_numpad6 ' +
    -      'vk_numpad7 vk_numpad8 vk_numpad9 vk_divide vk_multiply vk_subtract ' +
    -      'vk_add vk_decimal vk_lshift vk_lcontrol vk_lalt vk_rshift ' +
    -      'vk_rcontrol vk_ralt  mb_any mb_none mb_left mb_right mb_middle ' +
    -      'c_aqua c_black c_blue c_dkgray c_fuchsia c_gray c_green c_lime ' +
    -      'c_ltgray c_maroon c_navy c_olive c_purple c_red c_silver c_teal ' +
    -      'c_white c_yellow c_orange fa_left fa_center fa_right fa_top ' +
    -      'fa_middle fa_bottom pr_pointlist pr_linelist pr_linestrip ' +
    -      'pr_trianglelist pr_trianglestrip pr_trianglefan bm_complex bm_normal ' +
    -      'bm_add bm_max bm_subtract bm_zero bm_one bm_src_colour ' +
    -      'bm_inv_src_colour bm_src_color bm_inv_src_color bm_src_alpha ' +
    -      'bm_inv_src_alpha bm_dest_alpha bm_inv_dest_alpha bm_dest_colour ' +
    -      'bm_inv_dest_colour bm_dest_color bm_inv_dest_color bm_src_alpha_sat ' +
    -      'tf_point tf_linear tf_anisotropic mip_off mip_on mip_markedonly ' +
    -      'audio_falloff_none audio_falloff_inverse_distance ' +
    -      'audio_falloff_inverse_distance_clamped audio_falloff_linear_distance ' +
    -      'audio_falloff_linear_distance_clamped ' +
    -      'audio_falloff_exponent_distance ' +
    -      'audio_falloff_exponent_distance_clamped audio_old_system ' +
    -      'audio_new_system audio_mono audio_stereo audio_3d cr_default cr_none ' +
    -      'cr_arrow cr_cross cr_beam cr_size_nesw cr_size_ns cr_size_nwse ' +
    -      'cr_size_we cr_uparrow cr_hourglass cr_drag cr_appstart cr_handpoint ' +
    -      'cr_size_all spritespeed_framespersecond ' +
    -      'spritespeed_framespergameframe asset_object asset_unknown ' +
    -      'asset_sprite asset_sound asset_room asset_path asset_script ' +
    -      'asset_font asset_timeline asset_tiles asset_shader fa_readonly ' +
    -      'fa_hidden fa_sysfile fa_volumeid fa_directory fa_archive  ' +
    -      'ds_type_map ds_type_list ds_type_stack ds_type_queue ds_type_grid ' +
    -      'ds_type_priority ef_explosion ef_ring ef_ellipse ef_firework ' +
    -      'ef_smoke ef_smokeup ef_star ef_spark ef_flare ef_cloud ef_rain ' +
    -      'ef_snow pt_shape_pixel pt_shape_disk pt_shape_square pt_shape_line ' +
    -      'pt_shape_star pt_shape_circle pt_shape_ring pt_shape_sphere ' +
    -      'pt_shape_flare pt_shape_spark pt_shape_explosion pt_shape_cloud ' +
    -      'pt_shape_smoke pt_shape_snow ps_distr_linear ps_distr_gaussian ' +
    -      'ps_distr_invgaussian ps_shape_rectangle ps_shape_ellipse ' +
    -      'ps_shape_diamond ps_shape_line ty_real ty_string dll_cdecl ' +
    -      'dll_stdcall matrix_view matrix_projection matrix_world os_win32 ' +
    -      'os_windows os_macosx os_ios os_android os_symbian os_linux ' +
    -      'os_unknown os_winphone os_tizen os_win8native ' +
    -      'os_wiiu os_3ds  os_psvita os_bb10 os_ps4 os_xboxone ' +
    -      'os_ps3 os_xbox360 os_uwp os_tvos os_switch ' +
    -      'browser_not_a_browser browser_unknown browser_ie browser_firefox ' +
    -      'browser_chrome browser_safari browser_safari_mobile browser_opera ' +
    -      'browser_tizen browser_edge browser_windows_store browser_ie_mobile  ' +
    -      'device_ios_unknown device_ios_iphone device_ios_iphone_retina ' +
    -      'device_ios_ipad device_ios_ipad_retina device_ios_iphone5 ' +
    -      'device_ios_iphone6 device_ios_iphone6plus device_emulator ' +
    -      'device_tablet display_landscape display_landscape_flipped ' +
    -      'display_portrait display_portrait_flipped tm_sleep tm_countvsyncs ' +
    -      'of_challenge_win of_challen ge_lose of_challenge_tie ' +
    -      'leaderboard_type_number leaderboard_type_time_mins_secs ' +
    -      'cmpfunc_never cmpfunc_less cmpfunc_equal cmpfunc_lessequal ' +
    -      'cmpfunc_greater cmpfunc_notequal cmpfunc_greaterequal cmpfunc_always ' +
    -      'cull_noculling cull_clockwise cull_counterclockwise lighttype_dir ' +
    -      'lighttype_point iap_ev_storeload iap_ev_product iap_ev_purchase ' +
    -      'iap_ev_consume iap_ev_restore iap_storeload_ok iap_storeload_failed ' +
    -      'iap_status_uninitialised iap_status_unavailable iap_status_loading ' +
    -      'iap_status_available iap_status_processing iap_status_restoring ' +
    -      'iap_failed iap_unavailable iap_available iap_purchased iap_canceled ' +
    -      'iap_refunded fb_login_default fb_login_fallback_to_webview ' +
    -      'fb_login_no_fallback_to_webview fb_login_forcing_webview ' +
    -      'fb_login_use_system_account fb_login_forcing_safari  ' +
    -      'phy_joint_anchor_1_x phy_joint_anchor_1_y phy_joint_anchor_2_x ' +
    -      'phy_joint_anchor_2_y phy_joint_reaction_force_x ' +
    -      'phy_joint_reaction_force_y phy_joint_reaction_torque ' +
    -      'phy_joint_motor_speed phy_joint_angle phy_joint_motor_torque ' +
    -      'phy_joint_max_motor_torque phy_joint_translation phy_joint_speed ' +
    -      'phy_joint_motor_force phy_joint_max_motor_force phy_joint_length_1 ' +
    -      'phy_joint_length_2 phy_joint_damping_ratio phy_joint_frequency ' +
    -      'phy_joint_lower_angle_limit phy_joint_upper_angle_limit ' +
    -      'phy_joint_angle_limits phy_joint_max_length phy_joint_max_torque ' +
    -      'phy_joint_max_force phy_debug_render_aabb ' +
    -      'phy_debug_render_collision_pairs phy_debug_render_coms ' +
    -      'phy_debug_render_core_shapes phy_debug_render_joints ' +
    -      'phy_debug_render_obb phy_debug_render_shapes  ' +
    -      'phy_particle_flag_water phy_particle_flag_zombie ' +
    -      'phy_particle_flag_wall phy_particle_flag_spring ' +
    -      'phy_particle_flag_elastic phy_particle_flag_viscous ' +
    -      'phy_particle_flag_powder phy_particle_flag_tensile ' +
    -      'phy_particle_flag_colourmixing phy_particle_flag_colormixing ' +
    -      'phy_particle_group_flag_solid phy_particle_group_flag_rigid ' +
    -      'phy_particle_data_flag_typeflags phy_particle_data_flag_position ' +
    -      'phy_particle_data_flag_velocity phy_particle_data_flag_colour ' +
    -      'phy_particle_data_flag_color phy_particle_data_flag_category  ' +
    -      'achievement_our_info achievement_friends_info ' +
    -      'achievement_leaderboard_info achievement_achievement_info ' +
    -      'achievement_filter_all_players achievement_filter_friends_only ' +
    -      'achievement_filter_favorites_only ' +
    -      'achievement_type_achievement_challenge ' +
    -      'achievement_type_score_challenge achievement_pic_loaded  ' +
    -      'achievement_show_ui achievement_show_profile ' +
    -      'achievement_show_leaderboard achievement_show_achievement ' +
    -      'achievement_show_bank achievement_show_friend_picker ' +
    -      'achievement_show_purchase_prompt network_socket_tcp ' +
    -      'network_socket_udp network_socket_bluetooth network_type_connect ' +
    -      'network_type_disconnect network_type_data ' +
    -      'network_type_non_blocking_connect network_config_connect_timeout ' +
    -      'network_config_use_non_blocking_socket ' +
    -      'network_config_enable_reliable_udp ' +
    -      'network_config_disable_reliable_udp buffer_fixed buffer_grow ' +
    -      'buffer_wrap buffer_fast buffer_vbuffer buffer_network buffer_u8 ' +
    -      'buffer_s8 buffer_u16 buffer_s16 buffer_u32 buffer_s32 buffer_u64 ' +
    -      'buffer_f16 buffer_f32 buffer_f64 buffer_bool buffer_text ' +
    -      'buffer_string buffer_surface_copy buffer_seek_start ' +
    -      'buffer_seek_relative buffer_seek_end ' +
    -      'buffer_generalerror buffer_outofspace buffer_outofbounds ' +
    -      'buffer_invalidtype  text_type button_type input_type ANSI_CHARSET ' +
    -      'DEFAULT_CHARSET EASTEUROPE_CHARSET RUSSIAN_CHARSET SYMBOL_CHARSET ' +
    -      'SHIFTJIS_CHARSET HANGEUL_CHARSET GB2312_CHARSET CHINESEBIG5_CHARSET ' +
    -      'JOHAB_CHARSET HEBREW_CHARSET ARABIC_CHARSET GREEK_CHARSET ' +
    -      'TURKISH_CHARSET VIETNAMESE_CHARSET THAI_CHARSET MAC_CHARSET ' +
    -      'BALTIC_CHARSET OEM_CHARSET  gp_face1 gp_face2 gp_face3 gp_face4 ' +
    -      'gp_shoulderl gp_shoulderr gp_shoulderlb gp_shoulderrb gp_select ' +
    -      'gp_start gp_stickl gp_stickr gp_padu gp_padd gp_padl gp_padr ' +
    -      'gp_axislh gp_axislv gp_axisrh gp_axisrv ov_friends ov_community ' +
    -      'ov_players ov_settings ov_gamegroup ov_achievements lb_sort_none ' +
    -      'lb_sort_ascending lb_sort_descending lb_disp_none lb_disp_numeric ' +
    -      'lb_disp_time_sec lb_disp_time_ms ugc_result_success ' +
    -      'ugc_filetype_community ugc_filetype_microtrans ugc_visibility_public ' +
    -      'ugc_visibility_friends_only ugc_visibility_private ' +
    -      'ugc_query_RankedByVote ugc_query_RankedByPublicationDate ' +
    -      'ugc_query_AcceptedForGameRankedByAcceptanceDate ' +
    -      'ugc_query_RankedByTrend ' +
    -      'ugc_query_FavoritedByFriendsRankedByPublicationDate ' +
    -      'ugc_query_CreatedByFriendsRankedByPublicationDate ' +
    -      'ugc_query_RankedByNumTimesReported ' +
    -      'ugc_query_CreatedByFollowedUsersRankedByPublicationDate ' +
    -      'ugc_query_NotYetRated ugc_query_RankedByTotalVotesAsc ' +
    -      'ugc_query_RankedByVotesUp ugc_query_RankedByTextSearch ' +
    -      'ugc_sortorder_CreationOrderDesc ugc_sortorder_CreationOrderAsc ' +
    -      'ugc_sortorder_TitleAsc ugc_sortorder_LastUpdatedDesc ' +
    -      'ugc_sortorder_SubscriptionDateDesc ugc_sortorder_VoteScoreDesc ' +
    -      'ugc_sortorder_ForModeration ugc_list_Published ugc_list_VotedOn ' +
    -      'ugc_list_VotedUp ugc_list_VotedDown ugc_list_WillVoteLater ' +
    -      'ugc_list_Favorited ugc_list_Subscribed ugc_list_UsedOrPlayed ' +
    -      'ugc_list_Followed ugc_match_Items ugc_match_Items_Mtx ' +
    -      'ugc_match_Items_ReadyToUse ugc_match_Collections ugc_match_Artwork ' +
    -      'ugc_match_Videos ugc_match_Screenshots ugc_match_AllGuides ' +
    -      'ugc_match_WebGuides ugc_match_IntegratedGuides ' +
    -      'ugc_match_UsableInGame ugc_match_ControllerBindings  ' +
    -      'vertex_usage_position vertex_usage_colour vertex_usage_color ' +
    -      'vertex_usage_normal vertex_usage_texcoord vertex_usage_textcoord ' +
    -      'vertex_usage_blendweight vertex_usage_blendindices ' +
    -      'vertex_usage_psize vertex_usage_tangent vertex_usage_binormal ' +
    -      'vertex_usage_fog vertex_usage_depth vertex_usage_sample ' +
    -      'vertex_type_float1 vertex_type_float2 vertex_type_float3 ' +
    -      'vertex_type_float4 vertex_type_colour vertex_type_color ' +
    -      'vertex_type_ubyte4 layerelementtype_undefined ' +
    -      'layerelementtype_background layerelementtype_instance ' +
    -      'layerelementtype_oldtilemap layerelementtype_sprite ' +
    -      'layerelementtype_tilemap layerelementtype_particlesystem ' +
    -      'layerelementtype_tile tile_rotate tile_flip tile_mirror ' +
    -      'tile_index_mask kbv_type_default kbv_type_ascii kbv_type_url ' +
    -      'kbv_type_email kbv_type_numbers kbv_type_phone kbv_type_phone_name ' +
    -      'kbv_returnkey_default kbv_returnkey_go kbv_returnkey_google ' +
    -      'kbv_returnkey_join kbv_returnkey_next kbv_returnkey_route ' +
    -      'kbv_returnkey_search kbv_returnkey_send kbv_returnkey_yahoo ' +
    -      'kbv_returnkey_done kbv_returnkey_continue kbv_returnkey_emergency ' +
    -      'kbv_autocapitalize_none kbv_autocapitalize_words ' +
    -      'kbv_autocapitalize_sentences kbv_autocapitalize_characters',
    -    symbol: 'argument_relative argument argument0 argument1 argument2 ' +
    -      'argument3 argument4 argument5 argument6 argument7 argument8 ' +
    -      'argument9 argument10 argument11 argument12 argument13 argument14 ' +
    -      'argument15 argument_count x|0 y|0 xprevious yprevious xstart ystart ' +
    -      'hspeed vspeed direction speed friction gravity gravity_direction ' +
    -      'path_index path_position path_positionprevious path_speed ' +
    -      'path_scale path_orientation path_endaction object_index id solid ' +
    -      'persistent mask_index instance_count instance_id room_speed fps ' +
    -      'fps_real current_time current_year current_month current_day ' +
    -      'current_weekday current_hour current_minute current_second alarm ' +
    -      'timeline_index timeline_position timeline_speed timeline_running ' +
    -      'timeline_loop room room_first room_last room_width room_height ' +
    -      'room_caption room_persistent score lives health show_score ' +
    -      'show_lives show_health caption_score caption_lives caption_health ' +
    -      'event_type event_number event_object event_action ' +
    -      'application_surface gamemaker_pro gamemaker_registered ' +
    -      'gamemaker_version error_occurred error_last debug_mode ' +
    -      'keyboard_key keyboard_lastkey keyboard_lastchar keyboard_string ' +
    -      'mouse_x mouse_y mouse_button mouse_lastbutton cursor_sprite ' +
    -      'visible sprite_index sprite_width sprite_height sprite_xoffset ' +
    -      'sprite_yoffset image_number image_index image_speed depth ' +
    -      'image_xscale image_yscale image_angle image_alpha image_blend ' +
    -      'bbox_left bbox_right bbox_top bbox_bottom layer background_colour  ' +
    -      'background_showcolour background_color background_showcolor ' +
    -      'view_enabled view_current view_visible view_xview view_yview ' +
    -      'view_wview view_hview view_xport view_yport view_wport view_hport ' +
    -      'view_angle view_hborder view_vborder view_hspeed view_vspeed ' +
    -      'view_object view_surface_id view_camera game_id game_display_name ' +
    -      'game_project_name game_save_id working_directory temp_directory ' +
    -      'program_directory browser_width browser_height os_type os_device ' +
    -      'os_browser os_version display_aa async_load delta_time ' +
    -      'webgl_enabled event_data iap_data phy_rotation phy_position_x ' +
    -      'phy_position_y phy_angular_velocity phy_linear_velocity_x ' +
    -      'phy_linear_velocity_y phy_speed_x phy_speed_y phy_speed ' +
    -      'phy_angular_damping phy_linear_damping phy_bullet ' +
    -      'phy_fixed_rotation phy_active phy_mass phy_inertia phy_com_x ' +
    -      'phy_com_y phy_dynamic phy_kinematic phy_sleeping ' +
    -      'phy_collision_points phy_collision_x phy_collision_y ' +
    -      'phy_col_normal_x phy_col_normal_y phy_position_xprevious ' +
    -      'phy_position_yprevious'
    -  };
    -
    -  return {
    -    name: 'GML',
    -    case_insensitive: false, // language is case-insensitive
    -    keywords: GML_KEYWORDS,
    -
    -    contains: [
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.C_NUMBER_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = gml;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/go.js b/claude-code-source/node_modules/highlight.js/lib/languages/go.js
    deleted file mode 100644
    index 4c809922..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/go.js
    +++ /dev/null
    @@ -1,74 +0,0 @@
    -/*
    -Language: Go
    -Author: Stephan Kountso aka StepLg 
    -Contributors: Evgeny Stepanischev 
    -Description: Google go language (golang). For info about language
    -Website: http://golang.org/
    -Category: common, system
    -*/
    -
    -function go(hljs) {
    -  const GO_KEYWORDS = {
    -    keyword:
    -      'break default func interface select case map struct chan else goto package switch ' +
    -      'const fallthrough if range type continue for import return var go defer ' +
    -      'bool byte complex64 complex128 float32 float64 int8 int16 int32 int64 string uint8 ' +
    -      'uint16 uint32 uint64 int uint uintptr rune',
    -    literal:
    -       'true false iota nil',
    -    built_in:
    -      'append cap close complex copy imag len make new panic print println real recover delete'
    -  };
    -  return {
    -    name: 'Go',
    -    aliases: ['golang'],
    -    keywords: GO_KEYWORDS,
    -    illegal: '
    -Description: a lightweight dynamic language for the JVM
    -Website: http://golo-lang.org/
    -*/
    -
    -function golo(hljs) {
    -  return {
    -    name: 'Golo',
    -    keywords: {
    -      keyword:
    -          'println readln print import module function local return let var ' +
    -          'while for foreach times in case when match with break continue ' +
    -          'augment augmentation each find filter reduce ' +
    -          'if then else otherwise try catch finally raise throw orIfNull ' +
    -          'DynamicObject|10 DynamicVariable struct Observable map set vector list array',
    -      literal:
    -          'true false null'
    -    },
    -    contains: [
    -      hljs.HASH_COMMENT_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.C_NUMBER_MODE,
    -      {
    -        className: 'meta',
    -        begin: '@[A-Za-z]+'
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = golo;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/gradle.js b/claude-code-source/node_modules/highlight.js/lib/languages/gradle.js
    deleted file mode 100644
    index 59b663ea..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/gradle.js
    +++ /dev/null
    @@ -1,44 +0,0 @@
    -/*
    -Language: Gradle
    -Description: Gradle is an open-source build automation tool focused on flexibility and performance.
    -Website: https://gradle.org
    -Author: Damian Mee 
    -*/
    -
    -function gradle(hljs) {
    -  return {
    -    name: 'Gradle',
    -    case_insensitive: true,
    -    keywords: {
    -      keyword:
    -        'task project allprojects subprojects artifacts buildscript configurations ' +
    -        'dependencies repositories sourceSets description delete from into include ' +
    -        'exclude source classpath destinationDir includes options sourceCompatibility ' +
    -        'targetCompatibility group flatDir doLast doFirst flatten todir fromdir ant ' +
    -        'def abstract break case catch continue default do else extends final finally ' +
    -        'for if implements instanceof native new private protected public return static ' +
    -        'switch synchronized throw throws transient try volatile while strictfp package ' +
    -        'import false null super this true antlrtask checkstyle codenarc copy boolean ' +
    -        'byte char class double float int interface long short void compile runTime ' +
    -        'file fileTree abs any append asList asWritable call collect compareTo count ' +
    -        'div dump each eachByte eachFile eachLine every find findAll flatten getAt ' +
    -        'getErr getIn getOut getText grep immutable inject inspect intersect invokeMethods ' +
    -        'isCase join leftShift minus multiply newInputStream newOutputStream newPrintWriter ' +
    -        'newReader newWriter next plus pop power previous print println push putAt read ' +
    -        'readBytes readLines reverse reverseEach round size sort splitEachLine step subMap ' +
    -        'times toInteger toList tokenize upto waitForOrKill withPrintWriter withReader ' +
    -        'withStream withWriter withWriterAppend write writeLine'
    -    },
    -    contains: [
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.NUMBER_MODE,
    -      hljs.REGEXP_MODE
    -
    -    ]
    -  };
    -}
    -
    -module.exports = gradle;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/groovy.js b/claude-code-source/node_modules/highlight.js/lib/languages/groovy.js
    deleted file mode 100644
    index b6dfd33f..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/groovy.js
    +++ /dev/null
    @@ -1,174 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function lookahead(re) {
    -  return concat('(?=', re, ')');
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    - Language: Groovy
    - Author: Guillaume Laforge 
    - Description: Groovy programming language implementation inspired from Vsevolod's Java mode
    - Website: https://groovy-lang.org
    - */
    -
    -function variants(variants, obj = {}) {
    -  obj.variants = variants;
    -  return obj;
    -}
    -
    -function groovy(hljs) {
    -  const IDENT_RE = '[A-Za-z0-9_$]+';
    -  const COMMENT = variants([
    -    hljs.C_LINE_COMMENT_MODE,
    -    hljs.C_BLOCK_COMMENT_MODE,
    -    hljs.COMMENT(
    -      '/\\*\\*',
    -      '\\*/',
    -      {
    -        relevance: 0,
    -        contains: [
    -          {
    -            // eat up @'s in emails to prevent them to be recognized as doctags
    -            begin: /\w+@/,
    -            relevance: 0
    -          },
    -          {
    -            className: 'doctag',
    -            begin: '@[A-Za-z]+'
    -          }
    -        ]
    -      }
    -    )
    -  ]);
    -  const REGEXP = {
    -    className: 'regexp',
    -    begin: /~?\/[^\/\n]+\//,
    -    contains: [ hljs.BACKSLASH_ESCAPE ]
    -  };
    -  const NUMBER = variants([
    -    hljs.BINARY_NUMBER_MODE,
    -    hljs.C_NUMBER_MODE
    -  ]);
    -  const STRING = variants([
    -    {
    -      begin: /"""/,
    -      end: /"""/
    -    },
    -    {
    -      begin: /'''/,
    -      end: /'''/
    -    },
    -    {
    -      begin: "\\$/",
    -      end: "/\\$",
    -      relevance: 10
    -    },
    -    hljs.APOS_STRING_MODE,
    -    hljs.QUOTE_STRING_MODE
    -  ],
    -  {
    -    className: "string"
    -  }
    -  );
    -
    -  return {
    -    name: 'Groovy',
    -    keywords: {
    -      built_in: 'this super',
    -      literal: 'true false null',
    -      keyword:
    -            'byte short char int long boolean float double void ' +
    -            // groovy specific keywords
    -            'def as in assert trait ' +
    -            // common keywords with Java
    -            'abstract static volatile transient public private protected synchronized final ' +
    -            'class interface enum if else for while switch case break default continue ' +
    -            'throw throws try catch finally implements extends new import package return instanceof'
    -    },
    -    contains: [
    -      hljs.SHEBANG({
    -        binary: "groovy",
    -        relevance: 10
    -      }),
    -      COMMENT,
    -      STRING,
    -      REGEXP,
    -      NUMBER,
    -      {
    -        className: 'class',
    -        beginKeywords: 'class interface trait enum',
    -        end: /\{/,
    -        illegal: ':',
    -        contains: [
    -          {
    -            beginKeywords: 'extends implements'
    -          },
    -          hljs.UNDERSCORE_TITLE_MODE
    -        ]
    -      },
    -      {
    -        className: 'meta',
    -        begin: '@[A-Za-z]+',
    -        relevance: 0
    -      },
    -      {
    -        // highlight map keys and named parameters as attrs
    -        className: 'attr',
    -        begin: IDENT_RE + '[ \t]*:',
    -        relevance: 0
    -      },
    -      {
    -        // catch middle element of the ternary operator
    -        // to avoid highlight it as a label, named parameter, or map key
    -        begin: /\?/,
    -        end: /:/,
    -        relevance: 0,
    -        contains: [
    -          COMMENT,
    -          STRING,
    -          REGEXP,
    -          NUMBER,
    -          'self'
    -        ]
    -      },
    -      {
    -        // highlight labeled statements
    -        className: 'symbol',
    -        begin: '^[ \t]*' + lookahead(IDENT_RE + ':'),
    -        excludeBegin: true,
    -        end: IDENT_RE + ':',
    -        relevance: 0
    -      }
    -    ],
    -    illegal: /#|<\//
    -  };
    -}
    -
    -module.exports = groovy;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/haml.js b/claude-code-source/node_modules/highlight.js/lib/languages/haml.js
    deleted file mode 100644
    index cb6a5363..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/haml.js
    +++ /dev/null
    @@ -1,117 +0,0 @@
    -/*
    -Language: HAML
    -Requires: ruby.js
    -Author: Dan Allen 
    -Website: http://haml.info
    -Category: template
    -*/
    -
    -// TODO support filter tags like :javascript, support inline HTML
    -function haml(hljs) {
    -  return {
    -    name: 'HAML',
    -    case_insensitive: true,
    -    contains: [
    -      {
    -        className: 'meta',
    -        begin: '^!!!( (5|1\\.1|Strict|Frameset|Basic|Mobile|RDFa|XML\\b.*))?$',
    -        relevance: 10
    -      },
    -      // FIXME these comments should be allowed to span indented lines
    -      hljs.COMMENT(
    -        '^\\s*(!=#|=#|-#|/).*$',
    -        false,
    -        {
    -          relevance: 0
    -        }
    -      ),
    -      {
    -        begin: '^\\s*(-|=|!=)(?!#)',
    -        starts: {
    -          end: '\\n',
    -          subLanguage: 'ruby'
    -        }
    -      },
    -      {
    -        className: 'tag',
    -        begin: '^\\s*%',
    -        contains: [
    -          {
    -            className: 'selector-tag',
    -            begin: '\\w+'
    -          },
    -          {
    -            className: 'selector-id',
    -            begin: '#[\\w-]+'
    -          },
    -          {
    -            className: 'selector-class',
    -            begin: '\\.[\\w-]+'
    -          },
    -          {
    -            begin: /\{\s*/,
    -            end: /\s*\}/,
    -            contains: [
    -              {
    -                begin: ':\\w+\\s*=>',
    -                end: ',\\s+',
    -                returnBegin: true,
    -                endsWithParent: true,
    -                contains: [
    -                  {
    -                    className: 'attr',
    -                    begin: ':\\w+'
    -                  },
    -                  hljs.APOS_STRING_MODE,
    -                  hljs.QUOTE_STRING_MODE,
    -                  {
    -                    begin: '\\w+',
    -                    relevance: 0
    -                  }
    -                ]
    -              }
    -            ]
    -          },
    -          {
    -            begin: '\\(\\s*',
    -            end: '\\s*\\)',
    -            excludeEnd: true,
    -            contains: [
    -              {
    -                begin: '\\w+\\s*=',
    -                end: '\\s+',
    -                returnBegin: true,
    -                endsWithParent: true,
    -                contains: [
    -                  {
    -                    className: 'attr',
    -                    begin: '\\w+',
    -                    relevance: 0
    -                  },
    -                  hljs.APOS_STRING_MODE,
    -                  hljs.QUOTE_STRING_MODE,
    -                  {
    -                    begin: '\\w+',
    -                    relevance: 0
    -                  }
    -                ]
    -              }
    -            ]
    -          }
    -        ]
    -      },
    -      {
    -        begin: '^\\s*[=~]\\s*'
    -      },
    -      {
    -        begin: /#\{/,
    -        starts: {
    -          end: /\}/,
    -          subLanguage: 'ruby'
    -        }
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = haml;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/handlebars.js b/claude-code-source/node_modules/highlight.js/lib/languages/handlebars.js
    deleted file mode 100644
    index 88ae05a8..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/handlebars.js
    +++ /dev/null
    @@ -1,324 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function anyNumberOfTimes(re) {
    -  return concat('(', re, ')*');
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function optional(re) {
    -  return concat('(', re, ')?');
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/**
    - * Any of the passed expresssions may match
    - *
    - * Creates a huge this | this | that | that match
    - * @param {(RegExp | string)[] } args
    - * @returns {string}
    - */
    -function either(...args) {
    -  const joined = '(' + args.map((x) => source(x)).join("|") + ")";
    -  return joined;
    -}
    -
    -/*
    -Language: Handlebars
    -Requires: xml.js
    -Author: Robin Ward 
    -Description: Matcher for Handlebars as well as EmberJS additions.
    -Website: https://handlebarsjs.com
    -Category: template
    -*/
    -
    -function handlebars(hljs) {
    -  const BUILT_INS = {
    -    'builtin-name': [
    -      'action',
    -      'bindattr',
    -      'collection',
    -      'component',
    -      'concat',
    -      'debugger',
    -      'each',
    -      'each-in',
    -      'get',
    -      'hash',
    -      'if',
    -      'in',
    -      'input',
    -      'link-to',
    -      'loc',
    -      'log',
    -      'lookup',
    -      'mut',
    -      'outlet',
    -      'partial',
    -      'query-params',
    -      'render',
    -      'template',
    -      'textarea',
    -      'unbound',
    -      'unless',
    -      'view',
    -      'with',
    -      'yield'
    -    ]
    -  };
    -
    -  const LITERALS = {
    -    literal: [
    -      'true',
    -      'false',
    -      'undefined',
    -      'null'
    -    ]
    -  };
    -
    -  // as defined in https://handlebarsjs.com/guide/expressions.html#literal-segments
    -  // this regex matches literal segments like ' abc ' or [ abc ] as well as helpers and paths
    -  // like a/b, ./abc/cde, and abc.bcd
    -
    -  const DOUBLE_QUOTED_ID_REGEX = /""|"[^"]+"/;
    -  const SINGLE_QUOTED_ID_REGEX = /''|'[^']+'/;
    -  const BRACKET_QUOTED_ID_REGEX = /\[\]|\[[^\]]+\]/;
    -  const PLAIN_ID_REGEX = /[^\s!"#%&'()*+,.\/;<=>@\[\\\]^`{|}~]+/;
    -  const PATH_DELIMITER_REGEX = /(\.|\/)/;
    -  const ANY_ID = either(
    -    DOUBLE_QUOTED_ID_REGEX,
    -    SINGLE_QUOTED_ID_REGEX,
    -    BRACKET_QUOTED_ID_REGEX,
    -    PLAIN_ID_REGEX
    -    );
    -
    -  const IDENTIFIER_REGEX = concat(
    -    optional(/\.|\.\/|\//), // relative or absolute path
    -    ANY_ID,
    -    anyNumberOfTimes(concat(
    -      PATH_DELIMITER_REGEX,
    -      ANY_ID
    -    ))
    -  );
    -
    -  // identifier followed by a equal-sign (without the equal sign)
    -  const HASH_PARAM_REGEX = concat(
    -    '(',
    -    BRACKET_QUOTED_ID_REGEX, '|',
    -    PLAIN_ID_REGEX,
    -    ')(?==)'
    -  );
    -
    -  const HELPER_NAME_OR_PATH_EXPRESSION = {
    -    begin: IDENTIFIER_REGEX,
    -    lexemes: /[\w.\/]+/
    -  };
    -
    -  const HELPER_PARAMETER = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, {
    -    keywords: LITERALS
    -  });
    -
    -  const SUB_EXPRESSION = {
    -    begin: /\(/,
    -    end: /\)/
    -    // the "contains" is added below when all necessary sub-modes are defined
    -  };
    -
    -  const HASH = {
    -    // fka "attribute-assignment", parameters of the form 'key=value'
    -    className: 'attr',
    -    begin: HASH_PARAM_REGEX,
    -    relevance: 0,
    -    starts: {
    -      begin: /=/,
    -      end: /=/,
    -      starts: {
    -        contains: [
    -          hljs.NUMBER_MODE,
    -          hljs.QUOTE_STRING_MODE,
    -          hljs.APOS_STRING_MODE,
    -          HELPER_PARAMETER,
    -          SUB_EXPRESSION
    -        ]
    -      }
    -    }
    -  };
    -
    -  const BLOCK_PARAMS = {
    -    // parameters of the form '{{#with x as | y |}}...{{/with}}'
    -    begin: /as\s+\|/,
    -    keywords: {
    -      keyword: 'as'
    -    },
    -    end: /\|/,
    -    contains: [
    -      {
    -        // define sub-mode in order to prevent highlighting of block-parameter named "as"
    -        begin: /\w+/
    -      }
    -    ]
    -  };
    -
    -  const HELPER_PARAMETERS = {
    -    contains: [
    -      hljs.NUMBER_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.APOS_STRING_MODE,
    -      BLOCK_PARAMS,
    -      HASH,
    -      HELPER_PARAMETER,
    -      SUB_EXPRESSION
    -    ],
    -    returnEnd: true
    -    // the property "end" is defined through inheritance when the mode is used. If depends
    -    // on the surrounding mode, but "endsWithParent" does not work here (i.e. it includes the
    -    // end-token of the surrounding mode)
    -  };
    -
    -  const SUB_EXPRESSION_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, {
    -    className: 'name',
    -    keywords: BUILT_INS,
    -    starts: hljs.inherit(HELPER_PARAMETERS, {
    -      end: /\)/
    -    })
    -  });
    -
    -  SUB_EXPRESSION.contains = [SUB_EXPRESSION_CONTENTS];
    -
    -  const OPENING_BLOCK_MUSTACHE_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, {
    -    keywords: BUILT_INS,
    -    className: 'name',
    -    starts: hljs.inherit(HELPER_PARAMETERS, {
    -      end: /\}\}/
    -    })
    -  });
    -
    -  const CLOSING_BLOCK_MUSTACHE_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, {
    -    keywords: BUILT_INS,
    -    className: 'name'
    -  });
    -
    -  const BASIC_MUSTACHE_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, {
    -    className: 'name',
    -    keywords: BUILT_INS,
    -    starts: hljs.inherit(HELPER_PARAMETERS, {
    -      end: /\}\}/
    -    })
    -  });
    -
    -  const ESCAPE_MUSTACHE_WITH_PRECEEDING_BACKSLASH = {
    -    begin: /\\\{\{/,
    -    skip: true
    -  };
    -  const PREVENT_ESCAPE_WITH_ANOTHER_PRECEEDING_BACKSLASH = {
    -    begin: /\\\\(?=\{\{)/,
    -    skip: true
    -  };
    -
    -  return {
    -    name: 'Handlebars',
    -    aliases: [
    -      'hbs',
    -      'html.hbs',
    -      'html.handlebars',
    -      'htmlbars'
    -    ],
    -    case_insensitive: true,
    -    subLanguage: 'xml',
    -    contains: [
    -      ESCAPE_MUSTACHE_WITH_PRECEEDING_BACKSLASH,
    -      PREVENT_ESCAPE_WITH_ANOTHER_PRECEEDING_BACKSLASH,
    -      hljs.COMMENT(/\{\{!--/, /--\}\}/),
    -      hljs.COMMENT(/\{\{!/, /\}\}/),
    -      {
    -        // open raw block "{{{{raw}}}} content not evaluated {{{{/raw}}}}"
    -        className: 'template-tag',
    -        begin: /\{\{\{\{(?!\/)/,
    -        end: /\}\}\}\}/,
    -        contains: [OPENING_BLOCK_MUSTACHE_CONTENTS],
    -        starts: {
    -          end: /\{\{\{\{\//,
    -          returnEnd: true,
    -          subLanguage: 'xml'
    -        }
    -      },
    -      {
    -        // close raw block
    -        className: 'template-tag',
    -        begin: /\{\{\{\{\//,
    -        end: /\}\}\}\}/,
    -        contains: [CLOSING_BLOCK_MUSTACHE_CONTENTS]
    -      },
    -      {
    -        // open block statement
    -        className: 'template-tag',
    -        begin: /\{\{#/,
    -        end: /\}\}/,
    -        contains: [OPENING_BLOCK_MUSTACHE_CONTENTS]
    -      },
    -      {
    -        className: 'template-tag',
    -        begin: /\{\{(?=else\}\})/,
    -        end: /\}\}/,
    -        keywords: 'else'
    -      },
    -      {
    -        className: 'template-tag',
    -        begin: /\{\{(?=else if)/,
    -        end: /\}\}/,
    -        keywords: 'else if'
    -      },
    -      {
    -        // closing block statement
    -        className: 'template-tag',
    -        begin: /\{\{\//,
    -        end: /\}\}/,
    -        contains: [CLOSING_BLOCK_MUSTACHE_CONTENTS]
    -      },
    -      {
    -        // template variable or helper-call that is NOT html-escaped
    -        className: 'template-variable',
    -        begin: /\{\{\{/,
    -        end: /\}\}\}/,
    -        contains: [BASIC_MUSTACHE_CONTENTS]
    -      },
    -      {
    -        // template variable or helper-call that is html-escaped
    -        className: 'template-variable',
    -        begin: /\{\{/,
    -        end: /\}\}/,
    -        contains: [BASIC_MUSTACHE_CONTENTS]
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = handlebars;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/haskell.js b/claude-code-source/node_modules/highlight.js/lib/languages/haskell.js
    deleted file mode 100644
    index 5d6a3673..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/haskell.js
    +++ /dev/null
    @@ -1,173 +0,0 @@
    -/*
    -Language: Haskell
    -Author: Jeremy Hull 
    -Contributors: Zena Treep 
    -Website: https://www.haskell.org
    -Category: functional
    -*/
    -
    -function haskell(hljs) {
    -  const COMMENT = {
    -    variants: [
    -      hljs.COMMENT('--', '$'),
    -      hljs.COMMENT(
    -        /\{-/,
    -        /-\}/,
    -        {
    -          contains: ['self']
    -        }
    -      )
    -    ]
    -  };
    -
    -  const PRAGMA = {
    -    className: 'meta',
    -    begin: /\{-#/,
    -    end: /#-\}/
    -  };
    -
    -  const PREPROCESSOR = {
    -    className: 'meta',
    -    begin: '^#',
    -    end: '$'
    -  };
    -
    -  const CONSTRUCTOR = {
    -    className: 'type',
    -    begin: '\\b[A-Z][\\w\']*', // TODO: other constructors (build-in, infix).
    -    relevance: 0
    -  };
    -
    -  const LIST = {
    -    begin: '\\(',
    -    end: '\\)',
    -    illegal: '"',
    -    contains: [
    -      PRAGMA,
    -      PREPROCESSOR,
    -      {
    -        className: 'type',
    -        begin: '\\b[A-Z][\\w]*(\\((\\.\\.|,|\\w+)\\))?'
    -      },
    -      hljs.inherit(hljs.TITLE_MODE, {
    -        begin: '[_a-z][\\w\']*'
    -      }),
    -      COMMENT
    -    ]
    -  };
    -
    -  const RECORD = {
    -    begin: /\{/,
    -    end: /\}/,
    -    contains: LIST.contains
    -  };
    -
    -  return {
    -    name: 'Haskell',
    -    aliases: ['hs'],
    -    keywords:
    -      'let in if then else case of where do module import hiding ' +
    -      'qualified type data newtype deriving class instance as default ' +
    -      'infix infixl infixr foreign export ccall stdcall cplusplus ' +
    -      'jvm dotnet safe unsafe family forall mdo proc rec',
    -    contains: [
    -      // Top-level constructions.
    -      {
    -        beginKeywords: 'module',
    -        end: 'where',
    -        keywords: 'module where',
    -        contains: [
    -          LIST,
    -          COMMENT
    -        ],
    -        illegal: '\\W\\.|;'
    -      },
    -      {
    -        begin: '\\bimport\\b',
    -        end: '$',
    -        keywords: 'import qualified as hiding',
    -        contains: [
    -          LIST,
    -          COMMENT
    -        ],
    -        illegal: '\\W\\.|;'
    -      },
    -      {
    -        className: 'class',
    -        begin: '^(\\s*)?(class|instance)\\b',
    -        end: 'where',
    -        keywords: 'class family instance where',
    -        contains: [
    -          CONSTRUCTOR,
    -          LIST,
    -          COMMENT
    -        ]
    -      },
    -      {
    -        className: 'class',
    -        begin: '\\b(data|(new)?type)\\b',
    -        end: '$',
    -        keywords: 'data family type newtype deriving',
    -        contains: [
    -          PRAGMA,
    -          CONSTRUCTOR,
    -          LIST,
    -          RECORD,
    -          COMMENT
    -        ]
    -      },
    -      {
    -        beginKeywords: 'default',
    -        end: '$',
    -        contains: [
    -          CONSTRUCTOR,
    -          LIST,
    -          COMMENT
    -        ]
    -      },
    -      {
    -        beginKeywords: 'infix infixl infixr',
    -        end: '$',
    -        contains: [
    -          hljs.C_NUMBER_MODE,
    -          COMMENT
    -        ]
    -      },
    -      {
    -        begin: '\\bforeign\\b',
    -        end: '$',
    -        keywords: 'foreign import export ccall stdcall cplusplus jvm ' +
    -                  'dotnet safe unsafe',
    -        contains: [
    -          CONSTRUCTOR,
    -          hljs.QUOTE_STRING_MODE,
    -          COMMENT
    -        ]
    -      },
    -      {
    -        className: 'meta',
    -        begin: '#!\\/usr\\/bin\\/env\ runhaskell',
    -        end: '$'
    -      },
    -      // "Whitespaces".
    -      PRAGMA,
    -      PREPROCESSOR,
    -
    -      // Literals and names.
    -
    -      // TODO: characters.
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.C_NUMBER_MODE,
    -      CONSTRUCTOR,
    -      hljs.inherit(hljs.TITLE_MODE, {
    -        begin: '^[_a-z][\\w\']*'
    -      }),
    -      COMMENT,
    -      { // No markup, relevance booster
    -        begin: '->|<-'
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = haskell;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/haxe.js b/claude-code-source/node_modules/highlight.js/lib/languages/haxe.js
    deleted file mode 100644
    index 10045b37..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/haxe.js
    +++ /dev/null
    @@ -1,157 +0,0 @@
    -/*
    -Language: Haxe
    -Description: Haxe is an open source toolkit based on a modern, high level, strictly typed programming language.
    -Author: Christopher Kaster  (Based on the actionscript.js language file by Alexander Myadzel)
    -Contributors: Kenton Hamaluik 
    -Website: https://haxe.org
    -*/
    -
    -function haxe(hljs) {
    -
    -  const HAXE_BASIC_TYPES = 'Int Float String Bool Dynamic Void Array ';
    -
    -  return {
    -    name: 'Haxe',
    -    aliases: ['hx'],
    -    keywords: {
    -      keyword: 'break case cast catch continue default do dynamic else enum extern ' +
    -               'for function here if import in inline never new override package private get set ' +
    -               'public return static super switch this throw trace try typedef untyped using var while ' +
    -               HAXE_BASIC_TYPES,
    -      built_in:
    -        'trace this',
    -      literal:
    -        'true false null _'
    -    },
    -    contains: [
    -      {
    -        className: 'string', // interpolate-able strings
    -        begin: '\'',
    -        end: '\'',
    -        contains: [
    -          hljs.BACKSLASH_ESCAPE,
    -          {
    -            className: 'subst', // interpolation
    -            begin: '\\$\\{',
    -            end: '\\}'
    -          },
    -          {
    -            className: 'subst', // interpolation
    -            begin: '\\$',
    -            end: /\W\}/
    -          }
    -        ]
    -      },
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.C_NUMBER_MODE,
    -      {
    -        className: 'meta', // compiler meta
    -        begin: '@:',
    -        end: '$'
    -      },
    -      {
    -        className: 'meta', // compiler conditionals
    -        begin: '#',
    -        end: '$',
    -        keywords: {
    -          'meta-keyword': 'if else elseif end error'
    -        }
    -      },
    -      {
    -        className: 'type', // function types
    -        begin: ':[ \t]*',
    -        end: '[^A-Za-z0-9_ \t\\->]',
    -        excludeBegin: true,
    -        excludeEnd: true,
    -        relevance: 0
    -      },
    -      {
    -        className: 'type', // types
    -        begin: ':[ \t]*',
    -        end: '\\W',
    -        excludeBegin: true,
    -        excludeEnd: true
    -      },
    -      {
    -        className: 'type', // instantiation
    -        begin: 'new *',
    -        end: '\\W',
    -        excludeBegin: true,
    -        excludeEnd: true
    -      },
    -      {
    -        className: 'class', // enums
    -        beginKeywords: 'enum',
    -        end: '\\{',
    -        contains: [hljs.TITLE_MODE]
    -      },
    -      {
    -        className: 'class', // abstracts
    -        beginKeywords: 'abstract',
    -        end: '[\\{$]',
    -        contains: [
    -          {
    -            className: 'type',
    -            begin: '\\(',
    -            end: '\\)',
    -            excludeBegin: true,
    -            excludeEnd: true
    -          },
    -          {
    -            className: 'type',
    -            begin: 'from +',
    -            end: '\\W',
    -            excludeBegin: true,
    -            excludeEnd: true
    -          },
    -          {
    -            className: 'type',
    -            begin: 'to +',
    -            end: '\\W',
    -            excludeBegin: true,
    -            excludeEnd: true
    -          },
    -          hljs.TITLE_MODE
    -        ],
    -        keywords: {
    -          keyword: 'abstract from to'
    -        }
    -      },
    -      {
    -        className: 'class', // classes
    -        begin: '\\b(class|interface) +',
    -        end: '[\\{$]',
    -        excludeEnd: true,
    -        keywords: 'class interface',
    -        contains: [
    -          {
    -            className: 'keyword',
    -            begin: '\\b(extends|implements) +',
    -            keywords: 'extends implements',
    -            contains: [
    -              {
    -                className: 'type',
    -                begin: hljs.IDENT_RE,
    -                relevance: 0
    -              }
    -            ]
    -          },
    -          hljs.TITLE_MODE
    -        ]
    -      },
    -      {
    -        className: 'function',
    -        beginKeywords: 'function',
    -        end: '\\(',
    -        excludeEnd: true,
    -        illegal: '\\S',
    -        contains: [hljs.TITLE_MODE]
    -      }
    -    ],
    -    illegal: /<\//
    -  };
    -}
    -
    -module.exports = haxe;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/hsp.js b/claude-code-source/node_modules/highlight.js/lib/languages/hsp.js
    deleted file mode 100644
    index d2c09d6c..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/hsp.js
    +++ /dev/null
    @@ -1,65 +0,0 @@
    -/*
    -Language: HSP
    -Author: prince 
    -Website: https://en.wikipedia.org/wiki/Hot_Soup_Processor
    -Category: scripting
    -*/
    -
    -function hsp(hljs) {
    -  return {
    -    name: 'HSP',
    -    case_insensitive: true,
    -    keywords: {
    -      $pattern: /[\w._]+/,
    -      keyword: 'goto gosub return break repeat loop continue wait await dim sdim foreach dimtype dup dupptr end stop newmod delmod mref run exgoto on mcall assert logmes newlab resume yield onexit onerror onkey onclick oncmd exist delete mkdir chdir dirlist bload bsave bcopy memfile if else poke wpoke lpoke getstr chdpm memexpand memcpy memset notesel noteadd notedel noteload notesave randomize noteunsel noteget split strrep setease button chgdisp exec dialog mmload mmplay mmstop mci pset pget syscolor mes print title pos circle cls font sysfont objsize picload color palcolor palette redraw width gsel gcopy gzoom gmode bmpsave hsvcolor getkey listbox chkbox combox input mesbox buffer screen bgscr mouse objsel groll line clrobj boxf objprm objmode stick grect grotate gsquare gradf objimage objskip objenable celload celdiv celput newcom querycom delcom cnvstow comres axobj winobj sendmsg comevent comevarg sarrayconv callfunc cnvwtos comevdisp libptr system hspstat hspver stat cnt err strsize looplev sublev iparam wparam lparam refstr refdval int rnd strlen length length2 length3 length4 vartype gettime peek wpeek lpeek varptr varuse noteinfo instr abs limit getease str strmid strf getpath strtrim sin cos tan atan sqrt double absf expf logf limitf powf geteasef mousex mousey mousew hwnd hinstance hdc ginfo objinfo dirinfo sysinfo thismod __hspver__ __hsp30__ __date__ __time__ __line__ __file__ _debug __hspdef__ and or xor not screen_normal screen_palette screen_hide screen_fixedsize screen_tool screen_frame gmode_gdi gmode_mem gmode_rgb0 gmode_alpha gmode_rgb0alpha gmode_add gmode_sub gmode_pixela ginfo_mx ginfo_my ginfo_act ginfo_sel ginfo_wx1 ginfo_wy1 ginfo_wx2 ginfo_wy2 ginfo_vx ginfo_vy ginfo_sizex ginfo_sizey ginfo_winx ginfo_winy ginfo_mesx ginfo_mesy ginfo_r ginfo_g ginfo_b ginfo_paluse ginfo_dispx ginfo_dispy ginfo_cx ginfo_cy ginfo_intid ginfo_newid ginfo_sx ginfo_sy objinfo_mode objinfo_bmscr objinfo_hwnd notemax notesize dir_cur dir_exe dir_win dir_sys dir_cmdline dir_desktop dir_mydoc dir_tv font_normal font_bold font_italic font_underline font_strikeout font_antialias objmode_normal objmode_guifont objmode_usefont gsquare_grad msgothic msmincho do until while wend for next _break _continue switch case default swbreak swend ddim ldim alloc m_pi rad2deg deg2rad ease_linear ease_quad_in ease_quad_out ease_quad_inout ease_cubic_in ease_cubic_out ease_cubic_inout ease_quartic_in ease_quartic_out ease_quartic_inout ease_bounce_in ease_bounce_out ease_bounce_inout ease_shake_in ease_shake_out ease_shake_inout ease_loop'
    -    },
    -    contains: [
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.APOS_STRING_MODE,
    -
    -      {
    -        // multi-line string
    -        className: 'string',
    -        begin: /\{"/,
    -        end: /"\}/,
    -        contains: [hljs.BACKSLASH_ESCAPE]
    -      },
    -
    -      hljs.COMMENT(';', '$', {
    -        relevance: 0
    -      }),
    -
    -      {
    -        // pre-processor
    -        className: 'meta',
    -        begin: '#',
    -        end: '$',
    -        keywords: {
    -          'meta-keyword': 'addion cfunc cmd cmpopt comfunc const defcfunc deffunc define else endif enum epack func global if ifdef ifndef include modcfunc modfunc modinit modterm module pack packopt regcmd runtime undef usecom uselib'
    -        },
    -        contains: [
    -          hljs.inherit(hljs.QUOTE_STRING_MODE, {
    -            className: 'meta-string'
    -          }),
    -          hljs.NUMBER_MODE,
    -          hljs.C_NUMBER_MODE,
    -          hljs.C_LINE_COMMENT_MODE,
    -          hljs.C_BLOCK_COMMENT_MODE
    -        ]
    -      },
    -
    -      {
    -        // label
    -        className: 'symbol',
    -        begin: '^\\*(\\w+|@)'
    -      },
    -
    -      hljs.NUMBER_MODE,
    -      hljs.C_NUMBER_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = hsp;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/htmlbars.js b/claude-code-source/node_modules/highlight.js/lib/languages/htmlbars.js
    deleted file mode 100644
    index 7fb718c2..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/htmlbars.js
    +++ /dev/null
    @@ -1,352 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function anyNumberOfTimes(re) {
    -  return concat('(', re, ')*');
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function optional(re) {
    -  return concat('(', re, ')?');
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/**
    - * Any of the passed expresssions may match
    - *
    - * Creates a huge this | this | that | that match
    - * @param {(RegExp | string)[] } args
    - * @returns {string}
    - */
    -function either(...args) {
    -  const joined = '(' + args.map((x) => source(x)).join("|") + ")";
    -  return joined;
    -}
    -
    -/*
    -Language: Handlebars
    -Requires: xml.js
    -Author: Robin Ward 
    -Description: Matcher for Handlebars as well as EmberJS additions.
    -Website: https://handlebarsjs.com
    -Category: template
    -*/
    -
    -function handlebars(hljs) {
    -  const BUILT_INS = {
    -    'builtin-name': [
    -      'action',
    -      'bindattr',
    -      'collection',
    -      'component',
    -      'concat',
    -      'debugger',
    -      'each',
    -      'each-in',
    -      'get',
    -      'hash',
    -      'if',
    -      'in',
    -      'input',
    -      'link-to',
    -      'loc',
    -      'log',
    -      'lookup',
    -      'mut',
    -      'outlet',
    -      'partial',
    -      'query-params',
    -      'render',
    -      'template',
    -      'textarea',
    -      'unbound',
    -      'unless',
    -      'view',
    -      'with',
    -      'yield'
    -    ]
    -  };
    -
    -  const LITERALS = {
    -    literal: [
    -      'true',
    -      'false',
    -      'undefined',
    -      'null'
    -    ]
    -  };
    -
    -  // as defined in https://handlebarsjs.com/guide/expressions.html#literal-segments
    -  // this regex matches literal segments like ' abc ' or [ abc ] as well as helpers and paths
    -  // like a/b, ./abc/cde, and abc.bcd
    -
    -  const DOUBLE_QUOTED_ID_REGEX = /""|"[^"]+"/;
    -  const SINGLE_QUOTED_ID_REGEX = /''|'[^']+'/;
    -  const BRACKET_QUOTED_ID_REGEX = /\[\]|\[[^\]]+\]/;
    -  const PLAIN_ID_REGEX = /[^\s!"#%&'()*+,.\/;<=>@\[\\\]^`{|}~]+/;
    -  const PATH_DELIMITER_REGEX = /(\.|\/)/;
    -  const ANY_ID = either(
    -    DOUBLE_QUOTED_ID_REGEX,
    -    SINGLE_QUOTED_ID_REGEX,
    -    BRACKET_QUOTED_ID_REGEX,
    -    PLAIN_ID_REGEX
    -    );
    -
    -  const IDENTIFIER_REGEX = concat(
    -    optional(/\.|\.\/|\//), // relative or absolute path
    -    ANY_ID,
    -    anyNumberOfTimes(concat(
    -      PATH_DELIMITER_REGEX,
    -      ANY_ID
    -    ))
    -  );
    -
    -  // identifier followed by a equal-sign (without the equal sign)
    -  const HASH_PARAM_REGEX = concat(
    -    '(',
    -    BRACKET_QUOTED_ID_REGEX, '|',
    -    PLAIN_ID_REGEX,
    -    ')(?==)'
    -  );
    -
    -  const HELPER_NAME_OR_PATH_EXPRESSION = {
    -    begin: IDENTIFIER_REGEX,
    -    lexemes: /[\w.\/]+/
    -  };
    -
    -  const HELPER_PARAMETER = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, {
    -    keywords: LITERALS
    -  });
    -
    -  const SUB_EXPRESSION = {
    -    begin: /\(/,
    -    end: /\)/
    -    // the "contains" is added below when all necessary sub-modes are defined
    -  };
    -
    -  const HASH = {
    -    // fka "attribute-assignment", parameters of the form 'key=value'
    -    className: 'attr',
    -    begin: HASH_PARAM_REGEX,
    -    relevance: 0,
    -    starts: {
    -      begin: /=/,
    -      end: /=/,
    -      starts: {
    -        contains: [
    -          hljs.NUMBER_MODE,
    -          hljs.QUOTE_STRING_MODE,
    -          hljs.APOS_STRING_MODE,
    -          HELPER_PARAMETER,
    -          SUB_EXPRESSION
    -        ]
    -      }
    -    }
    -  };
    -
    -  const BLOCK_PARAMS = {
    -    // parameters of the form '{{#with x as | y |}}...{{/with}}'
    -    begin: /as\s+\|/,
    -    keywords: {
    -      keyword: 'as'
    -    },
    -    end: /\|/,
    -    contains: [
    -      {
    -        // define sub-mode in order to prevent highlighting of block-parameter named "as"
    -        begin: /\w+/
    -      }
    -    ]
    -  };
    -
    -  const HELPER_PARAMETERS = {
    -    contains: [
    -      hljs.NUMBER_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.APOS_STRING_MODE,
    -      BLOCK_PARAMS,
    -      HASH,
    -      HELPER_PARAMETER,
    -      SUB_EXPRESSION
    -    ],
    -    returnEnd: true
    -    // the property "end" is defined through inheritance when the mode is used. If depends
    -    // on the surrounding mode, but "endsWithParent" does not work here (i.e. it includes the
    -    // end-token of the surrounding mode)
    -  };
    -
    -  const SUB_EXPRESSION_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, {
    -    className: 'name',
    -    keywords: BUILT_INS,
    -    starts: hljs.inherit(HELPER_PARAMETERS, {
    -      end: /\)/
    -    })
    -  });
    -
    -  SUB_EXPRESSION.contains = [SUB_EXPRESSION_CONTENTS];
    -
    -  const OPENING_BLOCK_MUSTACHE_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, {
    -    keywords: BUILT_INS,
    -    className: 'name',
    -    starts: hljs.inherit(HELPER_PARAMETERS, {
    -      end: /\}\}/
    -    })
    -  });
    -
    -  const CLOSING_BLOCK_MUSTACHE_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, {
    -    keywords: BUILT_INS,
    -    className: 'name'
    -  });
    -
    -  const BASIC_MUSTACHE_CONTENTS = hljs.inherit(HELPER_NAME_OR_PATH_EXPRESSION, {
    -    className: 'name',
    -    keywords: BUILT_INS,
    -    starts: hljs.inherit(HELPER_PARAMETERS, {
    -      end: /\}\}/
    -    })
    -  });
    -
    -  const ESCAPE_MUSTACHE_WITH_PRECEEDING_BACKSLASH = {
    -    begin: /\\\{\{/,
    -    skip: true
    -  };
    -  const PREVENT_ESCAPE_WITH_ANOTHER_PRECEEDING_BACKSLASH = {
    -    begin: /\\\\(?=\{\{)/,
    -    skip: true
    -  };
    -
    -  return {
    -    name: 'Handlebars',
    -    aliases: [
    -      'hbs',
    -      'html.hbs',
    -      'html.handlebars',
    -      'htmlbars'
    -    ],
    -    case_insensitive: true,
    -    subLanguage: 'xml',
    -    contains: [
    -      ESCAPE_MUSTACHE_WITH_PRECEEDING_BACKSLASH,
    -      PREVENT_ESCAPE_WITH_ANOTHER_PRECEEDING_BACKSLASH,
    -      hljs.COMMENT(/\{\{!--/, /--\}\}/),
    -      hljs.COMMENT(/\{\{!/, /\}\}/),
    -      {
    -        // open raw block "{{{{raw}}}} content not evaluated {{{{/raw}}}}"
    -        className: 'template-tag',
    -        begin: /\{\{\{\{(?!\/)/,
    -        end: /\}\}\}\}/,
    -        contains: [OPENING_BLOCK_MUSTACHE_CONTENTS],
    -        starts: {
    -          end: /\{\{\{\{\//,
    -          returnEnd: true,
    -          subLanguage: 'xml'
    -        }
    -      },
    -      {
    -        // close raw block
    -        className: 'template-tag',
    -        begin: /\{\{\{\{\//,
    -        end: /\}\}\}\}/,
    -        contains: [CLOSING_BLOCK_MUSTACHE_CONTENTS]
    -      },
    -      {
    -        // open block statement
    -        className: 'template-tag',
    -        begin: /\{\{#/,
    -        end: /\}\}/,
    -        contains: [OPENING_BLOCK_MUSTACHE_CONTENTS]
    -      },
    -      {
    -        className: 'template-tag',
    -        begin: /\{\{(?=else\}\})/,
    -        end: /\}\}/,
    -        keywords: 'else'
    -      },
    -      {
    -        className: 'template-tag',
    -        begin: /\{\{(?=else if)/,
    -        end: /\}\}/,
    -        keywords: 'else if'
    -      },
    -      {
    -        // closing block statement
    -        className: 'template-tag',
    -        begin: /\{\{\//,
    -        end: /\}\}/,
    -        contains: [CLOSING_BLOCK_MUSTACHE_CONTENTS]
    -      },
    -      {
    -        // template variable or helper-call that is NOT html-escaped
    -        className: 'template-variable',
    -        begin: /\{\{\{/,
    -        end: /\}\}\}/,
    -        contains: [BASIC_MUSTACHE_CONTENTS]
    -      },
    -      {
    -        // template variable or helper-call that is html-escaped
    -        className: 'template-variable',
    -        begin: /\{\{/,
    -        end: /\}\}/,
    -        contains: [BASIC_MUSTACHE_CONTENTS]
    -      }
    -    ]
    -  };
    -}
    -
    -/*
    - Language: HTMLBars (legacy)
    - Requires: xml.js
    - Description: Matcher for Handlebars as well as EmberJS additions.
    - Website: https://github.com/tildeio/htmlbars
    - Category: template
    - */
    -
    -function htmlbars(hljs) {
    -  const definition = handlebars(hljs);
    -
    -  definition.name = "HTMLbars";
    -
    -  // HACK: This lets handlebars do the auto-detection if it's been loaded (by
    -  // default the build script will load in alphabetical order) and if not (perhaps
    -  // an install is only using `htmlbars`, not `handlebars`) then this will still
    -  // allow HTMLBars to participate in the auto-detection
    -
    -  // worse case someone will have HTMLbars and handlebars competing for the same
    -  // content and will need to change their setup to only require handlebars, but
    -  // I don't consider this a breaking change
    -  if (hljs.getLanguage("handlebars")) {
    -    definition.disableAutodetect = true;
    -  }
    -
    -  return definition;
    -}
    -
    -module.exports = htmlbars;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/http.js b/claude-code-source/node_modules/highlight.js/lib/languages/http.js
    deleted file mode 100644
    index d9c3681a..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/http.js
    +++ /dev/null
    @@ -1,121 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: HTTP
    -Description: HTTP request and response headers with automatic body highlighting
    -Author: Ivan Sagalaev 
    -Category: common, protocols
    -Website: https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview
    -*/
    -
    -function http(hljs) {
    -  const VERSION = 'HTTP/(2|1\\.[01])';
    -  const HEADER_NAME = /[A-Za-z][A-Za-z0-9-]*/;
    -  const HEADER = {
    -    className: 'attribute',
    -    begin: concat('^', HEADER_NAME, '(?=\\:\\s)'),
    -    starts: {
    -      contains: [
    -        {
    -          className: "punctuation",
    -          begin: /: /,
    -          relevance: 0,
    -          starts: {
    -            end: '$',
    -            relevance: 0
    -          }
    -        }
    -      ]
    -    }
    -  };
    -  const HEADERS_AND_BODY = [
    -    HEADER,
    -    {
    -      begin: '\\n\\n',
    -      starts: { subLanguage: [], endsWithParent: true }
    -    }
    -  ];
    -
    -  return {
    -    name: 'HTTP',
    -    aliases: ['https'],
    -    illegal: /\S/,
    -    contains: [
    -      // response
    -      {
    -        begin: '^(?=' + VERSION + " \\d{3})",
    -        end: /$/,
    -        contains: [
    -          {
    -            className: "meta",
    -            begin: VERSION
    -          },
    -          {
    -            className: 'number', begin: '\\b\\d{3}\\b'
    -          }
    -        ],
    -        starts: {
    -          end: /\b\B/,
    -          illegal: /\S/,
    -          contains: HEADERS_AND_BODY
    -        }
    -      },
    -      // request
    -      {
    -        begin: '(?=^[A-Z]+ (.*?) ' + VERSION + '$)',
    -        end: /$/,
    -        contains: [
    -          {
    -            className: 'string',
    -            begin: ' ',
    -            end: ' ',
    -            excludeBegin: true,
    -            excludeEnd: true
    -          },
    -          {
    -            className: "meta",
    -            begin: VERSION
    -          },
    -          {
    -            className: 'keyword',
    -            begin: '[A-Z]+'
    -          }
    -        ],
    -        starts: {
    -          end: /\b\B/,
    -          illegal: /\S/,
    -          contains: HEADERS_AND_BODY
    -        }
    -      },
    -      // to allow headers to work even without a preamble
    -      hljs.inherit(HEADER, {
    -        relevance: 0
    -      })
    -    ]
    -  };
    -}
    -
    -module.exports = http;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/hy.js b/claude-code-source/node_modules/highlight.js/lib/languages/hy.js
    deleted file mode 100644
    index 43ff6ba3..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/hy.js
    +++ /dev/null
    @@ -1,109 +0,0 @@
    -/*
    -Language: Hy
    -Description: Hy is a wonderful dialect of Lisp that’s embedded in Python.
    -Author: Sergey Sobko 
    -Website: http://docs.hylang.org/en/stable/
    -Category: lisp
    -*/
    -
    -function hy(hljs) {
    -  var SYMBOLSTART = 'a-zA-Z_\\-!.?+*=<>&#\'';
    -  var SYMBOL_RE = '[' + SYMBOLSTART + '][' + SYMBOLSTART + '0-9/;:]*';
    -  var keywords = {
    -    $pattern: SYMBOL_RE,
    -    'builtin-name':
    -      // keywords
    -      '!= % %= & &= * ** **= *= *map ' +
    -      '+ += , --build-class-- --import-- -= . / // //= ' +
    -      '/= < << <<= <= = > >= >> >>= ' +
    -      '@ @= ^ ^= abs accumulate all and any ap-compose ' +
    -      'ap-dotimes ap-each ap-each-while ap-filter ap-first ap-if ap-last ap-map ap-map-when ap-pipe ' +
    -      'ap-reduce ap-reject apply as-> ascii assert assoc bin break butlast ' +
    -      'callable calling-module-name car case cdr chain chr coll? combinations compile ' +
    -      'compress cond cons cons? continue count curry cut cycle dec ' +
    -      'def default-method defclass defmacro defmacro-alias defmacro/g! defmain defmethod defmulti defn ' +
    -      'defn-alias defnc defnr defreader defseq del delattr delete-route dict-comp dir ' +
    -      'disassemble dispatch-reader-macro distinct divmod do doto drop drop-last drop-while empty? ' +
    -      'end-sequence eval eval-and-compile eval-when-compile even? every? except exec filter first ' +
    -      'flatten float? fn fnc fnr for for* format fraction genexpr ' +
    -      'gensym get getattr global globals group-by hasattr hash hex id ' +
    -      'identity if if* if-not if-python2 import in inc input instance? ' +
    -      'integer integer-char? integer? interleave interpose is is-coll is-cons is-empty is-even ' +
    -      'is-every is-float is-instance is-integer is-integer-char is-iterable is-iterator is-keyword is-neg is-none ' +
    -      'is-not is-numeric is-odd is-pos is-string is-symbol is-zero isinstance islice issubclass ' +
    -      'iter iterable? iterate iterator? keyword keyword? lambda last len let ' +
    -      'lif lif-not list* list-comp locals loop macro-error macroexpand macroexpand-1 macroexpand-all ' +
    -      'map max merge-with method-decorator min multi-decorator multicombinations name neg? next ' +
    -      'none? nonlocal not not-in not? nth numeric? oct odd? open ' +
    -      'or ord partition permutations pos? post-route postwalk pow prewalk print ' +
    -      'product profile/calls profile/cpu put-route quasiquote quote raise range read read-str ' +
    -      'recursive-replace reduce remove repeat repeatedly repr require rest round route ' +
    -      'route-with-methods rwm second seq set-comp setattr setv some sorted string ' +
    -      'string? sum switch symbol? take take-nth take-while tee try unless ' +
    -      'unquote unquote-splicing vars walk when while with with* with-decorator with-gensyms ' +
    -      'xi xor yield yield-from zero? zip zip-longest | |= ~'
    -   };
    -
    -  var SIMPLE_NUMBER_RE = '[-+]?\\d+(\\.\\d+)?';
    -
    -  var SYMBOL = {
    -    begin: SYMBOL_RE,
    -    relevance: 0
    -  };
    -  var NUMBER = {
    -    className: 'number', begin: SIMPLE_NUMBER_RE,
    -    relevance: 0
    -  };
    -  var STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null});
    -  var COMMENT = hljs.COMMENT(
    -    ';',
    -    '$',
    -    {
    -      relevance: 0
    -    }
    -  );
    -  var LITERAL = {
    -    className: 'literal',
    -    begin: /\b([Tt]rue|[Ff]alse|nil|None)\b/
    -  };
    -  var COLLECTION = {
    -    begin: '[\\[\\{]', end: '[\\]\\}]'
    -  };
    -  var HINT = {
    -    className: 'comment',
    -    begin: '\\^' + SYMBOL_RE
    -  };
    -  var HINT_COL = hljs.COMMENT('\\^\\{', '\\}');
    -  var KEY = {
    -    className: 'symbol',
    -    begin: '[:]{1,2}' + SYMBOL_RE
    -  };
    -  var LIST = {
    -    begin: '\\(', end: '\\)'
    -  };
    -  var BODY = {
    -    endsWithParent: true,
    -    relevance: 0
    -  };
    -  var NAME = {
    -    className: 'name',
    -    relevance: 0,
    -    keywords: keywords,
    -    begin: SYMBOL_RE,
    -    starts: BODY
    -  };
    -  var DEFAULT_CONTAINS = [LIST, STRING, HINT, HINT_COL, COMMENT, KEY, COLLECTION, NUMBER, LITERAL, SYMBOL];
    -
    -  LIST.contains = [hljs.COMMENT('comment', ''), NAME, BODY];
    -  BODY.contains = DEFAULT_CONTAINS;
    -  COLLECTION.contains = DEFAULT_CONTAINS;
    -
    -  return {
    -    name: 'Hy',
    -    aliases: ['hylang'],
    -    illegal: /\S/,
    -    contains: [hljs.SHEBANG(), LIST, STRING, HINT, HINT_COL, COMMENT, KEY, COLLECTION, NUMBER, LITERAL]
    -  };
    -}
    -
    -module.exports = hy;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/inform7.js b/claude-code-source/node_modules/highlight.js/lib/languages/inform7.js
    deleted file mode 100644
    index 8570468b..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/inform7.js
    +++ /dev/null
    @@ -1,70 +0,0 @@
    -/*
    -Language: Inform 7
    -Author: Bruno Dias 
    -Description: Language definition for Inform 7, a DSL for writing parser interactive fiction.
    -Website: http://inform7.com
    -*/
    -
    -function inform7(hljs) {
    -  const START_BRACKET = '\\[';
    -  const END_BRACKET = '\\]';
    -  return {
    -    name: 'Inform 7',
    -    aliases: ['i7'],
    -    case_insensitive: true,
    -    keywords: {
    -      // Some keywords more or less unique to I7, for relevance.
    -      keyword:
    -        // kind:
    -        'thing room person man woman animal container ' +
    -        'supporter backdrop door ' +
    -        // characteristic:
    -        'scenery open closed locked inside gender ' +
    -        // verb:
    -        'is are say understand ' +
    -        // misc keyword:
    -        'kind of rule'
    -    },
    -    contains: [
    -      {
    -        className: 'string',
    -        begin: '"',
    -        end: '"',
    -        relevance: 0,
    -        contains: [
    -          {
    -            className: 'subst',
    -            begin: START_BRACKET,
    -            end: END_BRACKET
    -          }
    -        ]
    -      },
    -      {
    -        className: 'section',
    -        begin: /^(Volume|Book|Part|Chapter|Section|Table)\b/,
    -        end: '$'
    -      },
    -      {
    -        // Rule definition
    -        // This is here for relevance.
    -        begin: /^(Check|Carry out|Report|Instead of|To|Rule|When|Before|After)\b/,
    -        end: ':',
    -        contains: [
    -          {
    -            // Rule name
    -            begin: '\\(This',
    -            end: '\\)'
    -          }
    -        ]
    -      },
    -      {
    -        className: 'comment',
    -        begin: START_BRACKET,
    -        end: END_BRACKET,
    -        contains: ['self']
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = inform7;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/ini.js b/claude-code-source/node_modules/highlight.js/lib/languages/ini.js
    deleted file mode 100644
    index 1e027314..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/ini.js
    +++ /dev/null
    @@ -1,173 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function lookahead(re) {
    -  return concat('(?=', re, ')');
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/**
    - * Any of the passed expresssions may match
    - *
    - * Creates a huge this | this | that | that match
    - * @param {(RegExp | string)[] } args
    - * @returns {string}
    - */
    -function either(...args) {
    -  const joined = '(' + args.map((x) => source(x)).join("|") + ")";
    -  return joined;
    -}
    -
    -/*
    -Language: TOML, also INI
    -Description: TOML aims to be a minimal configuration file format that's easy to read due to obvious semantics.
    -Contributors: Guillaume Gomez 
    -Category: common, config
    -Website: https://github.com/toml-lang/toml
    -*/
    -
    -function ini(hljs) {
    -  const NUMBERS = {
    -    className: 'number',
    -    relevance: 0,
    -    variants: [
    -      {
    -        begin: /([+-]+)?[\d]+_[\d_]+/
    -      },
    -      {
    -        begin: hljs.NUMBER_RE
    -      }
    -    ]
    -  };
    -  const COMMENTS = hljs.COMMENT();
    -  COMMENTS.variants = [
    -    {
    -      begin: /;/,
    -      end: /$/
    -    },
    -    {
    -      begin: /#/,
    -      end: /$/
    -    }
    -  ];
    -  const VARIABLES = {
    -    className: 'variable',
    -    variants: [
    -      {
    -        begin: /\$[\w\d"][\w\d_]*/
    -      },
    -      {
    -        begin: /\$\{(.*?)\}/
    -      }
    -    ]
    -  };
    -  const LITERALS = {
    -    className: 'literal',
    -    begin: /\bon|off|true|false|yes|no\b/
    -  };
    -  const STRINGS = {
    -    className: "string",
    -    contains: [hljs.BACKSLASH_ESCAPE],
    -    variants: [
    -      {
    -        begin: "'''",
    -        end: "'''",
    -        relevance: 10
    -      },
    -      {
    -        begin: '"""',
    -        end: '"""',
    -        relevance: 10
    -      },
    -      {
    -        begin: '"',
    -        end: '"'
    -      },
    -      {
    -        begin: "'",
    -        end: "'"
    -      }
    -    ]
    -  };
    -  const ARRAY = {
    -    begin: /\[/,
    -    end: /\]/,
    -    contains: [
    -      COMMENTS,
    -      LITERALS,
    -      VARIABLES,
    -      STRINGS,
    -      NUMBERS,
    -      'self'
    -    ],
    -    relevance: 0
    -  };
    -
    -  const BARE_KEY = /[A-Za-z0-9_-]+/;
    -  const QUOTED_KEY_DOUBLE_QUOTE = /"(\\"|[^"])*"/;
    -  const QUOTED_KEY_SINGLE_QUOTE = /'[^']*'/;
    -  const ANY_KEY = either(
    -    BARE_KEY, QUOTED_KEY_DOUBLE_QUOTE, QUOTED_KEY_SINGLE_QUOTE
    -  );
    -  const DOTTED_KEY = concat(
    -    ANY_KEY, '(\\s*\\.\\s*', ANY_KEY, ')*',
    -    lookahead(/\s*=\s*[^#\s]/)
    -  );
    -
    -  return {
    -    name: 'TOML, also INI',
    -    aliases: ['toml'],
    -    case_insensitive: true,
    -    illegal: /\S/,
    -    contains: [
    -      COMMENTS,
    -      {
    -        className: 'section',
    -        begin: /\[+/,
    -        end: /\]+/
    -      },
    -      {
    -        begin: DOTTED_KEY,
    -        className: 'attr',
    -        starts: {
    -          end: /$/,
    -          contains: [
    -            COMMENTS,
    -            ARRAY,
    -            LITERALS,
    -            VARIABLES,
    -            STRINGS,
    -            NUMBERS
    -          ]
    -        }
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = ini;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/irpf90.js b/claude-code-source/node_modules/highlight.js/lib/languages/irpf90.js
    deleted file mode 100644
    index 1f2a27af..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/irpf90.js
    +++ /dev/null
    @@ -1,141 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: IRPF90
    -Author: Anthony Scemama 
    -Description: IRPF90 is an open-source Fortran code generator
    -Website: http://irpf90.ups-tlse.fr
    -Category: scientific
    -*/
    -
    -/** @type LanguageFn */
    -function irpf90(hljs) {
    -  const PARAMS = {
    -    className: 'params',
    -    begin: '\\(',
    -    end: '\\)'
    -  };
    -
    -  // regex in both fortran and irpf90 should match
    -  const OPTIONAL_NUMBER_SUFFIX = /(_[a-z_\d]+)?/;
    -  const OPTIONAL_NUMBER_EXP = /([de][+-]?\d+)?/;
    -  const NUMBER = {
    -    className: 'number',
    -    variants: [
    -      {
    -        begin: concat(/\b\d+/, /\.(\d*)/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX)
    -      },
    -      {
    -        begin: concat(/\b\d+/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX)
    -      },
    -      {
    -        begin: concat(/\.\d+/, OPTIONAL_NUMBER_EXP, OPTIONAL_NUMBER_SUFFIX)
    -      }
    -    ],
    -    relevance: 0
    -  };
    -
    -  const F_KEYWORDS = {
    -    literal: '.False. .True.',
    -    keyword: 'kind do while private call intrinsic where elsewhere ' +
    -      'type endtype endmodule endselect endinterface end enddo endif if forall endforall only contains default return stop then ' +
    -      'public subroutine|10 function program .and. .or. .not. .le. .eq. .ge. .gt. .lt. ' +
    -      'goto save else use module select case ' +
    -      'access blank direct exist file fmt form formatted iostat name named nextrec number opened rec recl sequential status unformatted unit ' +
    -      'continue format pause cycle exit ' +
    -      'c_null_char c_alert c_backspace c_form_feed flush wait decimal round iomsg ' +
    -      'synchronous nopass non_overridable pass protected volatile abstract extends import ' +
    -      'non_intrinsic value deferred generic final enumerator class associate bind enum ' +
    -      'c_int c_short c_long c_long_long c_signed_char c_size_t c_int8_t c_int16_t c_int32_t c_int64_t c_int_least8_t c_int_least16_t ' +
    -      'c_int_least32_t c_int_least64_t c_int_fast8_t c_int_fast16_t c_int_fast32_t c_int_fast64_t c_intmax_t C_intptr_t c_float c_double ' +
    -      'c_long_double c_float_complex c_double_complex c_long_double_complex c_bool c_char c_null_ptr c_null_funptr ' +
    -      'c_new_line c_carriage_return c_horizontal_tab c_vertical_tab iso_c_binding c_loc c_funloc c_associated  c_f_pointer ' +
    -      'c_ptr c_funptr iso_fortran_env character_storage_size error_unit file_storage_size input_unit iostat_end iostat_eor ' +
    -      'numeric_storage_size output_unit c_f_procpointer ieee_arithmetic ieee_support_underflow_control ' +
    -      'ieee_get_underflow_mode ieee_set_underflow_mode newunit contiguous recursive ' +
    -      'pad position action delim readwrite eor advance nml interface procedure namelist include sequence elemental pure ' +
    -      'integer real character complex logical dimension allocatable|10 parameter ' +
    -      'external implicit|10 none double precision assign intent optional pointer ' +
    -      'target in out common equivalence data ' +
    -      // IRPF90 special keywords
    -      'begin_provider &begin_provider end_provider begin_shell end_shell begin_template end_template subst assert touch ' +
    -      'soft_touch provide no_dep free irp_if irp_else irp_endif irp_write irp_read',
    -    built_in: 'alog alog10 amax0 amax1 amin0 amin1 amod cabs ccos cexp clog csin csqrt dabs dacos dasin datan datan2 dcos dcosh ddim dexp dint ' +
    -      'dlog dlog10 dmax1 dmin1 dmod dnint dsign dsin dsinh dsqrt dtan dtanh float iabs idim idint idnint ifix isign max0 max1 min0 min1 sngl ' +
    -      'algama cdabs cdcos cdexp cdlog cdsin cdsqrt cqabs cqcos cqexp cqlog cqsin cqsqrt dcmplx dconjg derf derfc dfloat dgamma dimag dlgama ' +
    -      'iqint qabs qacos qasin qatan qatan2 qcmplx qconjg qcos qcosh qdim qerf qerfc qexp qgamma qimag qlgama qlog qlog10 qmax1 qmin1 qmod ' +
    -      'qnint qsign qsin qsinh qsqrt qtan qtanh abs acos aimag aint anint asin atan atan2 char cmplx conjg cos cosh exp ichar index int log ' +
    -      'log10 max min nint sign sin sinh sqrt tan tanh print write dim lge lgt lle llt mod nullify allocate deallocate ' +
    -      'adjustl adjustr all allocated any associated bit_size btest ceiling count cshift date_and_time digits dot_product ' +
    -      'eoshift epsilon exponent floor fraction huge iand ibclr ibits ibset ieor ior ishft ishftc lbound len_trim matmul ' +
    -      'maxexponent maxloc maxval merge minexponent minloc minval modulo mvbits nearest pack present product ' +
    -      'radix random_number random_seed range repeat reshape rrspacing scale scan selected_int_kind selected_real_kind ' +
    -      'set_exponent shape size spacing spread sum system_clock tiny transpose trim ubound unpack verify achar iachar transfer ' +
    -      'dble entry dprod cpu_time command_argument_count get_command get_command_argument get_environment_variable is_iostat_end ' +
    -      'ieee_arithmetic ieee_support_underflow_control ieee_get_underflow_mode ieee_set_underflow_mode ' +
    -      'is_iostat_eor move_alloc new_line selected_char_kind same_type_as extends_type_of ' +
    -      'acosh asinh atanh bessel_j0 bessel_j1 bessel_jn bessel_y0 bessel_y1 bessel_yn erf erfc erfc_scaled gamma log_gamma hypot norm2 ' +
    -      'atomic_define atomic_ref execute_command_line leadz trailz storage_size merge_bits ' +
    -      'bge bgt ble blt dshiftl dshiftr findloc iall iany iparity image_index lcobound ucobound maskl maskr ' +
    -      'num_images parity popcnt poppar shifta shiftl shiftr this_image ' +
    -      // IRPF90 special built_ins
    -      'IRP_ALIGN irp_here'
    -  };
    -  return {
    -    name: 'IRPF90',
    -    case_insensitive: true,
    -    keywords: F_KEYWORDS,
    -    illegal: /\/\*/,
    -    contains: [
    -      hljs.inherit(hljs.APOS_STRING_MODE, {
    -        className: 'string',
    -        relevance: 0
    -      }),
    -      hljs.inherit(hljs.QUOTE_STRING_MODE, {
    -        className: 'string',
    -        relevance: 0
    -      }),
    -      {
    -        className: 'function',
    -        beginKeywords: 'subroutine function program',
    -        illegal: '[${=\\n]',
    -        contains: [
    -          hljs.UNDERSCORE_TITLE_MODE,
    -          PARAMS
    -        ]
    -      },
    -      hljs.COMMENT('!', '$', {
    -        relevance: 0
    -      }),
    -      hljs.COMMENT('begin_doc', 'end_doc', {
    -        relevance: 10
    -      }),
    -      NUMBER
    -    ]
    -  };
    -}
    -
    -module.exports = irpf90;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/isbl.js b/claude-code-source/node_modules/highlight.js/lib/languages/isbl.js
    deleted file mode 100644
    index e76891b9..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/isbl.js
    +++ /dev/null
    @@ -1,3207 +0,0 @@
    -/*
    -Language: ISBL
    -Author: Dmitriy Tarasov 
    -Description: built-in language DIRECTUM
    -Category: enterprise
    -*/
    -
    -function isbl(hljs) {
    -  // Определение идентификаторов
    -  const UNDERSCORE_IDENT_RE = "[A-Za-zА-Яа-яёЁ_!][A-Za-zА-Яа-яёЁ_0-9]*";
    -
    -  // Определение имен функций
    -  const FUNCTION_NAME_IDENT_RE = "[A-Za-zА-Яа-яёЁ_][A-Za-zА-Яа-яёЁ_0-9]*";
    -
    -  // keyword : ключевые слова
    -  const KEYWORD =
    -    "and и else иначе endexcept endfinally endforeach конецвсе endif конецесли endwhile конецпока " +
    -    "except exitfor finally foreach все if если in в not не or или try while пока ";
    -
    -  // SYSRES Constants
    -  const sysres_constants =
    -    "SYSRES_CONST_ACCES_RIGHT_TYPE_EDIT " +
    -    "SYSRES_CONST_ACCES_RIGHT_TYPE_FULL " +
    -    "SYSRES_CONST_ACCES_RIGHT_TYPE_VIEW " +
    -    "SYSRES_CONST_ACCESS_MODE_REQUISITE_CODE " +
    -    "SYSRES_CONST_ACCESS_NO_ACCESS_VIEW " +
    -    "SYSRES_CONST_ACCESS_NO_ACCESS_VIEW_CODE " +
    -    "SYSRES_CONST_ACCESS_RIGHTS_ADD_REQUISITE_CODE " +
    -    "SYSRES_CONST_ACCESS_RIGHTS_ADD_REQUISITE_YES_CODE " +
    -    "SYSRES_CONST_ACCESS_RIGHTS_CHANGE_REQUISITE_CODE " +
    -    "SYSRES_CONST_ACCESS_RIGHTS_CHANGE_REQUISITE_YES_CODE " +
    -    "SYSRES_CONST_ACCESS_RIGHTS_DELETE_REQUISITE_CODE " +
    -    "SYSRES_CONST_ACCESS_RIGHTS_DELETE_REQUISITE_YES_CODE " +
    -    "SYSRES_CONST_ACCESS_RIGHTS_EXECUTE_REQUISITE_CODE " +
    -    "SYSRES_CONST_ACCESS_RIGHTS_EXECUTE_REQUISITE_YES_CODE " +
    -    "SYSRES_CONST_ACCESS_RIGHTS_NO_ACCESS_REQUISITE_CODE " +
    -    "SYSRES_CONST_ACCESS_RIGHTS_NO_ACCESS_REQUISITE_YES_CODE " +
    -    "SYSRES_CONST_ACCESS_RIGHTS_RATIFY_REQUISITE_CODE " +
    -    "SYSRES_CONST_ACCESS_RIGHTS_RATIFY_REQUISITE_YES_CODE " +
    -    "SYSRES_CONST_ACCESS_RIGHTS_REQUISITE_CODE " +
    -    "SYSRES_CONST_ACCESS_RIGHTS_VIEW " +
    -    "SYSRES_CONST_ACCESS_RIGHTS_VIEW_CODE " +
    -    "SYSRES_CONST_ACCESS_RIGHTS_VIEW_REQUISITE_CODE " +
    -    "SYSRES_CONST_ACCESS_RIGHTS_VIEW_REQUISITE_YES_CODE " +
    -    "SYSRES_CONST_ACCESS_TYPE_CHANGE " +
    -    "SYSRES_CONST_ACCESS_TYPE_CHANGE_CODE " +
    -    "SYSRES_CONST_ACCESS_TYPE_EXISTS " +
    -    "SYSRES_CONST_ACCESS_TYPE_EXISTS_CODE " +
    -    "SYSRES_CONST_ACCESS_TYPE_FULL " +
    -    "SYSRES_CONST_ACCESS_TYPE_FULL_CODE " +
    -    "SYSRES_CONST_ACCESS_TYPE_VIEW " +
    -    "SYSRES_CONST_ACCESS_TYPE_VIEW_CODE " +
    -    "SYSRES_CONST_ACTION_TYPE_ABORT " +
    -    "SYSRES_CONST_ACTION_TYPE_ACCEPT " +
    -    "SYSRES_CONST_ACTION_TYPE_ACCESS_RIGHTS " +
    -    "SYSRES_CONST_ACTION_TYPE_ADD_ATTACHMENT " +
    -    "SYSRES_CONST_ACTION_TYPE_CHANGE_CARD " +
    -    "SYSRES_CONST_ACTION_TYPE_CHANGE_KIND " +
    -    "SYSRES_CONST_ACTION_TYPE_CHANGE_STORAGE " +
    -    "SYSRES_CONST_ACTION_TYPE_CONTINUE " +
    -    "SYSRES_CONST_ACTION_TYPE_COPY " +
    -    "SYSRES_CONST_ACTION_TYPE_CREATE " +
    -    "SYSRES_CONST_ACTION_TYPE_CREATE_VERSION " +
    -    "SYSRES_CONST_ACTION_TYPE_DELETE " +
    -    "SYSRES_CONST_ACTION_TYPE_DELETE_ATTACHMENT " +
    -    "SYSRES_CONST_ACTION_TYPE_DELETE_VERSION " +
    -    "SYSRES_CONST_ACTION_TYPE_DISABLE_DELEGATE_ACCESS_RIGHTS " +
    -    "SYSRES_CONST_ACTION_TYPE_ENABLE_DELEGATE_ACCESS_RIGHTS " +
    -    "SYSRES_CONST_ACTION_TYPE_ENCRYPTION_BY_CERTIFICATE " +
    -    "SYSRES_CONST_ACTION_TYPE_ENCRYPTION_BY_CERTIFICATE_AND_PASSWORD " +
    -    "SYSRES_CONST_ACTION_TYPE_ENCRYPTION_BY_PASSWORD " +
    -    "SYSRES_CONST_ACTION_TYPE_EXPORT_WITH_LOCK " +
    -    "SYSRES_CONST_ACTION_TYPE_EXPORT_WITHOUT_LOCK " +
    -    "SYSRES_CONST_ACTION_TYPE_IMPORT_WITH_UNLOCK " +
    -    "SYSRES_CONST_ACTION_TYPE_IMPORT_WITHOUT_UNLOCK " +
    -    "SYSRES_CONST_ACTION_TYPE_LIFE_CYCLE_STAGE " +
    -    "SYSRES_CONST_ACTION_TYPE_LOCK " +
    -    "SYSRES_CONST_ACTION_TYPE_LOCK_FOR_SERVER " +
    -    "SYSRES_CONST_ACTION_TYPE_LOCK_MODIFY " +
    -    "SYSRES_CONST_ACTION_TYPE_MARK_AS_READED " +
    -    "SYSRES_CONST_ACTION_TYPE_MARK_AS_UNREADED " +
    -    "SYSRES_CONST_ACTION_TYPE_MODIFY " +
    -    "SYSRES_CONST_ACTION_TYPE_MODIFY_CARD " +
    -    "SYSRES_CONST_ACTION_TYPE_MOVE_TO_ARCHIVE " +
    -    "SYSRES_CONST_ACTION_TYPE_OFF_ENCRYPTION " +
    -    "SYSRES_CONST_ACTION_TYPE_PASSWORD_CHANGE " +
    -    "SYSRES_CONST_ACTION_TYPE_PERFORM " +
    -    "SYSRES_CONST_ACTION_TYPE_RECOVER_FROM_LOCAL_COPY " +
    -    "SYSRES_CONST_ACTION_TYPE_RESTART " +
    -    "SYSRES_CONST_ACTION_TYPE_RESTORE_FROM_ARCHIVE " +
    -    "SYSRES_CONST_ACTION_TYPE_REVISION " +
    -    "SYSRES_CONST_ACTION_TYPE_SEND_BY_MAIL " +
    -    "SYSRES_CONST_ACTION_TYPE_SIGN " +
    -    "SYSRES_CONST_ACTION_TYPE_START " +
    -    "SYSRES_CONST_ACTION_TYPE_UNLOCK " +
    -    "SYSRES_CONST_ACTION_TYPE_UNLOCK_FROM_SERVER " +
    -    "SYSRES_CONST_ACTION_TYPE_VERSION_STATE " +
    -    "SYSRES_CONST_ACTION_TYPE_VERSION_VISIBILITY " +
    -    "SYSRES_CONST_ACTION_TYPE_VIEW " +
    -    "SYSRES_CONST_ACTION_TYPE_VIEW_SHADOW_COPY " +
    -    "SYSRES_CONST_ACTION_TYPE_WORKFLOW_DESCRIPTION_MODIFY " +
    -    "SYSRES_CONST_ACTION_TYPE_WRITE_HISTORY " +
    -    "SYSRES_CONST_ACTIVE_VERSION_STATE_PICK_VALUE " +
    -    "SYSRES_CONST_ADD_REFERENCE_MODE_NAME " +
    -    "SYSRES_CONST_ADDITION_REQUISITE_CODE " +
    -    "SYSRES_CONST_ADDITIONAL_PARAMS_REQUISITE_CODE " +
    -    "SYSRES_CONST_ADITIONAL_JOB_END_DATE_REQUISITE_NAME " +
    -    "SYSRES_CONST_ADITIONAL_JOB_READ_REQUISITE_NAME " +
    -    "SYSRES_CONST_ADITIONAL_JOB_START_DATE_REQUISITE_NAME " +
    -    "SYSRES_CONST_ADITIONAL_JOB_STATE_REQUISITE_NAME " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_ADDING_USER_TO_GROUP_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_ADDING_USER_TO_GROUP_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_COMP_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_COMP_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_GROUP_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_GROUP_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_USER_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_CREATION_USER_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_DATABASE_USER_CREATION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_DATABASE_USER_CREATION_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_DATABASE_USER_DELETION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_DATABASE_USER_DELETION_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_COMP_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_COMP_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_GROUP_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_GROUP_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_USER_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_USER_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_USER_FROM_GROUP_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_DELETION_USER_FROM_GROUP_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_FILTERER_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_FILTERER_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_FILTERER_RESTRICTION_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_FILTERER_RESTRICTION_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_PRIVILEGE_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_PRIVILEGE_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_RIGHTS_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_GRANTING_RIGHTS_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_IS_MAIN_SERVER_CHANGED_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_IS_MAIN_SERVER_CHANGED_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_IS_PUBLIC_CHANGED_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_IS_PUBLIC_CHANGED_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_FILTERER_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_FILTERER_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_FILTERER_RESTRICTION_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_FILTERER_RESTRICTION_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_PRIVILEGE_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_PRIVILEGE_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_RIGHTS_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_REMOVING_RIGHTS_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_SERVER_LOGIN_CREATION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_SERVER_LOGIN_CREATION_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_SERVER_LOGIN_DELETION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_SERVER_LOGIN_DELETION_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_CATEGORY_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_CATEGORY_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_COMP_TITLE_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_COMP_TITLE_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_FULL_NAME_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_FULL_NAME_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_GROUP_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_GROUP_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_PARENT_GROUP_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_PARENT_GROUP_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_AUTH_TYPE_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_AUTH_TYPE_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_LOGIN_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_LOGIN_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_STATUS_ACTION " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_UPDATING_USER_STATUS_ACTION_CODE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_USER_PASSWORD_CHANGE " +
    -    "SYSRES_CONST_ADMINISTRATION_HISTORY_USER_PASSWORD_CHANGE_ACTION " +
    -    "SYSRES_CONST_ALL_ACCEPT_CONDITION_RUS " +
    -    "SYSRES_CONST_ALL_USERS_GROUP " +
    -    "SYSRES_CONST_ALL_USERS_GROUP_NAME " +
    -    "SYSRES_CONST_ALL_USERS_SERVER_GROUP_NAME " +
    -    "SYSRES_CONST_ALLOWED_ACCESS_TYPE_CODE " +
    -    "SYSRES_CONST_ALLOWED_ACCESS_TYPE_NAME " +
    -    "SYSRES_CONST_APP_VIEWER_TYPE_REQUISITE_CODE " +
    -    "SYSRES_CONST_APPROVING_SIGNATURE_NAME " +
    -    "SYSRES_CONST_APPROVING_SIGNATURE_REQUISITE_CODE " +
    -    "SYSRES_CONST_ASSISTANT_SUBSTITUE_TYPE " +
    -    "SYSRES_CONST_ASSISTANT_SUBSTITUE_TYPE_CODE " +
    -    "SYSRES_CONST_ATTACH_TYPE_COMPONENT_TOKEN " +
    -    "SYSRES_CONST_ATTACH_TYPE_DOC " +
    -    "SYSRES_CONST_ATTACH_TYPE_EDOC " +
    -    "SYSRES_CONST_ATTACH_TYPE_FOLDER " +
    -    "SYSRES_CONST_ATTACH_TYPE_JOB " +
    -    "SYSRES_CONST_ATTACH_TYPE_REFERENCE " +
    -    "SYSRES_CONST_ATTACH_TYPE_TASK " +
    -    "SYSRES_CONST_AUTH_ENCODED_PASSWORD " +
    -    "SYSRES_CONST_AUTH_ENCODED_PASSWORD_CODE " +
    -    "SYSRES_CONST_AUTH_NOVELL " +
    -    "SYSRES_CONST_AUTH_PASSWORD " +
    -    "SYSRES_CONST_AUTH_PASSWORD_CODE " +
    -    "SYSRES_CONST_AUTH_WINDOWS " +
    -    "SYSRES_CONST_AUTHENTICATING_SIGNATURE_NAME " +
    -    "SYSRES_CONST_AUTHENTICATING_SIGNATURE_REQUISITE_CODE " +
    -    "SYSRES_CONST_AUTO_ENUM_METHOD_FLAG " +
    -    "SYSRES_CONST_AUTO_NUMERATION_CODE " +
    -    "SYSRES_CONST_AUTO_STRONG_ENUM_METHOD_FLAG " +
    -    "SYSRES_CONST_AUTOTEXT_NAME_REQUISITE_CODE " +
    -    "SYSRES_CONST_AUTOTEXT_TEXT_REQUISITE_CODE " +
    -    "SYSRES_CONST_AUTOTEXT_USAGE_ALL " +
    -    "SYSRES_CONST_AUTOTEXT_USAGE_ALL_CODE " +
    -    "SYSRES_CONST_AUTOTEXT_USAGE_SIGN " +
    -    "SYSRES_CONST_AUTOTEXT_USAGE_SIGN_CODE " +
    -    "SYSRES_CONST_AUTOTEXT_USAGE_WORK " +
    -    "SYSRES_CONST_AUTOTEXT_USAGE_WORK_CODE " +
    -    "SYSRES_CONST_AUTOTEXT_USE_ANYWHERE_CODE " +
    -    "SYSRES_CONST_AUTOTEXT_USE_ON_SIGNING_CODE " +
    -    "SYSRES_CONST_AUTOTEXT_USE_ON_WORK_CODE " +
    -    "SYSRES_CONST_BEGIN_DATE_REQUISITE_CODE " +
    -    "SYSRES_CONST_BLACK_LIFE_CYCLE_STAGE_FONT_COLOR " +
    -    "SYSRES_CONST_BLUE_LIFE_CYCLE_STAGE_FONT_COLOR " +
    -    "SYSRES_CONST_BTN_PART " +
    -    "SYSRES_CONST_CALCULATED_ROLE_TYPE_CODE " +
    -    "SYSRES_CONST_CALL_TYPE_VARIABLE_BUTTON_VALUE " +
    -    "SYSRES_CONST_CALL_TYPE_VARIABLE_PROGRAM_VALUE " +
    -    "SYSRES_CONST_CANCEL_MESSAGE_FUNCTION_RESULT " +
    -    "SYSRES_CONST_CARD_PART " +
    -    "SYSRES_CONST_CARD_REFERENCE_MODE_NAME " +
    -    "SYSRES_CONST_CERTIFICATE_TYPE_REQUISITE_ENCRYPT_VALUE " +
    -    "SYSRES_CONST_CERTIFICATE_TYPE_REQUISITE_SIGN_AND_ENCRYPT_VALUE " +
    -    "SYSRES_CONST_CERTIFICATE_TYPE_REQUISITE_SIGN_VALUE " +
    -    "SYSRES_CONST_CHECK_PARAM_VALUE_DATE_PARAM_TYPE " +
    -    "SYSRES_CONST_CHECK_PARAM_VALUE_FLOAT_PARAM_TYPE " +
    -    "SYSRES_CONST_CHECK_PARAM_VALUE_INTEGER_PARAM_TYPE " +
    -    "SYSRES_CONST_CHECK_PARAM_VALUE_PICK_PARAM_TYPE " +
    -    "SYSRES_CONST_CHECK_PARAM_VALUE_REEFRENCE_PARAM_TYPE " +
    -    "SYSRES_CONST_CLOSED_RECORD_FLAG_VALUE_FEMININE " +
    -    "SYSRES_CONST_CLOSED_RECORD_FLAG_VALUE_MASCULINE " +
    -    "SYSRES_CONST_CODE_COMPONENT_TYPE_ADMIN " +
    -    "SYSRES_CONST_CODE_COMPONENT_TYPE_DEVELOPER " +
    -    "SYSRES_CONST_CODE_COMPONENT_TYPE_DOCS " +
    -    "SYSRES_CONST_CODE_COMPONENT_TYPE_EDOC_CARDS " +
    -    "SYSRES_CONST_CODE_COMPONENT_TYPE_EXTERNAL_EXECUTABLE " +
    -    "SYSRES_CONST_CODE_COMPONENT_TYPE_OTHER " +
    -    "SYSRES_CONST_CODE_COMPONENT_TYPE_REFERENCE " +
    -    "SYSRES_CONST_CODE_COMPONENT_TYPE_REPORT " +
    -    "SYSRES_CONST_CODE_COMPONENT_TYPE_SCRIPT " +
    -    "SYSRES_CONST_CODE_COMPONENT_TYPE_URL " +
    -    "SYSRES_CONST_CODE_REQUISITE_ACCESS " +
    -    "SYSRES_CONST_CODE_REQUISITE_CODE " +
    -    "SYSRES_CONST_CODE_REQUISITE_COMPONENT " +
    -    "SYSRES_CONST_CODE_REQUISITE_DESCRIPTION " +
    -    "SYSRES_CONST_CODE_REQUISITE_EXCLUDE_COMPONENT " +
    -    "SYSRES_CONST_CODE_REQUISITE_RECORD " +
    -    "SYSRES_CONST_COMMENT_REQ_CODE " +
    -    "SYSRES_CONST_COMMON_SETTINGS_REQUISITE_CODE " +
    -    "SYSRES_CONST_COMP_CODE_GRD " +
    -    "SYSRES_CONST_COMPONENT_GROUP_TYPE_REQUISITE_CODE " +
    -    "SYSRES_CONST_COMPONENT_TYPE_ADMIN_COMPONENTS " +
    -    "SYSRES_CONST_COMPONENT_TYPE_DEVELOPER_COMPONENTS " +
    -    "SYSRES_CONST_COMPONENT_TYPE_DOCS " +
    -    "SYSRES_CONST_COMPONENT_TYPE_EDOC_CARDS " +
    -    "SYSRES_CONST_COMPONENT_TYPE_EDOCS " +
    -    "SYSRES_CONST_COMPONENT_TYPE_EXTERNAL_EXECUTABLE " +
    -    "SYSRES_CONST_COMPONENT_TYPE_OTHER " +
    -    "SYSRES_CONST_COMPONENT_TYPE_REFERENCE_TYPES " +
    -    "SYSRES_CONST_COMPONENT_TYPE_REFERENCES " +
    -    "SYSRES_CONST_COMPONENT_TYPE_REPORTS " +
    -    "SYSRES_CONST_COMPONENT_TYPE_SCRIPTS " +
    -    "SYSRES_CONST_COMPONENT_TYPE_URL " +
    -    "SYSRES_CONST_COMPONENTS_REMOTE_SERVERS_VIEW_CODE " +
    -    "SYSRES_CONST_CONDITION_BLOCK_DESCRIPTION " +
    -    "SYSRES_CONST_CONST_FIRM_STATUS_COMMON " +
    -    "SYSRES_CONST_CONST_FIRM_STATUS_INDIVIDUAL " +
    -    "SYSRES_CONST_CONST_NEGATIVE_VALUE " +
    -    "SYSRES_CONST_CONST_POSITIVE_VALUE " +
    -    "SYSRES_CONST_CONST_SERVER_STATUS_DONT_REPLICATE " +
    -    "SYSRES_CONST_CONST_SERVER_STATUS_REPLICATE " +
    -    "SYSRES_CONST_CONTENTS_REQUISITE_CODE " +
    -    "SYSRES_CONST_DATA_TYPE_BOOLEAN " +
    -    "SYSRES_CONST_DATA_TYPE_DATE " +
    -    "SYSRES_CONST_DATA_TYPE_FLOAT " +
    -    "SYSRES_CONST_DATA_TYPE_INTEGER " +
    -    "SYSRES_CONST_DATA_TYPE_PICK " +
    -    "SYSRES_CONST_DATA_TYPE_REFERENCE " +
    -    "SYSRES_CONST_DATA_TYPE_STRING " +
    -    "SYSRES_CONST_DATA_TYPE_TEXT " +
    -    "SYSRES_CONST_DATA_TYPE_VARIANT " +
    -    "SYSRES_CONST_DATE_CLOSE_REQ_CODE " +
    -    "SYSRES_CONST_DATE_FORMAT_DATE_ONLY_CHAR " +
    -    "SYSRES_CONST_DATE_OPEN_REQ_CODE " +
    -    "SYSRES_CONST_DATE_REQUISITE " +
    -    "SYSRES_CONST_DATE_REQUISITE_CODE " +
    -    "SYSRES_CONST_DATE_REQUISITE_NAME " +
    -    "SYSRES_CONST_DATE_REQUISITE_TYPE " +
    -    "SYSRES_CONST_DATE_TYPE_CHAR " +
    -    "SYSRES_CONST_DATETIME_FORMAT_VALUE " +
    -    "SYSRES_CONST_DEA_ACCESS_RIGHTS_ACTION_CODE " +
    -    "SYSRES_CONST_DESCRIPTION_LOCALIZE_ID_REQUISITE_CODE " +
    -    "SYSRES_CONST_DESCRIPTION_REQUISITE_CODE " +
    -    "SYSRES_CONST_DET1_PART " +
    -    "SYSRES_CONST_DET2_PART " +
    -    "SYSRES_CONST_DET3_PART " +
    -    "SYSRES_CONST_DET4_PART " +
    -    "SYSRES_CONST_DET5_PART " +
    -    "SYSRES_CONST_DET6_PART " +
    -    "SYSRES_CONST_DETAIL_DATASET_KEY_REQUISITE_CODE " +
    -    "SYSRES_CONST_DETAIL_PICK_REQUISITE_CODE " +
    -    "SYSRES_CONST_DETAIL_REQ_CODE " +
    -    "SYSRES_CONST_DO_NOT_USE_ACCESS_TYPE_CODE " +
    -    "SYSRES_CONST_DO_NOT_USE_ACCESS_TYPE_NAME " +
    -    "SYSRES_CONST_DO_NOT_USE_ON_VIEW_ACCESS_TYPE_CODE " +
    -    "SYSRES_CONST_DO_NOT_USE_ON_VIEW_ACCESS_TYPE_NAME " +
    -    "SYSRES_CONST_DOCUMENT_STORAGES_CODE " +
    -    "SYSRES_CONST_DOCUMENT_TEMPLATES_TYPE_NAME " +
    -    "SYSRES_CONST_DOUBLE_REQUISITE_CODE " +
    -    "SYSRES_CONST_EDITOR_CLOSE_FILE_OBSERV_TYPE_CODE " +
    -    "SYSRES_CONST_EDITOR_CLOSE_PROCESS_OBSERV_TYPE_CODE " +
    -    "SYSRES_CONST_EDITOR_TYPE_REQUISITE_CODE " +
    -    "SYSRES_CONST_EDITORS_APPLICATION_NAME_REQUISITE_CODE " +
    -    "SYSRES_CONST_EDITORS_CREATE_SEVERAL_PROCESSES_REQUISITE_CODE " +
    -    "SYSRES_CONST_EDITORS_EXTENSION_REQUISITE_CODE " +
    -    "SYSRES_CONST_EDITORS_OBSERVER_BY_PROCESS_TYPE " +
    -    "SYSRES_CONST_EDITORS_REFERENCE_CODE " +
    -    "SYSRES_CONST_EDITORS_REPLACE_SPEC_CHARS_REQUISITE_CODE " +
    -    "SYSRES_CONST_EDITORS_USE_PLUGINS_REQUISITE_CODE " +
    -    "SYSRES_CONST_EDITORS_VIEW_DOCUMENT_OPENED_TO_EDIT_CODE " +
    -    "SYSRES_CONST_EDOC_CARD_TYPE_REQUISITE_CODE " +
    -    "SYSRES_CONST_EDOC_CARD_TYPES_LINK_REQUISITE_CODE " +
    -    "SYSRES_CONST_EDOC_CERTIFICATE_AND_PASSWORD_ENCODE_CODE " +
    -    "SYSRES_CONST_EDOC_CERTIFICATE_ENCODE_CODE " +
    -    "SYSRES_CONST_EDOC_DATE_REQUISITE_CODE " +
    -    "SYSRES_CONST_EDOC_KIND_REFERENCE_CODE " +
    -    "SYSRES_CONST_EDOC_KINDS_BY_TEMPLATE_ACTION_CODE " +
    -    "SYSRES_CONST_EDOC_MANAGE_ACCESS_CODE " +
    -    "SYSRES_CONST_EDOC_NONE_ENCODE_CODE " +
    -    "SYSRES_CONST_EDOC_NUMBER_REQUISITE_CODE " +
    -    "SYSRES_CONST_EDOC_PASSWORD_ENCODE_CODE " +
    -    "SYSRES_CONST_EDOC_READONLY_ACCESS_CODE " +
    -    "SYSRES_CONST_EDOC_SHELL_LIFE_TYPE_VIEW_VALUE " +
    -    "SYSRES_CONST_EDOC_SIZE_RESTRICTION_PRIORITY_REQUISITE_CODE " +
    -    "SYSRES_CONST_EDOC_STORAGE_CHECK_ACCESS_RIGHTS_REQUISITE_CODE " +
    -    "SYSRES_CONST_EDOC_STORAGE_COMPUTER_NAME_REQUISITE_CODE " +
    -    "SYSRES_CONST_EDOC_STORAGE_DATABASE_NAME_REQUISITE_CODE " +
    -    "SYSRES_CONST_EDOC_STORAGE_EDIT_IN_STORAGE_REQUISITE_CODE " +
    -    "SYSRES_CONST_EDOC_STORAGE_LOCAL_PATH_REQUISITE_CODE " +
    -    "SYSRES_CONST_EDOC_STORAGE_SHARED_SOURCE_NAME_REQUISITE_CODE " +
    -    "SYSRES_CONST_EDOC_TEMPLATE_REQUISITE_CODE " +
    -    "SYSRES_CONST_EDOC_TYPES_REFERENCE_CODE " +
    -    "SYSRES_CONST_EDOC_VERSION_ACTIVE_STAGE_CODE " +
    -    "SYSRES_CONST_EDOC_VERSION_DESIGN_STAGE_CODE " +
    -    "SYSRES_CONST_EDOC_VERSION_OBSOLETE_STAGE_CODE " +
    -    "SYSRES_CONST_EDOC_WRITE_ACCES_CODE " +
    -    "SYSRES_CONST_EDOCUMENT_CARD_REQUISITES_REFERENCE_CODE_SELECTED_REQUISITE " +
    -    "SYSRES_CONST_ENCODE_CERTIFICATE_TYPE_CODE " +
    -    "SYSRES_CONST_END_DATE_REQUISITE_CODE " +
    -    "SYSRES_CONST_ENUMERATION_TYPE_REQUISITE_CODE " +
    -    "SYSRES_CONST_EXECUTE_ACCESS_RIGHTS_TYPE_CODE " +
    -    "SYSRES_CONST_EXECUTIVE_FILE_STORAGE_TYPE " +
    -    "SYSRES_CONST_EXIST_CONST " +
    -    "SYSRES_CONST_EXIST_VALUE " +
    -    "SYSRES_CONST_EXPORT_LOCK_TYPE_ASK " +
    -    "SYSRES_CONST_EXPORT_LOCK_TYPE_WITH_LOCK " +
    -    "SYSRES_CONST_EXPORT_LOCK_TYPE_WITHOUT_LOCK " +
    -    "SYSRES_CONST_EXPORT_VERSION_TYPE_ASK " +
    -    "SYSRES_CONST_EXPORT_VERSION_TYPE_LAST " +
    -    "SYSRES_CONST_EXPORT_VERSION_TYPE_LAST_ACTIVE " +
    -    "SYSRES_CONST_EXTENSION_REQUISITE_CODE " +
    -    "SYSRES_CONST_FILTER_NAME_REQUISITE_CODE " +
    -    "SYSRES_CONST_FILTER_REQUISITE_CODE " +
    -    "SYSRES_CONST_FILTER_TYPE_COMMON_CODE " +
    -    "SYSRES_CONST_FILTER_TYPE_COMMON_NAME " +
    -    "SYSRES_CONST_FILTER_TYPE_USER_CODE " +
    -    "SYSRES_CONST_FILTER_TYPE_USER_NAME " +
    -    "SYSRES_CONST_FILTER_VALUE_REQUISITE_NAME " +
    -    "SYSRES_CONST_FLOAT_NUMBER_FORMAT_CHAR " +
    -    "SYSRES_CONST_FLOAT_REQUISITE_TYPE " +
    -    "SYSRES_CONST_FOLDER_AUTHOR_VALUE " +
    -    "SYSRES_CONST_FOLDER_KIND_ANY_OBJECTS " +
    -    "SYSRES_CONST_FOLDER_KIND_COMPONENTS " +
    -    "SYSRES_CONST_FOLDER_KIND_EDOCS " +
    -    "SYSRES_CONST_FOLDER_KIND_JOBS " +
    -    "SYSRES_CONST_FOLDER_KIND_TASKS " +
    -    "SYSRES_CONST_FOLDER_TYPE_COMMON " +
    -    "SYSRES_CONST_FOLDER_TYPE_COMPONENT " +
    -    "SYSRES_CONST_FOLDER_TYPE_FAVORITES " +
    -    "SYSRES_CONST_FOLDER_TYPE_INBOX " +
    -    "SYSRES_CONST_FOLDER_TYPE_OUTBOX " +
    -    "SYSRES_CONST_FOLDER_TYPE_QUICK_LAUNCH " +
    -    "SYSRES_CONST_FOLDER_TYPE_SEARCH " +
    -    "SYSRES_CONST_FOLDER_TYPE_SHORTCUTS " +
    -    "SYSRES_CONST_FOLDER_TYPE_USER " +
    -    "SYSRES_CONST_FROM_DICTIONARY_ENUM_METHOD_FLAG " +
    -    "SYSRES_CONST_FULL_SUBSTITUTE_TYPE " +
    -    "SYSRES_CONST_FULL_SUBSTITUTE_TYPE_CODE " +
    -    "SYSRES_CONST_FUNCTION_CANCEL_RESULT " +
    -    "SYSRES_CONST_FUNCTION_CATEGORY_SYSTEM " +
    -    "SYSRES_CONST_FUNCTION_CATEGORY_USER " +
    -    "SYSRES_CONST_FUNCTION_FAILURE_RESULT " +
    -    "SYSRES_CONST_FUNCTION_SAVE_RESULT " +
    -    "SYSRES_CONST_GENERATED_REQUISITE " +
    -    "SYSRES_CONST_GREEN_LIFE_CYCLE_STAGE_FONT_COLOR " +
    -    "SYSRES_CONST_GROUP_ACCOUNT_TYPE_VALUE_CODE " +
    -    "SYSRES_CONST_GROUP_CATEGORY_NORMAL_CODE " +
    -    "SYSRES_CONST_GROUP_CATEGORY_NORMAL_NAME " +
    -    "SYSRES_CONST_GROUP_CATEGORY_SERVICE_CODE " +
    -    "SYSRES_CONST_GROUP_CATEGORY_SERVICE_NAME " +
    -    "SYSRES_CONST_GROUP_COMMON_CATEGORY_FIELD_VALUE " +
    -    "SYSRES_CONST_GROUP_FULL_NAME_REQUISITE_CODE " +
    -    "SYSRES_CONST_GROUP_NAME_REQUISITE_CODE " +
    -    "SYSRES_CONST_GROUP_RIGHTS_T_REQUISITE_CODE " +
    -    "SYSRES_CONST_GROUP_SERVER_CODES_REQUISITE_CODE " +
    -    "SYSRES_CONST_GROUP_SERVER_NAME_REQUISITE_CODE " +
    -    "SYSRES_CONST_GROUP_SERVICE_CATEGORY_FIELD_VALUE " +
    -    "SYSRES_CONST_GROUP_USER_REQUISITE_CODE " +
    -    "SYSRES_CONST_GROUPS_REFERENCE_CODE " +
    -    "SYSRES_CONST_GROUPS_REQUISITE_CODE " +
    -    "SYSRES_CONST_HIDDEN_MODE_NAME " +
    -    "SYSRES_CONST_HIGH_LVL_REQUISITE_CODE " +
    -    "SYSRES_CONST_HISTORY_ACTION_CREATE_CODE " +
    -    "SYSRES_CONST_HISTORY_ACTION_DELETE_CODE " +
    -    "SYSRES_CONST_HISTORY_ACTION_EDIT_CODE " +
    -    "SYSRES_CONST_HOUR_CHAR " +
    -    "SYSRES_CONST_ID_REQUISITE_CODE " +
    -    "SYSRES_CONST_IDSPS_REQUISITE_CODE " +
    -    "SYSRES_CONST_IMAGE_MODE_COLOR " +
    -    "SYSRES_CONST_IMAGE_MODE_GREYSCALE " +
    -    "SYSRES_CONST_IMAGE_MODE_MONOCHROME " +
    -    "SYSRES_CONST_IMPORTANCE_HIGH " +
    -    "SYSRES_CONST_IMPORTANCE_LOW " +
    -    "SYSRES_CONST_IMPORTANCE_NORMAL " +
    -    "SYSRES_CONST_IN_DESIGN_VERSION_STATE_PICK_VALUE " +
    -    "SYSRES_CONST_INCOMING_WORK_RULE_TYPE_CODE " +
    -    "SYSRES_CONST_INT_REQUISITE " +
    -    "SYSRES_CONST_INT_REQUISITE_TYPE " +
    -    "SYSRES_CONST_INTEGER_NUMBER_FORMAT_CHAR " +
    -    "SYSRES_CONST_INTEGER_TYPE_CHAR " +
    -    "SYSRES_CONST_IS_GENERATED_REQUISITE_NEGATIVE_VALUE " +
    -    "SYSRES_CONST_IS_PUBLIC_ROLE_REQUISITE_CODE " +
    -    "SYSRES_CONST_IS_REMOTE_USER_NEGATIVE_VALUE " +
    -    "SYSRES_CONST_IS_REMOTE_USER_POSITIVE_VALUE " +
    -    "SYSRES_CONST_IS_STORED_REQUISITE_NEGATIVE_VALUE " +
    -    "SYSRES_CONST_IS_STORED_REQUISITE_STORED_VALUE " +
    -    "SYSRES_CONST_ITALIC_LIFE_CYCLE_STAGE_DRAW_STYLE " +
    -    "SYSRES_CONST_JOB_BLOCK_DESCRIPTION " +
    -    "SYSRES_CONST_JOB_KIND_CONTROL_JOB " +
    -    "SYSRES_CONST_JOB_KIND_JOB " +
    -    "SYSRES_CONST_JOB_KIND_NOTICE " +
    -    "SYSRES_CONST_JOB_STATE_ABORTED " +
    -    "SYSRES_CONST_JOB_STATE_COMPLETE " +
    -    "SYSRES_CONST_JOB_STATE_WORKING " +
    -    "SYSRES_CONST_KIND_REQUISITE_CODE " +
    -    "SYSRES_CONST_KIND_REQUISITE_NAME " +
    -    "SYSRES_CONST_KINDS_CREATE_SHADOW_COPIES_REQUISITE_CODE " +
    -    "SYSRES_CONST_KINDS_DEFAULT_EDOC_LIFE_STAGE_REQUISITE_CODE " +
    -    "SYSRES_CONST_KINDS_EDOC_ALL_TEPLATES_ALLOWED_REQUISITE_CODE " +
    -    "SYSRES_CONST_KINDS_EDOC_ALLOW_LIFE_CYCLE_STAGE_CHANGING_REQUISITE_CODE " +
    -    "SYSRES_CONST_KINDS_EDOC_ALLOW_MULTIPLE_ACTIVE_VERSIONS_REQUISITE_CODE " +
    -    "SYSRES_CONST_KINDS_EDOC_SHARE_ACCES_RIGHTS_BY_DEFAULT_CODE " +
    -    "SYSRES_CONST_KINDS_EDOC_TEMPLATE_REQUISITE_CODE " +
    -    "SYSRES_CONST_KINDS_EDOC_TYPE_REQUISITE_CODE " +
    -    "SYSRES_CONST_KINDS_SIGNERS_REQUISITES_CODE " +
    -    "SYSRES_CONST_KOD_INPUT_TYPE " +
    -    "SYSRES_CONST_LAST_UPDATE_DATE_REQUISITE_CODE " +
    -    "SYSRES_CONST_LIFE_CYCLE_START_STAGE_REQUISITE_CODE " +
    -    "SYSRES_CONST_LILAC_LIFE_CYCLE_STAGE_FONT_COLOR " +
    -    "SYSRES_CONST_LINK_OBJECT_KIND_COMPONENT " +
    -    "SYSRES_CONST_LINK_OBJECT_KIND_DOCUMENT " +
    -    "SYSRES_CONST_LINK_OBJECT_KIND_EDOC " +
    -    "SYSRES_CONST_LINK_OBJECT_KIND_FOLDER " +
    -    "SYSRES_CONST_LINK_OBJECT_KIND_JOB " +
    -    "SYSRES_CONST_LINK_OBJECT_KIND_REFERENCE " +
    -    "SYSRES_CONST_LINK_OBJECT_KIND_TASK " +
    -    "SYSRES_CONST_LINK_REF_TYPE_REQUISITE_CODE " +
    -    "SYSRES_CONST_LIST_REFERENCE_MODE_NAME " +
    -    "SYSRES_CONST_LOCALIZATION_DICTIONARY_MAIN_VIEW_CODE " +
    -    "SYSRES_CONST_MAIN_VIEW_CODE " +
    -    "SYSRES_CONST_MANUAL_ENUM_METHOD_FLAG " +
    -    "SYSRES_CONST_MASTER_COMP_TYPE_REQUISITE_CODE " +
    -    "SYSRES_CONST_MASTER_TABLE_REC_ID_REQUISITE_CODE " +
    -    "SYSRES_CONST_MAXIMIZED_MODE_NAME " +
    -    "SYSRES_CONST_ME_VALUE " +
    -    "SYSRES_CONST_MESSAGE_ATTENTION_CAPTION " +
    -    "SYSRES_CONST_MESSAGE_CONFIRMATION_CAPTION " +
    -    "SYSRES_CONST_MESSAGE_ERROR_CAPTION " +
    -    "SYSRES_CONST_MESSAGE_INFORMATION_CAPTION " +
    -    "SYSRES_CONST_MINIMIZED_MODE_NAME " +
    -    "SYSRES_CONST_MINUTE_CHAR " +
    -    "SYSRES_CONST_MODULE_REQUISITE_CODE " +
    -    "SYSRES_CONST_MONITORING_BLOCK_DESCRIPTION " +
    -    "SYSRES_CONST_MONTH_FORMAT_VALUE " +
    -    "SYSRES_CONST_NAME_LOCALIZE_ID_REQUISITE_CODE " +
    -    "SYSRES_CONST_NAME_REQUISITE_CODE " +
    -    "SYSRES_CONST_NAME_SINGULAR_REQUISITE_CODE " +
    -    "SYSRES_CONST_NAMEAN_INPUT_TYPE " +
    -    "SYSRES_CONST_NEGATIVE_PICK_VALUE " +
    -    "SYSRES_CONST_NEGATIVE_VALUE " +
    -    "SYSRES_CONST_NO " +
    -    "SYSRES_CONST_NO_PICK_VALUE " +
    -    "SYSRES_CONST_NO_SIGNATURE_REQUISITE_CODE " +
    -    "SYSRES_CONST_NO_VALUE " +
    -    "SYSRES_CONST_NONE_ACCESS_RIGHTS_TYPE_CODE " +
    -    "SYSRES_CONST_NONOPERATING_RECORD_FLAG_VALUE " +
    -    "SYSRES_CONST_NONOPERATING_RECORD_FLAG_VALUE_MASCULINE " +
    -    "SYSRES_CONST_NORMAL_ACCESS_RIGHTS_TYPE_CODE " +
    -    "SYSRES_CONST_NORMAL_LIFE_CYCLE_STAGE_DRAW_STYLE " +
    -    "SYSRES_CONST_NORMAL_MODE_NAME " +
    -    "SYSRES_CONST_NOT_ALLOWED_ACCESS_TYPE_CODE " +
    -    "SYSRES_CONST_NOT_ALLOWED_ACCESS_TYPE_NAME " +
    -    "SYSRES_CONST_NOTE_REQUISITE_CODE " +
    -    "SYSRES_CONST_NOTICE_BLOCK_DESCRIPTION " +
    -    "SYSRES_CONST_NUM_REQUISITE " +
    -    "SYSRES_CONST_NUM_STR_REQUISITE_CODE " +
    -    "SYSRES_CONST_NUMERATION_AUTO_NOT_STRONG " +
    -    "SYSRES_CONST_NUMERATION_AUTO_STRONG " +
    -    "SYSRES_CONST_NUMERATION_FROM_DICTONARY " +
    -    "SYSRES_CONST_NUMERATION_MANUAL " +
    -    "SYSRES_CONST_NUMERIC_TYPE_CHAR " +
    -    "SYSRES_CONST_NUMREQ_REQUISITE_CODE " +
    -    "SYSRES_CONST_OBSOLETE_VERSION_STATE_PICK_VALUE " +
    -    "SYSRES_CONST_OPERATING_RECORD_FLAG_VALUE " +
    -    "SYSRES_CONST_OPERATING_RECORD_FLAG_VALUE_CODE " +
    -    "SYSRES_CONST_OPERATING_RECORD_FLAG_VALUE_FEMININE " +
    -    "SYSRES_CONST_OPERATING_RECORD_FLAG_VALUE_MASCULINE " +
    -    "SYSRES_CONST_OPTIONAL_FORM_COMP_REQCODE_PREFIX " +
    -    "SYSRES_CONST_ORANGE_LIFE_CYCLE_STAGE_FONT_COLOR " +
    -    "SYSRES_CONST_ORIGINALREF_REQUISITE_CODE " +
    -    "SYSRES_CONST_OURFIRM_REF_CODE " +
    -    "SYSRES_CONST_OURFIRM_REQUISITE_CODE " +
    -    "SYSRES_CONST_OURFIRM_VAR " +
    -    "SYSRES_CONST_OUTGOING_WORK_RULE_TYPE_CODE " +
    -    "SYSRES_CONST_PICK_NEGATIVE_RESULT " +
    -    "SYSRES_CONST_PICK_POSITIVE_RESULT " +
    -    "SYSRES_CONST_PICK_REQUISITE " +
    -    "SYSRES_CONST_PICK_REQUISITE_TYPE " +
    -    "SYSRES_CONST_PICK_TYPE_CHAR " +
    -    "SYSRES_CONST_PLAN_STATUS_REQUISITE_CODE " +
    -    "SYSRES_CONST_PLATFORM_VERSION_COMMENT " +
    -    "SYSRES_CONST_PLUGINS_SETTINGS_DESCRIPTION_REQUISITE_CODE " +
    -    "SYSRES_CONST_POSITIVE_PICK_VALUE " +
    -    "SYSRES_CONST_POWER_TO_CREATE_ACTION_CODE " +
    -    "SYSRES_CONST_POWER_TO_SIGN_ACTION_CODE " +
    -    "SYSRES_CONST_PRIORITY_REQUISITE_CODE " +
    -    "SYSRES_CONST_QUALIFIED_TASK_TYPE " +
    -    "SYSRES_CONST_QUALIFIED_TASK_TYPE_CODE " +
    -    "SYSRES_CONST_RECSTAT_REQUISITE_CODE " +
    -    "SYSRES_CONST_RED_LIFE_CYCLE_STAGE_FONT_COLOR " +
    -    "SYSRES_CONST_REF_ID_T_REF_TYPE_REQUISITE_CODE " +
    -    "SYSRES_CONST_REF_REQUISITE " +
    -    "SYSRES_CONST_REF_REQUISITE_TYPE " +
    -    "SYSRES_CONST_REF_REQUISITES_REFERENCE_CODE_SELECTED_REQUISITE " +
    -    "SYSRES_CONST_REFERENCE_RECORD_HISTORY_CREATE_ACTION_CODE " +
    -    "SYSRES_CONST_REFERENCE_RECORD_HISTORY_DELETE_ACTION_CODE " +
    -    "SYSRES_CONST_REFERENCE_RECORD_HISTORY_MODIFY_ACTION_CODE " +
    -    "SYSRES_CONST_REFERENCE_TYPE_CHAR " +
    -    "SYSRES_CONST_REFERENCE_TYPE_REQUISITE_NAME " +
    -    "SYSRES_CONST_REFERENCES_ADD_PARAMS_REQUISITE_CODE " +
    -    "SYSRES_CONST_REFERENCES_DISPLAY_REQUISITE_REQUISITE_CODE " +
    -    "SYSRES_CONST_REMOTE_SERVER_STATUS_WORKING " +
    -    "SYSRES_CONST_REMOTE_SERVER_TYPE_MAIN " +
    -    "SYSRES_CONST_REMOTE_SERVER_TYPE_SECONDARY " +
    -    "SYSRES_CONST_REMOTE_USER_FLAG_VALUE_CODE " +
    -    "SYSRES_CONST_REPORT_APP_EDITOR_INTERNAL " +
    -    "SYSRES_CONST_REPORT_BASE_REPORT_ID_REQUISITE_CODE " +
    -    "SYSRES_CONST_REPORT_BASE_REPORT_REQUISITE_CODE " +
    -    "SYSRES_CONST_REPORT_SCRIPT_REQUISITE_CODE " +
    -    "SYSRES_CONST_REPORT_TEMPLATE_REQUISITE_CODE " +
    -    "SYSRES_CONST_REPORT_VIEWER_CODE_REQUISITE_CODE " +
    -    "SYSRES_CONST_REQ_ALLOW_COMPONENT_DEFAULT_VALUE " +
    -    "SYSRES_CONST_REQ_ALLOW_RECORD_DEFAULT_VALUE " +
    -    "SYSRES_CONST_REQ_ALLOW_SERVER_COMPONENT_DEFAULT_VALUE " +
    -    "SYSRES_CONST_REQ_MODE_AVAILABLE_CODE " +
    -    "SYSRES_CONST_REQ_MODE_EDIT_CODE " +
    -    "SYSRES_CONST_REQ_MODE_HIDDEN_CODE " +
    -    "SYSRES_CONST_REQ_MODE_NOT_AVAILABLE_CODE " +
    -    "SYSRES_CONST_REQ_MODE_VIEW_CODE " +
    -    "SYSRES_CONST_REQ_NUMBER_REQUISITE_CODE " +
    -    "SYSRES_CONST_REQ_SECTION_VALUE " +
    -    "SYSRES_CONST_REQ_TYPE_VALUE " +
    -    "SYSRES_CONST_REQUISITE_FORMAT_BY_UNIT " +
    -    "SYSRES_CONST_REQUISITE_FORMAT_DATE_FULL " +
    -    "SYSRES_CONST_REQUISITE_FORMAT_DATE_TIME " +
    -    "SYSRES_CONST_REQUISITE_FORMAT_LEFT " +
    -    "SYSRES_CONST_REQUISITE_FORMAT_RIGHT " +
    -    "SYSRES_CONST_REQUISITE_FORMAT_WITHOUT_UNIT " +
    -    "SYSRES_CONST_REQUISITE_NUMBER_REQUISITE_CODE " +
    -    "SYSRES_CONST_REQUISITE_SECTION_ACTIONS " +
    -    "SYSRES_CONST_REQUISITE_SECTION_BUTTON " +
    -    "SYSRES_CONST_REQUISITE_SECTION_BUTTONS " +
    -    "SYSRES_CONST_REQUISITE_SECTION_CARD " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE10 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE11 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE12 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE13 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE14 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE15 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE16 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE17 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE18 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE19 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE2 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE20 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE21 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE22 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE23 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE24 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE3 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE4 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE5 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE6 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE7 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE8 " +
    -    "SYSRES_CONST_REQUISITE_SECTION_TABLE9 " +
    -    "SYSRES_CONST_REQUISITES_PSEUDOREFERENCE_REQUISITE_NUMBER_REQUISITE_CODE " +
    -    "SYSRES_CONST_RIGHT_ALIGNMENT_CODE " +
    -    "SYSRES_CONST_ROLES_REFERENCE_CODE " +
    -    "SYSRES_CONST_ROUTE_STEP_AFTER_RUS " +
    -    "SYSRES_CONST_ROUTE_STEP_AND_CONDITION_RUS " +
    -    "SYSRES_CONST_ROUTE_STEP_OR_CONDITION_RUS " +
    -    "SYSRES_CONST_ROUTE_TYPE_COMPLEX " +
    -    "SYSRES_CONST_ROUTE_TYPE_PARALLEL " +
    -    "SYSRES_CONST_ROUTE_TYPE_SERIAL " +
    -    "SYSRES_CONST_SBDATASETDESC_NEGATIVE_VALUE " +
    -    "SYSRES_CONST_SBDATASETDESC_POSITIVE_VALUE " +
    -    "SYSRES_CONST_SBVIEWSDESC_POSITIVE_VALUE " +
    -    "SYSRES_CONST_SCRIPT_BLOCK_DESCRIPTION " +
    -    "SYSRES_CONST_SEARCH_BY_TEXT_REQUISITE_CODE " +
    -    "SYSRES_CONST_SEARCHES_COMPONENT_CONTENT " +
    -    "SYSRES_CONST_SEARCHES_CRITERIA_ACTION_NAME " +
    -    "SYSRES_CONST_SEARCHES_EDOC_CONTENT " +
    -    "SYSRES_CONST_SEARCHES_FOLDER_CONTENT " +
    -    "SYSRES_CONST_SEARCHES_JOB_CONTENT " +
    -    "SYSRES_CONST_SEARCHES_REFERENCE_CODE " +
    -    "SYSRES_CONST_SEARCHES_TASK_CONTENT " +
    -    "SYSRES_CONST_SECOND_CHAR " +
    -    "SYSRES_CONST_SECTION_REQUISITE_ACTIONS_VALUE " +
    -    "SYSRES_CONST_SECTION_REQUISITE_CARD_VALUE " +
    -    "SYSRES_CONST_SECTION_REQUISITE_CODE " +
    -    "SYSRES_CONST_SECTION_REQUISITE_DETAIL_1_VALUE " +
    -    "SYSRES_CONST_SECTION_REQUISITE_DETAIL_2_VALUE " +
    -    "SYSRES_CONST_SECTION_REQUISITE_DETAIL_3_VALUE " +
    -    "SYSRES_CONST_SECTION_REQUISITE_DETAIL_4_VALUE " +
    -    "SYSRES_CONST_SECTION_REQUISITE_DETAIL_5_VALUE " +
    -    "SYSRES_CONST_SECTION_REQUISITE_DETAIL_6_VALUE " +
    -    "SYSRES_CONST_SELECT_REFERENCE_MODE_NAME " +
    -    "SYSRES_CONST_SELECT_TYPE_SELECTABLE " +
    -    "SYSRES_CONST_SELECT_TYPE_SELECTABLE_ONLY_CHILD " +
    -    "SYSRES_CONST_SELECT_TYPE_SELECTABLE_WITH_CHILD " +
    -    "SYSRES_CONST_SELECT_TYPE_UNSLECTABLE " +
    -    "SYSRES_CONST_SERVER_TYPE_MAIN " +
    -    "SYSRES_CONST_SERVICE_USER_CATEGORY_FIELD_VALUE " +
    -    "SYSRES_CONST_SETTINGS_USER_REQUISITE_CODE " +
    -    "SYSRES_CONST_SIGNATURE_AND_ENCODE_CERTIFICATE_TYPE_CODE " +
    -    "SYSRES_CONST_SIGNATURE_CERTIFICATE_TYPE_CODE " +
    -    "SYSRES_CONST_SINGULAR_TITLE_REQUISITE_CODE " +
    -    "SYSRES_CONST_SQL_SERVER_AUTHENTIFICATION_FLAG_VALUE_CODE " +
    -    "SYSRES_CONST_SQL_SERVER_ENCODE_AUTHENTIFICATION_FLAG_VALUE_CODE " +
    -    "SYSRES_CONST_STANDART_ROUTE_REFERENCE_CODE " +
    -    "SYSRES_CONST_STANDART_ROUTE_REFERENCE_COMMENT_REQUISITE_CODE " +
    -    "SYSRES_CONST_STANDART_ROUTES_GROUPS_REFERENCE_CODE " +
    -    "SYSRES_CONST_STATE_REQ_NAME " +
    -    "SYSRES_CONST_STATE_REQUISITE_ACTIVE_VALUE " +
    -    "SYSRES_CONST_STATE_REQUISITE_CLOSED_VALUE " +
    -    "SYSRES_CONST_STATE_REQUISITE_CODE " +
    -    "SYSRES_CONST_STATIC_ROLE_TYPE_CODE " +
    -    "SYSRES_CONST_STATUS_PLAN_DEFAULT_VALUE " +
    -    "SYSRES_CONST_STATUS_VALUE_AUTOCLEANING " +
    -    "SYSRES_CONST_STATUS_VALUE_BLUE_SQUARE " +
    -    "SYSRES_CONST_STATUS_VALUE_COMPLETE " +
    -    "SYSRES_CONST_STATUS_VALUE_GREEN_SQUARE " +
    -    "SYSRES_CONST_STATUS_VALUE_ORANGE_SQUARE " +
    -    "SYSRES_CONST_STATUS_VALUE_PURPLE_SQUARE " +
    -    "SYSRES_CONST_STATUS_VALUE_RED_SQUARE " +
    -    "SYSRES_CONST_STATUS_VALUE_SUSPEND " +
    -    "SYSRES_CONST_STATUS_VALUE_YELLOW_SQUARE " +
    -    "SYSRES_CONST_STDROUTE_SHOW_TO_USERS_REQUISITE_CODE " +
    -    "SYSRES_CONST_STORAGE_TYPE_FILE " +
    -    "SYSRES_CONST_STORAGE_TYPE_SQL_SERVER " +
    -    "SYSRES_CONST_STR_REQUISITE " +
    -    "SYSRES_CONST_STRIKEOUT_LIFE_CYCLE_STAGE_DRAW_STYLE " +
    -    "SYSRES_CONST_STRING_FORMAT_LEFT_ALIGN_CHAR " +
    -    "SYSRES_CONST_STRING_FORMAT_RIGHT_ALIGN_CHAR " +
    -    "SYSRES_CONST_STRING_REQUISITE_CODE " +
    -    "SYSRES_CONST_STRING_REQUISITE_TYPE " +
    -    "SYSRES_CONST_STRING_TYPE_CHAR " +
    -    "SYSRES_CONST_SUBSTITUTES_PSEUDOREFERENCE_CODE " +
    -    "SYSRES_CONST_SUBTASK_BLOCK_DESCRIPTION " +
    -    "SYSRES_CONST_SYSTEM_SETTING_CURRENT_USER_PARAM_VALUE " +
    -    "SYSRES_CONST_SYSTEM_SETTING_EMPTY_VALUE_PARAM_VALUE " +
    -    "SYSRES_CONST_SYSTEM_VERSION_COMMENT " +
    -    "SYSRES_CONST_TASK_ACCESS_TYPE_ALL " +
    -    "SYSRES_CONST_TASK_ACCESS_TYPE_ALL_MEMBERS " +
    -    "SYSRES_CONST_TASK_ACCESS_TYPE_MANUAL " +
    -    "SYSRES_CONST_TASK_ENCODE_TYPE_CERTIFICATION " +
    -    "SYSRES_CONST_TASK_ENCODE_TYPE_CERTIFICATION_AND_PASSWORD " +
    -    "SYSRES_CONST_TASK_ENCODE_TYPE_NONE " +
    -    "SYSRES_CONST_TASK_ENCODE_TYPE_PASSWORD " +
    -    "SYSRES_CONST_TASK_ROUTE_ALL_CONDITION " +
    -    "SYSRES_CONST_TASK_ROUTE_AND_CONDITION " +
    -    "SYSRES_CONST_TASK_ROUTE_OR_CONDITION " +
    -    "SYSRES_CONST_TASK_STATE_ABORTED " +
    -    "SYSRES_CONST_TASK_STATE_COMPLETE " +
    -    "SYSRES_CONST_TASK_STATE_CONTINUED " +
    -    "SYSRES_CONST_TASK_STATE_CONTROL " +
    -    "SYSRES_CONST_TASK_STATE_INIT " +
    -    "SYSRES_CONST_TASK_STATE_WORKING " +
    -    "SYSRES_CONST_TASK_TITLE " +
    -    "SYSRES_CONST_TASK_TYPES_GROUPS_REFERENCE_CODE " +
    -    "SYSRES_CONST_TASK_TYPES_REFERENCE_CODE " +
    -    "SYSRES_CONST_TEMPLATES_REFERENCE_CODE " +
    -    "SYSRES_CONST_TEST_DATE_REQUISITE_NAME " +
    -    "SYSRES_CONST_TEST_DEV_DATABASE_NAME " +
    -    "SYSRES_CONST_TEST_DEV_SYSTEM_CODE " +
    -    "SYSRES_CONST_TEST_EDMS_DATABASE_NAME " +
    -    "SYSRES_CONST_TEST_EDMS_MAIN_CODE " +
    -    "SYSRES_CONST_TEST_EDMS_MAIN_DB_NAME " +
    -    "SYSRES_CONST_TEST_EDMS_SECOND_CODE " +
    -    "SYSRES_CONST_TEST_EDMS_SECOND_DB_NAME " +
    -    "SYSRES_CONST_TEST_EDMS_SYSTEM_CODE " +
    -    "SYSRES_CONST_TEST_NUMERIC_REQUISITE_NAME " +
    -    "SYSRES_CONST_TEXT_REQUISITE " +
    -    "SYSRES_CONST_TEXT_REQUISITE_CODE " +
    -    "SYSRES_CONST_TEXT_REQUISITE_TYPE " +
    -    "SYSRES_CONST_TEXT_TYPE_CHAR " +
    -    "SYSRES_CONST_TYPE_CODE_REQUISITE_CODE " +
    -    "SYSRES_CONST_TYPE_REQUISITE_CODE " +
    -    "SYSRES_CONST_UNDEFINED_LIFE_CYCLE_STAGE_FONT_COLOR " +
    -    "SYSRES_CONST_UNITS_SECTION_ID_REQUISITE_CODE " +
    -    "SYSRES_CONST_UNITS_SECTION_REQUISITE_CODE " +
    -    "SYSRES_CONST_UNOPERATING_RECORD_FLAG_VALUE_CODE " +
    -    "SYSRES_CONST_UNSTORED_DATA_REQUISITE_CODE " +
    -    "SYSRES_CONST_UNSTORED_DATA_REQUISITE_NAME " +
    -    "SYSRES_CONST_USE_ACCESS_TYPE_CODE " +
    -    "SYSRES_CONST_USE_ACCESS_TYPE_NAME " +
    -    "SYSRES_CONST_USER_ACCOUNT_TYPE_VALUE_CODE " +
    -    "SYSRES_CONST_USER_ADDITIONAL_INFORMATION_REQUISITE_CODE " +
    -    "SYSRES_CONST_USER_AND_GROUP_ID_FROM_PSEUDOREFERENCE_REQUISITE_CODE " +
    -    "SYSRES_CONST_USER_CATEGORY_NORMAL " +
    -    "SYSRES_CONST_USER_CERTIFICATE_REQUISITE_CODE " +
    -    "SYSRES_CONST_USER_CERTIFICATE_STATE_REQUISITE_CODE " +
    -    "SYSRES_CONST_USER_CERTIFICATE_SUBJECT_NAME_REQUISITE_CODE " +
    -    "SYSRES_CONST_USER_CERTIFICATE_THUMBPRINT_REQUISITE_CODE " +
    -    "SYSRES_CONST_USER_COMMON_CATEGORY " +
    -    "SYSRES_CONST_USER_COMMON_CATEGORY_CODE " +
    -    "SYSRES_CONST_USER_FULL_NAME_REQUISITE_CODE " +
    -    "SYSRES_CONST_USER_GROUP_TYPE_REQUISITE_CODE " +
    -    "SYSRES_CONST_USER_LOGIN_REQUISITE_CODE " +
    -    "SYSRES_CONST_USER_REMOTE_CONTROLLER_REQUISITE_CODE " +
    -    "SYSRES_CONST_USER_REMOTE_SYSTEM_REQUISITE_CODE " +
    -    "SYSRES_CONST_USER_RIGHTS_T_REQUISITE_CODE " +
    -    "SYSRES_CONST_USER_SERVER_NAME_REQUISITE_CODE " +
    -    "SYSRES_CONST_USER_SERVICE_CATEGORY " +
    -    "SYSRES_CONST_USER_SERVICE_CATEGORY_CODE " +
    -    "SYSRES_CONST_USER_STATUS_ADMINISTRATOR_CODE " +
    -    "SYSRES_CONST_USER_STATUS_ADMINISTRATOR_NAME " +
    -    "SYSRES_CONST_USER_STATUS_DEVELOPER_CODE " +
    -    "SYSRES_CONST_USER_STATUS_DEVELOPER_NAME " +
    -    "SYSRES_CONST_USER_STATUS_DISABLED_CODE " +
    -    "SYSRES_CONST_USER_STATUS_DISABLED_NAME " +
    -    "SYSRES_CONST_USER_STATUS_SYSTEM_DEVELOPER_CODE " +
    -    "SYSRES_CONST_USER_STATUS_USER_CODE " +
    -    "SYSRES_CONST_USER_STATUS_USER_NAME " +
    -    "SYSRES_CONST_USER_STATUS_USER_NAME_DEPRECATED " +
    -    "SYSRES_CONST_USER_TYPE_FIELD_VALUE_USER " +
    -    "SYSRES_CONST_USER_TYPE_REQUISITE_CODE " +
    -    "SYSRES_CONST_USERS_CONTROLLER_REQUISITE_CODE " +
    -    "SYSRES_CONST_USERS_IS_MAIN_SERVER_REQUISITE_CODE " +
    -    "SYSRES_CONST_USERS_REFERENCE_CODE " +
    -    "SYSRES_CONST_USERS_REGISTRATION_CERTIFICATES_ACTION_NAME " +
    -    "SYSRES_CONST_USERS_REQUISITE_CODE " +
    -    "SYSRES_CONST_USERS_SYSTEM_REQUISITE_CODE " +
    -    "SYSRES_CONST_USERS_USER_ACCESS_RIGHTS_TYPR_REQUISITE_CODE " +
    -    "SYSRES_CONST_USERS_USER_AUTHENTICATION_REQUISITE_CODE " +
    -    "SYSRES_CONST_USERS_USER_COMPONENT_REQUISITE_CODE " +
    -    "SYSRES_CONST_USERS_USER_GROUP_REQUISITE_CODE " +
    -    "SYSRES_CONST_USERS_VIEW_CERTIFICATES_ACTION_NAME " +
    -    "SYSRES_CONST_VIEW_DEFAULT_CODE " +
    -    "SYSRES_CONST_VIEW_DEFAULT_NAME " +
    -    "SYSRES_CONST_VIEWER_REQUISITE_CODE " +
    -    "SYSRES_CONST_WAITING_BLOCK_DESCRIPTION " +
    -    "SYSRES_CONST_WIZARD_FORM_LABEL_TEST_STRING  " +
    -    "SYSRES_CONST_WIZARD_QUERY_PARAM_HEIGHT_ETALON_STRING " +
    -    "SYSRES_CONST_WIZARD_REFERENCE_COMMENT_REQUISITE_CODE " +
    -    "SYSRES_CONST_WORK_RULES_DESCRIPTION_REQUISITE_CODE " +
    -    "SYSRES_CONST_WORK_TIME_CALENDAR_REFERENCE_CODE " +
    -    "SYSRES_CONST_WORK_WORKFLOW_HARD_ROUTE_TYPE_VALUE " +
    -    "SYSRES_CONST_WORK_WORKFLOW_HARD_ROUTE_TYPE_VALUE_CODE " +
    -    "SYSRES_CONST_WORK_WORKFLOW_HARD_ROUTE_TYPE_VALUE_CODE_RUS " +
    -    "SYSRES_CONST_WORK_WORKFLOW_SOFT_ROUTE_TYPE_VALUE_CODE_RUS " +
    -    "SYSRES_CONST_WORKFLOW_ROUTE_TYPR_HARD " +
    -    "SYSRES_CONST_WORKFLOW_ROUTE_TYPR_SOFT " +
    -    "SYSRES_CONST_XML_ENCODING " +
    -    "SYSRES_CONST_XREC_STAT_REQUISITE_CODE " +
    -    "SYSRES_CONST_XRECID_FIELD_NAME " +
    -    "SYSRES_CONST_YES " +
    -    "SYSRES_CONST_YES_NO_2_REQUISITE_CODE " +
    -    "SYSRES_CONST_YES_NO_REQUISITE_CODE " +
    -    "SYSRES_CONST_YES_NO_T_REF_TYPE_REQUISITE_CODE " +
    -    "SYSRES_CONST_YES_PICK_VALUE " +
    -    "SYSRES_CONST_YES_VALUE ";
    -
    -  // Base constant
    -  const base_constants = "CR FALSE nil NO_VALUE NULL TAB TRUE YES_VALUE ";
    -
    -  // Base group name
    -  const base_group_name_constants =
    -    "ADMINISTRATORS_GROUP_NAME CUSTOMIZERS_GROUP_NAME DEVELOPERS_GROUP_NAME SERVICE_USERS_GROUP_NAME ";
    -
    -  // Decision block properties
    -  const decision_block_properties_constants =
    -    "DECISION_BLOCK_FIRST_OPERAND_PROPERTY DECISION_BLOCK_NAME_PROPERTY DECISION_BLOCK_OPERATION_PROPERTY " +
    -    "DECISION_BLOCK_RESULT_TYPE_PROPERTY DECISION_BLOCK_SECOND_OPERAND_PROPERTY ";
    -
    -  // File extension
    -  const file_extension_constants =
    -    "ANY_FILE_EXTENTION COMPRESSED_DOCUMENT_EXTENSION EXTENDED_DOCUMENT_EXTENSION " +
    -    "SHORT_COMPRESSED_DOCUMENT_EXTENSION SHORT_EXTENDED_DOCUMENT_EXTENSION ";
    -
    -  // Job block properties
    -  const job_block_properties_constants =
    -    "JOB_BLOCK_ABORT_DEADLINE_PROPERTY " +
    -    "JOB_BLOCK_AFTER_FINISH_EVENT " +
    -    "JOB_BLOCK_AFTER_QUERY_PARAMETERS_EVENT " +
    -    "JOB_BLOCK_ATTACHMENT_PROPERTY " +
    -    "JOB_BLOCK_ATTACHMENTS_RIGHTS_GROUP_PROPERTY " +
    -    "JOB_BLOCK_ATTACHMENTS_RIGHTS_TYPE_PROPERTY " +
    -    "JOB_BLOCK_BEFORE_QUERY_PARAMETERS_EVENT " +
    -    "JOB_BLOCK_BEFORE_START_EVENT " +
    -    "JOB_BLOCK_CREATED_JOBS_PROPERTY " +
    -    "JOB_BLOCK_DEADLINE_PROPERTY " +
    -    "JOB_BLOCK_EXECUTION_RESULTS_PROPERTY " +
    -    "JOB_BLOCK_IS_PARALLEL_PROPERTY " +
    -    "JOB_BLOCK_IS_RELATIVE_ABORT_DEADLINE_PROPERTY " +
    -    "JOB_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY " +
    -    "JOB_BLOCK_JOB_TEXT_PROPERTY " +
    -    "JOB_BLOCK_NAME_PROPERTY " +
    -    "JOB_BLOCK_NEED_SIGN_ON_PERFORM_PROPERTY " +
    -    "JOB_BLOCK_PERFORMER_PROPERTY " +
    -    "JOB_BLOCK_RELATIVE_ABORT_DEADLINE_TYPE_PROPERTY " +
    -    "JOB_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY " +
    -    "JOB_BLOCK_SUBJECT_PROPERTY ";
    -
    -  // Language code
    -  const language_code_constants = "ENGLISH_LANGUAGE_CODE RUSSIAN_LANGUAGE_CODE ";
    -
    -  // Launching external applications
    -  const launching_external_applications_constants =
    -    "smHidden smMaximized smMinimized smNormal wmNo wmYes ";
    -
    -  // Link kind
    -  const link_kind_constants =
    -    "COMPONENT_TOKEN_LINK_KIND " +
    -    "DOCUMENT_LINK_KIND " +
    -    "EDOCUMENT_LINK_KIND " +
    -    "FOLDER_LINK_KIND " +
    -    "JOB_LINK_KIND " +
    -    "REFERENCE_LINK_KIND " +
    -    "TASK_LINK_KIND ";
    -
    -  // Lock type
    -  const lock_type_constants =
    -    "COMPONENT_TOKEN_LOCK_TYPE EDOCUMENT_VERSION_LOCK_TYPE ";
    -
    -  // Monitor block properties
    -  const monitor_block_properties_constants =
    -    "MONITOR_BLOCK_AFTER_FINISH_EVENT " +
    -    "MONITOR_BLOCK_BEFORE_START_EVENT " +
    -    "MONITOR_BLOCK_DEADLINE_PROPERTY " +
    -    "MONITOR_BLOCK_INTERVAL_PROPERTY " +
    -    "MONITOR_BLOCK_INTERVAL_TYPE_PROPERTY " +
    -    "MONITOR_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY " +
    -    "MONITOR_BLOCK_NAME_PROPERTY " +
    -    "MONITOR_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY " +
    -    "MONITOR_BLOCK_SEARCH_SCRIPT_PROPERTY ";
    -
    -  // Notice block properties
    -  const notice_block_properties_constants =
    -    "NOTICE_BLOCK_AFTER_FINISH_EVENT " +
    -    "NOTICE_BLOCK_ATTACHMENT_PROPERTY " +
    -    "NOTICE_BLOCK_ATTACHMENTS_RIGHTS_GROUP_PROPERTY " +
    -    "NOTICE_BLOCK_ATTACHMENTS_RIGHTS_TYPE_PROPERTY " +
    -    "NOTICE_BLOCK_BEFORE_START_EVENT " +
    -    "NOTICE_BLOCK_CREATED_NOTICES_PROPERTY " +
    -    "NOTICE_BLOCK_DEADLINE_PROPERTY " +
    -    "NOTICE_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY " +
    -    "NOTICE_BLOCK_NAME_PROPERTY " +
    -    "NOTICE_BLOCK_NOTICE_TEXT_PROPERTY " +
    -    "NOTICE_BLOCK_PERFORMER_PROPERTY " +
    -    "NOTICE_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY " +
    -    "NOTICE_BLOCK_SUBJECT_PROPERTY ";
    -
    -  // Object events
    -  const object_events_constants =
    -    "dseAfterCancel " +
    -    "dseAfterClose " +
    -    "dseAfterDelete " +
    -    "dseAfterDeleteOutOfTransaction " +
    -    "dseAfterInsert " +
    -    "dseAfterOpen " +
    -    "dseAfterScroll " +
    -    "dseAfterUpdate " +
    -    "dseAfterUpdateOutOfTransaction " +
    -    "dseBeforeCancel " +
    -    "dseBeforeClose " +
    -    "dseBeforeDelete " +
    -    "dseBeforeDetailUpdate " +
    -    "dseBeforeInsert " +
    -    "dseBeforeOpen " +
    -    "dseBeforeUpdate " +
    -    "dseOnAnyRequisiteChange " +
    -    "dseOnCloseRecord " +
    -    "dseOnDeleteError " +
    -    "dseOnOpenRecord " +
    -    "dseOnPrepareUpdate " +
    -    "dseOnUpdateError " +
    -    "dseOnUpdateRatifiedRecord " +
    -    "dseOnValidDelete " +
    -    "dseOnValidUpdate " +
    -    "reOnChange " +
    -    "reOnChangeValues " +
    -    "SELECTION_BEGIN_ROUTE_EVENT " +
    -    "SELECTION_END_ROUTE_EVENT ";
    -
    -  // Object params
    -  const object_params_constants =
    -    "CURRENT_PERIOD_IS_REQUIRED " +
    -    "PREVIOUS_CARD_TYPE_NAME " +
    -    "SHOW_RECORD_PROPERTIES_FORM ";
    -
    -  // Other
    -  const other_constants =
    -    "ACCESS_RIGHTS_SETTING_DIALOG_CODE " +
    -    "ADMINISTRATOR_USER_CODE " +
    -    "ANALYTIC_REPORT_TYPE " +
    -    "asrtHideLocal " +
    -    "asrtHideRemote " +
    -    "CALCULATED_ROLE_TYPE_CODE " +
    -    "COMPONENTS_REFERENCE_DEVELOPER_VIEW_CODE " +
    -    "DCTS_TEST_PROTOCOLS_FOLDER_PATH " +
    -    "E_EDOC_VERSION_ALREADY_APPROVINGLY_SIGNED " +
    -    "E_EDOC_VERSION_ALREADY_APPROVINGLY_SIGNED_BY_USER " +
    -    "E_EDOC_VERSION_ALREDY_SIGNED " +
    -    "E_EDOC_VERSION_ALREDY_SIGNED_BY_USER " +
    -    "EDOC_TYPES_CODE_REQUISITE_FIELD_NAME " +
    -    "EDOCUMENTS_ALIAS_NAME " +
    -    "FILES_FOLDER_PATH " +
    -    "FILTER_OPERANDS_DELIMITER " +
    -    "FILTER_OPERATIONS_DELIMITER " +
    -    "FORMCARD_NAME " +
    -    "FORMLIST_NAME " +
    -    "GET_EXTENDED_DOCUMENT_EXTENSION_CREATION_MODE " +
    -    "GET_EXTENDED_DOCUMENT_EXTENSION_IMPORT_MODE " +
    -    "INTEGRATED_REPORT_TYPE " +
    -    "IS_BUILDER_APPLICATION_ROLE " +
    -    "IS_BUILDER_APPLICATION_ROLE2 " +
    -    "IS_BUILDER_USERS " +
    -    "ISBSYSDEV " +
    -    "LOG_FOLDER_PATH " +
    -    "mbCancel " +
    -    "mbNo " +
    -    "mbNoToAll " +
    -    "mbOK " +
    -    "mbYes " +
    -    "mbYesToAll " +
    -    "MEMORY_DATASET_DESRIPTIONS_FILENAME " +
    -    "mrNo " +
    -    "mrNoToAll " +
    -    "mrYes " +
    -    "mrYesToAll " +
    -    "MULTIPLE_SELECT_DIALOG_CODE " +
    -    "NONOPERATING_RECORD_FLAG_FEMININE " +
    -    "NONOPERATING_RECORD_FLAG_MASCULINE " +
    -    "OPERATING_RECORD_FLAG_FEMININE " +
    -    "OPERATING_RECORD_FLAG_MASCULINE " +
    -    "PROFILING_SETTINGS_COMMON_SETTINGS_CODE_VALUE " +
    -    "PROGRAM_INITIATED_LOOKUP_ACTION " +
    -    "ratDelete " +
    -    "ratEdit " +
    -    "ratInsert " +
    -    "REPORT_TYPE " +
    -    "REQUIRED_PICK_VALUES_VARIABLE " +
    -    "rmCard " +
    -    "rmList " +
    -    "SBRTE_PROGID_DEV " +
    -    "SBRTE_PROGID_RELEASE " +
    -    "STATIC_ROLE_TYPE_CODE " +
    -    "SUPPRESS_EMPTY_TEMPLATE_CREATION " +
    -    "SYSTEM_USER_CODE " +
    -    "UPDATE_DIALOG_DATASET " +
    -    "USED_IN_OBJECT_HINT_PARAM " +
    -    "USER_INITIATED_LOOKUP_ACTION " +
    -    "USER_NAME_FORMAT " +
    -    "USER_SELECTION_RESTRICTIONS " +
    -    "WORKFLOW_TEST_PROTOCOLS_FOLDER_PATH " +
    -    "ELS_SUBTYPE_CONTROL_NAME " +
    -    "ELS_FOLDER_KIND_CONTROL_NAME " +
    -    "REPEAT_PROCESS_CURRENT_OBJECT_EXCEPTION_NAME ";
    -
    -  // Privileges
    -  const privileges_constants =
    -    "PRIVILEGE_COMPONENT_FULL_ACCESS " +
    -    "PRIVILEGE_DEVELOPMENT_EXPORT " +
    -    "PRIVILEGE_DEVELOPMENT_IMPORT " +
    -    "PRIVILEGE_DOCUMENT_DELETE " +
    -    "PRIVILEGE_ESD " +
    -    "PRIVILEGE_FOLDER_DELETE " +
    -    "PRIVILEGE_MANAGE_ACCESS_RIGHTS " +
    -    "PRIVILEGE_MANAGE_REPLICATION " +
    -    "PRIVILEGE_MANAGE_SESSION_SERVER " +
    -    "PRIVILEGE_OBJECT_FULL_ACCESS " +
    -    "PRIVILEGE_OBJECT_VIEW " +
    -    "PRIVILEGE_RESERVE_LICENSE " +
    -    "PRIVILEGE_SYSTEM_CUSTOMIZE " +
    -    "PRIVILEGE_SYSTEM_DEVELOP " +
    -    "PRIVILEGE_SYSTEM_INSTALL " +
    -    "PRIVILEGE_TASK_DELETE " +
    -    "PRIVILEGE_USER_PLUGIN_SETTINGS_CUSTOMIZE " +
    -    "PRIVILEGES_PSEUDOREFERENCE_CODE ";
    -
    -  // Pseudoreference code
    -  const pseudoreference_code_constants =
    -    "ACCESS_TYPES_PSEUDOREFERENCE_CODE " +
    -    "ALL_AVAILABLE_COMPONENTS_PSEUDOREFERENCE_CODE " +
    -    "ALL_AVAILABLE_PRIVILEGES_PSEUDOREFERENCE_CODE " +
    -    "ALL_REPLICATE_COMPONENTS_PSEUDOREFERENCE_CODE " +
    -    "AVAILABLE_DEVELOPERS_COMPONENTS_PSEUDOREFERENCE_CODE " +
    -    "COMPONENTS_PSEUDOREFERENCE_CODE " +
    -    "FILTRATER_SETTINGS_CONFLICTS_PSEUDOREFERENCE_CODE " +
    -    "GROUPS_PSEUDOREFERENCE_CODE " +
    -    "RECEIVE_PROTOCOL_PSEUDOREFERENCE_CODE " +
    -    "REFERENCE_REQUISITE_PSEUDOREFERENCE_CODE " +
    -    "REFERENCE_REQUISITES_PSEUDOREFERENCE_CODE " +
    -    "REFTYPES_PSEUDOREFERENCE_CODE " +
    -    "REPLICATION_SEANCES_DIARY_PSEUDOREFERENCE_CODE " +
    -    "SEND_PROTOCOL_PSEUDOREFERENCE_CODE " +
    -    "SUBSTITUTES_PSEUDOREFERENCE_CODE " +
    -    "SYSTEM_SETTINGS_PSEUDOREFERENCE_CODE " +
    -    "UNITS_PSEUDOREFERENCE_CODE " +
    -    "USERS_PSEUDOREFERENCE_CODE " +
    -    "VIEWERS_PSEUDOREFERENCE_CODE ";
    -
    -  // Requisite ISBCertificateType values
    -  const requisite_ISBCertificateType_values_constants =
    -    "CERTIFICATE_TYPE_ENCRYPT " +
    -    "CERTIFICATE_TYPE_SIGN " +
    -    "CERTIFICATE_TYPE_SIGN_AND_ENCRYPT ";
    -
    -  // Requisite ISBEDocStorageType values
    -  const requisite_ISBEDocStorageType_values_constants =
    -    "STORAGE_TYPE_FILE " +
    -    "STORAGE_TYPE_NAS_CIFS " +
    -    "STORAGE_TYPE_SAPERION " +
    -    "STORAGE_TYPE_SQL_SERVER ";
    -
    -  // Requisite CompType2 values
    -  const requisite_compType2_values_constants =
    -    "COMPTYPE2_REQUISITE_DOCUMENTS_VALUE " +
    -    "COMPTYPE2_REQUISITE_TASKS_VALUE " +
    -    "COMPTYPE2_REQUISITE_FOLDERS_VALUE " +
    -    "COMPTYPE2_REQUISITE_REFERENCES_VALUE ";
    -
    -  // Requisite name
    -  const requisite_name_constants =
    -    "SYSREQ_CODE " +
    -    "SYSREQ_COMPTYPE2 " +
    -    "SYSREQ_CONST_AVAILABLE_FOR_WEB " +
    -    "SYSREQ_CONST_COMMON_CODE " +
    -    "SYSREQ_CONST_COMMON_VALUE " +
    -    "SYSREQ_CONST_FIRM_CODE " +
    -    "SYSREQ_CONST_FIRM_STATUS " +
    -    "SYSREQ_CONST_FIRM_VALUE " +
    -    "SYSREQ_CONST_SERVER_STATUS " +
    -    "SYSREQ_CONTENTS " +
    -    "SYSREQ_DATE_OPEN " +
    -    "SYSREQ_DATE_CLOSE " +
    -    "SYSREQ_DESCRIPTION " +
    -    "SYSREQ_DESCRIPTION_LOCALIZE_ID " +
    -    "SYSREQ_DOUBLE " +
    -    "SYSREQ_EDOC_ACCESS_TYPE " +
    -    "SYSREQ_EDOC_AUTHOR " +
    -    "SYSREQ_EDOC_CREATED " +
    -    "SYSREQ_EDOC_DELEGATE_RIGHTS_REQUISITE_CODE " +
    -    "SYSREQ_EDOC_EDITOR " +
    -    "SYSREQ_EDOC_ENCODE_TYPE " +
    -    "SYSREQ_EDOC_ENCRYPTION_PLUGIN_NAME " +
    -    "SYSREQ_EDOC_ENCRYPTION_PLUGIN_VERSION " +
    -    "SYSREQ_EDOC_EXPORT_DATE " +
    -    "SYSREQ_EDOC_EXPORTER " +
    -    "SYSREQ_EDOC_KIND " +
    -    "SYSREQ_EDOC_LIFE_STAGE_NAME " +
    -    "SYSREQ_EDOC_LOCKED_FOR_SERVER_CODE " +
    -    "SYSREQ_EDOC_MODIFIED " +
    -    "SYSREQ_EDOC_NAME " +
    -    "SYSREQ_EDOC_NOTE " +
    -    "SYSREQ_EDOC_QUALIFIED_ID " +
    -    "SYSREQ_EDOC_SESSION_KEY " +
    -    "SYSREQ_EDOC_SESSION_KEY_ENCRYPTION_PLUGIN_NAME " +
    -    "SYSREQ_EDOC_SESSION_KEY_ENCRYPTION_PLUGIN_VERSION " +
    -    "SYSREQ_EDOC_SIGNATURE_TYPE " +
    -    "SYSREQ_EDOC_SIGNED " +
    -    "SYSREQ_EDOC_STORAGE " +
    -    "SYSREQ_EDOC_STORAGES_ARCHIVE_STORAGE " +
    -    "SYSREQ_EDOC_STORAGES_CHECK_RIGHTS " +
    -    "SYSREQ_EDOC_STORAGES_COMPUTER_NAME " +
    -    "SYSREQ_EDOC_STORAGES_EDIT_IN_STORAGE " +
    -    "SYSREQ_EDOC_STORAGES_EXECUTIVE_STORAGE " +
    -    "SYSREQ_EDOC_STORAGES_FUNCTION " +
    -    "SYSREQ_EDOC_STORAGES_INITIALIZED " +
    -    "SYSREQ_EDOC_STORAGES_LOCAL_PATH " +
    -    "SYSREQ_EDOC_STORAGES_SAPERION_DATABASE_NAME " +
    -    "SYSREQ_EDOC_STORAGES_SEARCH_BY_TEXT " +
    -    "SYSREQ_EDOC_STORAGES_SERVER_NAME " +
    -    "SYSREQ_EDOC_STORAGES_SHARED_SOURCE_NAME " +
    -    "SYSREQ_EDOC_STORAGES_TYPE " +
    -    "SYSREQ_EDOC_TEXT_MODIFIED " +
    -    "SYSREQ_EDOC_TYPE_ACT_CODE " +
    -    "SYSREQ_EDOC_TYPE_ACT_DESCRIPTION " +
    -    "SYSREQ_EDOC_TYPE_ACT_DESCRIPTION_LOCALIZE_ID " +
    -    "SYSREQ_EDOC_TYPE_ACT_ON_EXECUTE " +
    -    "SYSREQ_EDOC_TYPE_ACT_ON_EXECUTE_EXISTS " +
    -    "SYSREQ_EDOC_TYPE_ACT_SECTION " +
    -    "SYSREQ_EDOC_TYPE_ADD_PARAMS " +
    -    "SYSREQ_EDOC_TYPE_COMMENT " +
    -    "SYSREQ_EDOC_TYPE_EVENT_TEXT " +
    -    "SYSREQ_EDOC_TYPE_NAME_IN_SINGULAR " +
    -    "SYSREQ_EDOC_TYPE_NAME_IN_SINGULAR_LOCALIZE_ID " +
    -    "SYSREQ_EDOC_TYPE_NAME_LOCALIZE_ID " +
    -    "SYSREQ_EDOC_TYPE_NUMERATION_METHOD " +
    -    "SYSREQ_EDOC_TYPE_PSEUDO_REQUISITE_CODE " +
    -    "SYSREQ_EDOC_TYPE_REQ_CODE " +
    -    "SYSREQ_EDOC_TYPE_REQ_DESCRIPTION " +
    -    "SYSREQ_EDOC_TYPE_REQ_DESCRIPTION_LOCALIZE_ID " +
    -    "SYSREQ_EDOC_TYPE_REQ_IS_LEADING " +
    -    "SYSREQ_EDOC_TYPE_REQ_IS_REQUIRED " +
    -    "SYSREQ_EDOC_TYPE_REQ_NUMBER " +
    -    "SYSREQ_EDOC_TYPE_REQ_ON_CHANGE " +
    -    "SYSREQ_EDOC_TYPE_REQ_ON_CHANGE_EXISTS " +
    -    "SYSREQ_EDOC_TYPE_REQ_ON_SELECT " +
    -    "SYSREQ_EDOC_TYPE_REQ_ON_SELECT_KIND " +
    -    "SYSREQ_EDOC_TYPE_REQ_SECTION " +
    -    "SYSREQ_EDOC_TYPE_VIEW_CARD " +
    -    "SYSREQ_EDOC_TYPE_VIEW_CODE " +
    -    "SYSREQ_EDOC_TYPE_VIEW_COMMENT " +
    -    "SYSREQ_EDOC_TYPE_VIEW_IS_MAIN " +
    -    "SYSREQ_EDOC_TYPE_VIEW_NAME " +
    -    "SYSREQ_EDOC_TYPE_VIEW_NAME_LOCALIZE_ID " +
    -    "SYSREQ_EDOC_VERSION_AUTHOR " +
    -    "SYSREQ_EDOC_VERSION_CRC " +
    -    "SYSREQ_EDOC_VERSION_DATA " +
    -    "SYSREQ_EDOC_VERSION_EDITOR " +
    -    "SYSREQ_EDOC_VERSION_EXPORT_DATE " +
    -    "SYSREQ_EDOC_VERSION_EXPORTER " +
    -    "SYSREQ_EDOC_VERSION_HIDDEN " +
    -    "SYSREQ_EDOC_VERSION_LIFE_STAGE " +
    -    "SYSREQ_EDOC_VERSION_MODIFIED " +
    -    "SYSREQ_EDOC_VERSION_NOTE " +
    -    "SYSREQ_EDOC_VERSION_SIGNATURE_TYPE " +
    -    "SYSREQ_EDOC_VERSION_SIGNED " +
    -    "SYSREQ_EDOC_VERSION_SIZE " +
    -    "SYSREQ_EDOC_VERSION_SOURCE " +
    -    "SYSREQ_EDOC_VERSION_TEXT_MODIFIED " +
    -    "SYSREQ_EDOCKIND_DEFAULT_VERSION_STATE_CODE " +
    -    "SYSREQ_FOLDER_KIND " +
    -    "SYSREQ_FUNC_CATEGORY " +
    -    "SYSREQ_FUNC_COMMENT " +
    -    "SYSREQ_FUNC_GROUP " +
    -    "SYSREQ_FUNC_GROUP_COMMENT " +
    -    "SYSREQ_FUNC_GROUP_NUMBER " +
    -    "SYSREQ_FUNC_HELP " +
    -    "SYSREQ_FUNC_PARAM_DEF_VALUE " +
    -    "SYSREQ_FUNC_PARAM_IDENT " +
    -    "SYSREQ_FUNC_PARAM_NUMBER " +
    -    "SYSREQ_FUNC_PARAM_TYPE " +
    -    "SYSREQ_FUNC_TEXT " +
    -    "SYSREQ_GROUP_CATEGORY " +
    -    "SYSREQ_ID " +
    -    "SYSREQ_LAST_UPDATE " +
    -    "SYSREQ_LEADER_REFERENCE " +
    -    "SYSREQ_LINE_NUMBER " +
    -    "SYSREQ_MAIN_RECORD_ID " +
    -    "SYSREQ_NAME " +
    -    "SYSREQ_NAME_LOCALIZE_ID " +
    -    "SYSREQ_NOTE " +
    -    "SYSREQ_ORIGINAL_RECORD " +
    -    "SYSREQ_OUR_FIRM " +
    -    "SYSREQ_PROFILING_SETTINGS_BATCH_LOGING " +
    -    "SYSREQ_PROFILING_SETTINGS_BATCH_SIZE " +
    -    "SYSREQ_PROFILING_SETTINGS_PROFILING_ENABLED " +
    -    "SYSREQ_PROFILING_SETTINGS_SQL_PROFILING_ENABLED " +
    -    "SYSREQ_PROFILING_SETTINGS_START_LOGGED " +
    -    "SYSREQ_RECORD_STATUS " +
    -    "SYSREQ_REF_REQ_FIELD_NAME " +
    -    "SYSREQ_REF_REQ_FORMAT " +
    -    "SYSREQ_REF_REQ_GENERATED " +
    -    "SYSREQ_REF_REQ_LENGTH " +
    -    "SYSREQ_REF_REQ_PRECISION " +
    -    "SYSREQ_REF_REQ_REFERENCE " +
    -    "SYSREQ_REF_REQ_SECTION " +
    -    "SYSREQ_REF_REQ_STORED " +
    -    "SYSREQ_REF_REQ_TOKENS " +
    -    "SYSREQ_REF_REQ_TYPE " +
    -    "SYSREQ_REF_REQ_VIEW " +
    -    "SYSREQ_REF_TYPE_ACT_CODE " +
    -    "SYSREQ_REF_TYPE_ACT_DESCRIPTION " +
    -    "SYSREQ_REF_TYPE_ACT_DESCRIPTION_LOCALIZE_ID " +
    -    "SYSREQ_REF_TYPE_ACT_ON_EXECUTE " +
    -    "SYSREQ_REF_TYPE_ACT_ON_EXECUTE_EXISTS " +
    -    "SYSREQ_REF_TYPE_ACT_SECTION " +
    -    "SYSREQ_REF_TYPE_ADD_PARAMS " +
    -    "SYSREQ_REF_TYPE_COMMENT " +
    -    "SYSREQ_REF_TYPE_COMMON_SETTINGS " +
    -    "SYSREQ_REF_TYPE_DISPLAY_REQUISITE_NAME " +
    -    "SYSREQ_REF_TYPE_EVENT_TEXT " +
    -    "SYSREQ_REF_TYPE_MAIN_LEADING_REF " +
    -    "SYSREQ_REF_TYPE_NAME_IN_SINGULAR " +
    -    "SYSREQ_REF_TYPE_NAME_IN_SINGULAR_LOCALIZE_ID " +
    -    "SYSREQ_REF_TYPE_NAME_LOCALIZE_ID " +
    -    "SYSREQ_REF_TYPE_NUMERATION_METHOD " +
    -    "SYSREQ_REF_TYPE_REQ_CODE " +
    -    "SYSREQ_REF_TYPE_REQ_DESCRIPTION " +
    -    "SYSREQ_REF_TYPE_REQ_DESCRIPTION_LOCALIZE_ID " +
    -    "SYSREQ_REF_TYPE_REQ_IS_CONTROL " +
    -    "SYSREQ_REF_TYPE_REQ_IS_FILTER " +
    -    "SYSREQ_REF_TYPE_REQ_IS_LEADING " +
    -    "SYSREQ_REF_TYPE_REQ_IS_REQUIRED " +
    -    "SYSREQ_REF_TYPE_REQ_NUMBER " +
    -    "SYSREQ_REF_TYPE_REQ_ON_CHANGE " +
    -    "SYSREQ_REF_TYPE_REQ_ON_CHANGE_EXISTS " +
    -    "SYSREQ_REF_TYPE_REQ_ON_SELECT " +
    -    "SYSREQ_REF_TYPE_REQ_ON_SELECT_KIND " +
    -    "SYSREQ_REF_TYPE_REQ_SECTION " +
    -    "SYSREQ_REF_TYPE_VIEW_CARD " +
    -    "SYSREQ_REF_TYPE_VIEW_CODE " +
    -    "SYSREQ_REF_TYPE_VIEW_COMMENT " +
    -    "SYSREQ_REF_TYPE_VIEW_IS_MAIN " +
    -    "SYSREQ_REF_TYPE_VIEW_NAME " +
    -    "SYSREQ_REF_TYPE_VIEW_NAME_LOCALIZE_ID " +
    -    "SYSREQ_REFERENCE_TYPE_ID " +
    -    "SYSREQ_STATE " +
    -    "SYSREQ_STATЕ " +
    -    "SYSREQ_SYSTEM_SETTINGS_VALUE " +
    -    "SYSREQ_TYPE " +
    -    "SYSREQ_UNIT " +
    -    "SYSREQ_UNIT_ID " +
    -    "SYSREQ_USER_GROUPS_GROUP_FULL_NAME " +
    -    "SYSREQ_USER_GROUPS_GROUP_NAME " +
    -    "SYSREQ_USER_GROUPS_GROUP_SERVER_NAME " +
    -    "SYSREQ_USERS_ACCESS_RIGHTS " +
    -    "SYSREQ_USERS_AUTHENTICATION " +
    -    "SYSREQ_USERS_CATEGORY " +
    -    "SYSREQ_USERS_COMPONENT " +
    -    "SYSREQ_USERS_COMPONENT_USER_IS_PUBLIC " +
    -    "SYSREQ_USERS_DOMAIN " +
    -    "SYSREQ_USERS_FULL_USER_NAME " +
    -    "SYSREQ_USERS_GROUP " +
    -    "SYSREQ_USERS_IS_MAIN_SERVER " +
    -    "SYSREQ_USERS_LOGIN " +
    -    "SYSREQ_USERS_REFERENCE_USER_IS_PUBLIC " +
    -    "SYSREQ_USERS_STATUS " +
    -    "SYSREQ_USERS_USER_CERTIFICATE " +
    -    "SYSREQ_USERS_USER_CERTIFICATE_INFO " +
    -    "SYSREQ_USERS_USER_CERTIFICATE_PLUGIN_NAME " +
    -    "SYSREQ_USERS_USER_CERTIFICATE_PLUGIN_VERSION " +
    -    "SYSREQ_USERS_USER_CERTIFICATE_STATE " +
    -    "SYSREQ_USERS_USER_CERTIFICATE_SUBJECT_NAME " +
    -    "SYSREQ_USERS_USER_CERTIFICATE_THUMBPRINT " +
    -    "SYSREQ_USERS_USER_DEFAULT_CERTIFICATE " +
    -    "SYSREQ_USERS_USER_DESCRIPTION " +
    -    "SYSREQ_USERS_USER_GLOBAL_NAME " +
    -    "SYSREQ_USERS_USER_LOGIN " +
    -    "SYSREQ_USERS_USER_MAIN_SERVER " +
    -    "SYSREQ_USERS_USER_TYPE " +
    -    "SYSREQ_WORK_RULES_FOLDER_ID ";
    -
    -  // Result
    -  const result_constants = "RESULT_VAR_NAME RESULT_VAR_NAME_ENG ";
    -
    -  // Rule identification
    -  const rule_identification_constants =
    -    "AUTO_NUMERATION_RULE_ID " +
    -    "CANT_CHANGE_ID_REQUISITE_RULE_ID " +
    -    "CANT_CHANGE_OURFIRM_REQUISITE_RULE_ID " +
    -    "CHECK_CHANGING_REFERENCE_RECORD_USE_RULE_ID " +
    -    "CHECK_CODE_REQUISITE_RULE_ID " +
    -    "CHECK_DELETING_REFERENCE_RECORD_USE_RULE_ID " +
    -    "CHECK_FILTRATER_CHANGES_RULE_ID " +
    -    "CHECK_RECORD_INTERVAL_RULE_ID " +
    -    "CHECK_REFERENCE_INTERVAL_RULE_ID " +
    -    "CHECK_REQUIRED_DATA_FULLNESS_RULE_ID " +
    -    "CHECK_REQUIRED_REQUISITES_FULLNESS_RULE_ID " +
    -    "MAKE_RECORD_UNRATIFIED_RULE_ID " +
    -    "RESTORE_AUTO_NUMERATION_RULE_ID " +
    -    "SET_FIRM_CONTEXT_FROM_RECORD_RULE_ID " +
    -    "SET_FIRST_RECORD_IN_LIST_FORM_RULE_ID " +
    -    "SET_IDSPS_VALUE_RULE_ID " +
    -    "SET_NEXT_CODE_VALUE_RULE_ID " +
    -    "SET_OURFIRM_BOUNDS_RULE_ID " +
    -    "SET_OURFIRM_REQUISITE_RULE_ID ";
    -
    -  // Script block properties
    -  const script_block_properties_constants =
    -    "SCRIPT_BLOCK_AFTER_FINISH_EVENT " +
    -    "SCRIPT_BLOCK_BEFORE_START_EVENT " +
    -    "SCRIPT_BLOCK_EXECUTION_RESULTS_PROPERTY " +
    -    "SCRIPT_BLOCK_NAME_PROPERTY " +
    -    "SCRIPT_BLOCK_SCRIPT_PROPERTY ";
    -
    -  // Subtask block properties
    -  const subtask_block_properties_constants =
    -    "SUBTASK_BLOCK_ABORT_DEADLINE_PROPERTY " +
    -    "SUBTASK_BLOCK_AFTER_FINISH_EVENT " +
    -    "SUBTASK_BLOCK_ASSIGN_PARAMS_EVENT " +
    -    "SUBTASK_BLOCK_ATTACHMENTS_PROPERTY " +
    -    "SUBTASK_BLOCK_ATTACHMENTS_RIGHTS_GROUP_PROPERTY " +
    -    "SUBTASK_BLOCK_ATTACHMENTS_RIGHTS_TYPE_PROPERTY " +
    -    "SUBTASK_BLOCK_BEFORE_START_EVENT " +
    -    "SUBTASK_BLOCK_CREATED_TASK_PROPERTY " +
    -    "SUBTASK_BLOCK_CREATION_EVENT " +
    -    "SUBTASK_BLOCK_DEADLINE_PROPERTY " +
    -    "SUBTASK_BLOCK_IMPORTANCE_PROPERTY " +
    -    "SUBTASK_BLOCK_INITIATOR_PROPERTY " +
    -    "SUBTASK_BLOCK_IS_RELATIVE_ABORT_DEADLINE_PROPERTY " +
    -    "SUBTASK_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY " +
    -    "SUBTASK_BLOCK_JOBS_TYPE_PROPERTY " +
    -    "SUBTASK_BLOCK_NAME_PROPERTY " +
    -    "SUBTASK_BLOCK_PARALLEL_ROUTE_PROPERTY " +
    -    "SUBTASK_BLOCK_PERFORMERS_PROPERTY " +
    -    "SUBTASK_BLOCK_RELATIVE_ABORT_DEADLINE_TYPE_PROPERTY " +
    -    "SUBTASK_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY " +
    -    "SUBTASK_BLOCK_REQUIRE_SIGN_PROPERTY " +
    -    "SUBTASK_BLOCK_STANDARD_ROUTE_PROPERTY " +
    -    "SUBTASK_BLOCK_START_EVENT " +
    -    "SUBTASK_BLOCK_STEP_CONTROL_PROPERTY " +
    -    "SUBTASK_BLOCK_SUBJECT_PROPERTY " +
    -    "SUBTASK_BLOCK_TASK_CONTROL_PROPERTY " +
    -    "SUBTASK_BLOCK_TEXT_PROPERTY " +
    -    "SUBTASK_BLOCK_UNLOCK_ATTACHMENTS_ON_STOP_PROPERTY " +
    -    "SUBTASK_BLOCK_USE_STANDARD_ROUTE_PROPERTY " +
    -    "SUBTASK_BLOCK_WAIT_FOR_TASK_COMPLETE_PROPERTY ";
    -
    -  // System component
    -  const system_component_constants =
    -    "SYSCOMP_CONTROL_JOBS " +
    -    "SYSCOMP_FOLDERS " +
    -    "SYSCOMP_JOBS " +
    -    "SYSCOMP_NOTICES " +
    -    "SYSCOMP_TASKS ";
    -
    -  // System dialogs
    -  const system_dialogs_constants =
    -    "SYSDLG_CREATE_EDOCUMENT " +
    -    "SYSDLG_CREATE_EDOCUMENT_VERSION " +
    -    "SYSDLG_CURRENT_PERIOD " +
    -    "SYSDLG_EDIT_FUNCTION_HELP " +
    -    "SYSDLG_EDOCUMENT_KINDS_FOR_TEMPLATE " +
    -    "SYSDLG_EXPORT_MULTIPLE_EDOCUMENTS " +
    -    "SYSDLG_EXPORT_SINGLE_EDOCUMENT " +
    -    "SYSDLG_IMPORT_EDOCUMENT " +
    -    "SYSDLG_MULTIPLE_SELECT " +
    -    "SYSDLG_SETUP_ACCESS_RIGHTS " +
    -    "SYSDLG_SETUP_DEFAULT_RIGHTS " +
    -    "SYSDLG_SETUP_FILTER_CONDITION " +
    -    "SYSDLG_SETUP_SIGN_RIGHTS " +
    -    "SYSDLG_SETUP_TASK_OBSERVERS " +
    -    "SYSDLG_SETUP_TASK_ROUTE " +
    -    "SYSDLG_SETUP_USERS_LIST " +
    -    "SYSDLG_SIGN_EDOCUMENT " +
    -    "SYSDLG_SIGN_MULTIPLE_EDOCUMENTS ";
    -
    -  // System reference names
    -  const system_reference_names_constants =
    -    "SYSREF_ACCESS_RIGHTS_TYPES " +
    -    "SYSREF_ADMINISTRATION_HISTORY " +
    -    "SYSREF_ALL_AVAILABLE_COMPONENTS " +
    -    "SYSREF_ALL_AVAILABLE_PRIVILEGES " +
    -    "SYSREF_ALL_REPLICATING_COMPONENTS " +
    -    "SYSREF_AVAILABLE_DEVELOPERS_COMPONENTS " +
    -    "SYSREF_CALENDAR_EVENTS " +
    -    "SYSREF_COMPONENT_TOKEN_HISTORY " +
    -    "SYSREF_COMPONENT_TOKENS " +
    -    "SYSREF_COMPONENTS " +
    -    "SYSREF_CONSTANTS " +
    -    "SYSREF_DATA_RECEIVE_PROTOCOL " +
    -    "SYSREF_DATA_SEND_PROTOCOL " +
    -    "SYSREF_DIALOGS " +
    -    "SYSREF_DIALOGS_REQUISITES " +
    -    "SYSREF_EDITORS " +
    -    "SYSREF_EDOC_CARDS " +
    -    "SYSREF_EDOC_TYPES " +
    -    "SYSREF_EDOCUMENT_CARD_REQUISITES " +
    -    "SYSREF_EDOCUMENT_CARD_TYPES " +
    -    "SYSREF_EDOCUMENT_CARD_TYPES_REFERENCE " +
    -    "SYSREF_EDOCUMENT_CARDS " +
    -    "SYSREF_EDOCUMENT_HISTORY " +
    -    "SYSREF_EDOCUMENT_KINDS " +
    -    "SYSREF_EDOCUMENT_REQUISITES " +
    -    "SYSREF_EDOCUMENT_SIGNATURES " +
    -    "SYSREF_EDOCUMENT_TEMPLATES " +
    -    "SYSREF_EDOCUMENT_TEXT_STORAGES " +
    -    "SYSREF_EDOCUMENT_VIEWS " +
    -    "SYSREF_FILTERER_SETUP_CONFLICTS " +
    -    "SYSREF_FILTRATER_SETTING_CONFLICTS " +
    -    "SYSREF_FOLDER_HISTORY " +
    -    "SYSREF_FOLDERS " +
    -    "SYSREF_FUNCTION_GROUPS " +
    -    "SYSREF_FUNCTION_PARAMS " +
    -    "SYSREF_FUNCTIONS " +
    -    "SYSREF_JOB_HISTORY " +
    -    "SYSREF_LINKS " +
    -    "SYSREF_LOCALIZATION_DICTIONARY " +
    -    "SYSREF_LOCALIZATION_LANGUAGES " +
    -    "SYSREF_MODULES " +
    -    "SYSREF_PRIVILEGES " +
    -    "SYSREF_RECORD_HISTORY " +
    -    "SYSREF_REFERENCE_REQUISITES " +
    -    "SYSREF_REFERENCE_TYPE_VIEWS " +
    -    "SYSREF_REFERENCE_TYPES " +
    -    "SYSREF_REFERENCES " +
    -    "SYSREF_REFERENCES_REQUISITES " +
    -    "SYSREF_REMOTE_SERVERS " +
    -    "SYSREF_REPLICATION_SESSIONS_LOG " +
    -    "SYSREF_REPLICATION_SESSIONS_PROTOCOL " +
    -    "SYSREF_REPORTS " +
    -    "SYSREF_ROLES " +
    -    "SYSREF_ROUTE_BLOCK_GROUPS " +
    -    "SYSREF_ROUTE_BLOCKS " +
    -    "SYSREF_SCRIPTS " +
    -    "SYSREF_SEARCHES " +
    -    "SYSREF_SERVER_EVENTS " +
    -    "SYSREF_SERVER_EVENTS_HISTORY " +
    -    "SYSREF_STANDARD_ROUTE_GROUPS " +
    -    "SYSREF_STANDARD_ROUTES " +
    -    "SYSREF_STATUSES " +
    -    "SYSREF_SYSTEM_SETTINGS " +
    -    "SYSREF_TASK_HISTORY " +
    -    "SYSREF_TASK_KIND_GROUPS " +
    -    "SYSREF_TASK_KINDS " +
    -    "SYSREF_TASK_RIGHTS " +
    -    "SYSREF_TASK_SIGNATURES " +
    -    "SYSREF_TASKS " +
    -    "SYSREF_UNITS " +
    -    "SYSREF_USER_GROUPS " +
    -    "SYSREF_USER_GROUPS_REFERENCE " +
    -    "SYSREF_USER_SUBSTITUTION " +
    -    "SYSREF_USERS " +
    -    "SYSREF_USERS_REFERENCE " +
    -    "SYSREF_VIEWERS " +
    -    "SYSREF_WORKING_TIME_CALENDARS ";
    -
    -  // Table name
    -  const table_name_constants =
    -    "ACCESS_RIGHTS_TABLE_NAME " +
    -    "EDMS_ACCESS_TABLE_NAME " +
    -    "EDOC_TYPES_TABLE_NAME ";
    -
    -  // Test
    -  const test_constants =
    -    "TEST_DEV_DB_NAME " +
    -    "TEST_DEV_SYSTEM_CODE " +
    -    "TEST_EDMS_DB_NAME " +
    -    "TEST_EDMS_MAIN_CODE " +
    -    "TEST_EDMS_MAIN_DB_NAME " +
    -    "TEST_EDMS_SECOND_CODE " +
    -    "TEST_EDMS_SECOND_DB_NAME " +
    -    "TEST_EDMS_SYSTEM_CODE " +
    -    "TEST_ISB5_MAIN_CODE " +
    -    "TEST_ISB5_SECOND_CODE " +
    -    "TEST_SQL_SERVER_2005_NAME " +
    -    "TEST_SQL_SERVER_NAME ";
    -
    -  // Using the dialog windows
    -  const using_the_dialog_windows_constants =
    -    "ATTENTION_CAPTION " +
    -    "cbsCommandLinks " +
    -    "cbsDefault " +
    -    "CONFIRMATION_CAPTION " +
    -    "ERROR_CAPTION " +
    -    "INFORMATION_CAPTION " +
    -    "mrCancel " +
    -    "mrOk ";
    -
    -  // Using the document
    -  const using_the_document_constants =
    -    "EDOC_VERSION_ACTIVE_STAGE_CODE " +
    -    "EDOC_VERSION_DESIGN_STAGE_CODE " +
    -    "EDOC_VERSION_OBSOLETE_STAGE_CODE ";
    -
    -  // Using the EA and encryption
    -  const using_the_EA_and_encryption_constants =
    -    "cpDataEnciphermentEnabled " +
    -    "cpDigitalSignatureEnabled " +
    -    "cpID " +
    -    "cpIssuer " +
    -    "cpPluginVersion " +
    -    "cpSerial " +
    -    "cpSubjectName " +
    -    "cpSubjSimpleName " +
    -    "cpValidFromDate " +
    -    "cpValidToDate ";
    -
    -  // Using the ISBL-editor
    -  const using_the_ISBL_editor_constants =
    -    "ISBL_SYNTAX " + "NO_SYNTAX " + "XML_SYNTAX ";
    -
    -  // Wait block properties
    -  const wait_block_properties_constants =
    -    "WAIT_BLOCK_AFTER_FINISH_EVENT " +
    -    "WAIT_BLOCK_BEFORE_START_EVENT " +
    -    "WAIT_BLOCK_DEADLINE_PROPERTY " +
    -    "WAIT_BLOCK_IS_RELATIVE_DEADLINE_PROPERTY " +
    -    "WAIT_BLOCK_NAME_PROPERTY " +
    -    "WAIT_BLOCK_RELATIVE_DEADLINE_TYPE_PROPERTY ";
    -
    -  // SYSRES Common
    -  const sysres_common_constants =
    -    "SYSRES_COMMON " +
    -    "SYSRES_CONST " +
    -    "SYSRES_MBFUNC " +
    -    "SYSRES_SBDATA " +
    -    "SYSRES_SBGUI " +
    -    "SYSRES_SBINTF " +
    -    "SYSRES_SBREFDSC " +
    -    "SYSRES_SQLERRORS " +
    -    "SYSRES_SYSCOMP ";
    -
    -  // Константы ==> built_in
    -  const CONSTANTS =
    -    sysres_constants +
    -    base_constants +
    -    base_group_name_constants +
    -    decision_block_properties_constants +
    -    file_extension_constants +
    -    job_block_properties_constants +
    -    language_code_constants +
    -    launching_external_applications_constants +
    -    link_kind_constants +
    -    lock_type_constants +
    -    monitor_block_properties_constants +
    -    notice_block_properties_constants +
    -    object_events_constants +
    -    object_params_constants +
    -    other_constants +
    -    privileges_constants +
    -    pseudoreference_code_constants +
    -    requisite_ISBCertificateType_values_constants +
    -    requisite_ISBEDocStorageType_values_constants +
    -    requisite_compType2_values_constants +
    -    requisite_name_constants +
    -    result_constants +
    -    rule_identification_constants +
    -    script_block_properties_constants +
    -    subtask_block_properties_constants +
    -    system_component_constants +
    -    system_dialogs_constants +
    -    system_reference_names_constants +
    -    table_name_constants +
    -    test_constants +
    -    using_the_dialog_windows_constants +
    -    using_the_document_constants +
    -    using_the_EA_and_encryption_constants +
    -    using_the_ISBL_editor_constants +
    -    wait_block_properties_constants +
    -    sysres_common_constants;
    -
    -  // enum TAccountType
    -  const TAccountType = "atUser atGroup atRole ";
    -
    -  // enum TActionEnabledMode
    -  const TActionEnabledMode =
    -    "aemEnabledAlways " +
    -    "aemDisabledAlways " +
    -    "aemEnabledOnBrowse " +
    -    "aemEnabledOnEdit " +
    -    "aemDisabledOnBrowseEmpty ";
    -
    -  // enum TAddPosition
    -  const TAddPosition = "apBegin apEnd ";
    -
    -  // enum TAlignment
    -  const TAlignment = "alLeft alRight ";
    -
    -  // enum TAreaShowMode
    -  const TAreaShowMode =
    -    "asmNever " +
    -    "asmNoButCustomize " +
    -    "asmAsLastTime " +
    -    "asmYesButCustomize " +
    -    "asmAlways ";
    -
    -  // enum TCertificateInvalidationReason
    -  const TCertificateInvalidationReason = "cirCommon cirRevoked ";
    -
    -  // enum TCertificateType
    -  const TCertificateType = "ctSignature ctEncode ctSignatureEncode ";
    -
    -  // enum TCheckListBoxItemState
    -  const TCheckListBoxItemState = "clbUnchecked clbChecked clbGrayed ";
    -
    -  // enum TCloseOnEsc
    -  const TCloseOnEsc = "ceISB ceAlways ceNever ";
    -
    -  // enum TCompType
    -  const TCompType =
    -    "ctDocument " +
    -    "ctReference " +
    -    "ctScript " +
    -    "ctUnknown " +
    -    "ctReport " +
    -    "ctDialog " +
    -    "ctFunction " +
    -    "ctFolder " +
    -    "ctEDocument " +
    -    "ctTask " +
    -    "ctJob " +
    -    "ctNotice " +
    -    "ctControlJob ";
    -
    -  // enum TConditionFormat
    -  const TConditionFormat = "cfInternal cfDisplay ";
    -
    -  // enum TConnectionIntent
    -  const TConnectionIntent = "ciUnspecified ciWrite ciRead ";
    -
    -  // enum TContentKind
    -  const TContentKind =
    -    "ckFolder " +
    -    "ckEDocument " +
    -    "ckTask " +
    -    "ckJob " +
    -    "ckComponentToken " +
    -    "ckAny " +
    -    "ckReference " +
    -    "ckScript " +
    -    "ckReport " +
    -    "ckDialog ";
    -
    -  // enum TControlType
    -  const TControlType =
    -    "ctISBLEditor " +
    -    "ctBevel " +
    -    "ctButton " +
    -    "ctCheckListBox " +
    -    "ctComboBox " +
    -    "ctComboEdit " +
    -    "ctGrid " +
    -    "ctDBCheckBox " +
    -    "ctDBComboBox " +
    -    "ctDBEdit " +
    -    "ctDBEllipsis " +
    -    "ctDBMemo " +
    -    "ctDBNavigator " +
    -    "ctDBRadioGroup " +
    -    "ctDBStatusLabel " +
    -    "ctEdit " +
    -    "ctGroupBox " +
    -    "ctInplaceHint " +
    -    "ctMemo " +
    -    "ctPanel " +
    -    "ctListBox " +
    -    "ctRadioButton " +
    -    "ctRichEdit " +
    -    "ctTabSheet " +
    -    "ctWebBrowser " +
    -    "ctImage " +
    -    "ctHyperLink " +
    -    "ctLabel " +
    -    "ctDBMultiEllipsis " +
    -    "ctRibbon " +
    -    "ctRichView " +
    -    "ctInnerPanel " +
    -    "ctPanelGroup " +
    -    "ctBitButton ";
    -
    -  // enum TCriterionContentType
    -  const TCriterionContentType =
    -    "cctDate " +
    -    "cctInteger " +
    -    "cctNumeric " +
    -    "cctPick " +
    -    "cctReference " +
    -    "cctString " +
    -    "cctText ";
    -
    -  // enum TCultureType
    -  const TCultureType = "cltInternal cltPrimary cltGUI ";
    -
    -  // enum TDataSetEventType
    -  const TDataSetEventType =
    -    "dseBeforeOpen " +
    -    "dseAfterOpen " +
    -    "dseBeforeClose " +
    -    "dseAfterClose " +
    -    "dseOnValidDelete " +
    -    "dseBeforeDelete " +
    -    "dseAfterDelete " +
    -    "dseAfterDeleteOutOfTransaction " +
    -    "dseOnDeleteError " +
    -    "dseBeforeInsert " +
    -    "dseAfterInsert " +
    -    "dseOnValidUpdate " +
    -    "dseBeforeUpdate " +
    -    "dseOnUpdateRatifiedRecord " +
    -    "dseAfterUpdate " +
    -    "dseAfterUpdateOutOfTransaction " +
    -    "dseOnUpdateError " +
    -    "dseAfterScroll " +
    -    "dseOnOpenRecord " +
    -    "dseOnCloseRecord " +
    -    "dseBeforeCancel " +
    -    "dseAfterCancel " +
    -    "dseOnUpdateDeadlockError " +
    -    "dseBeforeDetailUpdate " +
    -    "dseOnPrepareUpdate " +
    -    "dseOnAnyRequisiteChange ";
    -
    -  // enum TDataSetState
    -  const TDataSetState = "dssEdit dssInsert dssBrowse dssInActive ";
    -
    -  // enum TDateFormatType
    -  const TDateFormatType = "dftDate dftShortDate dftDateTime dftTimeStamp ";
    -
    -  // enum TDateOffsetType
    -  const TDateOffsetType = "dotDays dotHours dotMinutes dotSeconds ";
    -
    -  // enum TDateTimeKind
    -  const TDateTimeKind = "dtkndLocal dtkndUTC ";
    -
    -  // enum TDeaAccessRights
    -  const TDeaAccessRights = "arNone arView arEdit arFull ";
    -
    -  // enum TDocumentDefaultAction
    -  const TDocumentDefaultAction = "ddaView ddaEdit ";
    -
    -  // enum TEditMode
    -  const TEditMode =
    -    "emLock " +
    -    "emEdit " +
    -    "emSign " +
    -    "emExportWithLock " +
    -    "emImportWithUnlock " +
    -    "emChangeVersionNote " +
    -    "emOpenForModify " +
    -    "emChangeLifeStage " +
    -    "emDelete " +
    -    "emCreateVersion " +
    -    "emImport " +
    -    "emUnlockExportedWithLock " +
    -    "emStart " +
    -    "emAbort " +
    -    "emReInit " +
    -    "emMarkAsReaded " +
    -    "emMarkAsUnreaded " +
    -    "emPerform " +
    -    "emAccept " +
    -    "emResume " +
    -    "emChangeRights " +
    -    "emEditRoute " +
    -    "emEditObserver " +
    -    "emRecoveryFromLocalCopy " +
    -    "emChangeWorkAccessType " +
    -    "emChangeEncodeTypeToCertificate " +
    -    "emChangeEncodeTypeToPassword " +
    -    "emChangeEncodeTypeToNone " +
    -    "emChangeEncodeTypeToCertificatePassword " +
    -    "emChangeStandardRoute " +
    -    "emGetText " +
    -    "emOpenForView " +
    -    "emMoveToStorage " +
    -    "emCreateObject " +
    -    "emChangeVersionHidden " +
    -    "emDeleteVersion " +
    -    "emChangeLifeCycleStage " +
    -    "emApprovingSign " +
    -    "emExport " +
    -    "emContinue " +
    -    "emLockFromEdit " +
    -    "emUnLockForEdit " +
    -    "emLockForServer " +
    -    "emUnlockFromServer " +
    -    "emDelegateAccessRights " +
    -    "emReEncode ";
    -
    -  // enum TEditorCloseObservType
    -  const TEditorCloseObservType = "ecotFile ecotProcess ";
    -
    -  // enum TEdmsApplicationAction
    -  const TEdmsApplicationAction = "eaGet eaCopy eaCreate eaCreateStandardRoute ";
    -
    -  // enum TEDocumentLockType
    -  const TEDocumentLockType = "edltAll edltNothing edltQuery ";
    -
    -  // enum TEDocumentStepShowMode
    -  const TEDocumentStepShowMode = "essmText essmCard ";
    -
    -  // enum TEDocumentStepVersionType
    -  const TEDocumentStepVersionType = "esvtLast esvtLastActive esvtSpecified ";
    -
    -  // enum TEDocumentStorageFunction
    -  const TEDocumentStorageFunction = "edsfExecutive edsfArchive ";
    -
    -  // enum TEDocumentStorageType
    -  const TEDocumentStorageType = "edstSQLServer edstFile ";
    -
    -  // enum TEDocumentVersionSourceType
    -  const TEDocumentVersionSourceType =
    -    "edvstNone edvstEDocumentVersionCopy edvstFile edvstTemplate edvstScannedFile ";
    -
    -  // enum TEDocumentVersionState
    -  const TEDocumentVersionState = "vsDefault vsDesign vsActive vsObsolete ";
    -
    -  // enum TEncodeType
    -  const TEncodeType = "etNone etCertificate etPassword etCertificatePassword ";
    -
    -  // enum TExceptionCategory
    -  const TExceptionCategory = "ecException ecWarning ecInformation ";
    -
    -  // enum TExportedSignaturesType
    -  const TExportedSignaturesType = "estAll estApprovingOnly ";
    -
    -  // enum TExportedVersionType
    -  const TExportedVersionType = "evtLast evtLastActive evtQuery ";
    -
    -  // enum TFieldDataType
    -  const TFieldDataType =
    -    "fdtString " +
    -    "fdtNumeric " +
    -    "fdtInteger " +
    -    "fdtDate " +
    -    "fdtText " +
    -    "fdtUnknown " +
    -    "fdtWideString " +
    -    "fdtLargeInteger ";
    -
    -  // enum TFolderType
    -  const TFolderType =
    -    "ftInbox " +
    -    "ftOutbox " +
    -    "ftFavorites " +
    -    "ftCommonFolder " +
    -    "ftUserFolder " +
    -    "ftComponents " +
    -    "ftQuickLaunch " +
    -    "ftShortcuts " +
    -    "ftSearch ";
    -
    -  // enum TGridRowHeight
    -  const TGridRowHeight = "grhAuto " + "grhX1 " + "grhX2 " + "grhX3 ";
    -
    -  // enum THyperlinkType
    -  const THyperlinkType = "hltText " + "hltRTF " + "hltHTML ";
    -
    -  // enum TImageFileFormat
    -  const TImageFileFormat =
    -    "iffBMP " +
    -    "iffJPEG " +
    -    "iffMultiPageTIFF " +
    -    "iffSinglePageTIFF " +
    -    "iffTIFF " +
    -    "iffPNG ";
    -
    -  // enum TImageMode
    -  const TImageMode = "im8bGrayscale " + "im24bRGB " + "im1bMonochrome ";
    -
    -  // enum TImageType
    -  const TImageType = "itBMP " + "itJPEG " + "itWMF " + "itPNG ";
    -
    -  // enum TInplaceHintKind
    -  const TInplaceHintKind =
    -    "ikhInformation " + "ikhWarning " + "ikhError " + "ikhNoIcon ";
    -
    -  // enum TISBLContext
    -  const TISBLContext =
    -    "icUnknown " +
    -    "icScript " +
    -    "icFunction " +
    -    "icIntegratedReport " +
    -    "icAnalyticReport " +
    -    "icDataSetEventHandler " +
    -    "icActionHandler " +
    -    "icFormEventHandler " +
    -    "icLookUpEventHandler " +
    -    "icRequisiteChangeEventHandler " +
    -    "icBeforeSearchEventHandler " +
    -    "icRoleCalculation " +
    -    "icSelectRouteEventHandler " +
    -    "icBlockPropertyCalculation " +
    -    "icBlockQueryParamsEventHandler " +
    -    "icChangeSearchResultEventHandler " +
    -    "icBlockEventHandler " +
    -    "icSubTaskInitEventHandler " +
    -    "icEDocDataSetEventHandler " +
    -    "icEDocLookUpEventHandler " +
    -    "icEDocActionHandler " +
    -    "icEDocFormEventHandler " +
    -    "icEDocRequisiteChangeEventHandler " +
    -    "icStructuredConversionRule " +
    -    "icStructuredConversionEventBefore " +
    -    "icStructuredConversionEventAfter " +
    -    "icWizardEventHandler " +
    -    "icWizardFinishEventHandler " +
    -    "icWizardStepEventHandler " +
    -    "icWizardStepFinishEventHandler " +
    -    "icWizardActionEnableEventHandler " +
    -    "icWizardActionExecuteEventHandler " +
    -    "icCreateJobsHandler " +
    -    "icCreateNoticesHandler " +
    -    "icBeforeLookUpEventHandler " +
    -    "icAfterLookUpEventHandler " +
    -    "icTaskAbortEventHandler " +
    -    "icWorkflowBlockActionHandler " +
    -    "icDialogDataSetEventHandler " +
    -    "icDialogActionHandler " +
    -    "icDialogLookUpEventHandler " +
    -    "icDialogRequisiteChangeEventHandler " +
    -    "icDialogFormEventHandler " +
    -    "icDialogValidCloseEventHandler " +
    -    "icBlockFormEventHandler " +
    -    "icTaskFormEventHandler " +
    -    "icReferenceMethod " +
    -    "icEDocMethod " +
    -    "icDialogMethod " +
    -    "icProcessMessageHandler ";
    -
    -  // enum TItemShow
    -  const TItemShow = "isShow " + "isHide " + "isByUserSettings ";
    -
    -  // enum TJobKind
    -  const TJobKind = "jkJob " + "jkNotice " + "jkControlJob ";
    -
    -  // enum TJoinType
    -  const TJoinType = "jtInner " + "jtLeft " + "jtRight " + "jtFull " + "jtCross ";
    -
    -  // enum TLabelPos
    -  const TLabelPos = "lbpAbove " + "lbpBelow " + "lbpLeft " + "lbpRight ";
    -
    -  // enum TLicensingType
    -  const TLicensingType = "eltPerConnection " + "eltPerUser ";
    -
    -  // enum TLifeCycleStageFontColor
    -  const TLifeCycleStageFontColor =
    -    "sfcUndefined " +
    -    "sfcBlack " +
    -    "sfcGreen " +
    -    "sfcRed " +
    -    "sfcBlue " +
    -    "sfcOrange " +
    -    "sfcLilac ";
    -
    -  // enum TLifeCycleStageFontStyle
    -  const TLifeCycleStageFontStyle = "sfsItalic " + "sfsStrikeout " + "sfsNormal ";
    -
    -  // enum TLockableDevelopmentComponentType
    -  const TLockableDevelopmentComponentType =
    -    "ldctStandardRoute " +
    -    "ldctWizard " +
    -    "ldctScript " +
    -    "ldctFunction " +
    -    "ldctRouteBlock " +
    -    "ldctIntegratedReport " +
    -    "ldctAnalyticReport " +
    -    "ldctReferenceType " +
    -    "ldctEDocumentType " +
    -    "ldctDialog " +
    -    "ldctServerEvents ";
    -
    -  // enum TMaxRecordCountRestrictionType
    -  const TMaxRecordCountRestrictionType =
    -    "mrcrtNone " + "mrcrtUser " + "mrcrtMaximal " + "mrcrtCustom ";
    -
    -  // enum TRangeValueType
    -  const TRangeValueType =
    -    "vtEqual " + "vtGreaterOrEqual " + "vtLessOrEqual " + "vtRange ";
    -
    -  // enum TRelativeDate
    -  const TRelativeDate =
    -    "rdYesterday " +
    -    "rdToday " +
    -    "rdTomorrow " +
    -    "rdThisWeek " +
    -    "rdThisMonth " +
    -    "rdThisYear " +
    -    "rdNextMonth " +
    -    "rdNextWeek " +
    -    "rdLastWeek " +
    -    "rdLastMonth ";
    -
    -  // enum TReportDestination
    -  const TReportDestination = "rdWindow " + "rdFile " + "rdPrinter ";
    -
    -  // enum TReqDataType
    -  const TReqDataType =
    -    "rdtString " +
    -    "rdtNumeric " +
    -    "rdtInteger " +
    -    "rdtDate " +
    -    "rdtReference " +
    -    "rdtAccount " +
    -    "rdtText " +
    -    "rdtPick " +
    -    "rdtUnknown " +
    -    "rdtLargeInteger " +
    -    "rdtDocument ";
    -
    -  // enum TRequisiteEventType
    -  const TRequisiteEventType = "reOnChange " + "reOnChangeValues ";
    -
    -  // enum TSBTimeType
    -  const TSBTimeType = "ttGlobal " + "ttLocal " + "ttUser " + "ttSystem ";
    -
    -  // enum TSearchShowMode
    -  const TSearchShowMode =
    -    "ssmBrowse " + "ssmSelect " + "ssmMultiSelect " + "ssmBrowseModal ";
    -
    -  // enum TSelectMode
    -  const TSelectMode = "smSelect " + "smLike " + "smCard ";
    -
    -  // enum TSignatureType
    -  const TSignatureType = "stNone " + "stAuthenticating " + "stApproving ";
    -
    -  // enum TSignerContentType
    -  const TSignerContentType = "sctString " + "sctStream ";
    -
    -  // enum TStringsSortType
    -  const TStringsSortType = "sstAnsiSort " + "sstNaturalSort ";
    -
    -  // enum TStringValueType
    -  const TStringValueType = "svtEqual " + "svtContain ";
    -
    -  // enum TStructuredObjectAttributeType
    -  const TStructuredObjectAttributeType =
    -    "soatString " +
    -    "soatNumeric " +
    -    "soatInteger " +
    -    "soatDatetime " +
    -    "soatReferenceRecord " +
    -    "soatText " +
    -    "soatPick " +
    -    "soatBoolean " +
    -    "soatEDocument " +
    -    "soatAccount " +
    -    "soatIntegerCollection " +
    -    "soatNumericCollection " +
    -    "soatStringCollection " +
    -    "soatPickCollection " +
    -    "soatDatetimeCollection " +
    -    "soatBooleanCollection " +
    -    "soatReferenceRecordCollection " +
    -    "soatEDocumentCollection " +
    -    "soatAccountCollection " +
    -    "soatContents " +
    -    "soatUnknown ";
    -
    -  // enum TTaskAbortReason
    -  const TTaskAbortReason = "tarAbortByUser " + "tarAbortByWorkflowException ";
    -
    -  // enum TTextValueType
    -  const TTextValueType = "tvtAllWords " + "tvtExactPhrase " + "tvtAnyWord ";
    -
    -  // enum TUserObjectStatus
    -  const TUserObjectStatus =
    -    "usNone " +
    -    "usCompleted " +
    -    "usRedSquare " +
    -    "usBlueSquare " +
    -    "usYellowSquare " +
    -    "usGreenSquare " +
    -    "usOrangeSquare " +
    -    "usPurpleSquare " +
    -    "usFollowUp ";
    -
    -  // enum TUserType
    -  const TUserType =
    -    "utUnknown " +
    -    "utUser " +
    -    "utDeveloper " +
    -    "utAdministrator " +
    -    "utSystemDeveloper " +
    -    "utDisconnected ";
    -
    -  // enum TValuesBuildType
    -  const TValuesBuildType =
    -    "btAnd " + "btDetailAnd " + "btOr " + "btNotOr " + "btOnly ";
    -
    -  // enum TViewMode
    -  const TViewMode = "vmView " + "vmSelect " + "vmNavigation ";
    -
    -  // enum TViewSelectionMode
    -  const TViewSelectionMode =
    -    "vsmSingle " + "vsmMultiple " + "vsmMultipleCheck " + "vsmNoSelection ";
    -
    -  // enum TWizardActionType
    -  const TWizardActionType =
    -    "wfatPrevious " + "wfatNext " + "wfatCancel " + "wfatFinish ";
    -
    -  // enum TWizardFormElementProperty
    -  const TWizardFormElementProperty =
    -    "wfepUndefined " +
    -    "wfepText3 " +
    -    "wfepText6 " +
    -    "wfepText9 " +
    -    "wfepSpinEdit " +
    -    "wfepDropDown " +
    -    "wfepRadioGroup " +
    -    "wfepFlag " +
    -    "wfepText12 " +
    -    "wfepText15 " +
    -    "wfepText18 " +
    -    "wfepText21 " +
    -    "wfepText24 " +
    -    "wfepText27 " +
    -    "wfepText30 " +
    -    "wfepRadioGroupColumn1 " +
    -    "wfepRadioGroupColumn2 " +
    -    "wfepRadioGroupColumn3 ";
    -
    -  // enum TWizardFormElementType
    -  const TWizardFormElementType =
    -    "wfetQueryParameter " + "wfetText " + "wfetDelimiter " + "wfetLabel ";
    -
    -  // enum TWizardParamType
    -  const TWizardParamType =
    -    "wptString " +
    -    "wptInteger " +
    -    "wptNumeric " +
    -    "wptBoolean " +
    -    "wptDateTime " +
    -    "wptPick " +
    -    "wptText " +
    -    "wptUser " +
    -    "wptUserList " +
    -    "wptEDocumentInfo " +
    -    "wptEDocumentInfoList " +
    -    "wptReferenceRecordInfo " +
    -    "wptReferenceRecordInfoList " +
    -    "wptFolderInfo " +
    -    "wptTaskInfo " +
    -    "wptContents " +
    -    "wptFileName " +
    -    "wptDate ";
    -
    -  // enum TWizardStepResult
    -  const TWizardStepResult =
    -    "wsrComplete " +
    -    "wsrGoNext " +
    -    "wsrGoPrevious " +
    -    "wsrCustom " +
    -    "wsrCancel " +
    -    "wsrGoFinal ";
    -
    -  // enum TWizardStepType
    -  const TWizardStepType =
    -    "wstForm " +
    -    "wstEDocument " +
    -    "wstTaskCard " +
    -    "wstReferenceRecordCard " +
    -    "wstFinal ";
    -
    -  // enum TWorkAccessType
    -  const TWorkAccessType = "waAll " + "waPerformers " + "waManual ";
    -
    -  // enum TWorkflowBlockType
    -  const TWorkflowBlockType =
    -    "wsbStart " +
    -    "wsbFinish " +
    -    "wsbNotice " +
    -    "wsbStep " +
    -    "wsbDecision " +
    -    "wsbWait " +
    -    "wsbMonitor " +
    -    "wsbScript " +
    -    "wsbConnector " +
    -    "wsbSubTask " +
    -    "wsbLifeCycleStage " +
    -    "wsbPause ";
    -
    -  // enum TWorkflowDataType
    -  const TWorkflowDataType =
    -    "wdtInteger " +
    -    "wdtFloat " +
    -    "wdtString " +
    -    "wdtPick " +
    -    "wdtDateTime " +
    -    "wdtBoolean " +
    -    "wdtTask " +
    -    "wdtJob " +
    -    "wdtFolder " +
    -    "wdtEDocument " +
    -    "wdtReferenceRecord " +
    -    "wdtUser " +
    -    "wdtGroup " +
    -    "wdtRole " +
    -    "wdtIntegerCollection " +
    -    "wdtFloatCollection " +
    -    "wdtStringCollection " +
    -    "wdtPickCollection " +
    -    "wdtDateTimeCollection " +
    -    "wdtBooleanCollection " +
    -    "wdtTaskCollection " +
    -    "wdtJobCollection " +
    -    "wdtFolderCollection " +
    -    "wdtEDocumentCollection " +
    -    "wdtReferenceRecordCollection " +
    -    "wdtUserCollection " +
    -    "wdtGroupCollection " +
    -    "wdtRoleCollection " +
    -    "wdtContents " +
    -    "wdtUserList " +
    -    "wdtSearchDescription " +
    -    "wdtDeadLine " +
    -    "wdtPickSet " +
    -    "wdtAccountCollection ";
    -
    -  // enum TWorkImportance
    -  const TWorkImportance = "wiLow " + "wiNormal " + "wiHigh ";
    -
    -  // enum TWorkRouteType
    -  const TWorkRouteType = "wrtSoft " + "wrtHard ";
    -
    -  // enum TWorkState
    -  const TWorkState =
    -    "wsInit " +
    -    "wsRunning " +
    -    "wsDone " +
    -    "wsControlled " +
    -    "wsAborted " +
    -    "wsContinued ";
    -
    -  // enum TWorkTextBuildingMode
    -  const TWorkTextBuildingMode =
    -    "wtmFull " + "wtmFromCurrent " + "wtmOnlyCurrent ";
    -
    -  // Перечисления
    -  const ENUMS =
    -    TAccountType +
    -    TActionEnabledMode +
    -    TAddPosition +
    -    TAlignment +
    -    TAreaShowMode +
    -    TCertificateInvalidationReason +
    -    TCertificateType +
    -    TCheckListBoxItemState +
    -    TCloseOnEsc +
    -    TCompType +
    -    TConditionFormat +
    -    TConnectionIntent +
    -    TContentKind +
    -    TControlType +
    -    TCriterionContentType +
    -    TCultureType +
    -    TDataSetEventType +
    -    TDataSetState +
    -    TDateFormatType +
    -    TDateOffsetType +
    -    TDateTimeKind +
    -    TDeaAccessRights +
    -    TDocumentDefaultAction +
    -    TEditMode +
    -    TEditorCloseObservType +
    -    TEdmsApplicationAction +
    -    TEDocumentLockType +
    -    TEDocumentStepShowMode +
    -    TEDocumentStepVersionType +
    -    TEDocumentStorageFunction +
    -    TEDocumentStorageType +
    -    TEDocumentVersionSourceType +
    -    TEDocumentVersionState +
    -    TEncodeType +
    -    TExceptionCategory +
    -    TExportedSignaturesType +
    -    TExportedVersionType +
    -    TFieldDataType +
    -    TFolderType +
    -    TGridRowHeight +
    -    THyperlinkType +
    -    TImageFileFormat +
    -    TImageMode +
    -    TImageType +
    -    TInplaceHintKind +
    -    TISBLContext +
    -    TItemShow +
    -    TJobKind +
    -    TJoinType +
    -    TLabelPos +
    -    TLicensingType +
    -    TLifeCycleStageFontColor +
    -    TLifeCycleStageFontStyle +
    -    TLockableDevelopmentComponentType +
    -    TMaxRecordCountRestrictionType +
    -    TRangeValueType +
    -    TRelativeDate +
    -    TReportDestination +
    -    TReqDataType +
    -    TRequisiteEventType +
    -    TSBTimeType +
    -    TSearchShowMode +
    -    TSelectMode +
    -    TSignatureType +
    -    TSignerContentType +
    -    TStringsSortType +
    -    TStringValueType +
    -    TStructuredObjectAttributeType +
    -    TTaskAbortReason +
    -    TTextValueType +
    -    TUserObjectStatus +
    -    TUserType +
    -    TValuesBuildType +
    -    TViewMode +
    -    TViewSelectionMode +
    -    TWizardActionType +
    -    TWizardFormElementProperty +
    -    TWizardFormElementType +
    -    TWizardParamType +
    -    TWizardStepResult +
    -    TWizardStepType +
    -    TWorkAccessType +
    -    TWorkflowBlockType +
    -    TWorkflowDataType +
    -    TWorkImportance +
    -    TWorkRouteType +
    -    TWorkState +
    -    TWorkTextBuildingMode;
    -
    -  // Системные функции ==> SYSFUNCTIONS
    -  const system_functions =
    -    "AddSubString " +
    -    "AdjustLineBreaks " +
    -    "AmountInWords " +
    -    "Analysis " +
    -    "ArrayDimCount " +
    -    "ArrayHighBound " +
    -    "ArrayLowBound " +
    -    "ArrayOf " +
    -    "ArrayReDim " +
    -    "Assert " +
    -    "Assigned " +
    -    "BeginOfMonth " +
    -    "BeginOfPeriod " +
    -    "BuildProfilingOperationAnalysis " +
    -    "CallProcedure " +
    -    "CanReadFile " +
    -    "CArrayElement " +
    -    "CDataSetRequisite " +
    -    "ChangeDate " +
    -    "ChangeReferenceDataset " +
    -    "Char " +
    -    "CharPos " +
    -    "CheckParam " +
    -    "CheckParamValue " +
    -    "CompareStrings " +
    -    "ConstantExists " +
    -    "ControlState " +
    -    "ConvertDateStr " +
    -    "Copy " +
    -    "CopyFile " +
    -    "CreateArray " +
    -    "CreateCachedReference " +
    -    "CreateConnection " +
    -    "CreateDialog " +
    -    "CreateDualListDialog " +
    -    "CreateEditor " +
    -    "CreateException " +
    -    "CreateFile " +
    -    "CreateFolderDialog " +
    -    "CreateInputDialog " +
    -    "CreateLinkFile " +
    -    "CreateList " +
    -    "CreateLock " +
    -    "CreateMemoryDataSet " +
    -    "CreateObject " +
    -    "CreateOpenDialog " +
    -    "CreateProgress " +
    -    "CreateQuery " +
    -    "CreateReference " +
    -    "CreateReport " +
    -    "CreateSaveDialog " +
    -    "CreateScript " +
    -    "CreateSQLPivotFunction " +
    -    "CreateStringList " +
    -    "CreateTreeListSelectDialog " +
    -    "CSelectSQL " +
    -    "CSQL " +
    -    "CSubString " +
    -    "CurrentUserID " +
    -    "CurrentUserName " +
    -    "CurrentVersion " +
    -    "DataSetLocateEx " +
    -    "DateDiff " +
    -    "DateTimeDiff " +
    -    "DateToStr " +
    -    "DayOfWeek " +
    -    "DeleteFile " +
    -    "DirectoryExists " +
    -    "DisableCheckAccessRights " +
    -    "DisableCheckFullShowingRestriction " +
    -    "DisableMassTaskSendingRestrictions " +
    -    "DropTable " +
    -    "DupeString " +
    -    "EditText " +
    -    "EnableCheckAccessRights " +
    -    "EnableCheckFullShowingRestriction " +
    -    "EnableMassTaskSendingRestrictions " +
    -    "EndOfMonth " +
    -    "EndOfPeriod " +
    -    "ExceptionExists " +
    -    "ExceptionsOff " +
    -    "ExceptionsOn " +
    -    "Execute " +
    -    "ExecuteProcess " +
    -    "Exit " +
    -    "ExpandEnvironmentVariables " +
    -    "ExtractFileDrive " +
    -    "ExtractFileExt " +
    -    "ExtractFileName " +
    -    "ExtractFilePath " +
    -    "ExtractParams " +
    -    "FileExists " +
    -    "FileSize " +
    -    "FindFile " +
    -    "FindSubString " +
    -    "FirmContext " +
    -    "ForceDirectories " +
    -    "Format " +
    -    "FormatDate " +
    -    "FormatNumeric " +
    -    "FormatSQLDate " +
    -    "FormatString " +
    -    "FreeException " +
    -    "GetComponent " +
    -    "GetComponentLaunchParam " +
    -    "GetConstant " +
    -    "GetLastException " +
    -    "GetReferenceRecord " +
    -    "GetRefTypeByRefID " +
    -    "GetTableID " +
    -    "GetTempFolder " +
    -    "IfThen " +
    -    "In " +
    -    "IndexOf " +
    -    "InputDialog " +
    -    "InputDialogEx " +
    -    "InteractiveMode " +
    -    "IsFileLocked " +
    -    "IsGraphicFile " +
    -    "IsNumeric " +
    -    "Length " +
    -    "LoadString " +
    -    "LoadStringFmt " +
    -    "LocalTimeToUTC " +
    -    "LowerCase " +
    -    "Max " +
    -    "MessageBox " +
    -    "MessageBoxEx " +
    -    "MimeDecodeBinary " +
    -    "MimeDecodeString " +
    -    "MimeEncodeBinary " +
    -    "MimeEncodeString " +
    -    "Min " +
    -    "MoneyInWords " +
    -    "MoveFile " +
    -    "NewID " +
    -    "Now " +
    -    "OpenFile " +
    -    "Ord " +
    -    "Precision " +
    -    "Raise " +
    -    "ReadCertificateFromFile " +
    -    "ReadFile " +
    -    "ReferenceCodeByID " +
    -    "ReferenceNumber " +
    -    "ReferenceRequisiteMode " +
    -    "ReferenceRequisiteValue " +
    -    "RegionDateSettings " +
    -    "RegionNumberSettings " +
    -    "RegionTimeSettings " +
    -    "RegRead " +
    -    "RegWrite " +
    -    "RenameFile " +
    -    "Replace " +
    -    "Round " +
    -    "SelectServerCode " +
    -    "SelectSQL " +
    -    "ServerDateTime " +
    -    "SetConstant " +
    -    "SetManagedFolderFieldsState " +
    -    "ShowConstantsInputDialog " +
    -    "ShowMessage " +
    -    "Sleep " +
    -    "Split " +
    -    "SQL " +
    -    "SQL2XLSTAB " +
    -    "SQLProfilingSendReport " +
    -    "StrToDate " +
    -    "SubString " +
    -    "SubStringCount " +
    -    "SystemSetting " +
    -    "Time " +
    -    "TimeDiff " +
    -    "Today " +
    -    "Transliterate " +
    -    "Trim " +
    -    "UpperCase " +
    -    "UserStatus " +
    -    "UTCToLocalTime " +
    -    "ValidateXML " +
    -    "VarIsClear " +
    -    "VarIsEmpty " +
    -    "VarIsNull " +
    -    "WorkTimeDiff " +
    -    "WriteFile " +
    -    "WriteFileEx " +
    -    "WriteObjectHistory " +
    -    "Анализ " +
    -    "БазаДанных " +
    -    "БлокЕсть " +
    -    "БлокЕстьРасш " +
    -    "БлокИнфо " +
    -    "БлокСнять " +
    -    "БлокСнятьРасш " +
    -    "БлокУстановить " +
    -    "Ввод " +
    -    "ВводМеню " +
    -    "ВедС " +
    -    "ВедСпр " +
    -    "ВерхняяГраницаМассива " +
    -    "ВнешПрогр " +
    -    "Восст " +
    -    "ВременнаяПапка " +
    -    "Время " +
    -    "ВыборSQL " +
    -    "ВыбратьЗапись " +
    -    "ВыделитьСтр " +
    -    "Вызвать " +
    -    "Выполнить " +
    -    "ВыпПрогр " +
    -    "ГрафическийФайл " +
    -    "ГруппаДополнительно " +
    -    "ДатаВремяСерв " +
    -    "ДеньНедели " +
    -    "ДиалогДаНет " +
    -    "ДлинаСтр " +
    -    "ДобПодстр " +
    -    "ЕПусто " +
    -    "ЕслиТо " +
    -    "ЕЧисло " +
    -    "ЗамПодстр " +
    -    "ЗаписьСправочника " +
    -    "ЗначПоляСпр " +
    -    "ИДТипСпр " +
    -    "ИзвлечьДиск " +
    -    "ИзвлечьИмяФайла " +
    -    "ИзвлечьПуть " +
    -    "ИзвлечьРасширение " +
    -    "ИзмДат " +
    -    "ИзменитьРазмерМассива " +
    -    "ИзмеренийМассива " +
    -    "ИмяОрг " +
    -    "ИмяПоляСпр " +
    -    "Индекс " +
    -    "ИндикаторЗакрыть " +
    -    "ИндикаторОткрыть " +
    -    "ИндикаторШаг " +
    -    "ИнтерактивныйРежим " +
    -    "ИтогТблСпр " +
    -    "КодВидВедСпр " +
    -    "КодВидСпрПоИД " +
    -    "КодПоAnalit " +
    -    "КодСимвола " +
    -    "КодСпр " +
    -    "КолПодстр " +
    -    "КолПроп " +
    -    "КонМес " +
    -    "Конст " +
    -    "КонстЕсть " +
    -    "КонстЗнач " +
    -    "КонТран " +
    -    "КопироватьФайл " +
    -    "КопияСтр " +
    -    "КПериод " +
    -    "КСтрТблСпр " +
    -    "Макс " +
    -    "МаксСтрТблСпр " +
    -    "Массив " +
    -    "Меню " +
    -    "МенюРасш " +
    -    "Мин " +
    -    "НаборДанныхНайтиРасш " +
    -    "НаимВидСпр " +
    -    "НаимПоAnalit " +
    -    "НаимСпр " +
    -    "НастроитьПереводыСтрок " +
    -    "НачМес " +
    -    "НачТран " +
    -    "НижняяГраницаМассива " +
    -    "НомерСпр " +
    -    "НПериод " +
    -    "Окно " +
    -    "Окр " +
    -    "Окружение " +
    -    "ОтлИнфДобавить " +
    -    "ОтлИнфУдалить " +
    -    "Отчет " +
    -    "ОтчетАнал " +
    -    "ОтчетИнт " +
    -    "ПапкаСуществует " +
    -    "Пауза " +
    -    "ПВыборSQL " +
    -    "ПереименоватьФайл " +
    -    "Переменные " +
    -    "ПереместитьФайл " +
    -    "Подстр " +
    -    "ПоискПодстр " +
    -    "ПоискСтр " +
    -    "ПолучитьИДТаблицы " +
    -    "ПользовательДополнительно " +
    -    "ПользовательИД " +
    -    "ПользовательИмя " +
    -    "ПользовательСтатус " +
    -    "Прервать " +
    -    "ПроверитьПараметр " +
    -    "ПроверитьПараметрЗнач " +
    -    "ПроверитьУсловие " +
    -    "РазбСтр " +
    -    "РазнВремя " +
    -    "РазнДат " +
    -    "РазнДатаВремя " +
    -    "РазнРабВремя " +
    -    "РегУстВрем " +
    -    "РегУстДат " +
    -    "РегУстЧсл " +
    -    "РедТекст " +
    -    "РеестрЗапись " +
    -    "РеестрСписокИменПарам " +
    -    "РеестрЧтение " +
    -    "РеквСпр " +
    -    "РеквСпрПр " +
    -    "Сегодня " +
    -    "Сейчас " +
    -    "Сервер " +
    -    "СерверПроцессИД " +
    -    "СертификатФайлСчитать " +
    -    "СжПроб " +
    -    "Символ " +
    -    "СистемаДиректумКод " +
    -    "СистемаИнформация " +
    -    "СистемаКод " +
    -    "Содержит " +
    -    "СоединениеЗакрыть " +
    -    "СоединениеОткрыть " +
    -    "СоздатьДиалог " +
    -    "СоздатьДиалогВыбораИзДвухСписков " +
    -    "СоздатьДиалогВыбораПапки " +
    -    "СоздатьДиалогОткрытияФайла " +
    -    "СоздатьДиалогСохраненияФайла " +
    -    "СоздатьЗапрос " +
    -    "СоздатьИндикатор " +
    -    "СоздатьИсключение " +
    -    "СоздатьКэшированныйСправочник " +
    -    "СоздатьМассив " +
    -    "СоздатьНаборДанных " +
    -    "СоздатьОбъект " +
    -    "СоздатьОтчет " +
    -    "СоздатьПапку " +
    -    "СоздатьРедактор " +
    -    "СоздатьСоединение " +
    -    "СоздатьСписок " +
    -    "СоздатьСписокСтрок " +
    -    "СоздатьСправочник " +
    -    "СоздатьСценарий " +
    -    "СоздСпр " +
    -    "СостСпр " +
    -    "Сохр " +
    -    "СохрСпр " +
    -    "СписокСистем " +
    -    "Спр " +
    -    "Справочник " +
    -    "СпрБлокЕсть " +
    -    "СпрБлокСнять " +
    -    "СпрБлокСнятьРасш " +
    -    "СпрБлокУстановить " +
    -    "СпрИзмНабДан " +
    -    "СпрКод " +
    -    "СпрНомер " +
    -    "СпрОбновить " +
    -    "СпрОткрыть " +
    -    "СпрОтменить " +
    -    "СпрПарам " +
    -    "СпрПолеЗнач " +
    -    "СпрПолеИмя " +
    -    "СпрРекв " +
    -    "СпрРеквВведЗн " +
    -    "СпрРеквНовые " +
    -    "СпрРеквПр " +
    -    "СпрРеквПредЗн " +
    -    "СпрРеквРежим " +
    -    "СпрРеквТипТекст " +
    -    "СпрСоздать " +
    -    "СпрСост " +
    -    "СпрСохранить " +
    -    "СпрТблИтог " +
    -    "СпрТблСтр " +
    -    "СпрТблСтрКол " +
    -    "СпрТблСтрМакс " +
    -    "СпрТблСтрМин " +
    -    "СпрТблСтрПред " +
    -    "СпрТблСтрСлед " +
    -    "СпрТблСтрСозд " +
    -    "СпрТблСтрУд " +
    -    "СпрТекПредст " +
    -    "СпрУдалить " +
    -    "СравнитьСтр " +
    -    "СтрВерхРегистр " +
    -    "СтрНижнРегистр " +
    -    "СтрТблСпр " +
    -    "СумПроп " +
    -    "Сценарий " +
    -    "СценарийПарам " +
    -    "ТекВерсия " +
    -    "ТекОрг " +
    -    "Точн " +
    -    "Тран " +
    -    "Транслитерация " +
    -    "УдалитьТаблицу " +
    -    "УдалитьФайл " +
    -    "УдСпр " +
    -    "УдСтрТблСпр " +
    -    "Уст " +
    -    "УстановкиКонстант " +
    -    "ФайлАтрибутСчитать " +
    -    "ФайлАтрибутУстановить " +
    -    "ФайлВремя " +
    -    "ФайлВремяУстановить " +
    -    "ФайлВыбрать " +
    -    "ФайлЗанят " +
    -    "ФайлЗаписать " +
    -    "ФайлИскать " +
    -    "ФайлКопировать " +
    -    "ФайлМожноЧитать " +
    -    "ФайлОткрыть " +
    -    "ФайлПереименовать " +
    -    "ФайлПерекодировать " +
    -    "ФайлПереместить " +
    -    "ФайлПросмотреть " +
    -    "ФайлРазмер " +
    -    "ФайлСоздать " +
    -    "ФайлСсылкаСоздать " +
    -    "ФайлСуществует " +
    -    "ФайлСчитать " +
    -    "ФайлУдалить " +
    -    "ФмтSQLДат " +
    -    "ФмтДат " +
    -    "ФмтСтр " +
    -    "ФмтЧсл " +
    -    "Формат " +
    -    "ЦМассивЭлемент " +
    -    "ЦНаборДанныхРеквизит " +
    -    "ЦПодстр ";
    -
    -  // Предопределенные переменные ==> built_in
    -  const predefined_variables =
    -    "AltState " +
    -    "Application " +
    -    "CallType " +
    -    "ComponentTokens " +
    -    "CreatedJobs " +
    -    "CreatedNotices " +
    -    "ControlState " +
    -    "DialogResult " +
    -    "Dialogs " +
    -    "EDocuments " +
    -    "EDocumentVersionSource " +
    -    "Folders " +
    -    "GlobalIDs " +
    -    "Job " +
    -    "Jobs " +
    -    "InputValue " +
    -    "LookUpReference " +
    -    "LookUpRequisiteNames " +
    -    "LookUpSearch " +
    -    "Object " +
    -    "ParentComponent " +
    -    "Processes " +
    -    "References " +
    -    "Requisite " +
    -    "ReportName " +
    -    "Reports " +
    -    "Result " +
    -    "Scripts " +
    -    "Searches " +
    -    "SelectedAttachments " +
    -    "SelectedItems " +
    -    "SelectMode " +
    -    "Sender " +
    -    "ServerEvents " +
    -    "ServiceFactory " +
    -    "ShiftState " +
    -    "SubTask " +
    -    "SystemDialogs " +
    -    "Tasks " +
    -    "Wizard " +
    -    "Wizards " +
    -    "Work " +
    -    "ВызовСпособ " +
    -    "ИмяОтчета " +
    -    "РеквЗнач ";
    -
    -  // Интерфейсы ==> type
    -  const interfaces =
    -    "IApplication " +
    -    "IAccessRights " +
    -    "IAccountRepository " +
    -    "IAccountSelectionRestrictions " +
    -    "IAction " +
    -    "IActionList " +
    -    "IAdministrationHistoryDescription " +
    -    "IAnchors " +
    -    "IApplication " +
    -    "IArchiveInfo " +
    -    "IAttachment " +
    -    "IAttachmentList " +
    -    "ICheckListBox " +
    -    "ICheckPointedList " +
    -    "IColumn " +
    -    "IComponent " +
    -    "IComponentDescription " +
    -    "IComponentToken " +
    -    "IComponentTokenFactory " +
    -    "IComponentTokenInfo " +
    -    "ICompRecordInfo " +
    -    "IConnection " +
    -    "IContents " +
    -    "IControl " +
    -    "IControlJob " +
    -    "IControlJobInfo " +
    -    "IControlList " +
    -    "ICrypto " +
    -    "ICrypto2 " +
    -    "ICustomJob " +
    -    "ICustomJobInfo " +
    -    "ICustomListBox " +
    -    "ICustomObjectWizardStep " +
    -    "ICustomWork " +
    -    "ICustomWorkInfo " +
    -    "IDataSet " +
    -    "IDataSetAccessInfo " +
    -    "IDataSigner " +
    -    "IDateCriterion " +
    -    "IDateRequisite " +
    -    "IDateRequisiteDescription " +
    -    "IDateValue " +
    -    "IDeaAccessRights " +
    -    "IDeaObjectInfo " +
    -    "IDevelopmentComponentLock " +
    -    "IDialog " +
    -    "IDialogFactory " +
    -    "IDialogPickRequisiteItems " +
    -    "IDialogsFactory " +
    -    "IDICSFactory " +
    -    "IDocRequisite " +
    -    "IDocumentInfo " +
    -    "IDualListDialog " +
    -    "IECertificate " +
    -    "IECertificateInfo " +
    -    "IECertificates " +
    -    "IEditControl " +
    -    "IEditorForm " +
    -    "IEdmsExplorer " +
    -    "IEdmsObject " +
    -    "IEdmsObjectDescription " +
    -    "IEdmsObjectFactory " +
    -    "IEdmsObjectInfo " +
    -    "IEDocument " +
    -    "IEDocumentAccessRights " +
    -    "IEDocumentDescription " +
    -    "IEDocumentEditor " +
    -    "IEDocumentFactory " +
    -    "IEDocumentInfo " +
    -    "IEDocumentStorage " +
    -    "IEDocumentVersion " +
    -    "IEDocumentVersionListDialog " +
    -    "IEDocumentVersionSource " +
    -    "IEDocumentWizardStep " +
    -    "IEDocVerSignature " +
    -    "IEDocVersionState " +
    -    "IEnabledMode " +
    -    "IEncodeProvider " +
    -    "IEncrypter " +
    -    "IEvent " +
    -    "IEventList " +
    -    "IException " +
    -    "IExternalEvents " +
    -    "IExternalHandler " +
    -    "IFactory " +
    -    "IField " +
    -    "IFileDialog " +
    -    "IFolder " +
    -    "IFolderDescription " +
    -    "IFolderDialog " +
    -    "IFolderFactory " +
    -    "IFolderInfo " +
    -    "IForEach " +
    -    "IForm " +
    -    "IFormTitle " +
    -    "IFormWizardStep " +
    -    "IGlobalIDFactory " +
    -    "IGlobalIDInfo " +
    -    "IGrid " +
    -    "IHasher " +
    -    "IHistoryDescription " +
    -    "IHyperLinkControl " +
    -    "IImageButton " +
    -    "IImageControl " +
    -    "IInnerPanel " +
    -    "IInplaceHint " +
    -    "IIntegerCriterion " +
    -    "IIntegerList " +
    -    "IIntegerRequisite " +
    -    "IIntegerValue " +
    -    "IISBLEditorForm " +
    -    "IJob " +
    -    "IJobDescription " +
    -    "IJobFactory " +
    -    "IJobForm " +
    -    "IJobInfo " +
    -    "ILabelControl " +
    -    "ILargeIntegerCriterion " +
    -    "ILargeIntegerRequisite " +
    -    "ILargeIntegerValue " +
    -    "ILicenseInfo " +
    -    "ILifeCycleStage " +
    -    "IList " +
    -    "IListBox " +
    -    "ILocalIDInfo " +
    -    "ILocalization " +
    -    "ILock " +
    -    "IMemoryDataSet " +
    -    "IMessagingFactory " +
    -    "IMetadataRepository " +
    -    "INotice " +
    -    "INoticeInfo " +
    -    "INumericCriterion " +
    -    "INumericRequisite " +
    -    "INumericValue " +
    -    "IObject " +
    -    "IObjectDescription " +
    -    "IObjectImporter " +
    -    "IObjectInfo " +
    -    "IObserver " +
    -    "IPanelGroup " +
    -    "IPickCriterion " +
    -    "IPickProperty " +
    -    "IPickRequisite " +
    -    "IPickRequisiteDescription " +
    -    "IPickRequisiteItem " +
    -    "IPickRequisiteItems " +
    -    "IPickValue " +
    -    "IPrivilege " +
    -    "IPrivilegeList " +
    -    "IProcess " +
    -    "IProcessFactory " +
    -    "IProcessMessage " +
    -    "IProgress " +
    -    "IProperty " +
    -    "IPropertyChangeEvent " +
    -    "IQuery " +
    -    "IReference " +
    -    "IReferenceCriterion " +
    -    "IReferenceEnabledMode " +
    -    "IReferenceFactory " +
    -    "IReferenceHistoryDescription " +
    -    "IReferenceInfo " +
    -    "IReferenceRecordCardWizardStep " +
    -    "IReferenceRequisiteDescription " +
    -    "IReferencesFactory " +
    -    "IReferenceValue " +
    -    "IRefRequisite " +
    -    "IReport " +
    -    "IReportFactory " +
    -    "IRequisite " +
    -    "IRequisiteDescription " +
    -    "IRequisiteDescriptionList " +
    -    "IRequisiteFactory " +
    -    "IRichEdit " +
    -    "IRouteStep " +
    -    "IRule " +
    -    "IRuleList " +
    -    "ISchemeBlock " +
    -    "IScript " +
    -    "IScriptFactory " +
    -    "ISearchCriteria " +
    -    "ISearchCriterion " +
    -    "ISearchDescription " +
    -    "ISearchFactory " +
    -    "ISearchFolderInfo " +
    -    "ISearchForObjectDescription " +
    -    "ISearchResultRestrictions " +
    -    "ISecuredContext " +
    -    "ISelectDialog " +
    -    "IServerEvent " +
    -    "IServerEventFactory " +
    -    "IServiceDialog " +
    -    "IServiceFactory " +
    -    "ISignature " +
    -    "ISignProvider " +
    -    "ISignProvider2 " +
    -    "ISignProvider3 " +
    -    "ISimpleCriterion " +
    -    "IStringCriterion " +
    -    "IStringList " +
    -    "IStringRequisite " +
    -    "IStringRequisiteDescription " +
    -    "IStringValue " +
    -    "ISystemDialogsFactory " +
    -    "ISystemInfo " +
    -    "ITabSheet " +
    -    "ITask " +
    -    "ITaskAbortReasonInfo " +
    -    "ITaskCardWizardStep " +
    -    "ITaskDescription " +
    -    "ITaskFactory " +
    -    "ITaskInfo " +
    -    "ITaskRoute " +
    -    "ITextCriterion " +
    -    "ITextRequisite " +
    -    "ITextValue " +
    -    "ITreeListSelectDialog " +
    -    "IUser " +
    -    "IUserList " +
    -    "IValue " +
    -    "IView " +
    -    "IWebBrowserControl " +
    -    "IWizard " +
    -    "IWizardAction " +
    -    "IWizardFactory " +
    -    "IWizardFormElement " +
    -    "IWizardParam " +
    -    "IWizardPickParam " +
    -    "IWizardReferenceParam " +
    -    "IWizardStep " +
    -    "IWorkAccessRights " +
    -    "IWorkDescription " +
    -    "IWorkflowAskableParam " +
    -    "IWorkflowAskableParams " +
    -    "IWorkflowBlock " +
    -    "IWorkflowBlockResult " +
    -    "IWorkflowEnabledMode " +
    -    "IWorkflowParam " +
    -    "IWorkflowPickParam " +
    -    "IWorkflowReferenceParam " +
    -    "IWorkState " +
    -    "IWorkTreeCustomNode " +
    -    "IWorkTreeJobNode " +
    -    "IWorkTreeTaskNode " +
    -    "IXMLEditorForm " +
    -    "SBCrypto ";
    -
    -  // built_in : встроенные или библиотечные объекты (константы, перечисления)
    -  const BUILTIN = CONSTANTS + ENUMS;
    -
    -  // class: встроенные наборы значений, системные объекты, фабрики
    -  const CLASS = predefined_variables;
    -
    -  // literal : примитивные типы
    -  const LITERAL = "null true false nil ";
    -
    -  // number : числа
    -  const NUMBERS = {
    -    className: "number",
    -    begin: hljs.NUMBER_RE,
    -    relevance: 0
    -  };
    -
    -  // string : строки
    -  const STRINGS = {
    -    className: "string",
    -    variants: [
    -      {
    -        begin: '"',
    -        end: '"'
    -      },
    -      {
    -        begin: "'",
    -        end: "'"
    -      }
    -    ]
    -  };
    -
    -  // Токены
    -  const DOCTAGS = {
    -    className: "doctag",
    -    begin: "\\b(?:TODO|DONE|BEGIN|END|STUB|CHG|FIXME|NOTE|BUG|XXX)\\b",
    -    relevance: 0
    -  };
    -
    -  // Однострочный комментарий
    -  const ISBL_LINE_COMMENT_MODE = {
    -    className: "comment",
    -    begin: "//",
    -    end: "$",
    -    relevance: 0,
    -    contains: [
    -      hljs.PHRASAL_WORDS_MODE,
    -      DOCTAGS
    -    ]
    -  };
    -
    -  // Многострочный комментарий
    -  const ISBL_BLOCK_COMMENT_MODE = {
    -    className: "comment",
    -    begin: "/\\*",
    -    end: "\\*/",
    -    relevance: 0,
    -    contains: [
    -      hljs.PHRASAL_WORDS_MODE,
    -      DOCTAGS
    -    ]
    -  };
    -
    -  // comment : комментарии
    -  const COMMENTS = {
    -    variants: [
    -      ISBL_LINE_COMMENT_MODE,
    -      ISBL_BLOCK_COMMENT_MODE
    -    ]
    -  };
    -
    -  // keywords : ключевые слова
    -  const KEYWORDS = {
    -    $pattern: UNDERSCORE_IDENT_RE,
    -    keyword: KEYWORD,
    -    built_in: BUILTIN,
    -    class: CLASS,
    -    literal: LITERAL
    -  };
    -
    -  // methods : методы
    -  const METHODS = {
    -    begin: "\\.\\s*" + hljs.UNDERSCORE_IDENT_RE,
    -    keywords: KEYWORDS,
    -    relevance: 0
    -  };
    -
    -  // type : встроенные типы
    -  const TYPES = {
    -    className: "type",
    -    begin: ":[ \\t]*(" + interfaces.trim().replace(/\s/g, "|") + ")",
    -    end: "[ \\t]*=",
    -    excludeEnd: true
    -  };
    -
    -  // variables : переменные
    -  const VARIABLES = {
    -    className: "variable",
    -    keywords: KEYWORDS,
    -    begin: UNDERSCORE_IDENT_RE,
    -    relevance: 0,
    -    contains: [
    -      TYPES,
    -      METHODS
    -    ]
    -  };
    -
    -  // Имена функций
    -  const FUNCTION_TITLE = FUNCTION_NAME_IDENT_RE + "\\(";
    -
    -  const TITLE_MODE = {
    -    className: "title",
    -    keywords: {
    -      $pattern: UNDERSCORE_IDENT_RE,
    -      built_in: system_functions
    -    },
    -    begin: FUNCTION_TITLE,
    -    end: "\\(",
    -    returnBegin: true,
    -    excludeEnd: true
    -  };
    -
    -  // function : функции
    -  const FUNCTIONS = {
    -    className: "function",
    -    begin: FUNCTION_TITLE,
    -    end: "\\)$",
    -    returnBegin: true,
    -    keywords: KEYWORDS,
    -    illegal: "[\\[\\]\\|\\$\\?%,~#@]",
    -    contains: [
    -      TITLE_MODE,
    -      METHODS,
    -      VARIABLES,
    -      STRINGS,
    -      NUMBERS,
    -      COMMENTS
    -    ]
    -  };
    -
    -  return {
    -    name: 'ISBL',
    -    case_insensitive: true,
    -    keywords: KEYWORDS,
    -    illegal: "\\$|\\?|%|,|;$|~|#|@|
    -Category: common, enterprise
    -Website: https://www.java.com/
    -*/
    -
    -function java(hljs) {
    -  var JAVA_IDENT_RE = '[\u00C0-\u02B8a-zA-Z_$][\u00C0-\u02B8a-zA-Z_$0-9]*';
    -  var GENERIC_IDENT_RE = JAVA_IDENT_RE + '(<' + JAVA_IDENT_RE + '(\\s*,\\s*' + JAVA_IDENT_RE + ')*>)?';
    -  var KEYWORDS = 'false synchronized int abstract float private char boolean var static null if const ' +
    -    'for true while long strictfp finally protected import native final void ' +
    -    'enum else break transient catch instanceof byte super volatile case assert short ' +
    -    'package default double public try this switch continue throws protected public private ' +
    -    'module requires exports do';
    -
    -  var ANNOTATION = {
    -    className: 'meta',
    -    begin: '@' + JAVA_IDENT_RE,
    -    contains: [
    -      {
    -        begin: /\(/,
    -        end: /\)/,
    -        contains: ["self"] // allow nested () inside our annotation
    -      },
    -    ]
    -  };
    -  const NUMBER = NUMERIC;
    -
    -  return {
    -    name: 'Java',
    -    aliases: ['jsp'],
    -    keywords: KEYWORDS,
    -    illegal: /<\/|#/,
    -    contains: [
    -      hljs.COMMENT(
    -        '/\\*\\*',
    -        '\\*/',
    -        {
    -          relevance: 0,
    -          contains: [
    -            {
    -              // eat up @'s in emails to prevent them to be recognized as doctags
    -              begin: /\w+@/, relevance: 0
    -            },
    -            {
    -              className: 'doctag',
    -              begin: '@[A-Za-z]+'
    -            }
    -          ]
    -        }
    -      ),
    -      // relevance boost
    -      {
    -        begin: /import java\.[a-z]+\./,
    -        keywords: "import",
    -        relevance: 2
    -      },
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      {
    -        className: 'class',
    -        beginKeywords: 'class interface enum', end: /[{;=]/, excludeEnd: true,
    -        // TODO: can this be removed somehow?
    -        // an extra boost because Java is more popular than other languages with
    -        // this same syntax feature (this is just to preserve our tests passing
    -        // for now)
    -        relevance: 1,
    -        keywords: 'class interface enum',
    -        illegal: /[:"\[\]]/,
    -        contains: [
    -          { beginKeywords: 'extends implements' },
    -          hljs.UNDERSCORE_TITLE_MODE
    -        ]
    -      },
    -      {
    -        // Expression keywords prevent 'keyword Name(...)' from being
    -        // recognized as a function definition
    -        beginKeywords: 'new throw return else',
    -        relevance: 0
    -      },
    -      {
    -        className: 'class',
    -        begin: 'record\\s+' + hljs.UNDERSCORE_IDENT_RE + '\\s*\\(',
    -        returnBegin: true,
    -        excludeEnd: true,
    -        end: /[{;=]/,
    -        keywords: KEYWORDS,
    -        contains: [
    -          { beginKeywords: "record" },
    -          {
    -            begin: hljs.UNDERSCORE_IDENT_RE + '\\s*\\(',
    -            returnBegin: true,
    -            relevance: 0,
    -            contains: [hljs.UNDERSCORE_TITLE_MODE]
    -          },
    -          {
    -            className: 'params',
    -            begin: /\(/, end: /\)/,
    -            keywords: KEYWORDS,
    -            relevance: 0,
    -            contains: [
    -              hljs.C_BLOCK_COMMENT_MODE
    -            ]
    -          },
    -          hljs.C_LINE_COMMENT_MODE,
    -          hljs.C_BLOCK_COMMENT_MODE
    -        ]
    -      },
    -      {
    -        className: 'function',
    -        begin: '(' + GENERIC_IDENT_RE + '\\s+)+' + hljs.UNDERSCORE_IDENT_RE + '\\s*\\(', returnBegin: true, end: /[{;=]/,
    -        excludeEnd: true,
    -        keywords: KEYWORDS,
    -        contains: [
    -          {
    -            begin: hljs.UNDERSCORE_IDENT_RE + '\\s*\\(', returnBegin: true,
    -            relevance: 0,
    -            contains: [hljs.UNDERSCORE_TITLE_MODE]
    -          },
    -          {
    -            className: 'params',
    -            begin: /\(/, end: /\)/,
    -            keywords: KEYWORDS,
    -            relevance: 0,
    -            contains: [
    -              ANNOTATION,
    -              hljs.APOS_STRING_MODE,
    -              hljs.QUOTE_STRING_MODE,
    -              NUMBER,
    -              hljs.C_BLOCK_COMMENT_MODE
    -            ]
    -          },
    -          hljs.C_LINE_COMMENT_MODE,
    -          hljs.C_BLOCK_COMMENT_MODE
    -        ]
    -      },
    -      NUMBER,
    -      ANNOTATION
    -    ]
    -  };
    -}
    -
    -module.exports = java;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/javascript.js b/claude-code-source/node_modules/highlight.js/lib/languages/javascript.js
    deleted file mode 100644
    index bfbc616a..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/javascript.js
    +++ /dev/null
    @@ -1,604 +0,0 @@
    -const IDENT_RE = '[A-Za-z$_][0-9A-Za-z$_]*';
    -const KEYWORDS = [
    -  "as", // for exports
    -  "in",
    -  "of",
    -  "if",
    -  "for",
    -  "while",
    -  "finally",
    -  "var",
    -  "new",
    -  "function",
    -  "do",
    -  "return",
    -  "void",
    -  "else",
    -  "break",
    -  "catch",
    -  "instanceof",
    -  "with",
    -  "throw",
    -  "case",
    -  "default",
    -  "try",
    -  "switch",
    -  "continue",
    -  "typeof",
    -  "delete",
    -  "let",
    -  "yield",
    -  "const",
    -  "class",
    -  // JS handles these with a special rule
    -  // "get",
    -  // "set",
    -  "debugger",
    -  "async",
    -  "await",
    -  "static",
    -  "import",
    -  "from",
    -  "export",
    -  "extends"
    -];
    -const LITERALS = [
    -  "true",
    -  "false",
    -  "null",
    -  "undefined",
    -  "NaN",
    -  "Infinity"
    -];
    -
    -const TYPES = [
    -  "Intl",
    -  "DataView",
    -  "Number",
    -  "Math",
    -  "Date",
    -  "String",
    -  "RegExp",
    -  "Object",
    -  "Function",
    -  "Boolean",
    -  "Error",
    -  "Symbol",
    -  "Set",
    -  "Map",
    -  "WeakSet",
    -  "WeakMap",
    -  "Proxy",
    -  "Reflect",
    -  "JSON",
    -  "Promise",
    -  "Float64Array",
    -  "Int16Array",
    -  "Int32Array",
    -  "Int8Array",
    -  "Uint16Array",
    -  "Uint32Array",
    -  "Float32Array",
    -  "Array",
    -  "Uint8Array",
    -  "Uint8ClampedArray",
    -  "ArrayBuffer",
    -  "BigInt64Array",
    -  "BigUint64Array",
    -  "BigInt"
    -];
    -
    -const ERROR_TYPES = [
    -  "EvalError",
    -  "InternalError",
    -  "RangeError",
    -  "ReferenceError",
    -  "SyntaxError",
    -  "TypeError",
    -  "URIError"
    -];
    -
    -const BUILT_IN_GLOBALS = [
    -  "setInterval",
    -  "setTimeout",
    -  "clearInterval",
    -  "clearTimeout",
    -
    -  "require",
    -  "exports",
    -
    -  "eval",
    -  "isFinite",
    -  "isNaN",
    -  "parseFloat",
    -  "parseInt",
    -  "decodeURI",
    -  "decodeURIComponent",
    -  "encodeURI",
    -  "encodeURIComponent",
    -  "escape",
    -  "unescape"
    -];
    -
    -const BUILT_IN_VARIABLES = [
    -  "arguments",
    -  "this",
    -  "super",
    -  "console",
    -  "window",
    -  "document",
    -  "localStorage",
    -  "module",
    -  "global" // Node.js
    -];
    -
    -const BUILT_INS = [].concat(
    -  BUILT_IN_GLOBALS,
    -  BUILT_IN_VARIABLES,
    -  TYPES,
    -  ERROR_TYPES
    -);
    -
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function lookahead(re) {
    -  return concat('(?=', re, ')');
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: JavaScript
    -Description: JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions.
    -Category: common, scripting
    -Website: https://developer.mozilla.org/en-US/docs/Web/JavaScript
    -*/
    -
    -/** @type LanguageFn */
    -function javascript(hljs) {
    -  /**
    -   * Takes a string like " {
    -    const tag = "',
    -    end: ''
    -  };
    -  const XML_TAG = {
    -    begin: /<[A-Za-z0-9\\._:-]+/,
    -    end: /\/[A-Za-z0-9\\._:-]+>|\/>/,
    -    /**
    -     * @param {RegExpMatchArray} match
    -     * @param {CallbackResponse} response
    -     */
    -    isTrulyOpeningTag: (match, response) => {
    -      const afterMatchIndex = match[0].length + match.index;
    -      const nextChar = match.input[afterMatchIndex];
    -      // nested type?
    -      // HTML should not include another raw `<` inside a tag
    -      // But a type might: `>`, etc.
    -      if (nextChar === "<") {
    -        response.ignoreMatch();
    -        return;
    -      }
    -      // 
    -      // This is now either a tag or a type.
    -      if (nextChar === ">") {
    -        // if we cannot find a matching closing tag, then we
    -        // will ignore it
    -        if (!hasClosingTag(match, { after: afterMatchIndex })) {
    -          response.ignoreMatch();
    -        }
    -      }
    -    }
    -  };
    -  const KEYWORDS$1 = {
    -    $pattern: IDENT_RE,
    -    keyword: KEYWORDS,
    -    literal: LITERALS,
    -    built_in: BUILT_INS
    -  };
    -
    -  // https://tc39.es/ecma262/#sec-literals-numeric-literals
    -  const decimalDigits = '[0-9](_?[0-9])*';
    -  const frac = `\\.(${decimalDigits})`;
    -  // DecimalIntegerLiteral, including Annex B NonOctalDecimalIntegerLiteral
    -  // https://tc39.es/ecma262/#sec-additional-syntax-numeric-literals
    -  const decimalInteger = `0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*`;
    -  const NUMBER = {
    -    className: 'number',
    -    variants: [
    -      // DecimalLiteral
    -      { begin: `(\\b(${decimalInteger})((${frac})|\\.)?|(${frac}))` +
    -        `[eE][+-]?(${decimalDigits})\\b` },
    -      { begin: `\\b(${decimalInteger})\\b((${frac})\\b|\\.)?|(${frac})\\b` },
    -
    -      // DecimalBigIntegerLiteral
    -      { begin: `\\b(0|[1-9](_?[0-9])*)n\\b` },
    -
    -      // NonDecimalIntegerLiteral
    -      { begin: "\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b" },
    -      { begin: "\\b0[bB][0-1](_?[0-1])*n?\\b" },
    -      { begin: "\\b0[oO][0-7](_?[0-7])*n?\\b" },
    -
    -      // LegacyOctalIntegerLiteral (does not include underscore separators)
    -      // https://tc39.es/ecma262/#sec-additional-syntax-numeric-literals
    -      { begin: "\\b0[0-7]+n?\\b" },
    -    ],
    -    relevance: 0
    -  };
    -
    -  const SUBST = {
    -    className: 'subst',
    -    begin: '\\$\\{',
    -    end: '\\}',
    -    keywords: KEYWORDS$1,
    -    contains: [] // defined later
    -  };
    -  const HTML_TEMPLATE = {
    -    begin: 'html`',
    -    end: '',
    -    starts: {
    -      end: '`',
    -      returnEnd: false,
    -      contains: [
    -        hljs.BACKSLASH_ESCAPE,
    -        SUBST
    -      ],
    -      subLanguage: 'xml'
    -    }
    -  };
    -  const CSS_TEMPLATE = {
    -    begin: 'css`',
    -    end: '',
    -    starts: {
    -      end: '`',
    -      returnEnd: false,
    -      contains: [
    -        hljs.BACKSLASH_ESCAPE,
    -        SUBST
    -      ],
    -      subLanguage: 'css'
    -    }
    -  };
    -  const TEMPLATE_STRING = {
    -    className: 'string',
    -    begin: '`',
    -    end: '`',
    -    contains: [
    -      hljs.BACKSLASH_ESCAPE,
    -      SUBST
    -    ]
    -  };
    -  const JSDOC_COMMENT = hljs.COMMENT(
    -    /\/\*\*(?!\/)/,
    -    '\\*/',
    -    {
    -      relevance: 0,
    -      contains: [
    -        {
    -          className: 'doctag',
    -          begin: '@[A-Za-z]+',
    -          contains: [
    -            {
    -              className: 'type',
    -              begin: '\\{',
    -              end: '\\}',
    -              relevance: 0
    -            },
    -            {
    -              className: 'variable',
    -              begin: IDENT_RE$1 + '(?=\\s*(-)|$)',
    -              endsParent: true,
    -              relevance: 0
    -            },
    -            // eat spaces (not newlines) so we can find
    -            // types or variables
    -            {
    -              begin: /(?=[^\n])\s/,
    -              relevance: 0
    -            }
    -          ]
    -        }
    -      ]
    -    }
    -  );
    -  const COMMENT = {
    -    className: "comment",
    -    variants: [
    -      JSDOC_COMMENT,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.C_LINE_COMMENT_MODE
    -    ]
    -  };
    -  const SUBST_INTERNALS = [
    -    hljs.APOS_STRING_MODE,
    -    hljs.QUOTE_STRING_MODE,
    -    HTML_TEMPLATE,
    -    CSS_TEMPLATE,
    -    TEMPLATE_STRING,
    -    NUMBER,
    -    hljs.REGEXP_MODE
    -  ];
    -  SUBST.contains = SUBST_INTERNALS
    -    .concat({
    -      // we need to pair up {} inside our subst to prevent
    -      // it from ending too early by matching another }
    -      begin: /\{/,
    -      end: /\}/,
    -      keywords: KEYWORDS$1,
    -      contains: [
    -        "self"
    -      ].concat(SUBST_INTERNALS)
    -    });
    -  const SUBST_AND_COMMENTS = [].concat(COMMENT, SUBST.contains);
    -  const PARAMS_CONTAINS = SUBST_AND_COMMENTS.concat([
    -    // eat recursive parens in sub expressions
    -    {
    -      begin: /\(/,
    -      end: /\)/,
    -      keywords: KEYWORDS$1,
    -      contains: ["self"].concat(SUBST_AND_COMMENTS)
    -    }
    -  ]);
    -  const PARAMS = {
    -    className: 'params',
    -    begin: /\(/,
    -    end: /\)/,
    -    excludeBegin: true,
    -    excludeEnd: true,
    -    keywords: KEYWORDS$1,
    -    contains: PARAMS_CONTAINS
    -  };
    -
    -  return {
    -    name: 'Javascript',
    -    aliases: ['js', 'jsx', 'mjs', 'cjs'],
    -    keywords: KEYWORDS$1,
    -    // this will be extended by TypeScript
    -    exports: { PARAMS_CONTAINS },
    -    illegal: /#(?![$_A-z])/,
    -    contains: [
    -      hljs.SHEBANG({
    -        label: "shebang",
    -        binary: "node",
    -        relevance: 5
    -      }),
    -      {
    -        label: "use_strict",
    -        className: 'meta',
    -        relevance: 10,
    -        begin: /^\s*['"]use (strict|asm)['"]/
    -      },
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      HTML_TEMPLATE,
    -      CSS_TEMPLATE,
    -      TEMPLATE_STRING,
    -      COMMENT,
    -      NUMBER,
    -      { // object attr container
    -        begin: concat(/[{,\n]\s*/,
    -          // we need to look ahead to make sure that we actually have an
    -          // attribute coming up so we don't steal a comma from a potential
    -          // "value" container
    -          //
    -          // NOTE: this might not work how you think.  We don't actually always
    -          // enter this mode and stay.  Instead it might merely match `,
    -          // ` and then immediately end after the , because it
    -          // fails to find any actual attrs. But this still does the job because
    -          // it prevents the value contain rule from grabbing this instead and
    -          // prevening this rule from firing when we actually DO have keys.
    -          lookahead(concat(
    -            // we also need to allow for multiple possible comments inbetween
    -            // the first key:value pairing
    -            /(((\/\/.*$)|(\/\*(\*[^/]|[^*])*\*\/))\s*)*/,
    -            IDENT_RE$1 + '\\s*:'))),
    -        relevance: 0,
    -        contains: [
    -          {
    -            className: 'attr',
    -            begin: IDENT_RE$1 + lookahead('\\s*:'),
    -            relevance: 0
    -          }
    -        ]
    -      },
    -      { // "value" container
    -        begin: '(' + hljs.RE_STARTERS_RE + '|\\b(case|return|throw)\\b)\\s*',
    -        keywords: 'return throw case',
    -        contains: [
    -          COMMENT,
    -          hljs.REGEXP_MODE,
    -          {
    -            className: 'function',
    -            // we have to count the parens to make sure we actually have the
    -            // correct bounding ( ) before the =>.  There could be any number of
    -            // sub-expressions inside also surrounded by parens.
    -            begin: '(\\(' +
    -            '[^()]*(\\(' +
    -            '[^()]*(\\(' +
    -            '[^()]*' +
    -            '\\)[^()]*)*' +
    -            '\\)[^()]*)*' +
    -            '\\)|' + hljs.UNDERSCORE_IDENT_RE + ')\\s*=>',
    -            returnBegin: true,
    -            end: '\\s*=>',
    -            contains: [
    -              {
    -                className: 'params',
    -                variants: [
    -                  {
    -                    begin: hljs.UNDERSCORE_IDENT_RE,
    -                    relevance: 0
    -                  },
    -                  {
    -                    className: null,
    -                    begin: /\(\s*\)/,
    -                    skip: true
    -                  },
    -                  {
    -                    begin: /\(/,
    -                    end: /\)/,
    -                    excludeBegin: true,
    -                    excludeEnd: true,
    -                    keywords: KEYWORDS$1,
    -                    contains: PARAMS_CONTAINS
    -                  }
    -                ]
    -              }
    -            ]
    -          },
    -          { // could be a comma delimited list of params to a function call
    -            begin: /,/, relevance: 0
    -          },
    -          {
    -            className: '',
    -            begin: /\s/,
    -            end: /\s*/,
    -            skip: true
    -          },
    -          { // JSX
    -            variants: [
    -              { begin: FRAGMENT.begin, end: FRAGMENT.end },
    -              {
    -                begin: XML_TAG.begin,
    -                // we carefully check the opening tag to see if it truly
    -                // is a tag and not a false positive
    -                'on:begin': XML_TAG.isTrulyOpeningTag,
    -                end: XML_TAG.end
    -              }
    -            ],
    -            subLanguage: 'xml',
    -            contains: [
    -              {
    -                begin: XML_TAG.begin,
    -                end: XML_TAG.end,
    -                skip: true,
    -                contains: ['self']
    -              }
    -            ]
    -          }
    -        ],
    -        relevance: 0
    -      },
    -      {
    -        className: 'function',
    -        beginKeywords: 'function',
    -        end: /[{;]/,
    -        excludeEnd: true,
    -        keywords: KEYWORDS$1,
    -        contains: [
    -          'self',
    -          hljs.inherit(hljs.TITLE_MODE, { begin: IDENT_RE$1 }),
    -          PARAMS
    -        ],
    -        illegal: /%/
    -      },
    -      {
    -        // prevent this from getting swallowed up by function
    -        // since they appear "function like"
    -        beginKeywords: "while if switch catch for"
    -      },
    -      {
    -        className: 'function',
    -        // we have to count the parens to make sure we actually have the correct
    -        // bounding ( ).  There could be any number of sub-expressions inside
    -        // also surrounded by parens.
    -        begin: hljs.UNDERSCORE_IDENT_RE +
    -          '\\(' + // first parens
    -          '[^()]*(\\(' +
    -            '[^()]*(\\(' +
    -              '[^()]*' +
    -            '\\)[^()]*)*' +
    -          '\\)[^()]*)*' +
    -          '\\)\\s*\\{', // end parens
    -        returnBegin:true,
    -        contains: [
    -          PARAMS,
    -          hljs.inherit(hljs.TITLE_MODE, { begin: IDENT_RE$1 }),
    -        ]
    -      },
    -      // hack: prevents detection of keywords in some circumstances
    -      // .keyword()
    -      // $keyword = x
    -      {
    -        variants: [
    -          { begin: '\\.' + IDENT_RE$1 },
    -          { begin: '\\$' + IDENT_RE$1 }
    -        ],
    -        relevance: 0
    -      },
    -      { // ES6 class
    -        className: 'class',
    -        beginKeywords: 'class',
    -        end: /[{;=]/,
    -        excludeEnd: true,
    -        illegal: /[:"[\]]/,
    -        contains: [
    -          { beginKeywords: 'extends' },
    -          hljs.UNDERSCORE_TITLE_MODE
    -        ]
    -      },
    -      {
    -        begin: /\b(?=constructor)/,
    -        end: /[{;]/,
    -        excludeEnd: true,
    -        contains: [
    -          hljs.inherit(hljs.TITLE_MODE, { begin: IDENT_RE$1 }),
    -          'self',
    -          PARAMS
    -        ]
    -      },
    -      {
    -        begin: '(get|set)\\s+(?=' + IDENT_RE$1 + '\\()',
    -        end: /\{/,
    -        keywords: "get set",
    -        contains: [
    -          hljs.inherit(hljs.TITLE_MODE, { begin: IDENT_RE$1 }),
    -          { begin: /\(\)/ }, // eat to avoid empty params
    -          PARAMS
    -        ]
    -      },
    -      {
    -        begin: /\$[(.]/ // relevance booster for a pattern common to JS libs: `$(something)` and `$.something`
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = javascript;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/jboss-cli.js b/claude-code-source/node_modules/highlight.js/lib/languages/jboss-cli.js
    deleted file mode 100644
    index 64519d1c..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/jboss-cli.js
    +++ /dev/null
    @@ -1,63 +0,0 @@
    -/*
    - Language: JBoss CLI
    - Author: Raphaël Parrëe 
    - Description: language definition jboss cli
    - Website: https://docs.jboss.org/author/display/WFLY/Command+Line+Interface
    - Category: config
    - */
    -
    -function jbossCli(hljs) {
    -  const PARAM = {
    -    begin: /[\w-]+ *=/,
    -    returnBegin: true,
    -    relevance: 0,
    -    contains: [
    -      {
    -        className: 'attr',
    -        begin: /[\w-]+/
    -      }
    -    ]
    -  };
    -  const PARAMSBLOCK = {
    -    className: 'params',
    -    begin: /\(/,
    -    end: /\)/,
    -    contains: [PARAM],
    -    relevance: 0
    -  };
    -  const OPERATION = {
    -    className: 'function',
    -    begin: /:[\w\-.]+/,
    -    relevance: 0
    -  };
    -  const PATH = {
    -    className: 'string',
    -    begin: /\B([\/.])[\w\-.\/=]+/
    -  };
    -  const COMMAND_PARAMS = {
    -    className: 'params',
    -    begin: /--[\w\-=\/]+/
    -  };
    -  return {
    -    name: 'JBoss CLI',
    -    aliases: ['wildfly-cli'],
    -    keywords: {
    -      $pattern: '[a-z\-]+',
    -      keyword: 'alias batch cd clear command connect connection-factory connection-info data-source deploy ' +
    -      'deployment-info deployment-overlay echo echo-dmr help history if jdbc-driver-info jms-queue|20 jms-topic|20 ls ' +
    -      'patch pwd quit read-attribute read-operation reload rollout-plan run-batch set shutdown try unalias ' +
    -      'undeploy unset version xa-data-source', // module
    -      literal: 'true false'
    -    },
    -    contains: [
    -      hljs.HASH_COMMENT_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      COMMAND_PARAMS,
    -      OPERATION,
    -      PATH,
    -      PARAMSBLOCK
    -    ]
    -  };
    -}
    -
    -module.exports = jbossCli;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/json.js b/claude-code-source/node_modules/highlight.js/lib/languages/json.js
    deleted file mode 100644
    index 83e52bb3..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/json.js
    +++ /dev/null
    @@ -1,63 +0,0 @@
    -/*
    -Language: JSON
    -Description: JSON (JavaScript Object Notation) is a lightweight data-interchange format.
    -Author: Ivan Sagalaev 
    -Website: http://www.json.org
    -Category: common, protocols
    -*/
    -
    -function json(hljs) {
    -  const LITERALS = {
    -    literal: 'true false null'
    -  };
    -  const ALLOWED_COMMENTS = [
    -    hljs.C_LINE_COMMENT_MODE,
    -    hljs.C_BLOCK_COMMENT_MODE
    -  ];
    -  const TYPES = [
    -    hljs.QUOTE_STRING_MODE,
    -    hljs.C_NUMBER_MODE
    -  ];
    -  const VALUE_CONTAINER = {
    -    end: ',',
    -    endsWithParent: true,
    -    excludeEnd: true,
    -    contains: TYPES,
    -    keywords: LITERALS
    -  };
    -  const OBJECT = {
    -    begin: /\{/,
    -    end: /\}/,
    -    contains: [
    -      {
    -        className: 'attr',
    -        begin: /"/,
    -        end: /"/,
    -        contains: [hljs.BACKSLASH_ESCAPE],
    -        illegal: '\\n'
    -      },
    -      hljs.inherit(VALUE_CONTAINER, {
    -        begin: /:/
    -      })
    -    ].concat(ALLOWED_COMMENTS),
    -    illegal: '\\S'
    -  };
    -  const ARRAY = {
    -    begin: '\\[',
    -    end: '\\]',
    -    contains: [hljs.inherit(VALUE_CONTAINER)], // inherit is a workaround for a bug that makes shared modes with endsWithParent compile only the ending of one of the parents
    -    illegal: '\\S'
    -  };
    -  TYPES.push(OBJECT, ARRAY);
    -  ALLOWED_COMMENTS.forEach(function(rule) {
    -    TYPES.push(rule);
    -  });
    -  return {
    -    name: 'JSON',
    -    contains: TYPES,
    -    keywords: LITERALS,
    -    illegal: '\\S'
    -  };
    -}
    -
    -module.exports = json;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/julia-repl.js b/claude-code-source/node_modules/highlight.js/lib/languages/julia-repl.js
    deleted file mode 100644
    index 60fec985..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/julia-repl.js
    +++ /dev/null
    @@ -1,50 +0,0 @@
    -/*
    -Language: Julia REPL
    -Description: Julia REPL sessions
    -Author: Morten Piibeleht 
    -Website: https://julialang.org
    -Requires: julia.js
    -
    -The Julia REPL code blocks look something like the following:
    -
    -  julia> function foo(x)
    -             x + 1
    -         end
    -  foo (generic function with 1 method)
    -
    -They start on a new line with "julia>". Usually there should also be a space after this, but
    -we also allow the code to start right after the > character. The code may run over multiple
    -lines, but the additional lines must start with six spaces (i.e. be indented to match
    -"julia>"). The rest of the code is assumed to be output from the executed code and will be
    -left un-highlighted.
    -
    -Using simply spaces to identify line continuations may get a false-positive if the output
    -also prints out six spaces, but such cases should be rare.
    -*/
    -
    -function juliaRepl(hljs) {
    -  return {
    -    name: 'Julia REPL',
    -    contains: [
    -      {
    -        className: 'meta',
    -        begin: /^julia>/,
    -        relevance: 10,
    -        starts: {
    -          // end the highlighting if we are on a new line and the line does not have at
    -          // least six spaces in the beginning
    -          end: /^(?![ ]{6})/,
    -          subLanguage: 'julia'
    -      },
    -      // jldoctest Markdown blocks are used in the Julia manual and package docs indicate
    -      // code snippets that should be verified when the documentation is built. They can be
    -      // either REPL-like or script-like, but are usually REPL-like and therefore we apply
    -      // julia-repl highlighting to them. More information can be found in Documenter's
    -      // manual: https://juliadocs.github.io/Documenter.jl/latest/man/doctests.html
    -      aliases: ['jldoctest']
    -      }
    -    ]
    -  }
    -}
    -
    -module.exports = juliaRepl;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/julia.js b/claude-code-source/node_modules/highlight.js/lib/languages/julia.js
    deleted file mode 100644
    index 4486357b..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/julia.js
    +++ /dev/null
    @@ -1,416 +0,0 @@
    -/*
    -Language: Julia
    -Description: Julia is a high-level, high-performance, dynamic programming language.
    -Author: Kenta Sato 
    -Contributors: Alex Arslan , Fredrik Ekre 
    -Website: https://julialang.org
    -*/
    -
    -function julia(hljs) {
    -  // Since there are numerous special names in Julia, it is too much trouble
    -  // to maintain them by hand. Hence these names (i.e. keywords, literals and
    -  // built-ins) are automatically generated from Julia 1.5.2 itself through
    -  // the following scripts for each.
    -
    -  // ref: https://docs.julialang.org/en/v1/manual/variables/#Allowed-Variable-Names
    -  var VARIABLE_NAME_RE = '[A-Za-z_\\u00A1-\\uFFFF][A-Za-z_0-9\\u00A1-\\uFFFF]*';
    -
    -  // # keyword generator, multi-word keywords handled manually below (Julia 1.5.2)
    -  // import REPL.REPLCompletions
    -  // res = String["in", "isa", "where"]
    -  // for kw in collect(x.keyword for x in REPLCompletions.complete_keyword(""))
    -  //     if !(contains(kw, " ") || kw == "struct")
    -  //         push!(res, kw)
    -  //     end
    -  // end
    -  // sort!(unique!(res))
    -  // foreach(x -> println("\'", x, "\',"), res)
    -  var KEYWORD_LIST = [
    -    'baremodule',
    -    'begin',
    -    'break',
    -    'catch',
    -    'ccall',
    -    'const',
    -    'continue',
    -    'do',
    -    'else',
    -    'elseif',
    -    'end',
    -    'export',
    -    'false',
    -    'finally',
    -    'for',
    -    'function',
    -    'global',
    -    'if',
    -    'import',
    -    'in',
    -    'isa',
    -    'let',
    -    'local',
    -    'macro',
    -    'module',
    -    'quote',
    -    'return',
    -    'true',
    -    'try',
    -    'using',
    -    'where',
    -    'while',
    -  ];
    -
    -  // # literal generator (Julia 1.5.2)
    -  // import REPL.REPLCompletions
    -  // res = String["true", "false"]
    -  // for compl in filter!(x -> isa(x, REPLCompletions.ModuleCompletion) && (x.parent === Base || x.parent === Core),
    -  //                     REPLCompletions.completions("", 0)[1])
    -  //     try
    -  //         v = eval(Symbol(compl.mod))
    -  //         if !(v isa Function || v isa Type || v isa TypeVar || v isa Module || v isa Colon)
    -  //             push!(res, compl.mod)
    -  //         end
    -  //     catch e
    -  //     end
    -  // end
    -  // sort!(unique!(res))
    -  // foreach(x -> println("\'", x, "\',"), res)
    -  var LITERAL_LIST = [
    -    'ARGS',
    -    'C_NULL',
    -    'DEPOT_PATH',
    -    'ENDIAN_BOM',
    -    'ENV',
    -    'Inf',
    -    'Inf16',
    -    'Inf32',
    -    'Inf64',
    -    'InsertionSort',
    -    'LOAD_PATH',
    -    'MergeSort',
    -    'NaN',
    -    'NaN16',
    -    'NaN32',
    -    'NaN64',
    -    'PROGRAM_FILE',
    -    'QuickSort',
    -    'RoundDown',
    -    'RoundFromZero',
    -    'RoundNearest',
    -    'RoundNearestTiesAway',
    -    'RoundNearestTiesUp',
    -    'RoundToZero',
    -    'RoundUp',
    -    'VERSION|0',
    -    'devnull',
    -    'false',
    -    'im',
    -    'missing',
    -    'nothing',
    -    'pi',
    -    'stderr',
    -    'stdin',
    -    'stdout',
    -    'true',
    -    'undef',
    -    'π',
    -    'ℯ',
    -  ];
    -
    -  // # built_in generator (Julia 1.5.2)
    -  // import REPL.REPLCompletions
    -  // res = String[]
    -  // for compl in filter!(x -> isa(x, REPLCompletions.ModuleCompletion) && (x.parent === Base || x.parent === Core),
    -  //                     REPLCompletions.completions("", 0)[1])
    -  //     try
    -  //         v = eval(Symbol(compl.mod))
    -  //         if (v isa Type || v isa TypeVar) && (compl.mod != "=>")
    -  //             push!(res, compl.mod)
    -  //         end
    -  //     catch e
    -  //     end
    -  // end
    -  // sort!(unique!(res))
    -  // foreach(x -> println("\'", x, "\',"), res)
    -  var BUILT_IN_LIST = [
    -    'AbstractArray',
    -    'AbstractChannel',
    -    'AbstractChar',
    -    'AbstractDict',
    -    'AbstractDisplay',
    -    'AbstractFloat',
    -    'AbstractIrrational',
    -    'AbstractMatrix',
    -    'AbstractRange',
    -    'AbstractSet',
    -    'AbstractString',
    -    'AbstractUnitRange',
    -    'AbstractVecOrMat',
    -    'AbstractVector',
    -    'Any',
    -    'ArgumentError',
    -    'Array',
    -    'AssertionError',
    -    'BigFloat',
    -    'BigInt',
    -    'BitArray',
    -    'BitMatrix',
    -    'BitSet',
    -    'BitVector',
    -    'Bool',
    -    'BoundsError',
    -    'CapturedException',
    -    'CartesianIndex',
    -    'CartesianIndices',
    -    'Cchar',
    -    'Cdouble',
    -    'Cfloat',
    -    'Channel',
    -    'Char',
    -    'Cint',
    -    'Cintmax_t',
    -    'Clong',
    -    'Clonglong',
    -    'Cmd',
    -    'Colon',
    -    'Complex',
    -    'ComplexF16',
    -    'ComplexF32',
    -    'ComplexF64',
    -    'CompositeException',
    -    'Condition',
    -    'Cptrdiff_t',
    -    'Cshort',
    -    'Csize_t',
    -    'Cssize_t',
    -    'Cstring',
    -    'Cuchar',
    -    'Cuint',
    -    'Cuintmax_t',
    -    'Culong',
    -    'Culonglong',
    -    'Cushort',
    -    'Cvoid',
    -    'Cwchar_t',
    -    'Cwstring',
    -    'DataType',
    -    'DenseArray',
    -    'DenseMatrix',
    -    'DenseVecOrMat',
    -    'DenseVector',
    -    'Dict',
    -    'DimensionMismatch',
    -    'Dims',
    -    'DivideError',
    -    'DomainError',
    -    'EOFError',
    -    'Enum',
    -    'ErrorException',
    -    'Exception',
    -    'ExponentialBackOff',
    -    'Expr',
    -    'Float16',
    -    'Float32',
    -    'Float64',
    -    'Function',
    -    'GlobalRef',
    -    'HTML',
    -    'IO',
    -    'IOBuffer',
    -    'IOContext',
    -    'IOStream',
    -    'IdDict',
    -    'IndexCartesian',
    -    'IndexLinear',
    -    'IndexStyle',
    -    'InexactError',
    -    'InitError',
    -    'Int',
    -    'Int128',
    -    'Int16',
    -    'Int32',
    -    'Int64',
    -    'Int8',
    -    'Integer',
    -    'InterruptException',
    -    'InvalidStateException',
    -    'Irrational',
    -    'KeyError',
    -    'LinRange',
    -    'LineNumberNode',
    -    'LinearIndices',
    -    'LoadError',
    -    'MIME',
    -    'Matrix',
    -    'Method',
    -    'MethodError',
    -    'Missing',
    -    'MissingException',
    -    'Module',
    -    'NTuple',
    -    'NamedTuple',
    -    'Nothing',
    -    'Number',
    -    'OrdinalRange',
    -    'OutOfMemoryError',
    -    'OverflowError',
    -    'Pair',
    -    'PartialQuickSort',
    -    'PermutedDimsArray',
    -    'Pipe',
    -    'ProcessFailedException',
    -    'Ptr',
    -    'QuoteNode',
    -    'Rational',
    -    'RawFD',
    -    'ReadOnlyMemoryError',
    -    'Real',
    -    'ReentrantLock',
    -    'Ref',
    -    'Regex',
    -    'RegexMatch',
    -    'RoundingMode',
    -    'SegmentationFault',
    -    'Set',
    -    'Signed',
    -    'Some',
    -    'StackOverflowError',
    -    'StepRange',
    -    'StepRangeLen',
    -    'StridedArray',
    -    'StridedMatrix',
    -    'StridedVecOrMat',
    -    'StridedVector',
    -    'String',
    -    'StringIndexError',
    -    'SubArray',
    -    'SubString',
    -    'SubstitutionString',
    -    'Symbol',
    -    'SystemError',
    -    'Task',
    -    'TaskFailedException',
    -    'Text',
    -    'TextDisplay',
    -    'Timer',
    -    'Tuple',
    -    'Type',
    -    'TypeError',
    -    'TypeVar',
    -    'UInt',
    -    'UInt128',
    -    'UInt16',
    -    'UInt32',
    -    'UInt64',
    -    'UInt8',
    -    'UndefInitializer',
    -    'UndefKeywordError',
    -    'UndefRefError',
    -    'UndefVarError',
    -    'Union',
    -    'UnionAll',
    -    'UnitRange',
    -    'Unsigned',
    -    'Val',
    -    'Vararg',
    -    'VecElement',
    -    'VecOrMat',
    -    'Vector',
    -    'VersionNumber',
    -    'WeakKeyDict',
    -    'WeakRef',
    -  ];
    -
    -  var KEYWORDS = {
    -    $pattern: VARIABLE_NAME_RE,
    -    keyword: KEYWORD_LIST,
    -    literal: LITERAL_LIST,
    -    built_in: BUILT_IN_LIST,
    -  };
    -
    -  // placeholder for recursive self-reference
    -  var DEFAULT = {
    -    keywords: KEYWORDS, illegal: /<\//
    -  };
    -
    -  // ref: https://docs.julialang.org/en/v1/manual/integers-and-floating-point-numbers/
    -  var NUMBER = {
    -    className: 'number',
    -    // supported numeric literals:
    -    //  * binary literal (e.g. 0x10)
    -    //  * octal literal (e.g. 0o76543210)
    -    //  * hexadecimal literal (e.g. 0xfedcba876543210)
    -    //  * hexadecimal floating point literal (e.g. 0x1p0, 0x1.2p2)
    -    //  * decimal literal (e.g. 9876543210, 100_000_000)
    -    //  * floating pointe literal (e.g. 1.2, 1.2f, .2, 1., 1.2e10, 1.2e-10)
    -    begin: /(\b0x[\d_]*(\.[\d_]*)?|0x\.\d[\d_]*)p[-+]?\d+|\b0[box][a-fA-F0-9][a-fA-F0-9_]*|(\b\d[\d_]*(\.[\d_]*)?|\.\d[\d_]*)([eEfF][-+]?\d+)?/,
    -    relevance: 0
    -  };
    -
    -  var CHAR = {
    -    className: 'string',
    -    begin: /'(.|\\[xXuU][a-zA-Z0-9]+)'/
    -  };
    -
    -  var INTERPOLATION = {
    -    className: 'subst',
    -    begin: /\$\(/, end: /\)/,
    -    keywords: KEYWORDS
    -  };
    -
    -  var INTERPOLATED_VARIABLE = {
    -    className: 'variable',
    -    begin: '\\$' + VARIABLE_NAME_RE
    -  };
    -
    -  // TODO: neatly escape normal code in string literal
    -  var STRING = {
    -    className: 'string',
    -    contains: [hljs.BACKSLASH_ESCAPE, INTERPOLATION, INTERPOLATED_VARIABLE],
    -    variants: [
    -      { begin: /\w*"""/, end: /"""\w*/, relevance: 10 },
    -      { begin: /\w*"/, end: /"\w*/ }
    -    ]
    -  };
    -
    -  var COMMAND = {
    -    className: 'string',
    -    contains: [hljs.BACKSLASH_ESCAPE, INTERPOLATION, INTERPOLATED_VARIABLE],
    -    begin: '`', end: '`'
    -  };
    -
    -  var MACROCALL = {
    -    className: 'meta',
    -    begin: '@' + VARIABLE_NAME_RE
    -  };
    -
    -  var COMMENT = {
    -    className: 'comment',
    -    variants: [
    -      { begin: '#=', end: '=#', relevance: 10 },
    -      { begin: '#', end: '$' }
    -    ]
    -  };
    -
    -  DEFAULT.name = 'Julia';
    -  DEFAULT.contains = [
    -    NUMBER,
    -    CHAR,
    -    STRING,
    -    COMMAND,
    -    MACROCALL,
    -    COMMENT,
    -    hljs.HASH_COMMENT_MODE,
    -    {
    -      className: 'keyword',
    -      begin:
    -        '\\b(((abstract|primitive)\\s+)type|(mutable\\s+)?struct)\\b'
    -    },
    -    {begin: /<:/}  // relevance booster
    -  ];
    -  INTERPOLATION.contains = DEFAULT.contains;
    -
    -  return DEFAULT;
    -}
    -
    -module.exports = julia;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/kotlin.js b/claude-code-source/node_modules/highlight.js/lib/languages/kotlin.js
    deleted file mode 100644
    index 89d3d8cd..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/kotlin.js
    +++ /dev/null
    @@ -1,284 +0,0 @@
    -// https://docs.oracle.com/javase/specs/jls/se15/html/jls-3.html#jls-3.10
    -var decimalDigits = '[0-9](_*[0-9])*';
    -var frac = `\\.(${decimalDigits})`;
    -var hexDigits = '[0-9a-fA-F](_*[0-9a-fA-F])*';
    -var NUMERIC = {
    -  className: 'number',
    -  variants: [
    -    // DecimalFloatingPointLiteral
    -    // including ExponentPart
    -    { begin: `(\\b(${decimalDigits})((${frac})|\\.)?|(${frac}))` +
    -      `[eE][+-]?(${decimalDigits})[fFdD]?\\b` },
    -    // excluding ExponentPart
    -    { begin: `\\b(${decimalDigits})((${frac})[fFdD]?\\b|\\.([fFdD]\\b)?)` },
    -    { begin: `(${frac})[fFdD]?\\b` },
    -    { begin: `\\b(${decimalDigits})[fFdD]\\b` },
    -
    -    // HexadecimalFloatingPointLiteral
    -    { begin: `\\b0[xX]((${hexDigits})\\.?|(${hexDigits})?\\.(${hexDigits}))` +
    -      `[pP][+-]?(${decimalDigits})[fFdD]?\\b` },
    -
    -    // DecimalIntegerLiteral
    -    { begin: '\\b(0|[1-9](_*[0-9])*)[lL]?\\b' },
    -
    -    // HexIntegerLiteral
    -    { begin: `\\b0[xX](${hexDigits})[lL]?\\b` },
    -
    -    // OctalIntegerLiteral
    -    { begin: '\\b0(_*[0-7])*[lL]?\\b' },
    -
    -    // BinaryIntegerLiteral
    -    { begin: '\\b0[bB][01](_*[01])*[lL]?\\b' },
    -  ],
    -  relevance: 0
    -};
    -
    -/*
    - Language: Kotlin
    - Description: Kotlin is an OSS statically typed programming language that targets the JVM, Android, JavaScript and Native.
    - Author: Sergey Mashkov 
    - Website: https://kotlinlang.org
    - Category: common
    - */
    -
    -function kotlin(hljs) {
    -  const KEYWORDS = {
    -    keyword:
    -      'abstract as val var vararg get set class object open private protected public noinline ' +
    -      'crossinline dynamic final enum if else do while for when throw try catch finally ' +
    -      'import package is in fun override companion reified inline lateinit init ' +
    -      'interface annotation data sealed internal infix operator out by constructor super ' +
    -      'tailrec where const inner suspend typealias external expect actual',
    -    built_in:
    -      'Byte Short Char Int Long Boolean Float Double Void Unit Nothing',
    -    literal:
    -      'true false null'
    -  };
    -  const KEYWORDS_WITH_LABEL = {
    -    className: 'keyword',
    -    begin: /\b(break|continue|return|this)\b/,
    -    starts: {
    -      contains: [
    -        {
    -          className: 'symbol',
    -          begin: /@\w+/
    -        }
    -      ]
    -    }
    -  };
    -  const LABEL = {
    -    className: 'symbol',
    -    begin: hljs.UNDERSCORE_IDENT_RE + '@'
    -  };
    -
    -  // for string templates
    -  const SUBST = {
    -    className: 'subst',
    -    begin: /\$\{/,
    -    end: /\}/,
    -    contains: [ hljs.C_NUMBER_MODE ]
    -  };
    -  const VARIABLE = {
    -    className: 'variable',
    -    begin: '\\$' + hljs.UNDERSCORE_IDENT_RE
    -  };
    -  const STRING = {
    -    className: 'string',
    -    variants: [
    -      {
    -        begin: '"""',
    -        end: '"""(?=[^"])',
    -        contains: [
    -          VARIABLE,
    -          SUBST
    -        ]
    -      },
    -      // Can't use built-in modes easily, as we want to use STRING in the meta
    -      // context as 'meta-string' and there's no syntax to remove explicitly set
    -      // classNames in built-in modes.
    -      {
    -        begin: '\'',
    -        end: '\'',
    -        illegal: /\n/,
    -        contains: [ hljs.BACKSLASH_ESCAPE ]
    -      },
    -      {
    -        begin: '"',
    -        end: '"',
    -        illegal: /\n/,
    -        contains: [
    -          hljs.BACKSLASH_ESCAPE,
    -          VARIABLE,
    -          SUBST
    -        ]
    -      }
    -    ]
    -  };
    -  SUBST.contains.push(STRING);
    -
    -  const ANNOTATION_USE_SITE = {
    -    className: 'meta',
    -    begin: '@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*' + hljs.UNDERSCORE_IDENT_RE + ')?'
    -  };
    -  const ANNOTATION = {
    -    className: 'meta',
    -    begin: '@' + hljs.UNDERSCORE_IDENT_RE,
    -    contains: [
    -      {
    -        begin: /\(/,
    -        end: /\)/,
    -        contains: [
    -          hljs.inherit(STRING, {
    -            className: 'meta-string'
    -          })
    -        ]
    -      }
    -    ]
    -  };
    -
    -  // https://kotlinlang.org/docs/reference/whatsnew11.html#underscores-in-numeric-literals
    -  // According to the doc above, the number mode of kotlin is the same as java 8,
    -  // so the code below is copied from java.js
    -  const KOTLIN_NUMBER_MODE = NUMERIC;
    -  const KOTLIN_NESTED_COMMENT = hljs.COMMENT(
    -    '/\\*', '\\*/',
    -    {
    -      contains: [ hljs.C_BLOCK_COMMENT_MODE ]
    -    }
    -  );
    -  const KOTLIN_PAREN_TYPE = {
    -    variants: [
    -      {
    -        className: 'type',
    -        begin: hljs.UNDERSCORE_IDENT_RE
    -      },
    -      {
    -        begin: /\(/,
    -        end: /\)/,
    -        contains: [] // defined later
    -      }
    -    ]
    -  };
    -  const KOTLIN_PAREN_TYPE2 = KOTLIN_PAREN_TYPE;
    -  KOTLIN_PAREN_TYPE2.variants[1].contains = [ KOTLIN_PAREN_TYPE ];
    -  KOTLIN_PAREN_TYPE.variants[1].contains = [ KOTLIN_PAREN_TYPE2 ];
    -
    -  return {
    -    name: 'Kotlin',
    -    aliases: [ 'kt', 'kts' ],
    -    keywords: KEYWORDS,
    -    contains: [
    -      hljs.COMMENT(
    -        '/\\*\\*',
    -        '\\*/',
    -        {
    -          relevance: 0,
    -          contains: [
    -            {
    -              className: 'doctag',
    -              begin: '@[A-Za-z]+'
    -            }
    -          ]
    -        }
    -      ),
    -      hljs.C_LINE_COMMENT_MODE,
    -      KOTLIN_NESTED_COMMENT,
    -      KEYWORDS_WITH_LABEL,
    -      LABEL,
    -      ANNOTATION_USE_SITE,
    -      ANNOTATION,
    -      {
    -        className: 'function',
    -        beginKeywords: 'fun',
    -        end: '[(]|$',
    -        returnBegin: true,
    -        excludeEnd: true,
    -        keywords: KEYWORDS,
    -        relevance: 5,
    -        contains: [
    -          {
    -            begin: hljs.UNDERSCORE_IDENT_RE + '\\s*\\(',
    -            returnBegin: true,
    -            relevance: 0,
    -            contains: [ hljs.UNDERSCORE_TITLE_MODE ]
    -          },
    -          {
    -            className: 'type',
    -            begin: //,
    -            keywords: 'reified',
    -            relevance: 0
    -          },
    -          {
    -            className: 'params',
    -            begin: /\(/,
    -            end: /\)/,
    -            endsParent: true,
    -            keywords: KEYWORDS,
    -            relevance: 0,
    -            contains: [
    -              {
    -                begin: /:/,
    -                end: /[=,\/]/,
    -                endsWithParent: true,
    -                contains: [
    -                  KOTLIN_PAREN_TYPE,
    -                  hljs.C_LINE_COMMENT_MODE,
    -                  KOTLIN_NESTED_COMMENT
    -                ],
    -                relevance: 0
    -              },
    -              hljs.C_LINE_COMMENT_MODE,
    -              KOTLIN_NESTED_COMMENT,
    -              ANNOTATION_USE_SITE,
    -              ANNOTATION,
    -              STRING,
    -              hljs.C_NUMBER_MODE
    -            ]
    -          },
    -          KOTLIN_NESTED_COMMENT
    -        ]
    -      },
    -      {
    -        className: 'class',
    -        beginKeywords: 'class interface trait', // remove 'trait' when removed from KEYWORDS
    -        end: /[:\{(]|$/,
    -        excludeEnd: true,
    -        illegal: 'extends implements',
    -        contains: [
    -          {
    -            beginKeywords: 'public protected internal private constructor'
    -          },
    -          hljs.UNDERSCORE_TITLE_MODE,
    -          {
    -            className: 'type',
    -            begin: //,
    -            excludeBegin: true,
    -            excludeEnd: true,
    -            relevance: 0
    -          },
    -          {
    -            className: 'type',
    -            begin: /[,:]\s*/,
    -            end: /[<\(,]|$/,
    -            excludeBegin: true,
    -            returnEnd: true
    -          },
    -          ANNOTATION_USE_SITE,
    -          ANNOTATION
    -        ]
    -      },
    -      STRING,
    -      {
    -        className: 'meta',
    -        begin: "^#!/usr/bin/env",
    -        end: '$',
    -        illegal: '\n'
    -      },
    -      KOTLIN_NUMBER_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = kotlin;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/lasso.js b/claude-code-source/node_modules/highlight.js/lib/languages/lasso.js
    deleted file mode 100644
    index 184b4904..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/lasso.js
    +++ /dev/null
    @@ -1,187 +0,0 @@
    -/*
    -Language: Lasso
    -Author: Eric Knibbe 
    -Description: Lasso is a language and server platform for database-driven web applications. This definition handles Lasso 9 syntax and LassoScript for Lasso 8.6 and earlier.
    -Website: http://www.lassosoft.com/What-Is-Lasso
    -*/
    -
    -function lasso(hljs) {
    -  const LASSO_IDENT_RE = '[a-zA-Z_][\\w.]*';
    -  const LASSO_ANGLE_RE = '<\\?(lasso(script)?|=)';
    -  const LASSO_CLOSE_RE = '\\]|\\?>';
    -  const LASSO_KEYWORDS = {
    -    $pattern: LASSO_IDENT_RE + '|&[lg]t;',
    -    literal:
    -      'true false none minimal full all void and or not ' +
    -      'bw nbw ew new cn ncn lt lte gt gte eq neq rx nrx ft',
    -    built_in:
    -      'array date decimal duration integer map pair string tag xml null ' +
    -      'boolean bytes keyword list locale queue set stack staticarray ' +
    -      'local var variable global data self inherited currentcapture givenblock',
    -    keyword:
    -      'cache database_names database_schemanames database_tablenames ' +
    -      'define_tag define_type email_batch encode_set html_comment handle ' +
    -      'handle_error header if inline iterate ljax_target link ' +
    -      'link_currentaction link_currentgroup link_currentrecord link_detail ' +
    -      'link_firstgroup link_firstrecord link_lastgroup link_lastrecord ' +
    -      'link_nextgroup link_nextrecord link_prevgroup link_prevrecord log ' +
    -      'loop namespace_using output_none portal private protect records ' +
    -      'referer referrer repeating resultset rows search_args ' +
    -      'search_arguments select sort_args sort_arguments thread_atomic ' +
    -      'value_list while abort case else fail_if fail_ifnot fail if_empty ' +
    -      'if_false if_null if_true loop_abort loop_continue loop_count params ' +
    -      'params_up return return_value run_children soap_definetag ' +
    -      'soap_lastrequest soap_lastresponse tag_name ascending average by ' +
    -      'define descending do equals frozen group handle_failure import in ' +
    -      'into join let match max min on order parent protected provide public ' +
    -      'require returnhome skip split_thread sum take thread to trait type ' +
    -      'where with yield yieldhome'
    -  };
    -  const HTML_COMMENT = hljs.COMMENT(
    -    '',
    -    {
    -      relevance: 0
    -    }
    -  );
    -  const LASSO_NOPROCESS = {
    -    className: 'meta',
    -    begin: '\\[noprocess\\]',
    -    starts: {
    -      end: '\\[/noprocess\\]',
    -      returnEnd: true,
    -      contains: [HTML_COMMENT]
    -    }
    -  };
    -  const LASSO_START = {
    -    className: 'meta',
    -    begin: '\\[/noprocess|' + LASSO_ANGLE_RE
    -  };
    -  const LASSO_DATAMEMBER = {
    -    className: 'symbol',
    -    begin: '\'' + LASSO_IDENT_RE + '\''
    -  };
    -  const LASSO_CODE = [
    -    hljs.C_LINE_COMMENT_MODE,
    -    hljs.C_BLOCK_COMMENT_MODE,
    -    hljs.inherit(hljs.C_NUMBER_MODE, {
    -      begin: hljs.C_NUMBER_RE + '|(-?infinity|NaN)\\b'
    -    }),
    -    hljs.inherit(hljs.APOS_STRING_MODE, {
    -      illegal: null
    -    }),
    -    hljs.inherit(hljs.QUOTE_STRING_MODE, {
    -      illegal: null
    -    }),
    -    {
    -      className: 'string',
    -      begin: '`',
    -      end: '`'
    -    },
    -    { // variables
    -      variants: [
    -        {
    -          begin: '[#$]' + LASSO_IDENT_RE
    -        },
    -        {
    -          begin: '#',
    -          end: '\\d+',
    -          illegal: '\\W'
    -        }
    -      ]
    -    },
    -    {
    -      className: 'type',
    -      begin: '::\\s*',
    -      end: LASSO_IDENT_RE,
    -      illegal: '\\W'
    -    },
    -    {
    -      className: 'params',
    -      variants: [
    -        {
    -          begin: '-(?!infinity)' + LASSO_IDENT_RE,
    -          relevance: 0
    -        },
    -        {
    -          begin: '(\\.\\.\\.)'
    -        }
    -      ]
    -    },
    -    {
    -      begin: /(->|\.)\s*/,
    -      relevance: 0,
    -      contains: [LASSO_DATAMEMBER]
    -    },
    -    {
    -      className: 'class',
    -      beginKeywords: 'define',
    -      returnEnd: true,
    -      end: '\\(|=>',
    -      contains: [
    -        hljs.inherit(hljs.TITLE_MODE, {
    -          begin: LASSO_IDENT_RE + '(=(?!>))?|[-+*/%](?!>)'
    -        })
    -      ]
    -    }
    -  ];
    -  return {
    -    name: 'Lasso',
    -    aliases: [
    -      'ls',
    -      'lassoscript'
    -    ],
    -    case_insensitive: true,
    -    keywords: LASSO_KEYWORDS,
    -    contains: [
    -      {
    -        className: 'meta',
    -        begin: LASSO_CLOSE_RE,
    -        relevance: 0,
    -        starts: { // markup
    -          end: '\\[|' + LASSO_ANGLE_RE,
    -          returnEnd: true,
    -          relevance: 0,
    -          contains: [HTML_COMMENT]
    -        }
    -      },
    -      LASSO_NOPROCESS,
    -      LASSO_START,
    -      {
    -        className: 'meta',
    -        begin: '\\[no_square_brackets',
    -        starts: {
    -          end: '\\[/no_square_brackets\\]', // not implemented in the language
    -          keywords: LASSO_KEYWORDS,
    -          contains: [
    -            {
    -              className: 'meta',
    -              begin: LASSO_CLOSE_RE,
    -              relevance: 0,
    -              starts: {
    -                end: '\\[noprocess\\]|' + LASSO_ANGLE_RE,
    -                returnEnd: true,
    -                contains: [HTML_COMMENT]
    -              }
    -            },
    -            LASSO_NOPROCESS,
    -            LASSO_START
    -          ].concat(LASSO_CODE)
    -        }
    -      },
    -      {
    -        className: 'meta',
    -        begin: '\\[',
    -        relevance: 0
    -      },
    -      {
    -        className: 'meta',
    -        begin: '^#!',
    -        end: 'lasso9$',
    -        relevance: 10
    -      }
    -    ].concat(LASSO_CODE)
    -  };
    -}
    -
    -module.exports = lasso;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/latex.js b/claude-code-source/node_modules/highlight.js/lib/languages/latex.js
    deleted file mode 100644
    index e61c98a6..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/latex.js
    +++ /dev/null
    @@ -1,276 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * Any of the passed expresssions may match
    - *
    - * Creates a huge this | this | that | that match
    - * @param {(RegExp | string)[] } args
    - * @returns {string}
    - */
    -function either(...args) {
    -  const joined = '(' + args.map((x) => source(x)).join("|") + ")";
    -  return joined;
    -}
    -
    -/*
    -Language: LaTeX
    -Author: Benedikt Wilde 
    -Website: https://www.latex-project.org
    -Category: markup
    -*/
    -
    -/** @type LanguageFn */
    -function latex(hljs) {
    -  const KNOWN_CONTROL_WORDS = either(...[
    -      '(?:NeedsTeXFormat|RequirePackage|GetIdInfo)',
    -      'Provides(?:Expl)?(?:Package|Class|File)',
    -      '(?:DeclareOption|ProcessOptions)',
    -      '(?:documentclass|usepackage|input|include)',
    -      'makeat(?:letter|other)',
    -      'ExplSyntax(?:On|Off)',
    -      '(?:new|renew|provide)?command',
    -      '(?:re)newenvironment',
    -      '(?:New|Renew|Provide|Declare)(?:Expandable)?DocumentCommand',
    -      '(?:New|Renew|Provide|Declare)DocumentEnvironment',
    -      '(?:(?:e|g|x)?def|let)',
    -      '(?:begin|end)',
    -      '(?:part|chapter|(?:sub){0,2}section|(?:sub)?paragraph)',
    -      'caption',
    -      '(?:label|(?:eq|page|name)?ref|(?:paren|foot|super)?cite)',
    -      '(?:alpha|beta|[Gg]amma|[Dd]elta|(?:var)?epsilon|zeta|eta|[Tt]heta|vartheta)',
    -      '(?:iota|(?:var)?kappa|[Ll]ambda|mu|nu|[Xx]i|[Pp]i|varpi|(?:var)rho)',
    -      '(?:[Ss]igma|varsigma|tau|[Uu]psilon|[Pp]hi|varphi|chi|[Pp]si|[Oo]mega)',
    -      '(?:frac|sum|prod|lim|infty|times|sqrt|leq|geq|left|right|middle|[bB]igg?)',
    -      '(?:[lr]angle|q?quad|[lcvdi]?dots|d?dot|hat|tilde|bar)'
    -    ].map(word => word + '(?![a-zA-Z@:_])'));
    -  const L3_REGEX = new RegExp([
    -      // A function \module_function_name:signature or \__module_function_name:signature,
    -      // where both module and function_name need at least two characters and
    -      // function_name may contain single underscores.
    -      '(?:__)?[a-zA-Z]{2,}_[a-zA-Z](?:_?[a-zA-Z])+:[a-zA-Z]*',
    -      // A variable \scope_module_and_name_type or \scope__module_ane_name_type,
    -      // where scope is one of l, g or c, type needs at least two characters
    -      // and module_and_name may contain single underscores.
    -      '[lgc]__?[a-zA-Z](?:_?[a-zA-Z])*_[a-zA-Z]{2,}',
    -      // A quark \q_the_name or \q__the_name or
    -      // scan mark \s_the_name or \s__vthe_name,
    -      // where variable_name needs at least two characters and
    -      // may contain single underscores.
    -      '[qs]__?[a-zA-Z](?:_?[a-zA-Z])+',
    -      // Other LaTeX3 macro names that are not covered by the three rules above.
    -      'use(?:_i)?:[a-zA-Z]*',
    -      '(?:else|fi|or):',
    -      '(?:if|cs|exp):w',
    -      '(?:hbox|vbox):n',
    -      '::[a-zA-Z]_unbraced',
    -      '::[a-zA-Z:]'
    -    ].map(pattern => pattern + '(?![a-zA-Z:_])').join('|'));
    -  const L2_VARIANTS = [
    -    {begin: /[a-zA-Z@]+/}, // control word
    -    {begin: /[^a-zA-Z@]?/} // control symbol
    -  ];
    -  const DOUBLE_CARET_VARIANTS = [
    -    {begin: /\^{6}[0-9a-f]{6}/},
    -    {begin: /\^{5}[0-9a-f]{5}/},
    -    {begin: /\^{4}[0-9a-f]{4}/},
    -    {begin: /\^{3}[0-9a-f]{3}/},
    -    {begin: /\^{2}[0-9a-f]{2}/},
    -    {begin: /\^{2}[\u0000-\u007f]/}
    -  ];
    -  const CONTROL_SEQUENCE = {
    -    className: 'keyword',
    -    begin: /\\/,
    -    relevance: 0,
    -    contains: [
    -      {
    -        endsParent: true,
    -        begin: KNOWN_CONTROL_WORDS
    -      },
    -      {
    -        endsParent: true,
    -        begin: L3_REGEX
    -      },
    -      {
    -        endsParent: true,
    -        variants: DOUBLE_CARET_VARIANTS
    -      },
    -      {
    -        endsParent: true,
    -        relevance: 0,
    -        variants: L2_VARIANTS
    -      }
    -    ]
    -  };
    -  const MACRO_PARAM = {
    -    className: 'params',
    -    relevance: 0,
    -    begin: /#+\d?/
    -  };
    -  const DOUBLE_CARET_CHAR = {
    -    // relevance: 1
    -    variants: DOUBLE_CARET_VARIANTS
    -  };
    -  const SPECIAL_CATCODE = {
    -    className: 'built_in',
    -    relevance: 0,
    -    begin: /[$&^_]/
    -  };
    -  const MAGIC_COMMENT = {
    -    className: 'meta',
    -    begin: '% !TeX',
    -    end: '$',
    -    relevance: 10
    -  };
    -  const COMMENT = hljs.COMMENT(
    -    '%',
    -    '$',
    -    {
    -      relevance: 0
    -    }
    -  );
    -  const EVERYTHING_BUT_VERBATIM = [
    -    CONTROL_SEQUENCE,
    -    MACRO_PARAM,
    -    DOUBLE_CARET_CHAR,
    -    SPECIAL_CATCODE,
    -    MAGIC_COMMENT,
    -    COMMENT
    -  ];
    -  const BRACE_GROUP_NO_VERBATIM = {
    -    begin: /\{/, end: /\}/,
    -    relevance: 0,
    -    contains: ['self', ...EVERYTHING_BUT_VERBATIM]
    -  };
    -  const ARGUMENT_BRACES = hljs.inherit(
    -    BRACE_GROUP_NO_VERBATIM,
    -    {
    -      relevance: 0,
    -      endsParent: true,
    -      contains: [BRACE_GROUP_NO_VERBATIM, ...EVERYTHING_BUT_VERBATIM]
    -    }
    -  );
    -  const ARGUMENT_BRACKETS = {
    -    begin: /\[/,
    -      end: /\]/,
    -    endsParent: true,
    -    relevance: 0,
    -    contains: [BRACE_GROUP_NO_VERBATIM, ...EVERYTHING_BUT_VERBATIM]
    -  };
    -  const SPACE_GOBBLER = {
    -    begin: /\s+/,
    -    relevance: 0
    -  };
    -  const ARGUMENT_M = [ARGUMENT_BRACES];
    -  const ARGUMENT_O = [ARGUMENT_BRACKETS];
    -  const ARGUMENT_AND_THEN = function(arg, starts_mode) {
    -    return {
    -      contains: [SPACE_GOBBLER],
    -      starts: {
    -        relevance: 0,
    -        contains: arg,
    -        starts: starts_mode
    -      }
    -    };
    -  };
    -  const CSNAME = function(csname, starts_mode) {
    -    return {
    -        begin: '\\\\' + csname + '(?![a-zA-Z@:_])',
    -        keywords: {$pattern: /\\[a-zA-Z]+/, keyword: '\\' + csname},
    -        relevance: 0,
    -        contains: [SPACE_GOBBLER],
    -        starts: starts_mode
    -      };
    -  };
    -  const BEGIN_ENV = function(envname, starts_mode) {
    -    return hljs.inherit(
    -      {
    -        begin: '\\\\begin(?=[ \t]*(\\r?\\n[ \t]*)?\\{' + envname + '\\})',
    -        keywords: {$pattern: /\\[a-zA-Z]+/, keyword: '\\begin'},
    -        relevance: 0,
    -      },
    -      ARGUMENT_AND_THEN(ARGUMENT_M, starts_mode)
    -    );
    -  };
    -  const VERBATIM_DELIMITED_EQUAL = (innerName = "string") => {
    -    return hljs.END_SAME_AS_BEGIN({
    -      className: innerName,
    -      begin: /(.|\r?\n)/,
    -      end: /(.|\r?\n)/,
    -      excludeBegin: true,
    -      excludeEnd: true,
    -      endsParent: true
    -    });
    -  };
    -  const VERBATIM_DELIMITED_ENV = function(envname) {
    -    return {
    -      className: 'string',
    -      end: '(?=\\\\end\\{' + envname + '\\})'
    -    };
    -  };
    -
    -  const VERBATIM_DELIMITED_BRACES = (innerName = "string") => {
    -    return {
    -      relevance: 0,
    -      begin: /\{/,
    -      starts: {
    -        endsParent: true,
    -        contains: [
    -          {
    -            className: innerName,
    -            end: /(?=\})/,
    -            endsParent:true,
    -            contains: [
    -              {
    -                begin: /\{/,
    -                end: /\}/,
    -                relevance: 0,
    -                contains: ["self"]
    -              }
    -            ],
    -          }
    -        ]
    -      }
    -    };
    -  };
    -  const VERBATIM = [
    -    ...['verb', 'lstinline'].map(csname => CSNAME(csname, {contains: [VERBATIM_DELIMITED_EQUAL()]})),
    -    CSNAME('mint', ARGUMENT_AND_THEN(ARGUMENT_M, {contains: [VERBATIM_DELIMITED_EQUAL()]})),
    -    CSNAME('mintinline', ARGUMENT_AND_THEN(ARGUMENT_M, {contains: [VERBATIM_DELIMITED_BRACES(), VERBATIM_DELIMITED_EQUAL()]})),
    -    CSNAME('url', {contains: [VERBATIM_DELIMITED_BRACES("link"), VERBATIM_DELIMITED_BRACES("link")]}),
    -    CSNAME('hyperref', {contains: [VERBATIM_DELIMITED_BRACES("link")]}),
    -    CSNAME('href', ARGUMENT_AND_THEN(ARGUMENT_O, {contains: [VERBATIM_DELIMITED_BRACES("link")]})),
    -    ...[].concat(...['', '\\*'].map(suffix => [
    -      BEGIN_ENV('verbatim' + suffix, VERBATIM_DELIMITED_ENV('verbatim' + suffix)),
    -      BEGIN_ENV('filecontents' + suffix,  ARGUMENT_AND_THEN(ARGUMENT_M, VERBATIM_DELIMITED_ENV('filecontents' + suffix))),
    -      ...['', 'B', 'L'].map(prefix =>
    -        BEGIN_ENV(prefix + 'Verbatim' + suffix, ARGUMENT_AND_THEN(ARGUMENT_O, VERBATIM_DELIMITED_ENV(prefix + 'Verbatim' + suffix)))
    -      )
    -    ])),
    -    BEGIN_ENV('minted', ARGUMENT_AND_THEN(ARGUMENT_O, ARGUMENT_AND_THEN(ARGUMENT_M, VERBATIM_DELIMITED_ENV('minted')))),
    -  ];
    -
    -  return {
    -    name: 'LaTeX',
    -    aliases: ['tex'],
    -    contains: [
    -      ...VERBATIM,
    -      ...EVERYTHING_BUT_VERBATIM
    -    ]
    -  };
    -}
    -
    -module.exports = latex;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/ldif.js b/claude-code-source/node_modules/highlight.js/lib/languages/ldif.js
    deleted file mode 100644
    index 3b8d37b6..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/ldif.js
    +++ /dev/null
    @@ -1,42 +0,0 @@
    -/*
    -Language: LDIF
    -Contributors: Jacob Childress 
    -Category: enterprise, config
    -Website: https://en.wikipedia.org/wiki/LDAP_Data_Interchange_Format
    -*/
    -function ldif(hljs) {
    -  return {
    -    name: 'LDIF',
    -    contains: [
    -      {
    -        className: 'attribute',
    -        begin: '^dn',
    -        end: ': ',
    -        excludeEnd: true,
    -        starts: {
    -          end: '$',
    -          relevance: 0
    -        },
    -        relevance: 10
    -      },
    -      {
    -        className: 'attribute',
    -        begin: '^\\w',
    -        end: ': ',
    -        excludeEnd: true,
    -        starts: {
    -          end: '$',
    -          relevance: 0
    -        }
    -      },
    -      {
    -        className: 'literal',
    -        begin: '^-',
    -        end: '$'
    -      },
    -      hljs.HASH_COMMENT_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = ldif;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/leaf.js b/claude-code-source/node_modules/highlight.js/lib/languages/leaf.js
    deleted file mode 100644
    index e0ec10d2..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/leaf.js
    +++ /dev/null
    @@ -1,49 +0,0 @@
    -/*
    -Language: Leaf
    -Author: Hale Chan 
    -Description: Based on the Leaf reference from https://vapor.github.io/documentation/guide/leaf.html.
    -*/
    -
    -function leaf(hljs) {
    -  return {
    -    name: 'Leaf',
    -    contains: [
    -      {
    -        className: 'function',
    -        begin: '#+' + '[A-Za-z_0-9]*' + '\\(',
    -        end: / \{/,
    -        returnBegin: true,
    -        excludeEnd: true,
    -        contains: [
    -          {
    -            className: 'keyword',
    -            begin: '#+'
    -          },
    -          {
    -            className: 'title',
    -            begin: '[A-Za-z_][A-Za-z_0-9]*'
    -          },
    -          {
    -            className: 'params',
    -            begin: '\\(',
    -            end: '\\)',
    -            endsParent: true,
    -            contains: [
    -              {
    -                className: 'string',
    -                begin: '"',
    -                end: '"'
    -              },
    -              {
    -                className: 'variable',
    -                begin: '[A-Za-z_][A-Za-z_0-9]*'
    -              }
    -            ]
    -          }
    -        ]
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = leaf;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/less.js b/claude-code-source/node_modules/highlight.js/lib/languages/less.js
    deleted file mode 100644
    index d228acba..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/less.js
    +++ /dev/null
    @@ -1,666 +0,0 @@
    -const MODES = (hljs) => {
    -  return {
    -    IMPORTANT: {
    -      className: 'meta',
    -      begin: '!important'
    -    },
    -    HEXCOLOR: {
    -      className: 'number',
    -      begin: '#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})'
    -    },
    -    ATTRIBUTE_SELECTOR_MODE: {
    -      className: 'selector-attr',
    -      begin: /\[/,
    -      end: /\]/,
    -      illegal: '$',
    -      contains: [
    -        hljs.APOS_STRING_MODE,
    -        hljs.QUOTE_STRING_MODE
    -      ]
    -    }
    -  };
    -};
    -
    -const TAGS = [
    -  'a',
    -  'abbr',
    -  'address',
    -  'article',
    -  'aside',
    -  'audio',
    -  'b',
    -  'blockquote',
    -  'body',
    -  'button',
    -  'canvas',
    -  'caption',
    -  'cite',
    -  'code',
    -  'dd',
    -  'del',
    -  'details',
    -  'dfn',
    -  'div',
    -  'dl',
    -  'dt',
    -  'em',
    -  'fieldset',
    -  'figcaption',
    -  'figure',
    -  'footer',
    -  'form',
    -  'h1',
    -  'h2',
    -  'h3',
    -  'h4',
    -  'h5',
    -  'h6',
    -  'header',
    -  'hgroup',
    -  'html',
    -  'i',
    -  'iframe',
    -  'img',
    -  'input',
    -  'ins',
    -  'kbd',
    -  'label',
    -  'legend',
    -  'li',
    -  'main',
    -  'mark',
    -  'menu',
    -  'nav',
    -  'object',
    -  'ol',
    -  'p',
    -  'q',
    -  'quote',
    -  'samp',
    -  'section',
    -  'span',
    -  'strong',
    -  'summary',
    -  'sup',
    -  'table',
    -  'tbody',
    -  'td',
    -  'textarea',
    -  'tfoot',
    -  'th',
    -  'thead',
    -  'time',
    -  'tr',
    -  'ul',
    -  'var',
    -  'video'
    -];
    -
    -const MEDIA_FEATURES = [
    -  'any-hover',
    -  'any-pointer',
    -  'aspect-ratio',
    -  'color',
    -  'color-gamut',
    -  'color-index',
    -  'device-aspect-ratio',
    -  'device-height',
    -  'device-width',
    -  'display-mode',
    -  'forced-colors',
    -  'grid',
    -  'height',
    -  'hover',
    -  'inverted-colors',
    -  'monochrome',
    -  'orientation',
    -  'overflow-block',
    -  'overflow-inline',
    -  'pointer',
    -  'prefers-color-scheme',
    -  'prefers-contrast',
    -  'prefers-reduced-motion',
    -  'prefers-reduced-transparency',
    -  'resolution',
    -  'scan',
    -  'scripting',
    -  'update',
    -  'width',
    -  // TODO: find a better solution?
    -  'min-width',
    -  'max-width',
    -  'min-height',
    -  'max-height'
    -];
    -
    -// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes
    -const PSEUDO_CLASSES = [
    -  'active',
    -  'any-link',
    -  'blank',
    -  'checked',
    -  'current',
    -  'default',
    -  'defined',
    -  'dir', // dir()
    -  'disabled',
    -  'drop',
    -  'empty',
    -  'enabled',
    -  'first',
    -  'first-child',
    -  'first-of-type',
    -  'fullscreen',
    -  'future',
    -  'focus',
    -  'focus-visible',
    -  'focus-within',
    -  'has', // has()
    -  'host', // host or host()
    -  'host-context', // host-context()
    -  'hover',
    -  'indeterminate',
    -  'in-range',
    -  'invalid',
    -  'is', // is()
    -  'lang', // lang()
    -  'last-child',
    -  'last-of-type',
    -  'left',
    -  'link',
    -  'local-link',
    -  'not', // not()
    -  'nth-child', // nth-child()
    -  'nth-col', // nth-col()
    -  'nth-last-child', // nth-last-child()
    -  'nth-last-col', // nth-last-col()
    -  'nth-last-of-type', //nth-last-of-type()
    -  'nth-of-type', //nth-of-type()
    -  'only-child',
    -  'only-of-type',
    -  'optional',
    -  'out-of-range',
    -  'past',
    -  'placeholder-shown',
    -  'read-only',
    -  'read-write',
    -  'required',
    -  'right',
    -  'root',
    -  'scope',
    -  'target',
    -  'target-within',
    -  'user-invalid',
    -  'valid',
    -  'visited',
    -  'where' // where()
    -];
    -
    -// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements
    -const PSEUDO_ELEMENTS = [
    -  'after',
    -  'backdrop',
    -  'before',
    -  'cue',
    -  'cue-region',
    -  'first-letter',
    -  'first-line',
    -  'grammar-error',
    -  'marker',
    -  'part',
    -  'placeholder',
    -  'selection',
    -  'slotted',
    -  'spelling-error'
    -];
    -
    -const ATTRIBUTES = [
    -  'align-content',
    -  'align-items',
    -  'align-self',
    -  'animation',
    -  'animation-delay',
    -  'animation-direction',
    -  'animation-duration',
    -  'animation-fill-mode',
    -  'animation-iteration-count',
    -  'animation-name',
    -  'animation-play-state',
    -  'animation-timing-function',
    -  'auto',
    -  'backface-visibility',
    -  'background',
    -  'background-attachment',
    -  'background-clip',
    -  'background-color',
    -  'background-image',
    -  'background-origin',
    -  'background-position',
    -  'background-repeat',
    -  'background-size',
    -  'border',
    -  'border-bottom',
    -  'border-bottom-color',
    -  'border-bottom-left-radius',
    -  'border-bottom-right-radius',
    -  'border-bottom-style',
    -  'border-bottom-width',
    -  'border-collapse',
    -  'border-color',
    -  'border-image',
    -  'border-image-outset',
    -  'border-image-repeat',
    -  'border-image-slice',
    -  'border-image-source',
    -  'border-image-width',
    -  'border-left',
    -  'border-left-color',
    -  'border-left-style',
    -  'border-left-width',
    -  'border-radius',
    -  'border-right',
    -  'border-right-color',
    -  'border-right-style',
    -  'border-right-width',
    -  'border-spacing',
    -  'border-style',
    -  'border-top',
    -  'border-top-color',
    -  'border-top-left-radius',
    -  'border-top-right-radius',
    -  'border-top-style',
    -  'border-top-width',
    -  'border-width',
    -  'bottom',
    -  'box-decoration-break',
    -  'box-shadow',
    -  'box-sizing',
    -  'break-after',
    -  'break-before',
    -  'break-inside',
    -  'caption-side',
    -  'clear',
    -  'clip',
    -  'clip-path',
    -  'color',
    -  'column-count',
    -  'column-fill',
    -  'column-gap',
    -  'column-rule',
    -  'column-rule-color',
    -  'column-rule-style',
    -  'column-rule-width',
    -  'column-span',
    -  'column-width',
    -  'columns',
    -  'content',
    -  'counter-increment',
    -  'counter-reset',
    -  'cursor',
    -  'direction',
    -  'display',
    -  'empty-cells',
    -  'filter',
    -  'flex',
    -  'flex-basis',
    -  'flex-direction',
    -  'flex-flow',
    -  'flex-grow',
    -  'flex-shrink',
    -  'flex-wrap',
    -  'float',
    -  'font',
    -  'font-display',
    -  'font-family',
    -  'font-feature-settings',
    -  'font-kerning',
    -  'font-language-override',
    -  'font-size',
    -  'font-size-adjust',
    -  'font-smoothing',
    -  'font-stretch',
    -  'font-style',
    -  'font-variant',
    -  'font-variant-ligatures',
    -  'font-variation-settings',
    -  'font-weight',
    -  'height',
    -  'hyphens',
    -  'icon',
    -  'image-orientation',
    -  'image-rendering',
    -  'image-resolution',
    -  'ime-mode',
    -  'inherit',
    -  'initial',
    -  'justify-content',
    -  'left',
    -  'letter-spacing',
    -  'line-height',
    -  'list-style',
    -  'list-style-image',
    -  'list-style-position',
    -  'list-style-type',
    -  'margin',
    -  'margin-bottom',
    -  'margin-left',
    -  'margin-right',
    -  'margin-top',
    -  'marks',
    -  'mask',
    -  'max-height',
    -  'max-width',
    -  'min-height',
    -  'min-width',
    -  'nav-down',
    -  'nav-index',
    -  'nav-left',
    -  'nav-right',
    -  'nav-up',
    -  'none',
    -  'normal',
    -  'object-fit',
    -  'object-position',
    -  'opacity',
    -  'order',
    -  'orphans',
    -  'outline',
    -  'outline-color',
    -  'outline-offset',
    -  'outline-style',
    -  'outline-width',
    -  'overflow',
    -  'overflow-wrap',
    -  'overflow-x',
    -  'overflow-y',
    -  'padding',
    -  'padding-bottom',
    -  'padding-left',
    -  'padding-right',
    -  'padding-top',
    -  'page-break-after',
    -  'page-break-before',
    -  'page-break-inside',
    -  'perspective',
    -  'perspective-origin',
    -  'pointer-events',
    -  'position',
    -  'quotes',
    -  'resize',
    -  'right',
    -  'src', // @font-face
    -  'tab-size',
    -  'table-layout',
    -  'text-align',
    -  'text-align-last',
    -  'text-decoration',
    -  'text-decoration-color',
    -  'text-decoration-line',
    -  'text-decoration-style',
    -  'text-indent',
    -  'text-overflow',
    -  'text-rendering',
    -  'text-shadow',
    -  'text-transform',
    -  'text-underline-position',
    -  'top',
    -  'transform',
    -  'transform-origin',
    -  'transform-style',
    -  'transition',
    -  'transition-delay',
    -  'transition-duration',
    -  'transition-property',
    -  'transition-timing-function',
    -  'unicode-bidi',
    -  'vertical-align',
    -  'visibility',
    -  'white-space',
    -  'widows',
    -  'width',
    -  'word-break',
    -  'word-spacing',
    -  'word-wrap',
    -  'z-index'
    -  // reverse makes sure longer attributes `font-weight` are matched fully
    -  // instead of getting false positives on say `font`
    -].reverse();
    -
    -// some grammars use them all as a single group
    -const PSEUDO_SELECTORS = PSEUDO_CLASSES.concat(PSEUDO_ELEMENTS);
    -
    -/*
    -Language: Less
    -Description: It's CSS, with just a little more.
    -Author:   Max Mikhailov 
    -Website: http://lesscss.org
    -Category: common, css
    -*/
    -
    -/** @type LanguageFn */
    -function less(hljs) {
    -  const modes = MODES(hljs);
    -  const PSEUDO_SELECTORS$1 = PSEUDO_SELECTORS;
    -
    -  const AT_MODIFIERS = "and or not only";
    -  const IDENT_RE = '[\\w-]+'; // yes, Less identifiers may begin with a digit
    -  const INTERP_IDENT_RE = '(' + IDENT_RE + '|@\\{' + IDENT_RE + '\\})';
    -
    -  /* Generic Modes */
    -
    -  const RULES = []; const VALUE_MODES = []; // forward def. for recursive modes
    -
    -  const STRING_MODE = function(c) {
    -    return {
    -    // Less strings are not multiline (also include '~' for more consistent coloring of "escaped" strings)
    -      className: 'string',
    -      begin: '~?' + c + '.*?' + c
    -    };
    -  };
    -
    -  const IDENT_MODE = function(name, begin, relevance) {
    -    return {
    -      className: name,
    -      begin: begin,
    -      relevance: relevance
    -    };
    -  };
    -
    -  const AT_KEYWORDS = {
    -    $pattern: /[a-z-]+/,
    -    keyword: AT_MODIFIERS,
    -    attribute: MEDIA_FEATURES.join(" ")
    -  };
    -
    -  const PARENS_MODE = {
    -    // used only to properly balance nested parens inside mixin call, def. arg list
    -    begin: '\\(',
    -    end: '\\)',
    -    contains: VALUE_MODES,
    -    keywords: AT_KEYWORDS,
    -    relevance: 0
    -  };
    -
    -  // generic Less highlighter (used almost everywhere except selectors):
    -  VALUE_MODES.push(
    -    hljs.C_LINE_COMMENT_MODE,
    -    hljs.C_BLOCK_COMMENT_MODE,
    -    STRING_MODE("'"),
    -    STRING_MODE('"'),
    -    hljs.CSS_NUMBER_MODE, // fixme: it does not include dot for numbers like .5em :(
    -    {
    -      begin: '(url|data-uri)\\(',
    -      starts: {
    -        className: 'string',
    -        end: '[\\)\\n]',
    -        excludeEnd: true
    -      }
    -    },
    -    modes.HEXCOLOR,
    -    PARENS_MODE,
    -    IDENT_MODE('variable', '@@?' + IDENT_RE, 10),
    -    IDENT_MODE('variable', '@\\{' + IDENT_RE + '\\}'),
    -    IDENT_MODE('built_in', '~?`[^`]*?`'), // inline javascript (or whatever host language) *multiline* string
    -    { // @media features (it’s here to not duplicate things in AT_RULE_MODE with extra PARENS_MODE overriding):
    -      className: 'attribute',
    -      begin: IDENT_RE + '\\s*:',
    -      end: ':',
    -      returnBegin: true,
    -      excludeEnd: true
    -    },
    -    modes.IMPORTANT
    -  );
    -
    -  const VALUE_WITH_RULESETS = VALUE_MODES.concat({
    -    begin: /\{/,
    -    end: /\}/,
    -    contains: RULES
    -  });
    -
    -  const MIXIN_GUARD_MODE = {
    -    beginKeywords: 'when',
    -    endsWithParent: true,
    -    contains: [
    -      {
    -        beginKeywords: 'and not'
    -      }
    -    ].concat(VALUE_MODES) // using this form to override VALUE’s 'function' match
    -  };
    -
    -  /* Rule-Level Modes */
    -
    -  const RULE_MODE = {
    -    begin: INTERP_IDENT_RE + '\\s*:',
    -    returnBegin: true,
    -    end: /[;}]/,
    -    relevance: 0,
    -    contains: [
    -      {
    -        begin: /-(webkit|moz|ms|o)-/
    -      },
    -      {
    -        className: 'attribute',
    -        begin: '\\b(' + ATTRIBUTES.join('|') + ')\\b',
    -        end: /(?=:)/,
    -        starts: {
    -          endsWithParent: true,
    -          illegal: '[<=$]',
    -          relevance: 0,
    -          contains: VALUE_MODES
    -        }
    -      }
    -    ]
    -  };
    -
    -  const AT_RULE_MODE = {
    -    className: 'keyword',
    -    begin: '@(import|media|charset|font-face|(-[a-z]+-)?keyframes|supports|document|namespace|page|viewport|host)\\b',
    -    starts: {
    -      end: '[;{}]',
    -      keywords: AT_KEYWORDS,
    -      returnEnd: true,
    -      contains: VALUE_MODES,
    -      relevance: 0
    -    }
    -  };
    -
    -  // variable definitions and calls
    -  const VAR_RULE_MODE = {
    -    className: 'variable',
    -    variants: [
    -      // using more strict pattern for higher relevance to increase chances of Less detection.
    -      // this is *the only* Less specific statement used in most of the sources, so...
    -      // (we’ll still often loose to the css-parser unless there's '//' comment,
    -      // simply because 1 variable just can't beat 99 properties :)
    -      {
    -        begin: '@' + IDENT_RE + '\\s*:',
    -        relevance: 15
    -      },
    -      {
    -        begin: '@' + IDENT_RE
    -      }
    -    ],
    -    starts: {
    -      end: '[;}]',
    -      returnEnd: true,
    -      contains: VALUE_WITH_RULESETS
    -    }
    -  };
    -
    -  const SELECTOR_MODE = {
    -    // first parse unambiguous selectors (i.e. those not starting with tag)
    -    // then fall into the scary lookahead-discriminator variant.
    -    // this mode also handles mixin definitions and calls
    -    variants: [
    -      {
    -        begin: '[\\.#:&\\[>]',
    -        end: '[;{}]' // mixin calls end with ';'
    -      },
    -      {
    -        begin: INTERP_IDENT_RE,
    -        end: /\{/
    -      }
    -    ],
    -    returnBegin: true,
    -    returnEnd: true,
    -    illegal: '[<=\'$"]',
    -    relevance: 0,
    -    contains: [
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      MIXIN_GUARD_MODE,
    -      IDENT_MODE('keyword', 'all\\b'),
    -      IDENT_MODE('variable', '@\\{' + IDENT_RE + '\\}'), // otherwise it’s identified as tag
    -      {
    -        begin: '\\b(' + TAGS.join('|') + ')\\b',
    -        className: 'selector-tag'
    -      },
    -      IDENT_MODE('selector-tag', INTERP_IDENT_RE + '%?', 0), // '%' for more consistent coloring of @keyframes "tags"
    -      IDENT_MODE('selector-id', '#' + INTERP_IDENT_RE),
    -      IDENT_MODE('selector-class', '\\.' + INTERP_IDENT_RE, 0),
    -      IDENT_MODE('selector-tag', '&', 0),
    -      modes.ATTRIBUTE_SELECTOR_MODE,
    -      {
    -        className: 'selector-pseudo',
    -        begin: ':(' + PSEUDO_CLASSES.join('|') + ')'
    -      },
    -      {
    -        className: 'selector-pseudo',
    -        begin: '::(' + PSEUDO_ELEMENTS.join('|') + ')'
    -      },
    -      {
    -        begin: '\\(',
    -        end: '\\)',
    -        contains: VALUE_WITH_RULESETS
    -      }, // argument list of parametric mixins
    -      {
    -        begin: '!important'
    -      } // eat !important after mixin call or it will be colored as tag
    -    ]
    -  };
    -
    -  const PSEUDO_SELECTOR_MODE = {
    -    begin: IDENT_RE + ':(:)?' + `(${PSEUDO_SELECTORS$1.join('|')})`,
    -    returnBegin: true,
    -    contains: [ SELECTOR_MODE ]
    -  };
    -
    -  RULES.push(
    -    hljs.C_LINE_COMMENT_MODE,
    -    hljs.C_BLOCK_COMMENT_MODE,
    -    AT_RULE_MODE,
    -    VAR_RULE_MODE,
    -    PSEUDO_SELECTOR_MODE,
    -    RULE_MODE,
    -    SELECTOR_MODE
    -  );
    -
    -  return {
    -    name: 'Less',
    -    case_insensitive: true,
    -    illegal: '[=>\'/<($"]',
    -    contains: RULES
    -  };
    -}
    -
    -module.exports = less;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/lisp.js b/claude-code-source/node_modules/highlight.js/lib/languages/lisp.js
    deleted file mode 100644
    index 4c84d8f0..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/lisp.js
    +++ /dev/null
    @@ -1,111 +0,0 @@
    -/*
    -Language: Lisp
    -Description: Generic lisp syntax
    -Author: Vasily Polovnyov 
    -Category: lisp
    -*/
    -
    -function lisp(hljs) {
    -  var LISP_IDENT_RE = '[a-zA-Z_\\-+\\*\\/<=>&#][a-zA-Z0-9_\\-+*\\/<=>&#!]*';
    -  var MEC_RE = '\\|[^]*?\\|';
    -  var LISP_SIMPLE_NUMBER_RE = '(-|\\+)?\\d+(\\.\\d+|\\/\\d+)?((d|e|f|l|s|D|E|F|L|S)(\\+|-)?\\d+)?';
    -  var LITERAL = {
    -    className: 'literal',
    -    begin: '\\b(t{1}|nil)\\b'
    -  };
    -  var NUMBER = {
    -    className: 'number',
    -    variants: [
    -      {begin: LISP_SIMPLE_NUMBER_RE, relevance: 0},
    -      {begin: '#(b|B)[0-1]+(/[0-1]+)?'},
    -      {begin: '#(o|O)[0-7]+(/[0-7]+)?'},
    -      {begin: '#(x|X)[0-9a-fA-F]+(/[0-9a-fA-F]+)?'},
    -      {begin: '#(c|C)\\(' + LISP_SIMPLE_NUMBER_RE + ' +' + LISP_SIMPLE_NUMBER_RE, end: '\\)'}
    -    ]
    -  };
    -  var STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null});
    -  var COMMENT = hljs.COMMENT(
    -    ';', '$',
    -    {
    -      relevance: 0
    -    }
    -  );
    -  var VARIABLE = {
    -    begin: '\\*', end: '\\*'
    -  };
    -  var KEYWORD = {
    -    className: 'symbol',
    -    begin: '[:&]' + LISP_IDENT_RE
    -  };
    -  var IDENT = {
    -    begin: LISP_IDENT_RE,
    -    relevance: 0
    -  };
    -  var MEC = {
    -    begin: MEC_RE
    -  };
    -  var QUOTED_LIST = {
    -    begin: '\\(', end: '\\)',
    -    contains: ['self', LITERAL, STRING, NUMBER, IDENT]
    -  };
    -  var QUOTED = {
    -    contains: [NUMBER, STRING, VARIABLE, KEYWORD, QUOTED_LIST, IDENT],
    -    variants: [
    -      {
    -        begin: '[\'`]\\(', end: '\\)'
    -      },
    -      {
    -        begin: '\\(quote ', end: '\\)',
    -        keywords: {name: 'quote'}
    -      },
    -      {
    -        begin: '\'' + MEC_RE
    -      }
    -    ]
    -  };
    -  var QUOTED_ATOM = {
    -    variants: [
    -      {begin: '\'' + LISP_IDENT_RE},
    -      {begin: '#\'' + LISP_IDENT_RE + '(::' + LISP_IDENT_RE + ')*'}
    -    ]
    -  };
    -  var LIST = {
    -    begin: '\\(\\s*', end: '\\)'
    -  };
    -  var BODY = {
    -    endsWithParent: true,
    -    relevance: 0
    -  };
    -  LIST.contains = [
    -    {
    -      className: 'name',
    -      variants: [
    -        {
    -          begin: LISP_IDENT_RE,
    -          relevance: 0,
    -        },
    -        {begin: MEC_RE}
    -      ]
    -    },
    -    BODY
    -  ];
    -  BODY.contains = [QUOTED, QUOTED_ATOM, LIST, LITERAL, NUMBER, STRING, COMMENT, VARIABLE, KEYWORD, MEC, IDENT];
    -
    -  return {
    -    name: 'Lisp',
    -    illegal: /\S/,
    -    contains: [
    -      NUMBER,
    -      hljs.SHEBANG(),
    -      LITERAL,
    -      STRING,
    -      COMMENT,
    -      QUOTED,
    -      QUOTED_ATOM,
    -      LIST,
    -      IDENT
    -    ]
    -  };
    -}
    -
    -module.exports = lisp;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/livecodeserver.js b/claude-code-source/node_modules/highlight.js/lib/languages/livecodeserver.js
    deleted file mode 100644
    index b78c9b14..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/livecodeserver.js
    +++ /dev/null
    @@ -1,189 +0,0 @@
    -/*
    -Language: LiveCode
    -Author: Ralf Bitter 
    -Description: Language definition for LiveCode server accounting for revIgniter (a web application framework) characteristics.
    -Version: 1.1
    -Date: 2019-04-17
    -Category: enterprise
    -*/
    -
    -function livecodeserver(hljs) {
    -  const VARIABLE = {
    -    className: 'variable',
    -    variants: [
    -      {
    -        begin: '\\b([gtps][A-Z]{1}[a-zA-Z0-9]*)(\\[.+\\])?(?:\\s*?)'
    -      },
    -      {
    -        begin: '\\$_[A-Z]+'
    -      }
    -    ],
    -    relevance: 0
    -  };
    -  const COMMENT_MODES = [
    -    hljs.C_BLOCK_COMMENT_MODE,
    -    hljs.HASH_COMMENT_MODE,
    -    hljs.COMMENT('--', '$'),
    -    hljs.COMMENT('[^:]//', '$')
    -  ];
    -  const TITLE1 = hljs.inherit(hljs.TITLE_MODE, {
    -    variants: [
    -      {
    -        begin: '\\b_*rig[A-Z][A-Za-z0-9_\\-]*'
    -      },
    -      {
    -        begin: '\\b_[a-z0-9\\-]+'
    -      }
    -    ]
    -  });
    -  const TITLE2 = hljs.inherit(hljs.TITLE_MODE, {
    -    begin: '\\b([A-Za-z0-9_\\-]+)\\b'
    -  });
    -  return {
    -    name: 'LiveCode',
    -    case_insensitive: false,
    -    keywords: {
    -      keyword:
    -        '$_COOKIE $_FILES $_GET $_GET_BINARY $_GET_RAW $_POST $_POST_BINARY $_POST_RAW $_SESSION $_SERVER ' +
    -        'codepoint codepoints segment segments codeunit codeunits sentence sentences trueWord trueWords paragraph ' +
    -        'after byte bytes english the until http forever descending using line real8 with seventh ' +
    -        'for stdout finally element word words fourth before black ninth sixth characters chars stderr ' +
    -        'uInt1 uInt1s uInt2 uInt2s stdin string lines relative rel any fifth items from middle mid ' +
    -        'at else of catch then third it file milliseconds seconds second secs sec int1 int1s int4 ' +
    -        'int4s internet int2 int2s normal text item last long detailed effective uInt4 uInt4s repeat ' +
    -        'end repeat URL in try into switch to words https token binfile each tenth as ticks tick ' +
    -        'system real4 by dateItems without char character ascending eighth whole dateTime numeric short ' +
    -        'first ftp integer abbreviated abbr abbrev private case while if ' +
    -        'div mod wrap and or bitAnd bitNot bitOr bitXor among not in a an within ' +
    -        'contains ends with begins the keys of keys',
    -      literal:
    -        'SIX TEN FORMFEED NINE ZERO NONE SPACE FOUR FALSE COLON CRLF PI COMMA ENDOFFILE EOF EIGHT FIVE ' +
    -        'QUOTE EMPTY ONE TRUE RETURN CR LINEFEED RIGHT BACKSLASH NULL SEVEN TAB THREE TWO ' +
    -        'six ten formfeed nine zero none space four false colon crlf pi comma endoffile eof eight five ' +
    -        'quote empty one true return cr linefeed right backslash null seven tab three two ' +
    -        'RIVERSION RISTATE FILE_READ_MODE FILE_WRITE_MODE FILE_WRITE_MODE DIR_WRITE_MODE FILE_READ_UMASK ' +
    -        'FILE_WRITE_UMASK DIR_READ_UMASK DIR_WRITE_UMASK',
    -      built_in:
    -        'put abs acos aliasReference annuity arrayDecode arrayEncode asin atan atan2 average avg avgDev base64Decode ' +
    -        'base64Encode baseConvert binaryDecode binaryEncode byteOffset byteToNum cachedURL cachedURLs charToNum ' +
    -        'cipherNames codepointOffset codepointProperty codepointToNum codeunitOffset commandNames compound compress ' +
    -        'constantNames cos date dateFormat decompress difference directories ' +
    -        'diskSpace DNSServers exp exp1 exp2 exp10 extents files flushEvents folders format functionNames geometricMean global ' +
    -        'globals hasMemory harmonicMean hostAddress hostAddressToName hostName hostNameToAddress isNumber ISOToMac itemOffset ' +
    -        'keys len length libURLErrorData libUrlFormData libURLftpCommand libURLLastHTTPHeaders libURLLastRHHeaders ' +
    -        'libUrlMultipartFormAddPart libUrlMultipartFormData libURLVersion lineOffset ln ln1 localNames log log2 log10 ' +
    -        'longFilePath lower macToISO matchChunk matchText matrixMultiply max md5Digest median merge messageAuthenticationCode messageDigest millisec ' +
    -        'millisecs millisecond milliseconds min monthNames nativeCharToNum normalizeText num number numToByte numToChar ' +
    -        'numToCodepoint numToNativeChar offset open openfiles openProcesses openProcessIDs openSockets ' +
    -        'paragraphOffset paramCount param params peerAddress pendingMessages platform popStdDev populationStandardDeviation ' +
    -        'populationVariance popVariance processID random randomBytes replaceText result revCreateXMLTree revCreateXMLTreeFromFile ' +
    -        'revCurrentRecord revCurrentRecordIsFirst revCurrentRecordIsLast revDatabaseColumnCount revDatabaseColumnIsNull ' +
    -        'revDatabaseColumnLengths revDatabaseColumnNames revDatabaseColumnNamed revDatabaseColumnNumbered ' +
    -        'revDatabaseColumnTypes revDatabaseConnectResult revDatabaseCursors revDatabaseID revDatabaseTableNames ' +
    -        'revDatabaseType revDataFromQuery revdb_closeCursor revdb_columnbynumber revdb_columncount revdb_columnisnull ' +
    -        'revdb_columnlengths revdb_columnnames revdb_columntypes revdb_commit revdb_connect revdb_connections ' +
    -        'revdb_connectionerr revdb_currentrecord revdb_cursorconnection revdb_cursorerr revdb_cursors revdb_dbtype ' +
    -        'revdb_disconnect revdb_execute revdb_iseof revdb_isbof revdb_movefirst revdb_movelast revdb_movenext ' +
    -        'revdb_moveprev revdb_query revdb_querylist revdb_recordcount revdb_rollback revdb_tablenames ' +
    -        'revGetDatabaseDriverPath revNumberOfRecords revOpenDatabase revOpenDatabases revQueryDatabase ' +
    -        'revQueryDatabaseBlob revQueryResult revQueryIsAtStart revQueryIsAtEnd revUnixFromMacPath revXMLAttribute ' +
    -        'revXMLAttributes revXMLAttributeValues revXMLChildContents revXMLChildNames revXMLCreateTreeFromFileWithNamespaces ' +
    -        'revXMLCreateTreeWithNamespaces revXMLDataFromXPathQuery revXMLEvaluateXPath revXMLFirstChild revXMLMatchingNode ' +
    -        'revXMLNextSibling revXMLNodeContents revXMLNumberOfChildren revXMLParent revXMLPreviousSibling ' +
    -        'revXMLRootNode revXMLRPC_CreateRequest revXMLRPC_Documents revXMLRPC_Error ' +
    -        'revXMLRPC_GetHost revXMLRPC_GetMethod revXMLRPC_GetParam revXMLText revXMLRPC_Execute ' +
    -        'revXMLRPC_GetParamCount revXMLRPC_GetParamNode revXMLRPC_GetParamType revXMLRPC_GetPath revXMLRPC_GetPort ' +
    -        'revXMLRPC_GetProtocol revXMLRPC_GetRequest revXMLRPC_GetResponse revXMLRPC_GetSocket revXMLTree ' +
    -        'revXMLTrees revXMLValidateDTD revZipDescribeItem revZipEnumerateItems revZipOpenArchives round sampVariance ' +
    -        'sec secs seconds sentenceOffset sha1Digest shell shortFilePath sin specialFolderPath sqrt standardDeviation statRound ' +
    -        'stdDev sum sysError systemVersion tan tempName textDecode textEncode tick ticks time to tokenOffset toLower toUpper ' +
    -        'transpose truewordOffset trunc uniDecode uniEncode upper URLDecode URLEncode URLStatus uuid value variableNames ' +
    -        'variance version waitDepth weekdayNames wordOffset xsltApplyStylesheet xsltApplyStylesheetFromFile xsltLoadStylesheet ' +
    -        'xsltLoadStylesheetFromFile add breakpoint cancel clear local variable file word line folder directory URL close socket process ' +
    -        'combine constant convert create new alias folder directory decrypt delete variable word line folder ' +
    -        'directory URL dispatch divide do encrypt filter get include intersect kill libURLDownloadToFile ' +
    -        'libURLFollowHttpRedirects libURLftpUpload libURLftpUploadFile libURLresetAll libUrlSetAuthCallback libURLSetDriver ' +
    -        'libURLSetCustomHTTPHeaders libUrlSetExpect100 libURLSetFTPListCommand libURLSetFTPMode libURLSetFTPStopTime ' +
    -        'libURLSetStatusCallback load extension loadedExtensions multiply socket prepare process post seek rel relative read from process rename ' +
    -        'replace require resetAll resolve revAddXMLNode revAppendXML revCloseCursor revCloseDatabase revCommitDatabase ' +
    -        'revCopyFile revCopyFolder revCopyXMLNode revDeleteFolder revDeleteXMLNode revDeleteAllXMLTrees ' +
    -        'revDeleteXMLTree revExecuteSQL revGoURL revInsertXMLNode revMoveFolder revMoveToFirstRecord revMoveToLastRecord ' +
    -        'revMoveToNextRecord revMoveToPreviousRecord revMoveToRecord revMoveXMLNode revPutIntoXMLNode revRollBackDatabase ' +
    -        'revSetDatabaseDriverPath revSetXMLAttribute revXMLRPC_AddParam revXMLRPC_DeleteAllDocuments revXMLAddDTD ' +
    -        'revXMLRPC_Free revXMLRPC_FreeAll revXMLRPC_DeleteDocument revXMLRPC_DeleteParam revXMLRPC_SetHost ' +
    -        'revXMLRPC_SetMethod revXMLRPC_SetPort revXMLRPC_SetProtocol revXMLRPC_SetSocket revZipAddItemWithData ' +
    -        'revZipAddItemWithFile revZipAddUncompressedItemWithData revZipAddUncompressedItemWithFile revZipCancel ' +
    -        'revZipCloseArchive revZipDeleteItem revZipExtractItemToFile revZipExtractItemToVariable revZipSetProgressCallback ' +
    -        'revZipRenameItem revZipReplaceItemWithData revZipReplaceItemWithFile revZipOpenArchive send set sort split start stop ' +
    -        'subtract symmetric union unload vectorDotProduct wait write'
    -    },
    -    contains: [
    -      VARIABLE,
    -      {
    -        className: 'keyword',
    -        begin: '\\bend\\sif\\b'
    -      },
    -      {
    -        className: 'function',
    -        beginKeywords: 'function',
    -        end: '$',
    -        contains: [
    -          VARIABLE,
    -          TITLE2,
    -          hljs.APOS_STRING_MODE,
    -          hljs.QUOTE_STRING_MODE,
    -          hljs.BINARY_NUMBER_MODE,
    -          hljs.C_NUMBER_MODE,
    -          TITLE1
    -        ]
    -      },
    -      {
    -        className: 'function',
    -        begin: '\\bend\\s+',
    -        end: '$',
    -        keywords: 'end',
    -        contains: [
    -          TITLE2,
    -          TITLE1
    -        ],
    -        relevance: 0
    -      },
    -      {
    -        beginKeywords: 'command on',
    -        end: '$',
    -        contains: [
    -          VARIABLE,
    -          TITLE2,
    -          hljs.APOS_STRING_MODE,
    -          hljs.QUOTE_STRING_MODE,
    -          hljs.BINARY_NUMBER_MODE,
    -          hljs.C_NUMBER_MODE,
    -          TITLE1
    -        ]
    -      },
    -      {
    -        className: 'meta',
    -        variants: [
    -          {
    -            begin: '<\\?(rev|lc|livecode)',
    -            relevance: 10
    -          },
    -          {
    -            begin: '<\\?'
    -          },
    -          {
    -            begin: '\\?>'
    -          }
    -        ]
    -      },
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.BINARY_NUMBER_MODE,
    -      hljs.C_NUMBER_MODE,
    -      TITLE1
    -    ].concat(COMMENT_MODES),
    -    illegal: ';$|^\\[|^=|&|\\{'
    -  };
    -}
    -
    -module.exports = livecodeserver;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/livescript.js b/claude-code-source/node_modules/highlight.js/lib/languages/livescript.js
    deleted file mode 100644
    index b22cb9b4..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/livescript.js
    +++ /dev/null
    @@ -1,374 +0,0 @@
    -const KEYWORDS = [
    -  "as", // for exports
    -  "in",
    -  "of",
    -  "if",
    -  "for",
    -  "while",
    -  "finally",
    -  "var",
    -  "new",
    -  "function",
    -  "do",
    -  "return",
    -  "void",
    -  "else",
    -  "break",
    -  "catch",
    -  "instanceof",
    -  "with",
    -  "throw",
    -  "case",
    -  "default",
    -  "try",
    -  "switch",
    -  "continue",
    -  "typeof",
    -  "delete",
    -  "let",
    -  "yield",
    -  "const",
    -  "class",
    -  // JS handles these with a special rule
    -  // "get",
    -  // "set",
    -  "debugger",
    -  "async",
    -  "await",
    -  "static",
    -  "import",
    -  "from",
    -  "export",
    -  "extends"
    -];
    -const LITERALS = [
    -  "true",
    -  "false",
    -  "null",
    -  "undefined",
    -  "NaN",
    -  "Infinity"
    -];
    -
    -const TYPES = [
    -  "Intl",
    -  "DataView",
    -  "Number",
    -  "Math",
    -  "Date",
    -  "String",
    -  "RegExp",
    -  "Object",
    -  "Function",
    -  "Boolean",
    -  "Error",
    -  "Symbol",
    -  "Set",
    -  "Map",
    -  "WeakSet",
    -  "WeakMap",
    -  "Proxy",
    -  "Reflect",
    -  "JSON",
    -  "Promise",
    -  "Float64Array",
    -  "Int16Array",
    -  "Int32Array",
    -  "Int8Array",
    -  "Uint16Array",
    -  "Uint32Array",
    -  "Float32Array",
    -  "Array",
    -  "Uint8Array",
    -  "Uint8ClampedArray",
    -  "ArrayBuffer",
    -  "BigInt64Array",
    -  "BigUint64Array",
    -  "BigInt"
    -];
    -
    -const ERROR_TYPES = [
    -  "EvalError",
    -  "InternalError",
    -  "RangeError",
    -  "ReferenceError",
    -  "SyntaxError",
    -  "TypeError",
    -  "URIError"
    -];
    -
    -const BUILT_IN_GLOBALS = [
    -  "setInterval",
    -  "setTimeout",
    -  "clearInterval",
    -  "clearTimeout",
    -
    -  "require",
    -  "exports",
    -
    -  "eval",
    -  "isFinite",
    -  "isNaN",
    -  "parseFloat",
    -  "parseInt",
    -  "decodeURI",
    -  "decodeURIComponent",
    -  "encodeURI",
    -  "encodeURIComponent",
    -  "escape",
    -  "unescape"
    -];
    -
    -const BUILT_IN_VARIABLES = [
    -  "arguments",
    -  "this",
    -  "super",
    -  "console",
    -  "window",
    -  "document",
    -  "localStorage",
    -  "module",
    -  "global" // Node.js
    -];
    -
    -const BUILT_INS = [].concat(
    -  BUILT_IN_GLOBALS,
    -  BUILT_IN_VARIABLES,
    -  TYPES,
    -  ERROR_TYPES
    -);
    -
    -/*
    -Language: LiveScript
    -Author: Taneli Vatanen 
    -Contributors: Jen Evers-Corvina 
    -Origin: coffeescript.js
    -Description: LiveScript is a programming language that transcompiles to JavaScript. For info about language see http://livescript.net/
    -Website: https://livescript.net
    -Category: scripting
    -*/
    -
    -function livescript(hljs) {
    -  const LIVESCRIPT_BUILT_INS = [
    -    'npm',
    -    'print'
    -  ];
    -  const LIVESCRIPT_LITERALS = [
    -    'yes',
    -    'no',
    -    'on',
    -    'off',
    -    'it',
    -    'that',
    -    'void'
    -  ];
    -  const LIVESCRIPT_KEYWORDS = [
    -    'then',
    -    'unless',
    -    'until',
    -    'loop',
    -    'of',
    -    'by',
    -    'when',
    -    'and',
    -    'or',
    -    'is',
    -    'isnt',
    -    'not',
    -    'it',
    -    'that',
    -    'otherwise',
    -    'from',
    -    'to',
    -    'til',
    -    'fallthrough',
    -    'case',
    -    'enum',
    -    'native',
    -    'list',
    -    'map',
    -    '__hasProp',
    -    '__extends',
    -    '__slice',
    -    '__bind',
    -    '__indexOf'
    -  ];
    -  const KEYWORDS$1 = {
    -    keyword: KEYWORDS.concat(LIVESCRIPT_KEYWORDS),
    -    literal: LITERALS.concat(LIVESCRIPT_LITERALS),
    -    built_in: BUILT_INS.concat(LIVESCRIPT_BUILT_INS)
    -  };
    -  const JS_IDENT_RE = '[A-Za-z$_](?:-[0-9A-Za-z$_]|[0-9A-Za-z$_])*';
    -  const TITLE = hljs.inherit(hljs.TITLE_MODE, {
    -    begin: JS_IDENT_RE
    -  });
    -  const SUBST = {
    -    className: 'subst',
    -    begin: /#\{/,
    -    end: /\}/,
    -    keywords: KEYWORDS$1
    -  };
    -  const SUBST_SIMPLE = {
    -    className: 'subst',
    -    begin: /#[A-Za-z$_]/,
    -    end: /(?:-[0-9A-Za-z$_]|[0-9A-Za-z$_])*/,
    -    keywords: KEYWORDS$1
    -  };
    -  const EXPRESSIONS = [
    -    hljs.BINARY_NUMBER_MODE,
    -    {
    -      className: 'number',
    -      begin: '(\\b0[xX][a-fA-F0-9_]+)|(\\b\\d(\\d|_\\d)*(\\.(\\d(\\d|_\\d)*)?)?(_*[eE]([-+]\\d(_\\d|\\d)*)?)?[_a-z]*)',
    -      relevance: 0,
    -      starts: {
    -        end: '(\\s*/)?',
    -        relevance: 0
    -      } // a number tries to eat the following slash to prevent treating it as a regexp
    -    },
    -    {
    -      className: 'string',
    -      variants: [
    -        {
    -          begin: /'''/,
    -          end: /'''/,
    -          contains: [hljs.BACKSLASH_ESCAPE]
    -        },
    -        {
    -          begin: /'/,
    -          end: /'/,
    -          contains: [hljs.BACKSLASH_ESCAPE]
    -        },
    -        {
    -          begin: /"""/,
    -          end: /"""/,
    -          contains: [
    -            hljs.BACKSLASH_ESCAPE,
    -            SUBST,
    -            SUBST_SIMPLE
    -          ]
    -        },
    -        {
    -          begin: /"/,
    -          end: /"/,
    -          contains: [
    -            hljs.BACKSLASH_ESCAPE,
    -            SUBST,
    -            SUBST_SIMPLE
    -          ]
    -        },
    -        {
    -          begin: /\\/,
    -          end: /(\s|$)/,
    -          excludeEnd: true
    -        }
    -      ]
    -    },
    -    {
    -      className: 'regexp',
    -      variants: [
    -        {
    -          begin: '//',
    -          end: '//[gim]*',
    -          contains: [
    -            SUBST,
    -            hljs.HASH_COMMENT_MODE
    -          ]
    -        },
    -        {
    -          // regex can't start with space to parse x / 2 / 3 as two divisions
    -          // regex can't start with *, and it supports an "illegal" in the main mode
    -          begin: /\/(?![ *])(\\.|[^\\\n])*?\/[gim]*(?=\W)/
    -        }
    -      ]
    -    },
    -    {
    -      begin: '@' + JS_IDENT_RE
    -    },
    -    {
    -      begin: '``',
    -      end: '``',
    -      excludeBegin: true,
    -      excludeEnd: true,
    -      subLanguage: 'javascript'
    -    }
    -  ];
    -  SUBST.contains = EXPRESSIONS;
    -
    -  const PARAMS = {
    -    className: 'params',
    -    begin: '\\(',
    -    returnBegin: true,
    -    /* We need another contained nameless mode to not have every nested
    -    pair of parens to be called "params" */
    -    contains: [
    -      {
    -        begin: /\(/,
    -        end: /\)/,
    -        keywords: KEYWORDS$1,
    -        contains: ['self'].concat(EXPRESSIONS)
    -      }
    -    ]
    -  };
    -
    -  const SYMBOLS = {
    -    begin: '(#=>|=>|\\|>>|-?->|!->)'
    -  };
    -
    -  return {
    -    name: 'LiveScript',
    -    aliases: ['ls'],
    -    keywords: KEYWORDS$1,
    -    illegal: /\/\*/,
    -    contains: EXPRESSIONS.concat([
    -      hljs.COMMENT('\\/\\*', '\\*\\/'),
    -      hljs.HASH_COMMENT_MODE,
    -      SYMBOLS, // relevance booster
    -      {
    -        className: 'function',
    -        contains: [
    -          TITLE,
    -          PARAMS
    -        ],
    -        returnBegin: true,
    -        variants: [
    -          {
    -            begin: '(' + JS_IDENT_RE + '\\s*(?:=|:=)\\s*)?(\\(.*\\)\\s*)?\\B->\\*?',
    -            end: '->\\*?'
    -          },
    -          {
    -            begin: '(' + JS_IDENT_RE + '\\s*(?:=|:=)\\s*)?!?(\\(.*\\)\\s*)?\\B[-~]{1,2}>\\*?',
    -            end: '[-~]{1,2}>\\*?'
    -          },
    -          {
    -            begin: '(' + JS_IDENT_RE + '\\s*(?:=|:=)\\s*)?(\\(.*\\)\\s*)?\\B!?[-~]{1,2}>\\*?',
    -            end: '!?[-~]{1,2}>\\*?'
    -          }
    -        ]
    -      },
    -      {
    -        className: 'class',
    -        beginKeywords: 'class',
    -        end: '$',
    -        illegal: /[:="\[\]]/,
    -        contains: [
    -          {
    -            beginKeywords: 'extends',
    -            endsWithParent: true,
    -            illegal: /[:="\[\]]/,
    -            contains: [TITLE]
    -          },
    -          TITLE
    -        ]
    -      },
    -      {
    -        begin: JS_IDENT_RE + ':',
    -        end: ':',
    -        returnBegin: true,
    -        returnEnd: true,
    -        relevance: 0
    -      }
    -    ])
    -  };
    -}
    -
    -module.exports = livescript;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/llvm.js b/claude-code-source/node_modules/highlight.js/lib/languages/llvm.js
    deleted file mode 100644
    index b7eac64b..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/llvm.js
    +++ /dev/null
    @@ -1,154 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: LLVM IR
    -Author: Michael Rodler 
    -Description: language used as intermediate representation in the LLVM compiler framework
    -Website: https://llvm.org/docs/LangRef.html
    -Category: assembler
    -Audit: 2020
    -*/
    -
    -/** @type LanguageFn */
    -function llvm(hljs) {
    -  const IDENT_RE = /([-a-zA-Z$._][\w$.-]*)/;
    -  const TYPE = {
    -    className: 'type',
    -    begin: /\bi\d+(?=\s|\b)/
    -  };
    -  const OPERATOR = {
    -    className: 'operator',
    -    relevance: 0,
    -    begin: /=/
    -  };
    -  const PUNCTUATION = {
    -    className: 'punctuation',
    -    relevance: 0,
    -    begin: /,/
    -  };
    -  const NUMBER = {
    -    className: 'number',
    -    variants: [
    -        { begin: /0[xX][a-fA-F0-9]+/ },
    -        { begin: /-?\d+(?:[.]\d+)?(?:[eE][-+]?\d+(?:[.]\d+)?)?/ }
    -    ],
    -    relevance: 0
    -  };
    -  const LABEL = {
    -    className: 'symbol',
    -    variants: [
    -        { begin: /^\s*[a-z]+:/ }, // labels
    -    ],
    -    relevance: 0
    -  };
    -  const VARIABLE = {
    -    className: 'variable',
    -    variants: [
    -      { begin: concat(/%/, IDENT_RE) },
    -      { begin: /%\d+/ },
    -      { begin: /#\d+/ },
    -    ]
    -  };
    -  const FUNCTION = {
    -    className: 'title',
    -    variants: [
    -      { begin: concat(/@/, IDENT_RE) },
    -      { begin: /@\d+/ },
    -      { begin: concat(/!/, IDENT_RE) },
    -      { begin: concat(/!\d+/, IDENT_RE) },
    -      // https://llvm.org/docs/LangRef.html#namedmetadatastructure
    -      // obviously a single digit can also be used in this fashion
    -      { begin: /!\d+/ }
    -    ]
    -  };
    -
    -  return {
    -    name: 'LLVM IR',
    -    // TODO: split into different categories of keywords
    -    keywords:
    -      'begin end true false declare define global ' +
    -      'constant private linker_private internal ' +
    -      'available_externally linkonce linkonce_odr weak ' +
    -      'weak_odr appending dllimport dllexport common ' +
    -      'default hidden protected extern_weak external ' +
    -      'thread_local zeroinitializer undef null to tail ' +
    -      'target triple datalayout volatile nuw nsw nnan ' +
    -      'ninf nsz arcp fast exact inbounds align ' +
    -      'addrspace section alias module asm sideeffect ' +
    -      'gc dbg linker_private_weak attributes blockaddress ' +
    -      'initialexec localdynamic localexec prefix unnamed_addr ' +
    -      'ccc fastcc coldcc x86_stdcallcc x86_fastcallcc ' +
    -      'arm_apcscc arm_aapcscc arm_aapcs_vfpcc ptx_device ' +
    -      'ptx_kernel intel_ocl_bicc msp430_intrcc spir_func ' +
    -      'spir_kernel x86_64_sysvcc x86_64_win64cc x86_thiscallcc ' +
    -      'cc c signext zeroext inreg sret nounwind ' +
    -      'noreturn noalias nocapture byval nest readnone ' +
    -      'readonly inlinehint noinline alwaysinline optsize ssp ' +
    -      'sspreq noredzone noimplicitfloat naked builtin cold ' +
    -      'nobuiltin noduplicate nonlazybind optnone returns_twice ' +
    -      'sanitize_address sanitize_memory sanitize_thread sspstrong ' +
    -      'uwtable returned type opaque eq ne slt sgt ' +
    -      'sle sge ult ugt ule uge oeq one olt ogt ' +
    -      'ole oge ord uno ueq une x acq_rel acquire ' +
    -      'alignstack atomic catch cleanup filter inteldialect ' +
    -      'max min monotonic nand personality release seq_cst ' +
    -      'singlethread umax umin unordered xchg add fadd ' +
    -      'sub fsub mul fmul udiv sdiv fdiv urem srem ' +
    -      'frem shl lshr ashr and or xor icmp fcmp ' +
    -      'phi call trunc zext sext fptrunc fpext uitofp ' +
    -      'sitofp fptoui fptosi inttoptr ptrtoint bitcast ' +
    -      'addrspacecast select va_arg ret br switch invoke ' +
    -      'unwind unreachable indirectbr landingpad resume ' +
    -      'malloc alloca free load store getelementptr ' +
    -      'extractelement insertelement shufflevector getresult ' +
    -      'extractvalue insertvalue atomicrmw cmpxchg fence ' +
    -      'argmemonly double',
    -    contains: [
    -      TYPE,
    -      // this matches "empty comments"...
    -      // ...because it's far more likely this is a statement terminator in
    -      // another language than an actual comment
    -      hljs.COMMENT(/;\s*$/, null, { relevance: 0 }),
    -      hljs.COMMENT(/;/, /$/),
    -      hljs.QUOTE_STRING_MODE,
    -      {
    -        className: 'string',
    -        variants: [
    -          // Double-quoted string
    -          { begin: /"/, end: /[^\\]"/ },
    -        ]
    -      },
    -      FUNCTION,
    -      PUNCTUATION,
    -      OPERATOR,
    -      VARIABLE,
    -      LABEL,
    -      NUMBER
    -    ]
    -  };
    -}
    -
    -module.exports = llvm;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/lsl.js b/claude-code-source/node_modules/highlight.js/lib/languages/lsl.js
    deleted file mode 100644
    index 279fc46d..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/lsl.js
    +++ /dev/null
    @@ -1,95 +0,0 @@
    -/*
    -Language: LSL (Linden Scripting Language)
    -Description: The Linden Scripting Language is used in Second Life by Linden Labs.
    -Author: Builder's Brewery 
    -Website: http://wiki.secondlife.com/wiki/LSL_Portal
    -Category: scripting
    -*/
    -
    -function lsl(hljs) {
    -
    -    var LSL_STRING_ESCAPE_CHARS = {
    -        className: 'subst',
    -        begin: /\\[tn"\\]/
    -    };
    -
    -    var LSL_STRINGS = {
    -        className: 'string',
    -        begin: '"',
    -        end: '"',
    -        contains: [
    -            LSL_STRING_ESCAPE_CHARS
    -        ]
    -    };
    -
    -    var LSL_NUMBERS = {
    -        className: 'number',
    -        relevance:0,
    -        begin: hljs.C_NUMBER_RE
    -    };
    -
    -    var LSL_CONSTANTS = {
    -        className: 'literal',
    -        variants: [
    -            {
    -                begin: '\\b(PI|TWO_PI|PI_BY_TWO|DEG_TO_RAD|RAD_TO_DEG|SQRT2)\\b'
    -            },
    -            {
    -                begin: '\\b(XP_ERROR_(EXPERIENCES_DISABLED|EXPERIENCE_(DISABLED|SUSPENDED)|INVALID_(EXPERIENCE|PARAMETERS)|KEY_NOT_FOUND|MATURITY_EXCEEDED|NONE|NOT_(FOUND|PERMITTED(_LAND)?)|NO_EXPERIENCE|QUOTA_EXCEEDED|RETRY_UPDATE|STORAGE_EXCEPTION|STORE_DISABLED|THROTTLED|UNKNOWN_ERROR)|JSON_APPEND|STATUS_(PHYSICS|ROTATE_[XYZ]|PHANTOM|SANDBOX|BLOCK_GRAB(_OBJECT)?|(DIE|RETURN)_AT_EDGE|CAST_SHADOWS|OK|MALFORMED_PARAMS|TYPE_MISMATCH|BOUNDS_ERROR|NOT_(FOUND|SUPPORTED)|INTERNAL_ERROR|WHITELIST_FAILED)|AGENT(_(BY_(LEGACY_|USER)NAME|FLYING|ATTACHMENTS|SCRIPTED|MOUSELOOK|SITTING|ON_OBJECT|AWAY|WALKING|IN_AIR|TYPING|CROUCHING|BUSY|ALWAYS_RUN|AUTOPILOT|LIST_(PARCEL(_OWNER)?|REGION)))?|CAMERA_(PITCH|DISTANCE|BEHINDNESS_(ANGLE|LAG)|(FOCUS|POSITION)(_(THRESHOLD|LOCKED|LAG))?|FOCUS_OFFSET|ACTIVE)|ANIM_ON|LOOP|REVERSE|PING_PONG|SMOOTH|ROTATE|SCALE|ALL_SIDES|LINK_(ROOT|SET|ALL_(OTHERS|CHILDREN)|THIS)|ACTIVE|PASS(IVE|_(ALWAYS|IF_NOT_HANDLED|NEVER))|SCRIPTED|CONTROL_(FWD|BACK|(ROT_)?(LEFT|RIGHT)|UP|DOWN|(ML_)?LBUTTON)|PERMISSION_(RETURN_OBJECTS|DEBIT|OVERRIDE_ANIMATIONS|SILENT_ESTATE_MANAGEMENT|TAKE_CONTROLS|TRIGGER_ANIMATION|ATTACH|CHANGE_LINKS|(CONTROL|TRACK)_CAMERA|TELEPORT)|INVENTORY_(TEXTURE|SOUND|OBJECT|SCRIPT|LANDMARK|CLOTHING|NOTECARD|BODYPART|ANIMATION|GESTURE|ALL|NONE)|CHANGED_(INVENTORY|COLOR|SHAPE|SCALE|TEXTURE|LINK|ALLOWED_DROP|OWNER|REGION(_START)?|TELEPORT|MEDIA)|OBJECT_(CLICK_ACTION|HOVER_HEIGHT|LAST_OWNER_ID|(PHYSICS|SERVER|STREAMING)_COST|UNKNOWN_DETAIL|CHARACTER_TIME|PHANTOM|PHYSICS|TEMP_(ATTACHED|ON_REZ)|NAME|DESC|POS|PRIM_(COUNT|EQUIVALENCE)|RETURN_(PARCEL(_OWNER)?|REGION)|REZZER_KEY|ROO?T|VELOCITY|OMEGA|OWNER|GROUP(_TAG)?|CREATOR|ATTACHED_(POINT|SLOTS_AVAILABLE)|RENDER_WEIGHT|(BODY_SHAPE|PATHFINDING)_TYPE|(RUNNING|TOTAL)_SCRIPT_COUNT|TOTAL_INVENTORY_COUNT|SCRIPT_(MEMORY|TIME))|TYPE_(INTEGER|FLOAT|STRING|KEY|VECTOR|ROTATION|INVALID)|(DEBUG|PUBLIC)_CHANNEL|ATTACH_(AVATAR_CENTER|CHEST|HEAD|BACK|PELVIS|MOUTH|CHIN|NECK|NOSE|BELLY|[LR](SHOULDER|HAND|FOOT|EAR|EYE|[UL](ARM|LEG)|HIP)|(LEFT|RIGHT)_PEC|HUD_(CENTER_[12]|TOP_(RIGHT|CENTER|LEFT)|BOTTOM(_(RIGHT|LEFT))?)|[LR]HAND_RING1|TAIL_(BASE|TIP)|[LR]WING|FACE_(JAW|[LR]EAR|[LR]EYE|TOUNGE)|GROIN|HIND_[LR]FOOT)|LAND_(LEVEL|RAISE|LOWER|SMOOTH|NOISE|REVERT)|DATA_(ONLINE|NAME|BORN|SIM_(POS|STATUS|RATING)|PAYINFO)|PAYMENT_INFO_(ON_FILE|USED)|REMOTE_DATA_(CHANNEL|REQUEST|REPLY)|PSYS_(PART_(BF_(ZERO|ONE(_MINUS_(DEST_COLOR|SOURCE_(ALPHA|COLOR)))?|DEST_COLOR|SOURCE_(ALPHA|COLOR))|BLEND_FUNC_(DEST|SOURCE)|FLAGS|(START|END)_(COLOR|ALPHA|SCALE|GLOW)|MAX_AGE|(RIBBON|WIND|INTERP_(COLOR|SCALE)|BOUNCE|FOLLOW_(SRC|VELOCITY)|TARGET_(POS|LINEAR)|EMISSIVE)_MASK)|SRC_(MAX_AGE|PATTERN|ANGLE_(BEGIN|END)|BURST_(RATE|PART_COUNT|RADIUS|SPEED_(MIN|MAX))|ACCEL|TEXTURE|TARGET_KEY|OMEGA|PATTERN_(DROP|EXPLODE|ANGLE(_CONE(_EMPTY)?)?)))|VEHICLE_(REFERENCE_FRAME|TYPE_(NONE|SLED|CAR|BOAT|AIRPLANE|BALLOON)|(LINEAR|ANGULAR)_(FRICTION_TIMESCALE|MOTOR_DIRECTION)|LINEAR_MOTOR_OFFSET|HOVER_(HEIGHT|EFFICIENCY|TIMESCALE)|BUOYANCY|(LINEAR|ANGULAR)_(DEFLECTION_(EFFICIENCY|TIMESCALE)|MOTOR_(DECAY_)?TIMESCALE)|VERTICAL_ATTRACTION_(EFFICIENCY|TIMESCALE)|BANKING_(EFFICIENCY|MIX|TIMESCALE)|FLAG_(NO_DEFLECTION_UP|LIMIT_(ROLL_ONLY|MOTOR_UP)|HOVER_((WATER|TERRAIN|UP)_ONLY|GLOBAL_HEIGHT)|MOUSELOOK_(STEER|BANK)|CAMERA_DECOUPLED))|PRIM_(ALLOW_UNSIT|ALPHA_MODE(_(BLEND|EMISSIVE|MASK|NONE))?|NORMAL|SPECULAR|TYPE(_(BOX|CYLINDER|PRISM|SPHERE|TORUS|TUBE|RING|SCULPT))?|HOLE_(DEFAULT|CIRCLE|SQUARE|TRIANGLE)|MATERIAL(_(STONE|METAL|GLASS|WOOD|FLESH|PLASTIC|RUBBER))?|SHINY_(NONE|LOW|MEDIUM|HIGH)|BUMP_(NONE|BRIGHT|DARK|WOOD|BARK|BRICKS|CHECKER|CONCRETE|TILE|STONE|DISKS|GRAVEL|BLOBS|SIDING|LARGETILE|STUCCO|SUCTION|WEAVE)|TEXGEN_(DEFAULT|PLANAR)|SCRIPTED_SIT_ONLY|SCULPT_(TYPE_(SPHERE|TORUS|PLANE|CYLINDER|MASK)|FLAG_(MIRROR|INVERT))|PHYSICS(_(SHAPE_(CONVEX|NONE|PRIM|TYPE)))?|(POS|ROT)_LOCAL|SLICE|TEXT|FLEXIBLE|POINT_LIGHT|TEMP_ON_REZ|PHANTOM|POSITION|SIT_TARGET|SIZE|ROTATION|TEXTURE|NAME|OMEGA|DESC|LINK_TARGET|COLOR|BUMP_SHINY|FULLBRIGHT|TEXGEN|GLOW|MEDIA_(ALT_IMAGE_ENABLE|CONTROLS|(CURRENT|HOME)_URL|AUTO_(LOOP|PLAY|SCALE|ZOOM)|FIRST_CLICK_INTERACT|(WIDTH|HEIGHT)_PIXELS|WHITELIST(_ENABLE)?|PERMS_(INTERACT|CONTROL)|PARAM_MAX|CONTROLS_(STANDARD|MINI)|PERM_(NONE|OWNER|GROUP|ANYONE)|MAX_(URL_LENGTH|WHITELIST_(SIZE|COUNT)|(WIDTH|HEIGHT)_PIXELS)))|MASK_(BASE|OWNER|GROUP|EVERYONE|NEXT)|PERM_(TRANSFER|MODIFY|COPY|MOVE|ALL)|PARCEL_(MEDIA_COMMAND_(STOP|PAUSE|PLAY|LOOP|TEXTURE|URL|TIME|AGENT|UNLOAD|AUTO_ALIGN|TYPE|SIZE|DESC|LOOP_SET)|FLAG_(ALLOW_(FLY|(GROUP_)?SCRIPTS|LANDMARK|TERRAFORM|DAMAGE|CREATE_(GROUP_)?OBJECTS)|USE_(ACCESS_(GROUP|LIST)|BAN_LIST|LAND_PASS_LIST)|LOCAL_SOUND_ONLY|RESTRICT_PUSHOBJECT|ALLOW_(GROUP|ALL)_OBJECT_ENTRY)|COUNT_(TOTAL|OWNER|GROUP|OTHER|SELECTED|TEMP)|DETAILS_(NAME|DESC|OWNER|GROUP|AREA|ID|SEE_AVATARS))|LIST_STAT_(MAX|MIN|MEAN|MEDIAN|STD_DEV|SUM(_SQUARES)?|NUM_COUNT|GEOMETRIC_MEAN|RANGE)|PAY_(HIDE|DEFAULT)|REGION_FLAG_(ALLOW_DAMAGE|FIXED_SUN|BLOCK_TERRAFORM|SANDBOX|DISABLE_(COLLISIONS|PHYSICS)|BLOCK_FLY|ALLOW_DIRECT_TELEPORT|RESTRICT_PUSHOBJECT)|HTTP_(METHOD|MIMETYPE|BODY_(MAXLENGTH|TRUNCATED)|CUSTOM_HEADER|PRAGMA_NO_CACHE|VERBOSE_THROTTLE|VERIFY_CERT)|SIT_(INVALID_(AGENT|LINK_OBJECT)|NO(T_EXPERIENCE|_(ACCESS|EXPERIENCE_PERMISSION|SIT_TARGET)))|STRING_(TRIM(_(HEAD|TAIL))?)|CLICK_ACTION_(NONE|TOUCH|SIT|BUY|PAY|OPEN(_MEDIA)?|PLAY|ZOOM)|TOUCH_INVALID_FACE|PROFILE_(NONE|SCRIPT_MEMORY)|RC_(DATA_FLAGS|DETECT_PHANTOM|GET_(LINK_NUM|NORMAL|ROOT_KEY)|MAX_HITS|REJECT_(TYPES|AGENTS|(NON)?PHYSICAL|LAND))|RCERR_(CAST_TIME_EXCEEDED|SIM_PERF_LOW|UNKNOWN)|ESTATE_ACCESS_(ALLOWED_(AGENT|GROUP)_(ADD|REMOVE)|BANNED_AGENT_(ADD|REMOVE))|DENSITY|FRICTION|RESTITUTION|GRAVITY_MULTIPLIER|KFM_(COMMAND|CMD_(PLAY|STOP|PAUSE)|MODE|FORWARD|LOOP|PING_PONG|REVERSE|DATA|ROTATION|TRANSLATION)|ERR_(GENERIC|PARCEL_PERMISSIONS|MALFORMED_PARAMS|RUNTIME_PERMISSIONS|THROTTLED)|CHARACTER_(CMD_((SMOOTH_)?STOP|JUMP)|DESIRED_(TURN_)?SPEED|RADIUS|STAY_WITHIN_PARCEL|LENGTH|ORIENTATION|ACCOUNT_FOR_SKIPPED_FRAMES|AVOIDANCE_MODE|TYPE(_([ABCD]|NONE))?|MAX_(DECEL|TURN_RADIUS|(ACCEL|SPEED)))|PURSUIT_(OFFSET|FUZZ_FACTOR|GOAL_TOLERANCE|INTERCEPT)|REQUIRE_LINE_OF_SIGHT|FORCE_DIRECT_PATH|VERTICAL|HORIZONTAL|AVOID_(CHARACTERS|DYNAMIC_OBSTACLES|NONE)|PU_(EVADE_(HIDDEN|SPOTTED)|FAILURE_(DYNAMIC_PATHFINDING_DISABLED|INVALID_(GOAL|START)|NO_(NAVMESH|VALID_DESTINATION)|OTHER|TARGET_GONE|(PARCEL_)?UNREACHABLE)|(GOAL|SLOWDOWN_DISTANCE)_REACHED)|TRAVERSAL_TYPE(_(FAST|NONE|SLOW))?|CONTENT_TYPE_(ATOM|FORM|HTML|JSON|LLSD|RSS|TEXT|XHTML|XML)|GCNP_(RADIUS|STATIC)|(PATROL|WANDER)_PAUSE_AT_WAYPOINTS|OPT_(AVATAR|CHARACTER|EXCLUSION_VOLUME|LEGACY_LINKSET|MATERIAL_VOLUME|OTHER|STATIC_OBSTACLE|WALKABLE)|SIM_STAT_PCT_CHARS_STEPPED)\\b'
    -            },
    -            {
    -                begin: '\\b(FALSE|TRUE)\\b'
    -            },
    -            {
    -                begin: '\\b(ZERO_ROTATION)\\b'
    -            },
    -            {
    -                begin: '\\b(EOF|JSON_(ARRAY|DELETE|FALSE|INVALID|NULL|NUMBER|OBJECT|STRING|TRUE)|NULL_KEY|TEXTURE_(BLANK|DEFAULT|MEDIA|PLYWOOD|TRANSPARENT)|URL_REQUEST_(GRANTED|DENIED))\\b'
    -            },
    -            {
    -                begin: '\\b(ZERO_VECTOR|TOUCH_INVALID_(TEXCOORD|VECTOR))\\b'
    -            }
    -        ]
    -    };
    -
    -    var LSL_FUNCTIONS = {
    -        className: 'built_in',
    -        begin: '\\b(ll(AgentInExperience|(Create|DataSize|Delete|KeyCount|Keys|Read|Update)KeyValue|GetExperience(Details|ErrorMessage)|ReturnObjectsBy(ID|Owner)|Json(2List|[GS]etValue|ValueType)|Sin|Cos|Tan|Atan2|Sqrt|Pow|Abs|Fabs|Frand|Floor|Ceil|Round|Vec(Mag|Norm|Dist)|Rot(Between|2(Euler|Fwd|Left|Up))|(Euler|Axes)2Rot|Whisper|(Region|Owner)?Say|Shout|Listen(Control|Remove)?|Sensor(Repeat|Remove)?|Detected(Name|Key|Owner|Type|Pos|Vel|Grab|Rot|Group|LinkNumber)|Die|Ground|Wind|([GS]et)(AnimationOverride|MemoryLimit|PrimMediaParams|ParcelMusicURL|Object(Desc|Name)|PhysicsMaterial|Status|Scale|Color|Alpha|Texture|Pos|Rot|Force|Torque)|ResetAnimationOverride|(Scale|Offset|Rotate)Texture|(Rot)?Target(Remove)?|(Stop)?MoveToTarget|Apply(Rotational)?Impulse|Set(KeyframedMotion|ContentType|RegionPos|(Angular)?Velocity|Buoyancy|HoverHeight|ForceAndTorque|TimerEvent|ScriptState|Damage|TextureAnim|Sound(Queueing|Radius)|Vehicle(Type|(Float|Vector|Rotation)Param)|(Touch|Sit)?Text|Camera(Eye|At)Offset|PrimitiveParams|ClickAction|Link(Alpha|Color|PrimitiveParams(Fast)?|Texture(Anim)?|Camera|Media)|RemoteScriptAccessPin|PayPrice|LocalRot)|ScaleByFactor|Get((Max|Min)ScaleFactor|ClosestNavPoint|StaticPath|SimStats|Env|PrimitiveParams|Link(PrimitiveParams|Number(OfSides)?|Key|Name|Media)|HTTPHeader|FreeURLs|Object(Details|PermMask|PrimCount)|Parcel(MaxPrims|Details|Prim(Count|Owners))|Attached(List)?|(SPMax|Free|Used)Memory|Region(Name|TimeDilation|FPS|Corner|AgentCount)|Root(Position|Rotation)|UnixTime|(Parcel|Region)Flags|(Wall|GMT)clock|SimulatorHostname|BoundingBox|GeometricCenter|Creator|NumberOf(Prims|NotecardLines|Sides)|Animation(List)?|(Camera|Local)(Pos|Rot)|Vel|Accel|Omega|Time(stamp|OfDay)|(Object|CenterOf)?Mass|MassMKS|Energy|Owner|(Owner)?Key|SunDirection|Texture(Offset|Scale|Rot)|Inventory(Number|Name|Key|Type|Creator|PermMask)|Permissions(Key)?|StartParameter|List(Length|EntryType)|Date|Agent(Size|Info|Language|List)|LandOwnerAt|NotecardLine|Script(Name|State))|(Get|Reset|GetAndReset)Time|PlaySound(Slave)?|LoopSound(Master|Slave)?|(Trigger|Stop|Preload)Sound|((Get|Delete)Sub|Insert)String|To(Upper|Lower)|Give(InventoryList|Money)|RezObject|(Stop)?LookAt|Sleep|CollisionFilter|(Take|Release)Controls|DetachFromAvatar|AttachToAvatar(Temp)?|InstantMessage|(GetNext)?Email|StopHover|MinEventDelay|RotLookAt|String(Length|Trim)|(Start|Stop)Animation|TargetOmega|Request(Experience)?Permissions|(Create|Break)Link|BreakAllLinks|(Give|Remove)Inventory|Water|PassTouches|Request(Agent|Inventory)Data|TeleportAgent(Home|GlobalCoords)?|ModifyLand|CollisionSound|ResetScript|MessageLinked|PushObject|PassCollisions|AxisAngle2Rot|Rot2(Axis|Angle)|A(cos|sin)|AngleBetween|AllowInventoryDrop|SubStringIndex|List2(CSV|Integer|Json|Float|String|Key|Vector|Rot|List(Strided)?)|DeleteSubList|List(Statistics|Sort|Randomize|(Insert|Find|Replace)List)|EdgeOfWorld|AdjustSoundVolume|Key2Name|TriggerSoundLimited|EjectFromLand|(CSV|ParseString)2List|OverMyLand|SameGroup|UnSit|Ground(Slope|Normal|Contour)|GroundRepel|(Set|Remove)VehicleFlags|SitOnLink|(AvatarOn)?(Link)?SitTarget|Script(Danger|Profiler)|Dialog|VolumeDetect|ResetOtherScript|RemoteLoadScriptPin|(Open|Close)RemoteDataChannel|SendRemoteData|RemoteDataReply|(Integer|String)ToBase64|XorBase64|Log(10)?|Base64To(String|Integer)|ParseStringKeepNulls|RezAtRoot|RequestSimulatorData|ForceMouselook|(Load|Release|(E|Une)scape)URL|ParcelMedia(CommandList|Query)|ModPow|MapDestination|(RemoveFrom|AddTo|Reset)Land(Pass|Ban)List|(Set|Clear)CameraParams|HTTP(Request|Response)|TextBox|DetectedTouch(UV|Face|Pos|(N|Bin)ormal|ST)|(MD5|SHA1|DumpList2)String|Request(Secure)?URL|Clear(Prim|Link)Media|(Link)?ParticleSystem|(Get|Request)(Username|DisplayName)|RegionSayTo|CastRay|GenerateKey|TransferLindenDollars|ManageEstateAccess|(Create|Delete)Character|ExecCharacterCmd|Evade|FleeFrom|NavigateTo|PatrolPoints|Pursue|UpdateCharacter|WanderWithin))\\b'
    -    };
    -
    -    return {
    -        name: 'LSL (Linden Scripting Language)',
    -        illegal: ':',
    -        contains: [
    -            LSL_STRINGS,
    -            {
    -                className: 'comment',
    -                variants: [
    -                    hljs.COMMENT('//', '$'),
    -                    hljs.COMMENT('/\\*', '\\*/')
    -                ],
    -                relevance: 0
    -            },
    -            LSL_NUMBERS,
    -            {
    -                className: 'section',
    -                variants: [
    -                    {
    -                        begin: '\\b(state|default)\\b'
    -                    },
    -                    {
    -                        begin: '\\b(state_(entry|exit)|touch(_(start|end))?|(land_)?collision(_(start|end))?|timer|listen|(no_)?sensor|control|(not_)?at_(rot_)?target|money|email|experience_permissions(_denied)?|run_time_permissions|changed|attach|dataserver|moving_(start|end)|link_message|(on|object)_rez|remote_data|http_re(sponse|quest)|path_update|transaction_result)\\b'
    -                    }
    -                ]
    -            },
    -            LSL_FUNCTIONS,
    -            LSL_CONSTANTS,
    -            {
    -                className: 'type',
    -                begin: '\\b(integer|float|string|key|vector|quaternion|rotation|list)\\b'
    -            }
    -        ]
    -    };
    -}
    -
    -module.exports = lsl;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/lua.js b/claude-code-source/node_modules/highlight.js/lib/languages/lua.js
    deleted file mode 100644
    index 210669d2..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/lua.js
    +++ /dev/null
    @@ -1,82 +0,0 @@
    -/*
    -Language: Lua
    -Description: Lua is a powerful, efficient, lightweight, embeddable scripting language.
    -Author: Andrew Fedorov 
    -Category: common, scripting
    -Website: https://www.lua.org
    -*/
    -
    -function lua(hljs) {
    -  const OPENING_LONG_BRACKET = '\\[=*\\[';
    -  const CLOSING_LONG_BRACKET = '\\]=*\\]';
    -  const LONG_BRACKETS = {
    -    begin: OPENING_LONG_BRACKET,
    -    end: CLOSING_LONG_BRACKET,
    -    contains: ['self']
    -  };
    -  const COMMENTS = [
    -    hljs.COMMENT('--(?!' + OPENING_LONG_BRACKET + ')', '$'),
    -    hljs.COMMENT(
    -      '--' + OPENING_LONG_BRACKET,
    -      CLOSING_LONG_BRACKET,
    -      {
    -        contains: [LONG_BRACKETS],
    -        relevance: 10
    -      }
    -    )
    -  ];
    -  return {
    -    name: 'Lua',
    -    keywords: {
    -      $pattern: hljs.UNDERSCORE_IDENT_RE,
    -      literal: "true false nil",
    -      keyword: "and break do else elseif end for goto if in local not or repeat return then until while",
    -      built_in:
    -        // Metatags and globals:
    -        '_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len ' +
    -        '__gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert ' +
    -        // Standard methods and properties:
    -        'collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring ' +
    -        'module next pairs pcall print rawequal rawget rawset require select setfenv ' +
    -        'setmetatable tonumber tostring type unpack xpcall arg self ' +
    -        // Library methods and properties (one line per library):
    -        'coroutine resume yield status wrap create running debug getupvalue ' +
    -        'debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv ' +
    -        'io lines write close flush open output type read stderr stdin input stdout popen tmpfile ' +
    -        'math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan ' +
    -        'os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath config path seeall ' +
    -        'string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower ' +
    -        'table setn insert getn foreachi maxn foreach concat sort remove'
    -    },
    -    contains: COMMENTS.concat([
    -      {
    -        className: 'function',
    -        beginKeywords: 'function',
    -        end: '\\)',
    -        contains: [
    -          hljs.inherit(hljs.TITLE_MODE, {
    -            begin: '([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*'
    -          }),
    -          {
    -            className: 'params',
    -            begin: '\\(',
    -            endsWithParent: true,
    -            contains: COMMENTS
    -          }
    -        ].concat(COMMENTS)
    -      },
    -      hljs.C_NUMBER_MODE,
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      {
    -        className: 'string',
    -        begin: OPENING_LONG_BRACKET,
    -        end: CLOSING_LONG_BRACKET,
    -        contains: [LONG_BRACKETS],
    -        relevance: 5
    -      }
    -    ])
    -  };
    -}
    -
    -module.exports = lua;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/makefile.js b/claude-code-source/node_modules/highlight.js/lib/languages/makefile.js
    deleted file mode 100644
    index b1c55dda..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/makefile.js
    +++ /dev/null
    @@ -1,92 +0,0 @@
    -/*
    -Language: Makefile
    -Author: Ivan Sagalaev 
    -Contributors: Joël Porquet 
    -Website: https://www.gnu.org/software/make/manual/html_node/Introduction.html
    -Category: common
    -*/
    -
    -function makefile(hljs) {
    -  /* Variables: simple (eg $(var)) and special (eg $@) */
    -  const VARIABLE = {
    -    className: 'variable',
    -    variants: [
    -      {
    -        begin: '\\$\\(' + hljs.UNDERSCORE_IDENT_RE + '\\)',
    -        contains: [ hljs.BACKSLASH_ESCAPE ]
    -      },
    -      {
    -        begin: /\$[@% source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: Markdown
    -Requires: xml.js
    -Author: John Crepezzi 
    -Website: https://daringfireball.net/projects/markdown/
    -Category: common, markup
    -*/
    -
    -function markdown(hljs) {
    -  const INLINE_HTML = {
    -    begin: /<\/?[A-Za-z_]/,
    -    end: '>',
    -    subLanguage: 'xml',
    -    relevance: 0
    -  };
    -  const HORIZONTAL_RULE = {
    -    begin: '^[-\\*]{3,}',
    -    end: '$'
    -  };
    -  const CODE = {
    -    className: 'code',
    -    variants: [
    -      // TODO: fix to allow these to work with sublanguage also
    -      {
    -        begin: '(`{3,})[^`](.|\\n)*?\\1`*[ ]*'
    -      },
    -      {
    -        begin: '(~{3,})[^~](.|\\n)*?\\1~*[ ]*'
    -      },
    -      // needed to allow markdown as a sublanguage to work
    -      {
    -        begin: '```',
    -        end: '```+[ ]*$'
    -      },
    -      {
    -        begin: '~~~',
    -        end: '~~~+[ ]*$'
    -      },
    -      {
    -        begin: '`.+?`'
    -      },
    -      {
    -        begin: '(?=^( {4}|\\t))',
    -        // use contains to gobble up multiple lines to allow the block to be whatever size
    -        // but only have a single open/close tag vs one per line
    -        contains: [
    -          {
    -            begin: '^( {4}|\\t)',
    -            end: '(\\n)$'
    -          }
    -        ],
    -        relevance: 0
    -      }
    -    ]
    -  };
    -  const LIST = {
    -    className: 'bullet',
    -    begin: '^[ \t]*([*+-]|(\\d+\\.))(?=\\s+)',
    -    end: '\\s+',
    -    excludeEnd: true
    -  };
    -  const LINK_REFERENCE = {
    -    begin: /^\[[^\n]+\]:/,
    -    returnBegin: true,
    -    contains: [
    -      {
    -        className: 'symbol',
    -        begin: /\[/,
    -        end: /\]/,
    -        excludeBegin: true,
    -        excludeEnd: true
    -      },
    -      {
    -        className: 'link',
    -        begin: /:\s*/,
    -        end: /$/,
    -        excludeBegin: true
    -      }
    -    ]
    -  };
    -  const URL_SCHEME = /[A-Za-z][A-Za-z0-9+.-]*/;
    -  const LINK = {
    -    variants: [
    -      // too much like nested array access in so many languages
    -      // to have any real relevance
    -      {
    -        begin: /\[.+?\]\[.*?\]/,
    -        relevance: 0
    -      },
    -      // popular internet URLs
    -      {
    -        begin: /\[.+?\]\(((data|javascript|mailto):|(?:http|ftp)s?:\/\/).*?\)/,
    -        relevance: 2
    -      },
    -      {
    -        begin: concat(/\[.+?\]\(/, URL_SCHEME, /:\/\/.*?\)/),
    -        relevance: 2
    -      },
    -      // relative urls
    -      {
    -        begin: /\[.+?\]\([./?&#].*?\)/,
    -        relevance: 1
    -      },
    -      // whatever else, lower relevance (might not be a link at all)
    -      {
    -        begin: /\[.+?\]\(.*?\)/,
    -        relevance: 0
    -      }
    -    ],
    -    returnBegin: true,
    -    contains: [
    -      {
    -        className: 'string',
    -        relevance: 0,
    -        begin: '\\[',
    -        end: '\\]',
    -        excludeBegin: true,
    -        returnEnd: true
    -      },
    -      {
    -        className: 'link',
    -        relevance: 0,
    -        begin: '\\]\\(',
    -        end: '\\)',
    -        excludeBegin: true,
    -        excludeEnd: true
    -      },
    -      {
    -        className: 'symbol',
    -        relevance: 0,
    -        begin: '\\]\\[',
    -        end: '\\]',
    -        excludeBegin: true,
    -        excludeEnd: true
    -      }
    -    ]
    -  };
    -  const BOLD = {
    -    className: 'strong',
    -    contains: [], // defined later
    -    variants: [
    -      {
    -        begin: /_{2}/,
    -        end: /_{2}/
    -      },
    -      {
    -        begin: /\*{2}/,
    -        end: /\*{2}/
    -      }
    -    ]
    -  };
    -  const ITALIC = {
    -    className: 'emphasis',
    -    contains: [], // defined later
    -    variants: [
    -      {
    -        begin: /\*(?!\*)/,
    -        end: /\*/
    -      },
    -      {
    -        begin: /_(?!_)/,
    -        end: /_/,
    -        relevance: 0
    -      }
    -    ]
    -  };
    -  BOLD.contains.push(ITALIC);
    -  ITALIC.contains.push(BOLD);
    -
    -  let CONTAINABLE = [
    -    INLINE_HTML,
    -    LINK
    -  ];
    -
    -  BOLD.contains = BOLD.contains.concat(CONTAINABLE);
    -  ITALIC.contains = ITALIC.contains.concat(CONTAINABLE);
    -
    -  CONTAINABLE = CONTAINABLE.concat(BOLD, ITALIC);
    -
    -  const HEADER = {
    -    className: 'section',
    -    variants: [
    -      {
    -        begin: '^#{1,6}',
    -        end: '$',
    -        contains: CONTAINABLE
    -      },
    -      {
    -        begin: '(?=^.+?\\n[=-]{2,}$)',
    -        contains: [
    -          {
    -            begin: '^[=-]*$'
    -          },
    -          {
    -            begin: '^',
    -            end: "\\n",
    -            contains: CONTAINABLE
    -          }
    -        ]
    -      }
    -    ]
    -  };
    -
    -  const BLOCKQUOTE = {
    -    className: 'quote',
    -    begin: '^>\\s+',
    -    contains: CONTAINABLE,
    -    end: '$'
    -  };
    -
    -  return {
    -    name: 'Markdown',
    -    aliases: [
    -      'md',
    -      'mkdown',
    -      'mkd'
    -    ],
    -    contains: [
    -      HEADER,
    -      INLINE_HTML,
    -      LIST,
    -      BOLD,
    -      ITALIC,
    -      BLOCKQUOTE,
    -      CODE,
    -      HORIZONTAL_RULE,
    -      LINK,
    -      LINK_REFERENCE
    -    ]
    -  };
    -}
    -
    -module.exports = markdown;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/mathematica.js b/claude-code-source/node_modules/highlight.js/lib/languages/mathematica.js
    deleted file mode 100644
    index f376cb0b..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/mathematica.js
    +++ /dev/null
    @@ -1,6797 +0,0 @@
    -const SYSTEM_SYMBOLS = [
    -  "AASTriangle",
    -  "AbelianGroup",
    -  "Abort",
    -  "AbortKernels",
    -  "AbortProtect",
    -  "AbortScheduledTask",
    -  "Above",
    -  "Abs",
    -  "AbsArg",
    -  "AbsArgPlot",
    -  "Absolute",
    -  "AbsoluteCorrelation",
    -  "AbsoluteCorrelationFunction",
    -  "AbsoluteCurrentValue",
    -  "AbsoluteDashing",
    -  "AbsoluteFileName",
    -  "AbsoluteOptions",
    -  "AbsolutePointSize",
    -  "AbsoluteThickness",
    -  "AbsoluteTime",
    -  "AbsoluteTiming",
    -  "AcceptanceThreshold",
    -  "AccountingForm",
    -  "Accumulate",
    -  "Accuracy",
    -  "AccuracyGoal",
    -  "ActionDelay",
    -  "ActionMenu",
    -  "ActionMenuBox",
    -  "ActionMenuBoxOptions",
    -  "Activate",
    -  "Active",
    -  "ActiveClassification",
    -  "ActiveClassificationObject",
    -  "ActiveItem",
    -  "ActivePrediction",
    -  "ActivePredictionObject",
    -  "ActiveStyle",
    -  "AcyclicGraphQ",
    -  "AddOnHelpPath",
    -  "AddSides",
    -  "AddTo",
    -  "AddToSearchIndex",
    -  "AddUsers",
    -  "AdjacencyGraph",
    -  "AdjacencyList",
    -  "AdjacencyMatrix",
    -  "AdjacentMeshCells",
    -  "AdjustmentBox",
    -  "AdjustmentBoxOptions",
    -  "AdjustTimeSeriesForecast",
    -  "AdministrativeDivisionData",
    -  "AffineHalfSpace",
    -  "AffineSpace",
    -  "AffineStateSpaceModel",
    -  "AffineTransform",
    -  "After",
    -  "AggregatedEntityClass",
    -  "AggregationLayer",
    -  "AircraftData",
    -  "AirportData",
    -  "AirPressureData",
    -  "AirTemperatureData",
    -  "AiryAi",
    -  "AiryAiPrime",
    -  "AiryAiZero",
    -  "AiryBi",
    -  "AiryBiPrime",
    -  "AiryBiZero",
    -  "AlgebraicIntegerQ",
    -  "AlgebraicNumber",
    -  "AlgebraicNumberDenominator",
    -  "AlgebraicNumberNorm",
    -  "AlgebraicNumberPolynomial",
    -  "AlgebraicNumberTrace",
    -  "AlgebraicRules",
    -  "AlgebraicRulesData",
    -  "Algebraics",
    -  "AlgebraicUnitQ",
    -  "Alignment",
    -  "AlignmentMarker",
    -  "AlignmentPoint",
    -  "All",
    -  "AllowAdultContent",
    -  "AllowedCloudExtraParameters",
    -  "AllowedCloudParameterExtensions",
    -  "AllowedDimensions",
    -  "AllowedFrequencyRange",
    -  "AllowedHeads",
    -  "AllowGroupClose",
    -  "AllowIncomplete",
    -  "AllowInlineCells",
    -  "AllowKernelInitialization",
    -  "AllowLooseGrammar",
    -  "AllowReverseGroupClose",
    -  "AllowScriptLevelChange",
    -  "AllowVersionUpdate",
    -  "AllTrue",
    -  "Alphabet",
    -  "AlphabeticOrder",
    -  "AlphabeticSort",
    -  "AlphaChannel",
    -  "AlternateImage",
    -  "AlternatingFactorial",
    -  "AlternatingGroup",
    -  "AlternativeHypothesis",
    -  "Alternatives",
    -  "AltitudeMethod",
    -  "AmbientLight",
    -  "AmbiguityFunction",
    -  "AmbiguityList",
    -  "Analytic",
    -  "AnatomyData",
    -  "AnatomyForm",
    -  "AnatomyPlot3D",
    -  "AnatomySkinStyle",
    -  "AnatomyStyling",
    -  "AnchoredSearch",
    -  "And",
    -  "AndersonDarlingTest",
    -  "AngerJ",
    -  "AngleBisector",
    -  "AngleBracket",
    -  "AnglePath",
    -  "AnglePath3D",
    -  "AngleVector",
    -  "AngularGauge",
    -  "Animate",
    -  "AnimationCycleOffset",
    -  "AnimationCycleRepetitions",
    -  "AnimationDirection",
    -  "AnimationDisplayTime",
    -  "AnimationRate",
    -  "AnimationRepetitions",
    -  "AnimationRunning",
    -  "AnimationRunTime",
    -  "AnimationTimeIndex",
    -  "Animator",
    -  "AnimatorBox",
    -  "AnimatorBoxOptions",
    -  "AnimatorElements",
    -  "Annotate",
    -  "Annotation",
    -  "AnnotationDelete",
    -  "AnnotationKeys",
    -  "AnnotationRules",
    -  "AnnotationValue",
    -  "Annuity",
    -  "AnnuityDue",
    -  "Annulus",
    -  "AnomalyDetection",
    -  "AnomalyDetector",
    -  "AnomalyDetectorFunction",
    -  "Anonymous",
    -  "Antialiasing",
    -  "AntihermitianMatrixQ",
    -  "Antisymmetric",
    -  "AntisymmetricMatrixQ",
    -  "Antonyms",
    -  "AnyOrder",
    -  "AnySubset",
    -  "AnyTrue",
    -  "Apart",
    -  "ApartSquareFree",
    -  "APIFunction",
    -  "Appearance",
    -  "AppearanceElements",
    -  "AppearanceRules",
    -  "AppellF1",
    -  "Append",
    -  "AppendCheck",
    -  "AppendLayer",
    -  "AppendTo",
    -  "Apply",
    -  "ApplySides",
    -  "ArcCos",
    -  "ArcCosh",
    -  "ArcCot",
    -  "ArcCoth",
    -  "ArcCsc",
    -  "ArcCsch",
    -  "ArcCurvature",
    -  "ARCHProcess",
    -  "ArcLength",
    -  "ArcSec",
    -  "ArcSech",
    -  "ArcSin",
    -  "ArcSinDistribution",
    -  "ArcSinh",
    -  "ArcTan",
    -  "ArcTanh",
    -  "Area",
    -  "Arg",
    -  "ArgMax",
    -  "ArgMin",
    -  "ArgumentCountQ",
    -  "ARIMAProcess",
    -  "ArithmeticGeometricMean",
    -  "ARMAProcess",
    -  "Around",
    -  "AroundReplace",
    -  "ARProcess",
    -  "Array",
    -  "ArrayComponents",
    -  "ArrayDepth",
    -  "ArrayFilter",
    -  "ArrayFlatten",
    -  "ArrayMesh",
    -  "ArrayPad",
    -  "ArrayPlot",
    -  "ArrayQ",
    -  "ArrayResample",
    -  "ArrayReshape",
    -  "ArrayRules",
    -  "Arrays",
    -  "Arrow",
    -  "Arrow3DBox",
    -  "ArrowBox",
    -  "Arrowheads",
    -  "ASATriangle",
    -  "Ask",
    -  "AskAppend",
    -  "AskConfirm",
    -  "AskDisplay",
    -  "AskedQ",
    -  "AskedValue",
    -  "AskFunction",
    -  "AskState",
    -  "AskTemplateDisplay",
    -  "AspectRatio",
    -  "AspectRatioFixed",
    -  "Assert",
    -  "AssociateTo",
    -  "Association",
    -  "AssociationFormat",
    -  "AssociationMap",
    -  "AssociationQ",
    -  "AssociationThread",
    -  "AssumeDeterministic",
    -  "Assuming",
    -  "Assumptions",
    -  "AstronomicalData",
    -  "Asymptotic",
    -  "AsymptoticDSolveValue",
    -  "AsymptoticEqual",
    -  "AsymptoticEquivalent",
    -  "AsymptoticGreater",
    -  "AsymptoticGreaterEqual",
    -  "AsymptoticIntegrate",
    -  "AsymptoticLess",
    -  "AsymptoticLessEqual",
    -  "AsymptoticOutputTracker",
    -  "AsymptoticProduct",
    -  "AsymptoticRSolveValue",
    -  "AsymptoticSolve",
    -  "AsymptoticSum",
    -  "Asynchronous",
    -  "AsynchronousTaskObject",
    -  "AsynchronousTasks",
    -  "Atom",
    -  "AtomCoordinates",
    -  "AtomCount",
    -  "AtomDiagramCoordinates",
    -  "AtomList",
    -  "AtomQ",
    -  "AttentionLayer",
    -  "Attributes",
    -  "Audio",
    -  "AudioAmplify",
    -  "AudioAnnotate",
    -  "AudioAnnotationLookup",
    -  "AudioBlockMap",
    -  "AudioCapture",
    -  "AudioChannelAssignment",
    -  "AudioChannelCombine",
    -  "AudioChannelMix",
    -  "AudioChannels",
    -  "AudioChannelSeparate",
    -  "AudioData",
    -  "AudioDelay",
    -  "AudioDelete",
    -  "AudioDevice",
    -  "AudioDistance",
    -  "AudioEncoding",
    -  "AudioFade",
    -  "AudioFrequencyShift",
    -  "AudioGenerator",
    -  "AudioIdentify",
    -  "AudioInputDevice",
    -  "AudioInsert",
    -  "AudioInstanceQ",
    -  "AudioIntervals",
    -  "AudioJoin",
    -  "AudioLabel",
    -  "AudioLength",
    -  "AudioLocalMeasurements",
    -  "AudioLooping",
    -  "AudioLoudness",
    -  "AudioMeasurements",
    -  "AudioNormalize",
    -  "AudioOutputDevice",
    -  "AudioOverlay",
    -  "AudioPad",
    -  "AudioPan",
    -  "AudioPartition",
    -  "AudioPause",
    -  "AudioPitchShift",
    -  "AudioPlay",
    -  "AudioPlot",
    -  "AudioQ",
    -  "AudioRecord",
    -  "AudioReplace",
    -  "AudioResample",
    -  "AudioReverb",
    -  "AudioReverse",
    -  "AudioSampleRate",
    -  "AudioSpectralMap",
    -  "AudioSpectralTransformation",
    -  "AudioSplit",
    -  "AudioStop",
    -  "AudioStream",
    -  "AudioStreams",
    -  "AudioTimeStretch",
    -  "AudioTracks",
    -  "AudioTrim",
    -  "AudioType",
    -  "AugmentedPolyhedron",
    -  "AugmentedSymmetricPolynomial",
    -  "Authenticate",
    -  "Authentication",
    -  "AuthenticationDialog",
    -  "AutoAction",
    -  "Autocomplete",
    -  "AutocompletionFunction",
    -  "AutoCopy",
    -  "AutocorrelationTest",
    -  "AutoDelete",
    -  "AutoEvaluateEvents",
    -  "AutoGeneratedPackage",
    -  "AutoIndent",
    -  "AutoIndentSpacings",
    -  "AutoItalicWords",
    -  "AutoloadPath",
    -  "AutoMatch",
    -  "Automatic",
    -  "AutomaticImageSize",
    -  "AutoMultiplicationSymbol",
    -  "AutoNumberFormatting",
    -  "AutoOpenNotebooks",
    -  "AutoOpenPalettes",
    -  "AutoQuoteCharacters",
    -  "AutoRefreshed",
    -  "AutoRemove",
    -  "AutorunSequencing",
    -  "AutoScaling",
    -  "AutoScroll",
    -  "AutoSpacing",
    -  "AutoStyleOptions",
    -  "AutoStyleWords",
    -  "AutoSubmitting",
    -  "Axes",
    -  "AxesEdge",
    -  "AxesLabel",
    -  "AxesOrigin",
    -  "AxesStyle",
    -  "AxiomaticTheory",
    -  "Axis",
    -  "BabyMonsterGroupB",
    -  "Back",
    -  "Background",
    -  "BackgroundAppearance",
    -  "BackgroundTasksSettings",
    -  "Backslash",
    -  "Backsubstitution",
    -  "Backward",
    -  "Ball",
    -  "Band",
    -  "BandpassFilter",
    -  "BandstopFilter",
    -  "BarabasiAlbertGraphDistribution",
    -  "BarChart",
    -  "BarChart3D",
    -  "BarcodeImage",
    -  "BarcodeRecognize",
    -  "BaringhausHenzeTest",
    -  "BarLegend",
    -  "BarlowProschanImportance",
    -  "BarnesG",
    -  "BarOrigin",
    -  "BarSpacing",
    -  "BartlettHannWindow",
    -  "BartlettWindow",
    -  "BaseDecode",
    -  "BaseEncode",
    -  "BaseForm",
    -  "Baseline",
    -  "BaselinePosition",
    -  "BaseStyle",
    -  "BasicRecurrentLayer",
    -  "BatchNormalizationLayer",
    -  "BatchSize",
    -  "BatesDistribution",
    -  "BattleLemarieWavelet",
    -  "BayesianMaximization",
    -  "BayesianMaximizationObject",
    -  "BayesianMinimization",
    -  "BayesianMinimizationObject",
    -  "Because",
    -  "BeckmannDistribution",
    -  "Beep",
    -  "Before",
    -  "Begin",
    -  "BeginDialogPacket",
    -  "BeginFrontEndInteractionPacket",
    -  "BeginPackage",
    -  "BellB",
    -  "BellY",
    -  "Below",
    -  "BenfordDistribution",
    -  "BeniniDistribution",
    -  "BenktanderGibratDistribution",
    -  "BenktanderWeibullDistribution",
    -  "BernoulliB",
    -  "BernoulliDistribution",
    -  "BernoulliGraphDistribution",
    -  "BernoulliProcess",
    -  "BernsteinBasis",
    -  "BesselFilterModel",
    -  "BesselI",
    -  "BesselJ",
    -  "BesselJZero",
    -  "BesselK",
    -  "BesselY",
    -  "BesselYZero",
    -  "Beta",
    -  "BetaBinomialDistribution",
    -  "BetaDistribution",
    -  "BetaNegativeBinomialDistribution",
    -  "BetaPrimeDistribution",
    -  "BetaRegularized",
    -  "Between",
    -  "BetweennessCentrality",
    -  "BeveledPolyhedron",
    -  "BezierCurve",
    -  "BezierCurve3DBox",
    -  "BezierCurve3DBoxOptions",
    -  "BezierCurveBox",
    -  "BezierCurveBoxOptions",
    -  "BezierFunction",
    -  "BilateralFilter",
    -  "Binarize",
    -  "BinaryDeserialize",
    -  "BinaryDistance",
    -  "BinaryFormat",
    -  "BinaryImageQ",
    -  "BinaryRead",
    -  "BinaryReadList",
    -  "BinarySerialize",
    -  "BinaryWrite",
    -  "BinCounts",
    -  "BinLists",
    -  "Binomial",
    -  "BinomialDistribution",
    -  "BinomialProcess",
    -  "BinormalDistribution",
    -  "BiorthogonalSplineWavelet",
    -  "BipartiteGraphQ",
    -  "BiquadraticFilterModel",
    -  "BirnbaumImportance",
    -  "BirnbaumSaundersDistribution",
    -  "BitAnd",
    -  "BitClear",
    -  "BitGet",
    -  "BitLength",
    -  "BitNot",
    -  "BitOr",
    -  "BitSet",
    -  "BitShiftLeft",
    -  "BitShiftRight",
    -  "BitXor",
    -  "BiweightLocation",
    -  "BiweightMidvariance",
    -  "Black",
    -  "BlackmanHarrisWindow",
    -  "BlackmanNuttallWindow",
    -  "BlackmanWindow",
    -  "Blank",
    -  "BlankForm",
    -  "BlankNullSequence",
    -  "BlankSequence",
    -  "Blend",
    -  "Block",
    -  "BlockchainAddressData",
    -  "BlockchainBase",
    -  "BlockchainBlockData",
    -  "BlockchainContractValue",
    -  "BlockchainData",
    -  "BlockchainGet",
    -  "BlockchainKeyEncode",
    -  "BlockchainPut",
    -  "BlockchainTokenData",
    -  "BlockchainTransaction",
    -  "BlockchainTransactionData",
    -  "BlockchainTransactionSign",
    -  "BlockchainTransactionSubmit",
    -  "BlockMap",
    -  "BlockRandom",
    -  "BlomqvistBeta",
    -  "BlomqvistBetaTest",
    -  "Blue",
    -  "Blur",
    -  "BodePlot",
    -  "BohmanWindow",
    -  "Bold",
    -  "Bond",
    -  "BondCount",
    -  "BondList",
    -  "BondQ",
    -  "Bookmarks",
    -  "Boole",
    -  "BooleanConsecutiveFunction",
    -  "BooleanConvert",
    -  "BooleanCountingFunction",
    -  "BooleanFunction",
    -  "BooleanGraph",
    -  "BooleanMaxterms",
    -  "BooleanMinimize",
    -  "BooleanMinterms",
    -  "BooleanQ",
    -  "BooleanRegion",
    -  "Booleans",
    -  "BooleanStrings",
    -  "BooleanTable",
    -  "BooleanVariables",
    -  "BorderDimensions",
    -  "BorelTannerDistribution",
    -  "Bottom",
    -  "BottomHatTransform",
    -  "BoundaryDiscretizeGraphics",
    -  "BoundaryDiscretizeRegion",
    -  "BoundaryMesh",
    -  "BoundaryMeshRegion",
    -  "BoundaryMeshRegionQ",
    -  "BoundaryStyle",
    -  "BoundedRegionQ",
    -  "BoundingRegion",
    -  "Bounds",
    -  "Box",
    -  "BoxBaselineShift",
    -  "BoxData",
    -  "BoxDimensions",
    -  "Boxed",
    -  "Boxes",
    -  "BoxForm",
    -  "BoxFormFormatTypes",
    -  "BoxFrame",
    -  "BoxID",
    -  "BoxMargins",
    -  "BoxMatrix",
    -  "BoxObject",
    -  "BoxRatios",
    -  "BoxRotation",
    -  "BoxRotationPoint",
    -  "BoxStyle",
    -  "BoxWhiskerChart",
    -  "Bra",
    -  "BracketingBar",
    -  "BraKet",
    -  "BrayCurtisDistance",
    -  "BreadthFirstScan",
    -  "Break",
    -  "BridgeData",
    -  "BrightnessEqualize",
    -  "BroadcastStationData",
    -  "Brown",
    -  "BrownForsytheTest",
    -  "BrownianBridgeProcess",
    -  "BrowserCategory",
    -  "BSplineBasis",
    -  "BSplineCurve",
    -  "BSplineCurve3DBox",
    -  "BSplineCurve3DBoxOptions",
    -  "BSplineCurveBox",
    -  "BSplineCurveBoxOptions",
    -  "BSplineFunction",
    -  "BSplineSurface",
    -  "BSplineSurface3DBox",
    -  "BSplineSurface3DBoxOptions",
    -  "BubbleChart",
    -  "BubbleChart3D",
    -  "BubbleScale",
    -  "BubbleSizes",
    -  "BuildingData",
    -  "BulletGauge",
    -  "BusinessDayQ",
    -  "ButterflyGraph",
    -  "ButterworthFilterModel",
    -  "Button",
    -  "ButtonBar",
    -  "ButtonBox",
    -  "ButtonBoxOptions",
    -  "ButtonCell",
    -  "ButtonContents",
    -  "ButtonData",
    -  "ButtonEvaluator",
    -  "ButtonExpandable",
    -  "ButtonFrame",
    -  "ButtonFunction",
    -  "ButtonMargins",
    -  "ButtonMinHeight",
    -  "ButtonNote",
    -  "ButtonNotebook",
    -  "ButtonSource",
    -  "ButtonStyle",
    -  "ButtonStyleMenuListing",
    -  "Byte",
    -  "ByteArray",
    -  "ByteArrayFormat",
    -  "ByteArrayQ",
    -  "ByteArrayToString",
    -  "ByteCount",
    -  "ByteOrdering",
    -  "C",
    -  "CachedValue",
    -  "CacheGraphics",
    -  "CachePersistence",
    -  "CalendarConvert",
    -  "CalendarData",
    -  "CalendarType",
    -  "Callout",
    -  "CalloutMarker",
    -  "CalloutStyle",
    -  "CallPacket",
    -  "CanberraDistance",
    -  "Cancel",
    -  "CancelButton",
    -  "CandlestickChart",
    -  "CanonicalGraph",
    -  "CanonicalizePolygon",
    -  "CanonicalizePolyhedron",
    -  "CanonicalName",
    -  "CanonicalWarpingCorrespondence",
    -  "CanonicalWarpingDistance",
    -  "CantorMesh",
    -  "CantorStaircase",
    -  "Cap",
    -  "CapForm",
    -  "CapitalDifferentialD",
    -  "Capitalize",
    -  "CapsuleShape",
    -  "CaptureRunning",
    -  "CardinalBSplineBasis",
    -  "CarlemanLinearize",
    -  "CarmichaelLambda",
    -  "CaseOrdering",
    -  "Cases",
    -  "CaseSensitive",
    -  "Cashflow",
    -  "Casoratian",
    -  "Catalan",
    -  "CatalanNumber",
    -  "Catch",
    -  "CategoricalDistribution",
    -  "Catenate",
    -  "CatenateLayer",
    -  "CauchyDistribution",
    -  "CauchyWindow",
    -  "CayleyGraph",
    -  "CDF",
    -  "CDFDeploy",
    -  "CDFInformation",
    -  "CDFWavelet",
    -  "Ceiling",
    -  "CelestialSystem",
    -  "Cell",
    -  "CellAutoOverwrite",
    -  "CellBaseline",
    -  "CellBoundingBox",
    -  "CellBracketOptions",
    -  "CellChangeTimes",
    -  "CellContents",
    -  "CellContext",
    -  "CellDingbat",
    -  "CellDynamicExpression",
    -  "CellEditDuplicate",
    -  "CellElementsBoundingBox",
    -  "CellElementSpacings",
    -  "CellEpilog",
    -  "CellEvaluationDuplicate",
    -  "CellEvaluationFunction",
    -  "CellEvaluationLanguage",
    -  "CellEventActions",
    -  "CellFrame",
    -  "CellFrameColor",
    -  "CellFrameLabelMargins",
    -  "CellFrameLabels",
    -  "CellFrameMargins",
    -  "CellGroup",
    -  "CellGroupData",
    -  "CellGrouping",
    -  "CellGroupingRules",
    -  "CellHorizontalScrolling",
    -  "CellID",
    -  "CellLabel",
    -  "CellLabelAutoDelete",
    -  "CellLabelMargins",
    -  "CellLabelPositioning",
    -  "CellLabelStyle",
    -  "CellLabelTemplate",
    -  "CellMargins",
    -  "CellObject",
    -  "CellOpen",
    -  "CellPrint",
    -  "CellProlog",
    -  "Cells",
    -  "CellSize",
    -  "CellStyle",
    -  "CellTags",
    -  "CellularAutomaton",
    -  "CensoredDistribution",
    -  "Censoring",
    -  "Center",
    -  "CenterArray",
    -  "CenterDot",
    -  "CentralFeature",
    -  "CentralMoment",
    -  "CentralMomentGeneratingFunction",
    -  "Cepstrogram",
    -  "CepstrogramArray",
    -  "CepstrumArray",
    -  "CForm",
    -  "ChampernowneNumber",
    -  "ChangeOptions",
    -  "ChannelBase",
    -  "ChannelBrokerAction",
    -  "ChannelDatabin",
    -  "ChannelHistoryLength",
    -  "ChannelListen",
    -  "ChannelListener",
    -  "ChannelListeners",
    -  "ChannelListenerWait",
    -  "ChannelObject",
    -  "ChannelPreSendFunction",
    -  "ChannelReceiverFunction",
    -  "ChannelSend",
    -  "ChannelSubscribers",
    -  "ChanVeseBinarize",
    -  "Character",
    -  "CharacterCounts",
    -  "CharacterEncoding",
    -  "CharacterEncodingsPath",
    -  "CharacteristicFunction",
    -  "CharacteristicPolynomial",
    -  "CharacterName",
    -  "CharacterNormalize",
    -  "CharacterRange",
    -  "Characters",
    -  "ChartBaseStyle",
    -  "ChartElementData",
    -  "ChartElementDataFunction",
    -  "ChartElementFunction",
    -  "ChartElements",
    -  "ChartLabels",
    -  "ChartLayout",
    -  "ChartLegends",
    -  "ChartStyle",
    -  "Chebyshev1FilterModel",
    -  "Chebyshev2FilterModel",
    -  "ChebyshevDistance",
    -  "ChebyshevT",
    -  "ChebyshevU",
    -  "Check",
    -  "CheckAbort",
    -  "CheckAll",
    -  "Checkbox",
    -  "CheckboxBar",
    -  "CheckboxBox",
    -  "CheckboxBoxOptions",
    -  "ChemicalData",
    -  "ChessboardDistance",
    -  "ChiDistribution",
    -  "ChineseRemainder",
    -  "ChiSquareDistribution",
    -  "ChoiceButtons",
    -  "ChoiceDialog",
    -  "CholeskyDecomposition",
    -  "Chop",
    -  "ChromaticityPlot",
    -  "ChromaticityPlot3D",
    -  "ChromaticPolynomial",
    -  "Circle",
    -  "CircleBox",
    -  "CircleDot",
    -  "CircleMinus",
    -  "CirclePlus",
    -  "CirclePoints",
    -  "CircleThrough",
    -  "CircleTimes",
    -  "CirculantGraph",
    -  "CircularOrthogonalMatrixDistribution",
    -  "CircularQuaternionMatrixDistribution",
    -  "CircularRealMatrixDistribution",
    -  "CircularSymplecticMatrixDistribution",
    -  "CircularUnitaryMatrixDistribution",
    -  "Circumsphere",
    -  "CityData",
    -  "ClassifierFunction",
    -  "ClassifierInformation",
    -  "ClassifierMeasurements",
    -  "ClassifierMeasurementsObject",
    -  "Classify",
    -  "ClassPriors",
    -  "Clear",
    -  "ClearAll",
    -  "ClearAttributes",
    -  "ClearCookies",
    -  "ClearPermissions",
    -  "ClearSystemCache",
    -  "ClebschGordan",
    -  "ClickPane",
    -  "Clip",
    -  "ClipboardNotebook",
    -  "ClipFill",
    -  "ClippingStyle",
    -  "ClipPlanes",
    -  "ClipPlanesStyle",
    -  "ClipRange",
    -  "Clock",
    -  "ClockGauge",
    -  "ClockwiseContourIntegral",
    -  "Close",
    -  "Closed",
    -  "CloseKernels",
    -  "ClosenessCentrality",
    -  "Closing",
    -  "ClosingAutoSave",
    -  "ClosingEvent",
    -  "ClosingSaveDialog",
    -  "CloudAccountData",
    -  "CloudBase",
    -  "CloudConnect",
    -  "CloudConnections",
    -  "CloudDeploy",
    -  "CloudDirectory",
    -  "CloudDisconnect",
    -  "CloudEvaluate",
    -  "CloudExport",
    -  "CloudExpression",
    -  "CloudExpressions",
    -  "CloudFunction",
    -  "CloudGet",
    -  "CloudImport",
    -  "CloudLoggingData",
    -  "CloudObject",
    -  "CloudObjectInformation",
    -  "CloudObjectInformationData",
    -  "CloudObjectNameFormat",
    -  "CloudObjects",
    -  "CloudObjectURLType",
    -  "CloudPublish",
    -  "CloudPut",
    -  "CloudRenderingMethod",
    -  "CloudSave",
    -  "CloudShare",
    -  "CloudSubmit",
    -  "CloudSymbol",
    -  "CloudUnshare",
    -  "CloudUserID",
    -  "ClusterClassify",
    -  "ClusterDissimilarityFunction",
    -  "ClusteringComponents",
    -  "ClusteringTree",
    -  "CMYKColor",
    -  "Coarse",
    -  "CodeAssistOptions",
    -  "Coefficient",
    -  "CoefficientArrays",
    -  "CoefficientDomain",
    -  "CoefficientList",
    -  "CoefficientRules",
    -  "CoifletWavelet",
    -  "Collect",
    -  "Colon",
    -  "ColonForm",
    -  "ColorBalance",
    -  "ColorCombine",
    -  "ColorConvert",
    -  "ColorCoverage",
    -  "ColorData",
    -  "ColorDataFunction",
    -  "ColorDetect",
    -  "ColorDistance",
    -  "ColorFunction",
    -  "ColorFunctionScaling",
    -  "Colorize",
    -  "ColorNegate",
    -  "ColorOutput",
    -  "ColorProfileData",
    -  "ColorQ",
    -  "ColorQuantize",
    -  "ColorReplace",
    -  "ColorRules",
    -  "ColorSelectorSettings",
    -  "ColorSeparate",
    -  "ColorSetter",
    -  "ColorSetterBox",
    -  "ColorSetterBoxOptions",
    -  "ColorSlider",
    -  "ColorsNear",
    -  "ColorSpace",
    -  "ColorToneMapping",
    -  "Column",
    -  "ColumnAlignments",
    -  "ColumnBackgrounds",
    -  "ColumnForm",
    -  "ColumnLines",
    -  "ColumnsEqual",
    -  "ColumnSpacings",
    -  "ColumnWidths",
    -  "CombinedEntityClass",
    -  "CombinerFunction",
    -  "CometData",
    -  "CommonDefaultFormatTypes",
    -  "Commonest",
    -  "CommonestFilter",
    -  "CommonName",
    -  "CommonUnits",
    -  "CommunityBoundaryStyle",
    -  "CommunityGraphPlot",
    -  "CommunityLabels",
    -  "CommunityRegionStyle",
    -  "CompanyData",
    -  "CompatibleUnitQ",
    -  "CompilationOptions",
    -  "CompilationTarget",
    -  "Compile",
    -  "Compiled",
    -  "CompiledCodeFunction",
    -  "CompiledFunction",
    -  "CompilerOptions",
    -  "Complement",
    -  "ComplementedEntityClass",
    -  "CompleteGraph",
    -  "CompleteGraphQ",
    -  "CompleteKaryTree",
    -  "CompletionsListPacket",
    -  "Complex",
    -  "ComplexContourPlot",
    -  "Complexes",
    -  "ComplexExpand",
    -  "ComplexInfinity",
    -  "ComplexityFunction",
    -  "ComplexListPlot",
    -  "ComplexPlot",
    -  "ComplexPlot3D",
    -  "ComplexRegionPlot",
    -  "ComplexStreamPlot",
    -  "ComplexVectorPlot",
    -  "ComponentMeasurements",
    -  "ComponentwiseContextMenu",
    -  "Compose",
    -  "ComposeList",
    -  "ComposeSeries",
    -  "CompositeQ",
    -  "Composition",
    -  "CompoundElement",
    -  "CompoundExpression",
    -  "CompoundPoissonDistribution",
    -  "CompoundPoissonProcess",
    -  "CompoundRenewalProcess",
    -  "Compress",
    -  "CompressedData",
    -  "CompressionLevel",
    -  "ComputeUncertainty",
    -  "Condition",
    -  "ConditionalExpression",
    -  "Conditioned",
    -  "Cone",
    -  "ConeBox",
    -  "ConfidenceLevel",
    -  "ConfidenceRange",
    -  "ConfidenceTransform",
    -  "ConfigurationPath",
    -  "ConformAudio",
    -  "ConformImages",
    -  "Congruent",
    -  "ConicHullRegion",
    -  "ConicHullRegion3DBox",
    -  "ConicHullRegionBox",
    -  "ConicOptimization",
    -  "Conjugate",
    -  "ConjugateTranspose",
    -  "Conjunction",
    -  "Connect",
    -  "ConnectedComponents",
    -  "ConnectedGraphComponents",
    -  "ConnectedGraphQ",
    -  "ConnectedMeshComponents",
    -  "ConnectedMoleculeComponents",
    -  "ConnectedMoleculeQ",
    -  "ConnectionSettings",
    -  "ConnectLibraryCallbackFunction",
    -  "ConnectSystemModelComponents",
    -  "ConnesWindow",
    -  "ConoverTest",
    -  "ConsoleMessage",
    -  "ConsoleMessagePacket",
    -  "Constant",
    -  "ConstantArray",
    -  "ConstantArrayLayer",
    -  "ConstantImage",
    -  "ConstantPlusLayer",
    -  "ConstantRegionQ",
    -  "Constants",
    -  "ConstantTimesLayer",
    -  "ConstellationData",
    -  "ConstrainedMax",
    -  "ConstrainedMin",
    -  "Construct",
    -  "Containing",
    -  "ContainsAll",
    -  "ContainsAny",
    -  "ContainsExactly",
    -  "ContainsNone",
    -  "ContainsOnly",
    -  "ContentFieldOptions",
    -  "ContentLocationFunction",
    -  "ContentObject",
    -  "ContentPadding",
    -  "ContentsBoundingBox",
    -  "ContentSelectable",
    -  "ContentSize",
    -  "Context",
    -  "ContextMenu",
    -  "Contexts",
    -  "ContextToFileName",
    -  "Continuation",
    -  "Continue",
    -  "ContinuedFraction",
    -  "ContinuedFractionK",
    -  "ContinuousAction",
    -  "ContinuousMarkovProcess",
    -  "ContinuousTask",
    -  "ContinuousTimeModelQ",
    -  "ContinuousWaveletData",
    -  "ContinuousWaveletTransform",
    -  "ContourDetect",
    -  "ContourGraphics",
    -  "ContourIntegral",
    -  "ContourLabels",
    -  "ContourLines",
    -  "ContourPlot",
    -  "ContourPlot3D",
    -  "Contours",
    -  "ContourShading",
    -  "ContourSmoothing",
    -  "ContourStyle",
    -  "ContraharmonicMean",
    -  "ContrastiveLossLayer",
    -  "Control",
    -  "ControlActive",
    -  "ControlAlignment",
    -  "ControlGroupContentsBox",
    -  "ControllabilityGramian",
    -  "ControllabilityMatrix",
    -  "ControllableDecomposition",
    -  "ControllableModelQ",
    -  "ControllerDuration",
    -  "ControllerInformation",
    -  "ControllerInformationData",
    -  "ControllerLinking",
    -  "ControllerManipulate",
    -  "ControllerMethod",
    -  "ControllerPath",
    -  "ControllerState",
    -  "ControlPlacement",
    -  "ControlsRendering",
    -  "ControlType",
    -  "Convergents",
    -  "ConversionOptions",
    -  "ConversionRules",
    -  "ConvertToBitmapPacket",
    -  "ConvertToPostScript",
    -  "ConvertToPostScriptPacket",
    -  "ConvexHullMesh",
    -  "ConvexPolygonQ",
    -  "ConvexPolyhedronQ",
    -  "ConvolutionLayer",
    -  "Convolve",
    -  "ConwayGroupCo1",
    -  "ConwayGroupCo2",
    -  "ConwayGroupCo3",
    -  "CookieFunction",
    -  "Cookies",
    -  "CoordinateBoundingBox",
    -  "CoordinateBoundingBoxArray",
    -  "CoordinateBounds",
    -  "CoordinateBoundsArray",
    -  "CoordinateChartData",
    -  "CoordinatesToolOptions",
    -  "CoordinateTransform",
    -  "CoordinateTransformData",
    -  "CoprimeQ",
    -  "Coproduct",
    -  "CopulaDistribution",
    -  "Copyable",
    -  "CopyDatabin",
    -  "CopyDirectory",
    -  "CopyFile",
    -  "CopyTag",
    -  "CopyToClipboard",
    -  "CornerFilter",
    -  "CornerNeighbors",
    -  "Correlation",
    -  "CorrelationDistance",
    -  "CorrelationFunction",
    -  "CorrelationTest",
    -  "Cos",
    -  "Cosh",
    -  "CoshIntegral",
    -  "CosineDistance",
    -  "CosineWindow",
    -  "CosIntegral",
    -  "Cot",
    -  "Coth",
    -  "Count",
    -  "CountDistinct",
    -  "CountDistinctBy",
    -  "CounterAssignments",
    -  "CounterBox",
    -  "CounterBoxOptions",
    -  "CounterClockwiseContourIntegral",
    -  "CounterEvaluator",
    -  "CounterFunction",
    -  "CounterIncrements",
    -  "CounterStyle",
    -  "CounterStyleMenuListing",
    -  "CountRoots",
    -  "CountryData",
    -  "Counts",
    -  "CountsBy",
    -  "Covariance",
    -  "CovarianceEstimatorFunction",
    -  "CovarianceFunction",
    -  "CoxianDistribution",
    -  "CoxIngersollRossProcess",
    -  "CoxModel",
    -  "CoxModelFit",
    -  "CramerVonMisesTest",
    -  "CreateArchive",
    -  "CreateCellID",
    -  "CreateChannel",
    -  "CreateCloudExpression",
    -  "CreateDatabin",
    -  "CreateDataStructure",
    -  "CreateDataSystemModel",
    -  "CreateDialog",
    -  "CreateDirectory",
    -  "CreateDocument",
    -  "CreateFile",
    -  "CreateIntermediateDirectories",
    -  "CreateManagedLibraryExpression",
    -  "CreateNotebook",
    -  "CreatePacletArchive",
    -  "CreatePalette",
    -  "CreatePalettePacket",
    -  "CreatePermissionsGroup",
    -  "CreateScheduledTask",
    -  "CreateSearchIndex",
    -  "CreateSystemModel",
    -  "CreateTemporary",
    -  "CreateUUID",
    -  "CreateWindow",
    -  "CriterionFunction",
    -  "CriticalityFailureImportance",
    -  "CriticalitySuccessImportance",
    -  "CriticalSection",
    -  "Cross",
    -  "CrossEntropyLossLayer",
    -  "CrossingCount",
    -  "CrossingDetect",
    -  "CrossingPolygon",
    -  "CrossMatrix",
    -  "Csc",
    -  "Csch",
    -  "CTCLossLayer",
    -  "Cube",
    -  "CubeRoot",
    -  "Cubics",
    -  "Cuboid",
    -  "CuboidBox",
    -  "Cumulant",
    -  "CumulantGeneratingFunction",
    -  "Cup",
    -  "CupCap",
    -  "Curl",
    -  "CurlyDoubleQuote",
    -  "CurlyQuote",
    -  "CurrencyConvert",
    -  "CurrentDate",
    -  "CurrentImage",
    -  "CurrentlySpeakingPacket",
    -  "CurrentNotebookImage",
    -  "CurrentScreenImage",
    -  "CurrentValue",
    -  "Curry",
    -  "CurryApplied",
    -  "CurvatureFlowFilter",
    -  "CurveClosed",
    -  "Cyan",
    -  "CycleGraph",
    -  "CycleIndexPolynomial",
    -  "Cycles",
    -  "CyclicGroup",
    -  "Cyclotomic",
    -  "Cylinder",
    -  "CylinderBox",
    -  "CylindricalDecomposition",
    -  "D",
    -  "DagumDistribution",
    -  "DamData",
    -  "DamerauLevenshteinDistance",
    -  "DampingFactor",
    -  "Darker",
    -  "Dashed",
    -  "Dashing",
    -  "DatabaseConnect",
    -  "DatabaseDisconnect",
    -  "DatabaseReference",
    -  "Databin",
    -  "DatabinAdd",
    -  "DatabinRemove",
    -  "Databins",
    -  "DatabinUpload",
    -  "DataCompression",
    -  "DataDistribution",
    -  "DataRange",
    -  "DataReversed",
    -  "Dataset",
    -  "DatasetDisplayPanel",
    -  "DataStructure",
    -  "DataStructureQ",
    -  "Date",
    -  "DateBounds",
    -  "Dated",
    -  "DateDelimiters",
    -  "DateDifference",
    -  "DatedUnit",
    -  "DateFormat",
    -  "DateFunction",
    -  "DateHistogram",
    -  "DateInterval",
    -  "DateList",
    -  "DateListLogPlot",
    -  "DateListPlot",
    -  "DateListStepPlot",
    -  "DateObject",
    -  "DateObjectQ",
    -  "DateOverlapsQ",
    -  "DatePattern",
    -  "DatePlus",
    -  "DateRange",
    -  "DateReduction",
    -  "DateString",
    -  "DateTicksFormat",
    -  "DateValue",
    -  "DateWithinQ",
    -  "DaubechiesWavelet",
    -  "DavisDistribution",
    -  "DawsonF",
    -  "DayCount",
    -  "DayCountConvention",
    -  "DayHemisphere",
    -  "DaylightQ",
    -  "DayMatchQ",
    -  "DayName",
    -  "DayNightTerminator",
    -  "DayPlus",
    -  "DayRange",
    -  "DayRound",
    -  "DeBruijnGraph",
    -  "DeBruijnSequence",
    -  "Debug",
    -  "DebugTag",
    -  "Decapitalize",
    -  "Decimal",
    -  "DecimalForm",
    -  "DeclareKnownSymbols",
    -  "DeclarePackage",
    -  "Decompose",
    -  "DeconvolutionLayer",
    -  "Decrement",
    -  "Decrypt",
    -  "DecryptFile",
    -  "DedekindEta",
    -  "DeepSpaceProbeData",
    -  "Default",
    -  "DefaultAxesStyle",
    -  "DefaultBaseStyle",
    -  "DefaultBoxStyle",
    -  "DefaultButton",
    -  "DefaultColor",
    -  "DefaultControlPlacement",
    -  "DefaultDuplicateCellStyle",
    -  "DefaultDuration",
    -  "DefaultElement",
    -  "DefaultFaceGridsStyle",
    -  "DefaultFieldHintStyle",
    -  "DefaultFont",
    -  "DefaultFontProperties",
    -  "DefaultFormatType",
    -  "DefaultFormatTypeForStyle",
    -  "DefaultFrameStyle",
    -  "DefaultFrameTicksStyle",
    -  "DefaultGridLinesStyle",
    -  "DefaultInlineFormatType",
    -  "DefaultInputFormatType",
    -  "DefaultLabelStyle",
    -  "DefaultMenuStyle",
    -  "DefaultNaturalLanguage",
    -  "DefaultNewCellStyle",
    -  "DefaultNewInlineCellStyle",
    -  "DefaultNotebook",
    -  "DefaultOptions",
    -  "DefaultOutputFormatType",
    -  "DefaultPrintPrecision",
    -  "DefaultStyle",
    -  "DefaultStyleDefinitions",
    -  "DefaultTextFormatType",
    -  "DefaultTextInlineFormatType",
    -  "DefaultTicksStyle",
    -  "DefaultTooltipStyle",
    -  "DefaultValue",
    -  "DefaultValues",
    -  "Defer",
    -  "DefineExternal",
    -  "DefineInputStreamMethod",
    -  "DefineOutputStreamMethod",
    -  "DefineResourceFunction",
    -  "Definition",
    -  "Degree",
    -  "DegreeCentrality",
    -  "DegreeGraphDistribution",
    -  "DegreeLexicographic",
    -  "DegreeReverseLexicographic",
    -  "DEigensystem",
    -  "DEigenvalues",
    -  "Deinitialization",
    -  "Del",
    -  "DelaunayMesh",
    -  "Delayed",
    -  "Deletable",
    -  "Delete",
    -  "DeleteAnomalies",
    -  "DeleteBorderComponents",
    -  "DeleteCases",
    -  "DeleteChannel",
    -  "DeleteCloudExpression",
    -  "DeleteContents",
    -  "DeleteDirectory",
    -  "DeleteDuplicates",
    -  "DeleteDuplicatesBy",
    -  "DeleteFile",
    -  "DeleteMissing",
    -  "DeleteObject",
    -  "DeletePermissionsKey",
    -  "DeleteSearchIndex",
    -  "DeleteSmallComponents",
    -  "DeleteStopwords",
    -  "DeleteWithContents",
    -  "DeletionWarning",
    -  "DelimitedArray",
    -  "DelimitedSequence",
    -  "Delimiter",
    -  "DelimiterFlashTime",
    -  "DelimiterMatching",
    -  "Delimiters",
    -  "DeliveryFunction",
    -  "Dendrogram",
    -  "Denominator",
    -  "DensityGraphics",
    -  "DensityHistogram",
    -  "DensityPlot",
    -  "DensityPlot3D",
    -  "DependentVariables",
    -  "Deploy",
    -  "Deployed",
    -  "Depth",
    -  "DepthFirstScan",
    -  "Derivative",
    -  "DerivativeFilter",
    -  "DerivedKey",
    -  "DescriptorStateSpace",
    -  "DesignMatrix",
    -  "DestroyAfterEvaluation",
    -  "Det",
    -  "DeviceClose",
    -  "DeviceConfigure",
    -  "DeviceExecute",
    -  "DeviceExecuteAsynchronous",
    -  "DeviceObject",
    -  "DeviceOpen",
    -  "DeviceOpenQ",
    -  "DeviceRead",
    -  "DeviceReadBuffer",
    -  "DeviceReadLatest",
    -  "DeviceReadList",
    -  "DeviceReadTimeSeries",
    -  "Devices",
    -  "DeviceStreams",
    -  "DeviceWrite",
    -  "DeviceWriteBuffer",
    -  "DGaussianWavelet",
    -  "DiacriticalPositioning",
    -  "Diagonal",
    -  "DiagonalizableMatrixQ",
    -  "DiagonalMatrix",
    -  "DiagonalMatrixQ",
    -  "Dialog",
    -  "DialogIndent",
    -  "DialogInput",
    -  "DialogLevel",
    -  "DialogNotebook",
    -  "DialogProlog",
    -  "DialogReturn",
    -  "DialogSymbols",
    -  "Diamond",
    -  "DiamondMatrix",
    -  "DiceDissimilarity",
    -  "DictionaryLookup",
    -  "DictionaryWordQ",
    -  "DifferenceDelta",
    -  "DifferenceOrder",
    -  "DifferenceQuotient",
    -  "DifferenceRoot",
    -  "DifferenceRootReduce",
    -  "Differences",
    -  "DifferentialD",
    -  "DifferentialRoot",
    -  "DifferentialRootReduce",
    -  "DifferentiatorFilter",
    -  "DigitalSignature",
    -  "DigitBlock",
    -  "DigitBlockMinimum",
    -  "DigitCharacter",
    -  "DigitCount",
    -  "DigitQ",
    -  "DihedralAngle",
    -  "DihedralGroup",
    -  "Dilation",
    -  "DimensionalCombinations",
    -  "DimensionalMeshComponents",
    -  "DimensionReduce",
    -  "DimensionReducerFunction",
    -  "DimensionReduction",
    -  "Dimensions",
    -  "DiracComb",
    -  "DiracDelta",
    -  "DirectedEdge",
    -  "DirectedEdges",
    -  "DirectedGraph",
    -  "DirectedGraphQ",
    -  "DirectedInfinity",
    -  "Direction",
    -  "Directive",
    -  "Directory",
    -  "DirectoryName",
    -  "DirectoryQ",
    -  "DirectoryStack",
    -  "DirichletBeta",
    -  "DirichletCharacter",
    -  "DirichletCondition",
    -  "DirichletConvolve",
    -  "DirichletDistribution",
    -  "DirichletEta",
    -  "DirichletL",
    -  "DirichletLambda",
    -  "DirichletTransform",
    -  "DirichletWindow",
    -  "DisableConsolePrintPacket",
    -  "DisableFormatting",
    -  "DiscreteAsymptotic",
    -  "DiscreteChirpZTransform",
    -  "DiscreteConvolve",
    -  "DiscreteDelta",
    -  "DiscreteHadamardTransform",
    -  "DiscreteIndicator",
    -  "DiscreteLimit",
    -  "DiscreteLQEstimatorGains",
    -  "DiscreteLQRegulatorGains",
    -  "DiscreteLyapunovSolve",
    -  "DiscreteMarkovProcess",
    -  "DiscreteMaxLimit",
    -  "DiscreteMinLimit",
    -  "DiscretePlot",
    -  "DiscretePlot3D",
    -  "DiscreteRatio",
    -  "DiscreteRiccatiSolve",
    -  "DiscreteShift",
    -  "DiscreteTimeModelQ",
    -  "DiscreteUniformDistribution",
    -  "DiscreteVariables",
    -  "DiscreteWaveletData",
    -  "DiscreteWaveletPacketTransform",
    -  "DiscreteWaveletTransform",
    -  "DiscretizeGraphics",
    -  "DiscretizeRegion",
    -  "Discriminant",
    -  "DisjointQ",
    -  "Disjunction",
    -  "Disk",
    -  "DiskBox",
    -  "DiskMatrix",
    -  "DiskSegment",
    -  "Dispatch",
    -  "DispatchQ",
    -  "DispersionEstimatorFunction",
    -  "Display",
    -  "DisplayAllSteps",
    -  "DisplayEndPacket",
    -  "DisplayFlushImagePacket",
    -  "DisplayForm",
    -  "DisplayFunction",
    -  "DisplayPacket",
    -  "DisplayRules",
    -  "DisplaySetSizePacket",
    -  "DisplayString",
    -  "DisplayTemporary",
    -  "DisplayWith",
    -  "DisplayWithRef",
    -  "DisplayWithVariable",
    -  "DistanceFunction",
    -  "DistanceMatrix",
    -  "DistanceTransform",
    -  "Distribute",
    -  "Distributed",
    -  "DistributedContexts",
    -  "DistributeDefinitions",
    -  "DistributionChart",
    -  "DistributionDomain",
    -  "DistributionFitTest",
    -  "DistributionParameterAssumptions",
    -  "DistributionParameterQ",
    -  "Dithering",
    -  "Div",
    -  "Divergence",
    -  "Divide",
    -  "DivideBy",
    -  "Dividers",
    -  "DivideSides",
    -  "Divisible",
    -  "Divisors",
    -  "DivisorSigma",
    -  "DivisorSum",
    -  "DMSList",
    -  "DMSString",
    -  "Do",
    -  "DockedCells",
    -  "DocumentGenerator",
    -  "DocumentGeneratorInformation",
    -  "DocumentGeneratorInformationData",
    -  "DocumentGenerators",
    -  "DocumentNotebook",
    -  "DocumentWeightingRules",
    -  "Dodecahedron",
    -  "DomainRegistrationInformation",
    -  "DominantColors",
    -  "DOSTextFormat",
    -  "Dot",
    -  "DotDashed",
    -  "DotEqual",
    -  "DotLayer",
    -  "DotPlusLayer",
    -  "Dotted",
    -  "DoubleBracketingBar",
    -  "DoubleContourIntegral",
    -  "DoubleDownArrow",
    -  "DoubleLeftArrow",
    -  "DoubleLeftRightArrow",
    -  "DoubleLeftTee",
    -  "DoubleLongLeftArrow",
    -  "DoubleLongLeftRightArrow",
    -  "DoubleLongRightArrow",
    -  "DoubleRightArrow",
    -  "DoubleRightTee",
    -  "DoubleUpArrow",
    -  "DoubleUpDownArrow",
    -  "DoubleVerticalBar",
    -  "DoublyInfinite",
    -  "Down",
    -  "DownArrow",
    -  "DownArrowBar",
    -  "DownArrowUpArrow",
    -  "DownLeftRightVector",
    -  "DownLeftTeeVector",
    -  "DownLeftVector",
    -  "DownLeftVectorBar",
    -  "DownRightTeeVector",
    -  "DownRightVector",
    -  "DownRightVectorBar",
    -  "Downsample",
    -  "DownTee",
    -  "DownTeeArrow",
    -  "DownValues",
    -  "DragAndDrop",
    -  "DrawEdges",
    -  "DrawFrontFaces",
    -  "DrawHighlighted",
    -  "Drop",
    -  "DropoutLayer",
    -  "DSolve",
    -  "DSolveValue",
    -  "Dt",
    -  "DualLinearProgramming",
    -  "DualPolyhedron",
    -  "DualSystemsModel",
    -  "DumpGet",
    -  "DumpSave",
    -  "DuplicateFreeQ",
    -  "Duration",
    -  "Dynamic",
    -  "DynamicBox",
    -  "DynamicBoxOptions",
    -  "DynamicEvaluationTimeout",
    -  "DynamicGeoGraphics",
    -  "DynamicImage",
    -  "DynamicLocation",
    -  "DynamicModule",
    -  "DynamicModuleBox",
    -  "DynamicModuleBoxOptions",
    -  "DynamicModuleParent",
    -  "DynamicModuleValues",
    -  "DynamicName",
    -  "DynamicNamespace",
    -  "DynamicReference",
    -  "DynamicSetting",
    -  "DynamicUpdating",
    -  "DynamicWrapper",
    -  "DynamicWrapperBox",
    -  "DynamicWrapperBoxOptions",
    -  "E",
    -  "EarthImpactData",
    -  "EarthquakeData",
    -  "EccentricityCentrality",
    -  "Echo",
    -  "EchoFunction",
    -  "EclipseType",
    -  "EdgeAdd",
    -  "EdgeBetweennessCentrality",
    -  "EdgeCapacity",
    -  "EdgeCapForm",
    -  "EdgeColor",
    -  "EdgeConnectivity",
    -  "EdgeContract",
    -  "EdgeCost",
    -  "EdgeCount",
    -  "EdgeCoverQ",
    -  "EdgeCycleMatrix",
    -  "EdgeDashing",
    -  "EdgeDelete",
    -  "EdgeDetect",
    -  "EdgeForm",
    -  "EdgeIndex",
    -  "EdgeJoinForm",
    -  "EdgeLabeling",
    -  "EdgeLabels",
    -  "EdgeLabelStyle",
    -  "EdgeList",
    -  "EdgeOpacity",
    -  "EdgeQ",
    -  "EdgeRenderingFunction",
    -  "EdgeRules",
    -  "EdgeShapeFunction",
    -  "EdgeStyle",
    -  "EdgeTaggedGraph",
    -  "EdgeTaggedGraphQ",
    -  "EdgeTags",
    -  "EdgeThickness",
    -  "EdgeWeight",
    -  "EdgeWeightedGraphQ",
    -  "Editable",
    -  "EditButtonSettings",
    -  "EditCellTagsSettings",
    -  "EditDistance",
    -  "EffectiveInterest",
    -  "Eigensystem",
    -  "Eigenvalues",
    -  "EigenvectorCentrality",
    -  "Eigenvectors",
    -  "Element",
    -  "ElementData",
    -  "ElementwiseLayer",
    -  "ElidedForms",
    -  "Eliminate",
    -  "EliminationOrder",
    -  "Ellipsoid",
    -  "EllipticE",
    -  "EllipticExp",
    -  "EllipticExpPrime",
    -  "EllipticF",
    -  "EllipticFilterModel",
    -  "EllipticK",
    -  "EllipticLog",
    -  "EllipticNomeQ",
    -  "EllipticPi",
    -  "EllipticReducedHalfPeriods",
    -  "EllipticTheta",
    -  "EllipticThetaPrime",
    -  "EmbedCode",
    -  "EmbeddedHTML",
    -  "EmbeddedService",
    -  "EmbeddingLayer",
    -  "EmbeddingObject",
    -  "EmitSound",
    -  "EmphasizeSyntaxErrors",
    -  "EmpiricalDistribution",
    -  "Empty",
    -  "EmptyGraphQ",
    -  "EmptyRegion",
    -  "EnableConsolePrintPacket",
    -  "Enabled",
    -  "Encode",
    -  "Encrypt",
    -  "EncryptedObject",
    -  "EncryptFile",
    -  "End",
    -  "EndAdd",
    -  "EndDialogPacket",
    -  "EndFrontEndInteractionPacket",
    -  "EndOfBuffer",
    -  "EndOfFile",
    -  "EndOfLine",
    -  "EndOfString",
    -  "EndPackage",
    -  "EngineEnvironment",
    -  "EngineeringForm",
    -  "Enter",
    -  "EnterExpressionPacket",
    -  "EnterTextPacket",
    -  "Entity",
    -  "EntityClass",
    -  "EntityClassList",
    -  "EntityCopies",
    -  "EntityFunction",
    -  "EntityGroup",
    -  "EntityInstance",
    -  "EntityList",
    -  "EntityPrefetch",
    -  "EntityProperties",
    -  "EntityProperty",
    -  "EntityPropertyClass",
    -  "EntityRegister",
    -  "EntityStore",
    -  "EntityStores",
    -  "EntityTypeName",
    -  "EntityUnregister",
    -  "EntityValue",
    -  "Entropy",
    -  "EntropyFilter",
    -  "Environment",
    -  "Epilog",
    -  "EpilogFunction",
    -  "Equal",
    -  "EqualColumns",
    -  "EqualRows",
    -  "EqualTilde",
    -  "EqualTo",
    -  "EquatedTo",
    -  "Equilibrium",
    -  "EquirippleFilterKernel",
    -  "Equivalent",
    -  "Erf",
    -  "Erfc",
    -  "Erfi",
    -  "ErlangB",
    -  "ErlangC",
    -  "ErlangDistribution",
    -  "Erosion",
    -  "ErrorBox",
    -  "ErrorBoxOptions",
    -  "ErrorNorm",
    -  "ErrorPacket",
    -  "ErrorsDialogSettings",
    -  "EscapeRadius",
    -  "EstimatedBackground",
    -  "EstimatedDistribution",
    -  "EstimatedProcess",
    -  "EstimatorGains",
    -  "EstimatorRegulator",
    -  "EuclideanDistance",
    -  "EulerAngles",
    -  "EulerCharacteristic",
    -  "EulerE",
    -  "EulerGamma",
    -  "EulerianGraphQ",
    -  "EulerMatrix",
    -  "EulerPhi",
    -  "Evaluatable",
    -  "Evaluate",
    -  "Evaluated",
    -  "EvaluatePacket",
    -  "EvaluateScheduledTask",
    -  "EvaluationBox",
    -  "EvaluationCell",
    -  "EvaluationCompletionAction",
    -  "EvaluationData",
    -  "EvaluationElements",
    -  "EvaluationEnvironment",
    -  "EvaluationMode",
    -  "EvaluationMonitor",
    -  "EvaluationNotebook",
    -  "EvaluationObject",
    -  "EvaluationOrder",
    -  "Evaluator",
    -  "EvaluatorNames",
    -  "EvenQ",
    -  "EventData",
    -  "EventEvaluator",
    -  "EventHandler",
    -  "EventHandlerTag",
    -  "EventLabels",
    -  "EventSeries",
    -  "ExactBlackmanWindow",
    -  "ExactNumberQ",
    -  "ExactRootIsolation",
    -  "ExampleData",
    -  "Except",
    -  "ExcludedForms",
    -  "ExcludedLines",
    -  "ExcludedPhysicalQuantities",
    -  "ExcludePods",
    -  "Exclusions",
    -  "ExclusionsStyle",
    -  "Exists",
    -  "Exit",
    -  "ExitDialog",
    -  "ExoplanetData",
    -  "Exp",
    -  "Expand",
    -  "ExpandAll",
    -  "ExpandDenominator",
    -  "ExpandFileName",
    -  "ExpandNumerator",
    -  "Expectation",
    -  "ExpectationE",
    -  "ExpectedValue",
    -  "ExpGammaDistribution",
    -  "ExpIntegralE",
    -  "ExpIntegralEi",
    -  "ExpirationDate",
    -  "Exponent",
    -  "ExponentFunction",
    -  "ExponentialDistribution",
    -  "ExponentialFamily",
    -  "ExponentialGeneratingFunction",
    -  "ExponentialMovingAverage",
    -  "ExponentialPowerDistribution",
    -  "ExponentPosition",
    -  "ExponentStep",
    -  "Export",
    -  "ExportAutoReplacements",
    -  "ExportByteArray",
    -  "ExportForm",
    -  "ExportPacket",
    -  "ExportString",
    -  "Expression",
    -  "ExpressionCell",
    -  "ExpressionGraph",
    -  "ExpressionPacket",
    -  "ExpressionUUID",
    -  "ExpToTrig",
    -  "ExtendedEntityClass",
    -  "ExtendedGCD",
    -  "Extension",
    -  "ExtentElementFunction",
    -  "ExtentMarkers",
    -  "ExtentSize",
    -  "ExternalBundle",
    -  "ExternalCall",
    -  "ExternalDataCharacterEncoding",
    -  "ExternalEvaluate",
    -  "ExternalFunction",
    -  "ExternalFunctionName",
    -  "ExternalIdentifier",
    -  "ExternalObject",
    -  "ExternalOptions",
    -  "ExternalSessionObject",
    -  "ExternalSessions",
    -  "ExternalStorageBase",
    -  "ExternalStorageDownload",
    -  "ExternalStorageGet",
    -  "ExternalStorageObject",
    -  "ExternalStoragePut",
    -  "ExternalStorageUpload",
    -  "ExternalTypeSignature",
    -  "ExternalValue",
    -  "Extract",
    -  "ExtractArchive",
    -  "ExtractLayer",
    -  "ExtractPacletArchive",
    -  "ExtremeValueDistribution",
    -  "FaceAlign",
    -  "FaceForm",
    -  "FaceGrids",
    -  "FaceGridsStyle",
    -  "FacialFeatures",
    -  "Factor",
    -  "FactorComplete",
    -  "Factorial",
    -  "Factorial2",
    -  "FactorialMoment",
    -  "FactorialMomentGeneratingFunction",
    -  "FactorialPower",
    -  "FactorInteger",
    -  "FactorList",
    -  "FactorSquareFree",
    -  "FactorSquareFreeList",
    -  "FactorTerms",
    -  "FactorTermsList",
    -  "Fail",
    -  "Failure",
    -  "FailureAction",
    -  "FailureDistribution",
    -  "FailureQ",
    -  "False",
    -  "FareySequence",
    -  "FARIMAProcess",
    -  "FeatureDistance",
    -  "FeatureExtract",
    -  "FeatureExtraction",
    -  "FeatureExtractor",
    -  "FeatureExtractorFunction",
    -  "FeatureNames",
    -  "FeatureNearest",
    -  "FeatureSpacePlot",
    -  "FeatureSpacePlot3D",
    -  "FeatureTypes",
    -  "FEDisableConsolePrintPacket",
    -  "FeedbackLinearize",
    -  "FeedbackSector",
    -  "FeedbackSectorStyle",
    -  "FeedbackType",
    -  "FEEnableConsolePrintPacket",
    -  "FetalGrowthData",
    -  "Fibonacci",
    -  "Fibonorial",
    -  "FieldCompletionFunction",
    -  "FieldHint",
    -  "FieldHintStyle",
    -  "FieldMasked",
    -  "FieldSize",
    -  "File",
    -  "FileBaseName",
    -  "FileByteCount",
    -  "FileConvert",
    -  "FileDate",
    -  "FileExistsQ",
    -  "FileExtension",
    -  "FileFormat",
    -  "FileHandler",
    -  "FileHash",
    -  "FileInformation",
    -  "FileName",
    -  "FileNameDepth",
    -  "FileNameDialogSettings",
    -  "FileNameDrop",
    -  "FileNameForms",
    -  "FileNameJoin",
    -  "FileNames",
    -  "FileNameSetter",
    -  "FileNameSplit",
    -  "FileNameTake",
    -  "FilePrint",
    -  "FileSize",
    -  "FileSystemMap",
    -  "FileSystemScan",
    -  "FileTemplate",
    -  "FileTemplateApply",
    -  "FileType",
    -  "FilledCurve",
    -  "FilledCurveBox",
    -  "FilledCurveBoxOptions",
    -  "Filling",
    -  "FillingStyle",
    -  "FillingTransform",
    -  "FilteredEntityClass",
    -  "FilterRules",
    -  "FinancialBond",
    -  "FinancialData",
    -  "FinancialDerivative",
    -  "FinancialIndicator",
    -  "Find",
    -  "FindAnomalies",
    -  "FindArgMax",
    -  "FindArgMin",
    -  "FindChannels",
    -  "FindClique",
    -  "FindClusters",
    -  "FindCookies",
    -  "FindCurvePath",
    -  "FindCycle",
    -  "FindDevices",
    -  "FindDistribution",
    -  "FindDistributionParameters",
    -  "FindDivisions",
    -  "FindEdgeCover",
    -  "FindEdgeCut",
    -  "FindEdgeIndependentPaths",
    -  "FindEquationalProof",
    -  "FindEulerianCycle",
    -  "FindExternalEvaluators",
    -  "FindFaces",
    -  "FindFile",
    -  "FindFit",
    -  "FindFormula",
    -  "FindFundamentalCycles",
    -  "FindGeneratingFunction",
    -  "FindGeoLocation",
    -  "FindGeometricConjectures",
    -  "FindGeometricTransform",
    -  "FindGraphCommunities",
    -  "FindGraphIsomorphism",
    -  "FindGraphPartition",
    -  "FindHamiltonianCycle",
    -  "FindHamiltonianPath",
    -  "FindHiddenMarkovStates",
    -  "FindImageText",
    -  "FindIndependentEdgeSet",
    -  "FindIndependentVertexSet",
    -  "FindInstance",
    -  "FindIntegerNullVector",
    -  "FindKClan",
    -  "FindKClique",
    -  "FindKClub",
    -  "FindKPlex",
    -  "FindLibrary",
    -  "FindLinearRecurrence",
    -  "FindList",
    -  "FindMatchingColor",
    -  "FindMaximum",
    -  "FindMaximumCut",
    -  "FindMaximumFlow",
    -  "FindMaxValue",
    -  "FindMeshDefects",
    -  "FindMinimum",
    -  "FindMinimumCostFlow",
    -  "FindMinimumCut",
    -  "FindMinValue",
    -  "FindMoleculeSubstructure",
    -  "FindPath",
    -  "FindPeaks",
    -  "FindPermutation",
    -  "FindPostmanTour",
    -  "FindProcessParameters",
    -  "FindRepeat",
    -  "FindRoot",
    -  "FindSequenceFunction",
    -  "FindSettings",
    -  "FindShortestPath",
    -  "FindShortestTour",
    -  "FindSpanningTree",
    -  "FindSystemModelEquilibrium",
    -  "FindTextualAnswer",
    -  "FindThreshold",
    -  "FindTransientRepeat",
    -  "FindVertexCover",
    -  "FindVertexCut",
    -  "FindVertexIndependentPaths",
    -  "Fine",
    -  "FinishDynamic",
    -  "FiniteAbelianGroupCount",
    -  "FiniteGroupCount",
    -  "FiniteGroupData",
    -  "First",
    -  "FirstCase",
    -  "FirstPassageTimeDistribution",
    -  "FirstPosition",
    -  "FischerGroupFi22",
    -  "FischerGroupFi23",
    -  "FischerGroupFi24Prime",
    -  "FisherHypergeometricDistribution",
    -  "FisherRatioTest",
    -  "FisherZDistribution",
    -  "Fit",
    -  "FitAll",
    -  "FitRegularization",
    -  "FittedModel",
    -  "FixedOrder",
    -  "FixedPoint",
    -  "FixedPointList",
    -  "FlashSelection",
    -  "Flat",
    -  "Flatten",
    -  "FlattenAt",
    -  "FlattenLayer",
    -  "FlatTopWindow",
    -  "FlipView",
    -  "Floor",
    -  "FlowPolynomial",
    -  "FlushPrintOutputPacket",
    -  "Fold",
    -  "FoldList",
    -  "FoldPair",
    -  "FoldPairList",
    -  "FollowRedirects",
    -  "Font",
    -  "FontColor",
    -  "FontFamily",
    -  "FontForm",
    -  "FontName",
    -  "FontOpacity",
    -  "FontPostScriptName",
    -  "FontProperties",
    -  "FontReencoding",
    -  "FontSize",
    -  "FontSlant",
    -  "FontSubstitutions",
    -  "FontTracking",
    -  "FontVariations",
    -  "FontWeight",
    -  "For",
    -  "ForAll",
    -  "ForceVersionInstall",
    -  "Format",
    -  "FormatRules",
    -  "FormatType",
    -  "FormatTypeAutoConvert",
    -  "FormatValues",
    -  "FormBox",
    -  "FormBoxOptions",
    -  "FormControl",
    -  "FormFunction",
    -  "FormLayoutFunction",
    -  "FormObject",
    -  "FormPage",
    -  "FormTheme",
    -  "FormulaData",
    -  "FormulaLookup",
    -  "FortranForm",
    -  "Forward",
    -  "ForwardBackward",
    -  "Fourier",
    -  "FourierCoefficient",
    -  "FourierCosCoefficient",
    -  "FourierCosSeries",
    -  "FourierCosTransform",
    -  "FourierDCT",
    -  "FourierDCTFilter",
    -  "FourierDCTMatrix",
    -  "FourierDST",
    -  "FourierDSTMatrix",
    -  "FourierMatrix",
    -  "FourierParameters",
    -  "FourierSequenceTransform",
    -  "FourierSeries",
    -  "FourierSinCoefficient",
    -  "FourierSinSeries",
    -  "FourierSinTransform",
    -  "FourierTransform",
    -  "FourierTrigSeries",
    -  "FractionalBrownianMotionProcess",
    -  "FractionalGaussianNoiseProcess",
    -  "FractionalPart",
    -  "FractionBox",
    -  "FractionBoxOptions",
    -  "FractionLine",
    -  "Frame",
    -  "FrameBox",
    -  "FrameBoxOptions",
    -  "Framed",
    -  "FrameInset",
    -  "FrameLabel",
    -  "Frameless",
    -  "FrameMargins",
    -  "FrameRate",
    -  "FrameStyle",
    -  "FrameTicks",
    -  "FrameTicksStyle",
    -  "FRatioDistribution",
    -  "FrechetDistribution",
    -  "FreeQ",
    -  "FrenetSerretSystem",
    -  "FrequencySamplingFilterKernel",
    -  "FresnelC",
    -  "FresnelF",
    -  "FresnelG",
    -  "FresnelS",
    -  "Friday",
    -  "FrobeniusNumber",
    -  "FrobeniusSolve",
    -  "FromAbsoluteTime",
    -  "FromCharacterCode",
    -  "FromCoefficientRules",
    -  "FromContinuedFraction",
    -  "FromDate",
    -  "FromDigits",
    -  "FromDMS",
    -  "FromEntity",
    -  "FromJulianDate",
    -  "FromLetterNumber",
    -  "FromPolarCoordinates",
    -  "FromRomanNumeral",
    -  "FromSphericalCoordinates",
    -  "FromUnixTime",
    -  "Front",
    -  "FrontEndDynamicExpression",
    -  "FrontEndEventActions",
    -  "FrontEndExecute",
    -  "FrontEndObject",
    -  "FrontEndResource",
    -  "FrontEndResourceString",
    -  "FrontEndStackSize",
    -  "FrontEndToken",
    -  "FrontEndTokenExecute",
    -  "FrontEndValueCache",
    -  "FrontEndVersion",
    -  "FrontFaceColor",
    -  "FrontFaceOpacity",
    -  "Full",
    -  "FullAxes",
    -  "FullDefinition",
    -  "FullForm",
    -  "FullGraphics",
    -  "FullInformationOutputRegulator",
    -  "FullOptions",
    -  "FullRegion",
    -  "FullSimplify",
    -  "Function",
    -  "FunctionCompile",
    -  "FunctionCompileExport",
    -  "FunctionCompileExportByteArray",
    -  "FunctionCompileExportLibrary",
    -  "FunctionCompileExportString",
    -  "FunctionDomain",
    -  "FunctionExpand",
    -  "FunctionInterpolation",
    -  "FunctionPeriod",
    -  "FunctionRange",
    -  "FunctionSpace",
    -  "FussellVeselyImportance",
    -  "GaborFilter",
    -  "GaborMatrix",
    -  "GaborWavelet",
    -  "GainMargins",
    -  "GainPhaseMargins",
    -  "GalaxyData",
    -  "GalleryView",
    -  "Gamma",
    -  "GammaDistribution",
    -  "GammaRegularized",
    -  "GapPenalty",
    -  "GARCHProcess",
    -  "GatedRecurrentLayer",
    -  "Gather",
    -  "GatherBy",
    -  "GaugeFaceElementFunction",
    -  "GaugeFaceStyle",
    -  "GaugeFrameElementFunction",
    -  "GaugeFrameSize",
    -  "GaugeFrameStyle",
    -  "GaugeLabels",
    -  "GaugeMarkers",
    -  "GaugeStyle",
    -  "GaussianFilter",
    -  "GaussianIntegers",
    -  "GaussianMatrix",
    -  "GaussianOrthogonalMatrixDistribution",
    -  "GaussianSymplecticMatrixDistribution",
    -  "GaussianUnitaryMatrixDistribution",
    -  "GaussianWindow",
    -  "GCD",
    -  "GegenbauerC",
    -  "General",
    -  "GeneralizedLinearModelFit",
    -  "GenerateAsymmetricKeyPair",
    -  "GenerateConditions",
    -  "GeneratedCell",
    -  "GeneratedDocumentBinding",
    -  "GenerateDerivedKey",
    -  "GenerateDigitalSignature",
    -  "GenerateDocument",
    -  "GeneratedParameters",
    -  "GeneratedQuantityMagnitudes",
    -  "GenerateFileSignature",
    -  "GenerateHTTPResponse",
    -  "GenerateSecuredAuthenticationKey",
    -  "GenerateSymmetricKey",
    -  "GeneratingFunction",
    -  "GeneratorDescription",
    -  "GeneratorHistoryLength",
    -  "GeneratorOutputType",
    -  "Generic",
    -  "GenericCylindricalDecomposition",
    -  "GenomeData",
    -  "GenomeLookup",
    -  "GeoAntipode",
    -  "GeoArea",
    -  "GeoArraySize",
    -  "GeoBackground",
    -  "GeoBoundingBox",
    -  "GeoBounds",
    -  "GeoBoundsRegion",
    -  "GeoBubbleChart",
    -  "GeoCenter",
    -  "GeoCircle",
    -  "GeoContourPlot",
    -  "GeoDensityPlot",
    -  "GeodesicClosing",
    -  "GeodesicDilation",
    -  "GeodesicErosion",
    -  "GeodesicOpening",
    -  "GeoDestination",
    -  "GeodesyData",
    -  "GeoDirection",
    -  "GeoDisk",
    -  "GeoDisplacement",
    -  "GeoDistance",
    -  "GeoDistanceList",
    -  "GeoElevationData",
    -  "GeoEntities",
    -  "GeoGraphics",
    -  "GeogravityModelData",
    -  "GeoGridDirectionDifference",
    -  "GeoGridLines",
    -  "GeoGridLinesStyle",
    -  "GeoGridPosition",
    -  "GeoGridRange",
    -  "GeoGridRangePadding",
    -  "GeoGridUnitArea",
    -  "GeoGridUnitDistance",
    -  "GeoGridVector",
    -  "GeoGroup",
    -  "GeoHemisphere",
    -  "GeoHemisphereBoundary",
    -  "GeoHistogram",
    -  "GeoIdentify",
    -  "GeoImage",
    -  "GeoLabels",
    -  "GeoLength",
    -  "GeoListPlot",
    -  "GeoLocation",
    -  "GeologicalPeriodData",
    -  "GeomagneticModelData",
    -  "GeoMarker",
    -  "GeometricAssertion",
    -  "GeometricBrownianMotionProcess",
    -  "GeometricDistribution",
    -  "GeometricMean",
    -  "GeometricMeanFilter",
    -  "GeometricOptimization",
    -  "GeometricScene",
    -  "GeometricTransformation",
    -  "GeometricTransformation3DBox",
    -  "GeometricTransformation3DBoxOptions",
    -  "GeometricTransformationBox",
    -  "GeometricTransformationBoxOptions",
    -  "GeoModel",
    -  "GeoNearest",
    -  "GeoPath",
    -  "GeoPosition",
    -  "GeoPositionENU",
    -  "GeoPositionXYZ",
    -  "GeoProjection",
    -  "GeoProjectionData",
    -  "GeoRange",
    -  "GeoRangePadding",
    -  "GeoRegionValuePlot",
    -  "GeoResolution",
    -  "GeoScaleBar",
    -  "GeoServer",
    -  "GeoSmoothHistogram",
    -  "GeoStreamPlot",
    -  "GeoStyling",
    -  "GeoStylingImageFunction",
    -  "GeoVariant",
    -  "GeoVector",
    -  "GeoVectorENU",
    -  "GeoVectorPlot",
    -  "GeoVectorXYZ",
    -  "GeoVisibleRegion",
    -  "GeoVisibleRegionBoundary",
    -  "GeoWithinQ",
    -  "GeoZoomLevel",
    -  "GestureHandler",
    -  "GestureHandlerTag",
    -  "Get",
    -  "GetBoundingBoxSizePacket",
    -  "GetContext",
    -  "GetEnvironment",
    -  "GetFileName",
    -  "GetFrontEndOptionsDataPacket",
    -  "GetLinebreakInformationPacket",
    -  "GetMenusPacket",
    -  "GetPageBreakInformationPacket",
    -  "Glaisher",
    -  "GlobalClusteringCoefficient",
    -  "GlobalPreferences",
    -  "GlobalSession",
    -  "Glow",
    -  "GoldenAngle",
    -  "GoldenRatio",
    -  "GompertzMakehamDistribution",
    -  "GoochShading",
    -  "GoodmanKruskalGamma",
    -  "GoodmanKruskalGammaTest",
    -  "Goto",
    -  "Grad",
    -  "Gradient",
    -  "GradientFilter",
    -  "GradientOrientationFilter",
    -  "GrammarApply",
    -  "GrammarRules",
    -  "GrammarToken",
    -  "Graph",
    -  "Graph3D",
    -  "GraphAssortativity",
    -  "GraphAutomorphismGroup",
    -  "GraphCenter",
    -  "GraphComplement",
    -  "GraphData",
    -  "GraphDensity",
    -  "GraphDiameter",
    -  "GraphDifference",
    -  "GraphDisjointUnion",
    -  "GraphDistance",
    -  "GraphDistanceMatrix",
    -  "GraphElementData",
    -  "GraphEmbedding",
    -  "GraphHighlight",
    -  "GraphHighlightStyle",
    -  "GraphHub",
    -  "Graphics",
    -  "Graphics3D",
    -  "Graphics3DBox",
    -  "Graphics3DBoxOptions",
    -  "GraphicsArray",
    -  "GraphicsBaseline",
    -  "GraphicsBox",
    -  "GraphicsBoxOptions",
    -  "GraphicsColor",
    -  "GraphicsColumn",
    -  "GraphicsComplex",
    -  "GraphicsComplex3DBox",
    -  "GraphicsComplex3DBoxOptions",
    -  "GraphicsComplexBox",
    -  "GraphicsComplexBoxOptions",
    -  "GraphicsContents",
    -  "GraphicsData",
    -  "GraphicsGrid",
    -  "GraphicsGridBox",
    -  "GraphicsGroup",
    -  "GraphicsGroup3DBox",
    -  "GraphicsGroup3DBoxOptions",
    -  "GraphicsGroupBox",
    -  "GraphicsGroupBoxOptions",
    -  "GraphicsGrouping",
    -  "GraphicsHighlightColor",
    -  "GraphicsRow",
    -  "GraphicsSpacing",
    -  "GraphicsStyle",
    -  "GraphIntersection",
    -  "GraphLayout",
    -  "GraphLinkEfficiency",
    -  "GraphPeriphery",
    -  "GraphPlot",
    -  "GraphPlot3D",
    -  "GraphPower",
    -  "GraphPropertyDistribution",
    -  "GraphQ",
    -  "GraphRadius",
    -  "GraphReciprocity",
    -  "GraphRoot",
    -  "GraphStyle",
    -  "GraphUnion",
    -  "Gray",
    -  "GrayLevel",
    -  "Greater",
    -  "GreaterEqual",
    -  "GreaterEqualLess",
    -  "GreaterEqualThan",
    -  "GreaterFullEqual",
    -  "GreaterGreater",
    -  "GreaterLess",
    -  "GreaterSlantEqual",
    -  "GreaterThan",
    -  "GreaterTilde",
    -  "Green",
    -  "GreenFunction",
    -  "Grid",
    -  "GridBaseline",
    -  "GridBox",
    -  "GridBoxAlignment",
    -  "GridBoxBackground",
    -  "GridBoxDividers",
    -  "GridBoxFrame",
    -  "GridBoxItemSize",
    -  "GridBoxItemStyle",
    -  "GridBoxOptions",
    -  "GridBoxSpacings",
    -  "GridCreationSettings",
    -  "GridDefaultElement",
    -  "GridElementStyleOptions",
    -  "GridFrame",
    -  "GridFrameMargins",
    -  "GridGraph",
    -  "GridLines",
    -  "GridLinesStyle",
    -  "GroebnerBasis",
    -  "GroupActionBase",
    -  "GroupBy",
    -  "GroupCentralizer",
    -  "GroupElementFromWord",
    -  "GroupElementPosition",
    -  "GroupElementQ",
    -  "GroupElements",
    -  "GroupElementToWord",
    -  "GroupGenerators",
    -  "Groupings",
    -  "GroupMultiplicationTable",
    -  "GroupOrbits",
    -  "GroupOrder",
    -  "GroupPageBreakWithin",
    -  "GroupSetwiseStabilizer",
    -  "GroupStabilizer",
    -  "GroupStabilizerChain",
    -  "GroupTogetherGrouping",
    -  "GroupTogetherNestedGrouping",
    -  "GrowCutComponents",
    -  "Gudermannian",
    -  "GuidedFilter",
    -  "GumbelDistribution",
    -  "HaarWavelet",
    -  "HadamardMatrix",
    -  "HalfLine",
    -  "HalfNormalDistribution",
    -  "HalfPlane",
    -  "HalfSpace",
    -  "HalftoneShading",
    -  "HamiltonianGraphQ",
    -  "HammingDistance",
    -  "HammingWindow",
    -  "HandlerFunctions",
    -  "HandlerFunctionsKeys",
    -  "HankelH1",
    -  "HankelH2",
    -  "HankelMatrix",
    -  "HankelTransform",
    -  "HannPoissonWindow",
    -  "HannWindow",
    -  "HaradaNortonGroupHN",
    -  "HararyGraph",
    -  "HarmonicMean",
    -  "HarmonicMeanFilter",
    -  "HarmonicNumber",
    -  "Hash",
    -  "HatchFilling",
    -  "HatchShading",
    -  "Haversine",
    -  "HazardFunction",
    -  "Head",
    -  "HeadCompose",
    -  "HeaderAlignment",
    -  "HeaderBackground",
    -  "HeaderDisplayFunction",
    -  "HeaderLines",
    -  "HeaderSize",
    -  "HeaderStyle",
    -  "Heads",
    -  "HeavisideLambda",
    -  "HeavisidePi",
    -  "HeavisideTheta",
    -  "HeldGroupHe",
    -  "HeldPart",
    -  "HelpBrowserLookup",
    -  "HelpBrowserNotebook",
    -  "HelpBrowserSettings",
    -  "Here",
    -  "HermiteDecomposition",
    -  "HermiteH",
    -  "HermitianMatrixQ",
    -  "HessenbergDecomposition",
    -  "Hessian",
    -  "HeunB",
    -  "HeunBPrime",
    -  "HeunC",
    -  "HeunCPrime",
    -  "HeunD",
    -  "HeunDPrime",
    -  "HeunG",
    -  "HeunGPrime",
    -  "HeunT",
    -  "HeunTPrime",
    -  "HexadecimalCharacter",
    -  "Hexahedron",
    -  "HexahedronBox",
    -  "HexahedronBoxOptions",
    -  "HiddenItems",
    -  "HiddenMarkovProcess",
    -  "HiddenSurface",
    -  "Highlighted",
    -  "HighlightGraph",
    -  "HighlightImage",
    -  "HighlightMesh",
    -  "HighpassFilter",
    -  "HigmanSimsGroupHS",
    -  "HilbertCurve",
    -  "HilbertFilter",
    -  "HilbertMatrix",
    -  "Histogram",
    -  "Histogram3D",
    -  "HistogramDistribution",
    -  "HistogramList",
    -  "HistogramTransform",
    -  "HistogramTransformInterpolation",
    -  "HistoricalPeriodData",
    -  "HitMissTransform",
    -  "HITSCentrality",
    -  "HjorthDistribution",
    -  "HodgeDual",
    -  "HoeffdingD",
    -  "HoeffdingDTest",
    -  "Hold",
    -  "HoldAll",
    -  "HoldAllComplete",
    -  "HoldComplete",
    -  "HoldFirst",
    -  "HoldForm",
    -  "HoldPattern",
    -  "HoldRest",
    -  "HolidayCalendar",
    -  "HomeDirectory",
    -  "HomePage",
    -  "Horizontal",
    -  "HorizontalForm",
    -  "HorizontalGauge",
    -  "HorizontalScrollPosition",
    -  "HornerForm",
    -  "HostLookup",
    -  "HotellingTSquareDistribution",
    -  "HoytDistribution",
    -  "HTMLSave",
    -  "HTTPErrorResponse",
    -  "HTTPRedirect",
    -  "HTTPRequest",
    -  "HTTPRequestData",
    -  "HTTPResponse",
    -  "Hue",
    -  "HumanGrowthData",
    -  "HumpDownHump",
    -  "HumpEqual",
    -  "HurwitzLerchPhi",
    -  "HurwitzZeta",
    -  "HyperbolicDistribution",
    -  "HypercubeGraph",
    -  "HyperexponentialDistribution",
    -  "Hyperfactorial",
    -  "Hypergeometric0F1",
    -  "Hypergeometric0F1Regularized",
    -  "Hypergeometric1F1",
    -  "Hypergeometric1F1Regularized",
    -  "Hypergeometric2F1",
    -  "Hypergeometric2F1Regularized",
    -  "HypergeometricDistribution",
    -  "HypergeometricPFQ",
    -  "HypergeometricPFQRegularized",
    -  "HypergeometricU",
    -  "Hyperlink",
    -  "HyperlinkAction",
    -  "HyperlinkCreationSettings",
    -  "Hyperplane",
    -  "Hyphenation",
    -  "HyphenationOptions",
    -  "HypoexponentialDistribution",
    -  "HypothesisTestData",
    -  "I",
    -  "IconData",
    -  "Iconize",
    -  "IconizedObject",
    -  "IconRules",
    -  "Icosahedron",
    -  "Identity",
    -  "IdentityMatrix",
    -  "If",
    -  "IgnoreCase",
    -  "IgnoreDiacritics",
    -  "IgnorePunctuation",
    -  "IgnoreSpellCheck",
    -  "IgnoringInactive",
    -  "Im",
    -  "Image",
    -  "Image3D",
    -  "Image3DProjection",
    -  "Image3DSlices",
    -  "ImageAccumulate",
    -  "ImageAdd",
    -  "ImageAdjust",
    -  "ImageAlign",
    -  "ImageApply",
    -  "ImageApplyIndexed",
    -  "ImageAspectRatio",
    -  "ImageAssemble",
    -  "ImageAugmentationLayer",
    -  "ImageBoundingBoxes",
    -  "ImageCache",
    -  "ImageCacheValid",
    -  "ImageCapture",
    -  "ImageCaptureFunction",
    -  "ImageCases",
    -  "ImageChannels",
    -  "ImageClip",
    -  "ImageCollage",
    -  "ImageColorSpace",
    -  "ImageCompose",
    -  "ImageContainsQ",
    -  "ImageContents",
    -  "ImageConvolve",
    -  "ImageCooccurrence",
    -  "ImageCorners",
    -  "ImageCorrelate",
    -  "ImageCorrespondingPoints",
    -  "ImageCrop",
    -  "ImageData",
    -  "ImageDeconvolve",
    -  "ImageDemosaic",
    -  "ImageDifference",
    -  "ImageDimensions",
    -  "ImageDisplacements",
    -  "ImageDistance",
    -  "ImageEffect",
    -  "ImageExposureCombine",
    -  "ImageFeatureTrack",
    -  "ImageFileApply",
    -  "ImageFileFilter",
    -  "ImageFileScan",
    -  "ImageFilter",
    -  "ImageFocusCombine",
    -  "ImageForestingComponents",
    -  "ImageFormattingWidth",
    -  "ImageForwardTransformation",
    -  "ImageGraphics",
    -  "ImageHistogram",
    -  "ImageIdentify",
    -  "ImageInstanceQ",
    -  "ImageKeypoints",
    -  "ImageLabels",
    -  "ImageLegends",
    -  "ImageLevels",
    -  "ImageLines",
    -  "ImageMargins",
    -  "ImageMarker",
    -  "ImageMarkers",
    -  "ImageMeasurements",
    -  "ImageMesh",
    -  "ImageMultiply",
    -  "ImageOffset",
    -  "ImagePad",
    -  "ImagePadding",
    -  "ImagePartition",
    -  "ImagePeriodogram",
    -  "ImagePerspectiveTransformation",
    -  "ImagePosition",
    -  "ImagePreviewFunction",
    -  "ImagePyramid",
    -  "ImagePyramidApply",
    -  "ImageQ",
    -  "ImageRangeCache",
    -  "ImageRecolor",
    -  "ImageReflect",
    -  "ImageRegion",
    -  "ImageResize",
    -  "ImageResolution",
    -  "ImageRestyle",
    -  "ImageRotate",
    -  "ImageRotated",
    -  "ImageSaliencyFilter",
    -  "ImageScaled",
    -  "ImageScan",
    -  "ImageSize",
    -  "ImageSizeAction",
    -  "ImageSizeCache",
    -  "ImageSizeMultipliers",
    -  "ImageSizeRaw",
    -  "ImageSubtract",
    -  "ImageTake",
    -  "ImageTransformation",
    -  "ImageTrim",
    -  "ImageType",
    -  "ImageValue",
    -  "ImageValuePositions",
    -  "ImagingDevice",
    -  "ImplicitRegion",
    -  "Implies",
    -  "Import",
    -  "ImportAutoReplacements",
    -  "ImportByteArray",
    -  "ImportOptions",
    -  "ImportString",
    -  "ImprovementImportance",
    -  "In",
    -  "Inactivate",
    -  "Inactive",
    -  "IncidenceGraph",
    -  "IncidenceList",
    -  "IncidenceMatrix",
    -  "IncludeAromaticBonds",
    -  "IncludeConstantBasis",
    -  "IncludeDefinitions",
    -  "IncludeDirectories",
    -  "IncludeFileExtension",
    -  "IncludeGeneratorTasks",
    -  "IncludeHydrogens",
    -  "IncludeInflections",
    -  "IncludeMetaInformation",
    -  "IncludePods",
    -  "IncludeQuantities",
    -  "IncludeRelatedTables",
    -  "IncludeSingularTerm",
    -  "IncludeWindowTimes",
    -  "Increment",
    -  "IndefiniteMatrixQ",
    -  "Indent",
    -  "IndentingNewlineSpacings",
    -  "IndentMaxFraction",
    -  "IndependenceTest",
    -  "IndependentEdgeSetQ",
    -  "IndependentPhysicalQuantity",
    -  "IndependentUnit",
    -  "IndependentUnitDimension",
    -  "IndependentVertexSetQ",
    -  "Indeterminate",
    -  "IndeterminateThreshold",
    -  "IndexCreationOptions",
    -  "Indexed",
    -  "IndexEdgeTaggedGraph",
    -  "IndexGraph",
    -  "IndexTag",
    -  "Inequality",
    -  "InexactNumberQ",
    -  "InexactNumbers",
    -  "InfiniteFuture",
    -  "InfiniteLine",
    -  "InfinitePast",
    -  "InfinitePlane",
    -  "Infinity",
    -  "Infix",
    -  "InflationAdjust",
    -  "InflationMethod",
    -  "Information",
    -  "InformationData",
    -  "InformationDataGrid",
    -  "Inherited",
    -  "InheritScope",
    -  "InhomogeneousPoissonProcess",
    -  "InitialEvaluationHistory",
    -  "Initialization",
    -  "InitializationCell",
    -  "InitializationCellEvaluation",
    -  "InitializationCellWarning",
    -  "InitializationObjects",
    -  "InitializationValue",
    -  "Initialize",
    -  "InitialSeeding",
    -  "InlineCounterAssignments",
    -  "InlineCounterIncrements",
    -  "InlineRules",
    -  "Inner",
    -  "InnerPolygon",
    -  "InnerPolyhedron",
    -  "Inpaint",
    -  "Input",
    -  "InputAliases",
    -  "InputAssumptions",
    -  "InputAutoReplacements",
    -  "InputField",
    -  "InputFieldBox",
    -  "InputFieldBoxOptions",
    -  "InputForm",
    -  "InputGrouping",
    -  "InputNamePacket",
    -  "InputNotebook",
    -  "InputPacket",
    -  "InputSettings",
    -  "InputStream",
    -  "InputString",
    -  "InputStringPacket",
    -  "InputToBoxFormPacket",
    -  "Insert",
    -  "InsertionFunction",
    -  "InsertionPointObject",
    -  "InsertLinebreaks",
    -  "InsertResults",
    -  "Inset",
    -  "Inset3DBox",
    -  "Inset3DBoxOptions",
    -  "InsetBox",
    -  "InsetBoxOptions",
    -  "Insphere",
    -  "Install",
    -  "InstallService",
    -  "InstanceNormalizationLayer",
    -  "InString",
    -  "Integer",
    -  "IntegerDigits",
    -  "IntegerExponent",
    -  "IntegerLength",
    -  "IntegerName",
    -  "IntegerPart",
    -  "IntegerPartitions",
    -  "IntegerQ",
    -  "IntegerReverse",
    -  "Integers",
    -  "IntegerString",
    -  "Integral",
    -  "Integrate",
    -  "Interactive",
    -  "InteractiveTradingChart",
    -  "Interlaced",
    -  "Interleaving",
    -  "InternallyBalancedDecomposition",
    -  "InterpolatingFunction",
    -  "InterpolatingPolynomial",
    -  "Interpolation",
    -  "InterpolationOrder",
    -  "InterpolationPoints",
    -  "InterpolationPrecision",
    -  "Interpretation",
    -  "InterpretationBox",
    -  "InterpretationBoxOptions",
    -  "InterpretationFunction",
    -  "Interpreter",
    -  "InterpretTemplate",
    -  "InterquartileRange",
    -  "Interrupt",
    -  "InterruptSettings",
    -  "IntersectedEntityClass",
    -  "IntersectingQ",
    -  "Intersection",
    -  "Interval",
    -  "IntervalIntersection",
    -  "IntervalMarkers",
    -  "IntervalMarkersStyle",
    -  "IntervalMemberQ",
    -  "IntervalSlider",
    -  "IntervalUnion",
    -  "Into",
    -  "Inverse",
    -  "InverseBetaRegularized",
    -  "InverseCDF",
    -  "InverseChiSquareDistribution",
    -  "InverseContinuousWaveletTransform",
    -  "InverseDistanceTransform",
    -  "InverseEllipticNomeQ",
    -  "InverseErf",
    -  "InverseErfc",
    -  "InverseFourier",
    -  "InverseFourierCosTransform",
    -  "InverseFourierSequenceTransform",
    -  "InverseFourierSinTransform",
    -  "InverseFourierTransform",
    -  "InverseFunction",
    -  "InverseFunctions",
    -  "InverseGammaDistribution",
    -  "InverseGammaRegularized",
    -  "InverseGaussianDistribution",
    -  "InverseGudermannian",
    -  "InverseHankelTransform",
    -  "InverseHaversine",
    -  "InverseImagePyramid",
    -  "InverseJacobiCD",
    -  "InverseJacobiCN",
    -  "InverseJacobiCS",
    -  "InverseJacobiDC",
    -  "InverseJacobiDN",
    -  "InverseJacobiDS",
    -  "InverseJacobiNC",
    -  "InverseJacobiND",
    -  "InverseJacobiNS",
    -  "InverseJacobiSC",
    -  "InverseJacobiSD",
    -  "InverseJacobiSN",
    -  "InverseLaplaceTransform",
    -  "InverseMellinTransform",
    -  "InversePermutation",
    -  "InverseRadon",
    -  "InverseRadonTransform",
    -  "InverseSeries",
    -  "InverseShortTimeFourier",
    -  "InverseSpectrogram",
    -  "InverseSurvivalFunction",
    -  "InverseTransformedRegion",
    -  "InverseWaveletTransform",
    -  "InverseWeierstrassP",
    -  "InverseWishartMatrixDistribution",
    -  "InverseZTransform",
    -  "Invisible",
    -  "InvisibleApplication",
    -  "InvisibleTimes",
    -  "IPAddress",
    -  "IrreduciblePolynomialQ",
    -  "IslandData",
    -  "IsolatingInterval",
    -  "IsomorphicGraphQ",
    -  "IsotopeData",
    -  "Italic",
    -  "Item",
    -  "ItemAspectRatio",
    -  "ItemBox",
    -  "ItemBoxOptions",
    -  "ItemDisplayFunction",
    -  "ItemSize",
    -  "ItemStyle",
    -  "ItoProcess",
    -  "JaccardDissimilarity",
    -  "JacobiAmplitude",
    -  "Jacobian",
    -  "JacobiCD",
    -  "JacobiCN",
    -  "JacobiCS",
    -  "JacobiDC",
    -  "JacobiDN",
    -  "JacobiDS",
    -  "JacobiNC",
    -  "JacobiND",
    -  "JacobiNS",
    -  "JacobiP",
    -  "JacobiSC",
    -  "JacobiSD",
    -  "JacobiSN",
    -  "JacobiSymbol",
    -  "JacobiZeta",
    -  "JankoGroupJ1",
    -  "JankoGroupJ2",
    -  "JankoGroupJ3",
    -  "JankoGroupJ4",
    -  "JarqueBeraALMTest",
    -  "JohnsonDistribution",
    -  "Join",
    -  "JoinAcross",
    -  "Joined",
    -  "JoinedCurve",
    -  "JoinedCurveBox",
    -  "JoinedCurveBoxOptions",
    -  "JoinForm",
    -  "JordanDecomposition",
    -  "JordanModelDecomposition",
    -  "JulianDate",
    -  "JuliaSetBoettcher",
    -  "JuliaSetIterationCount",
    -  "JuliaSetPlot",
    -  "JuliaSetPoints",
    -  "K",
    -  "KagiChart",
    -  "KaiserBesselWindow",
    -  "KaiserWindow",
    -  "KalmanEstimator",
    -  "KalmanFilter",
    -  "KarhunenLoeveDecomposition",
    -  "KaryTree",
    -  "KatzCentrality",
    -  "KCoreComponents",
    -  "KDistribution",
    -  "KEdgeConnectedComponents",
    -  "KEdgeConnectedGraphQ",
    -  "KeepExistingVersion",
    -  "KelvinBei",
    -  "KelvinBer",
    -  "KelvinKei",
    -  "KelvinKer",
    -  "KendallTau",
    -  "KendallTauTest",
    -  "KernelExecute",
    -  "KernelFunction",
    -  "KernelMixtureDistribution",
    -  "KernelObject",
    -  "Kernels",
    -  "Ket",
    -  "Key",
    -  "KeyCollisionFunction",
    -  "KeyComplement",
    -  "KeyDrop",
    -  "KeyDropFrom",
    -  "KeyExistsQ",
    -  "KeyFreeQ",
    -  "KeyIntersection",
    -  "KeyMap",
    -  "KeyMemberQ",
    -  "KeypointStrength",
    -  "Keys",
    -  "KeySelect",
    -  "KeySort",
    -  "KeySortBy",
    -  "KeyTake",
    -  "KeyUnion",
    -  "KeyValueMap",
    -  "KeyValuePattern",
    -  "Khinchin",
    -  "KillProcess",
    -  "KirchhoffGraph",
    -  "KirchhoffMatrix",
    -  "KleinInvariantJ",
    -  "KnapsackSolve",
    -  "KnightTourGraph",
    -  "KnotData",
    -  "KnownUnitQ",
    -  "KochCurve",
    -  "KolmogorovSmirnovTest",
    -  "KroneckerDelta",
    -  "KroneckerModelDecomposition",
    -  "KroneckerProduct",
    -  "KroneckerSymbol",
    -  "KuiperTest",
    -  "KumaraswamyDistribution",
    -  "Kurtosis",
    -  "KuwaharaFilter",
    -  "KVertexConnectedComponents",
    -  "KVertexConnectedGraphQ",
    -  "LABColor",
    -  "Label",
    -  "Labeled",
    -  "LabeledSlider",
    -  "LabelingFunction",
    -  "LabelingSize",
    -  "LabelStyle",
    -  "LabelVisibility",
    -  "LaguerreL",
    -  "LakeData",
    -  "LambdaComponents",
    -  "LambertW",
    -  "LaminaData",
    -  "LanczosWindow",
    -  "LandauDistribution",
    -  "Language",
    -  "LanguageCategory",
    -  "LanguageData",
    -  "LanguageIdentify",
    -  "LanguageOptions",
    -  "LaplaceDistribution",
    -  "LaplaceTransform",
    -  "Laplacian",
    -  "LaplacianFilter",
    -  "LaplacianGaussianFilter",
    -  "Large",
    -  "Larger",
    -  "Last",
    -  "Latitude",
    -  "LatitudeLongitude",
    -  "LatticeData",
    -  "LatticeReduce",
    -  "Launch",
    -  "LaunchKernels",
    -  "LayeredGraphPlot",
    -  "LayerSizeFunction",
    -  "LayoutInformation",
    -  "LCHColor",
    -  "LCM",
    -  "LeaderSize",
    -  "LeafCount",
    -  "LeapYearQ",
    -  "LearnDistribution",
    -  "LearnedDistribution",
    -  "LearningRate",
    -  "LearningRateMultipliers",
    -  "LeastSquares",
    -  "LeastSquaresFilterKernel",
    -  "Left",
    -  "LeftArrow",
    -  "LeftArrowBar",
    -  "LeftArrowRightArrow",
    -  "LeftDownTeeVector",
    -  "LeftDownVector",
    -  "LeftDownVectorBar",
    -  "LeftRightArrow",
    -  "LeftRightVector",
    -  "LeftTee",
    -  "LeftTeeArrow",
    -  "LeftTeeVector",
    -  "LeftTriangle",
    -  "LeftTriangleBar",
    -  "LeftTriangleEqual",
    -  "LeftUpDownVector",
    -  "LeftUpTeeVector",
    -  "LeftUpVector",
    -  "LeftUpVectorBar",
    -  "LeftVector",
    -  "LeftVectorBar",
    -  "LegendAppearance",
    -  "Legended",
    -  "LegendFunction",
    -  "LegendLabel",
    -  "LegendLayout",
    -  "LegendMargins",
    -  "LegendMarkers",
    -  "LegendMarkerSize",
    -  "LegendreP",
    -  "LegendreQ",
    -  "LegendreType",
    -  "Length",
    -  "LengthWhile",
    -  "LerchPhi",
    -  "Less",
    -  "LessEqual",
    -  "LessEqualGreater",
    -  "LessEqualThan",
    -  "LessFullEqual",
    -  "LessGreater",
    -  "LessLess",
    -  "LessSlantEqual",
    -  "LessThan",
    -  "LessTilde",
    -  "LetterCharacter",
    -  "LetterCounts",
    -  "LetterNumber",
    -  "LetterQ",
    -  "Level",
    -  "LeveneTest",
    -  "LeviCivitaTensor",
    -  "LevyDistribution",
    -  "Lexicographic",
    -  "LibraryDataType",
    -  "LibraryFunction",
    -  "LibraryFunctionError",
    -  "LibraryFunctionInformation",
    -  "LibraryFunctionLoad",
    -  "LibraryFunctionUnload",
    -  "LibraryLoad",
    -  "LibraryUnload",
    -  "LicenseID",
    -  "LiftingFilterData",
    -  "LiftingWaveletTransform",
    -  "LightBlue",
    -  "LightBrown",
    -  "LightCyan",
    -  "Lighter",
    -  "LightGray",
    -  "LightGreen",
    -  "Lighting",
    -  "LightingAngle",
    -  "LightMagenta",
    -  "LightOrange",
    -  "LightPink",
    -  "LightPurple",
    -  "LightRed",
    -  "LightSources",
    -  "LightYellow",
    -  "Likelihood",
    -  "Limit",
    -  "LimitsPositioning",
    -  "LimitsPositioningTokens",
    -  "LindleyDistribution",
    -  "Line",
    -  "Line3DBox",
    -  "Line3DBoxOptions",
    -  "LinearFilter",
    -  "LinearFractionalOptimization",
    -  "LinearFractionalTransform",
    -  "LinearGradientImage",
    -  "LinearizingTransformationData",
    -  "LinearLayer",
    -  "LinearModelFit",
    -  "LinearOffsetFunction",
    -  "LinearOptimization",
    -  "LinearProgramming",
    -  "LinearRecurrence",
    -  "LinearSolve",
    -  "LinearSolveFunction",
    -  "LineBox",
    -  "LineBoxOptions",
    -  "LineBreak",
    -  "LinebreakAdjustments",
    -  "LineBreakChart",
    -  "LinebreakSemicolonWeighting",
    -  "LineBreakWithin",
    -  "LineColor",
    -  "LineGraph",
    -  "LineIndent",
    -  "LineIndentMaxFraction",
    -  "LineIntegralConvolutionPlot",
    -  "LineIntegralConvolutionScale",
    -  "LineLegend",
    -  "LineOpacity",
    -  "LineSpacing",
    -  "LineWrapParts",
    -  "LinkActivate",
    -  "LinkClose",
    -  "LinkConnect",
    -  "LinkConnectedQ",
    -  "LinkCreate",
    -  "LinkError",
    -  "LinkFlush",
    -  "LinkFunction",
    -  "LinkHost",
    -  "LinkInterrupt",
    -  "LinkLaunch",
    -  "LinkMode",
    -  "LinkObject",
    -  "LinkOpen",
    -  "LinkOptions",
    -  "LinkPatterns",
    -  "LinkProtocol",
    -  "LinkRankCentrality",
    -  "LinkRead",
    -  "LinkReadHeld",
    -  "LinkReadyQ",
    -  "Links",
    -  "LinkService",
    -  "LinkWrite",
    -  "LinkWriteHeld",
    -  "LiouvilleLambda",
    -  "List",
    -  "Listable",
    -  "ListAnimate",
    -  "ListContourPlot",
    -  "ListContourPlot3D",
    -  "ListConvolve",
    -  "ListCorrelate",
    -  "ListCurvePathPlot",
    -  "ListDeconvolve",
    -  "ListDensityPlot",
    -  "ListDensityPlot3D",
    -  "Listen",
    -  "ListFormat",
    -  "ListFourierSequenceTransform",
    -  "ListInterpolation",
    -  "ListLineIntegralConvolutionPlot",
    -  "ListLinePlot",
    -  "ListLogLinearPlot",
    -  "ListLogLogPlot",
    -  "ListLogPlot",
    -  "ListPicker",
    -  "ListPickerBox",
    -  "ListPickerBoxBackground",
    -  "ListPickerBoxOptions",
    -  "ListPlay",
    -  "ListPlot",
    -  "ListPlot3D",
    -  "ListPointPlot3D",
    -  "ListPolarPlot",
    -  "ListQ",
    -  "ListSliceContourPlot3D",
    -  "ListSliceDensityPlot3D",
    -  "ListSliceVectorPlot3D",
    -  "ListStepPlot",
    -  "ListStreamDensityPlot",
    -  "ListStreamPlot",
    -  "ListSurfacePlot3D",
    -  "ListVectorDensityPlot",
    -  "ListVectorPlot",
    -  "ListVectorPlot3D",
    -  "ListZTransform",
    -  "Literal",
    -  "LiteralSearch",
    -  "LocalAdaptiveBinarize",
    -  "LocalCache",
    -  "LocalClusteringCoefficient",
    -  "LocalizeDefinitions",
    -  "LocalizeVariables",
    -  "LocalObject",
    -  "LocalObjects",
    -  "LocalResponseNormalizationLayer",
    -  "LocalSubmit",
    -  "LocalSymbol",
    -  "LocalTime",
    -  "LocalTimeZone",
    -  "LocationEquivalenceTest",
    -  "LocationTest",
    -  "Locator",
    -  "LocatorAutoCreate",
    -  "LocatorBox",
    -  "LocatorBoxOptions",
    -  "LocatorCentering",
    -  "LocatorPane",
    -  "LocatorPaneBox",
    -  "LocatorPaneBoxOptions",
    -  "LocatorRegion",
    -  "Locked",
    -  "Log",
    -  "Log10",
    -  "Log2",
    -  "LogBarnesG",
    -  "LogGamma",
    -  "LogGammaDistribution",
    -  "LogicalExpand",
    -  "LogIntegral",
    -  "LogisticDistribution",
    -  "LogisticSigmoid",
    -  "LogitModelFit",
    -  "LogLikelihood",
    -  "LogLinearPlot",
    -  "LogLogisticDistribution",
    -  "LogLogPlot",
    -  "LogMultinormalDistribution",
    -  "LogNormalDistribution",
    -  "LogPlot",
    -  "LogRankTest",
    -  "LogSeriesDistribution",
    -  "LongEqual",
    -  "Longest",
    -  "LongestCommonSequence",
    -  "LongestCommonSequencePositions",
    -  "LongestCommonSubsequence",
    -  "LongestCommonSubsequencePositions",
    -  "LongestMatch",
    -  "LongestOrderedSequence",
    -  "LongForm",
    -  "Longitude",
    -  "LongLeftArrow",
    -  "LongLeftRightArrow",
    -  "LongRightArrow",
    -  "LongShortTermMemoryLayer",
    -  "Lookup",
    -  "Loopback",
    -  "LoopFreeGraphQ",
    -  "Looping",
    -  "LossFunction",
    -  "LowerCaseQ",
    -  "LowerLeftArrow",
    -  "LowerRightArrow",
    -  "LowerTriangularize",
    -  "LowerTriangularMatrixQ",
    -  "LowpassFilter",
    -  "LQEstimatorGains",
    -  "LQGRegulator",
    -  "LQOutputRegulatorGains",
    -  "LQRegulatorGains",
    -  "LUBackSubstitution",
    -  "LucasL",
    -  "LuccioSamiComponents",
    -  "LUDecomposition",
    -  "LunarEclipse",
    -  "LUVColor",
    -  "LyapunovSolve",
    -  "LyonsGroupLy",
    -  "MachineID",
    -  "MachineName",
    -  "MachineNumberQ",
    -  "MachinePrecision",
    -  "MacintoshSystemPageSetup",
    -  "Magenta",
    -  "Magnification",
    -  "Magnify",
    -  "MailAddressValidation",
    -  "MailExecute",
    -  "MailFolder",
    -  "MailItem",
    -  "MailReceiverFunction",
    -  "MailResponseFunction",
    -  "MailSearch",
    -  "MailServerConnect",
    -  "MailServerConnection",
    -  "MailSettings",
    -  "MainSolve",
    -  "MaintainDynamicCaches",
    -  "Majority",
    -  "MakeBoxes",
    -  "MakeExpression",
    -  "MakeRules",
    -  "ManagedLibraryExpressionID",
    -  "ManagedLibraryExpressionQ",
    -  "MandelbrotSetBoettcher",
    -  "MandelbrotSetDistance",
    -  "MandelbrotSetIterationCount",
    -  "MandelbrotSetMemberQ",
    -  "MandelbrotSetPlot",
    -  "MangoldtLambda",
    -  "ManhattanDistance",
    -  "Manipulate",
    -  "Manipulator",
    -  "MannedSpaceMissionData",
    -  "MannWhitneyTest",
    -  "MantissaExponent",
    -  "Manual",
    -  "Map",
    -  "MapAll",
    -  "MapAt",
    -  "MapIndexed",
    -  "MAProcess",
    -  "MapThread",
    -  "MarchenkoPasturDistribution",
    -  "MarcumQ",
    -  "MardiaCombinedTest",
    -  "MardiaKurtosisTest",
    -  "MardiaSkewnessTest",
    -  "MarginalDistribution",
    -  "MarkovProcessProperties",
    -  "Masking",
    -  "MatchingDissimilarity",
    -  "MatchLocalNameQ",
    -  "MatchLocalNames",
    -  "MatchQ",
    -  "Material",
    -  "MathematicalFunctionData",
    -  "MathematicaNotation",
    -  "MathieuC",
    -  "MathieuCharacteristicA",
    -  "MathieuCharacteristicB",
    -  "MathieuCharacteristicExponent",
    -  "MathieuCPrime",
    -  "MathieuGroupM11",
    -  "MathieuGroupM12",
    -  "MathieuGroupM22",
    -  "MathieuGroupM23",
    -  "MathieuGroupM24",
    -  "MathieuS",
    -  "MathieuSPrime",
    -  "MathMLForm",
    -  "MathMLText",
    -  "Matrices",
    -  "MatrixExp",
    -  "MatrixForm",
    -  "MatrixFunction",
    -  "MatrixLog",
    -  "MatrixNormalDistribution",
    -  "MatrixPlot",
    -  "MatrixPower",
    -  "MatrixPropertyDistribution",
    -  "MatrixQ",
    -  "MatrixRank",
    -  "MatrixTDistribution",
    -  "Max",
    -  "MaxBend",
    -  "MaxCellMeasure",
    -  "MaxColorDistance",
    -  "MaxDate",
    -  "MaxDetect",
    -  "MaxDuration",
    -  "MaxExtraBandwidths",
    -  "MaxExtraConditions",
    -  "MaxFeatureDisplacement",
    -  "MaxFeatures",
    -  "MaxFilter",
    -  "MaximalBy",
    -  "Maximize",
    -  "MaxItems",
    -  "MaxIterations",
    -  "MaxLimit",
    -  "MaxMemoryUsed",
    -  "MaxMixtureKernels",
    -  "MaxOverlapFraction",
    -  "MaxPlotPoints",
    -  "MaxPoints",
    -  "MaxRecursion",
    -  "MaxStableDistribution",
    -  "MaxStepFraction",
    -  "MaxSteps",
    -  "MaxStepSize",
    -  "MaxTrainingRounds",
    -  "MaxValue",
    -  "MaxwellDistribution",
    -  "MaxWordGap",
    -  "McLaughlinGroupMcL",
    -  "Mean",
    -  "MeanAbsoluteLossLayer",
    -  "MeanAround",
    -  "MeanClusteringCoefficient",
    -  "MeanDegreeConnectivity",
    -  "MeanDeviation",
    -  "MeanFilter",
    -  "MeanGraphDistance",
    -  "MeanNeighborDegree",
    -  "MeanShift",
    -  "MeanShiftFilter",
    -  "MeanSquaredLossLayer",
    -  "Median",
    -  "MedianDeviation",
    -  "MedianFilter",
    -  "MedicalTestData",
    -  "Medium",
    -  "MeijerG",
    -  "MeijerGReduce",
    -  "MeixnerDistribution",
    -  "MellinConvolve",
    -  "MellinTransform",
    -  "MemberQ",
    -  "MemoryAvailable",
    -  "MemoryConstrained",
    -  "MemoryConstraint",
    -  "MemoryInUse",
    -  "MengerMesh",
    -  "Menu",
    -  "MenuAppearance",
    -  "MenuCommandKey",
    -  "MenuEvaluator",
    -  "MenuItem",
    -  "MenuList",
    -  "MenuPacket",
    -  "MenuSortingValue",
    -  "MenuStyle",
    -  "MenuView",
    -  "Merge",
    -  "MergeDifferences",
    -  "MergingFunction",
    -  "MersennePrimeExponent",
    -  "MersennePrimeExponentQ",
    -  "Mesh",
    -  "MeshCellCentroid",
    -  "MeshCellCount",
    -  "MeshCellHighlight",
    -  "MeshCellIndex",
    -  "MeshCellLabel",
    -  "MeshCellMarker",
    -  "MeshCellMeasure",
    -  "MeshCellQuality",
    -  "MeshCells",
    -  "MeshCellShapeFunction",
    -  "MeshCellStyle",
    -  "MeshConnectivityGraph",
    -  "MeshCoordinates",
    -  "MeshFunctions",
    -  "MeshPrimitives",
    -  "MeshQualityGoal",
    -  "MeshRange",
    -  "MeshRefinementFunction",
    -  "MeshRegion",
    -  "MeshRegionQ",
    -  "MeshShading",
    -  "MeshStyle",
    -  "Message",
    -  "MessageDialog",
    -  "MessageList",
    -  "MessageName",
    -  "MessageObject",
    -  "MessageOptions",
    -  "MessagePacket",
    -  "Messages",
    -  "MessagesNotebook",
    -  "MetaCharacters",
    -  "MetaInformation",
    -  "MeteorShowerData",
    -  "Method",
    -  "MethodOptions",
    -  "MexicanHatWavelet",
    -  "MeyerWavelet",
    -  "Midpoint",
    -  "Min",
    -  "MinColorDistance",
    -  "MinDate",
    -  "MinDetect",
    -  "MineralData",
    -  "MinFilter",
    -  "MinimalBy",
    -  "MinimalPolynomial",
    -  "MinimalStateSpaceModel",
    -  "Minimize",
    -  "MinimumTimeIncrement",
    -  "MinIntervalSize",
    -  "MinkowskiQuestionMark",
    -  "MinLimit",
    -  "MinMax",
    -  "MinorPlanetData",
    -  "Minors",
    -  "MinRecursion",
    -  "MinSize",
    -  "MinStableDistribution",
    -  "Minus",
    -  "MinusPlus",
    -  "MinValue",
    -  "Missing",
    -  "MissingBehavior",
    -  "MissingDataMethod",
    -  "MissingDataRules",
    -  "MissingQ",
    -  "MissingString",
    -  "MissingStyle",
    -  "MissingValuePattern",
    -  "MittagLefflerE",
    -  "MixedFractionParts",
    -  "MixedGraphQ",
    -  "MixedMagnitude",
    -  "MixedRadix",
    -  "MixedRadixQuantity",
    -  "MixedUnit",
    -  "MixtureDistribution",
    -  "Mod",
    -  "Modal",
    -  "Mode",
    -  "Modular",
    -  "ModularInverse",
    -  "ModularLambda",
    -  "Module",
    -  "Modulus",
    -  "MoebiusMu",
    -  "Molecule",
    -  "MoleculeContainsQ",
    -  "MoleculeEquivalentQ",
    -  "MoleculeGraph",
    -  "MoleculeModify",
    -  "MoleculePattern",
    -  "MoleculePlot",
    -  "MoleculePlot3D",
    -  "MoleculeProperty",
    -  "MoleculeQ",
    -  "MoleculeRecognize",
    -  "MoleculeValue",
    -  "Moment",
    -  "Momentary",
    -  "MomentConvert",
    -  "MomentEvaluate",
    -  "MomentGeneratingFunction",
    -  "MomentOfInertia",
    -  "Monday",
    -  "Monitor",
    -  "MonomialList",
    -  "MonomialOrder",
    -  "MonsterGroupM",
    -  "MoonPhase",
    -  "MoonPosition",
    -  "MorletWavelet",
    -  "MorphologicalBinarize",
    -  "MorphologicalBranchPoints",
    -  "MorphologicalComponents",
    -  "MorphologicalEulerNumber",
    -  "MorphologicalGraph",
    -  "MorphologicalPerimeter",
    -  "MorphologicalTransform",
    -  "MortalityData",
    -  "Most",
    -  "MountainData",
    -  "MouseAnnotation",
    -  "MouseAppearance",
    -  "MouseAppearanceTag",
    -  "MouseButtons",
    -  "Mouseover",
    -  "MousePointerNote",
    -  "MousePosition",
    -  "MovieData",
    -  "MovingAverage",
    -  "MovingMap",
    -  "MovingMedian",
    -  "MoyalDistribution",
    -  "Multicolumn",
    -  "MultiedgeStyle",
    -  "MultigraphQ",
    -  "MultilaunchWarning",
    -  "MultiLetterItalics",
    -  "MultiLetterStyle",
    -  "MultilineFunction",
    -  "Multinomial",
    -  "MultinomialDistribution",
    -  "MultinormalDistribution",
    -  "MultiplicativeOrder",
    -  "Multiplicity",
    -  "MultiplySides",
    -  "Multiselection",
    -  "MultivariateHypergeometricDistribution",
    -  "MultivariatePoissonDistribution",
    -  "MultivariateTDistribution",
    -  "N",
    -  "NakagamiDistribution",
    -  "NameQ",
    -  "Names",
    -  "NamespaceBox",
    -  "NamespaceBoxOptions",
    -  "Nand",
    -  "NArgMax",
    -  "NArgMin",
    -  "NBernoulliB",
    -  "NBodySimulation",
    -  "NBodySimulationData",
    -  "NCache",
    -  "NDEigensystem",
    -  "NDEigenvalues",
    -  "NDSolve",
    -  "NDSolveValue",
    -  "Nearest",
    -  "NearestFunction",
    -  "NearestMeshCells",
    -  "NearestNeighborGraph",
    -  "NearestTo",
    -  "NebulaData",
    -  "NeedCurrentFrontEndPackagePacket",
    -  "NeedCurrentFrontEndSymbolsPacket",
    -  "NeedlemanWunschSimilarity",
    -  "Needs",
    -  "Negative",
    -  "NegativeBinomialDistribution",
    -  "NegativeDefiniteMatrixQ",
    -  "NegativeIntegers",
    -  "NegativeMultinomialDistribution",
    -  "NegativeRationals",
    -  "NegativeReals",
    -  "NegativeSemidefiniteMatrixQ",
    -  "NeighborhoodData",
    -  "NeighborhoodGraph",
    -  "Nest",
    -  "NestedGreaterGreater",
    -  "NestedLessLess",
    -  "NestedScriptRules",
    -  "NestGraph",
    -  "NestList",
    -  "NestWhile",
    -  "NestWhileList",
    -  "NetAppend",
    -  "NetBidirectionalOperator",
    -  "NetChain",
    -  "NetDecoder",
    -  "NetDelete",
    -  "NetDrop",
    -  "NetEncoder",
    -  "NetEvaluationMode",
    -  "NetExtract",
    -  "NetFlatten",
    -  "NetFoldOperator",
    -  "NetGANOperator",
    -  "NetGraph",
    -  "NetInformation",
    -  "NetInitialize",
    -  "NetInsert",
    -  "NetInsertSharedArrays",
    -  "NetJoin",
    -  "NetMapOperator",
    -  "NetMapThreadOperator",
    -  "NetMeasurements",
    -  "NetModel",
    -  "NetNestOperator",
    -  "NetPairEmbeddingOperator",
    -  "NetPort",
    -  "NetPortGradient",
    -  "NetPrepend",
    -  "NetRename",
    -  "NetReplace",
    -  "NetReplacePart",
    -  "NetSharedArray",
    -  "NetStateObject",
    -  "NetTake",
    -  "NetTrain",
    -  "NetTrainResultsObject",
    -  "NetworkPacketCapture",
    -  "NetworkPacketRecording",
    -  "NetworkPacketRecordingDuring",
    -  "NetworkPacketTrace",
    -  "NeumannValue",
    -  "NevilleThetaC",
    -  "NevilleThetaD",
    -  "NevilleThetaN",
    -  "NevilleThetaS",
    -  "NewPrimitiveStyle",
    -  "NExpectation",
    -  "Next",
    -  "NextCell",
    -  "NextDate",
    -  "NextPrime",
    -  "NextScheduledTaskTime",
    -  "NHoldAll",
    -  "NHoldFirst",
    -  "NHoldRest",
    -  "NicholsGridLines",
    -  "NicholsPlot",
    -  "NightHemisphere",
    -  "NIntegrate",
    -  "NMaximize",
    -  "NMaxValue",
    -  "NMinimize",
    -  "NMinValue",
    -  "NominalVariables",
    -  "NonAssociative",
    -  "NoncentralBetaDistribution",
    -  "NoncentralChiSquareDistribution",
    -  "NoncentralFRatioDistribution",
    -  "NoncentralStudentTDistribution",
    -  "NonCommutativeMultiply",
    -  "NonConstants",
    -  "NondimensionalizationTransform",
    -  "None",
    -  "NoneTrue",
    -  "NonlinearModelFit",
    -  "NonlinearStateSpaceModel",
    -  "NonlocalMeansFilter",
    -  "NonNegative",
    -  "NonNegativeIntegers",
    -  "NonNegativeRationals",
    -  "NonNegativeReals",
    -  "NonPositive",
    -  "NonPositiveIntegers",
    -  "NonPositiveRationals",
    -  "NonPositiveReals",
    -  "Nor",
    -  "NorlundB",
    -  "Norm",
    -  "Normal",
    -  "NormalDistribution",
    -  "NormalGrouping",
    -  "NormalizationLayer",
    -  "Normalize",
    -  "Normalized",
    -  "NormalizedSquaredEuclideanDistance",
    -  "NormalMatrixQ",
    -  "NormalsFunction",
    -  "NormFunction",
    -  "Not",
    -  "NotCongruent",
    -  "NotCupCap",
    -  "NotDoubleVerticalBar",
    -  "Notebook",
    -  "NotebookApply",
    -  "NotebookAutoSave",
    -  "NotebookClose",
    -  "NotebookConvertSettings",
    -  "NotebookCreate",
    -  "NotebookCreateReturnObject",
    -  "NotebookDefault",
    -  "NotebookDelete",
    -  "NotebookDirectory",
    -  "NotebookDynamicExpression",
    -  "NotebookEvaluate",
    -  "NotebookEventActions",
    -  "NotebookFileName",
    -  "NotebookFind",
    -  "NotebookFindReturnObject",
    -  "NotebookGet",
    -  "NotebookGetLayoutInformationPacket",
    -  "NotebookGetMisspellingsPacket",
    -  "NotebookImport",
    -  "NotebookInformation",
    -  "NotebookInterfaceObject",
    -  "NotebookLocate",
    -  "NotebookObject",
    -  "NotebookOpen",
    -  "NotebookOpenReturnObject",
    -  "NotebookPath",
    -  "NotebookPrint",
    -  "NotebookPut",
    -  "NotebookPutReturnObject",
    -  "NotebookRead",
    -  "NotebookResetGeneratedCells",
    -  "Notebooks",
    -  "NotebookSave",
    -  "NotebookSaveAs",
    -  "NotebookSelection",
    -  "NotebookSetupLayoutInformationPacket",
    -  "NotebooksMenu",
    -  "NotebookTemplate",
    -  "NotebookWrite",
    -  "NotElement",
    -  "NotEqualTilde",
    -  "NotExists",
    -  "NotGreater",
    -  "NotGreaterEqual",
    -  "NotGreaterFullEqual",
    -  "NotGreaterGreater",
    -  "NotGreaterLess",
    -  "NotGreaterSlantEqual",
    -  "NotGreaterTilde",
    -  "Nothing",
    -  "NotHumpDownHump",
    -  "NotHumpEqual",
    -  "NotificationFunction",
    -  "NotLeftTriangle",
    -  "NotLeftTriangleBar",
    -  "NotLeftTriangleEqual",
    -  "NotLess",
    -  "NotLessEqual",
    -  "NotLessFullEqual",
    -  "NotLessGreater",
    -  "NotLessLess",
    -  "NotLessSlantEqual",
    -  "NotLessTilde",
    -  "NotNestedGreaterGreater",
    -  "NotNestedLessLess",
    -  "NotPrecedes",
    -  "NotPrecedesEqual",
    -  "NotPrecedesSlantEqual",
    -  "NotPrecedesTilde",
    -  "NotReverseElement",
    -  "NotRightTriangle",
    -  "NotRightTriangleBar",
    -  "NotRightTriangleEqual",
    -  "NotSquareSubset",
    -  "NotSquareSubsetEqual",
    -  "NotSquareSuperset",
    -  "NotSquareSupersetEqual",
    -  "NotSubset",
    -  "NotSubsetEqual",
    -  "NotSucceeds",
    -  "NotSucceedsEqual",
    -  "NotSucceedsSlantEqual",
    -  "NotSucceedsTilde",
    -  "NotSuperset",
    -  "NotSupersetEqual",
    -  "NotTilde",
    -  "NotTildeEqual",
    -  "NotTildeFullEqual",
    -  "NotTildeTilde",
    -  "NotVerticalBar",
    -  "Now",
    -  "NoWhitespace",
    -  "NProbability",
    -  "NProduct",
    -  "NProductFactors",
    -  "NRoots",
    -  "NSolve",
    -  "NSum",
    -  "NSumTerms",
    -  "NuclearExplosionData",
    -  "NuclearReactorData",
    -  "Null",
    -  "NullRecords",
    -  "NullSpace",
    -  "NullWords",
    -  "Number",
    -  "NumberCompose",
    -  "NumberDecompose",
    -  "NumberExpand",
    -  "NumberFieldClassNumber",
    -  "NumberFieldDiscriminant",
    -  "NumberFieldFundamentalUnits",
    -  "NumberFieldIntegralBasis",
    -  "NumberFieldNormRepresentatives",
    -  "NumberFieldRegulator",
    -  "NumberFieldRootsOfUnity",
    -  "NumberFieldSignature",
    -  "NumberForm",
    -  "NumberFormat",
    -  "NumberLinePlot",
    -  "NumberMarks",
    -  "NumberMultiplier",
    -  "NumberPadding",
    -  "NumberPoint",
    -  "NumberQ",
    -  "NumberSeparator",
    -  "NumberSigns",
    -  "NumberString",
    -  "Numerator",
    -  "NumeratorDenominator",
    -  "NumericalOrder",
    -  "NumericalSort",
    -  "NumericArray",
    -  "NumericArrayQ",
    -  "NumericArrayType",
    -  "NumericFunction",
    -  "NumericQ",
    -  "NuttallWindow",
    -  "NValues",
    -  "NyquistGridLines",
    -  "NyquistPlot",
    -  "O",
    -  "ObservabilityGramian",
    -  "ObservabilityMatrix",
    -  "ObservableDecomposition",
    -  "ObservableModelQ",
    -  "OceanData",
    -  "Octahedron",
    -  "OddQ",
    -  "Off",
    -  "Offset",
    -  "OLEData",
    -  "On",
    -  "ONanGroupON",
    -  "Once",
    -  "OneIdentity",
    -  "Opacity",
    -  "OpacityFunction",
    -  "OpacityFunctionScaling",
    -  "Open",
    -  "OpenAppend",
    -  "Opener",
    -  "OpenerBox",
    -  "OpenerBoxOptions",
    -  "OpenerView",
    -  "OpenFunctionInspectorPacket",
    -  "Opening",
    -  "OpenRead",
    -  "OpenSpecialOptions",
    -  "OpenTemporary",
    -  "OpenWrite",
    -  "Operate",
    -  "OperatingSystem",
    -  "OperatorApplied",
    -  "OptimumFlowData",
    -  "Optional",
    -  "OptionalElement",
    -  "OptionInspectorSettings",
    -  "OptionQ",
    -  "Options",
    -  "OptionsPacket",
    -  "OptionsPattern",
    -  "OptionValue",
    -  "OptionValueBox",
    -  "OptionValueBoxOptions",
    -  "Or",
    -  "Orange",
    -  "Order",
    -  "OrderDistribution",
    -  "OrderedQ",
    -  "Ordering",
    -  "OrderingBy",
    -  "OrderingLayer",
    -  "Orderless",
    -  "OrderlessPatternSequence",
    -  "OrnsteinUhlenbeckProcess",
    -  "Orthogonalize",
    -  "OrthogonalMatrixQ",
    -  "Out",
    -  "Outer",
    -  "OuterPolygon",
    -  "OuterPolyhedron",
    -  "OutputAutoOverwrite",
    -  "OutputControllabilityMatrix",
    -  "OutputControllableModelQ",
    -  "OutputForm",
    -  "OutputFormData",
    -  "OutputGrouping",
    -  "OutputMathEditExpression",
    -  "OutputNamePacket",
    -  "OutputResponse",
    -  "OutputSizeLimit",
    -  "OutputStream",
    -  "Over",
    -  "OverBar",
    -  "OverDot",
    -  "Overflow",
    -  "OverHat",
    -  "Overlaps",
    -  "Overlay",
    -  "OverlayBox",
    -  "OverlayBoxOptions",
    -  "Overscript",
    -  "OverscriptBox",
    -  "OverscriptBoxOptions",
    -  "OverTilde",
    -  "OverVector",
    -  "OverwriteTarget",
    -  "OwenT",
    -  "OwnValues",
    -  "Package",
    -  "PackingMethod",
    -  "PackPaclet",
    -  "PacletDataRebuild",
    -  "PacletDirectoryAdd",
    -  "PacletDirectoryLoad",
    -  "PacletDirectoryRemove",
    -  "PacletDirectoryUnload",
    -  "PacletDisable",
    -  "PacletEnable",
    -  "PacletFind",
    -  "PacletFindRemote",
    -  "PacletInformation",
    -  "PacletInstall",
    -  "PacletInstallSubmit",
    -  "PacletNewerQ",
    -  "PacletObject",
    -  "PacletObjectQ",
    -  "PacletSite",
    -  "PacletSiteObject",
    -  "PacletSiteRegister",
    -  "PacletSites",
    -  "PacletSiteUnregister",
    -  "PacletSiteUpdate",
    -  "PacletUninstall",
    -  "PacletUpdate",
    -  "PaddedForm",
    -  "Padding",
    -  "PaddingLayer",
    -  "PaddingSize",
    -  "PadeApproximant",
    -  "PadLeft",
    -  "PadRight",
    -  "PageBreakAbove",
    -  "PageBreakBelow",
    -  "PageBreakWithin",
    -  "PageFooterLines",
    -  "PageFooters",
    -  "PageHeaderLines",
    -  "PageHeaders",
    -  "PageHeight",
    -  "PageRankCentrality",
    -  "PageTheme",
    -  "PageWidth",
    -  "Pagination",
    -  "PairedBarChart",
    -  "PairedHistogram",
    -  "PairedSmoothHistogram",
    -  "PairedTTest",
    -  "PairedZTest",
    -  "PaletteNotebook",
    -  "PalettePath",
    -  "PalindromeQ",
    -  "Pane",
    -  "PaneBox",
    -  "PaneBoxOptions",
    -  "Panel",
    -  "PanelBox",
    -  "PanelBoxOptions",
    -  "Paneled",
    -  "PaneSelector",
    -  "PaneSelectorBox",
    -  "PaneSelectorBoxOptions",
    -  "PaperWidth",
    -  "ParabolicCylinderD",
    -  "ParagraphIndent",
    -  "ParagraphSpacing",
    -  "ParallelArray",
    -  "ParallelCombine",
    -  "ParallelDo",
    -  "Parallelepiped",
    -  "ParallelEvaluate",
    -  "Parallelization",
    -  "Parallelize",
    -  "ParallelMap",
    -  "ParallelNeeds",
    -  "Parallelogram",
    -  "ParallelProduct",
    -  "ParallelSubmit",
    -  "ParallelSum",
    -  "ParallelTable",
    -  "ParallelTry",
    -  "Parameter",
    -  "ParameterEstimator",
    -  "ParameterMixtureDistribution",
    -  "ParameterVariables",
    -  "ParametricFunction",
    -  "ParametricNDSolve",
    -  "ParametricNDSolveValue",
    -  "ParametricPlot",
    -  "ParametricPlot3D",
    -  "ParametricRampLayer",
    -  "ParametricRegion",
    -  "ParentBox",
    -  "ParentCell",
    -  "ParentConnect",
    -  "ParentDirectory",
    -  "ParentForm",
    -  "Parenthesize",
    -  "ParentList",
    -  "ParentNotebook",
    -  "ParetoDistribution",
    -  "ParetoPickandsDistribution",
    -  "ParkData",
    -  "Part",
    -  "PartBehavior",
    -  "PartialCorrelationFunction",
    -  "PartialD",
    -  "ParticleAcceleratorData",
    -  "ParticleData",
    -  "Partition",
    -  "PartitionGranularity",
    -  "PartitionsP",
    -  "PartitionsQ",
    -  "PartLayer",
    -  "PartOfSpeech",
    -  "PartProtection",
    -  "ParzenWindow",
    -  "PascalDistribution",
    -  "PassEventsDown",
    -  "PassEventsUp",
    -  "Paste",
    -  "PasteAutoQuoteCharacters",
    -  "PasteBoxFormInlineCells",
    -  "PasteButton",
    -  "Path",
    -  "PathGraph",
    -  "PathGraphQ",
    -  "Pattern",
    -  "PatternFilling",
    -  "PatternSequence",
    -  "PatternTest",
    -  "PauliMatrix",
    -  "PaulWavelet",
    -  "Pause",
    -  "PausedTime",
    -  "PDF",
    -  "PeakDetect",
    -  "PeanoCurve",
    -  "PearsonChiSquareTest",
    -  "PearsonCorrelationTest",
    -  "PearsonDistribution",
    -  "PercentForm",
    -  "PerfectNumber",
    -  "PerfectNumberQ",
    -  "PerformanceGoal",
    -  "Perimeter",
    -  "PeriodicBoundaryCondition",
    -  "PeriodicInterpolation",
    -  "Periodogram",
    -  "PeriodogramArray",
    -  "Permanent",
    -  "Permissions",
    -  "PermissionsGroup",
    -  "PermissionsGroupMemberQ",
    -  "PermissionsGroups",
    -  "PermissionsKey",
    -  "PermissionsKeys",
    -  "PermutationCycles",
    -  "PermutationCyclesQ",
    -  "PermutationGroup",
    -  "PermutationLength",
    -  "PermutationList",
    -  "PermutationListQ",
    -  "PermutationMax",
    -  "PermutationMin",
    -  "PermutationOrder",
    -  "PermutationPower",
    -  "PermutationProduct",
    -  "PermutationReplace",
    -  "Permutations",
    -  "PermutationSupport",
    -  "Permute",
    -  "PeronaMalikFilter",
    -  "Perpendicular",
    -  "PerpendicularBisector",
    -  "PersistenceLocation",
    -  "PersistenceTime",
    -  "PersistentObject",
    -  "PersistentObjects",
    -  "PersistentValue",
    -  "PersonData",
    -  "PERTDistribution",
    -  "PetersenGraph",
    -  "PhaseMargins",
    -  "PhaseRange",
    -  "PhysicalSystemData",
    -  "Pi",
    -  "Pick",
    -  "PIDData",
    -  "PIDDerivativeFilter",
    -  "PIDFeedforward",
    -  "PIDTune",
    -  "Piecewise",
    -  "PiecewiseExpand",
    -  "PieChart",
    -  "PieChart3D",
    -  "PillaiTrace",
    -  "PillaiTraceTest",
    -  "PingTime",
    -  "Pink",
    -  "PitchRecognize",
    -  "Pivoting",
    -  "PixelConstrained",
    -  "PixelValue",
    -  "PixelValuePositions",
    -  "Placed",
    -  "Placeholder",
    -  "PlaceholderReplace",
    -  "Plain",
    -  "PlanarAngle",
    -  "PlanarGraph",
    -  "PlanarGraphQ",
    -  "PlanckRadiationLaw",
    -  "PlaneCurveData",
    -  "PlanetaryMoonData",
    -  "PlanetData",
    -  "PlantData",
    -  "Play",
    -  "PlayRange",
    -  "Plot",
    -  "Plot3D",
    -  "Plot3Matrix",
    -  "PlotDivision",
    -  "PlotJoined",
    -  "PlotLabel",
    -  "PlotLabels",
    -  "PlotLayout",
    -  "PlotLegends",
    -  "PlotMarkers",
    -  "PlotPoints",
    -  "PlotRange",
    -  "PlotRangeClipping",
    -  "PlotRangeClipPlanesStyle",
    -  "PlotRangePadding",
    -  "PlotRegion",
    -  "PlotStyle",
    -  "PlotTheme",
    -  "Pluralize",
    -  "Plus",
    -  "PlusMinus",
    -  "Pochhammer",
    -  "PodStates",
    -  "PodWidth",
    -  "Point",
    -  "Point3DBox",
    -  "Point3DBoxOptions",
    -  "PointBox",
    -  "PointBoxOptions",
    -  "PointFigureChart",
    -  "PointLegend",
    -  "PointSize",
    -  "PoissonConsulDistribution",
    -  "PoissonDistribution",
    -  "PoissonProcess",
    -  "PoissonWindow",
    -  "PolarAxes",
    -  "PolarAxesOrigin",
    -  "PolarGridLines",
    -  "PolarPlot",
    -  "PolarTicks",
    -  "PoleZeroMarkers",
    -  "PolyaAeppliDistribution",
    -  "PolyGamma",
    -  "Polygon",
    -  "Polygon3DBox",
    -  "Polygon3DBoxOptions",
    -  "PolygonalNumber",
    -  "PolygonAngle",
    -  "PolygonBox",
    -  "PolygonBoxOptions",
    -  "PolygonCoordinates",
    -  "PolygonDecomposition",
    -  "PolygonHoleScale",
    -  "PolygonIntersections",
    -  "PolygonScale",
    -  "Polyhedron",
    -  "PolyhedronAngle",
    -  "PolyhedronCoordinates",
    -  "PolyhedronData",
    -  "PolyhedronDecomposition",
    -  "PolyhedronGenus",
    -  "PolyLog",
    -  "PolynomialExtendedGCD",
    -  "PolynomialForm",
    -  "PolynomialGCD",
    -  "PolynomialLCM",
    -  "PolynomialMod",
    -  "PolynomialQ",
    -  "PolynomialQuotient",
    -  "PolynomialQuotientRemainder",
    -  "PolynomialReduce",
    -  "PolynomialRemainder",
    -  "Polynomials",
    -  "PoolingLayer",
    -  "PopupMenu",
    -  "PopupMenuBox",
    -  "PopupMenuBoxOptions",
    -  "PopupView",
    -  "PopupWindow",
    -  "Position",
    -  "PositionIndex",
    -  "Positive",
    -  "PositiveDefiniteMatrixQ",
    -  "PositiveIntegers",
    -  "PositiveRationals",
    -  "PositiveReals",
    -  "PositiveSemidefiniteMatrixQ",
    -  "PossibleZeroQ",
    -  "Postfix",
    -  "PostScript",
    -  "Power",
    -  "PowerDistribution",
    -  "PowerExpand",
    -  "PowerMod",
    -  "PowerModList",
    -  "PowerRange",
    -  "PowerSpectralDensity",
    -  "PowersRepresentations",
    -  "PowerSymmetricPolynomial",
    -  "Precedence",
    -  "PrecedenceForm",
    -  "Precedes",
    -  "PrecedesEqual",
    -  "PrecedesSlantEqual",
    -  "PrecedesTilde",
    -  "Precision",
    -  "PrecisionGoal",
    -  "PreDecrement",
    -  "Predict",
    -  "PredictionRoot",
    -  "PredictorFunction",
    -  "PredictorInformation",
    -  "PredictorMeasurements",
    -  "PredictorMeasurementsObject",
    -  "PreemptProtect",
    -  "PreferencesPath",
    -  "Prefix",
    -  "PreIncrement",
    -  "Prepend",
    -  "PrependLayer",
    -  "PrependTo",
    -  "PreprocessingRules",
    -  "PreserveColor",
    -  "PreserveImageOptions",
    -  "Previous",
    -  "PreviousCell",
    -  "PreviousDate",
    -  "PriceGraphDistribution",
    -  "PrimaryPlaceholder",
    -  "Prime",
    -  "PrimeNu",
    -  "PrimeOmega",
    -  "PrimePi",
    -  "PrimePowerQ",
    -  "PrimeQ",
    -  "Primes",
    -  "PrimeZetaP",
    -  "PrimitivePolynomialQ",
    -  "PrimitiveRoot",
    -  "PrimitiveRootList",
    -  "PrincipalComponents",
    -  "PrincipalValue",
    -  "Print",
    -  "PrintableASCIIQ",
    -  "PrintAction",
    -  "PrintForm",
    -  "PrintingCopies",
    -  "PrintingOptions",
    -  "PrintingPageRange",
    -  "PrintingStartingPageNumber",
    -  "PrintingStyleEnvironment",
    -  "Printout3D",
    -  "Printout3DPreviewer",
    -  "PrintPrecision",
    -  "PrintTemporary",
    -  "Prism",
    -  "PrismBox",
    -  "PrismBoxOptions",
    -  "PrivateCellOptions",
    -  "PrivateEvaluationOptions",
    -  "PrivateFontOptions",
    -  "PrivateFrontEndOptions",
    -  "PrivateKey",
    -  "PrivateNotebookOptions",
    -  "PrivatePaths",
    -  "Probability",
    -  "ProbabilityDistribution",
    -  "ProbabilityPlot",
    -  "ProbabilityPr",
    -  "ProbabilityScalePlot",
    -  "ProbitModelFit",
    -  "ProcessConnection",
    -  "ProcessDirectory",
    -  "ProcessEnvironment",
    -  "Processes",
    -  "ProcessEstimator",
    -  "ProcessInformation",
    -  "ProcessObject",
    -  "ProcessParameterAssumptions",
    -  "ProcessParameterQ",
    -  "ProcessStateDomain",
    -  "ProcessStatus",
    -  "ProcessTimeDomain",
    -  "Product",
    -  "ProductDistribution",
    -  "ProductLog",
    -  "ProgressIndicator",
    -  "ProgressIndicatorBox",
    -  "ProgressIndicatorBoxOptions",
    -  "Projection",
    -  "Prolog",
    -  "PromptForm",
    -  "ProofObject",
    -  "Properties",
    -  "Property",
    -  "PropertyList",
    -  "PropertyValue",
    -  "Proportion",
    -  "Proportional",
    -  "Protect",
    -  "Protected",
    -  "ProteinData",
    -  "Pruning",
    -  "PseudoInverse",
    -  "PsychrometricPropertyData",
    -  "PublicKey",
    -  "PublisherID",
    -  "PulsarData",
    -  "PunctuationCharacter",
    -  "Purple",
    -  "Put",
    -  "PutAppend",
    -  "Pyramid",
    -  "PyramidBox",
    -  "PyramidBoxOptions",
    -  "QBinomial",
    -  "QFactorial",
    -  "QGamma",
    -  "QHypergeometricPFQ",
    -  "QnDispersion",
    -  "QPochhammer",
    -  "QPolyGamma",
    -  "QRDecomposition",
    -  "QuadraticIrrationalQ",
    -  "QuadraticOptimization",
    -  "Quantile",
    -  "QuantilePlot",
    -  "Quantity",
    -  "QuantityArray",
    -  "QuantityDistribution",
    -  "QuantityForm",
    -  "QuantityMagnitude",
    -  "QuantityQ",
    -  "QuantityUnit",
    -  "QuantityVariable",
    -  "QuantityVariableCanonicalUnit",
    -  "QuantityVariableDimensions",
    -  "QuantityVariableIdentifier",
    -  "QuantityVariablePhysicalQuantity",
    -  "Quartics",
    -  "QuartileDeviation",
    -  "Quartiles",
    -  "QuartileSkewness",
    -  "Query",
    -  "QueueingNetworkProcess",
    -  "QueueingProcess",
    -  "QueueProperties",
    -  "Quiet",
    -  "Quit",
    -  "Quotient",
    -  "QuotientRemainder",
    -  "RadialGradientImage",
    -  "RadialityCentrality",
    -  "RadicalBox",
    -  "RadicalBoxOptions",
    -  "RadioButton",
    -  "RadioButtonBar",
    -  "RadioButtonBox",
    -  "RadioButtonBoxOptions",
    -  "Radon",
    -  "RadonTransform",
    -  "RamanujanTau",
    -  "RamanujanTauL",
    -  "RamanujanTauTheta",
    -  "RamanujanTauZ",
    -  "Ramp",
    -  "Random",
    -  "RandomChoice",
    -  "RandomColor",
    -  "RandomComplex",
    -  "RandomEntity",
    -  "RandomFunction",
    -  "RandomGeoPosition",
    -  "RandomGraph",
    -  "RandomImage",
    -  "RandomInstance",
    -  "RandomInteger",
    -  "RandomPermutation",
    -  "RandomPoint",
    -  "RandomPolygon",
    -  "RandomPolyhedron",
    -  "RandomPrime",
    -  "RandomReal",
    -  "RandomSample",
    -  "RandomSeed",
    -  "RandomSeeding",
    -  "RandomVariate",
    -  "RandomWalkProcess",
    -  "RandomWord",
    -  "Range",
    -  "RangeFilter",
    -  "RangeSpecification",
    -  "RankedMax",
    -  "RankedMin",
    -  "RarerProbability",
    -  "Raster",
    -  "Raster3D",
    -  "Raster3DBox",
    -  "Raster3DBoxOptions",
    -  "RasterArray",
    -  "RasterBox",
    -  "RasterBoxOptions",
    -  "Rasterize",
    -  "RasterSize",
    -  "Rational",
    -  "RationalFunctions",
    -  "Rationalize",
    -  "Rationals",
    -  "Ratios",
    -  "RawArray",
    -  "RawBoxes",
    -  "RawData",
    -  "RawMedium",
    -  "RayleighDistribution",
    -  "Re",
    -  "Read",
    -  "ReadByteArray",
    -  "ReadLine",
    -  "ReadList",
    -  "ReadProtected",
    -  "ReadString",
    -  "Real",
    -  "RealAbs",
    -  "RealBlockDiagonalForm",
    -  "RealDigits",
    -  "RealExponent",
    -  "Reals",
    -  "RealSign",
    -  "Reap",
    -  "RebuildPacletData",
    -  "RecognitionPrior",
    -  "RecognitionThreshold",
    -  "Record",
    -  "RecordLists",
    -  "RecordSeparators",
    -  "Rectangle",
    -  "RectangleBox",
    -  "RectangleBoxOptions",
    -  "RectangleChart",
    -  "RectangleChart3D",
    -  "RectangularRepeatingElement",
    -  "RecurrenceFilter",
    -  "RecurrenceTable",
    -  "RecurringDigitsForm",
    -  "Red",
    -  "Reduce",
    -  "RefBox",
    -  "ReferenceLineStyle",
    -  "ReferenceMarkers",
    -  "ReferenceMarkerStyle",
    -  "Refine",
    -  "ReflectionMatrix",
    -  "ReflectionTransform",
    -  "Refresh",
    -  "RefreshRate",
    -  "Region",
    -  "RegionBinarize",
    -  "RegionBoundary",
    -  "RegionBoundaryStyle",
    -  "RegionBounds",
    -  "RegionCentroid",
    -  "RegionDifference",
    -  "RegionDimension",
    -  "RegionDisjoint",
    -  "RegionDistance",
    -  "RegionDistanceFunction",
    -  "RegionEmbeddingDimension",
    -  "RegionEqual",
    -  "RegionFillingStyle",
    -  "RegionFunction",
    -  "RegionImage",
    -  "RegionIntersection",
    -  "RegionMeasure",
    -  "RegionMember",
    -  "RegionMemberFunction",
    -  "RegionMoment",
    -  "RegionNearest",
    -  "RegionNearestFunction",
    -  "RegionPlot",
    -  "RegionPlot3D",
    -  "RegionProduct",
    -  "RegionQ",
    -  "RegionResize",
    -  "RegionSize",
    -  "RegionSymmetricDifference",
    -  "RegionUnion",
    -  "RegionWithin",
    -  "RegisterExternalEvaluator",
    -  "RegularExpression",
    -  "Regularization",
    -  "RegularlySampledQ",
    -  "RegularPolygon",
    -  "ReIm",
    -  "ReImLabels",
    -  "ReImPlot",
    -  "ReImStyle",
    -  "Reinstall",
    -  "RelationalDatabase",
    -  "RelationGraph",
    -  "Release",
    -  "ReleaseHold",
    -  "ReliabilityDistribution",
    -  "ReliefImage",
    -  "ReliefPlot",
    -  "RemoteAuthorizationCaching",
    -  "RemoteConnect",
    -  "RemoteConnectionObject",
    -  "RemoteFile",
    -  "RemoteRun",
    -  "RemoteRunProcess",
    -  "Remove",
    -  "RemoveAlphaChannel",
    -  "RemoveAsynchronousTask",
    -  "RemoveAudioStream",
    -  "RemoveBackground",
    -  "RemoveChannelListener",
    -  "RemoveChannelSubscribers",
    -  "Removed",
    -  "RemoveDiacritics",
    -  "RemoveInputStreamMethod",
    -  "RemoveOutputStreamMethod",
    -  "RemoveProperty",
    -  "RemoveScheduledTask",
    -  "RemoveUsers",
    -  "RemoveVideoStream",
    -  "RenameDirectory",
    -  "RenameFile",
    -  "RenderAll",
    -  "RenderingOptions",
    -  "RenewalProcess",
    -  "RenkoChart",
    -  "RepairMesh",
    -  "Repeated",
    -  "RepeatedNull",
    -  "RepeatedString",
    -  "RepeatedTiming",
    -  "RepeatingElement",
    -  "Replace",
    -  "ReplaceAll",
    -  "ReplaceHeldPart",
    -  "ReplaceImageValue",
    -  "ReplaceList",
    -  "ReplacePart",
    -  "ReplacePixelValue",
    -  "ReplaceRepeated",
    -  "ReplicateLayer",
    -  "RequiredPhysicalQuantities",
    -  "Resampling",
    -  "ResamplingAlgorithmData",
    -  "ResamplingMethod",
    -  "Rescale",
    -  "RescalingTransform",
    -  "ResetDirectory",
    -  "ResetMenusPacket",
    -  "ResetScheduledTask",
    -  "ReshapeLayer",
    -  "Residue",
    -  "ResizeLayer",
    -  "Resolve",
    -  "ResourceAcquire",
    -  "ResourceData",
    -  "ResourceFunction",
    -  "ResourceObject",
    -  "ResourceRegister",
    -  "ResourceRemove",
    -  "ResourceSearch",
    -  "ResourceSubmissionObject",
    -  "ResourceSubmit",
    -  "ResourceSystemBase",
    -  "ResourceSystemPath",
    -  "ResourceUpdate",
    -  "ResourceVersion",
    -  "ResponseForm",
    -  "Rest",
    -  "RestartInterval",
    -  "Restricted",
    -  "Resultant",
    -  "ResumePacket",
    -  "Return",
    -  "ReturnEntersInput",
    -  "ReturnExpressionPacket",
    -  "ReturnInputFormPacket",
    -  "ReturnPacket",
    -  "ReturnReceiptFunction",
    -  "ReturnTextPacket",
    -  "Reverse",
    -  "ReverseApplied",
    -  "ReverseBiorthogonalSplineWavelet",
    -  "ReverseElement",
    -  "ReverseEquilibrium",
    -  "ReverseGraph",
    -  "ReverseSort",
    -  "ReverseSortBy",
    -  "ReverseUpEquilibrium",
    -  "RevolutionAxis",
    -  "RevolutionPlot3D",
    -  "RGBColor",
    -  "RiccatiSolve",
    -  "RiceDistribution",
    -  "RidgeFilter",
    -  "RiemannR",
    -  "RiemannSiegelTheta",
    -  "RiemannSiegelZ",
    -  "RiemannXi",
    -  "Riffle",
    -  "Right",
    -  "RightArrow",
    -  "RightArrowBar",
    -  "RightArrowLeftArrow",
    -  "RightComposition",
    -  "RightCosetRepresentative",
    -  "RightDownTeeVector",
    -  "RightDownVector",
    -  "RightDownVectorBar",
    -  "RightTee",
    -  "RightTeeArrow",
    -  "RightTeeVector",
    -  "RightTriangle",
    -  "RightTriangleBar",
    -  "RightTriangleEqual",
    -  "RightUpDownVector",
    -  "RightUpTeeVector",
    -  "RightUpVector",
    -  "RightUpVectorBar",
    -  "RightVector",
    -  "RightVectorBar",
    -  "RiskAchievementImportance",
    -  "RiskReductionImportance",
    -  "RogersTanimotoDissimilarity",
    -  "RollPitchYawAngles",
    -  "RollPitchYawMatrix",
    -  "RomanNumeral",
    -  "Root",
    -  "RootApproximant",
    -  "RootIntervals",
    -  "RootLocusPlot",
    -  "RootMeanSquare",
    -  "RootOfUnityQ",
    -  "RootReduce",
    -  "Roots",
    -  "RootSum",
    -  "Rotate",
    -  "RotateLabel",
    -  "RotateLeft",
    -  "RotateRight",
    -  "RotationAction",
    -  "RotationBox",
    -  "RotationBoxOptions",
    -  "RotationMatrix",
    -  "RotationTransform",
    -  "Round",
    -  "RoundImplies",
    -  "RoundingRadius",
    -  "Row",
    -  "RowAlignments",
    -  "RowBackgrounds",
    -  "RowBox",
    -  "RowHeights",
    -  "RowLines",
    -  "RowMinHeight",
    -  "RowReduce",
    -  "RowsEqual",
    -  "RowSpacings",
    -  "RSolve",
    -  "RSolveValue",
    -  "RudinShapiro",
    -  "RudvalisGroupRu",
    -  "Rule",
    -  "RuleCondition",
    -  "RuleDelayed",
    -  "RuleForm",
    -  "RulePlot",
    -  "RulerUnits",
    -  "Run",
    -  "RunProcess",
    -  "RunScheduledTask",
    -  "RunThrough",
    -  "RuntimeAttributes",
    -  "RuntimeOptions",
    -  "RussellRaoDissimilarity",
    -  "SameQ",
    -  "SameTest",
    -  "SameTestProperties",
    -  "SampledEntityClass",
    -  "SampleDepth",
    -  "SampledSoundFunction",
    -  "SampledSoundList",
    -  "SampleRate",
    -  "SamplingPeriod",
    -  "SARIMAProcess",
    -  "SARMAProcess",
    -  "SASTriangle",
    -  "SatelliteData",
    -  "SatisfiabilityCount",
    -  "SatisfiabilityInstances",
    -  "SatisfiableQ",
    -  "Saturday",
    -  "Save",
    -  "Saveable",
    -  "SaveAutoDelete",
    -  "SaveConnection",
    -  "SaveDefinitions",
    -  "SavitzkyGolayMatrix",
    -  "SawtoothWave",
    -  "Scale",
    -  "Scaled",
    -  "ScaleDivisions",
    -  "ScaledMousePosition",
    -  "ScaleOrigin",
    -  "ScalePadding",
    -  "ScaleRanges",
    -  "ScaleRangeStyle",
    -  "ScalingFunctions",
    -  "ScalingMatrix",
    -  "ScalingTransform",
    -  "Scan",
    -  "ScheduledTask",
    -  "ScheduledTaskActiveQ",
    -  "ScheduledTaskInformation",
    -  "ScheduledTaskInformationData",
    -  "ScheduledTaskObject",
    -  "ScheduledTasks",
    -  "SchurDecomposition",
    -  "ScientificForm",
    -  "ScientificNotationThreshold",
    -  "ScorerGi",
    -  "ScorerGiPrime",
    -  "ScorerHi",
    -  "ScorerHiPrime",
    -  "ScreenRectangle",
    -  "ScreenStyleEnvironment",
    -  "ScriptBaselineShifts",
    -  "ScriptForm",
    -  "ScriptLevel",
    -  "ScriptMinSize",
    -  "ScriptRules",
    -  "ScriptSizeMultipliers",
    -  "Scrollbars",
    -  "ScrollingOptions",
    -  "ScrollPosition",
    -  "SearchAdjustment",
    -  "SearchIndexObject",
    -  "SearchIndices",
    -  "SearchQueryString",
    -  "SearchResultObject",
    -  "Sec",
    -  "Sech",
    -  "SechDistribution",
    -  "SecondOrderConeOptimization",
    -  "SectionGrouping",
    -  "SectorChart",
    -  "SectorChart3D",
    -  "SectorOrigin",
    -  "SectorSpacing",
    -  "SecuredAuthenticationKey",
    -  "SecuredAuthenticationKeys",
    -  "SeedRandom",
    -  "Select",
    -  "Selectable",
    -  "SelectComponents",
    -  "SelectedCells",
    -  "SelectedNotebook",
    -  "SelectFirst",
    -  "Selection",
    -  "SelectionAnimate",
    -  "SelectionCell",
    -  "SelectionCellCreateCell",
    -  "SelectionCellDefaultStyle",
    -  "SelectionCellParentStyle",
    -  "SelectionCreateCell",
    -  "SelectionDebuggerTag",
    -  "SelectionDuplicateCell",
    -  "SelectionEvaluate",
    -  "SelectionEvaluateCreateCell",
    -  "SelectionMove",
    -  "SelectionPlaceholder",
    -  "SelectionSetStyle",
    -  "SelectWithContents",
    -  "SelfLoops",
    -  "SelfLoopStyle",
    -  "SemanticImport",
    -  "SemanticImportString",
    -  "SemanticInterpretation",
    -  "SemialgebraicComponentInstances",
    -  "SemidefiniteOptimization",
    -  "SendMail",
    -  "SendMessage",
    -  "Sequence",
    -  "SequenceAlignment",
    -  "SequenceAttentionLayer",
    -  "SequenceCases",
    -  "SequenceCount",
    -  "SequenceFold",
    -  "SequenceFoldList",
    -  "SequenceForm",
    -  "SequenceHold",
    -  "SequenceLastLayer",
    -  "SequenceMostLayer",
    -  "SequencePosition",
    -  "SequencePredict",
    -  "SequencePredictorFunction",
    -  "SequenceReplace",
    -  "SequenceRestLayer",
    -  "SequenceReverseLayer",
    -  "SequenceSplit",
    -  "Series",
    -  "SeriesCoefficient",
    -  "SeriesData",
    -  "SeriesTermGoal",
    -  "ServiceConnect",
    -  "ServiceDisconnect",
    -  "ServiceExecute",
    -  "ServiceObject",
    -  "ServiceRequest",
    -  "ServiceResponse",
    -  "ServiceSubmit",
    -  "SessionSubmit",
    -  "SessionTime",
    -  "Set",
    -  "SetAccuracy",
    -  "SetAlphaChannel",
    -  "SetAttributes",
    -  "Setbacks",
    -  "SetBoxFormNamesPacket",
    -  "SetCloudDirectory",
    -  "SetCookies",
    -  "SetDelayed",
    -  "SetDirectory",
    -  "SetEnvironment",
    -  "SetEvaluationNotebook",
    -  "SetFileDate",
    -  "SetFileLoadingContext",
    -  "SetNotebookStatusLine",
    -  "SetOptions",
    -  "SetOptionsPacket",
    -  "SetPermissions",
    -  "SetPrecision",
    -  "SetProperty",
    -  "SetSecuredAuthenticationKey",
    -  "SetSelectedNotebook",
    -  "SetSharedFunction",
    -  "SetSharedVariable",
    -  "SetSpeechParametersPacket",
    -  "SetStreamPosition",
    -  "SetSystemModel",
    -  "SetSystemOptions",
    -  "Setter",
    -  "SetterBar",
    -  "SetterBox",
    -  "SetterBoxOptions",
    -  "Setting",
    -  "SetUsers",
    -  "SetValue",
    -  "Shading",
    -  "Shallow",
    -  "ShannonWavelet",
    -  "ShapiroWilkTest",
    -  "Share",
    -  "SharingList",
    -  "Sharpen",
    -  "ShearingMatrix",
    -  "ShearingTransform",
    -  "ShellRegion",
    -  "ShenCastanMatrix",
    -  "ShiftedGompertzDistribution",
    -  "ShiftRegisterSequence",
    -  "Short",
    -  "ShortDownArrow",
    -  "Shortest",
    -  "ShortestMatch",
    -  "ShortestPathFunction",
    -  "ShortLeftArrow",
    -  "ShortRightArrow",
    -  "ShortTimeFourier",
    -  "ShortTimeFourierData",
    -  "ShortUpArrow",
    -  "Show",
    -  "ShowAutoConvert",
    -  "ShowAutoSpellCheck",
    -  "ShowAutoStyles",
    -  "ShowCellBracket",
    -  "ShowCellLabel",
    -  "ShowCellTags",
    -  "ShowClosedCellArea",
    -  "ShowCodeAssist",
    -  "ShowContents",
    -  "ShowControls",
    -  "ShowCursorTracker",
    -  "ShowGroupOpenCloseIcon",
    -  "ShowGroupOpener",
    -  "ShowInvisibleCharacters",
    -  "ShowPageBreaks",
    -  "ShowPredictiveInterface",
    -  "ShowSelection",
    -  "ShowShortBoxForm",
    -  "ShowSpecialCharacters",
    -  "ShowStringCharacters",
    -  "ShowSyntaxStyles",
    -  "ShrinkingDelay",
    -  "ShrinkWrapBoundingBox",
    -  "SiderealTime",
    -  "SiegelTheta",
    -  "SiegelTukeyTest",
    -  "SierpinskiCurve",
    -  "SierpinskiMesh",
    -  "Sign",
    -  "Signature",
    -  "SignedRankTest",
    -  "SignedRegionDistance",
    -  "SignificanceLevel",
    -  "SignPadding",
    -  "SignTest",
    -  "SimilarityRules",
    -  "SimpleGraph",
    -  "SimpleGraphQ",
    -  "SimplePolygonQ",
    -  "SimplePolyhedronQ",
    -  "Simplex",
    -  "Simplify",
    -  "Sin",
    -  "Sinc",
    -  "SinghMaddalaDistribution",
    -  "SingleEvaluation",
    -  "SingleLetterItalics",
    -  "SingleLetterStyle",
    -  "SingularValueDecomposition",
    -  "SingularValueList",
    -  "SingularValuePlot",
    -  "SingularValues",
    -  "Sinh",
    -  "SinhIntegral",
    -  "SinIntegral",
    -  "SixJSymbol",
    -  "Skeleton",
    -  "SkeletonTransform",
    -  "SkellamDistribution",
    -  "Skewness",
    -  "SkewNormalDistribution",
    -  "SkinStyle",
    -  "Skip",
    -  "SliceContourPlot3D",
    -  "SliceDensityPlot3D",
    -  "SliceDistribution",
    -  "SliceVectorPlot3D",
    -  "Slider",
    -  "Slider2D",
    -  "Slider2DBox",
    -  "Slider2DBoxOptions",
    -  "SliderBox",
    -  "SliderBoxOptions",
    -  "SlideView",
    -  "Slot",
    -  "SlotSequence",
    -  "Small",
    -  "SmallCircle",
    -  "Smaller",
    -  "SmithDecomposition",
    -  "SmithDelayCompensator",
    -  "SmithWatermanSimilarity",
    -  "SmoothDensityHistogram",
    -  "SmoothHistogram",
    -  "SmoothHistogram3D",
    -  "SmoothKernelDistribution",
    -  "SnDispersion",
    -  "Snippet",
    -  "SnubPolyhedron",
    -  "SocialMediaData",
    -  "Socket",
    -  "SocketConnect",
    -  "SocketListen",
    -  "SocketListener",
    -  "SocketObject",
    -  "SocketOpen",
    -  "SocketReadMessage",
    -  "SocketReadyQ",
    -  "Sockets",
    -  "SocketWaitAll",
    -  "SocketWaitNext",
    -  "SoftmaxLayer",
    -  "SokalSneathDissimilarity",
    -  "SolarEclipse",
    -  "SolarSystemFeatureData",
    -  "SolidAngle",
    -  "SolidData",
    -  "SolidRegionQ",
    -  "Solve",
    -  "SolveAlways",
    -  "SolveDelayed",
    -  "Sort",
    -  "SortBy",
    -  "SortedBy",
    -  "SortedEntityClass",
    -  "Sound",
    -  "SoundAndGraphics",
    -  "SoundNote",
    -  "SoundVolume",
    -  "SourceLink",
    -  "Sow",
    -  "Space",
    -  "SpaceCurveData",
    -  "SpaceForm",
    -  "Spacer",
    -  "Spacings",
    -  "Span",
    -  "SpanAdjustments",
    -  "SpanCharacterRounding",
    -  "SpanFromAbove",
    -  "SpanFromBoth",
    -  "SpanFromLeft",
    -  "SpanLineThickness",
    -  "SpanMaxSize",
    -  "SpanMinSize",
    -  "SpanningCharacters",
    -  "SpanSymmetric",
    -  "SparseArray",
    -  "SpatialGraphDistribution",
    -  "SpatialMedian",
    -  "SpatialTransformationLayer",
    -  "Speak",
    -  "SpeakerMatchQ",
    -  "SpeakTextPacket",
    -  "SpearmanRankTest",
    -  "SpearmanRho",
    -  "SpeciesData",
    -  "SpecificityGoal",
    -  "SpectralLineData",
    -  "Spectrogram",
    -  "SpectrogramArray",
    -  "Specularity",
    -  "SpeechCases",
    -  "SpeechInterpreter",
    -  "SpeechRecognize",
    -  "SpeechSynthesize",
    -  "SpellingCorrection",
    -  "SpellingCorrectionList",
    -  "SpellingDictionaries",
    -  "SpellingDictionariesPath",
    -  "SpellingOptions",
    -  "SpellingSuggestionsPacket",
    -  "Sphere",
    -  "SphereBox",
    -  "SpherePoints",
    -  "SphericalBesselJ",
    -  "SphericalBesselY",
    -  "SphericalHankelH1",
    -  "SphericalHankelH2",
    -  "SphericalHarmonicY",
    -  "SphericalPlot3D",
    -  "SphericalRegion",
    -  "SphericalShell",
    -  "SpheroidalEigenvalue",
    -  "SpheroidalJoiningFactor",
    -  "SpheroidalPS",
    -  "SpheroidalPSPrime",
    -  "SpheroidalQS",
    -  "SpheroidalQSPrime",
    -  "SpheroidalRadialFactor",
    -  "SpheroidalS1",
    -  "SpheroidalS1Prime",
    -  "SpheroidalS2",
    -  "SpheroidalS2Prime",
    -  "Splice",
    -  "SplicedDistribution",
    -  "SplineClosed",
    -  "SplineDegree",
    -  "SplineKnots",
    -  "SplineWeights",
    -  "Split",
    -  "SplitBy",
    -  "SpokenString",
    -  "Sqrt",
    -  "SqrtBox",
    -  "SqrtBoxOptions",
    -  "Square",
    -  "SquaredEuclideanDistance",
    -  "SquareFreeQ",
    -  "SquareIntersection",
    -  "SquareMatrixQ",
    -  "SquareRepeatingElement",
    -  "SquaresR",
    -  "SquareSubset",
    -  "SquareSubsetEqual",
    -  "SquareSuperset",
    -  "SquareSupersetEqual",
    -  "SquareUnion",
    -  "SquareWave",
    -  "SSSTriangle",
    -  "StabilityMargins",
    -  "StabilityMarginsStyle",
    -  "StableDistribution",
    -  "Stack",
    -  "StackBegin",
    -  "StackComplete",
    -  "StackedDateListPlot",
    -  "StackedListPlot",
    -  "StackInhibit",
    -  "StadiumShape",
    -  "StandardAtmosphereData",
    -  "StandardDeviation",
    -  "StandardDeviationFilter",
    -  "StandardForm",
    -  "Standardize",
    -  "Standardized",
    -  "StandardOceanData",
    -  "StandbyDistribution",
    -  "Star",
    -  "StarClusterData",
    -  "StarData",
    -  "StarGraph",
    -  "StartAsynchronousTask",
    -  "StartExternalSession",
    -  "StartingStepSize",
    -  "StartOfLine",
    -  "StartOfString",
    -  "StartProcess",
    -  "StartScheduledTask",
    -  "StartupSound",
    -  "StartWebSession",
    -  "StateDimensions",
    -  "StateFeedbackGains",
    -  "StateOutputEstimator",
    -  "StateResponse",
    -  "StateSpaceModel",
    -  "StateSpaceRealization",
    -  "StateSpaceTransform",
    -  "StateTransformationLinearize",
    -  "StationaryDistribution",
    -  "StationaryWaveletPacketTransform",
    -  "StationaryWaveletTransform",
    -  "StatusArea",
    -  "StatusCentrality",
    -  "StepMonitor",
    -  "StereochemistryElements",
    -  "StieltjesGamma",
    -  "StippleShading",
    -  "StirlingS1",
    -  "StirlingS2",
    -  "StopAsynchronousTask",
    -  "StoppingPowerData",
    -  "StopScheduledTask",
    -  "StrataVariables",
    -  "StratonovichProcess",
    -  "StreamColorFunction",
    -  "StreamColorFunctionScaling",
    -  "StreamDensityPlot",
    -  "StreamMarkers",
    -  "StreamPlot",
    -  "StreamPoints",
    -  "StreamPosition",
    -  "Streams",
    -  "StreamScale",
    -  "StreamStyle",
    -  "String",
    -  "StringBreak",
    -  "StringByteCount",
    -  "StringCases",
    -  "StringContainsQ",
    -  "StringCount",
    -  "StringDelete",
    -  "StringDrop",
    -  "StringEndsQ",
    -  "StringExpression",
    -  "StringExtract",
    -  "StringForm",
    -  "StringFormat",
    -  "StringFreeQ",
    -  "StringInsert",
    -  "StringJoin",
    -  "StringLength",
    -  "StringMatchQ",
    -  "StringPadLeft",
    -  "StringPadRight",
    -  "StringPart",
    -  "StringPartition",
    -  "StringPosition",
    -  "StringQ",
    -  "StringRepeat",
    -  "StringReplace",
    -  "StringReplaceList",
    -  "StringReplacePart",
    -  "StringReverse",
    -  "StringRiffle",
    -  "StringRotateLeft",
    -  "StringRotateRight",
    -  "StringSkeleton",
    -  "StringSplit",
    -  "StringStartsQ",
    -  "StringTake",
    -  "StringTemplate",
    -  "StringToByteArray",
    -  "StringToStream",
    -  "StringTrim",
    -  "StripBoxes",
    -  "StripOnInput",
    -  "StripWrapperBoxes",
    -  "StrokeForm",
    -  "StructuralImportance",
    -  "StructuredArray",
    -  "StructuredArrayHeadQ",
    -  "StructuredSelection",
    -  "StruveH",
    -  "StruveL",
    -  "Stub",
    -  "StudentTDistribution",
    -  "Style",
    -  "StyleBox",
    -  "StyleBoxAutoDelete",
    -  "StyleData",
    -  "StyleDefinitions",
    -  "StyleForm",
    -  "StyleHints",
    -  "StyleKeyMapping",
    -  "StyleMenuListing",
    -  "StyleNameDialogSettings",
    -  "StyleNames",
    -  "StylePrint",
    -  "StyleSheetPath",
    -  "Subdivide",
    -  "Subfactorial",
    -  "Subgraph",
    -  "SubMinus",
    -  "SubPlus",
    -  "SubresultantPolynomialRemainders",
    -  "SubresultantPolynomials",
    -  "Subresultants",
    -  "Subscript",
    -  "SubscriptBox",
    -  "SubscriptBoxOptions",
    -  "Subscripted",
    -  "Subsequences",
    -  "Subset",
    -  "SubsetCases",
    -  "SubsetCount",
    -  "SubsetEqual",
    -  "SubsetMap",
    -  "SubsetPosition",
    -  "SubsetQ",
    -  "SubsetReplace",
    -  "Subsets",
    -  "SubStar",
    -  "SubstitutionSystem",
    -  "Subsuperscript",
    -  "SubsuperscriptBox",
    -  "SubsuperscriptBoxOptions",
    -  "SubtitleEncoding",
    -  "SubtitleTracks",
    -  "Subtract",
    -  "SubtractFrom",
    -  "SubtractSides",
    -  "SubValues",
    -  "Succeeds",
    -  "SucceedsEqual",
    -  "SucceedsSlantEqual",
    -  "SucceedsTilde",
    -  "Success",
    -  "SuchThat",
    -  "Sum",
    -  "SumConvergence",
    -  "SummationLayer",
    -  "Sunday",
    -  "SunPosition",
    -  "Sunrise",
    -  "Sunset",
    -  "SuperDagger",
    -  "SuperMinus",
    -  "SupernovaData",
    -  "SuperPlus",
    -  "Superscript",
    -  "SuperscriptBox",
    -  "SuperscriptBoxOptions",
    -  "Superset",
    -  "SupersetEqual",
    -  "SuperStar",
    -  "Surd",
    -  "SurdForm",
    -  "SurfaceAppearance",
    -  "SurfaceArea",
    -  "SurfaceColor",
    -  "SurfaceData",
    -  "SurfaceGraphics",
    -  "SurvivalDistribution",
    -  "SurvivalFunction",
    -  "SurvivalModel",
    -  "SurvivalModelFit",
    -  "SuspendPacket",
    -  "SuzukiDistribution",
    -  "SuzukiGroupSuz",
    -  "SwatchLegend",
    -  "Switch",
    -  "Symbol",
    -  "SymbolName",
    -  "SymletWavelet",
    -  "Symmetric",
    -  "SymmetricGroup",
    -  "SymmetricKey",
    -  "SymmetricMatrixQ",
    -  "SymmetricPolynomial",
    -  "SymmetricReduction",
    -  "Symmetrize",
    -  "SymmetrizedArray",
    -  "SymmetrizedArrayRules",
    -  "SymmetrizedDependentComponents",
    -  "SymmetrizedIndependentComponents",
    -  "SymmetrizedReplacePart",
    -  "SynchronousInitialization",
    -  "SynchronousUpdating",
    -  "Synonyms",
    -  "Syntax",
    -  "SyntaxForm",
    -  "SyntaxInformation",
    -  "SyntaxLength",
    -  "SyntaxPacket",
    -  "SyntaxQ",
    -  "SynthesizeMissingValues",
    -  "SystemCredential",
    -  "SystemCredentialData",
    -  "SystemCredentialKey",
    -  "SystemCredentialKeys",
    -  "SystemCredentialStoreObject",
    -  "SystemDialogInput",
    -  "SystemException",
    -  "SystemGet",
    -  "SystemHelpPath",
    -  "SystemInformation",
    -  "SystemInformationData",
    -  "SystemInstall",
    -  "SystemModel",
    -  "SystemModeler",
    -  "SystemModelExamples",
    -  "SystemModelLinearize",
    -  "SystemModelParametricSimulate",
    -  "SystemModelPlot",
    -  "SystemModelProgressReporting",
    -  "SystemModelReliability",
    -  "SystemModels",
    -  "SystemModelSimulate",
    -  "SystemModelSimulateSensitivity",
    -  "SystemModelSimulationData",
    -  "SystemOpen",
    -  "SystemOptions",
    -  "SystemProcessData",
    -  "SystemProcesses",
    -  "SystemsConnectionsModel",
    -  "SystemsModelDelay",
    -  "SystemsModelDelayApproximate",
    -  "SystemsModelDelete",
    -  "SystemsModelDimensions",
    -  "SystemsModelExtract",
    -  "SystemsModelFeedbackConnect",
    -  "SystemsModelLabels",
    -  "SystemsModelLinearity",
    -  "SystemsModelMerge",
    -  "SystemsModelOrder",
    -  "SystemsModelParallelConnect",
    -  "SystemsModelSeriesConnect",
    -  "SystemsModelStateFeedbackConnect",
    -  "SystemsModelVectorRelativeOrders",
    -  "SystemStub",
    -  "SystemTest",
    -  "Tab",
    -  "TabFilling",
    -  "Table",
    -  "TableAlignments",
    -  "TableDepth",
    -  "TableDirections",
    -  "TableForm",
    -  "TableHeadings",
    -  "TableSpacing",
    -  "TableView",
    -  "TableViewBox",
    -  "TableViewBoxBackground",
    -  "TableViewBoxItemSize",
    -  "TableViewBoxOptions",
    -  "TabSpacings",
    -  "TabView",
    -  "TabViewBox",
    -  "TabViewBoxOptions",
    -  "TagBox",
    -  "TagBoxNote",
    -  "TagBoxOptions",
    -  "TaggingRules",
    -  "TagSet",
    -  "TagSetDelayed",
    -  "TagStyle",
    -  "TagUnset",
    -  "Take",
    -  "TakeDrop",
    -  "TakeLargest",
    -  "TakeLargestBy",
    -  "TakeList",
    -  "TakeSmallest",
    -  "TakeSmallestBy",
    -  "TakeWhile",
    -  "Tally",
    -  "Tan",
    -  "Tanh",
    -  "TargetDevice",
    -  "TargetFunctions",
    -  "TargetSystem",
    -  "TargetUnits",
    -  "TaskAbort",
    -  "TaskExecute",
    -  "TaskObject",
    -  "TaskRemove",
    -  "TaskResume",
    -  "Tasks",
    -  "TaskSuspend",
    -  "TaskWait",
    -  "TautologyQ",
    -  "TelegraphProcess",
    -  "TemplateApply",
    -  "TemplateArgBox",
    -  "TemplateBox",
    -  "TemplateBoxOptions",
    -  "TemplateEvaluate",
    -  "TemplateExpression",
    -  "TemplateIf",
    -  "TemplateObject",
    -  "TemplateSequence",
    -  "TemplateSlot",
    -  "TemplateSlotSequence",
    -  "TemplateUnevaluated",
    -  "TemplateVerbatim",
    -  "TemplateWith",
    -  "TemporalData",
    -  "TemporalRegularity",
    -  "Temporary",
    -  "TemporaryVariable",
    -  "TensorContract",
    -  "TensorDimensions",
    -  "TensorExpand",
    -  "TensorProduct",
    -  "TensorQ",
    -  "TensorRank",
    -  "TensorReduce",
    -  "TensorSymmetry",
    -  "TensorTranspose",
    -  "TensorWedge",
    -  "TestID",
    -  "TestReport",
    -  "TestReportObject",
    -  "TestResultObject",
    -  "Tetrahedron",
    -  "TetrahedronBox",
    -  "TetrahedronBoxOptions",
    -  "TeXForm",
    -  "TeXSave",
    -  "Text",
    -  "Text3DBox",
    -  "Text3DBoxOptions",
    -  "TextAlignment",
    -  "TextBand",
    -  "TextBoundingBox",
    -  "TextBox",
    -  "TextCases",
    -  "TextCell",
    -  "TextClipboardType",
    -  "TextContents",
    -  "TextData",
    -  "TextElement",
    -  "TextForm",
    -  "TextGrid",
    -  "TextJustification",
    -  "TextLine",
    -  "TextPacket",
    -  "TextParagraph",
    -  "TextPosition",
    -  "TextRecognize",
    -  "TextSearch",
    -  "TextSearchReport",
    -  "TextSentences",
    -  "TextString",
    -  "TextStructure",
    -  "TextStyle",
    -  "TextTranslation",
    -  "Texture",
    -  "TextureCoordinateFunction",
    -  "TextureCoordinateScaling",
    -  "TextWords",
    -  "Therefore",
    -  "ThermodynamicData",
    -  "ThermometerGauge",
    -  "Thick",
    -  "Thickness",
    -  "Thin",
    -  "Thinning",
    -  "ThisLink",
    -  "ThompsonGroupTh",
    -  "Thread",
    -  "ThreadingLayer",
    -  "ThreeJSymbol",
    -  "Threshold",
    -  "Through",
    -  "Throw",
    -  "ThueMorse",
    -  "Thumbnail",
    -  "Thursday",
    -  "Ticks",
    -  "TicksStyle",
    -  "TideData",
    -  "Tilde",
    -  "TildeEqual",
    -  "TildeFullEqual",
    -  "TildeTilde",
    -  "TimeConstrained",
    -  "TimeConstraint",
    -  "TimeDirection",
    -  "TimeFormat",
    -  "TimeGoal",
    -  "TimelinePlot",
    -  "TimeObject",
    -  "TimeObjectQ",
    -  "TimeRemaining",
    -  "Times",
    -  "TimesBy",
    -  "TimeSeries",
    -  "TimeSeriesAggregate",
    -  "TimeSeriesForecast",
    -  "TimeSeriesInsert",
    -  "TimeSeriesInvertibility",
    -  "TimeSeriesMap",
    -  "TimeSeriesMapThread",
    -  "TimeSeriesModel",
    -  "TimeSeriesModelFit",
    -  "TimeSeriesResample",
    -  "TimeSeriesRescale",
    -  "TimeSeriesShift",
    -  "TimeSeriesThread",
    -  "TimeSeriesWindow",
    -  "TimeUsed",
    -  "TimeValue",
    -  "TimeWarpingCorrespondence",
    -  "TimeWarpingDistance",
    -  "TimeZone",
    -  "TimeZoneConvert",
    -  "TimeZoneOffset",
    -  "Timing",
    -  "Tiny",
    -  "TitleGrouping",
    -  "TitsGroupT",
    -  "ToBoxes",
    -  "ToCharacterCode",
    -  "ToColor",
    -  "ToContinuousTimeModel",
    -  "ToDate",
    -  "Today",
    -  "ToDiscreteTimeModel",
    -  "ToEntity",
    -  "ToeplitzMatrix",
    -  "ToExpression",
    -  "ToFileName",
    -  "Together",
    -  "Toggle",
    -  "ToggleFalse",
    -  "Toggler",
    -  "TogglerBar",
    -  "TogglerBox",
    -  "TogglerBoxOptions",
    -  "ToHeldExpression",
    -  "ToInvertibleTimeSeries",
    -  "TokenWords",
    -  "Tolerance",
    -  "ToLowerCase",
    -  "Tomorrow",
    -  "ToNumberField",
    -  "TooBig",
    -  "Tooltip",
    -  "TooltipBox",
    -  "TooltipBoxOptions",
    -  "TooltipDelay",
    -  "TooltipStyle",
    -  "ToonShading",
    -  "Top",
    -  "TopHatTransform",
    -  "ToPolarCoordinates",
    -  "TopologicalSort",
    -  "ToRadicals",
    -  "ToRules",
    -  "ToSphericalCoordinates",
    -  "ToString",
    -  "Total",
    -  "TotalHeight",
    -  "TotalLayer",
    -  "TotalVariationFilter",
    -  "TotalWidth",
    -  "TouchPosition",
    -  "TouchscreenAutoZoom",
    -  "TouchscreenControlPlacement",
    -  "ToUpperCase",
    -  "Tr",
    -  "Trace",
    -  "TraceAbove",
    -  "TraceAction",
    -  "TraceBackward",
    -  "TraceDepth",
    -  "TraceDialog",
    -  "TraceForward",
    -  "TraceInternal",
    -  "TraceLevel",
    -  "TraceOff",
    -  "TraceOn",
    -  "TraceOriginal",
    -  "TracePrint",
    -  "TraceScan",
    -  "TrackedSymbols",
    -  "TrackingFunction",
    -  "TracyWidomDistribution",
    -  "TradingChart",
    -  "TraditionalForm",
    -  "TraditionalFunctionNotation",
    -  "TraditionalNotation",
    -  "TraditionalOrder",
    -  "TrainingProgressCheckpointing",
    -  "TrainingProgressFunction",
    -  "TrainingProgressMeasurements",
    -  "TrainingProgressReporting",
    -  "TrainingStoppingCriterion",
    -  "TrainingUpdateSchedule",
    -  "TransferFunctionCancel",
    -  "TransferFunctionExpand",
    -  "TransferFunctionFactor",
    -  "TransferFunctionModel",
    -  "TransferFunctionPoles",
    -  "TransferFunctionTransform",
    -  "TransferFunctionZeros",
    -  "TransformationClass",
    -  "TransformationFunction",
    -  "TransformationFunctions",
    -  "TransformationMatrix",
    -  "TransformedDistribution",
    -  "TransformedField",
    -  "TransformedProcess",
    -  "TransformedRegion",
    -  "TransitionDirection",
    -  "TransitionDuration",
    -  "TransitionEffect",
    -  "TransitiveClosureGraph",
    -  "TransitiveReductionGraph",
    -  "Translate",
    -  "TranslationOptions",
    -  "TranslationTransform",
    -  "Transliterate",
    -  "Transparent",
    -  "TransparentColor",
    -  "Transpose",
    -  "TransposeLayer",
    -  "TrapSelection",
    -  "TravelDirections",
    -  "TravelDirectionsData",
    -  "TravelDistance",
    -  "TravelDistanceList",
    -  "TravelMethod",
    -  "TravelTime",
    -  "TreeForm",
    -  "TreeGraph",
    -  "TreeGraphQ",
    -  "TreePlot",
    -  "TrendStyle",
    -  "Triangle",
    -  "TriangleCenter",
    -  "TriangleConstruct",
    -  "TriangleMeasurement",
    -  "TriangleWave",
    -  "TriangularDistribution",
    -  "TriangulateMesh",
    -  "Trig",
    -  "TrigExpand",
    -  "TrigFactor",
    -  "TrigFactorList",
    -  "Trigger",
    -  "TrigReduce",
    -  "TrigToExp",
    -  "TrimmedMean",
    -  "TrimmedVariance",
    -  "TropicalStormData",
    -  "True",
    -  "TrueQ",
    -  "TruncatedDistribution",
    -  "TruncatedPolyhedron",
    -  "TsallisQExponentialDistribution",
    -  "TsallisQGaussianDistribution",
    -  "TTest",
    -  "Tube",
    -  "TubeBezierCurveBox",
    -  "TubeBezierCurveBoxOptions",
    -  "TubeBox",
    -  "TubeBoxOptions",
    -  "TubeBSplineCurveBox",
    -  "TubeBSplineCurveBoxOptions",
    -  "Tuesday",
    -  "TukeyLambdaDistribution",
    -  "TukeyWindow",
    -  "TunnelData",
    -  "Tuples",
    -  "TuranGraph",
    -  "TuringMachine",
    -  "TuttePolynomial",
    -  "TwoWayRule",
    -  "Typed",
    -  "TypeSpecifier",
    -  "UnateQ",
    -  "Uncompress",
    -  "UnconstrainedParameters",
    -  "Undefined",
    -  "UnderBar",
    -  "Underflow",
    -  "Underlined",
    -  "Underoverscript",
    -  "UnderoverscriptBox",
    -  "UnderoverscriptBoxOptions",
    -  "Underscript",
    -  "UnderscriptBox",
    -  "UnderscriptBoxOptions",
    -  "UnderseaFeatureData",
    -  "UndirectedEdge",
    -  "UndirectedGraph",
    -  "UndirectedGraphQ",
    -  "UndoOptions",
    -  "UndoTrackedVariables",
    -  "Unequal",
    -  "UnequalTo",
    -  "Unevaluated",
    -  "UniformDistribution",
    -  "UniformGraphDistribution",
    -  "UniformPolyhedron",
    -  "UniformSumDistribution",
    -  "Uninstall",
    -  "Union",
    -  "UnionedEntityClass",
    -  "UnionPlus",
    -  "Unique",
    -  "UnitaryMatrixQ",
    -  "UnitBox",
    -  "UnitConvert",
    -  "UnitDimensions",
    -  "Unitize",
    -  "UnitRootTest",
    -  "UnitSimplify",
    -  "UnitStep",
    -  "UnitSystem",
    -  "UnitTriangle",
    -  "UnitVector",
    -  "UnitVectorLayer",
    -  "UnityDimensions",
    -  "UniverseModelData",
    -  "UniversityData",
    -  "UnixTime",
    -  "Unprotect",
    -  "UnregisterExternalEvaluator",
    -  "UnsameQ",
    -  "UnsavedVariables",
    -  "Unset",
    -  "UnsetShared",
    -  "UntrackedVariables",
    -  "Up",
    -  "UpArrow",
    -  "UpArrowBar",
    -  "UpArrowDownArrow",
    -  "Update",
    -  "UpdateDynamicObjects",
    -  "UpdateDynamicObjectsSynchronous",
    -  "UpdateInterval",
    -  "UpdatePacletSites",
    -  "UpdateSearchIndex",
    -  "UpDownArrow",
    -  "UpEquilibrium",
    -  "UpperCaseQ",
    -  "UpperLeftArrow",
    -  "UpperRightArrow",
    -  "UpperTriangularize",
    -  "UpperTriangularMatrixQ",
    -  "Upsample",
    -  "UpSet",
    -  "UpSetDelayed",
    -  "UpTee",
    -  "UpTeeArrow",
    -  "UpTo",
    -  "UpValues",
    -  "URL",
    -  "URLBuild",
    -  "URLDecode",
    -  "URLDispatcher",
    -  "URLDownload",
    -  "URLDownloadSubmit",
    -  "URLEncode",
    -  "URLExecute",
    -  "URLExpand",
    -  "URLFetch",
    -  "URLFetchAsynchronous",
    -  "URLParse",
    -  "URLQueryDecode",
    -  "URLQueryEncode",
    -  "URLRead",
    -  "URLResponseTime",
    -  "URLSave",
    -  "URLSaveAsynchronous",
    -  "URLShorten",
    -  "URLSubmit",
    -  "UseGraphicsRange",
    -  "UserDefinedWavelet",
    -  "Using",
    -  "UsingFrontEnd",
    -  "UtilityFunction",
    -  "V2Get",
    -  "ValenceErrorHandling",
    -  "ValidationLength",
    -  "ValidationSet",
    -  "Value",
    -  "ValueBox",
    -  "ValueBoxOptions",
    -  "ValueDimensions",
    -  "ValueForm",
    -  "ValuePreprocessingFunction",
    -  "ValueQ",
    -  "Values",
    -  "ValuesData",
    -  "Variables",
    -  "Variance",
    -  "VarianceEquivalenceTest",
    -  "VarianceEstimatorFunction",
    -  "VarianceGammaDistribution",
    -  "VarianceTest",
    -  "VectorAngle",
    -  "VectorAround",
    -  "VectorAspectRatio",
    -  "VectorColorFunction",
    -  "VectorColorFunctionScaling",
    -  "VectorDensityPlot",
    -  "VectorGlyphData",
    -  "VectorGreater",
    -  "VectorGreaterEqual",
    -  "VectorLess",
    -  "VectorLessEqual",
    -  "VectorMarkers",
    -  "VectorPlot",
    -  "VectorPlot3D",
    -  "VectorPoints",
    -  "VectorQ",
    -  "VectorRange",
    -  "Vectors",
    -  "VectorScale",
    -  "VectorScaling",
    -  "VectorSizes",
    -  "VectorStyle",
    -  "Vee",
    -  "Verbatim",
    -  "Verbose",
    -  "VerboseConvertToPostScriptPacket",
    -  "VerificationTest",
    -  "VerifyConvergence",
    -  "VerifyDerivedKey",
    -  "VerifyDigitalSignature",
    -  "VerifyFileSignature",
    -  "VerifyInterpretation",
    -  "VerifySecurityCertificates",
    -  "VerifySolutions",
    -  "VerifyTestAssumptions",
    -  "Version",
    -  "VersionedPreferences",
    -  "VersionNumber",
    -  "VertexAdd",
    -  "VertexCapacity",
    -  "VertexColors",
    -  "VertexComponent",
    -  "VertexConnectivity",
    -  "VertexContract",
    -  "VertexCoordinateRules",
    -  "VertexCoordinates",
    -  "VertexCorrelationSimilarity",
    -  "VertexCosineSimilarity",
    -  "VertexCount",
    -  "VertexCoverQ",
    -  "VertexDataCoordinates",
    -  "VertexDegree",
    -  "VertexDelete",
    -  "VertexDiceSimilarity",
    -  "VertexEccentricity",
    -  "VertexInComponent",
    -  "VertexInDegree",
    -  "VertexIndex",
    -  "VertexJaccardSimilarity",
    -  "VertexLabeling",
    -  "VertexLabels",
    -  "VertexLabelStyle",
    -  "VertexList",
    -  "VertexNormals",
    -  "VertexOutComponent",
    -  "VertexOutDegree",
    -  "VertexQ",
    -  "VertexRenderingFunction",
    -  "VertexReplace",
    -  "VertexShape",
    -  "VertexShapeFunction",
    -  "VertexSize",
    -  "VertexStyle",
    -  "VertexTextureCoordinates",
    -  "VertexWeight",
    -  "VertexWeightedGraphQ",
    -  "Vertical",
    -  "VerticalBar",
    -  "VerticalForm",
    -  "VerticalGauge",
    -  "VerticalSeparator",
    -  "VerticalSlider",
    -  "VerticalTilde",
    -  "Video",
    -  "VideoEncoding",
    -  "VideoExtractFrames",
    -  "VideoFrameList",
    -  "VideoFrameMap",
    -  "VideoPause",
    -  "VideoPlay",
    -  "VideoQ",
    -  "VideoStop",
    -  "VideoStream",
    -  "VideoStreams",
    -  "VideoTimeSeries",
    -  "VideoTracks",
    -  "VideoTrim",
    -  "ViewAngle",
    -  "ViewCenter",
    -  "ViewMatrix",
    -  "ViewPoint",
    -  "ViewPointSelectorSettings",
    -  "ViewPort",
    -  "ViewProjection",
    -  "ViewRange",
    -  "ViewVector",
    -  "ViewVertical",
    -  "VirtualGroupData",
    -  "Visible",
    -  "VisibleCell",
    -  "VoiceStyleData",
    -  "VoigtDistribution",
    -  "VolcanoData",
    -  "Volume",
    -  "VonMisesDistribution",
    -  "VoronoiMesh",
    -  "WaitAll",
    -  "WaitAsynchronousTask",
    -  "WaitNext",
    -  "WaitUntil",
    -  "WakebyDistribution",
    -  "WalleniusHypergeometricDistribution",
    -  "WaringYuleDistribution",
    -  "WarpingCorrespondence",
    -  "WarpingDistance",
    -  "WatershedComponents",
    -  "WatsonUSquareTest",
    -  "WattsStrogatzGraphDistribution",
    -  "WaveletBestBasis",
    -  "WaveletFilterCoefficients",
    -  "WaveletImagePlot",
    -  "WaveletListPlot",
    -  "WaveletMapIndexed",
    -  "WaveletMatrixPlot",
    -  "WaveletPhi",
    -  "WaveletPsi",
    -  "WaveletScale",
    -  "WaveletScalogram",
    -  "WaveletThreshold",
    -  "WeaklyConnectedComponents",
    -  "WeaklyConnectedGraphComponents",
    -  "WeaklyConnectedGraphQ",
    -  "WeakStationarity",
    -  "WeatherData",
    -  "WeatherForecastData",
    -  "WebAudioSearch",
    -  "WebElementObject",
    -  "WeberE",
    -  "WebExecute",
    -  "WebImage",
    -  "WebImageSearch",
    -  "WebSearch",
    -  "WebSessionObject",
    -  "WebSessions",
    -  "WebWindowObject",
    -  "Wedge",
    -  "Wednesday",
    -  "WeibullDistribution",
    -  "WeierstrassE1",
    -  "WeierstrassE2",
    -  "WeierstrassE3",
    -  "WeierstrassEta1",
    -  "WeierstrassEta2",
    -  "WeierstrassEta3",
    -  "WeierstrassHalfPeriods",
    -  "WeierstrassHalfPeriodW1",
    -  "WeierstrassHalfPeriodW2",
    -  "WeierstrassHalfPeriodW3",
    -  "WeierstrassInvariantG2",
    -  "WeierstrassInvariantG3",
    -  "WeierstrassInvariants",
    -  "WeierstrassP",
    -  "WeierstrassPPrime",
    -  "WeierstrassSigma",
    -  "WeierstrassZeta",
    -  "WeightedAdjacencyGraph",
    -  "WeightedAdjacencyMatrix",
    -  "WeightedData",
    -  "WeightedGraphQ",
    -  "Weights",
    -  "WelchWindow",
    -  "WheelGraph",
    -  "WhenEvent",
    -  "Which",
    -  "While",
    -  "White",
    -  "WhiteNoiseProcess",
    -  "WhitePoint",
    -  "Whitespace",
    -  "WhitespaceCharacter",
    -  "WhittakerM",
    -  "WhittakerW",
    -  "WienerFilter",
    -  "WienerProcess",
    -  "WignerD",
    -  "WignerSemicircleDistribution",
    -  "WikidataData",
    -  "WikidataSearch",
    -  "WikipediaData",
    -  "WikipediaSearch",
    -  "WilksW",
    -  "WilksWTest",
    -  "WindDirectionData",
    -  "WindingCount",
    -  "WindingPolygon",
    -  "WindowClickSelect",
    -  "WindowElements",
    -  "WindowFloating",
    -  "WindowFrame",
    -  "WindowFrameElements",
    -  "WindowMargins",
    -  "WindowMovable",
    -  "WindowOpacity",
    -  "WindowPersistentStyles",
    -  "WindowSelected",
    -  "WindowSize",
    -  "WindowStatusArea",
    -  "WindowTitle",
    -  "WindowToolbars",
    -  "WindowWidth",
    -  "WindSpeedData",
    -  "WindVectorData",
    -  "WinsorizedMean",
    -  "WinsorizedVariance",
    -  "WishartMatrixDistribution",
    -  "With",
    -  "WolframAlpha",
    -  "WolframAlphaDate",
    -  "WolframAlphaQuantity",
    -  "WolframAlphaResult",
    -  "WolframLanguageData",
    -  "Word",
    -  "WordBoundary",
    -  "WordCharacter",
    -  "WordCloud",
    -  "WordCount",
    -  "WordCounts",
    -  "WordData",
    -  "WordDefinition",
    -  "WordFrequency",
    -  "WordFrequencyData",
    -  "WordList",
    -  "WordOrientation",
    -  "WordSearch",
    -  "WordSelectionFunction",
    -  "WordSeparators",
    -  "WordSpacings",
    -  "WordStem",
    -  "WordTranslation",
    -  "WorkingPrecision",
    -  "WrapAround",
    -  "Write",
    -  "WriteLine",
    -  "WriteString",
    -  "Wronskian",
    -  "XMLElement",
    -  "XMLObject",
    -  "XMLTemplate",
    -  "Xnor",
    -  "Xor",
    -  "XYZColor",
    -  "Yellow",
    -  "Yesterday",
    -  "YuleDissimilarity",
    -  "ZernikeR",
    -  "ZeroSymmetric",
    -  "ZeroTest",
    -  "ZeroWidthTimes",
    -  "Zeta",
    -  "ZetaZero",
    -  "ZIPCodeData",
    -  "ZipfDistribution",
    -  "ZoomCenter",
    -  "ZoomFactor",
    -  "ZTest",
    -  "ZTransform",
    -  "$Aborted",
    -  "$ActivationGroupID",
    -  "$ActivationKey",
    -  "$ActivationUserRegistered",
    -  "$AddOnsDirectory",
    -  "$AllowDataUpdates",
    -  "$AllowExternalChannelFunctions",
    -  "$AllowInternet",
    -  "$AssertFunction",
    -  "$Assumptions",
    -  "$AsynchronousTask",
    -  "$AudioDecoders",
    -  "$AudioEncoders",
    -  "$AudioInputDevices",
    -  "$AudioOutputDevices",
    -  "$BaseDirectory",
    -  "$BasePacletsDirectory",
    -  "$BatchInput",
    -  "$BatchOutput",
    -  "$BlockchainBase",
    -  "$BoxForms",
    -  "$ByteOrdering",
    -  "$CacheBaseDirectory",
    -  "$Canceled",
    -  "$ChannelBase",
    -  "$CharacterEncoding",
    -  "$CharacterEncodings",
    -  "$CloudAccountName",
    -  "$CloudBase",
    -  "$CloudConnected",
    -  "$CloudConnection",
    -  "$CloudCreditsAvailable",
    -  "$CloudEvaluation",
    -  "$CloudExpressionBase",
    -  "$CloudObjectNameFormat",
    -  "$CloudObjectURLType",
    -  "$CloudRootDirectory",
    -  "$CloudSymbolBase",
    -  "$CloudUserID",
    -  "$CloudUserUUID",
    -  "$CloudVersion",
    -  "$CloudVersionNumber",
    -  "$CloudWolframEngineVersionNumber",
    -  "$CommandLine",
    -  "$CompilationTarget",
    -  "$ConditionHold",
    -  "$ConfiguredKernels",
    -  "$Context",
    -  "$ContextPath",
    -  "$ControlActiveSetting",
    -  "$Cookies",
    -  "$CookieStore",
    -  "$CreationDate",
    -  "$CurrentLink",
    -  "$CurrentTask",
    -  "$CurrentWebSession",
    -  "$DataStructures",
    -  "$DateStringFormat",
    -  "$DefaultAudioInputDevice",
    -  "$DefaultAudioOutputDevice",
    -  "$DefaultFont",
    -  "$DefaultFrontEnd",
    -  "$DefaultImagingDevice",
    -  "$DefaultLocalBase",
    -  "$DefaultMailbox",
    -  "$DefaultNetworkInterface",
    -  "$DefaultPath",
    -  "$DefaultProxyRules",
    -  "$DefaultSystemCredentialStore",
    -  "$Display",
    -  "$DisplayFunction",
    -  "$DistributedContexts",
    -  "$DynamicEvaluation",
    -  "$Echo",
    -  "$EmbedCodeEnvironments",
    -  "$EmbeddableServices",
    -  "$EntityStores",
    -  "$Epilog",
    -  "$EvaluationCloudBase",
    -  "$EvaluationCloudObject",
    -  "$EvaluationEnvironment",
    -  "$ExportFormats",
    -  "$ExternalIdentifierTypes",
    -  "$ExternalStorageBase",
    -  "$Failed",
    -  "$FinancialDataSource",
    -  "$FontFamilies",
    -  "$FormatType",
    -  "$FrontEnd",
    -  "$FrontEndSession",
    -  "$GeoEntityTypes",
    -  "$GeoLocation",
    -  "$GeoLocationCity",
    -  "$GeoLocationCountry",
    -  "$GeoLocationPrecision",
    -  "$GeoLocationSource",
    -  "$HistoryLength",
    -  "$HomeDirectory",
    -  "$HTMLExportRules",
    -  "$HTTPCookies",
    -  "$HTTPRequest",
    -  "$IgnoreEOF",
    -  "$ImageFormattingWidth",
    -  "$ImageResolution",
    -  "$ImagingDevice",
    -  "$ImagingDevices",
    -  "$ImportFormats",
    -  "$IncomingMailSettings",
    -  "$InitialDirectory",
    -  "$Initialization",
    -  "$InitializationContexts",
    -  "$Input",
    -  "$InputFileName",
    -  "$InputStreamMethods",
    -  "$Inspector",
    -  "$InstallationDate",
    -  "$InstallationDirectory",
    -  "$InterfaceEnvironment",
    -  "$InterpreterTypes",
    -  "$IterationLimit",
    -  "$KernelCount",
    -  "$KernelID",
    -  "$Language",
    -  "$LaunchDirectory",
    -  "$LibraryPath",
    -  "$LicenseExpirationDate",
    -  "$LicenseID",
    -  "$LicenseProcesses",
    -  "$LicenseServer",
    -  "$LicenseSubprocesses",
    -  "$LicenseType",
    -  "$Line",
    -  "$Linked",
    -  "$LinkSupported",
    -  "$LoadedFiles",
    -  "$LocalBase",
    -  "$LocalSymbolBase",
    -  "$MachineAddresses",
    -  "$MachineDomain",
    -  "$MachineDomains",
    -  "$MachineEpsilon",
    -  "$MachineID",
    -  "$MachineName",
    -  "$MachinePrecision",
    -  "$MachineType",
    -  "$MaxExtraPrecision",
    -  "$MaxLicenseProcesses",
    -  "$MaxLicenseSubprocesses",
    -  "$MaxMachineNumber",
    -  "$MaxNumber",
    -  "$MaxPiecewiseCases",
    -  "$MaxPrecision",
    -  "$MaxRootDegree",
    -  "$MessageGroups",
    -  "$MessageList",
    -  "$MessagePrePrint",
    -  "$Messages",
    -  "$MinMachineNumber",
    -  "$MinNumber",
    -  "$MinorReleaseNumber",
    -  "$MinPrecision",
    -  "$MobilePhone",
    -  "$ModuleNumber",
    -  "$NetworkConnected",
    -  "$NetworkInterfaces",
    -  "$NetworkLicense",
    -  "$NewMessage",
    -  "$NewSymbol",
    -  "$NotebookInlineStorageLimit",
    -  "$Notebooks",
    -  "$NoValue",
    -  "$NumberMarks",
    -  "$Off",
    -  "$OperatingSystem",
    -  "$Output",
    -  "$OutputForms",
    -  "$OutputSizeLimit",
    -  "$OutputStreamMethods",
    -  "$Packages",
    -  "$ParentLink",
    -  "$ParentProcessID",
    -  "$PasswordFile",
    -  "$PatchLevelID",
    -  "$Path",
    -  "$PathnameSeparator",
    -  "$PerformanceGoal",
    -  "$Permissions",
    -  "$PermissionsGroupBase",
    -  "$PersistenceBase",
    -  "$PersistencePath",
    -  "$PipeSupported",
    -  "$PlotTheme",
    -  "$Post",
    -  "$Pre",
    -  "$PreferencesDirectory",
    -  "$PreInitialization",
    -  "$PrePrint",
    -  "$PreRead",
    -  "$PrintForms",
    -  "$PrintLiteral",
    -  "$Printout3DPreviewer",
    -  "$ProcessID",
    -  "$ProcessorCount",
    -  "$ProcessorType",
    -  "$ProductInformation",
    -  "$ProgramName",
    -  "$PublisherID",
    -  "$RandomState",
    -  "$RecursionLimit",
    -  "$RegisteredDeviceClasses",
    -  "$RegisteredUserName",
    -  "$ReleaseNumber",
    -  "$RequesterAddress",
    -  "$RequesterWolframID",
    -  "$RequesterWolframUUID",
    -  "$RootDirectory",
    -  "$ScheduledTask",
    -  "$ScriptCommandLine",
    -  "$ScriptInputString",
    -  "$SecuredAuthenticationKeyTokens",
    -  "$ServiceCreditsAvailable",
    -  "$Services",
    -  "$SessionID",
    -  "$SetParentLink",
    -  "$SharedFunctions",
    -  "$SharedVariables",
    -  "$SoundDisplay",
    -  "$SoundDisplayFunction",
    -  "$SourceLink",
    -  "$SSHAuthentication",
    -  "$SubtitleDecoders",
    -  "$SubtitleEncoders",
    -  "$SummaryBoxDataSizeLimit",
    -  "$SuppressInputFormHeads",
    -  "$SynchronousEvaluation",
    -  "$SyntaxHandler",
    -  "$System",
    -  "$SystemCharacterEncoding",
    -  "$SystemCredentialStore",
    -  "$SystemID",
    -  "$SystemMemory",
    -  "$SystemShell",
    -  "$SystemTimeZone",
    -  "$SystemWordLength",
    -  "$TemplatePath",
    -  "$TemporaryDirectory",
    -  "$TemporaryPrefix",
    -  "$TestFileName",
    -  "$TextStyle",
    -  "$TimedOut",
    -  "$TimeUnit",
    -  "$TimeZone",
    -  "$TimeZoneEntity",
    -  "$TopDirectory",
    -  "$TraceOff",
    -  "$TraceOn",
    -  "$TracePattern",
    -  "$TracePostAction",
    -  "$TracePreAction",
    -  "$UnitSystem",
    -  "$Urgent",
    -  "$UserAddOnsDirectory",
    -  "$UserAgentLanguages",
    -  "$UserAgentMachine",
    -  "$UserAgentName",
    -  "$UserAgentOperatingSystem",
    -  "$UserAgentString",
    -  "$UserAgentVersion",
    -  "$UserBaseDirectory",
    -  "$UserBasePacletsDirectory",
    -  "$UserDocumentsDirectory",
    -  "$Username",
    -  "$UserName",
    -  "$UserURLBase",
    -  "$Version",
    -  "$VersionNumber",
    -  "$VideoDecoders",
    -  "$VideoEncoders",
    -  "$VoiceStyles",
    -  "$WolframDocumentsDirectory",
    -  "$WolframID",
    -  "$WolframUUID"
    -];
    -
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function optional(re) {
    -  return concat('(', re, ')?');
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/**
    - * Any of the passed expresssions may match
    - *
    - * Creates a huge this | this | that | that match
    - * @param {(RegExp | string)[] } args
    - * @returns {string}
    - */
    -function either(...args) {
    -  const joined = '(' + args.map((x) => source(x)).join("|") + ")";
    -  return joined;
    -}
    -
    -/*
    -Language: Wolfram Language
    -Description: The Wolfram Language is the programming language used in Wolfram Mathematica, a modern technical computing system spanning most areas of technical computing.
    -Authors: Patrick Scheibe , Robert Jacobson 
    -Website: https://www.wolfram.com/mathematica/
    -Category: scientific
    -*/
    -
    -/** @type LanguageFn */
    -function mathematica(hljs) {
    -  /*
    -  This rather scary looking matching of Mathematica numbers is carefully explained by Robert Jacobson here:
    -  https://wltools.github.io/LanguageSpec/Specification/Syntax/Number-representations/
    -   */
    -  const BASE_RE = /([2-9]|[1-2]\d|[3][0-5])\^\^/;
    -  const BASE_DIGITS_RE = /(\w*\.\w+|\w+\.\w*|\w+)/;
    -  const NUMBER_RE = /(\d*\.\d+|\d+\.\d*|\d+)/;
    -  const BASE_NUMBER_RE = either(concat(BASE_RE, BASE_DIGITS_RE), NUMBER_RE);
    -
    -  const ACCURACY_RE = /``[+-]?(\d*\.\d+|\d+\.\d*|\d+)/;
    -  const PRECISION_RE = /`([+-]?(\d*\.\d+|\d+\.\d*|\d+))?/;
    -  const APPROXIMATE_NUMBER_RE = either(ACCURACY_RE, PRECISION_RE);
    -
    -  const SCIENTIFIC_NOTATION_RE = /\*\^[+-]?\d+/;
    -
    -  const MATHEMATICA_NUMBER_RE = concat(
    -    BASE_NUMBER_RE,
    -    optional(APPROXIMATE_NUMBER_RE),
    -    optional(SCIENTIFIC_NOTATION_RE)
    -  );
    -
    -  const NUMBERS = {
    -    className: 'number',
    -    relevance: 0,
    -    begin: MATHEMATICA_NUMBER_RE
    -  };
    -
    -  const SYMBOL_RE = /[a-zA-Z$][a-zA-Z0-9$]*/;
    -  const SYSTEM_SYMBOLS_SET = new Set(SYSTEM_SYMBOLS);
    -  /** @type {Mode} */
    -  const SYMBOLS = {
    -    variants: [
    -      {
    -        className: 'builtin-symbol',
    -        begin: SYMBOL_RE,
    -        // for performance out of fear of regex.either(...Mathematica.SYSTEM_SYMBOLS)
    -        "on:begin": (match, response) => {
    -          if (!SYSTEM_SYMBOLS_SET.has(match[0])) response.ignoreMatch();
    -        }
    -      },
    -      {
    -        className: 'symbol',
    -        relevance: 0,
    -        begin: SYMBOL_RE
    -      }
    -    ]
    -  };
    -
    -  const NAMED_CHARACTER = {
    -    className: 'named-character',
    -    begin: /\\\[[$a-zA-Z][$a-zA-Z0-9]+\]/
    -  };
    -
    -  const OPERATORS = {
    -    className: 'operator',
    -    relevance: 0,
    -    begin: /[+\-*/,;.:@~=><&|_`'^?!%]+/
    -  };
    -  const PATTERNS = {
    -    className: 'pattern',
    -    relevance: 0,
    -    begin: /([a-zA-Z$][a-zA-Z0-9$]*)?_+([a-zA-Z$][a-zA-Z0-9$]*)?/
    -  };
    -
    -  const SLOTS = {
    -    className: 'slot',
    -    relevance: 0,
    -    begin: /#[a-zA-Z$][a-zA-Z0-9$]*|#+[0-9]?/
    -  };
    -
    -  const BRACES = {
    -    className: 'brace',
    -    relevance: 0,
    -    begin: /[[\](){}]/
    -  };
    -
    -  const MESSAGES = {
    -    className: 'message-name',
    -    relevance: 0,
    -    begin: concat("::", SYMBOL_RE)
    -  };
    -
    -  return {
    -    name: 'Mathematica',
    -    aliases: [
    -      'mma',
    -      'wl'
    -    ],
    -    classNameAliases: {
    -      brace: 'punctuation',
    -      pattern: 'type',
    -      slot: 'type',
    -      symbol: 'variable',
    -      'named-character': 'variable',
    -      'builtin-symbol': 'built_in',
    -      'message-name': 'string'
    -    },
    -    contains: [
    -      hljs.COMMENT(/\(\*/, /\*\)/, {
    -        contains: [ 'self' ]
    -      }),
    -      PATTERNS,
    -      SLOTS,
    -      MESSAGES,
    -      SYMBOLS,
    -      NAMED_CHARACTER,
    -      hljs.QUOTE_STRING_MODE,
    -      NUMBERS,
    -      OPERATORS,
    -      BRACES
    -    ]
    -  };
    -}
    -
    -module.exports = mathematica;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/matlab.js b/claude-code-source/node_modules/highlight.js/lib/languages/matlab.js
    deleted file mode 100644
    index af05c3d7..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/matlab.js
    +++ /dev/null
    @@ -1,106 +0,0 @@
    -/*
    -Language: Matlab
    -Author: Denis Bardadym 
    -Contributors: Eugene Nizhibitsky , Egor Rogov 
    -Website: https://www.mathworks.com/products/matlab.html
    -Category: scientific
    -*/
    -
    -/*
    -  Formal syntax is not published, helpful link:
    -  https://github.com/kornilova-l/matlab-IntelliJ-plugin/blob/master/src/main/grammar/Matlab.bnf
    -*/
    -function matlab(hljs) {
    -
    -  var TRANSPOSE_RE = '(\'|\\.\')+';
    -  var TRANSPOSE = {
    -    relevance: 0,
    -    contains: [
    -      { begin: TRANSPOSE_RE }
    -    ]
    -  };
    -
    -  return {
    -    name: 'Matlab',
    -    keywords: {
    -      keyword:
    -        'arguments break case catch classdef continue else elseif end enumeration events for function ' +
    -        'global if methods otherwise parfor persistent properties return spmd switch try while',
    -      built_in:
    -        'sin sind sinh asin asind asinh cos cosd cosh acos acosd acosh tan tand tanh atan ' +
    -        'atand atan2 atanh sec secd sech asec asecd asech csc cscd csch acsc acscd acsch cot ' +
    -        'cotd coth acot acotd acoth hypot exp expm1 log log1p log10 log2 pow2 realpow reallog ' +
    -        'realsqrt sqrt nthroot nextpow2 abs angle complex conj imag real unwrap isreal ' +
    -        'cplxpair fix floor ceil round mod rem sign airy besselj bessely besselh besseli ' +
    -        'besselk beta betainc betaln ellipj ellipke erf erfc erfcx erfinv expint gamma ' +
    -        'gammainc gammaln psi legendre cross dot factor isprime primes gcd lcm rat rats perms ' +
    -        'nchoosek factorial cart2sph cart2pol pol2cart sph2cart hsv2rgb rgb2hsv zeros ones ' +
    -        'eye repmat rand randn linspace logspace freqspace meshgrid accumarray size length ' +
    -        'ndims numel disp isempty isequal isequalwithequalnans cat reshape diag blkdiag tril ' +
    -        'triu fliplr flipud flipdim rot90 find sub2ind ind2sub bsxfun ndgrid permute ipermute ' +
    -        'shiftdim circshift squeeze isscalar isvector ans eps realmax realmin pi i|0 inf nan ' +
    -        'isnan isinf isfinite j|0 why compan gallery hadamard hankel hilb invhilb magic pascal ' +
    -        'rosser toeplitz vander wilkinson max min nanmax nanmin mean nanmean type table ' +
    -        'readtable writetable sortrows sort figure plot plot3 scatter scatter3 cellfun ' +
    -        'legend intersect ismember procrustes hold num2cell '
    -    },
    -    illegal: '(//|"|#|/\\*|\\s+/\\w+)',
    -    contains: [
    -      {
    -        className: 'function',
    -        beginKeywords: 'function', end: '$',
    -        contains: [
    -          hljs.UNDERSCORE_TITLE_MODE,
    -          {
    -            className: 'params',
    -            variants: [
    -              {begin: '\\(', end: '\\)'},
    -              {begin: '\\[', end: '\\]'}
    -            ]
    -          }
    -        ]
    -      },
    -      {
    -        className: 'built_in',
    -        begin: /true|false/,
    -        relevance: 0,
    -        starts: TRANSPOSE
    -      },
    -      {
    -        begin: '[a-zA-Z][a-zA-Z_0-9]*' + TRANSPOSE_RE,
    -        relevance: 0
    -      },
    -      {
    -        className: 'number',
    -        begin: hljs.C_NUMBER_RE,
    -        relevance: 0,
    -        starts: TRANSPOSE
    -      },
    -      {
    -        className: 'string',
    -        begin: '\'', end: '\'',
    -        contains: [
    -          hljs.BACKSLASH_ESCAPE,
    -          {begin: '\'\''}]
    -      },
    -      {
    -        begin: /\]|\}|\)/,
    -        relevance: 0,
    -        starts: TRANSPOSE
    -      },
    -      {
    -        className: 'string',
    -        begin: '"', end: '"',
    -        contains: [
    -          hljs.BACKSLASH_ESCAPE,
    -          {begin: '""'}
    -        ],
    -        starts: TRANSPOSE
    -      },
    -      hljs.COMMENT('^\\s*%\\{\\s*$', '^\\s*%\\}\\s*$'),
    -      hljs.COMMENT('%', '$')
    -    ]
    -  };
    -}
    -
    -module.exports = matlab;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/maxima.js b/claude-code-source/node_modules/highlight.js/lib/languages/maxima.js
    deleted file mode 100644
    index d0b210aa..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/maxima.js
    +++ /dev/null
    @@ -1,417 +0,0 @@
    -/*
    -Language: Maxima
    -Author: Robert Dodier 
    -Website: http://maxima.sourceforge.net
    -Category: scientific
    -*/
    -
    -function maxima(hljs) {
    -  const KEYWORDS =
    -    'if then else elseif for thru do while unless step in and or not';
    -  const LITERALS =
    -    'true false unknown inf minf ind und %e %i %pi %phi %gamma';
    -  const BUILTIN_FUNCTIONS =
    -    ' abasep abs absint absolute_real_time acos acosh acot acoth acsc acsch activate' +
    -    ' addcol add_edge add_edges addmatrices addrow add_vertex add_vertices adjacency_matrix' +
    -    ' adjoin adjoint af agd airy airy_ai airy_bi airy_dai airy_dbi algsys alg_type' +
    -    ' alias allroots alphacharp alphanumericp amortization %and annuity_fv' +
    -    ' annuity_pv antid antidiff AntiDifference append appendfile apply apply1 apply2' +
    -    ' applyb1 apropos args arit_amortization arithmetic arithsum array arrayapply' +
    -    ' arrayinfo arraymake arraysetapply ascii asec asech asin asinh askinteger' +
    -    ' asksign assoc assoc_legendre_p assoc_legendre_q assume assume_external_byte_order' +
    -    ' asympa at atan atan2 atanh atensimp atom atvalue augcoefmatrix augmented_lagrangian_method' +
    -    ' av average_degree backtrace bars barsplot barsplot_description base64 base64_decode' +
    -    ' bashindices batch batchload bc2 bdvac belln benefit_cost bern bernpoly bernstein_approx' +
    -    ' bernstein_expand bernstein_poly bessel bessel_i bessel_j bessel_k bessel_simplify' +
    -    ' bessel_y beta beta_incomplete beta_incomplete_generalized beta_incomplete_regularized' +
    -    ' bezout bfallroots bffac bf_find_root bf_fmin_cobyla bfhzeta bfloat bfloatp' +
    -    ' bfpsi bfpsi0 bfzeta biconnected_components bimetric binomial bipartition' +
    -    ' block blockmatrixp bode_gain bode_phase bothcoef box boxplot boxplot_description' +
    -    ' break bug_report build_info|10 buildq build_sample burn cabs canform canten' +
    -    ' cardinality carg cartan cartesian_product catch cauchy_matrix cbffac cdf_bernoulli' +
    -    ' cdf_beta cdf_binomial cdf_cauchy cdf_chi2 cdf_continuous_uniform cdf_discrete_uniform' +
    -    ' cdf_exp cdf_f cdf_gamma cdf_general_finite_discrete cdf_geometric cdf_gumbel' +
    -    ' cdf_hypergeometric cdf_laplace cdf_logistic cdf_lognormal cdf_negative_binomial' +
    -    ' cdf_noncentral_chi2 cdf_noncentral_student_t cdf_normal cdf_pareto cdf_poisson' +
    -    ' cdf_rank_sum cdf_rayleigh cdf_signed_rank cdf_student_t cdf_weibull cdisplay' +
    -    ' ceiling central_moment cequal cequalignore cf cfdisrep cfexpand cgeodesic' +
    -    ' cgreaterp cgreaterpignore changename changevar chaosgame charat charfun charfun2' +
    -    ' charlist charp charpoly chdir chebyshev_t chebyshev_u checkdiv check_overlaps' +
    -    ' chinese cholesky christof chromatic_index chromatic_number cint circulant_graph' +
    -    ' clear_edge_weight clear_rules clear_vertex_label clebsch_gordan clebsch_graph' +
    -    ' clessp clesspignore close closefile cmetric coeff coefmatrix cograd col collapse' +
    -    ' collectterms columnop columnspace columnswap columnvector combination combine' +
    -    ' comp2pui compare compfile compile compile_file complement_graph complete_bipartite_graph' +
    -    ' complete_graph complex_number_p components compose_functions concan concat' +
    -    ' conjugate conmetderiv connected_components connect_vertices cons constant' +
    -    ' constantp constituent constvalue cont2part content continuous_freq contortion' +
    -    ' contour_plot contract contract_edge contragrad contrib_ode convert coord' +
    -    ' copy copy_file copy_graph copylist copymatrix cor cos cosh cot coth cov cov1' +
    -    ' covdiff covect covers crc24sum create_graph create_list csc csch csetup cspline' +
    -    ' ctaylor ct_coordsys ctransform ctranspose cube_graph cuboctahedron_graph' +
    -    ' cunlisp cv cycle_digraph cycle_graph cylindrical days360 dblint deactivate' +
    -    ' declare declare_constvalue declare_dimensions declare_fundamental_dimensions' +
    -    ' declare_fundamental_units declare_qty declare_translated declare_unit_conversion' +
    -    ' declare_units declare_weights decsym defcon define define_alt_display define_variable' +
    -    ' defint defmatch defrule defstruct deftaylor degree_sequence del delete deleten' +
    -    ' delta demo demoivre denom depends derivdegree derivlist describe desolve' +
    -    ' determinant dfloat dgauss_a dgauss_b dgeev dgemm dgeqrf dgesv dgesvd diag' +
    -    ' diagmatrix diag_matrix diagmatrixp diameter diff digitcharp dimacs_export' +
    -    ' dimacs_import dimension dimensionless dimensions dimensions_as_list direct' +
    -    ' directory discrete_freq disjoin disjointp disolate disp dispcon dispform' +
    -    ' dispfun dispJordan display disprule dispterms distrib divide divisors divsum' +
    -    ' dkummer_m dkummer_u dlange dodecahedron_graph dotproduct dotsimp dpart' +
    -    ' draw draw2d draw3d drawdf draw_file draw_graph dscalar echelon edge_coloring' +
    -    ' edge_connectivity edges eigens_by_jacobi eigenvalues eigenvectors eighth' +
    -    ' einstein eivals eivects elapsed_real_time elapsed_run_time ele2comp ele2polynome' +
    -    ' ele2pui elem elementp elevation_grid elim elim_allbut eliminate eliminate_using' +
    -    ' ellipse elliptic_e elliptic_ec elliptic_eu elliptic_f elliptic_kc elliptic_pi' +
    -    ' ematrix empty_graph emptyp endcons entermatrix entertensor entier equal equalp' +
    -    ' equiv_classes erf erfc erf_generalized erfi errcatch error errormsg errors' +
    -    ' euler ev eval_string evenp every evolution evolution2d evundiff example exp' +
    -    ' expand expandwrt expandwrt_factored expint expintegral_chi expintegral_ci' +
    -    ' expintegral_e expintegral_e1 expintegral_ei expintegral_e_simplify expintegral_li' +
    -    ' expintegral_shi expintegral_si explicit explose exponentialize express expt' +
    -    ' exsec extdiff extract_linear_equations extremal_subset ezgcd %f f90 facsum' +
    -    ' factcomb factor factorfacsum factorial factorout factorsum facts fast_central_elements' +
    -    ' fast_linsolve fasttimes featurep fernfale fft fib fibtophi fifth filename_merge' +
    -    ' file_search file_type fillarray findde find_root find_root_abs find_root_error' +
    -    ' find_root_rel first fix flatten flength float floatnump floor flower_snark' +
    -    ' flush flush1deriv flushd flushnd flush_output fmin_cobyla forget fortran' +
    -    ' fourcos fourexpand fourier fourier_elim fourint fourintcos fourintsin foursimp' +
    -    ' foursin fourth fposition frame_bracket freeof freshline fresnel_c fresnel_s' +
    -    ' from_adjacency_matrix frucht_graph full_listify fullmap fullmapl fullratsimp' +
    -    ' fullratsubst fullsetify funcsolve fundamental_dimensions fundamental_units' +
    -    ' fundef funmake funp fv g0 g1 gamma gamma_greek gamma_incomplete gamma_incomplete_generalized' +
    -    ' gamma_incomplete_regularized gauss gauss_a gauss_b gaussprob gcd gcdex gcdivide' +
    -    ' gcfac gcfactor gd generalized_lambert_w genfact gen_laguerre genmatrix gensym' +
    -    ' geo_amortization geo_annuity_fv geo_annuity_pv geomap geometric geometric_mean' +
    -    ' geosum get getcurrentdirectory get_edge_weight getenv get_lu_factors get_output_stream_string' +
    -    ' get_pixel get_plot_option get_tex_environment get_tex_environment_default' +
    -    ' get_vertex_label gfactor gfactorsum ggf girth global_variances gn gnuplot_close' +
    -    ' gnuplot_replot gnuplot_reset gnuplot_restart gnuplot_start go Gosper GosperSum' +
    -    ' gr2d gr3d gradef gramschmidt graph6_decode graph6_encode graph6_export graph6_import' +
    -    ' graph_center graph_charpoly graph_eigenvalues graph_flow graph_order graph_periphery' +
    -    ' graph_product graph_size graph_union great_rhombicosidodecahedron_graph great_rhombicuboctahedron_graph' +
    -    ' grid_graph grind grobner_basis grotzch_graph hamilton_cycle hamilton_path' +
    -    ' hankel hankel_1 hankel_2 harmonic harmonic_mean hav heawood_graph hermite' +
    -    ' hessian hgfred hilbertmap hilbert_matrix hipow histogram histogram_description' +
    -    ' hodge horner hypergeometric i0 i1 %ibes ic1 ic2 ic_convert ichr1 ichr2 icosahedron_graph' +
    -    ' icosidodecahedron_graph icurvature ident identfor identity idiff idim idummy' +
    -    ' ieqn %if ifactors iframes ifs igcdex igeodesic_coords ilt image imagpart' +
    -    ' imetric implicit implicit_derivative implicit_plot indexed_tensor indices' +
    -    ' induced_subgraph inferencep inference_result infix info_display init_atensor' +
    -    ' init_ctensor in_neighbors innerproduct inpart inprod inrt integerp integer_partitions' +
    -    ' integrate intersect intersection intervalp intopois intosum invariant1 invariant2' +
    -    ' inverse_fft inverse_jacobi_cd inverse_jacobi_cn inverse_jacobi_cs inverse_jacobi_dc' +
    -    ' inverse_jacobi_dn inverse_jacobi_ds inverse_jacobi_nc inverse_jacobi_nd inverse_jacobi_ns' +
    -    ' inverse_jacobi_sc inverse_jacobi_sd inverse_jacobi_sn invert invert_by_adjoint' +
    -    ' invert_by_lu inv_mod irr is is_biconnected is_bipartite is_connected is_digraph' +
    -    ' is_edge_in_graph is_graph is_graph_or_digraph ishow is_isomorphic isolate' +
    -    ' isomorphism is_planar isqrt isreal_p is_sconnected is_tree is_vertex_in_graph' +
    -    ' items_inference %j j0 j1 jacobi jacobian jacobi_cd jacobi_cn jacobi_cs jacobi_dc' +
    -    ' jacobi_dn jacobi_ds jacobi_nc jacobi_nd jacobi_ns jacobi_p jacobi_sc jacobi_sd' +
    -    ' jacobi_sn JF jn join jordan julia julia_set julia_sin %k kdels kdelta kill' +
    -    ' killcontext kostka kron_delta kronecker_product kummer_m kummer_u kurtosis' +
    -    ' kurtosis_bernoulli kurtosis_beta kurtosis_binomial kurtosis_chi2 kurtosis_continuous_uniform' +
    -    ' kurtosis_discrete_uniform kurtosis_exp kurtosis_f kurtosis_gamma kurtosis_general_finite_discrete' +
    -    ' kurtosis_geometric kurtosis_gumbel kurtosis_hypergeometric kurtosis_laplace' +
    -    ' kurtosis_logistic kurtosis_lognormal kurtosis_negative_binomial kurtosis_noncentral_chi2' +
    -    ' kurtosis_noncentral_student_t kurtosis_normal kurtosis_pareto kurtosis_poisson' +
    -    ' kurtosis_rayleigh kurtosis_student_t kurtosis_weibull label labels lagrange' +
    -    ' laguerre lambda lambert_w laplace laplacian_matrix last lbfgs lc2kdt lcharp' +
    -    ' lc_l lcm lc_u ldefint ldisp ldisplay legendre_p legendre_q leinstein length' +
    -    ' let letrules letsimp levi_civita lfreeof lgtreillis lhs li liediff limit' +
    -    ' Lindstedt linear linearinterpol linear_program linear_regression line_graph' +
    -    ' linsolve listarray list_correlations listify list_matrix_entries list_nc_monomials' +
    -    ' listoftens listofvars listp lmax lmin load loadfile local locate_matrix_entry' +
    -    ' log logcontract log_gamma lopow lorentz_gauge lowercasep lpart lratsubst' +
    -    ' lreduce lriemann lsquares_estimates lsquares_estimates_approximate lsquares_estimates_exact' +
    -    ' lsquares_mse lsquares_residual_mse lsquares_residuals lsum ltreillis lu_backsub' +
    -    ' lucas lu_factor %m macroexpand macroexpand1 make_array makebox makefact makegamma' +
    -    ' make_graph make_level_picture makelist makeOrders make_poly_continent make_poly_country' +
    -    ' make_polygon make_random_state make_rgb_picture makeset make_string_input_stream' +
    -    ' make_string_output_stream make_transform mandelbrot mandelbrot_set map mapatom' +
    -    ' maplist matchdeclare matchfix mat_cond mat_fullunblocker mat_function mathml_display' +
    -    ' mat_norm matrix matrixmap matrixp matrix_size mattrace mat_trace mat_unblocker' +
    -    ' max max_clique max_degree max_flow maximize_lp max_independent_set max_matching' +
    -    ' maybe md5sum mean mean_bernoulli mean_beta mean_binomial mean_chi2 mean_continuous_uniform' +
    -    ' mean_deviation mean_discrete_uniform mean_exp mean_f mean_gamma mean_general_finite_discrete' +
    -    ' mean_geometric mean_gumbel mean_hypergeometric mean_laplace mean_logistic' +
    -    ' mean_lognormal mean_negative_binomial mean_noncentral_chi2 mean_noncentral_student_t' +
    -    ' mean_normal mean_pareto mean_poisson mean_rayleigh mean_student_t mean_weibull' +
    -    ' median median_deviation member mesh metricexpandall mgf1_sha1 min min_degree' +
    -    ' min_edge_cut minfactorial minimalPoly minimize_lp minimum_spanning_tree minor' +
    -    ' minpack_lsquares minpack_solve min_vertex_cover min_vertex_cut mkdir mnewton' +
    -    ' mod mode_declare mode_identity ModeMatrix moebius mon2schur mono monomial_dimensions' +
    -    ' multibernstein_poly multi_display_for_texinfo multi_elem multinomial multinomial_coeff' +
    -    ' multi_orbit multiplot_mode multi_pui multsym multthru mycielski_graph nary' +
    -    ' natural_unit nc_degree ncexpt ncharpoly negative_picture neighbors new newcontext' +
    -    ' newdet new_graph newline newton new_variable next_prime nicedummies niceindices' +
    -    ' ninth nofix nonarray noncentral_moment nonmetricity nonnegintegerp nonscalarp' +
    -    ' nonzeroandfreeof notequal nounify nptetrad npv nroots nterms ntermst' +
    -    ' nthroot nullity nullspace num numbered_boundaries numberp number_to_octets' +
    -    ' num_distinct_partitions numerval numfactor num_partitions nusum nzeta nzetai' +
    -    ' nzetar octets_to_number octets_to_oid odd_girth oddp ode2 ode_check odelin' +
    -    ' oid_to_octets op opena opena_binary openr openr_binary openw openw_binary' +
    -    ' operatorp opsubst optimize %or orbit orbits ordergreat ordergreatp orderless' +
    -    ' orderlessp orthogonal_complement orthopoly_recur orthopoly_weight outermap' +
    -    ' out_neighbors outofpois pade parabolic_cylinder_d parametric parametric_surface' +
    -    ' parg parGosper parse_string parse_timedate part part2cont partfrac partition' +
    -    ' partition_set partpol path_digraph path_graph pathname_directory pathname_name' +
    -    ' pathname_type pdf_bernoulli pdf_beta pdf_binomial pdf_cauchy pdf_chi2 pdf_continuous_uniform' +
    -    ' pdf_discrete_uniform pdf_exp pdf_f pdf_gamma pdf_general_finite_discrete' +
    -    ' pdf_geometric pdf_gumbel pdf_hypergeometric pdf_laplace pdf_logistic pdf_lognormal' +
    -    ' pdf_negative_binomial pdf_noncentral_chi2 pdf_noncentral_student_t pdf_normal' +
    -    ' pdf_pareto pdf_poisson pdf_rank_sum pdf_rayleigh pdf_signed_rank pdf_student_t' +
    -    ' pdf_weibull pearson_skewness permanent permut permutation permutations petersen_graph' +
    -    ' petrov pickapart picture_equalp picturep piechart piechart_description planar_embedding' +
    -    ' playback plog plot2d plot3d plotdf ploteq plsquares pochhammer points poisdiff' +
    -    ' poisexpt poisint poismap poisplus poissimp poissubst poistimes poistrim polar' +
    -    ' polarform polartorect polar_to_xy poly_add poly_buchberger poly_buchberger_criterion' +
    -    ' poly_colon_ideal poly_content polydecomp poly_depends_p poly_elimination_ideal' +
    -    ' poly_exact_divide poly_expand poly_expt poly_gcd polygon poly_grobner poly_grobner_equal' +
    -    ' poly_grobner_member poly_grobner_subsetp poly_ideal_intersection poly_ideal_polysaturation' +
    -    ' poly_ideal_polysaturation1 poly_ideal_saturation poly_ideal_saturation1 poly_lcm' +
    -    ' poly_minimization polymod poly_multiply polynome2ele polynomialp poly_normal_form' +
    -    ' poly_normalize poly_normalize_list poly_polysaturation_extension poly_primitive_part' +
    -    ' poly_pseudo_divide poly_reduced_grobner poly_reduction poly_saturation_extension' +
    -    ' poly_s_polynomial poly_subtract polytocompanion pop postfix potential power_mod' +
    -    ' powerseries powerset prefix prev_prime primep primes principal_components' +
    -    ' print printf printfile print_graph printpois printprops prodrac product properties' +
    -    ' propvars psi psubst ptriangularize pui pui2comp pui2ele pui2polynome pui_direct' +
    -    ' puireduc push put pv qput qrange qty quad_control quad_qag quad_qagi quad_qagp' +
    -    ' quad_qags quad_qawc quad_qawf quad_qawo quad_qaws quadrilateral quantile' +
    -    ' quantile_bernoulli quantile_beta quantile_binomial quantile_cauchy quantile_chi2' +
    -    ' quantile_continuous_uniform quantile_discrete_uniform quantile_exp quantile_f' +
    -    ' quantile_gamma quantile_general_finite_discrete quantile_geometric quantile_gumbel' +
    -    ' quantile_hypergeometric quantile_laplace quantile_logistic quantile_lognormal' +
    -    ' quantile_negative_binomial quantile_noncentral_chi2 quantile_noncentral_student_t' +
    -    ' quantile_normal quantile_pareto quantile_poisson quantile_rayleigh quantile_student_t' +
    -    ' quantile_weibull quartile_skewness quit qunit quotient racah_v racah_w radcan' +
    -    ' radius random random_bernoulli random_beta random_binomial random_bipartite_graph' +
    -    ' random_cauchy random_chi2 random_continuous_uniform random_digraph random_discrete_uniform' +
    -    ' random_exp random_f random_gamma random_general_finite_discrete random_geometric' +
    -    ' random_graph random_graph1 random_gumbel random_hypergeometric random_laplace' +
    -    ' random_logistic random_lognormal random_negative_binomial random_network' +
    -    ' random_noncentral_chi2 random_noncentral_student_t random_normal random_pareto' +
    -    ' random_permutation random_poisson random_rayleigh random_regular_graph random_student_t' +
    -    ' random_tournament random_tree random_weibull range rank rat ratcoef ratdenom' +
    -    ' ratdiff ratdisrep ratexpand ratinterpol rational rationalize ratnumer ratnump' +
    -    ' ratp ratsimp ratsubst ratvars ratweight read read_array read_binary_array' +
    -    ' read_binary_list read_binary_matrix readbyte readchar read_hashed_array readline' +
    -    ' read_list read_matrix read_nested_list readonly read_xpm real_imagpart_to_conjugate' +
    -    ' realpart realroots rearray rectangle rectform rectform_log_if_constant recttopolar' +
    -    ' rediff reduce_consts reduce_order region region_boundaries region_boundaries_plus' +
    -    ' rem remainder remarray rembox remcomps remcon remcoord remfun remfunction' +
    -    ' remlet remove remove_constvalue remove_dimensions remove_edge remove_fundamental_dimensions' +
    -    ' remove_fundamental_units remove_plot_option remove_vertex rempart remrule' +
    -    ' remsym remvalue rename rename_file reset reset_displays residue resolvante' +
    -    ' resolvante_alternee1 resolvante_bipartite resolvante_diedrale resolvante_klein' +
    -    ' resolvante_klein3 resolvante_produit_sym resolvante_unitaire resolvante_vierer' +
    -    ' rest resultant return reveal reverse revert revert2 rgb2level rhs ricci riemann' +
    -    ' rinvariant risch rk rmdir rncombine romberg room rootscontract round row' +
    -    ' rowop rowswap rreduce run_testsuite %s save saving scalarp scaled_bessel_i' +
    -    ' scaled_bessel_i0 scaled_bessel_i1 scalefactors scanmap scatterplot scatterplot_description' +
    -    ' scene schur2comp sconcat scopy scsimp scurvature sdowncase sec sech second' +
    -    ' sequal sequalignore set_alt_display setdifference set_draw_defaults set_edge_weight' +
    -    ' setelmx setequalp setify setp set_partitions set_plot_option set_prompt set_random_state' +
    -    ' set_tex_environment set_tex_environment_default setunits setup_autoload set_up_dot_simplifications' +
    -    ' set_vertex_label seventh sexplode sf sha1sum sha256sum shortest_path shortest_weighted_path' +
    -    ' show showcomps showratvars sierpinskiale sierpinskimap sign signum similaritytransform' +
    -    ' simp_inequality simplify_sum simplode simpmetderiv simtran sin sinh sinsert' +
    -    ' sinvertcase sixth skewness skewness_bernoulli skewness_beta skewness_binomial' +
    -    ' skewness_chi2 skewness_continuous_uniform skewness_discrete_uniform skewness_exp' +
    -    ' skewness_f skewness_gamma skewness_general_finite_discrete skewness_geometric' +
    -    ' skewness_gumbel skewness_hypergeometric skewness_laplace skewness_logistic' +
    -    ' skewness_lognormal skewness_negative_binomial skewness_noncentral_chi2 skewness_noncentral_student_t' +
    -    ' skewness_normal skewness_pareto skewness_poisson skewness_rayleigh skewness_student_t' +
    -    ' skewness_weibull slength smake small_rhombicosidodecahedron_graph small_rhombicuboctahedron_graph' +
    -    ' smax smin smismatch snowmap snub_cube_graph snub_dodecahedron_graph solve' +
    -    ' solve_rec solve_rec_rat some somrac sort sparse6_decode sparse6_encode sparse6_export' +
    -    ' sparse6_import specint spherical spherical_bessel_j spherical_bessel_y spherical_hankel1' +
    -    ' spherical_hankel2 spherical_harmonic spherical_to_xyz splice split sposition' +
    -    ' sprint sqfr sqrt sqrtdenest sremove sremovefirst sreverse ssearch ssort sstatus' +
    -    ' ssubst ssubstfirst staircase standardize standardize_inverse_trig starplot' +
    -    ' starplot_description status std std1 std_bernoulli std_beta std_binomial' +
    -    ' std_chi2 std_continuous_uniform std_discrete_uniform std_exp std_f std_gamma' +
    -    ' std_general_finite_discrete std_geometric std_gumbel std_hypergeometric std_laplace' +
    -    ' std_logistic std_lognormal std_negative_binomial std_noncentral_chi2 std_noncentral_student_t' +
    -    ' std_normal std_pareto std_poisson std_rayleigh std_student_t std_weibull' +
    -    ' stemplot stirling stirling1 stirling2 strim striml strimr string stringout' +
    -    ' stringp strong_components struve_h struve_l sublis sublist sublist_indices' +
    -    ' submatrix subsample subset subsetp subst substinpart subst_parallel substpart' +
    -    ' substring subvar subvarp sum sumcontract summand_to_rec supcase supcontext' +
    -    ' symbolp symmdifference symmetricp system take_channel take_inference tan' +
    -    ' tanh taylor taylorinfo taylorp taylor_simplifier taytorat tcl_output tcontract' +
    -    ' tellrat tellsimp tellsimpafter tentex tenth test_mean test_means_difference' +
    -    ' test_normality test_proportion test_proportions_difference test_rank_sum' +
    -    ' test_sign test_signed_rank test_variance test_variance_ratio tex tex1 tex_display' +
    -    ' texput %th third throw time timedate timer timer_info tldefint tlimit todd_coxeter' +
    -    ' toeplitz tokens to_lisp topological_sort to_poly to_poly_solve totaldisrep' +
    -    ' totalfourier totient tpartpol trace tracematrix trace_options transform_sample' +
    -    ' translate translate_file transpose treefale tree_reduce treillis treinat' +
    -    ' triangle triangularize trigexpand trigrat trigreduce trigsimp trunc truncate' +
    -    ' truncated_cube_graph truncated_dodecahedron_graph truncated_icosahedron_graph' +
    -    ' truncated_tetrahedron_graph tr_warnings_get tube tutte_graph ueivects uforget' +
    -    ' ultraspherical underlying_graph undiff union unique uniteigenvectors unitp' +
    -    ' units unit_step unitvector unorder unsum untellrat untimer' +
    -    ' untrace uppercasep uricci uriemann uvect vandermonde_matrix var var1 var_bernoulli' +
    -    ' var_beta var_binomial var_chi2 var_continuous_uniform var_discrete_uniform' +
    -    ' var_exp var_f var_gamma var_general_finite_discrete var_geometric var_gumbel' +
    -    ' var_hypergeometric var_laplace var_logistic var_lognormal var_negative_binomial' +
    -    ' var_noncentral_chi2 var_noncentral_student_t var_normal var_pareto var_poisson' +
    -    ' var_rayleigh var_student_t var_weibull vector vectorpotential vectorsimp' +
    -    ' verbify vers vertex_coloring vertex_connectivity vertex_degree vertex_distance' +
    -    ' vertex_eccentricity vertex_in_degree vertex_out_degree vertices vertices_to_cycle' +
    -    ' vertices_to_path %w weyl wheel_graph wiener_index wigner_3j wigner_6j' +
    -    ' wigner_9j with_stdout write_binary_data writebyte write_data writefile wronskian' +
    -    ' xreduce xthru %y Zeilberger zeroequiv zerofor zeromatrix zeromatrixp zeta' +
    -    ' zgeev zheev zlange zn_add_table zn_carmichael_lambda zn_characteristic_factors' +
    -    ' zn_determinant zn_factor_generators zn_invert_by_lu zn_log zn_mult_table' +
    -    ' absboxchar activecontexts adapt_depth additive adim aform algebraic' +
    -    ' algepsilon algexact aliases allbut all_dotsimp_denoms allocation allsym alphabetic' +
    -    ' animation antisymmetric arrays askexp assume_pos assume_pos_pred assumescalar' +
    -    ' asymbol atomgrad atrig1 axes axis_3d axis_bottom axis_left axis_right axis_top' +
    -    ' azimuth background background_color backsubst berlefact bernstein_explicit' +
    -    ' besselexpand beta_args_sum_to_integer beta_expand bftorat bftrunc bindtest' +
    -    ' border boundaries_array box boxchar breakup %c capping cauchysum cbrange' +
    -    ' cbtics center cflength cframe_flag cnonmet_flag color color_bar color_bar_tics' +
    -    ' colorbox columns commutative complex cone context contexts contour contour_levels' +
    -    ' cosnpiflag ctaypov ctaypt ctayswitch ctayvar ct_coords ctorsion_flag ctrgsimp' +
    -    ' cube current_let_rule_package cylinder data_file_name debugmode decreasing' +
    -    ' default_let_rule_package delay dependencies derivabbrev derivsubst detout' +
    -    ' diagmetric diff dim dimensions dispflag display2d|10 display_format_internal' +
    -    ' distribute_over doallmxops domain domxexpt domxmxops domxnctimes dontfactor' +
    -    ' doscmxops doscmxplus dot0nscsimp dot0simp dot1simp dotassoc dotconstrules' +
    -    ' dotdistrib dotexptsimp dotident dotscrules draw_graph_program draw_realpart' +
    -    ' edge_color edge_coloring edge_partition edge_type edge_width %edispflag' +
    -    ' elevation %emode endphi endtheta engineering_format_floats enhanced3d %enumer' +
    -    ' epsilon_lp erfflag erf_representation errormsg error_size error_syms error_type' +
    -    ' %e_to_numlog eval even evenfun evflag evfun ev_point expandwrt_denom expintexpand' +
    -    ' expintrep expon expop exptdispflag exptisolate exptsubst facexpand facsum_combine' +
    -    ' factlim factorflag factorial_expand factors_only fb feature features' +
    -    ' file_name file_output_append file_search_demo file_search_lisp file_search_maxima|10' +
    -    ' file_search_tests file_search_usage file_type_lisp file_type_maxima|10 fill_color' +
    -    ' fill_density filled_func fixed_vertices flipflag float2bf font font_size' +
    -    ' fortindent fortspaces fpprec fpprintprec functions gamma_expand gammalim' +
    -    ' gdet genindex gensumnum GGFCFMAX GGFINFINITY globalsolve gnuplot_command' +
    -    ' gnuplot_curve_styles gnuplot_curve_titles gnuplot_default_term_command gnuplot_dumb_term_command' +
    -    ' gnuplot_file_args gnuplot_file_name gnuplot_out_file gnuplot_pdf_term_command' +
    -    ' gnuplot_pm3d gnuplot_png_term_command gnuplot_postamble gnuplot_preamble' +
    -    ' gnuplot_ps_term_command gnuplot_svg_term_command gnuplot_term gnuplot_view_args' +
    -    ' Gosper_in_Zeilberger gradefs grid grid2d grind halfangles head_angle head_both' +
    -    ' head_length head_type height hypergeometric_representation %iargs ibase' +
    -    ' icc1 icc2 icounter idummyx ieqnprint ifb ifc1 ifc2 ifg ifgi ifr iframe_bracket_form' +
    -    ' ifri igeowedge_flag ikt1 ikt2 imaginary inchar increasing infeval' +
    -    ' infinity inflag infolists inm inmc1 inmc2 intanalysis integer integervalued' +
    -    ' integrate_use_rootsof integration_constant integration_constant_counter interpolate_color' +
    -    ' intfaclim ip_grid ip_grid_in irrational isolate_wrt_times iterations itr' +
    -    ' julia_parameter %k1 %k2 keepfloat key key_pos kinvariant kt label label_alignment' +
    -    ' label_orientation labels lassociative lbfgs_ncorrections lbfgs_nfeval_max' +
    -    ' leftjust legend letrat let_rule_packages lfg lg lhospitallim limsubst linear' +
    -    ' linear_solver linechar linel|10 linenum line_type linewidth line_width linsolve_params' +
    -    ' linsolvewarn lispdisp listarith listconstvars listdummyvars lmxchar load_pathname' +
    -    ' loadprint logabs logarc logcb logconcoeffp logexpand lognegint logsimp logx' +
    -    ' logx_secondary logy logy_secondary logz lriem m1pbranch macroexpansion macros' +
    -    ' mainvar manual_demo maperror mapprint matrix_element_add matrix_element_mult' +
    -    ' matrix_element_transpose maxapplydepth maxapplyheight maxima_tempdir|10 maxima_userdir|10' +
    -    ' maxnegex MAX_ORD maxposex maxpsifracdenom maxpsifracnum maxpsinegint maxpsiposint' +
    -    ' maxtayorder mesh_lines_color method mod_big_prime mode_check_errorp' +
    -    ' mode_checkp mode_check_warnp mod_test mod_threshold modular_linear_solver' +
    -    ' modulus multiplicative multiplicities myoptions nary negdistrib negsumdispflag' +
    -    ' newline newtonepsilon newtonmaxiter nextlayerfactor niceindicespref nm nmc' +
    -    ' noeval nolabels nonegative_lp noninteger nonscalar noun noundisp nouns np' +
    -    ' npi nticks ntrig numer numer_pbranch obase odd oddfun opacity opproperties' +
    -    ' opsubst optimprefix optionset orientation origin orthopoly_returns_intervals' +
    -    ' outative outchar packagefile palette partswitch pdf_file pfeformat phiresolution' +
    -    ' %piargs piece pivot_count_sx pivot_max_sx plot_format plot_options plot_realpart' +
    -    ' png_file pochhammer_max_index points pointsize point_size points_joined point_type' +
    -    ' poislim poisson poly_coefficient_ring poly_elimination_order polyfactor poly_grobner_algorithm' +
    -    ' poly_grobner_debug poly_monomial_order poly_primary_elimination_order poly_return_term_list' +
    -    ' poly_secondary_elimination_order poly_top_reduction_only posfun position' +
    -    ' powerdisp pred prederror primep_number_of_tests product_use_gamma program' +
    -    ' programmode promote_float_to_bigfloat prompt proportional_axes props psexpand' +
    -    ' ps_file radexpand radius radsubstflag rassociative ratalgdenom ratchristof' +
    -    ' ratdenomdivide rateinstein ratepsilon ratfac rational ratmx ratprint ratriemann' +
    -    ' ratsimpexpons ratvarswitch ratweights ratweyl ratwtlvl real realonly redraw' +
    -    ' refcheck resolution restart resultant ric riem rmxchar %rnum_list rombergabs' +
    -    ' rombergit rombergmin rombergtol rootsconmode rootsepsilon run_viewer same_xy' +
    -    ' same_xyz savedef savefactors scalar scalarmatrixp scale scale_lp setcheck' +
    -    ' setcheckbreak setval show_edge_color show_edges show_edge_type show_edge_width' +
    -    ' show_id show_label showtime show_vertex_color show_vertex_size show_vertex_type' +
    -    ' show_vertices show_weight simp simplified_output simplify_products simpproduct' +
    -    ' simpsum sinnpiflag solvedecomposes solveexplicit solvefactors solvenullwarn' +
    -    ' solveradcan solvetrigwarn space sparse sphere spring_embedding_depth sqrtdispflag' +
    -    ' stardisp startphi starttheta stats_numer stringdisp structures style sublis_apply_lambda' +
    -    ' subnumsimp sumexpand sumsplitfact surface surface_hide svg_file symmetric' +
    -    ' tab taylordepth taylor_logexpand taylor_order_coefficients taylor_truncate_polynomials' +
    -    ' tensorkill terminal testsuite_files thetaresolution timer_devalue title tlimswitch' +
    -    ' tr track transcompile transform transform_xy translate_fast_arrays transparent' +
    -    ' transrun tr_array_as_ref tr_bound_function_applyp tr_file_tty_messagesp tr_float_can_branch_complex' +
    -    ' tr_function_call_default trigexpandplus trigexpandtimes triginverses trigsign' +
    -    ' trivial_solutions tr_numer tr_optimize_max_loop tr_semicompile tr_state_vars' +
    -    ' tr_warn_bad_function_calls tr_warn_fexpr tr_warn_meval tr_warn_mode' +
    -    ' tr_warn_undeclared tr_warn_undefined_variable tstep ttyoff tube_extremes' +
    -    ' ufg ug %unitexpand unit_vectors uric uriem use_fast_arrays user_preamble' +
    -    ' usersetunits values vect_cross verbose vertex_color vertex_coloring vertex_partition' +
    -    ' vertex_size vertex_type view warnings weyl width windowname windowtitle wired_surface' +
    -    ' wireframe xaxis xaxis_color xaxis_secondary xaxis_type xaxis_width xlabel' +
    -    ' xlabel_secondary xlength xrange xrange_secondary xtics xtics_axis xtics_rotate' +
    -    ' xtics_rotate_secondary xtics_secondary xtics_secondary_axis xu_grid x_voxel' +
    -    ' xy_file xyplane xy_scale yaxis yaxis_color yaxis_secondary yaxis_type yaxis_width' +
    -    ' ylabel ylabel_secondary ylength yrange yrange_secondary ytics ytics_axis' +
    -    ' ytics_rotate ytics_rotate_secondary ytics_secondary ytics_secondary_axis' +
    -    ' yv_grid y_voxel yx_ratio zaxis zaxis_color zaxis_type zaxis_width zeroa zerob' +
    -    ' zerobern zeta%pi zlabel zlabel_rotate zlength zmin zn_primroot_limit zn_primroot_pretest';
    -  const SYMBOLS = '_ __ %|0 %%|0';
    -
    -  return {
    -    name: 'Maxima',
    -    keywords: {
    -      $pattern: '[A-Za-z_%][0-9A-Za-z_%]*',
    -      keyword: KEYWORDS,
    -      literal: LITERALS,
    -      built_in: BUILTIN_FUNCTIONS,
    -      symbol: SYMBOLS
    -    },
    -    contains: [
    -      {
    -        className: 'comment',
    -        begin: '/\\*',
    -        end: '\\*/',
    -        contains: [ 'self' ]
    -      },
    -      hljs.QUOTE_STRING_MODE,
    -      {
    -        className: 'number',
    -        relevance: 0,
    -        variants: [
    -          {
    -            // float number w/ exponent
    -            // hmm, I wonder if we ought to include other exponent markers?
    -            begin: '\\b(\\d+|\\d+\\.|\\.\\d+|\\d+\\.\\d+)[Ee][-+]?\\d+\\b'
    -          },
    -          {
    -            // bigfloat number
    -            begin: '\\b(\\d+|\\d+\\.|\\.\\d+|\\d+\\.\\d+)[Bb][-+]?\\d+\\b',
    -            relevance: 10
    -          },
    -          {
    -            // float number w/out exponent
    -            // Doesn't seem to recognize floats which start with '.'
    -            begin: '\\b(\\.\\d+|\\d+\\.\\d+)\\b'
    -          },
    -          {
    -            // integer in base up to 36
    -            // Doesn't seem to recognize integers which end with '.'
    -            begin: '\\b(\\d+|0[0-9A-Za-z]+)\\.?\\b'
    -          }
    -        ]
    -      }
    -    ],
    -    illegal: /@/
    -  };
    -}
    -
    -module.exports = maxima;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/mel.js b/claude-code-source/node_modules/highlight.js/lib/languages/mel.js
    deleted file mode 100644
    index 6c66f673..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/mel.js
    +++ /dev/null
    @@ -1,236 +0,0 @@
    -/*
    -Language: MEL
    -Description: Maya Embedded Language
    -Author: Shuen-Huei Guan 
    -Website: http://www.autodesk.com/products/autodesk-maya/overview
    -Category: graphics
    -*/
    -
    -function mel(hljs) {
    -  return {
    -    name: 'MEL',
    -    keywords:
    -      'int float string vector matrix if else switch case default while do for in break ' +
    -      'continue global proc return about abs addAttr addAttributeEditorNodeHelp addDynamic ' +
    -      'addNewShelfTab addPP addPanelCategory addPrefixToName advanceToNextDrivenKey ' +
    -      'affectedNet affects aimConstraint air alias aliasAttr align alignCtx alignCurve ' +
    -      'alignSurface allViewFit ambientLight angle angleBetween animCone animCurveEditor ' +
    -      'animDisplay animView annotate appendStringArray applicationName applyAttrPreset ' +
    -      'applyTake arcLenDimContext arcLengthDimension arclen arrayMapper art3dPaintCtx ' +
    -      'artAttrCtx artAttrPaintVertexCtx artAttrSkinPaintCtx artAttrTool artBuildPaintMenu ' +
    -      'artFluidAttrCtx artPuttyCtx artSelectCtx artSetPaintCtx artUserPaintCtx assignCommand ' +
    -      'assignInputDevice assignViewportFactories attachCurve attachDeviceAttr attachSurface ' +
    -      'attrColorSliderGrp attrCompatibility attrControlGrp attrEnumOptionMenu ' +
    -      'attrEnumOptionMenuGrp attrFieldGrp attrFieldSliderGrp attrNavigationControlGrp ' +
    -      'attrPresetEditWin attributeExists attributeInfo attributeMenu attributeQuery ' +
    -      'autoKeyframe autoPlace bakeClip bakeFluidShading bakePartialHistory bakeResults ' +
    -      'bakeSimulation basename basenameEx batchRender bessel bevel bevelPlus binMembership ' +
    -      'bindSkin blend2 blendShape blendShapeEditor blendShapePanel blendTwoAttr blindDataType ' +
    -      'boneLattice boundary boxDollyCtx boxZoomCtx bufferCurve buildBookmarkMenu ' +
    -      'buildKeyframeMenu button buttonManip CBG cacheFile cacheFileCombine cacheFileMerge ' +
    -      'cacheFileTrack camera cameraView canCreateManip canvas capitalizeString catch ' +
    -      'catchQuiet ceil changeSubdivComponentDisplayLevel changeSubdivRegion channelBox ' +
    -      'character characterMap characterOutlineEditor characterize chdir checkBox checkBoxGrp ' +
    -      'checkDefaultRenderGlobals choice circle circularFillet clamp clear clearCache clip ' +
    -      'clipEditor clipEditorCurrentTimeCtx clipSchedule clipSchedulerOutliner clipTrimBefore ' +
    -      'closeCurve closeSurface cluster cmdFileOutput cmdScrollFieldExecuter ' +
    -      'cmdScrollFieldReporter cmdShell coarsenSubdivSelectionList collision color ' +
    -      'colorAtPoint colorEditor colorIndex colorIndexSliderGrp colorSliderButtonGrp ' +
    -      'colorSliderGrp columnLayout commandEcho commandLine commandPort compactHairSystem ' +
    -      'componentEditor compositingInterop computePolysetVolume condition cone confirmDialog ' +
    -      'connectAttr connectControl connectDynamic connectJoint connectionInfo constrain ' +
    -      'constrainValue constructionHistory container containsMultibyte contextInfo control ' +
    -      'convertFromOldLayers convertIffToPsd convertLightmap convertSolidTx convertTessellation ' +
    -      'convertUnit copyArray copyFlexor copyKey copySkinWeights cos cpButton cpCache ' +
    -      'cpClothSet cpCollision cpConstraint cpConvClothToMesh cpForces cpGetSolverAttr cpPanel ' +
    -      'cpProperty cpRigidCollisionFilter cpSeam cpSetEdit cpSetSolverAttr cpSolver ' +
    -      'cpSolverTypes cpTool cpUpdateClothUVs createDisplayLayer createDrawCtx createEditor ' +
    -      'createLayeredPsdFile createMotionField createNewShelf createNode createRenderLayer ' +
    -      'createSubdivRegion cross crossProduct ctxAbort ctxCompletion ctxEditMode ctxTraverse ' +
    -      'currentCtx currentTime currentTimeCtx currentUnit curve curveAddPtCtx ' +
    -      'curveCVCtx curveEPCtx curveEditorCtx curveIntersect curveMoveEPCtx curveOnSurface ' +
    -      'curveSketchCtx cutKey cycleCheck cylinder dagPose date defaultLightListCheckBox ' +
    -      'defaultNavigation defineDataServer defineVirtualDevice deformer deg_to_rad delete ' +
    -      'deleteAttr deleteShadingGroupsAndMaterials deleteShelfTab deleteUI deleteUnusedBrushes ' +
    -      'delrandstr detachCurve detachDeviceAttr detachSurface deviceEditor devicePanel dgInfo ' +
    -      'dgdirty dgeval dgtimer dimWhen directKeyCtx directionalLight dirmap dirname disable ' +
    -      'disconnectAttr disconnectJoint diskCache displacementToPoly displayAffected ' +
    -      'displayColor displayCull displayLevelOfDetail displayPref displayRGBColor ' +
    -      'displaySmoothness displayStats displayString displaySurface distanceDimContext ' +
    -      'distanceDimension doBlur dolly dollyCtx dopeSheetEditor dot dotProduct ' +
    -      'doubleProfileBirailSurface drag dragAttrContext draggerContext dropoffLocator ' +
    -      'duplicate duplicateCurve duplicateSurface dynCache dynControl dynExport dynExpression ' +
    -      'dynGlobals dynPaintEditor dynParticleCtx dynPref dynRelEdPanel dynRelEditor ' +
    -      'dynamicLoad editAttrLimits editDisplayLayerGlobals editDisplayLayerMembers ' +
    -      'editRenderLayerAdjustment editRenderLayerGlobals editRenderLayerMembers editor ' +
    -      'editorTemplate effector emit emitter enableDevice encodeString endString endsWith env ' +
    -      'equivalent equivalentTol erf error eval evalDeferred evalEcho event ' +
    -      'exactWorldBoundingBox exclusiveLightCheckBox exec executeForEachObject exists exp ' +
    -      'expression expressionEditorListen extendCurve extendSurface extrude fcheck fclose feof ' +
    -      'fflush fgetline fgetword file fileBrowserDialog fileDialog fileExtension fileInfo ' +
    -      'filetest filletCurve filter filterCurve filterExpand filterStudioImport ' +
    -      'findAllIntersections findAnimCurves findKeyframe findMenuItem findRelatedSkinCluster ' +
    -      'finder firstParentOf fitBspline flexor floatEq floatField floatFieldGrp floatScrollBar ' +
    -      'floatSlider floatSlider2 floatSliderButtonGrp floatSliderGrp floor flow fluidCacheInfo ' +
    -      'fluidEmitter fluidVoxelInfo flushUndo fmod fontDialog fopen formLayout format fprint ' +
    -      'frameLayout fread freeFormFillet frewind fromNativePath fwrite gamma gauss ' +
    -      'geometryConstraint getApplicationVersionAsFloat getAttr getClassification ' +
    -      'getDefaultBrush getFileList getFluidAttr getInputDeviceRange getMayaPanelTypes ' +
    -      'getModifiers getPanel getParticleAttr getPluginResource getenv getpid glRender ' +
    -      'glRenderEditor globalStitch gmatch goal gotoBindPose grabColor gradientControl ' +
    -      'gradientControlNoAttr graphDollyCtx graphSelectContext graphTrackCtx gravity grid ' +
    -      'gridLayout group groupObjectsByName HfAddAttractorToAS HfAssignAS HfBuildEqualMap ' +
    -      'HfBuildFurFiles HfBuildFurImages HfCancelAFR HfConnectASToHF HfCreateAttractor ' +
    -      'HfDeleteAS HfEditAS HfPerformCreateAS HfRemoveAttractorFromAS HfSelectAttached ' +
    -      'HfSelectAttractors HfUnAssignAS hardenPointCurve hardware hardwareRenderPanel ' +
    -      'headsUpDisplay headsUpMessage help helpLine hermite hide hilite hitTest hotBox hotkey ' +
    -      'hotkeyCheck hsv_to_rgb hudButton hudSlider hudSliderButton hwReflectionMap hwRender ' +
    -      'hwRenderLoad hyperGraph hyperPanel hyperShade hypot iconTextButton iconTextCheckBox ' +
    -      'iconTextRadioButton iconTextRadioCollection iconTextScrollList iconTextStaticLabel ' +
    -      'ikHandle ikHandleCtx ikHandleDisplayScale ikSolver ikSplineHandleCtx ikSystem ' +
    -      'ikSystemInfo ikfkDisplayMethod illustratorCurves image imfPlugins inheritTransform ' +
    -      'insertJoint insertJointCtx insertKeyCtx insertKnotCurve insertKnotSurface instance ' +
    -      'instanceable instancer intField intFieldGrp intScrollBar intSlider intSliderGrp ' +
    -      'interToUI internalVar intersect iprEngine isAnimCurve isConnected isDirty isParentOf ' +
    -      'isSameObject isTrue isValidObjectName isValidString isValidUiName isolateSelect ' +
    -      'itemFilter itemFilterAttr itemFilterRender itemFilterType joint jointCluster jointCtx ' +
    -      'jointDisplayScale jointLattice keyTangent keyframe keyframeOutliner ' +
    -      'keyframeRegionCurrentTimeCtx keyframeRegionDirectKeyCtx keyframeRegionDollyCtx ' +
    -      'keyframeRegionInsertKeyCtx keyframeRegionMoveKeyCtx keyframeRegionScaleKeyCtx ' +
    -      'keyframeRegionSelectKeyCtx keyframeRegionSetKeyCtx keyframeRegionTrackCtx ' +
    -      'keyframeStats lassoContext lattice latticeDeformKeyCtx launch launchImageEditor ' +
    -      'layerButton layeredShaderPort layeredTexturePort layout layoutDialog lightList ' +
    -      'lightListEditor lightListPanel lightlink lineIntersection linearPrecision linstep ' +
    -      'listAnimatable listAttr listCameras listConnections listDeviceAttachments listHistory ' +
    -      'listInputDeviceAxes listInputDeviceButtons listInputDevices listMenuAnnotation ' +
    -      'listNodeTypes listPanelCategories listRelatives listSets listTransforms ' +
    -      'listUnselected listerEditor loadFluid loadNewShelf loadPlugin ' +
    -      'loadPluginLanguageResources loadPrefObjects localizedPanelLabel lockNode loft log ' +
    -      'longNameOf lookThru ls lsThroughFilter lsType lsUI Mayatomr mag makeIdentity makeLive ' +
    -      'makePaintable makeRoll makeSingleSurface makeTubeOn makebot manipMoveContext ' +
    -      'manipMoveLimitsCtx manipOptions manipRotateContext manipRotateLimitsCtx ' +
    -      'manipScaleContext manipScaleLimitsCtx marker match max memory menu menuBarLayout ' +
    -      'menuEditor menuItem menuItemToShelf menuSet menuSetPref messageLine min minimizeApp ' +
    -      'mirrorJoint modelCurrentTimeCtx modelEditor modelPanel mouse movIn movOut move ' +
    -      'moveIKtoFK moveKeyCtx moveVertexAlongDirection multiProfileBirailSurface mute ' +
    -      'nParticle nameCommand nameField namespace namespaceInfo newPanelItems newton nodeCast ' +
    -      'nodeIconButton nodeOutliner nodePreset nodeType noise nonLinear normalConstraint ' +
    -      'normalize nurbsBoolean nurbsCopyUVSet nurbsCube nurbsEditUV nurbsPlane nurbsSelect ' +
    -      'nurbsSquare nurbsToPoly nurbsToPolygonsPref nurbsToSubdiv nurbsToSubdivPref ' +
    -      'nurbsUVSet nurbsViewDirectionVector objExists objectCenter objectLayer objectType ' +
    -      'objectTypeUI obsoleteProc oceanNurbsPreviewPlane offsetCurve offsetCurveOnSurface ' +
    -      'offsetSurface openGLExtension openMayaPref optionMenu optionMenuGrp optionVar orbit ' +
    -      'orbitCtx orientConstraint outlinerEditor outlinerPanel overrideModifier ' +
    -      'paintEffectsDisplay pairBlend palettePort paneLayout panel panelConfiguration ' +
    -      'panelHistory paramDimContext paramDimension paramLocator parent parentConstraint ' +
    -      'particle particleExists particleInstancer particleRenderInfo partition pasteKey ' +
    -      'pathAnimation pause pclose percent performanceOptions pfxstrokes pickWalk picture ' +
    -      'pixelMove planarSrf plane play playbackOptions playblast plugAttr plugNode pluginInfo ' +
    -      'pluginResourceUtil pointConstraint pointCurveConstraint pointLight pointMatrixMult ' +
    -      'pointOnCurve pointOnSurface pointPosition poleVectorConstraint polyAppend ' +
    -      'polyAppendFacetCtx polyAppendVertex polyAutoProjection polyAverageNormal ' +
    -      'polyAverageVertex polyBevel polyBlendColor polyBlindData polyBoolOp polyBridgeEdge ' +
    -      'polyCacheMonitor polyCheck polyChipOff polyClipboard polyCloseBorder polyCollapseEdge ' +
    -      'polyCollapseFacet polyColorBlindData polyColorDel polyColorPerVertex polyColorSet ' +
    -      'polyCompare polyCone polyCopyUV polyCrease polyCreaseCtx polyCreateFacet ' +
    -      'polyCreateFacetCtx polyCube polyCut polyCutCtx polyCylinder polyCylindricalProjection ' +
    -      'polyDelEdge polyDelFacet polyDelVertex polyDuplicateAndConnect polyDuplicateEdge ' +
    -      'polyEditUV polyEditUVShell polyEvaluate polyExtrudeEdge polyExtrudeFacet ' +
    -      'polyExtrudeVertex polyFlipEdge polyFlipUV polyForceUV polyGeoSampler polyHelix ' +
    -      'polyInfo polyInstallAction polyLayoutUV polyListComponentConversion polyMapCut ' +
    -      'polyMapDel polyMapSew polyMapSewMove polyMergeEdge polyMergeEdgeCtx polyMergeFacet ' +
    -      'polyMergeFacetCtx polyMergeUV polyMergeVertex polyMirrorFace polyMoveEdge ' +
    -      'polyMoveFacet polyMoveFacetUV polyMoveUV polyMoveVertex polyNormal polyNormalPerVertex ' +
    -      'polyNormalizeUV polyOptUvs polyOptions polyOutput polyPipe polyPlanarProjection ' +
    -      'polyPlane polyPlatonicSolid polyPoke polyPrimitive polyPrism polyProjection ' +
    -      'polyPyramid polyQuad polyQueryBlindData polyReduce polySelect polySelectConstraint ' +
    -      'polySelectConstraintMonitor polySelectCtx polySelectEditCtx polySeparate ' +
    -      'polySetToFaceNormal polySewEdge polyShortestPathCtx polySmooth polySoftEdge ' +
    -      'polySphere polySphericalProjection polySplit polySplitCtx polySplitEdge polySplitRing ' +
    -      'polySplitVertex polyStraightenUVBorder polySubdivideEdge polySubdivideFacet ' +
    -      'polyToSubdiv polyTorus polyTransfer polyTriangulate polyUVSet polyUnite polyWedgeFace ' +
    -      'popen popupMenu pose pow preloadRefEd print progressBar progressWindow projFileViewer ' +
    -      'projectCurve projectTangent projectionContext projectionManip promptDialog propModCtx ' +
    -      'propMove psdChannelOutliner psdEditTextureFile psdExport psdTextureFile putenv pwd ' +
    -      'python querySubdiv quit rad_to_deg radial radioButton radioButtonGrp radioCollection ' +
    -      'radioMenuItemCollection rampColorPort rand randomizeFollicles randstate rangeControl ' +
    -      'readTake rebuildCurve rebuildSurface recordAttr recordDevice redo reference ' +
    -      'referenceEdit referenceQuery refineSubdivSelectionList refresh refreshAE ' +
    -      'registerPluginResource rehash reloadImage removeJoint removeMultiInstance ' +
    -      'removePanelCategory rename renameAttr renameSelectionList renameUI render ' +
    -      'renderGlobalsNode renderInfo renderLayerButton renderLayerParent ' +
    -      'renderLayerPostProcess renderLayerUnparent renderManip renderPartition ' +
    -      'renderQualityNode renderSettings renderThumbnailUpdate renderWindowEditor ' +
    -      'renderWindowSelectContext renderer reorder reorderDeformers requires reroot ' +
    -      'resampleFluid resetAE resetPfxToPolyCamera resetTool resolutionNode retarget ' +
    -      'reverseCurve reverseSurface revolve rgb_to_hsv rigidBody rigidSolver roll rollCtx ' +
    -      'rootOf rot rotate rotationInterpolation roundConstantRadius rowColumnLayout rowLayout ' +
    -      'runTimeCommand runup sampleImage saveAllShelves saveAttrPreset saveFluid saveImage ' +
    -      'saveInitialState saveMenu savePrefObjects savePrefs saveShelf saveToolSettings scale ' +
    -      'scaleBrushBrightness scaleComponents scaleConstraint scaleKey scaleKeyCtx sceneEditor ' +
    -      'sceneUIReplacement scmh scriptCtx scriptEditorInfo scriptJob scriptNode scriptTable ' +
    -      'scriptToShelf scriptedPanel scriptedPanelType scrollField scrollLayout sculpt ' +
    -      'searchPathArray seed selLoadSettings select selectContext selectCurveCV selectKey ' +
    -      'selectKeyCtx selectKeyframeRegionCtx selectMode selectPref selectPriority selectType ' +
    -      'selectedNodes selectionConnection separator setAttr setAttrEnumResource ' +
    -      'setAttrMapping setAttrNiceNameResource setConstraintRestPosition ' +
    -      'setDefaultShadingGroup setDrivenKeyframe setDynamic setEditCtx setEditor setFluidAttr ' +
    -      'setFocus setInfinity setInputDeviceMapping setKeyCtx setKeyPath setKeyframe ' +
    -      'setKeyframeBlendshapeTargetWts setMenuMode setNodeNiceNameResource setNodeTypeFlag ' +
    -      'setParent setParticleAttr setPfxToPolyCamera setPluginResource setProject ' +
    -      'setStampDensity setStartupMessage setState setToolTo setUITemplate setXformManip sets ' +
    -      'shadingConnection shadingGeometryRelCtx shadingLightRelCtx shadingNetworkCompare ' +
    -      'shadingNode shapeCompare shelfButton shelfLayout shelfTabLayout shellField ' +
    -      'shortNameOf showHelp showHidden showManipCtx showSelectionInTitle ' +
    -      'showShadingGroupAttrEditor showWindow sign simplify sin singleProfileBirailSurface ' +
    -      'size sizeBytes skinCluster skinPercent smoothCurve smoothTangentSurface smoothstep ' +
    -      'snap2to2 snapKey snapMode snapTogetherCtx snapshot soft softMod softModCtx sort sound ' +
    -      'soundControl source spaceLocator sphere sphrand spotLight spotLightPreviewPort ' +
    -      'spreadSheetEditor spring sqrt squareSurface srtContext stackTrace startString ' +
    -      'startsWith stitchAndExplodeShell stitchSurface stitchSurfacePoints strcmp ' +
    -      'stringArrayCatenate stringArrayContains stringArrayCount stringArrayInsertAtIndex ' +
    -      'stringArrayIntersector stringArrayRemove stringArrayRemoveAtIndex ' +
    -      'stringArrayRemoveDuplicates stringArrayRemoveExact stringArrayToString ' +
    -      'stringToStringArray strip stripPrefixFromName stroke subdAutoProjection ' +
    -      'subdCleanTopology subdCollapse subdDuplicateAndConnect subdEditUV ' +
    -      'subdListComponentConversion subdMapCut subdMapSewMove subdMatchTopology subdMirror ' +
    -      'subdToBlind subdToPoly subdTransferUVsToCache subdiv subdivCrease ' +
    -      'subdivDisplaySmoothness substitute substituteAllString substituteGeometry substring ' +
    -      'surface surfaceSampler surfaceShaderList swatchDisplayPort switchTable symbolButton ' +
    -      'symbolCheckBox sysFile system tabLayout tan tangentConstraint texLatticeDeformContext ' +
    -      'texManipContext texMoveContext texMoveUVShellContext texRotateContext texScaleContext ' +
    -      'texSelectContext texSelectShortestPathCtx texSmudgeUVContext texWinToolCtx text ' +
    -      'textCurves textField textFieldButtonGrp textFieldGrp textManip textScrollList ' +
    -      'textToShelf textureDisplacePlane textureHairColor texturePlacementContext ' +
    -      'textureWindow threadCount threePointArcCtx timeControl timePort timerX toNativePath ' +
    -      'toggle toggleAxis toggleWindowVisibility tokenize tokenizeList tolerance tolower ' +
    -      'toolButton toolCollection toolDropped toolHasOptions toolPropertyWindow torus toupper ' +
    -      'trace track trackCtx transferAttributes transformCompare transformLimits translator ' +
    -      'trim trunc truncateFluidCache truncateHairCache tumble tumbleCtx turbulence ' +
    -      'twoPointArcCtx uiRes uiTemplate unassignInputDevice undo undoInfo ungroup uniform unit ' +
    -      'unloadPlugin untangleUV untitledFileName untrim upAxis updateAE userCtx uvLink ' +
    -      'uvSnapshot validateShelfName vectorize view2dToolCtx viewCamera viewClipPlane ' +
    -      'viewFit viewHeadOn viewLookAt viewManip viewPlace viewSet visor volumeAxis vortex ' +
    -      'waitCursor warning webBrowser webBrowserPrefs whatIs window windowPref wire ' +
    -      'wireContext workspace wrinkle wrinkleContext writeTake xbmLangPathList xform',
    -    illegal: '
    -Description: Mercury is a logic/functional programming language which combines the clarity and expressiveness of declarative programming with advanced static analysis and error detection features.
    -Website: https://www.mercurylang.org
    -*/
    -
    -function mercury(hljs) {
    -  const KEYWORDS = {
    -    keyword:
    -      'module use_module import_module include_module end_module initialise ' +
    -      'mutable initialize finalize finalise interface implementation pred ' +
    -      'mode func type inst solver any_pred any_func is semidet det nondet ' +
    -      'multi erroneous failure cc_nondet cc_multi typeclass instance where ' +
    -      'pragma promise external trace atomic or_else require_complete_switch ' +
    -      'require_det require_semidet require_multi require_nondet ' +
    -      'require_cc_multi require_cc_nondet require_erroneous require_failure',
    -    meta:
    -      // pragma
    -      'inline no_inline type_spec source_file fact_table obsolete memo ' +
    -      'loop_check minimal_model terminates does_not_terminate ' +
    -      'check_termination promise_equivalent_clauses ' +
    -      // preprocessor
    -      'foreign_proc foreign_decl foreign_code foreign_type ' +
    -      'foreign_import_module foreign_export_enum foreign_export ' +
    -      'foreign_enum may_call_mercury will_not_call_mercury thread_safe ' +
    -      'not_thread_safe maybe_thread_safe promise_pure promise_semipure ' +
    -      'tabled_for_io local untrailed trailed attach_to_io_state ' +
    -      'can_pass_as_mercury_type stable will_not_throw_exception ' +
    -      'may_modify_trail will_not_modify_trail may_duplicate ' +
    -      'may_not_duplicate affects_liveness does_not_affect_liveness ' +
    -      'doesnt_affect_liveness no_sharing unknown_sharing sharing',
    -    built_in:
    -      'some all not if then else true fail false try catch catch_any ' +
    -      'semidet_true semidet_false semidet_fail impure_true impure semipure'
    -  };
    -
    -  const COMMENT = hljs.COMMENT('%', '$');
    -
    -  const NUMCODE = {
    -    className: 'number',
    -    begin: "0'.\\|0[box][0-9a-fA-F]*"
    -  };
    -
    -  const ATOM = hljs.inherit(hljs.APOS_STRING_MODE, {
    -    relevance: 0
    -  });
    -  const STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, {
    -    relevance: 0
    -  });
    -  const STRING_FMT = {
    -    className: 'subst',
    -    begin: '\\\\[abfnrtv]\\|\\\\x[0-9a-fA-F]*\\\\\\|%[-+# *.0-9]*[dioxXucsfeEgGp]',
    -    relevance: 0
    -  };
    -  STRING.contains = STRING.contains.slice(); // we need our own copy of contains
    -  STRING.contains.push(STRING_FMT);
    -
    -  const IMPLICATION = {
    -    className: 'built_in',
    -    variants: [
    -      {
    -        begin: '<=>'
    -      },
    -      {
    -        begin: '<=',
    -        relevance: 0
    -      },
    -      {
    -        begin: '=>',
    -        relevance: 0
    -      },
    -      {
    -        begin: '/\\\\'
    -      },
    -      {
    -        begin: '\\\\/'
    -      }
    -    ]
    -  };
    -
    -  const HEAD_BODY_CONJUNCTION = {
    -    className: 'built_in',
    -    variants: [
    -      {
    -        begin: ':-\\|-->'
    -      },
    -      {
    -        begin: '=',
    -        relevance: 0
    -      }
    -    ]
    -  };
    -
    -  return {
    -    name: 'Mercury',
    -    aliases: [
    -      'm',
    -      'moo'
    -    ],
    -    keywords: KEYWORDS,
    -    contains: [
    -      IMPLICATION,
    -      HEAD_BODY_CONJUNCTION,
    -      COMMENT,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      NUMCODE,
    -      hljs.NUMBER_MODE,
    -      ATOM,
    -      STRING,
    -      { // relevance booster
    -        begin: /:-/
    -      },
    -      { // relevance booster
    -        begin: /\.$/
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = mercury;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/mipsasm.js b/claude-code-source/node_modules/highlight.js/lib/languages/mipsasm.js
    deleted file mode 100644
    index 9f14ddef..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/mipsasm.js
    +++ /dev/null
    @@ -1,109 +0,0 @@
    -/*
    -Language: MIPS Assembly
    -Author: Nebuleon Fumika 
    -Description: MIPS Assembly (up to MIPS32R2)
    -Website: https://en.wikipedia.org/wiki/MIPS_architecture
    -Category: assembler
    -*/
    -
    -function mipsasm(hljs) {
    -  // local labels: %?[FB]?[AT]?\d{1,2}\w+
    -  return {
    -    name: 'MIPS Assembly',
    -    case_insensitive: true,
    -    aliases: [ 'mips' ],
    -    keywords: {
    -      $pattern: '\\.?' + hljs.IDENT_RE,
    -      meta:
    -        // GNU preprocs
    -        '.2byte .4byte .align .ascii .asciz .balign .byte .code .data .else .end .endif .endm .endr .equ .err .exitm .extern .global .hword .if .ifdef .ifndef .include .irp .long .macro .rept .req .section .set .skip .space .text .word .ltorg ',
    -      built_in:
    -        '$0 $1 $2 $3 $4 $5 $6 $7 $8 $9 $10 $11 $12 $13 $14 $15 ' + // integer registers
    -        '$16 $17 $18 $19 $20 $21 $22 $23 $24 $25 $26 $27 $28 $29 $30 $31 ' + // integer registers
    -        'zero at v0 v1 a0 a1 a2 a3 a4 a5 a6 a7 ' + // integer register aliases
    -        't0 t1 t2 t3 t4 t5 t6 t7 t8 t9 s0 s1 s2 s3 s4 s5 s6 s7 s8 ' + // integer register aliases
    -        'k0 k1 gp sp fp ra ' + // integer register aliases
    -        '$f0 $f1 $f2 $f2 $f4 $f5 $f6 $f7 $f8 $f9 $f10 $f11 $f12 $f13 $f14 $f15 ' + // floating-point registers
    -        '$f16 $f17 $f18 $f19 $f20 $f21 $f22 $f23 $f24 $f25 $f26 $f27 $f28 $f29 $f30 $f31 ' + // floating-point registers
    -        'Context Random EntryLo0 EntryLo1 Context PageMask Wired EntryHi ' + // Coprocessor 0 registers
    -        'HWREna BadVAddr Count Compare SR IntCtl SRSCtl SRSMap Cause EPC PRId ' + // Coprocessor 0 registers
    -        'EBase Config Config1 Config2 Config3 LLAddr Debug DEPC DESAVE CacheErr ' + // Coprocessor 0 registers
    -        'ECC ErrorEPC TagLo DataLo TagHi DataHi WatchLo WatchHi PerfCtl PerfCnt ' // Coprocessor 0 registers
    -    },
    -    contains: [
    -      {
    -        className: 'keyword',
    -        begin: '\\b(' + // mnemonics
    -            // 32-bit integer instructions
    -            'addi?u?|andi?|b(al)?|beql?|bgez(al)?l?|bgtzl?|blezl?|bltz(al)?l?|' +
    -            'bnel?|cl[oz]|divu?|ext|ins|j(al)?|jalr(\\.hb)?|jr(\\.hb)?|lbu?|lhu?|' +
    -            'll|lui|lw[lr]?|maddu?|mfhi|mflo|movn|movz|move|msubu?|mthi|mtlo|mul|' +
    -            'multu?|nop|nor|ori?|rotrv?|sb|sc|se[bh]|sh|sllv?|slti?u?|srav?|' +
    -            'srlv?|subu?|sw[lr]?|xori?|wsbh|' +
    -            // floating-point instructions
    -            'abs\\.[sd]|add\\.[sd]|alnv.ps|bc1[ft]l?|' +
    -            'c\\.(s?f|un|u?eq|[ou]lt|[ou]le|ngle?|seq|l[et]|ng[et])\\.[sd]|' +
    -            '(ceil|floor|round|trunc)\\.[lw]\\.[sd]|cfc1|cvt\\.d\\.[lsw]|' +
    -            'cvt\\.l\\.[dsw]|cvt\\.ps\\.s|cvt\\.s\\.[dlw]|cvt\\.s\\.p[lu]|cvt\\.w\\.[dls]|' +
    -            'div\\.[ds]|ldx?c1|luxc1|lwx?c1|madd\\.[sd]|mfc1|mov[fntz]?\\.[ds]|' +
    -            'msub\\.[sd]|mth?c1|mul\\.[ds]|neg\\.[ds]|nmadd\\.[ds]|nmsub\\.[ds]|' +
    -            'p[lu][lu]\\.ps|recip\\.fmt|r?sqrt\\.[ds]|sdx?c1|sub\\.[ds]|suxc1|' +
    -            'swx?c1|' +
    -            // system control instructions
    -            'break|cache|d?eret|[de]i|ehb|mfc0|mtc0|pause|prefx?|rdhwr|' +
    -            'rdpgpr|sdbbp|ssnop|synci?|syscall|teqi?|tgei?u?|tlb(p|r|w[ir])|' +
    -            'tlti?u?|tnei?|wait|wrpgpr' +
    -        ')',
    -        end: '\\s'
    -      },
    -      // lines ending with ; or # aren't really comments, probably auto-detect fail
    -      hljs.COMMENT('[;#](?!\\s*$)', '$'),
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      {
    -        className: 'string',
    -        begin: '\'',
    -        end: '[^\\\\]\'',
    -        relevance: 0
    -      },
    -      {
    -        className: 'title',
    -        begin: '\\|',
    -        end: '\\|',
    -        illegal: '\\n',
    -        relevance: 0
    -      },
    -      {
    -        className: 'number',
    -        variants: [
    -          { // hex
    -            begin: '0x[0-9a-f]+'
    -          },
    -          { // bare number
    -            begin: '\\b-?\\d+'
    -          }
    -        ],
    -        relevance: 0
    -      },
    -      {
    -        className: 'symbol',
    -        variants: [
    -          { // GNU MIPS syntax
    -            begin: '^\\s*[a-z_\\.\\$][a-z0-9_\\.\\$]+:'
    -          },
    -          { // numbered local labels
    -            begin: '^\\s*[0-9]+:'
    -          },
    -          { // number local label reference (backwards, forwards)
    -            begin: '[0-9]+[bf]'
    -          }
    -        ],
    -        relevance: 0
    -      }
    -    ],
    -    // forward slashes are not allowed
    -    illegal: /\//
    -  };
    -}
    -
    -module.exports = mipsasm;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/mizar.js b/claude-code-source/node_modules/highlight.js/lib/languages/mizar.js
    deleted file mode 100644
    index ed02c0df..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/mizar.js
    +++ /dev/null
    @@ -1,29 +0,0 @@
    -/*
    -Language: Mizar
    -Description: The Mizar Language is a formal language derived from the mathematical vernacular.
    -Author: Kelley van Evert 
    -Website: http://mizar.org/language/
    -Category: scientific
    -*/
    -
    -function mizar(hljs) {
    -  return {
    -    name: 'Mizar',
    -    keywords:
    -      'environ vocabularies notations constructors definitions ' +
    -      'registrations theorems schemes requirements begin end definition ' +
    -      'registration cluster existence pred func defpred deffunc theorem ' +
    -      'proof let take assume then thus hence ex for st holds consider ' +
    -      'reconsider such that and in provided of as from be being by means ' +
    -      'equals implies iff redefine define now not or attr is mode ' +
    -      'suppose per cases set thesis contradiction scheme reserve struct ' +
    -      'correctness compatibility coherence symmetry assymetry ' +
    -      'reflexivity irreflexivity connectedness uniqueness commutativity ' +
    -      'idempotence involutiveness projectivity',
    -    contains: [
    -      hljs.COMMENT('::', '$')
    -    ]
    -  };
    -}
    -
    -module.exports = mizar;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/mojolicious.js b/claude-code-source/node_modules/highlight.js/lib/languages/mojolicious.js
    deleted file mode 100644
    index 890b16ba..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/mojolicious.js
    +++ /dev/null
    @@ -1,36 +0,0 @@
    -/*
    -Language: Mojolicious
    -Requires: xml.js, perl.js
    -Author: Dotan Dimet 
    -Description: Mojolicious .ep (Embedded Perl) templates
    -Website: https://mojolicious.org
    -Category: template
    -*/
    -function mojolicious(hljs) {
    -  return {
    -    name: 'Mojolicious',
    -    subLanguage: 'xml',
    -    contains: [
    -      {
    -        className: 'meta',
    -        begin: '^__(END|DATA)__$'
    -      },
    -      // mojolicious line
    -      {
    -        begin: "^\\s*%{1,2}={0,2}",
    -        end: '$',
    -        subLanguage: 'perl'
    -      },
    -      // mojolicious block
    -      {
    -        begin: "<%{1,2}={0,2}",
    -        end: "={0,1}%>",
    -        subLanguage: 'perl',
    -        excludeBegin: true,
    -        excludeEnd: true
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = mojolicious;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/monkey.js b/claude-code-source/node_modules/highlight.js/lib/languages/monkey.js
    deleted file mode 100644
    index 2d99a153..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/monkey.js
    +++ /dev/null
    @@ -1,89 +0,0 @@
    -/*
    -Language: Monkey
    -Description: Monkey2 is an easy to use, cross platform, games oriented programming language from Blitz Research.
    -Author: Arthur Bikmullin 
    -Website: https://blitzresearch.itch.io/monkey2
    -*/
    -
    -function monkey(hljs) {
    -  const NUMBER = {
    -    className: 'number',
    -    relevance: 0,
    -    variants: [
    -      {
    -        begin: '[$][a-fA-F0-9]+'
    -      },
    -      hljs.NUMBER_MODE
    -    ]
    -  };
    -
    -  return {
    -    name: 'Monkey',
    -    case_insensitive: true,
    -    keywords: {
    -      keyword: 'public private property continue exit extern new try catch ' +
    -        'eachin not abstract final select case default const local global field ' +
    -        'end if then else elseif endif while wend repeat until forever for ' +
    -        'to step next return module inline throw import',
    -
    -      built_in: 'DebugLog DebugStop Error Print ACos ACosr ASin ASinr ATan ATan2 ATan2r ATanr Abs Abs Ceil ' +
    -        'Clamp Clamp Cos Cosr Exp Floor Log Max Max Min Min Pow Sgn Sgn Sin Sinr Sqrt Tan Tanr Seed PI HALFPI TWOPI',
    -
    -      literal: 'true false null and or shl shr mod'
    -    },
    -    illegal: /\/\*/,
    -    contains: [
    -      hljs.COMMENT('#rem', '#end'),
    -      hljs.COMMENT(
    -        "'",
    -        '$',
    -        {
    -          relevance: 0
    -        }
    -      ),
    -      {
    -        className: 'function',
    -        beginKeywords: 'function method',
    -        end: '[(=:]|$',
    -        illegal: /\n/,
    -        contains: [ hljs.UNDERSCORE_TITLE_MODE ]
    -      },
    -      {
    -        className: 'class',
    -        beginKeywords: 'class interface',
    -        end: '$',
    -        contains: [
    -          {
    -            beginKeywords: 'extends implements'
    -          },
    -          hljs.UNDERSCORE_TITLE_MODE
    -        ]
    -      },
    -      {
    -        className: 'built_in',
    -        begin: '\\b(self|super)\\b'
    -      },
    -      {
    -        className: 'meta',
    -        begin: '\\s*#',
    -        end: '$',
    -        keywords: {
    -          'meta-keyword': 'if else elseif endif end then'
    -        }
    -      },
    -      {
    -        className: 'meta',
    -        begin: '^\\s*strict\\b'
    -      },
    -      {
    -        beginKeywords: 'alias',
    -        end: '=',
    -        contains: [ hljs.UNDERSCORE_TITLE_MODE ]
    -      },
    -      hljs.QUOTE_STRING_MODE,
    -      NUMBER
    -    ]
    -  };
    -}
    -
    -module.exports = monkey;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/moonscript.js b/claude-code-source/node_modules/highlight.js/lib/languages/moonscript.js
    deleted file mode 100644
    index fe24cd9f..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/moonscript.js
    +++ /dev/null
    @@ -1,147 +0,0 @@
    -/*
    -Language: MoonScript
    -Author: Billy Quith 
    -Description: MoonScript is a programming language that transcompiles to Lua.
    -Origin: coffeescript.js
    -Website: http://moonscript.org/
    -Category: scripting
    -*/
    -
    -function moonscript(hljs) {
    -  const KEYWORDS = {
    -    keyword:
    -      // Moonscript keywords
    -      'if then not for in while do return else elseif break continue switch and or ' +
    -      'unless when class extends super local import export from using',
    -    literal:
    -      'true false nil',
    -    built_in:
    -      '_G _VERSION assert collectgarbage dofile error getfenv getmetatable ipairs load ' +
    -      'loadfile loadstring module next pairs pcall print rawequal rawget rawset require ' +
    -      'select setfenv setmetatable tonumber tostring type unpack xpcall coroutine debug ' +
    -      'io math os package string table'
    -  };
    -  const JS_IDENT_RE = '[A-Za-z$_][0-9A-Za-z$_]*';
    -  const SUBST = {
    -    className: 'subst',
    -    begin: /#\{/,
    -    end: /\}/,
    -    keywords: KEYWORDS
    -  };
    -  const EXPRESSIONS = [
    -    hljs.inherit(hljs.C_NUMBER_MODE,
    -      {
    -        starts: {
    -          end: '(\\s*/)?',
    -          relevance: 0
    -        }
    -      }), // a number tries to eat the following slash to prevent treating it as a regexp
    -    {
    -      className: 'string',
    -      variants: [
    -        {
    -          begin: /'/,
    -          end: /'/,
    -          contains: [ hljs.BACKSLASH_ESCAPE ]
    -        },
    -        {
    -          begin: /"/,
    -          end: /"/,
    -          contains: [
    -            hljs.BACKSLASH_ESCAPE,
    -            SUBST
    -          ]
    -        }
    -      ]
    -    },
    -    {
    -      className: 'built_in',
    -      begin: '@__' + hljs.IDENT_RE
    -    },
    -    {
    -      begin: '@' + hljs.IDENT_RE // relevance booster on par with CoffeeScript
    -    },
    -    {
    -      begin: hljs.IDENT_RE + '\\\\' + hljs.IDENT_RE // inst\method
    -    }
    -  ];
    -  SUBST.contains = EXPRESSIONS;
    -
    -  const TITLE = hljs.inherit(hljs.TITLE_MODE, {
    -    begin: JS_IDENT_RE
    -  });
    -  const POSSIBLE_PARAMS_RE = '(\\(.*\\)\\s*)?\\B[-=]>';
    -  const PARAMS = {
    -    className: 'params',
    -    begin: '\\([^\\(]',
    -    returnBegin: true,
    -    /* We need another contained nameless mode to not have every nested
    -    pair of parens to be called "params" */
    -    contains: [
    -      {
    -        begin: /\(/,
    -        end: /\)/,
    -        keywords: KEYWORDS,
    -        contains: [ 'self' ].concat(EXPRESSIONS)
    -      }
    -    ]
    -  };
    -
    -  return {
    -    name: 'MoonScript',
    -    aliases: [ 'moon' ],
    -    keywords: KEYWORDS,
    -    illegal: /\/\*/,
    -    contains: EXPRESSIONS.concat([
    -      hljs.COMMENT('--', '$'),
    -      {
    -        className: 'function', // function: -> =>
    -        begin: '^\\s*' + JS_IDENT_RE + '\\s*=\\s*' + POSSIBLE_PARAMS_RE,
    -        end: '[-=]>',
    -        returnBegin: true,
    -        contains: [
    -          TITLE,
    -          PARAMS
    -        ]
    -      },
    -      {
    -        begin: /[\(,:=]\s*/, // anonymous function start
    -        relevance: 0,
    -        contains: [
    -          {
    -            className: 'function',
    -            begin: POSSIBLE_PARAMS_RE,
    -            end: '[-=]>',
    -            returnBegin: true,
    -            contains: [ PARAMS ]
    -          }
    -        ]
    -      },
    -      {
    -        className: 'class',
    -        beginKeywords: 'class',
    -        end: '$',
    -        illegal: /[:="\[\]]/,
    -        contains: [
    -          {
    -            beginKeywords: 'extends',
    -            endsWithParent: true,
    -            illegal: /[:="\[\]]/,
    -            contains: [ TITLE ]
    -          },
    -          TITLE
    -        ]
    -      },
    -      {
    -        className: 'name', // table
    -        begin: JS_IDENT_RE + ':',
    -        end: ':',
    -        returnBegin: true,
    -        returnEnd: true,
    -        relevance: 0
    -      }
    -    ])
    -  };
    -}
    -
    -module.exports = moonscript;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/n1ql.js b/claude-code-source/node_modules/highlight.js/lib/languages/n1ql.js
    deleted file mode 100644
    index bef9523c..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/n1ql.js
    +++ /dev/null
    @@ -1,77 +0,0 @@
    -/*
    - Language: N1QL
    - Author: Andres Täht 
    - Contributors: Rene Saarsoo 
    - Description: Couchbase query language
    - Website: https://www.couchbase.com/products/n1ql
    - */
    -
    -function n1ql(hljs) {
    -  return {
    -    name: 'N1QL',
    -    case_insensitive: true,
    -    contains: [
    -      {
    -        beginKeywords:
    -          'build create index delete drop explain infer|10 insert merge prepare select update upsert|10',
    -        end: /;/, endsWithParent: true,
    -        keywords: {
    -          // Taken from http://developer.couchbase.com/documentation/server/current/n1ql/n1ql-language-reference/reservedwords.html
    -          keyword:
    -            'all alter analyze and any array as asc begin between binary boolean break bucket build by call ' +
    -            'case cast cluster collate collection commit connect continue correlate cover create database ' +
    -            'dataset datastore declare decrement delete derived desc describe distinct do drop each element ' +
    -            'else end every except exclude execute exists explain fetch first flatten for force from ' +
    -            'function grant group gsi having if ignore ilike in include increment index infer inline inner ' +
    -            'insert intersect into is join key keys keyspace known last left let letting like limit lsm map ' +
    -            'mapping matched materialized merge minus namespace nest not number object offset on ' +
    -            'option or order outer over parse partition password path pool prepare primary private privilege ' +
    -            'procedure public raw realm reduce rename return returning revoke right role rollback satisfies ' +
    -            'schema select self semi set show some start statistics string system then to transaction trigger ' +
    -            'truncate under union unique unknown unnest unset update upsert use user using validate value ' +
    -            'valued values via view when where while with within work xor',
    -          // Taken from http://developer.couchbase.com/documentation/server/4.5/n1ql/n1ql-language-reference/literals.html
    -          literal:
    -            'true false null missing|5',
    -          // Taken from http://developer.couchbase.com/documentation/server/4.5/n1ql/n1ql-language-reference/functions.html
    -          built_in:
    -            'array_agg array_append array_concat array_contains array_count array_distinct array_ifnull array_length ' +
    -            'array_max array_min array_position array_prepend array_put array_range array_remove array_repeat array_replace ' +
    -            'array_reverse array_sort array_sum avg count max min sum greatest least ifmissing ifmissingornull ifnull ' +
    -            'missingif nullif ifinf ifnan ifnanorinf naninf neginfif posinfif clock_millis clock_str date_add_millis ' +
    -            'date_add_str date_diff_millis date_diff_str date_part_millis date_part_str date_trunc_millis date_trunc_str ' +
    -            'duration_to_str millis str_to_millis millis_to_str millis_to_utc millis_to_zone_name now_millis now_str ' +
    -            'str_to_duration str_to_utc str_to_zone_name decode_json encode_json encoded_size poly_length base64 base64_encode ' +
    -            'base64_decode meta uuid abs acos asin atan atan2 ceil cos degrees e exp ln log floor pi power radians random ' +
    -            'round sign sin sqrt tan trunc object_length object_names object_pairs object_inner_pairs object_values ' +
    -            'object_inner_values object_add object_put object_remove object_unwrap regexp_contains regexp_like regexp_position ' +
    -            'regexp_replace contains initcap length lower ltrim position repeat replace rtrim split substr title trim upper ' +
    -            'isarray isatom isboolean isnumber isobject isstring type toarray toatom toboolean tonumber toobject tostring'
    -        },
    -        contains: [
    -          {
    -            className: 'string',
    -            begin: '\'', end: '\'',
    -            contains: [hljs.BACKSLASH_ESCAPE]
    -          },
    -          {
    -            className: 'string',
    -            begin: '"', end: '"',
    -            contains: [hljs.BACKSLASH_ESCAPE]
    -          },
    -          {
    -            className: 'symbol',
    -            begin: '`', end: '`',
    -            contains: [hljs.BACKSLASH_ESCAPE],
    -            relevance: 2
    -          },
    -          hljs.C_NUMBER_MODE,
    -          hljs.C_BLOCK_COMMENT_MODE
    -        ]
    -      },
    -      hljs.C_BLOCK_COMMENT_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = n1ql;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/nginx.js b/claude-code-source/node_modules/highlight.js/lib/languages/nginx.js
    deleted file mode 100644
    index 186e2f41..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/nginx.js
    +++ /dev/null
    @@ -1,140 +0,0 @@
    -/*
    -Language: Nginx config
    -Author: Peter Leonov 
    -Contributors: Ivan Sagalaev 
    -Category: common, config
    -Website: https://www.nginx.com
    -*/
    -
    -function nginx(hljs) {
    -  const VAR = {
    -    className: 'variable',
    -    variants: [
    -      {
    -        begin: /\$\d+/
    -      },
    -      {
    -        begin: /\$\{/,
    -        end: /\}/
    -      },
    -      {
    -        begin: /[$@]/ + hljs.UNDERSCORE_IDENT_RE
    -      }
    -    ]
    -  };
    -  const DEFAULT = {
    -    endsWithParent: true,
    -    keywords: {
    -      $pattern: '[a-z/_]+',
    -      literal:
    -        'on off yes no true false none blocked debug info notice warn error crit ' +
    -        'select break last permanent redirect kqueue rtsig epoll poll /dev/poll'
    -    },
    -    relevance: 0,
    -    illegal: '=>',
    -    contains: [
    -      hljs.HASH_COMMENT_MODE,
    -      {
    -        className: 'string',
    -        contains: [
    -          hljs.BACKSLASH_ESCAPE,
    -          VAR
    -        ],
    -        variants: [
    -          {
    -            begin: /"/,
    -            end: /"/
    -          },
    -          {
    -            begin: /'/,
    -            end: /'/
    -          }
    -        ]
    -      },
    -      // this swallows entire URLs to avoid detecting numbers within
    -      {
    -        begin: '([a-z]+):/',
    -        end: '\\s',
    -        endsWithParent: true,
    -        excludeEnd: true,
    -        contains: [ VAR ]
    -      },
    -      {
    -        className: 'regexp',
    -        contains: [
    -          hljs.BACKSLASH_ESCAPE,
    -          VAR
    -        ],
    -        variants: [
    -          {
    -            begin: "\\s\\^",
    -            end: "\\s|\\{|;",
    -            returnEnd: true
    -          },
    -          // regexp locations (~, ~*)
    -          {
    -            begin: "~\\*?\\s+",
    -            end: "\\s|\\{|;",
    -            returnEnd: true
    -          },
    -          // *.example.com
    -          {
    -            begin: "\\*(\\.[a-z\\-]+)+"
    -          },
    -          // sub.example.*
    -          {
    -            begin: "([a-z\\-]+\\.)+\\*"
    -          }
    -        ]
    -      },
    -      // IP
    -      {
    -        className: 'number',
    -        begin: '\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}(:\\d{1,5})?\\b'
    -      },
    -      // units
    -      {
    -        className: 'number',
    -        begin: '\\b\\d+[kKmMgGdshdwy]*\\b',
    -        relevance: 0
    -      },
    -      VAR
    -    ]
    -  };
    -
    -  return {
    -    name: 'Nginx config',
    -    aliases: [ 'nginxconf' ],
    -    contains: [
    -      hljs.HASH_COMMENT_MODE,
    -      {
    -        begin: hljs.UNDERSCORE_IDENT_RE + '\\s+\\{',
    -        returnBegin: true,
    -        end: /\{/,
    -        contains: [
    -          {
    -            className: 'section',
    -            begin: hljs.UNDERSCORE_IDENT_RE
    -          }
    -        ],
    -        relevance: 0
    -      },
    -      {
    -        begin: hljs.UNDERSCORE_IDENT_RE + '\\s',
    -        end: ';|\\{',
    -        returnBegin: true,
    -        contains: [
    -          {
    -            className: 'attribute',
    -            begin: hljs.UNDERSCORE_IDENT_RE,
    -            starts: DEFAULT
    -          }
    -        ],
    -        relevance: 0
    -      }
    -    ],
    -    illegal: '[^\\s\\}]'
    -  };
    -}
    -
    -module.exports = nginx;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/nim.js b/claude-code-source/node_modules/highlight.js/lib/languages/nim.js
    deleted file mode 100644
    index b77dc848..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/nim.js
    +++ /dev/null
    @@ -1,79 +0,0 @@
    -/*
    -Language: Nim
    -Description: Nim is a statically typed compiled systems programming language.
    -Website: https://nim-lang.org
    -Category: system
    -*/
    -
    -function nim(hljs) {
    -  return {
    -    name: 'Nim',
    -    keywords: {
    -      keyword:
    -        'addr and as asm bind block break case cast const continue converter ' +
    -        'discard distinct div do elif else end enum except export finally ' +
    -        'for from func generic if import in include interface is isnot iterator ' +
    -        'let macro method mixin mod nil not notin object of or out proc ptr ' +
    -        'raise ref return shl shr static template try tuple type using var ' +
    -        'when while with without xor yield',
    -      literal:
    -        'shared guarded stdin stdout stderr result true false',
    -      built_in:
    -        'int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 float ' +
    -        'float32 float64 bool char string cstring pointer expr stmt void ' +
    -        'auto any range array openarray varargs seq set clong culong cchar ' +
    -        'cschar cshort cint csize clonglong cfloat cdouble clongdouble ' +
    -        'cuchar cushort cuint culonglong cstringarray semistatic'
    -    },
    -    contains: [
    -      {
    -        className: 'meta', // Actually pragma
    -        begin: /\{\./,
    -        end: /\.\}/,
    -        relevance: 10
    -      },
    -      {
    -        className: 'string',
    -        begin: /[a-zA-Z]\w*"/,
    -        end: /"/,
    -        contains: [
    -          {
    -            begin: /""/
    -          }
    -        ]
    -      },
    -      {
    -        className: 'string',
    -        begin: /([a-zA-Z]\w*)?"""/,
    -        end: /"""/
    -      },
    -      hljs.QUOTE_STRING_MODE,
    -      {
    -        className: 'type',
    -        begin: /\b[A-Z]\w+\b/,
    -        relevance: 0
    -      },
    -      {
    -        className: 'number',
    -        relevance: 0,
    -        variants: [
    -          {
    -            begin: /\b(0[xX][0-9a-fA-F][_0-9a-fA-F]*)('?[iIuU](8|16|32|64))?/
    -          },
    -          {
    -            begin: /\b(0o[0-7][_0-7]*)('?[iIuUfF](8|16|32|64))?/
    -          },
    -          {
    -            begin: /\b(0(b|B)[01][_01]*)('?[iIuUfF](8|16|32|64))?/
    -          },
    -          {
    -            begin: /\b(\d[_\d]*)('?[iIuUfF](8|16|32|64))?/
    -          }
    -        ]
    -      },
    -      hljs.HASH_COMMENT_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = nim;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/nix.js b/claude-code-source/node_modules/highlight.js/lib/languages/nix.js
    deleted file mode 100644
    index 15b945e3..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/nix.js
    +++ /dev/null
    @@ -1,65 +0,0 @@
    -/*
    -Language: Nix
    -Author: Domen Kožar 
    -Description: Nix functional language
    -Website: http://nixos.org/nix
    -*/
    -
    -function nix(hljs) {
    -  const NIX_KEYWORDS = {
    -    keyword:
    -      'rec with let in inherit assert if else then',
    -    literal:
    -      'true false or and null',
    -    built_in:
    -      'import abort baseNameOf dirOf isNull builtins map removeAttrs throw ' +
    -      'toString derivation'
    -  };
    -  const ANTIQUOTE = {
    -    className: 'subst',
    -    begin: /\$\{/,
    -    end: /\}/,
    -    keywords: NIX_KEYWORDS
    -  };
    -  const ATTRS = {
    -    begin: /[a-zA-Z0-9-_]+(\s*=)/,
    -    returnBegin: true,
    -    relevance: 0,
    -    contains: [
    -      {
    -        className: 'attr',
    -        begin: /\S+/
    -      }
    -    ]
    -  };
    -  const STRING = {
    -    className: 'string',
    -    contains: [ ANTIQUOTE ],
    -    variants: [
    -      {
    -        begin: "''",
    -        end: "''"
    -      },
    -      {
    -        begin: '"',
    -        end: '"'
    -      }
    -    ]
    -  };
    -  const EXPRESSIONS = [
    -    hljs.NUMBER_MODE,
    -    hljs.HASH_COMMENT_MODE,
    -    hljs.C_BLOCK_COMMENT_MODE,
    -    STRING,
    -    ATTRS
    -  ];
    -  ANTIQUOTE.contains = EXPRESSIONS;
    -  return {
    -    name: 'Nix',
    -    aliases: [ "nixos" ],
    -    keywords: NIX_KEYWORDS,
    -    contains: EXPRESSIONS
    -  };
    -}
    -
    -module.exports = nix;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/node-repl.js b/claude-code-source/node_modules/highlight.js/lib/languages/node-repl.js
    deleted file mode 100644
    index 15e3b66d..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/node-repl.js
    +++ /dev/null
    @@ -1,37 +0,0 @@
    -/*
    -Language: Node REPL
    -Requires: javascript.js
    -Author: Marat Nagayev 
    -Category: scripting
    -*/
    -
    -/** @type LanguageFn */
    -function nodeRepl(hljs) {
    -  return {
    -    name: 'Node REPL',
    -    contains: [
    -      {
    -        className: 'meta',
    -        starts: {
    -          // a space separates the REPL prefix from the actual code
    -          // this is purely for cleaner HTML output
    -          end: / |$/,
    -          starts: {
    -            end: '$',
    -            subLanguage: 'javascript'
    -          }
    -        },
    -        variants: [
    -          {
    -            begin: /^>(?=[ ]|$)/
    -          },
    -          {
    -            begin: /^\.\.\.(?=[ ]|$)/
    -          }
    -        ]
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = nodeRepl;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/nsis.js b/claude-code-source/node_modules/highlight.js/lib/languages/nsis.js
    deleted file mode 100644
    index da621ba2..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/nsis.js
    +++ /dev/null
    @@ -1,119 +0,0 @@
    -/*
    -Language: NSIS
    -Description: Nullsoft Scriptable Install System
    -Author: Jan T. Sott 
    -Website: https://nsis.sourceforge.io/Main_Page
    -*/
    -
    -function nsis(hljs) {
    -  const CONSTANTS = {
    -    className: 'variable',
    -    begin: /\$(ADMINTOOLS|APPDATA|CDBURN_AREA|CMDLINE|COMMONFILES32|COMMONFILES64|COMMONFILES|COOKIES|DESKTOP|DOCUMENTS|EXEDIR|EXEFILE|EXEPATH|FAVORITES|FONTS|HISTORY|HWNDPARENT|INSTDIR|INTERNET_CACHE|LANGUAGE|LOCALAPPDATA|MUSIC|NETHOOD|OUTDIR|PICTURES|PLUGINSDIR|PRINTHOOD|PROFILE|PROGRAMFILES32|PROGRAMFILES64|PROGRAMFILES|QUICKLAUNCH|RECENT|RESOURCES_LOCALIZED|RESOURCES|SENDTO|SMPROGRAMS|SMSTARTUP|STARTMENU|SYSDIR|TEMP|TEMPLATES|VIDEOS|WINDIR)/
    -  };
    -
    -  const DEFINES = {
    -    // ${defines}
    -    className: 'variable',
    -    begin: /\$+\{[\w.:-]+\}/
    -  };
    -
    -  const VARIABLES = {
    -    // $variables
    -    className: 'variable',
    -    begin: /\$+\w+/,
    -    illegal: /\(\)\{\}/
    -  };
    -
    -  const LANGUAGES = {
    -    // $(language_strings)
    -    className: 'variable',
    -    begin: /\$+\([\w^.:-]+\)/
    -  };
    -
    -  const PARAMETERS = {
    -    // command parameters
    -    className: 'params',
    -    begin: '(ARCHIVE|FILE_ATTRIBUTE_ARCHIVE|FILE_ATTRIBUTE_NORMAL|FILE_ATTRIBUTE_OFFLINE|FILE_ATTRIBUTE_READONLY|FILE_ATTRIBUTE_SYSTEM|FILE_ATTRIBUTE_TEMPORARY|HKCR|HKCU|HKDD|HKEY_CLASSES_ROOT|HKEY_CURRENT_CONFIG|HKEY_CURRENT_USER|HKEY_DYN_DATA|HKEY_LOCAL_MACHINE|HKEY_PERFORMANCE_DATA|HKEY_USERS|HKLM|HKPD|HKU|IDABORT|IDCANCEL|IDIGNORE|IDNO|IDOK|IDRETRY|IDYES|MB_ABORTRETRYIGNORE|MB_DEFBUTTON1|MB_DEFBUTTON2|MB_DEFBUTTON3|MB_DEFBUTTON4|MB_ICONEXCLAMATION|MB_ICONINFORMATION|MB_ICONQUESTION|MB_ICONSTOP|MB_OK|MB_OKCANCEL|MB_RETRYCANCEL|MB_RIGHT|MB_RTLREADING|MB_SETFOREGROUND|MB_TOPMOST|MB_USERICON|MB_YESNO|NORMAL|OFFLINE|READONLY|SHCTX|SHELL_CONTEXT|SYSTEM|TEMPORARY)'
    -  };
    -
    -  const COMPILER = {
    -    // !compiler_flags
    -    className: 'keyword',
    -    begin: /!(addincludedir|addplugindir|appendfile|cd|define|delfile|echo|else|endif|error|execute|finalize|getdllversion|gettlbversion|if|ifdef|ifmacrodef|ifmacrondef|ifndef|include|insertmacro|macro|macroend|makensis|packhdr|searchparse|searchreplace|system|tempfile|undef|verbose|warning)/
    -  };
    -
    -  const METACHARS = {
    -    // $\n, $\r, $\t, $$
    -    className: 'meta',
    -    begin: /\$(\\[nrt]|\$)/
    -  };
    -
    -  const PLUGINS = {
    -    // plug::ins
    -    className: 'class',
    -    begin: /\w+::\w+/
    -  };
    -
    -  const STRING = {
    -    className: 'string',
    -    variants: [
    -      {
    -        begin: '"',
    -        end: '"'
    -      },
    -      {
    -        begin: '\'',
    -        end: '\''
    -      },
    -      {
    -        begin: '`',
    -        end: '`'
    -      }
    -    ],
    -    illegal: /\n/,
    -    contains: [
    -      METACHARS,
    -      CONSTANTS,
    -      DEFINES,
    -      VARIABLES,
    -      LANGUAGES
    -    ]
    -  };
    -
    -  return {
    -    name: 'NSIS',
    -    case_insensitive: false,
    -    keywords: {
    -      keyword:
    -      'Abort AddBrandingImage AddSize AllowRootDirInstall AllowSkipFiles AutoCloseWindow BGFont BGGradient BrandingText BringToFront Call CallInstDLL Caption ChangeUI CheckBitmap ClearErrors CompletedText ComponentText CopyFiles CRCCheck CreateDirectory CreateFont CreateShortCut Delete DeleteINISec DeleteINIStr DeleteRegKey DeleteRegValue DetailPrint DetailsButtonText DirText DirVar DirVerify EnableWindow EnumRegKey EnumRegValue Exch Exec ExecShell ExecShellWait ExecWait ExpandEnvStrings File FileBufSize FileClose FileErrorText FileOpen FileRead FileReadByte FileReadUTF16LE FileReadWord FileWriteUTF16LE FileSeek FileWrite FileWriteByte FileWriteWord FindClose FindFirst FindNext FindWindow FlushINI GetCurInstType GetCurrentAddress GetDlgItem GetDLLVersion GetDLLVersionLocal GetErrorLevel GetFileTime GetFileTimeLocal GetFullPathName GetFunctionAddress GetInstDirError GetKnownFolderPath GetLabelAddress GetTempFileName Goto HideWindow Icon IfAbort IfErrors IfFileExists IfRebootFlag IfRtlLanguage IfShellVarContextAll IfSilent InitPluginsDir InstallButtonText InstallColors InstallDir InstallDirRegKey InstProgressFlags InstType InstTypeGetText InstTypeSetText Int64Cmp Int64CmpU Int64Fmt IntCmp IntCmpU IntFmt IntOp IntPtrCmp IntPtrCmpU IntPtrOp IsWindow LangString LicenseBkColor LicenseData LicenseForceSelection LicenseLangString LicenseText LoadAndSetImage LoadLanguageFile LockWindow LogSet LogText ManifestDPIAware ManifestLongPathAware ManifestMaxVersionTested ManifestSupportedOS MessageBox MiscButtonText Name Nop OutFile Page PageCallbacks PEAddResource PEDllCharacteristics PERemoveResource PESubsysVer Pop Push Quit ReadEnvStr ReadINIStr ReadRegDWORD ReadRegStr Reboot RegDLL Rename RequestExecutionLevel ReserveFile Return RMDir SearchPath SectionGetFlags SectionGetInstTypes SectionGetSize SectionGetText SectionIn SectionSetFlags SectionSetInstTypes SectionSetSize SectionSetText SendMessage SetAutoClose SetBrandingImage SetCompress SetCompressor SetCompressorDictSize SetCtlColors SetCurInstType SetDatablockOptimize SetDateSave SetDetailsPrint SetDetailsView SetErrorLevel SetErrors SetFileAttributes SetFont SetOutPath SetOverwrite SetRebootFlag SetRegView SetShellVarContext SetSilent ShowInstDetails ShowUninstDetails ShowWindow SilentInstall SilentUnInstall Sleep SpaceTexts StrCmp StrCmpS StrCpy StrLen SubCaption Unicode UninstallButtonText UninstallCaption UninstallIcon UninstallSubCaption UninstallText UninstPage UnRegDLL Var VIAddVersionKey VIFileVersion VIProductVersion WindowIcon WriteINIStr WriteRegBin WriteRegDWORD WriteRegExpandStr WriteRegMultiStr WriteRegNone WriteRegStr WriteUninstaller XPStyle',
    -      literal:
    -      'admin all auto both bottom bzip2 colored components current custom directory false force hide highest ifdiff ifnewer instfiles lastused leave left license listonly lzma nevershow none normal notset off on open print right show silent silentlog smooth textonly top true try un.components un.custom un.directory un.instfiles un.license uninstConfirm user Win10 Win7 Win8 WinVista zlib'
    -    },
    -    contains: [
    -      hljs.HASH_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.COMMENT(
    -        ';',
    -        '$',
    -        {
    -          relevance: 0
    -        }
    -      ),
    -      {
    -        className: 'function',
    -        beginKeywords: 'Function PageEx Section SectionGroup',
    -        end: '$'
    -      },
    -      STRING,
    -      COMPILER,
    -      DEFINES,
    -      VARIABLES,
    -      LANGUAGES,
    -      PARAMETERS,
    -      PLUGINS,
    -      hljs.NUMBER_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = nsis;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/objectivec.js b/claude-code-source/node_modules/highlight.js/lib/languages/objectivec.js
    deleted file mode 100644
    index 18016ef9..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/objectivec.js
    +++ /dev/null
    @@ -1,121 +0,0 @@
    -/*
    -Language: Objective-C
    -Author: Valerii Hiora 
    -Contributors: Angel G. Olloqui , Matt Diephouse , Andrew Farmer , Minh Nguyễn 
    -Website: https://developer.apple.com/documentation/objectivec
    -Category: common
    -*/
    -
    -function objectivec(hljs) {
    -  const API_CLASS = {
    -    className: 'built_in',
    -    begin: '\\b(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)\\w+'
    -  };
    -  const IDENTIFIER_RE = /[a-zA-Z@][a-zA-Z0-9_]*/;
    -  const OBJC_KEYWORDS = {
    -    $pattern: IDENTIFIER_RE,
    -    keyword:
    -      'int float while char export sizeof typedef const struct for union ' +
    -      'unsigned long volatile static bool mutable if do return goto void ' +
    -      'enum else break extern asm case short default double register explicit ' +
    -      'signed typename this switch continue wchar_t inline readonly assign ' +
    -      'readwrite self @synchronized id typeof ' +
    -      'nonatomic super unichar IBOutlet IBAction strong weak copy ' +
    -      'in out inout bycopy byref oneway __strong __weak __block __autoreleasing ' +
    -      '@private @protected @public @try @property @end @throw @catch @finally ' +
    -      '@autoreleasepool @synthesize @dynamic @selector @optional @required ' +
    -      '@encode @package @import @defs @compatibility_alias ' +
    -      '__bridge __bridge_transfer __bridge_retained __bridge_retain ' +
    -      '__covariant __contravariant __kindof ' +
    -      '_Nonnull _Nullable _Null_unspecified ' +
    -      '__FUNCTION__ __PRETTY_FUNCTION__ __attribute__ ' +
    -      'getter setter retain unsafe_unretained ' +
    -      'nonnull nullable null_unspecified null_resettable class instancetype ' +
    -      'NS_DESIGNATED_INITIALIZER NS_UNAVAILABLE NS_REQUIRES_SUPER ' +
    -      'NS_RETURNS_INNER_POINTER NS_INLINE NS_AVAILABLE NS_DEPRECATED ' +
    -      'NS_ENUM NS_OPTIONS NS_SWIFT_UNAVAILABLE ' +
    -      'NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END ' +
    -      'NS_REFINED_FOR_SWIFT NS_SWIFT_NAME NS_SWIFT_NOTHROW ' +
    -      'NS_DURING NS_HANDLER NS_ENDHANDLER NS_VALUERETURN NS_VOIDRETURN',
    -    literal:
    -      'false true FALSE TRUE nil YES NO NULL',
    -    built_in:
    -      'BOOL dispatch_once_t dispatch_queue_t dispatch_sync dispatch_async dispatch_once'
    -  };
    -  const CLASS_KEYWORDS = {
    -    $pattern: IDENTIFIER_RE,
    -    keyword: '@interface @class @protocol @implementation'
    -  };
    -  return {
    -    name: 'Objective-C',
    -    aliases: [
    -      'mm',
    -      'objc',
    -      'obj-c',
    -      'obj-c++',
    -      'objective-c++'
    -    ],
    -    keywords: OBJC_KEYWORDS,
    -    illegal: '/,
    -            end: /$/,
    -            illegal: '\\n'
    -          },
    -          hljs.C_LINE_COMMENT_MODE,
    -          hljs.C_BLOCK_COMMENT_MODE
    -        ]
    -      },
    -      {
    -        className: 'class',
    -        begin: '(' + CLASS_KEYWORDS.keyword.split(' ').join('|') + ')\\b',
    -        end: /(\{|$)/,
    -        excludeEnd: true,
    -        keywords: CLASS_KEYWORDS,
    -        contains: [ hljs.UNDERSCORE_TITLE_MODE ]
    -      },
    -      {
    -        begin: '\\.' + hljs.UNDERSCORE_IDENT_RE,
    -        relevance: 0
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = objectivec;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/ocaml.js b/claude-code-source/node_modules/highlight.js/lib/languages/ocaml.js
    deleted file mode 100644
    index 3e617bde..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/ocaml.js
    +++ /dev/null
    @@ -1,82 +0,0 @@
    -/*
    -Language: OCaml
    -Author: Mehdi Dogguy 
    -Contributors: Nicolas Braud-Santoni , Mickael Delahaye 
    -Description: OCaml language definition.
    -Website: https://ocaml.org
    -Category: functional
    -*/
    -
    -function ocaml(hljs) {
    -  /* missing support for heredoc-like string (OCaml 4.0.2+) */
    -  return {
    -    name: 'OCaml',
    -    aliases: ['ml'],
    -    keywords: {
    -      $pattern: '[a-z_]\\w*!?',
    -      keyword:
    -        'and as assert asr begin class constraint do done downto else end ' +
    -        'exception external for fun function functor if in include ' +
    -        'inherit! inherit initializer land lazy let lor lsl lsr lxor match method!|10 method ' +
    -        'mod module mutable new object of open! open or private rec sig struct ' +
    -        'then to try type val! val virtual when while with ' +
    -        /* camlp4 */
    -        'parser value',
    -      built_in:
    -        /* built-in types */
    -        'array bool bytes char exn|5 float int int32 int64 list lazy_t|5 nativeint|5 string unit ' +
    -        /* (some) types in Pervasives */
    -        'in_channel out_channel ref',
    -      literal:
    -        'true false'
    -    },
    -    illegal: /\/\/|>>/,
    -    contains: [
    -      {
    -        className: 'literal',
    -        begin: '\\[(\\|\\|)?\\]|\\(\\)',
    -        relevance: 0
    -      },
    -      hljs.COMMENT(
    -        '\\(\\*',
    -        '\\*\\)',
    -        {
    -          contains: ['self']
    -        }
    -      ),
    -      { /* type variable */
    -        className: 'symbol',
    -        begin: '\'[A-Za-z_](?!\')[\\w\']*'
    -        /* the grammar is ambiguous on how 'a'b should be interpreted but not the compiler */
    -      },
    -      { /* polymorphic variant */
    -        className: 'type',
    -        begin: '`[A-Z][\\w\']*'
    -      },
    -      { /* module or constructor */
    -        className: 'type',
    -        begin: '\\b[A-Z][\\w\']*',
    -        relevance: 0
    -      },
    -      { /* don't color identifiers, but safely catch all identifiers with '*/
    -        begin: '[a-z_]\\w*\'[\\w\']*', relevance: 0
    -      },
    -      hljs.inherit(hljs.APOS_STRING_MODE, {className: 'string', relevance: 0}),
    -      hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null}),
    -      {
    -        className: 'number',
    -        begin:
    -          '\\b(0[xX][a-fA-F0-9_]+[Lln]?|' +
    -          '0[oO][0-7_]+[Lln]?|' +
    -          '0[bB][01_]+[Lln]?|' +
    -          '[0-9][0-9_]*([Lln]|(\\.[0-9_]*)?([eE][-+]?[0-9_]+)?)?)',
    -        relevance: 0
    -      },
    -      {
    -        begin: /->/ // relevance booster
    -      }
    -    ]
    -  }
    -}
    -
    -module.exports = ocaml;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/openscad.js b/claude-code-source/node_modules/highlight.js/lib/languages/openscad.js
    deleted file mode 100644
    index 54708058..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/openscad.js
    +++ /dev/null
    @@ -1,81 +0,0 @@
    -/*
    -Language: OpenSCAD
    -Author: Dan Panzarella 
    -Description: OpenSCAD is a language for the 3D CAD modeling software of the same name.
    -Website: https://www.openscad.org
    -Category: scientific
    -*/
    -
    -function openscad(hljs) {
    -  const SPECIAL_VARS = {
    -    className: 'keyword',
    -    begin: '\\$(f[asn]|t|vp[rtd]|children)'
    -  };
    -  const LITERALS = {
    -    className: 'literal',
    -    begin: 'false|true|PI|undef'
    -  };
    -  const NUMBERS = {
    -    className: 'number',
    -    begin: '\\b\\d+(\\.\\d+)?(e-?\\d+)?', // adds 1e5, 1e-10
    -    relevance: 0
    -  };
    -  const STRING = hljs.inherit(hljs.QUOTE_STRING_MODE, {
    -    illegal: null
    -  });
    -  const PREPRO = {
    -    className: 'meta',
    -    keywords: {
    -      'meta-keyword': 'include use'
    -    },
    -    begin: 'include|use <',
    -    end: '>'
    -  };
    -  const PARAMS = {
    -    className: 'params',
    -    begin: '\\(',
    -    end: '\\)',
    -    contains: [
    -      'self',
    -      NUMBERS,
    -      STRING,
    -      SPECIAL_VARS,
    -      LITERALS
    -    ]
    -  };
    -  const MODIFIERS = {
    -    begin: '[*!#%]',
    -    relevance: 0
    -  };
    -  const FUNCTIONS = {
    -    className: 'function',
    -    beginKeywords: 'module function',
    -    end: /=|\{/,
    -    contains: [
    -      PARAMS,
    -      hljs.UNDERSCORE_TITLE_MODE
    -    ]
    -  };
    -
    -  return {
    -    name: 'OpenSCAD',
    -    aliases: [ 'scad' ],
    -    keywords: {
    -      keyword: 'function module include use for intersection_for if else \\%',
    -      literal: 'false true PI undef',
    -      built_in: 'circle square polygon text sphere cube cylinder polyhedron translate rotate scale resize mirror multmatrix color offset hull minkowski union difference intersection abs sign sin cos tan acos asin atan atan2 floor round ceil ln log pow sqrt exp rands min max concat lookup str chr search version version_num norm cross parent_module echo import import_dxf dxf_linear_extrude linear_extrude rotate_extrude surface projection render children dxf_cross dxf_dim let assign'
    -    },
    -    contains: [
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      NUMBERS,
    -      PREPRO,
    -      STRING,
    -      SPECIAL_VARS,
    -      MODIFIERS,
    -      FUNCTIONS
    -    ]
    -  };
    -}
    -
    -module.exports = openscad;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/oxygene.js b/claude-code-source/node_modules/highlight.js/lib/languages/oxygene.js
    deleted file mode 100644
    index 4649cf87..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/oxygene.js
    +++ /dev/null
    @@ -1,101 +0,0 @@
    -/*
    -Language: Oxygene
    -Author: Carlo Kok 
    -Description: Oxygene is built on the foundation of Object Pascal, revamped and extended to be a modern language for the twenty-first century.
    -Website: https://www.elementscompiler.com/elements/default.aspx
    -*/
    -
    -function oxygene(hljs) {
    -  const OXYGENE_KEYWORDS = {
    -    $pattern: /\.?\w+/,
    -    keyword:
    -      'abstract add and array as asc aspect assembly async begin break block by case class concat const copy constructor continue ' +
    -      'create default delegate desc distinct div do downto dynamic each else empty end ensure enum equals event except exit extension external false ' +
    -      'final finalize finalizer finally flags for forward from function future global group has if implementation implements implies in index inherited ' +
    -      'inline interface into invariants is iterator join locked locking loop matching method mod module namespace nested new nil not notify nullable of ' +
    -      'old on operator or order out override parallel params partial pinned private procedure property protected public queryable raise read readonly ' +
    -      'record reintroduce remove repeat require result reverse sealed select self sequence set shl shr skip static step soft take then to true try tuple ' +
    -      'type union unit unsafe until uses using var virtual raises volatile where while with write xor yield await mapped deprecated stdcall cdecl pascal ' +
    -      'register safecall overload library platform reference packed strict published autoreleasepool selector strong weak unretained'
    -  };
    -  const CURLY_COMMENT = hljs.COMMENT(
    -    /\{/,
    -    /\}/,
    -    {
    -      relevance: 0
    -    }
    -  );
    -  const PAREN_COMMENT = hljs.COMMENT(
    -    '\\(\\*',
    -    '\\*\\)',
    -    {
    -      relevance: 10
    -    }
    -  );
    -  const STRING = {
    -    className: 'string',
    -    begin: '\'',
    -    end: '\'',
    -    contains: [
    -      {
    -        begin: '\'\''
    -      }
    -    ]
    -  };
    -  const CHAR_STRING = {
    -    className: 'string',
    -    begin: '(#\\d+)+'
    -  };
    -  const FUNCTION = {
    -    className: 'function',
    -    beginKeywords: 'function constructor destructor procedure method',
    -    end: '[:;]',
    -    keywords: 'function constructor|10 destructor|10 procedure|10 method|10',
    -    contains: [
    -      hljs.TITLE_MODE,
    -      {
    -        className: 'params',
    -        begin: '\\(',
    -        end: '\\)',
    -        keywords: OXYGENE_KEYWORDS,
    -        contains: [
    -          STRING,
    -          CHAR_STRING
    -        ]
    -      },
    -      CURLY_COMMENT,
    -      PAREN_COMMENT
    -    ]
    -  };
    -  return {
    -    name: 'Oxygene',
    -    case_insensitive: true,
    -    keywords: OXYGENE_KEYWORDS,
    -    illegal: '("|\\$[G-Zg-z]|\\/\\*||->)',
    -    contains: [
    -      CURLY_COMMENT,
    -      PAREN_COMMENT,
    -      hljs.C_LINE_COMMENT_MODE,
    -      STRING,
    -      CHAR_STRING,
    -      hljs.NUMBER_MODE,
    -      FUNCTION,
    -      {
    -        className: 'class',
    -        begin: '=\\bclass\\b',
    -        end: 'end;',
    -        keywords: OXYGENE_KEYWORDS,
    -        contains: [
    -          STRING,
    -          CHAR_STRING,
    -          CURLY_COMMENT,
    -          PAREN_COMMENT,
    -          hljs.C_LINE_COMMENT_MODE,
    -          FUNCTION
    -        ]
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = oxygene;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/parser3.js b/claude-code-source/node_modules/highlight.js/lib/languages/parser3.js
    deleted file mode 100644
    index 708b02c4..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/parser3.js
    +++ /dev/null
    @@ -1,57 +0,0 @@
    -/*
    -Language: Parser3
    -Requires: xml.js
    -Author: Oleg Volchkov 
    -Website: https://www.parser.ru/en/
    -Category: template
    -*/
    -
    -function parser3(hljs) {
    -  const CURLY_SUBCOMMENT = hljs.COMMENT(
    -    /\{/,
    -    /\}/,
    -    {
    -      contains: [ 'self' ]
    -    }
    -  );
    -  return {
    -    name: 'Parser3',
    -    subLanguage: 'xml',
    -    relevance: 0,
    -    contains: [
    -      hljs.COMMENT('^#', '$'),
    -      hljs.COMMENT(
    -        /\^rem\{/,
    -        /\}/,
    -        {
    -          relevance: 10,
    -          contains: [ CURLY_SUBCOMMENT ]
    -        }
    -      ),
    -      {
    -        className: 'meta',
    -        begin: '^@(?:BASE|USE|CLASS|OPTIONS)$',
    -        relevance: 10
    -      },
    -      {
    -        className: 'title',
    -        begin: '@[\\w\\-]+\\[[\\w^;\\-]*\\](?:\\[[\\w^;\\-]*\\])?(?:.*)$'
    -      },
    -      {
    -        className: 'variable',
    -        begin: /\$\{?[\w\-.:]+\}?/
    -      },
    -      {
    -        className: 'keyword',
    -        begin: /\^[\w\-.:]+/
    -      },
    -      {
    -        className: 'number',
    -        begin: '\\^#[0-9a-fA-F]+'
    -      },
    -      hljs.C_NUMBER_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = parser3;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/perl.js b/claude-code-source/node_modules/highlight.js/lib/languages/perl.js
    deleted file mode 100644
    index ff02952b..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/perl.js
    +++ /dev/null
    @@ -1,515 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/**
    - * Any of the passed expresssions may match
    - *
    - * Creates a huge this | this | that | that match
    - * @param {(RegExp | string)[] } args
    - * @returns {string}
    - */
    -function either(...args) {
    -  const joined = '(' + args.map((x) => source(x)).join("|") + ")";
    -  return joined;
    -}
    -
    -/*
    -Language: Perl
    -Author: Peter Leonov 
    -Website: https://www.perl.org
    -Category: common
    -*/
    -
    -/** @type LanguageFn */
    -function perl(hljs) {
    -  const KEYWORDS = [
    -    'abs',
    -    'accept',
    -    'alarm',
    -    'and',
    -    'atan2',
    -    'bind',
    -    'binmode',
    -    'bless',
    -    'break',
    -    'caller',
    -    'chdir',
    -    'chmod',
    -    'chomp',
    -    'chop',
    -    'chown',
    -    'chr',
    -    'chroot',
    -    'close',
    -    'closedir',
    -    'connect',
    -    'continue',
    -    'cos',
    -    'crypt',
    -    'dbmclose',
    -    'dbmopen',
    -    'defined',
    -    'delete',
    -    'die',
    -    'do',
    -    'dump',
    -    'each',
    -    'else',
    -    'elsif',
    -    'endgrent',
    -    'endhostent',
    -    'endnetent',
    -    'endprotoent',
    -    'endpwent',
    -    'endservent',
    -    'eof',
    -    'eval',
    -    'exec',
    -    'exists',
    -    'exit',
    -    'exp',
    -    'fcntl',
    -    'fileno',
    -    'flock',
    -    'for',
    -    'foreach',
    -    'fork',
    -    'format',
    -    'formline',
    -    'getc',
    -    'getgrent',
    -    'getgrgid',
    -    'getgrnam',
    -    'gethostbyaddr',
    -    'gethostbyname',
    -    'gethostent',
    -    'getlogin',
    -    'getnetbyaddr',
    -    'getnetbyname',
    -    'getnetent',
    -    'getpeername',
    -    'getpgrp',
    -    'getpriority',
    -    'getprotobyname',
    -    'getprotobynumber',
    -    'getprotoent',
    -    'getpwent',
    -    'getpwnam',
    -    'getpwuid',
    -    'getservbyname',
    -    'getservbyport',
    -    'getservent',
    -    'getsockname',
    -    'getsockopt',
    -    'given',
    -    'glob',
    -    'gmtime',
    -    'goto',
    -    'grep',
    -    'gt',
    -    'hex',
    -    'if',
    -    'index',
    -    'int',
    -    'ioctl',
    -    'join',
    -    'keys',
    -    'kill',
    -    'last',
    -    'lc',
    -    'lcfirst',
    -    'length',
    -    'link',
    -    'listen',
    -    'local',
    -    'localtime',
    -    'log',
    -    'lstat',
    -    'lt',
    -    'ma',
    -    'map',
    -    'mkdir',
    -    'msgctl',
    -    'msgget',
    -    'msgrcv',
    -    'msgsnd',
    -    'my',
    -    'ne',
    -    'next',
    -    'no',
    -    'not',
    -    'oct',
    -    'open',
    -    'opendir',
    -    'or',
    -    'ord',
    -    'our',
    -    'pack',
    -    'package',
    -    'pipe',
    -    'pop',
    -    'pos',
    -    'print',
    -    'printf',
    -    'prototype',
    -    'push',
    -    'q|0',
    -    'qq',
    -    'quotemeta',
    -    'qw',
    -    'qx',
    -    'rand',
    -    'read',
    -    'readdir',
    -    'readline',
    -    'readlink',
    -    'readpipe',
    -    'recv',
    -    'redo',
    -    'ref',
    -    'rename',
    -    'require',
    -    'reset',
    -    'return',
    -    'reverse',
    -    'rewinddir',
    -    'rindex',
    -    'rmdir',
    -    'say',
    -    'scalar',
    -    'seek',
    -    'seekdir',
    -    'select',
    -    'semctl',
    -    'semget',
    -    'semop',
    -    'send',
    -    'setgrent',
    -    'sethostent',
    -    'setnetent',
    -    'setpgrp',
    -    'setpriority',
    -    'setprotoent',
    -    'setpwent',
    -    'setservent',
    -    'setsockopt',
    -    'shift',
    -    'shmctl',
    -    'shmget',
    -    'shmread',
    -    'shmwrite',
    -    'shutdown',
    -    'sin',
    -    'sleep',
    -    'socket',
    -    'socketpair',
    -    'sort',
    -    'splice',
    -    'split',
    -    'sprintf',
    -    'sqrt',
    -    'srand',
    -    'stat',
    -    'state',
    -    'study',
    -    'sub',
    -    'substr',
    -    'symlink',
    -    'syscall',
    -    'sysopen',
    -    'sysread',
    -    'sysseek',
    -    'system',
    -    'syswrite',
    -    'tell',
    -    'telldir',
    -    'tie',
    -    'tied',
    -    'time',
    -    'times',
    -    'tr',
    -    'truncate',
    -    'uc',
    -    'ucfirst',
    -    'umask',
    -    'undef',
    -    'unless',
    -    'unlink',
    -    'unpack',
    -    'unshift',
    -    'untie',
    -    'until',
    -    'use',
    -    'utime',
    -    'values',
    -    'vec',
    -    'wait',
    -    'waitpid',
    -    'wantarray',
    -    'warn',
    -    'when',
    -    'while',
    -    'write',
    -    'x|0',
    -    'xor',
    -    'y|0'
    -  ];
    -
    -  // https://perldoc.perl.org/perlre#Modifiers
    -  const REGEX_MODIFIERS = /[dualxmsipngr]{0,12}/; // aa and xx are valid, making max length 12
    -  const PERL_KEYWORDS = {
    -    $pattern: /[\w.]+/,
    -    keyword: KEYWORDS.join(" ")
    -  };
    -  const SUBST = {
    -    className: 'subst',
    -    begin: '[$@]\\{',
    -    end: '\\}',
    -    keywords: PERL_KEYWORDS
    -  };
    -  const METHOD = {
    -    begin: /->\{/,
    -    end: /\}/
    -    // contains defined later
    -  };
    -  const VAR = {
    -    variants: [
    -      {
    -        begin: /\$\d/
    -      },
    -      {
    -        begin: concat(
    -          /[$%@](\^\w\b|#\w+(::\w+)*|\{\w+\}|\w+(::\w*)*)/,
    -          // negative look-ahead tries to avoid matching patterns that are not
    -          // Perl at all like $ident$, @ident@, etc.
    -          `(?![A-Za-z])(?![@$%])`
    -        )
    -      },
    -      {
    -        begin: /[$%@][^\s\w{]/,
    -        relevance: 0
    -      }
    -    ]
    -  };
    -  const STRING_CONTAINS = [
    -    hljs.BACKSLASH_ESCAPE,
    -    SUBST,
    -    VAR
    -  ];
    -  const REGEX_DELIMS = [
    -    /!/,
    -    /\//,
    -    /\|/,
    -    /\?/,
    -    /'/,
    -    /"/, // valid but infrequent and weird
    -    /#/ // valid but infrequent and weird
    -  ];
    -  /**
    -   * @param {string|RegExp} prefix
    -   * @param {string|RegExp} open
    -   * @param {string|RegExp} close
    -   */
    -  const PAIRED_DOUBLE_RE = (prefix, open, close = '\\1') => {
    -    const middle = (close === '\\1')
    -      ? close
    -      : concat(close, open);
    -    return concat(
    -      concat("(?:", prefix, ")"),
    -      open,
    -      /(?:\\.|[^\\\/])*?/,
    -      middle,
    -      /(?:\\.|[^\\\/])*?/,
    -      close,
    -      REGEX_MODIFIERS
    -    );
    -  };
    -  /**
    -   * @param {string|RegExp} prefix
    -   * @param {string|RegExp} open
    -   * @param {string|RegExp} close
    -   */
    -  const PAIRED_RE = (prefix, open, close) => {
    -    return concat(
    -      concat("(?:", prefix, ")"),
    -      open,
    -      /(?:\\.|[^\\\/])*?/,
    -      close,
    -      REGEX_MODIFIERS
    -    );
    -  };
    -  const PERL_DEFAULT_CONTAINS = [
    -    VAR,
    -    hljs.HASH_COMMENT_MODE,
    -    hljs.COMMENT(
    -      /^=\w/,
    -      /=cut/,
    -      {
    -        endsWithParent: true
    -      }
    -    ),
    -    METHOD,
    -    {
    -      className: 'string',
    -      contains: STRING_CONTAINS,
    -      variants: [
    -        {
    -          begin: 'q[qwxr]?\\s*\\(',
    -          end: '\\)',
    -          relevance: 5
    -        },
    -        {
    -          begin: 'q[qwxr]?\\s*\\[',
    -          end: '\\]',
    -          relevance: 5
    -        },
    -        {
    -          begin: 'q[qwxr]?\\s*\\{',
    -          end: '\\}',
    -          relevance: 5
    -        },
    -        {
    -          begin: 'q[qwxr]?\\s*\\|',
    -          end: '\\|',
    -          relevance: 5
    -        },
    -        {
    -          begin: 'q[qwxr]?\\s*<',
    -          end: '>',
    -          relevance: 5
    -        },
    -        {
    -          begin: 'qw\\s+q',
    -          end: 'q',
    -          relevance: 5
    -        },
    -        {
    -          begin: '\'',
    -          end: '\'',
    -          contains: [ hljs.BACKSLASH_ESCAPE ]
    -        },
    -        {
    -          begin: '"',
    -          end: '"'
    -        },
    -        {
    -          begin: '`',
    -          end: '`',
    -          contains: [ hljs.BACKSLASH_ESCAPE ]
    -        },
    -        {
    -          begin: /\{\w+\}/,
    -          relevance: 0
    -        },
    -        {
    -          begin: '-?\\w+\\s*=>',
    -          relevance: 0
    -        }
    -      ]
    -    },
    -    {
    -      className: 'number',
    -      begin: '(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b',
    -      relevance: 0
    -    },
    -    { // regexp container
    -      begin: '(\\/\\/|' + hljs.RE_STARTERS_RE + '|\\b(split|return|print|reverse|grep)\\b)\\s*',
    -      keywords: 'split return print reverse grep',
    -      relevance: 0,
    -      contains: [
    -        hljs.HASH_COMMENT_MODE,
    -        {
    -          className: 'regexp',
    -          variants: [
    -            // allow matching common delimiters
    -            { begin: PAIRED_DOUBLE_RE("s|tr|y", either(...REGEX_DELIMS)) },
    -            // and then paired delmis
    -            { begin: PAIRED_DOUBLE_RE("s|tr|y", "\\(", "\\)") },
    -            { begin: PAIRED_DOUBLE_RE("s|tr|y", "\\[", "\\]") },
    -            { begin: PAIRED_DOUBLE_RE("s|tr|y", "\\{", "\\}") }
    -          ],
    -          relevance: 2
    -        },
    -        {
    -          className: 'regexp',
    -          variants: [
    -            {
    -              // could be a comment in many languages so do not count
    -              // as relevant
    -              begin: /(m|qr)\/\//,
    -              relevance: 0
    -            },
    -            // prefix is optional with /regex/
    -            { begin: PAIRED_RE("(?:m|qr)?", /\//, /\//)},
    -            // allow matching common delimiters
    -            { begin: PAIRED_RE("m|qr", either(...REGEX_DELIMS), /\1/)},
    -            // allow common paired delmins
    -            { begin: PAIRED_RE("m|qr", /\(/, /\)/)},
    -            { begin: PAIRED_RE("m|qr", /\[/, /\]/)},
    -            { begin: PAIRED_RE("m|qr", /\{/, /\}/)}
    -          ]
    -        }
    -      ]
    -    },
    -    {
    -      className: 'function',
    -      beginKeywords: 'sub',
    -      end: '(\\s*\\(.*?\\))?[;{]',
    -      excludeEnd: true,
    -      relevance: 5,
    -      contains: [ hljs.TITLE_MODE ]
    -    },
    -    {
    -      begin: '-\\w\\b',
    -      relevance: 0
    -    },
    -    {
    -      begin: "^__DATA__$",
    -      end: "^__END__$",
    -      subLanguage: 'mojolicious',
    -      contains: [
    -        {
    -          begin: "^@@.*",
    -          end: "$",
    -          className: "comment"
    -        }
    -      ]
    -    }
    -  ];
    -  SUBST.contains = PERL_DEFAULT_CONTAINS;
    -  METHOD.contains = PERL_DEFAULT_CONTAINS;
    -
    -  return {
    -    name: 'Perl',
    -    aliases: [
    -      'pl',
    -      'pm'
    -    ],
    -    keywords: PERL_KEYWORDS,
    -    contains: PERL_DEFAULT_CONTAINS
    -  };
    -}
    -
    -module.exports = perl;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/pf.js b/claude-code-source/node_modules/highlight.js/lib/languages/pf.js
    deleted file mode 100644
    index 60689360..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/pf.js
    +++ /dev/null
    @@ -1,59 +0,0 @@
    -/*
    -Language: Packet Filter config
    -Description: pf.conf — packet filter configuration file (OpenBSD)
    -Author: Peter Piwowarski 
    -Website: http://man.openbsd.org/pf.conf
    -Category: config
    -*/
    -
    -function pf(hljs) {
    -  const MACRO = {
    -    className: 'variable',
    -    begin: /\$[\w\d#@][\w\d_]*/
    -  };
    -  const TABLE = {
    -    className: 'variable',
    -    begin: /<(?!\/)/,
    -    end: />/
    -  };
    -
    -  return {
    -    name: 'Packet Filter config',
    -    aliases: [ 'pf.conf' ],
    -    keywords: {
    -      $pattern: /[a-z0-9_<>-]+/,
    -      built_in: /* block match pass are "actions" in pf.conf(5), the rest are
    -                 * lexically similar top-level commands.
    -                 */
    -        'block match pass load anchor|5 antispoof|10 set table',
    -      keyword:
    -        'in out log quick on rdomain inet inet6 proto from port os to route ' +
    -        'allow-opts divert-packet divert-reply divert-to flags group icmp-type ' +
    -        'icmp6-type label once probability recieved-on rtable prio queue ' +
    -        'tos tag tagged user keep fragment for os drop ' +
    -        'af-to|10 binat-to|10 nat-to|10 rdr-to|10 bitmask least-stats random round-robin ' +
    -        'source-hash static-port ' +
    -        'dup-to reply-to route-to ' +
    -        'parent bandwidth default min max qlimit ' +
    -        'block-policy debug fingerprints hostid limit loginterface optimization ' +
    -        'reassemble ruleset-optimization basic none profile skip state-defaults ' +
    -        'state-policy timeout ' +
    -        'const counters persist ' +
    -        'no modulate synproxy state|5 floating if-bound no-sync pflow|10 sloppy ' +
    -        'source-track global rule max-src-nodes max-src-states max-src-conn ' +
    -        'max-src-conn-rate overload flush ' +
    -        'scrub|5 max-mss min-ttl no-df|10 random-id',
    -      literal:
    -        'all any no-route self urpf-failed egress|5 unknown'
    -    },
    -    contains: [
    -      hljs.HASH_COMMENT_MODE,
    -      hljs.NUMBER_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      MACRO,
    -      TABLE
    -    ]
    -  };
    -}
    -
    -module.exports = pf;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/pgsql.js b/claude-code-source/node_modules/highlight.js/lib/languages/pgsql.js
    deleted file mode 100644
    index 9978c2dc..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/pgsql.js
    +++ /dev/null
    @@ -1,630 +0,0 @@
    -/*
    -Language: PostgreSQL and PL/pgSQL
    -Author: Egor Rogov (e.rogov@postgrespro.ru)
    -Website: https://www.postgresql.org/docs/11/sql.html
    -Description:
    -    This language incorporates both PostgreSQL SQL dialect and PL/pgSQL language.
    -    It is based on PostgreSQL version 11. Some notes:
    -    - Text in double-dollar-strings is _always_ interpreted as some programming code. Text
    -      in ordinary quotes is _never_ interpreted that way and highlighted just as a string.
    -    - There are quite a bit "special cases". That's because many keywords are not strictly
    -      they are keywords in some contexts and ordinary identifiers in others. Only some
    -      of such cases are handled; you still can get some of your identifiers highlighted
    -      wrong way.
    -    - Function names deliberately are not highlighted. There is no way to tell function
    -      call from other constructs, hence we can't highlight _all_ function names. And
    -      some names highlighted while others not looks ugly.
    -*/
    -
    -function pgsql(hljs) {
    -  const COMMENT_MODE = hljs.COMMENT('--', '$');
    -  const UNQUOTED_IDENT = '[a-zA-Z_][a-zA-Z_0-9$]*';
    -  const DOLLAR_STRING = '\\$([a-zA-Z_]?|[a-zA-Z_][a-zA-Z_0-9]*)\\$';
    -  const LABEL = '<<\\s*' + UNQUOTED_IDENT + '\\s*>>';
    -
    -  const SQL_KW =
    -    // https://www.postgresql.org/docs/11/static/sql-keywords-appendix.html
    -    // https://www.postgresql.org/docs/11/static/sql-commands.html
    -    // SQL commands (starting words)
    -    'ABORT ALTER ANALYZE BEGIN CALL CHECKPOINT|10 CLOSE CLUSTER COMMENT COMMIT COPY CREATE DEALLOCATE DECLARE ' +
    -    'DELETE DISCARD DO DROP END EXECUTE EXPLAIN FETCH GRANT IMPORT INSERT LISTEN LOAD LOCK MOVE NOTIFY ' +
    -    'PREPARE REASSIGN|10 REFRESH REINDEX RELEASE RESET REVOKE ROLLBACK SAVEPOINT SECURITY SELECT SET SHOW ' +
    -    'START TRUNCATE UNLISTEN|10 UPDATE VACUUM|10 VALUES ' +
    -    // SQL commands (others)
    -    'AGGREGATE COLLATION CONVERSION|10 DATABASE DEFAULT PRIVILEGES DOMAIN TRIGGER EXTENSION FOREIGN ' +
    -    'WRAPPER|10 TABLE FUNCTION GROUP LANGUAGE LARGE OBJECT MATERIALIZED VIEW OPERATOR CLASS ' +
    -    'FAMILY POLICY PUBLICATION|10 ROLE RULE SCHEMA SEQUENCE SERVER STATISTICS SUBSCRIPTION SYSTEM ' +
    -    'TABLESPACE CONFIGURATION DICTIONARY PARSER TEMPLATE TYPE USER MAPPING PREPARED ACCESS ' +
    -    'METHOD CAST AS TRANSFORM TRANSACTION OWNED TO INTO SESSION AUTHORIZATION ' +
    -    'INDEX PROCEDURE ASSERTION ' +
    -    // additional reserved key words
    -    'ALL ANALYSE AND ANY ARRAY ASC ASYMMETRIC|10 BOTH CASE CHECK ' +
    -    'COLLATE COLUMN CONCURRENTLY|10 CONSTRAINT CROSS ' +
    -    'DEFERRABLE RANGE ' +
    -    'DESC DISTINCT ELSE EXCEPT FOR FREEZE|10 FROM FULL HAVING ' +
    -    'ILIKE IN INITIALLY INNER INTERSECT IS ISNULL JOIN LATERAL LEADING LIKE LIMIT ' +
    -    'NATURAL NOT NOTNULL NULL OFFSET ON ONLY OR ORDER OUTER OVERLAPS PLACING PRIMARY ' +
    -    'REFERENCES RETURNING SIMILAR SOME SYMMETRIC TABLESAMPLE THEN ' +
    -    'TRAILING UNION UNIQUE USING VARIADIC|10 VERBOSE WHEN WHERE WINDOW WITH ' +
    -    // some of non-reserved (which are used in clauses or as PL/pgSQL keyword)
    -    'BY RETURNS INOUT OUT SETOF|10 IF STRICT CURRENT CONTINUE OWNER LOCATION OVER PARTITION WITHIN ' +
    -    'BETWEEN ESCAPE EXTERNAL INVOKER DEFINER WORK RENAME VERSION CONNECTION CONNECT ' +
    -    'TABLES TEMP TEMPORARY FUNCTIONS SEQUENCES TYPES SCHEMAS OPTION CASCADE RESTRICT ADD ADMIN ' +
    -    'EXISTS VALID VALIDATE ENABLE DISABLE REPLICA|10 ALWAYS PASSING COLUMNS PATH ' +
    -    'REF VALUE OVERRIDING IMMUTABLE STABLE VOLATILE BEFORE AFTER EACH ROW PROCEDURAL ' +
    -    'ROUTINE NO HANDLER VALIDATOR OPTIONS STORAGE OIDS|10 WITHOUT INHERIT DEPENDS CALLED ' +
    -    'INPUT LEAKPROOF|10 COST ROWS NOWAIT SEARCH UNTIL ENCRYPTED|10 PASSWORD CONFLICT|10 ' +
    -    'INSTEAD INHERITS CHARACTERISTICS WRITE CURSOR ALSO STATEMENT SHARE EXCLUSIVE INLINE ' +
    -    'ISOLATION REPEATABLE READ COMMITTED SERIALIZABLE UNCOMMITTED LOCAL GLOBAL SQL PROCEDURES ' +
    -    'RECURSIVE SNAPSHOT ROLLUP CUBE TRUSTED|10 INCLUDE FOLLOWING PRECEDING UNBOUNDED RANGE GROUPS ' +
    -    'UNENCRYPTED|10 SYSID FORMAT DELIMITER HEADER QUOTE ENCODING FILTER OFF ' +
    -    // some parameters of VACUUM/ANALYZE/EXPLAIN
    -    'FORCE_QUOTE FORCE_NOT_NULL FORCE_NULL COSTS BUFFERS TIMING SUMMARY DISABLE_PAGE_SKIPPING ' +
    -    //
    -    'RESTART CYCLE GENERATED IDENTITY DEFERRED IMMEDIATE LEVEL LOGGED UNLOGGED ' +
    -    'OF NOTHING NONE EXCLUDE ATTRIBUTE ' +
    -    // from GRANT (not keywords actually)
    -    'USAGE ROUTINES ' +
    -    // actually literals, but look better this way (due to IS TRUE, IS FALSE, ISNULL etc)
    -    'TRUE FALSE NAN INFINITY ';
    -
    -  const ROLE_ATTRS = // only those not in keywrods already
    -    'SUPERUSER NOSUPERUSER CREATEDB NOCREATEDB CREATEROLE NOCREATEROLE INHERIT NOINHERIT ' +
    -    'LOGIN NOLOGIN REPLICATION NOREPLICATION BYPASSRLS NOBYPASSRLS ';
    -
    -  const PLPGSQL_KW =
    -    'ALIAS BEGIN CONSTANT DECLARE END EXCEPTION RETURN PERFORM|10 RAISE GET DIAGNOSTICS ' +
    -    'STACKED|10 FOREACH LOOP ELSIF EXIT WHILE REVERSE SLICE DEBUG LOG INFO NOTICE WARNING ASSERT ' +
    -    'OPEN ';
    -
    -  const TYPES =
    -    // https://www.postgresql.org/docs/11/static/datatype.html
    -    'BIGINT INT8 BIGSERIAL SERIAL8 BIT VARYING VARBIT BOOLEAN BOOL BOX BYTEA CHARACTER CHAR VARCHAR ' +
    -    'CIDR CIRCLE DATE DOUBLE PRECISION FLOAT8 FLOAT INET INTEGER INT INT4 INTERVAL JSON JSONB LINE LSEG|10 ' +
    -    'MACADDR MACADDR8 MONEY NUMERIC DEC DECIMAL PATH POINT POLYGON REAL FLOAT4 SMALLINT INT2 ' +
    -    'SMALLSERIAL|10 SERIAL2|10 SERIAL|10 SERIAL4|10 TEXT TIME ZONE TIMETZ|10 TIMESTAMP TIMESTAMPTZ|10 TSQUERY|10 TSVECTOR|10 ' +
    -    'TXID_SNAPSHOT|10 UUID XML NATIONAL NCHAR ' +
    -    'INT4RANGE|10 INT8RANGE|10 NUMRANGE|10 TSRANGE|10 TSTZRANGE|10 DATERANGE|10 ' +
    -    // pseudotypes
    -    'ANYELEMENT ANYARRAY ANYNONARRAY ANYENUM ANYRANGE CSTRING INTERNAL ' +
    -    'RECORD PG_DDL_COMMAND VOID UNKNOWN OPAQUE REFCURSOR ' +
    -    // spec. type
    -    'NAME ' +
    -    // OID-types
    -    'OID REGPROC|10 REGPROCEDURE|10 REGOPER|10 REGOPERATOR|10 REGCLASS|10 REGTYPE|10 REGROLE|10 ' +
    -    'REGNAMESPACE|10 REGCONFIG|10 REGDICTIONARY|10 ';// +
    -
    -  const TYPES_RE =
    -    TYPES.trim()
    -      .split(' ')
    -      .map(function(val) { return val.split('|')[0]; })
    -      .join('|');
    -
    -  const SQL_BI =
    -    'CURRENT_TIME CURRENT_TIMESTAMP CURRENT_USER CURRENT_CATALOG|10 CURRENT_DATE LOCALTIME LOCALTIMESTAMP ' +
    -    'CURRENT_ROLE|10 CURRENT_SCHEMA|10 SESSION_USER PUBLIC ';
    -
    -  const PLPGSQL_BI =
    -    'FOUND NEW OLD TG_NAME|10 TG_WHEN|10 TG_LEVEL|10 TG_OP|10 TG_RELID|10 TG_RELNAME|10 ' +
    -    'TG_TABLE_NAME|10 TG_TABLE_SCHEMA|10 TG_NARGS|10 TG_ARGV|10 TG_EVENT|10 TG_TAG|10 ' +
    -    // get diagnostics
    -    'ROW_COUNT RESULT_OID|10 PG_CONTEXT|10 RETURNED_SQLSTATE COLUMN_NAME CONSTRAINT_NAME ' +
    -    'PG_DATATYPE_NAME|10 MESSAGE_TEXT TABLE_NAME SCHEMA_NAME PG_EXCEPTION_DETAIL|10 ' +
    -    'PG_EXCEPTION_HINT|10 PG_EXCEPTION_CONTEXT|10 ';
    -
    -  const PLPGSQL_EXCEPTIONS =
    -    // exceptions https://www.postgresql.org/docs/current/static/errcodes-appendix.html
    -    'SQLSTATE SQLERRM|10 ' +
    -    'SUCCESSFUL_COMPLETION WARNING DYNAMIC_RESULT_SETS_RETURNED IMPLICIT_ZERO_BIT_PADDING ' +
    -    'NULL_VALUE_ELIMINATED_IN_SET_FUNCTION PRIVILEGE_NOT_GRANTED PRIVILEGE_NOT_REVOKED ' +
    -    'STRING_DATA_RIGHT_TRUNCATION DEPRECATED_FEATURE NO_DATA NO_ADDITIONAL_DYNAMIC_RESULT_SETS_RETURNED ' +
    -    'SQL_STATEMENT_NOT_YET_COMPLETE CONNECTION_EXCEPTION CONNECTION_DOES_NOT_EXIST CONNECTION_FAILURE ' +
    -    'SQLCLIENT_UNABLE_TO_ESTABLISH_SQLCONNECTION SQLSERVER_REJECTED_ESTABLISHMENT_OF_SQLCONNECTION ' +
    -    'TRANSACTION_RESOLUTION_UNKNOWN PROTOCOL_VIOLATION TRIGGERED_ACTION_EXCEPTION FEATURE_NOT_SUPPORTED ' +
    -    'INVALID_TRANSACTION_INITIATION LOCATOR_EXCEPTION INVALID_LOCATOR_SPECIFICATION INVALID_GRANTOR ' +
    -    'INVALID_GRANT_OPERATION INVALID_ROLE_SPECIFICATION DIAGNOSTICS_EXCEPTION ' +
    -    'STACKED_DIAGNOSTICS_ACCESSED_WITHOUT_ACTIVE_HANDLER CASE_NOT_FOUND CARDINALITY_VIOLATION ' +
    -    'DATA_EXCEPTION ARRAY_SUBSCRIPT_ERROR CHARACTER_NOT_IN_REPERTOIRE DATETIME_FIELD_OVERFLOW ' +
    -    'DIVISION_BY_ZERO ERROR_IN_ASSIGNMENT ESCAPE_CHARACTER_CONFLICT INDICATOR_OVERFLOW ' +
    -    'INTERVAL_FIELD_OVERFLOW INVALID_ARGUMENT_FOR_LOGARITHM INVALID_ARGUMENT_FOR_NTILE_FUNCTION ' +
    -    'INVALID_ARGUMENT_FOR_NTH_VALUE_FUNCTION INVALID_ARGUMENT_FOR_POWER_FUNCTION ' +
    -    'INVALID_ARGUMENT_FOR_WIDTH_BUCKET_FUNCTION INVALID_CHARACTER_VALUE_FOR_CAST ' +
    -    'INVALID_DATETIME_FORMAT INVALID_ESCAPE_CHARACTER INVALID_ESCAPE_OCTET INVALID_ESCAPE_SEQUENCE ' +
    -    'NONSTANDARD_USE_OF_ESCAPE_CHARACTER INVALID_INDICATOR_PARAMETER_VALUE INVALID_PARAMETER_VALUE ' +
    -    'INVALID_REGULAR_EXPRESSION INVALID_ROW_COUNT_IN_LIMIT_CLAUSE ' +
    -    'INVALID_ROW_COUNT_IN_RESULT_OFFSET_CLAUSE INVALID_TABLESAMPLE_ARGUMENT INVALID_TABLESAMPLE_REPEAT ' +
    -    'INVALID_TIME_ZONE_DISPLACEMENT_VALUE INVALID_USE_OF_ESCAPE_CHARACTER MOST_SPECIFIC_TYPE_MISMATCH ' +
    -    'NULL_VALUE_NOT_ALLOWED NULL_VALUE_NO_INDICATOR_PARAMETER NUMERIC_VALUE_OUT_OF_RANGE ' +
    -    'SEQUENCE_GENERATOR_LIMIT_EXCEEDED STRING_DATA_LENGTH_MISMATCH STRING_DATA_RIGHT_TRUNCATION ' +
    -    'SUBSTRING_ERROR TRIM_ERROR UNTERMINATED_C_STRING ZERO_LENGTH_CHARACTER_STRING ' +
    -    'FLOATING_POINT_EXCEPTION INVALID_TEXT_REPRESENTATION INVALID_BINARY_REPRESENTATION ' +
    -    'BAD_COPY_FILE_FORMAT UNTRANSLATABLE_CHARACTER NOT_AN_XML_DOCUMENT INVALID_XML_DOCUMENT ' +
    -    'INVALID_XML_CONTENT INVALID_XML_COMMENT INVALID_XML_PROCESSING_INSTRUCTION ' +
    -    'INTEGRITY_CONSTRAINT_VIOLATION RESTRICT_VIOLATION NOT_NULL_VIOLATION FOREIGN_KEY_VIOLATION ' +
    -    'UNIQUE_VIOLATION CHECK_VIOLATION EXCLUSION_VIOLATION INVALID_CURSOR_STATE ' +
    -    'INVALID_TRANSACTION_STATE ACTIVE_SQL_TRANSACTION BRANCH_TRANSACTION_ALREADY_ACTIVE ' +
    -    'HELD_CURSOR_REQUIRES_SAME_ISOLATION_LEVEL INAPPROPRIATE_ACCESS_MODE_FOR_BRANCH_TRANSACTION ' +
    -    'INAPPROPRIATE_ISOLATION_LEVEL_FOR_BRANCH_TRANSACTION ' +
    -    'NO_ACTIVE_SQL_TRANSACTION_FOR_BRANCH_TRANSACTION READ_ONLY_SQL_TRANSACTION ' +
    -    'SCHEMA_AND_DATA_STATEMENT_MIXING_NOT_SUPPORTED NO_ACTIVE_SQL_TRANSACTION ' +
    -    'IN_FAILED_SQL_TRANSACTION IDLE_IN_TRANSACTION_SESSION_TIMEOUT INVALID_SQL_STATEMENT_NAME ' +
    -    'TRIGGERED_DATA_CHANGE_VIOLATION INVALID_AUTHORIZATION_SPECIFICATION INVALID_PASSWORD ' +
    -    'DEPENDENT_PRIVILEGE_DESCRIPTORS_STILL_EXIST DEPENDENT_OBJECTS_STILL_EXIST ' +
    -    'INVALID_TRANSACTION_TERMINATION SQL_ROUTINE_EXCEPTION FUNCTION_EXECUTED_NO_RETURN_STATEMENT ' +
    -    'MODIFYING_SQL_DATA_NOT_PERMITTED PROHIBITED_SQL_STATEMENT_ATTEMPTED ' +
    -    'READING_SQL_DATA_NOT_PERMITTED INVALID_CURSOR_NAME EXTERNAL_ROUTINE_EXCEPTION ' +
    -    'CONTAINING_SQL_NOT_PERMITTED MODIFYING_SQL_DATA_NOT_PERMITTED ' +
    -    'PROHIBITED_SQL_STATEMENT_ATTEMPTED READING_SQL_DATA_NOT_PERMITTED ' +
    -    'EXTERNAL_ROUTINE_INVOCATION_EXCEPTION INVALID_SQLSTATE_RETURNED NULL_VALUE_NOT_ALLOWED ' +
    -    'TRIGGER_PROTOCOL_VIOLATED SRF_PROTOCOL_VIOLATED EVENT_TRIGGER_PROTOCOL_VIOLATED ' +
    -    'SAVEPOINT_EXCEPTION INVALID_SAVEPOINT_SPECIFICATION INVALID_CATALOG_NAME ' +
    -    'INVALID_SCHEMA_NAME TRANSACTION_ROLLBACK TRANSACTION_INTEGRITY_CONSTRAINT_VIOLATION ' +
    -    'SERIALIZATION_FAILURE STATEMENT_COMPLETION_UNKNOWN DEADLOCK_DETECTED ' +
    -    'SYNTAX_ERROR_OR_ACCESS_RULE_VIOLATION SYNTAX_ERROR INSUFFICIENT_PRIVILEGE CANNOT_COERCE ' +
    -    'GROUPING_ERROR WINDOWING_ERROR INVALID_RECURSION INVALID_FOREIGN_KEY INVALID_NAME ' +
    -    'NAME_TOO_LONG RESERVED_NAME DATATYPE_MISMATCH INDETERMINATE_DATATYPE COLLATION_MISMATCH ' +
    -    'INDETERMINATE_COLLATION WRONG_OBJECT_TYPE GENERATED_ALWAYS UNDEFINED_COLUMN ' +
    -    'UNDEFINED_FUNCTION UNDEFINED_TABLE UNDEFINED_PARAMETER UNDEFINED_OBJECT ' +
    -    'DUPLICATE_COLUMN DUPLICATE_CURSOR DUPLICATE_DATABASE DUPLICATE_FUNCTION ' +
    -    'DUPLICATE_PREPARED_STATEMENT DUPLICATE_SCHEMA DUPLICATE_TABLE DUPLICATE_ALIAS ' +
    -    'DUPLICATE_OBJECT AMBIGUOUS_COLUMN AMBIGUOUS_FUNCTION AMBIGUOUS_PARAMETER AMBIGUOUS_ALIAS ' +
    -    'INVALID_COLUMN_REFERENCE INVALID_COLUMN_DEFINITION INVALID_CURSOR_DEFINITION ' +
    -    'INVALID_DATABASE_DEFINITION INVALID_FUNCTION_DEFINITION ' +
    -    'INVALID_PREPARED_STATEMENT_DEFINITION INVALID_SCHEMA_DEFINITION INVALID_TABLE_DEFINITION ' +
    -    'INVALID_OBJECT_DEFINITION WITH_CHECK_OPTION_VIOLATION INSUFFICIENT_RESOURCES DISK_FULL ' +
    -    'OUT_OF_MEMORY TOO_MANY_CONNECTIONS CONFIGURATION_LIMIT_EXCEEDED PROGRAM_LIMIT_EXCEEDED ' +
    -    'STATEMENT_TOO_COMPLEX TOO_MANY_COLUMNS TOO_MANY_ARGUMENTS OBJECT_NOT_IN_PREREQUISITE_STATE ' +
    -    'OBJECT_IN_USE CANT_CHANGE_RUNTIME_PARAM LOCK_NOT_AVAILABLE OPERATOR_INTERVENTION ' +
    -    'QUERY_CANCELED ADMIN_SHUTDOWN CRASH_SHUTDOWN CANNOT_CONNECT_NOW DATABASE_DROPPED ' +
    -    'SYSTEM_ERROR IO_ERROR UNDEFINED_FILE DUPLICATE_FILE SNAPSHOT_TOO_OLD CONFIG_FILE_ERROR ' +
    -    'LOCK_FILE_EXISTS FDW_ERROR FDW_COLUMN_NAME_NOT_FOUND FDW_DYNAMIC_PARAMETER_VALUE_NEEDED ' +
    -    'FDW_FUNCTION_SEQUENCE_ERROR FDW_INCONSISTENT_DESCRIPTOR_INFORMATION ' +
    -    'FDW_INVALID_ATTRIBUTE_VALUE FDW_INVALID_COLUMN_NAME FDW_INVALID_COLUMN_NUMBER ' +
    -    'FDW_INVALID_DATA_TYPE FDW_INVALID_DATA_TYPE_DESCRIPTORS ' +
    -    'FDW_INVALID_DESCRIPTOR_FIELD_IDENTIFIER FDW_INVALID_HANDLE FDW_INVALID_OPTION_INDEX ' +
    -    'FDW_INVALID_OPTION_NAME FDW_INVALID_STRING_LENGTH_OR_BUFFER_LENGTH ' +
    -    'FDW_INVALID_STRING_FORMAT FDW_INVALID_USE_OF_NULL_POINTER FDW_TOO_MANY_HANDLES ' +
    -    'FDW_OUT_OF_MEMORY FDW_NO_SCHEMAS FDW_OPTION_NAME_NOT_FOUND FDW_REPLY_HANDLE ' +
    -    'FDW_SCHEMA_NOT_FOUND FDW_TABLE_NOT_FOUND FDW_UNABLE_TO_CREATE_EXECUTION ' +
    -    'FDW_UNABLE_TO_CREATE_REPLY FDW_UNABLE_TO_ESTABLISH_CONNECTION PLPGSQL_ERROR ' +
    -    'RAISE_EXCEPTION NO_DATA_FOUND TOO_MANY_ROWS ASSERT_FAILURE INTERNAL_ERROR DATA_CORRUPTED ' +
    -    'INDEX_CORRUPTED ';
    -
    -  const FUNCTIONS =
    -    // https://www.postgresql.org/docs/11/static/functions-aggregate.html
    -    'ARRAY_AGG AVG BIT_AND BIT_OR BOOL_AND BOOL_OR COUNT EVERY JSON_AGG JSONB_AGG JSON_OBJECT_AGG ' +
    -    'JSONB_OBJECT_AGG MAX MIN MODE STRING_AGG SUM XMLAGG ' +
    -    'CORR COVAR_POP COVAR_SAMP REGR_AVGX REGR_AVGY REGR_COUNT REGR_INTERCEPT REGR_R2 REGR_SLOPE ' +
    -    'REGR_SXX REGR_SXY REGR_SYY STDDEV STDDEV_POP STDDEV_SAMP VARIANCE VAR_POP VAR_SAMP ' +
    -    'PERCENTILE_CONT PERCENTILE_DISC ' +
    -    // https://www.postgresql.org/docs/11/static/functions-window.html
    -    'ROW_NUMBER RANK DENSE_RANK PERCENT_RANK CUME_DIST NTILE LAG LEAD FIRST_VALUE LAST_VALUE NTH_VALUE ' +
    -    // https://www.postgresql.org/docs/11/static/functions-comparison.html
    -    'NUM_NONNULLS NUM_NULLS ' +
    -    // https://www.postgresql.org/docs/11/static/functions-math.html
    -    'ABS CBRT CEIL CEILING DEGREES DIV EXP FLOOR LN LOG MOD PI POWER RADIANS ROUND SCALE SIGN SQRT ' +
    -    'TRUNC WIDTH_BUCKET ' +
    -    'RANDOM SETSEED ' +
    -    'ACOS ACOSD ASIN ASIND ATAN ATAND ATAN2 ATAN2D COS COSD COT COTD SIN SIND TAN TAND ' +
    -    // https://www.postgresql.org/docs/11/static/functions-string.html
    -    'BIT_LENGTH CHAR_LENGTH CHARACTER_LENGTH LOWER OCTET_LENGTH OVERLAY POSITION SUBSTRING TREAT TRIM UPPER ' +
    -    'ASCII BTRIM CHR CONCAT CONCAT_WS CONVERT CONVERT_FROM CONVERT_TO DECODE ENCODE INITCAP ' +
    -    'LEFT LENGTH LPAD LTRIM MD5 PARSE_IDENT PG_CLIENT_ENCODING QUOTE_IDENT|10 QUOTE_LITERAL|10 ' +
    -    'QUOTE_NULLABLE|10 REGEXP_MATCH REGEXP_MATCHES REGEXP_REPLACE REGEXP_SPLIT_TO_ARRAY ' +
    -    'REGEXP_SPLIT_TO_TABLE REPEAT REPLACE REVERSE RIGHT RPAD RTRIM SPLIT_PART STRPOS SUBSTR ' +
    -    'TO_ASCII TO_HEX TRANSLATE ' +
    -    // https://www.postgresql.org/docs/11/static/functions-binarystring.html
    -    'OCTET_LENGTH GET_BIT GET_BYTE SET_BIT SET_BYTE ' +
    -    // https://www.postgresql.org/docs/11/static/functions-formatting.html
    -    'TO_CHAR TO_DATE TO_NUMBER TO_TIMESTAMP ' +
    -    // https://www.postgresql.org/docs/11/static/functions-datetime.html
    -    'AGE CLOCK_TIMESTAMP|10 DATE_PART DATE_TRUNC ISFINITE JUSTIFY_DAYS JUSTIFY_HOURS JUSTIFY_INTERVAL ' +
    -    'MAKE_DATE MAKE_INTERVAL|10 MAKE_TIME MAKE_TIMESTAMP|10 MAKE_TIMESTAMPTZ|10 NOW STATEMENT_TIMESTAMP|10 ' +
    -    'TIMEOFDAY TRANSACTION_TIMESTAMP|10 ' +
    -    // https://www.postgresql.org/docs/11/static/functions-enum.html
    -    'ENUM_FIRST ENUM_LAST ENUM_RANGE ' +
    -    // https://www.postgresql.org/docs/11/static/functions-geometry.html
    -    'AREA CENTER DIAMETER HEIGHT ISCLOSED ISOPEN NPOINTS PCLOSE POPEN RADIUS WIDTH ' +
    -    'BOX BOUND_BOX CIRCLE LINE LSEG PATH POLYGON ' +
    -    // https://www.postgresql.org/docs/11/static/functions-net.html
    -    'ABBREV BROADCAST HOST HOSTMASK MASKLEN NETMASK NETWORK SET_MASKLEN TEXT INET_SAME_FAMILY ' +
    -    'INET_MERGE MACADDR8_SET7BIT ' +
    -    // https://www.postgresql.org/docs/11/static/functions-textsearch.html
    -    'ARRAY_TO_TSVECTOR GET_CURRENT_TS_CONFIG NUMNODE PLAINTO_TSQUERY PHRASETO_TSQUERY WEBSEARCH_TO_TSQUERY ' +
    -    'QUERYTREE SETWEIGHT STRIP TO_TSQUERY TO_TSVECTOR JSON_TO_TSVECTOR JSONB_TO_TSVECTOR TS_DELETE ' +
    -    'TS_FILTER TS_HEADLINE TS_RANK TS_RANK_CD TS_REWRITE TSQUERY_PHRASE TSVECTOR_TO_ARRAY ' +
    -    'TSVECTOR_UPDATE_TRIGGER TSVECTOR_UPDATE_TRIGGER_COLUMN ' +
    -    // https://www.postgresql.org/docs/11/static/functions-xml.html
    -    'XMLCOMMENT XMLCONCAT XMLELEMENT XMLFOREST XMLPI XMLROOT ' +
    -    'XMLEXISTS XML_IS_WELL_FORMED XML_IS_WELL_FORMED_DOCUMENT XML_IS_WELL_FORMED_CONTENT ' +
    -    'XPATH XPATH_EXISTS XMLTABLE XMLNAMESPACES ' +
    -    'TABLE_TO_XML TABLE_TO_XMLSCHEMA TABLE_TO_XML_AND_XMLSCHEMA ' +
    -    'QUERY_TO_XML QUERY_TO_XMLSCHEMA QUERY_TO_XML_AND_XMLSCHEMA ' +
    -    'CURSOR_TO_XML CURSOR_TO_XMLSCHEMA ' +
    -    'SCHEMA_TO_XML SCHEMA_TO_XMLSCHEMA SCHEMA_TO_XML_AND_XMLSCHEMA ' +
    -    'DATABASE_TO_XML DATABASE_TO_XMLSCHEMA DATABASE_TO_XML_AND_XMLSCHEMA ' +
    -    'XMLATTRIBUTES ' +
    -    // https://www.postgresql.org/docs/11/static/functions-json.html
    -    'TO_JSON TO_JSONB ARRAY_TO_JSON ROW_TO_JSON JSON_BUILD_ARRAY JSONB_BUILD_ARRAY JSON_BUILD_OBJECT ' +
    -    'JSONB_BUILD_OBJECT JSON_OBJECT JSONB_OBJECT JSON_ARRAY_LENGTH JSONB_ARRAY_LENGTH JSON_EACH ' +
    -    'JSONB_EACH JSON_EACH_TEXT JSONB_EACH_TEXT JSON_EXTRACT_PATH JSONB_EXTRACT_PATH ' +
    -    'JSON_OBJECT_KEYS JSONB_OBJECT_KEYS JSON_POPULATE_RECORD JSONB_POPULATE_RECORD JSON_POPULATE_RECORDSET ' +
    -    'JSONB_POPULATE_RECORDSET JSON_ARRAY_ELEMENTS JSONB_ARRAY_ELEMENTS JSON_ARRAY_ELEMENTS_TEXT ' +
    -    'JSONB_ARRAY_ELEMENTS_TEXT JSON_TYPEOF JSONB_TYPEOF JSON_TO_RECORD JSONB_TO_RECORD JSON_TO_RECORDSET ' +
    -    'JSONB_TO_RECORDSET JSON_STRIP_NULLS JSONB_STRIP_NULLS JSONB_SET JSONB_INSERT JSONB_PRETTY ' +
    -    // https://www.postgresql.org/docs/11/static/functions-sequence.html
    -    'CURRVAL LASTVAL NEXTVAL SETVAL ' +
    -    // https://www.postgresql.org/docs/11/static/functions-conditional.html
    -    'COALESCE NULLIF GREATEST LEAST ' +
    -    // https://www.postgresql.org/docs/11/static/functions-array.html
    -    'ARRAY_APPEND ARRAY_CAT ARRAY_NDIMS ARRAY_DIMS ARRAY_FILL ARRAY_LENGTH ARRAY_LOWER ARRAY_POSITION ' +
    -    'ARRAY_POSITIONS ARRAY_PREPEND ARRAY_REMOVE ARRAY_REPLACE ARRAY_TO_STRING ARRAY_UPPER CARDINALITY ' +
    -    'STRING_TO_ARRAY UNNEST ' +
    -    // https://www.postgresql.org/docs/11/static/functions-range.html
    -    'ISEMPTY LOWER_INC UPPER_INC LOWER_INF UPPER_INF RANGE_MERGE ' +
    -    // https://www.postgresql.org/docs/11/static/functions-srf.html
    -    'GENERATE_SERIES GENERATE_SUBSCRIPTS ' +
    -    // https://www.postgresql.org/docs/11/static/functions-info.html
    -    'CURRENT_DATABASE CURRENT_QUERY CURRENT_SCHEMA|10 CURRENT_SCHEMAS|10 INET_CLIENT_ADDR INET_CLIENT_PORT ' +
    -    'INET_SERVER_ADDR INET_SERVER_PORT ROW_SECURITY_ACTIVE FORMAT_TYPE ' +
    -    'TO_REGCLASS TO_REGPROC TO_REGPROCEDURE TO_REGOPER TO_REGOPERATOR TO_REGTYPE TO_REGNAMESPACE TO_REGROLE ' +
    -    'COL_DESCRIPTION OBJ_DESCRIPTION SHOBJ_DESCRIPTION ' +
    -    'TXID_CURRENT TXID_CURRENT_IF_ASSIGNED TXID_CURRENT_SNAPSHOT TXID_SNAPSHOT_XIP TXID_SNAPSHOT_XMAX ' +
    -    'TXID_SNAPSHOT_XMIN TXID_VISIBLE_IN_SNAPSHOT TXID_STATUS ' +
    -    // https://www.postgresql.org/docs/11/static/functions-admin.html
    -    'CURRENT_SETTING SET_CONFIG BRIN_SUMMARIZE_NEW_VALUES BRIN_SUMMARIZE_RANGE BRIN_DESUMMARIZE_RANGE ' +
    -    'GIN_CLEAN_PENDING_LIST ' +
    -    // https://www.postgresql.org/docs/11/static/functions-trigger.html
    -    'SUPPRESS_REDUNDANT_UPDATES_TRIGGER ' +
    -    // ihttps://www.postgresql.org/docs/devel/static/lo-funcs.html
    -    'LO_FROM_BYTEA LO_PUT LO_GET LO_CREAT LO_CREATE LO_UNLINK LO_IMPORT LO_EXPORT LOREAD LOWRITE ' +
    -    //
    -    'GROUPING CAST ';
    -
    -  const FUNCTIONS_RE =
    -      FUNCTIONS.trim()
    -        .split(' ')
    -        .map(function(val) { return val.split('|')[0]; })
    -        .join('|');
    -
    -  return {
    -    name: 'PostgreSQL',
    -    aliases: [
    -      'postgres',
    -      'postgresql'
    -    ],
    -    case_insensitive: true,
    -    keywords: {
    -      keyword:
    -            SQL_KW + PLPGSQL_KW + ROLE_ATTRS,
    -      built_in:
    -            SQL_BI + PLPGSQL_BI + PLPGSQL_EXCEPTIONS
    -    },
    -    // Forbid some cunstructs from other languages to improve autodetect. In fact
    -    // "[a-z]:" is legal (as part of array slice), but improbabal.
    -    illegal: /:==|\W\s*\(\*|(^|\s)\$[a-z]|\{\{|[a-z]:\s*$|\.\.\.|TO:|DO:/,
    -    contains: [
    -      // special handling of some words, which are reserved only in some contexts
    -      {
    -        className: 'keyword',
    -        variants: [
    -          {
    -            begin: /\bTEXT\s*SEARCH\b/
    -          },
    -          {
    -            begin: /\b(PRIMARY|FOREIGN|FOR(\s+NO)?)\s+KEY\b/
    -          },
    -          {
    -            begin: /\bPARALLEL\s+(UNSAFE|RESTRICTED|SAFE)\b/
    -          },
    -          {
    -            begin: /\bSTORAGE\s+(PLAIN|EXTERNAL|EXTENDED|MAIN)\b/
    -          },
    -          {
    -            begin: /\bMATCH\s+(FULL|PARTIAL|SIMPLE)\b/
    -          },
    -          {
    -            begin: /\bNULLS\s+(FIRST|LAST)\b/
    -          },
    -          {
    -            begin: /\bEVENT\s+TRIGGER\b/
    -          },
    -          {
    -            begin: /\b(MAPPING|OR)\s+REPLACE\b/
    -          },
    -          {
    -            begin: /\b(FROM|TO)\s+(PROGRAM|STDIN|STDOUT)\b/
    -          },
    -          {
    -            begin: /\b(SHARE|EXCLUSIVE)\s+MODE\b/
    -          },
    -          {
    -            begin: /\b(LEFT|RIGHT)\s+(OUTER\s+)?JOIN\b/
    -          },
    -          {
    -            begin: /\b(FETCH|MOVE)\s+(NEXT|PRIOR|FIRST|LAST|ABSOLUTE|RELATIVE|FORWARD|BACKWARD)\b/
    -          },
    -          {
    -            begin: /\bPRESERVE\s+ROWS\b/
    -          },
    -          {
    -            begin: /\bDISCARD\s+PLANS\b/
    -          },
    -          {
    -            begin: /\bREFERENCING\s+(OLD|NEW)\b/
    -          },
    -          {
    -            begin: /\bSKIP\s+LOCKED\b/
    -          },
    -          {
    -            begin: /\bGROUPING\s+SETS\b/
    -          },
    -          {
    -            begin: /\b(BINARY|INSENSITIVE|SCROLL|NO\s+SCROLL)\s+(CURSOR|FOR)\b/
    -          },
    -          {
    -            begin: /\b(WITH|WITHOUT)\s+HOLD\b/
    -          },
    -          {
    -            begin: /\bWITH\s+(CASCADED|LOCAL)\s+CHECK\s+OPTION\b/
    -          },
    -          {
    -            begin: /\bEXCLUDE\s+(TIES|NO\s+OTHERS)\b/
    -          },
    -          {
    -            begin: /\bFORMAT\s+(TEXT|XML|JSON|YAML)\b/
    -          },
    -          {
    -            begin: /\bSET\s+((SESSION|LOCAL)\s+)?NAMES\b/
    -          },
    -          {
    -            begin: /\bIS\s+(NOT\s+)?UNKNOWN\b/
    -          },
    -          {
    -            begin: /\bSECURITY\s+LABEL\b/
    -          },
    -          {
    -            begin: /\bSTANDALONE\s+(YES|NO|NO\s+VALUE)\b/
    -          },
    -          {
    -            begin: /\bWITH\s+(NO\s+)?DATA\b/
    -          },
    -          {
    -            begin: /\b(FOREIGN|SET)\s+DATA\b/
    -          },
    -          {
    -            begin: /\bSET\s+(CATALOG|CONSTRAINTS)\b/
    -          },
    -          {
    -            begin: /\b(WITH|FOR)\s+ORDINALITY\b/
    -          },
    -          {
    -            begin: /\bIS\s+(NOT\s+)?DOCUMENT\b/
    -          },
    -          {
    -            begin: /\bXML\s+OPTION\s+(DOCUMENT|CONTENT)\b/
    -          },
    -          {
    -            begin: /\b(STRIP|PRESERVE)\s+WHITESPACE\b/
    -          },
    -          {
    -            begin: /\bNO\s+(ACTION|MAXVALUE|MINVALUE)\b/
    -          },
    -          {
    -            begin: /\bPARTITION\s+BY\s+(RANGE|LIST|HASH)\b/
    -          },
    -          {
    -            begin: /\bAT\s+TIME\s+ZONE\b/
    -          },
    -          {
    -            begin: /\bGRANTED\s+BY\b/
    -          },
    -          {
    -            begin: /\bRETURN\s+(QUERY|NEXT)\b/
    -          },
    -          {
    -            begin: /\b(ATTACH|DETACH)\s+PARTITION\b/
    -          },
    -          {
    -            begin: /\bFORCE\s+ROW\s+LEVEL\s+SECURITY\b/
    -          },
    -          {
    -            begin: /\b(INCLUDING|EXCLUDING)\s+(COMMENTS|CONSTRAINTS|DEFAULTS|IDENTITY|INDEXES|STATISTICS|STORAGE|ALL)\b/
    -          },
    -          {
    -            begin: /\bAS\s+(ASSIGNMENT|IMPLICIT|PERMISSIVE|RESTRICTIVE|ENUM|RANGE)\b/
    -          }
    -        ]
    -      },
    -      // functions named as keywords, followed by '('
    -      {
    -        begin: /\b(FORMAT|FAMILY|VERSION)\s*\(/
    -        // keywords: { built_in: 'FORMAT FAMILY VERSION' }
    -      },
    -      // INCLUDE ( ... ) in index_parameters in CREATE TABLE
    -      {
    -        begin: /\bINCLUDE\s*\(/,
    -        keywords: 'INCLUDE'
    -      },
    -      // not highlight RANGE if not in frame_clause (not 100% correct, but seems satisfactory)
    -      {
    -        begin: /\bRANGE(?!\s*(BETWEEN|UNBOUNDED|CURRENT|[-0-9]+))/
    -      },
    -      // disable highlighting in commands CREATE AGGREGATE/COLLATION/DATABASE/OPERTOR/TEXT SEARCH .../TYPE
    -      // and in PL/pgSQL RAISE ... USING
    -      {
    -        begin: /\b(VERSION|OWNER|TEMPLATE|TABLESPACE|CONNECTION\s+LIMIT|PROCEDURE|RESTRICT|JOIN|PARSER|COPY|START|END|COLLATION|INPUT|ANALYZE|STORAGE|LIKE|DEFAULT|DELIMITER|ENCODING|COLUMN|CONSTRAINT|TABLE|SCHEMA)\s*=/
    -      },
    -      // PG_smth; HAS_some_PRIVILEGE
    -      {
    -        // className: 'built_in',
    -        begin: /\b(PG_\w+?|HAS_[A-Z_]+_PRIVILEGE)\b/,
    -        relevance: 10
    -      },
    -      // extract
    -      {
    -        begin: /\bEXTRACT\s*\(/,
    -        end: /\bFROM\b/,
    -        returnEnd: true,
    -        keywords: {
    -          // built_in: 'EXTRACT',
    -          type: 'CENTURY DAY DECADE DOW DOY EPOCH HOUR ISODOW ISOYEAR MICROSECONDS ' +
    -                        'MILLENNIUM MILLISECONDS MINUTE MONTH QUARTER SECOND TIMEZONE TIMEZONE_HOUR ' +
    -                        'TIMEZONE_MINUTE WEEK YEAR'
    -        }
    -      },
    -      // xmlelement, xmlpi - special NAME
    -      {
    -        begin: /\b(XMLELEMENT|XMLPI)\s*\(\s*NAME/,
    -        keywords: {
    -          // built_in: 'XMLELEMENT XMLPI',
    -          keyword: 'NAME'
    -        }
    -      },
    -      // xmlparse, xmlserialize
    -      {
    -        begin: /\b(XMLPARSE|XMLSERIALIZE)\s*\(\s*(DOCUMENT|CONTENT)/,
    -        keywords: {
    -          // built_in: 'XMLPARSE XMLSERIALIZE',
    -          keyword: 'DOCUMENT CONTENT'
    -        }
    -      },
    -      // Sequences. We actually skip everything between CACHE|INCREMENT|MAXVALUE|MINVALUE and
    -      // nearest following numeric constant. Without with trick we find a lot of "keywords"
    -      // in 'avrasm' autodetection test...
    -      {
    -        beginKeywords: 'CACHE INCREMENT MAXVALUE MINVALUE',
    -        end: hljs.C_NUMBER_RE,
    -        returnEnd: true,
    -        keywords: 'BY CACHE INCREMENT MAXVALUE MINVALUE'
    -      },
    -      // WITH|WITHOUT TIME ZONE as part of datatype
    -      {
    -        className: 'type',
    -        begin: /\b(WITH|WITHOUT)\s+TIME\s+ZONE\b/
    -      },
    -      // INTERVAL optional fields
    -      {
    -        className: 'type',
    -        begin: /\bINTERVAL\s+(YEAR|MONTH|DAY|HOUR|MINUTE|SECOND)(\s+TO\s+(MONTH|HOUR|MINUTE|SECOND))?\b/
    -      },
    -      // Pseudo-types which allowed only as return type
    -      {
    -        begin: /\bRETURNS\s+(LANGUAGE_HANDLER|TRIGGER|EVENT_TRIGGER|FDW_HANDLER|INDEX_AM_HANDLER|TSM_HANDLER)\b/,
    -        keywords: {
    -          keyword: 'RETURNS',
    -          type: 'LANGUAGE_HANDLER TRIGGER EVENT_TRIGGER FDW_HANDLER INDEX_AM_HANDLER TSM_HANDLER'
    -        }
    -      },
    -      // Known functions - only when followed by '('
    -      {
    -        begin: '\\b(' + FUNCTIONS_RE + ')\\s*\\('
    -        // keywords: { built_in: FUNCTIONS }
    -      },
    -      // Types
    -      {
    -        begin: '\\.(' + TYPES_RE + ')\\b' // prevent highlight as type, say, 'oid' in 'pgclass.oid'
    -      },
    -      {
    -        begin: '\\b(' + TYPES_RE + ')\\s+PATH\\b', // in XMLTABLE
    -        keywords: {
    -          keyword: 'PATH', // hopefully no one would use PATH type in XMLTABLE...
    -          type: TYPES.replace('PATH ', '')
    -        }
    -      },
    -      {
    -        className: 'type',
    -        begin: '\\b(' + TYPES_RE + ')\\b'
    -      },
    -      // Strings, see https://www.postgresql.org/docs/11/static/sql-syntax-lexical.html#SQL-SYNTAX-CONSTANTS
    -      {
    -        className: 'string',
    -        begin: '\'',
    -        end: '\'',
    -        contains: [
    -          {
    -            begin: '\'\''
    -          }
    -        ]
    -      },
    -      {
    -        className: 'string',
    -        begin: '(e|E|u&|U&)\'',
    -        end: '\'',
    -        contains: [
    -          {
    -            begin: '\\\\.'
    -          }
    -        ],
    -        relevance: 10
    -      },
    -      hljs.END_SAME_AS_BEGIN({
    -        begin: DOLLAR_STRING,
    -        end: DOLLAR_STRING,
    -        contains: [
    -          {
    -            // actually we want them all except SQL; listed are those with known implementations
    -            // and XML + JSON just in case
    -            subLanguage: [
    -              'pgsql',
    -              'perl',
    -              'python',
    -              'tcl',
    -              'r',
    -              'lua',
    -              'java',
    -              'php',
    -              'ruby',
    -              'bash',
    -              'scheme',
    -              'xml',
    -              'json'
    -            ],
    -            endsWithParent: true
    -          }
    -        ]
    -      }),
    -      // identifiers in quotes
    -      {
    -        begin: '"',
    -        end: '"',
    -        contains: [
    -          {
    -            begin: '""'
    -          }
    -        ]
    -      },
    -      // numbers
    -      hljs.C_NUMBER_MODE,
    -      // comments
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      COMMENT_MODE,
    -      // PL/pgSQL staff
    -      // %ROWTYPE, %TYPE, $n
    -      {
    -        className: 'meta',
    -        variants: [
    -          { // %TYPE, %ROWTYPE
    -            begin: '%(ROW)?TYPE',
    -            relevance: 10
    -          },
    -          { // $n
    -            begin: '\\$\\d+'
    -          },
    -          { // #compiler option
    -            begin: '^#\\w',
    -            end: '$'
    -          }
    -        ]
    -      },
    -      // <>
    -      {
    -        className: 'symbol',
    -        begin: LABEL,
    -        relevance: 10
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = pgsql;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/php-template.js b/claude-code-source/node_modules/highlight.js/lib/languages/php-template.js
    deleted file mode 100644
    index a3de4b27..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/php-template.js
    +++ /dev/null
    @@ -1,54 +0,0 @@
    -/*
    -Language: PHP Template
    -Requires: xml.js, php.js
    -Author: Josh Goebel 
    -Website: https://www.php.net
    -Category: common
    -*/
    -
    -function phpTemplate(hljs) {
    -  return {
    -    name: "PHP template",
    -    subLanguage: 'xml',
    -    contains: [
    -      {
    -        begin: /<\?(php|=)?/,
    -        end: /\?>/,
    -        subLanguage: 'php',
    -        contains: [
    -          // We don't want the php closing tag ?> to close the PHP block when
    -          // inside any of the following blocks:
    -          {
    -            begin: '/\\*',
    -            end: '\\*/',
    -            skip: true
    -          },
    -          {
    -            begin: 'b"',
    -            end: '"',
    -            skip: true
    -          },
    -          {
    -            begin: 'b\'',
    -            end: '\'',
    -            skip: true
    -          },
    -          hljs.inherit(hljs.APOS_STRING_MODE, {
    -            illegal: null,
    -            className: null,
    -            contains: null,
    -            skip: true
    -          }),
    -          hljs.inherit(hljs.QUOTE_STRING_MODE, {
    -            illegal: null,
    -            className: null,
    -            contains: null,
    -            skip: true
    -          })
    -        ]
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = phpTemplate;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/php.js b/claude-code-source/node_modules/highlight.js/lib/languages/php.js
    deleted file mode 100644
    index 0004275f..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/php.js
    +++ /dev/null
    @@ -1,204 +0,0 @@
    -/*
    -Language: PHP
    -Author: Victor Karamzin 
    -Contributors: Evgeny Stepanischev , Ivan Sagalaev 
    -Website: https://www.php.net
    -Category: common
    -*/
    -
    -/**
    - * @param {HLJSApi} hljs
    - * @returns {LanguageDetail}
    - * */
    -function php(hljs) {
    -  const VARIABLE = {
    -    className: 'variable',
    -    begin: '\\$+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*' +
    -      // negative look-ahead tries to avoid matching patterns that are not
    -      // Perl at all like $ident$, @ident@, etc.
    -      `(?![A-Za-z0-9])(?![$])`
    -  };
    -  const PREPROCESSOR = {
    -    className: 'meta',
    -    variants: [
    -      { begin: /<\?php/, relevance: 10 }, // boost for obvious PHP
    -      { begin: /<\?[=]?/ },
    -      { begin: /\?>/ } // end php tag
    -    ]
    -  };
    -  const SUBST = {
    -    className: 'subst',
    -    variants: [
    -      { begin: /\$\w+/ },
    -      { begin: /\{\$/, end: /\}/ }
    -    ]
    -  };
    -  const SINGLE_QUOTED = hljs.inherit(hljs.APOS_STRING_MODE, {
    -    illegal: null,
    -  });
    -  const DOUBLE_QUOTED = hljs.inherit(hljs.QUOTE_STRING_MODE, {
    -    illegal: null,
    -    contains: hljs.QUOTE_STRING_MODE.contains.concat(SUBST),
    -  });
    -  const HEREDOC = hljs.END_SAME_AS_BEGIN({
    -    begin: /<<<[ \t]*(\w+)\n/,
    -    end: /[ \t]*(\w+)\b/,
    -    contains: hljs.QUOTE_STRING_MODE.contains.concat(SUBST),
    -  });
    -  const STRING = {
    -    className: 'string',
    -    contains: [hljs.BACKSLASH_ESCAPE, PREPROCESSOR],
    -    variants: [
    -      hljs.inherit(SINGLE_QUOTED, {
    -        begin: "b'", end: "'",
    -      }),
    -      hljs.inherit(DOUBLE_QUOTED, {
    -        begin: 'b"', end: '"',
    -      }),
    -      DOUBLE_QUOTED,
    -      SINGLE_QUOTED,
    -      HEREDOC
    -    ]
    -  };
    -  const NUMBER = {
    -    className: 'number',
    -    variants: [
    -      { begin: `\\b0b[01]+(?:_[01]+)*\\b` }, // Binary w/ underscore support
    -      { begin: `\\b0o[0-7]+(?:_[0-7]+)*\\b` }, // Octals w/ underscore support
    -      { begin: `\\b0x[\\da-f]+(?:_[\\da-f]+)*\\b` }, // Hex w/ underscore support
    -      // Decimals w/ underscore support, with optional fragments and scientific exponent (e) suffix.
    -      { begin: `(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:e[+-]?\\d+)?` }
    -    ],
    -    relevance: 0
    -  };
    -  const KEYWORDS = {
    -    keyword:
    -    // Magic constants:
    -    // 
    -    '__CLASS__ __DIR__ __FILE__ __FUNCTION__ __LINE__ __METHOD__ __NAMESPACE__ __TRAIT__ ' +
    -    // Function that look like language construct or language construct that look like function:
    -    // List of keywords that may not require parenthesis
    -    'die echo exit include include_once print require require_once ' +
    -    // These are not language construct (function) but operate on the currently-executing function and can access the current symbol table
    -    // 'compact extract func_get_arg func_get_args func_num_args get_called_class get_parent_class ' +
    -    // Other keywords:
    -    // 
    -    // 
    -    'array abstract and as binary bool boolean break callable case catch class clone const continue declare ' +
    -    'default do double else elseif empty enddeclare endfor endforeach endif endswitch endwhile enum eval extends ' +
    -    'final finally float for foreach from global goto if implements instanceof insteadof int integer interface ' +
    -    'isset iterable list match|0 mixed new object or private protected public real return string switch throw trait ' +
    -    'try unset use var void while xor yield',
    -    literal: 'false null true',
    -    built_in:
    -    // Standard PHP library:
    -    // 
    -    'Error|0 ' + // error is too common a name esp since PHP is case in-sensitive
    -    'AppendIterator ArgumentCountError ArithmeticError ArrayIterator ArrayObject AssertionError BadFunctionCallException BadMethodCallException CachingIterator CallbackFilterIterator CompileError Countable DirectoryIterator DivisionByZeroError DomainException EmptyIterator ErrorException Exception FilesystemIterator FilterIterator GlobIterator InfiniteIterator InvalidArgumentException IteratorIterator LengthException LimitIterator LogicException MultipleIterator NoRewindIterator OutOfBoundsException OutOfRangeException OuterIterator OverflowException ParentIterator ParseError RangeException RecursiveArrayIterator RecursiveCachingIterator RecursiveCallbackFilterIterator RecursiveDirectoryIterator RecursiveFilterIterator RecursiveIterator RecursiveIteratorIterator RecursiveRegexIterator RecursiveTreeIterator RegexIterator RuntimeException SeekableIterator SplDoublyLinkedList SplFileInfo SplFileObject SplFixedArray SplHeap SplMaxHeap SplMinHeap SplObjectStorage SplObserver SplObserver SplPriorityQueue SplQueue SplStack SplSubject SplSubject SplTempFileObject TypeError UnderflowException UnexpectedValueException UnhandledMatchError ' +
    -    // Reserved interfaces:
    -    // 
    -    'ArrayAccess Closure Generator Iterator IteratorAggregate Serializable Stringable Throwable Traversable WeakReference WeakMap ' +
    -    // Reserved classes:
    -    // 
    -    'Directory __PHP_Incomplete_Class parent php_user_filter self static stdClass'
    -  };
    -  return {
    -    aliases: ['php3', 'php4', 'php5', 'php6', 'php7', 'php8'],
    -    case_insensitive: true,
    -    keywords: KEYWORDS,
    -    contains: [
    -      hljs.HASH_COMMENT_MODE,
    -      hljs.COMMENT('//', '$', {contains: [PREPROCESSOR]}),
    -      hljs.COMMENT(
    -        '/\\*',
    -        '\\*/',
    -        {
    -          contains: [
    -            {
    -              className: 'doctag',
    -              begin: '@[A-Za-z]+'
    -            }
    -          ]
    -        }
    -      ),
    -      hljs.COMMENT(
    -        '__halt_compiler.+?;',
    -        false,
    -        {
    -          endsWithParent: true,
    -          keywords: '__halt_compiler'
    -        }
    -      ),
    -      PREPROCESSOR,
    -      {
    -        className: 'keyword', begin: /\$this\b/
    -      },
    -      VARIABLE,
    -      {
    -        // swallow composed identifiers to avoid parsing them as keywords
    -        begin: /(::|->)+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/
    -      },
    -      {
    -        className: 'function',
    -        relevance: 0,
    -        beginKeywords: 'fn function', end: /[;{]/, excludeEnd: true,
    -        illegal: '[$%\\[]',
    -        contains: [
    -          {
    -            beginKeywords: 'use',
    -          },
    -          hljs.UNDERSCORE_TITLE_MODE,
    -          {
    -            begin: '=>', // No markup, just a relevance booster
    -            endsParent: true
    -          },
    -          {
    -            className: 'params',
    -            begin: '\\(', end: '\\)',
    -            excludeBegin: true,
    -            excludeEnd: true,
    -            keywords: KEYWORDS,
    -            contains: [
    -              'self',
    -              VARIABLE,
    -              hljs.C_BLOCK_COMMENT_MODE,
    -              STRING,
    -              NUMBER
    -            ]
    -          }
    -        ]
    -      },
    -      {
    -        className: 'class',
    -        variants: [
    -          { beginKeywords: "enum", illegal: /[($"]/ },
    -          { beginKeywords: "class interface trait", illegal: /[:($"]/ }
    -        ],
    -        relevance: 0,
    -        end: /\{/,
    -        excludeEnd: true,
    -        contains: [
    -          {beginKeywords: 'extends implements'},
    -          hljs.UNDERSCORE_TITLE_MODE
    -        ]
    -      },
    -      {
    -        beginKeywords: 'namespace',
    -        relevance: 0,
    -        end: ';',
    -        illegal: /[.']/,
    -        contains: [hljs.UNDERSCORE_TITLE_MODE]
    -      },
    -      {
    -        beginKeywords: 'use',
    -        relevance: 0,
    -        end: ';',
    -        contains: [hljs.UNDERSCORE_TITLE_MODE]
    -      },
    -      STRING,
    -      NUMBER
    -    ]
    -  };
    -}
    -
    -module.exports = php;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/plaintext.js b/claude-code-source/node_modules/highlight.js/lib/languages/plaintext.js
    deleted file mode 100644
    index 5cb2de76..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/plaintext.js
    +++ /dev/null
    @@ -1,19 +0,0 @@
    -/*
    -Language: Plain text
    -Author: Egor Rogov (e.rogov@postgrespro.ru)
    -Description: Plain text without any highlighting.
    -Category: common
    -*/
    -
    -function plaintext(hljs) {
    -  return {
    -    name: 'Plain text',
    -    aliases: [
    -      'text',
    -      'txt'
    -    ],
    -    disableAutodetect: true
    -  };
    -}
    -
    -module.exports = plaintext;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/pony.js b/claude-code-source/node_modules/highlight.js/lib/languages/pony.js
    deleted file mode 100644
    index 6bfba13e..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/pony.js
    +++ /dev/null
    @@ -1,89 +0,0 @@
    -/*
    -Language: Pony
    -Author: Joe Eli McIlvain 
    -Description: Pony is an open-source, object-oriented, actor-model,
    -             capabilities-secure, high performance programming language.
    -Website: https://www.ponylang.io
    -*/
    -
    -function pony(hljs) {
    -  const KEYWORDS = {
    -    keyword:
    -      'actor addressof and as be break class compile_error compile_intrinsic ' +
    -      'consume continue delegate digestof do else elseif embed end error ' +
    -      'for fun if ifdef in interface is isnt lambda let match new not object ' +
    -      'or primitive recover repeat return struct then trait try type until ' +
    -      'use var where while with xor',
    -    meta:
    -      'iso val tag trn box ref',
    -    literal:
    -      'this false true'
    -  };
    -
    -  const TRIPLE_QUOTE_STRING_MODE = {
    -    className: 'string',
    -    begin: '"""',
    -    end: '"""',
    -    relevance: 10
    -  };
    -
    -  const QUOTE_STRING_MODE = {
    -    className: 'string',
    -    begin: '"',
    -    end: '"',
    -    contains: [ hljs.BACKSLASH_ESCAPE ]
    -  };
    -
    -  const SINGLE_QUOTE_CHAR_MODE = {
    -    className: 'string',
    -    begin: '\'',
    -    end: '\'',
    -    contains: [ hljs.BACKSLASH_ESCAPE ],
    -    relevance: 0
    -  };
    -
    -  const TYPE_NAME = {
    -    className: 'type',
    -    begin: '\\b_?[A-Z][\\w]*',
    -    relevance: 0
    -  };
    -
    -  const PRIMED_NAME = {
    -    begin: hljs.IDENT_RE + '\'',
    -    relevance: 0
    -  };
    -
    -  const NUMBER_MODE = {
    -    className: 'number',
    -    begin: '(-?)(\\b0[xX][a-fA-F0-9]+|\\b0[bB][01]+|(\\b\\d+(_\\d+)?(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)',
    -    relevance: 0
    -  };
    -
    -  /**
    -   * The `FUNCTION` and `CLASS` modes were intentionally removed to simplify
    -   * highlighting and fix cases like
    -   * ```
    -   * interface Iterator[A: A]
    -   *   fun has_next(): Bool
    -   *   fun next(): A?
    -   * ```
    -   * where it is valid to have a function head without a body
    -   */
    -
    -  return {
    -    name: 'Pony',
    -    keywords: KEYWORDS,
    -    contains: [
    -      TYPE_NAME,
    -      TRIPLE_QUOTE_STRING_MODE,
    -      QUOTE_STRING_MODE,
    -      SINGLE_QUOTE_CHAR_MODE,
    -      PRIMED_NAME,
    -      NUMBER_MODE,
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = pony;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/powershell.js b/claude-code-source/node_modules/highlight.js/lib/languages/powershell.js
    deleted file mode 100644
    index 46c2d4c2..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/powershell.js
    +++ /dev/null
    @@ -1,331 +0,0 @@
    -/*
    -Language: PowerShell
    -Description: PowerShell is a task-based command-line shell and scripting language built on .NET.
    -Author: David Mohundro 
    -Contributors: Nicholas Blumhardt , Victor Zhou , Nicolas Le Gall 
    -Website: https://docs.microsoft.com/en-us/powershell/
    -*/
    -
    -function powershell(hljs) {
    -  const TYPES = [
    -    "string",
    -    "char",
    -    "byte",
    -    "int",
    -    "long",
    -    "bool",
    -    "decimal",
    -    "single",
    -    "double",
    -    "DateTime",
    -    "xml",
    -    "array",
    -    "hashtable",
    -    "void"
    -  ];
    -
    -  // https://docs.microsoft.com/en-us/powershell/scripting/developer/cmdlet/approved-verbs-for-windows-powershell-commands
    -  const VALID_VERBS =
    -    'Add|Clear|Close|Copy|Enter|Exit|Find|Format|Get|Hide|Join|Lock|' +
    -    'Move|New|Open|Optimize|Pop|Push|Redo|Remove|Rename|Reset|Resize|' +
    -    'Search|Select|Set|Show|Skip|Split|Step|Switch|Undo|Unlock|' +
    -    'Watch|Backup|Checkpoint|Compare|Compress|Convert|ConvertFrom|' +
    -    'ConvertTo|Dismount|Edit|Expand|Export|Group|Import|Initialize|' +
    -    'Limit|Merge|Mount|Out|Publish|Restore|Save|Sync|Unpublish|Update|' +
    -    'Approve|Assert|Build|Complete|Confirm|Deny|Deploy|Disable|Enable|Install|Invoke|' +
    -    'Register|Request|Restart|Resume|Start|Stop|Submit|Suspend|Uninstall|' +
    -    'Unregister|Wait|Debug|Measure|Ping|Repair|Resolve|Test|Trace|Connect|' +
    -    'Disconnect|Read|Receive|Send|Write|Block|Grant|Protect|Revoke|Unblock|' +
    -    'Unprotect|Use|ForEach|Sort|Tee|Where';
    -
    -  const COMPARISON_OPERATORS =
    -    '-and|-as|-band|-bnot|-bor|-bxor|-casesensitive|-ccontains|-ceq|-cge|-cgt|' +
    -    '-cle|-clike|-clt|-cmatch|-cne|-cnotcontains|-cnotlike|-cnotmatch|-contains|' +
    -    '-creplace|-csplit|-eq|-exact|-f|-file|-ge|-gt|-icontains|-ieq|-ige|-igt|' +
    -    '-ile|-ilike|-ilt|-imatch|-in|-ine|-inotcontains|-inotlike|-inotmatch|' +
    -    '-ireplace|-is|-isnot|-isplit|-join|-le|-like|-lt|-match|-ne|-not|' +
    -    '-notcontains|-notin|-notlike|-notmatch|-or|-regex|-replace|-shl|-shr|' +
    -    '-split|-wildcard|-xor';
    -
    -  const KEYWORDS = {
    -    $pattern: /-?[A-z\.\-]+\b/,
    -    keyword:
    -      'if else foreach return do while until elseif begin for trap data dynamicparam ' +
    -      'end break throw param continue finally in switch exit filter try process catch ' +
    -      'hidden static parameter',
    -    // "echo" relevance has been set to 0 to avoid auto-detect conflicts with shell transcripts
    -    built_in:
    -      'ac asnp cat cd CFS chdir clc clear clhy cli clp cls clv cnsn compare copy cp ' +
    -      'cpi cpp curl cvpa dbp del diff dir dnsn ebp echo|0 epal epcsv epsn erase etsn exsn fc fhx ' +
    -      'fl ft fw gal gbp gc gcb gci gcm gcs gdr gerr ghy gi gin gjb gl gm gmo gp gps gpv group ' +
    -      'gsn gsnp gsv gtz gu gv gwmi h history icm iex ihy ii ipal ipcsv ipmo ipsn irm ise iwmi ' +
    -      'iwr kill lp ls man md measure mi mount move mp mv nal ndr ni nmo npssc nsn nv ogv oh ' +
    -      'popd ps pushd pwd r rbp rcjb rcsn rd rdr ren ri rjb rm rmdir rmo rni rnp rp rsn rsnp ' +
    -      'rujb rv rvpa rwmi sajb sal saps sasv sbp sc scb select set shcm si sl sleep sls sort sp ' +
    -      'spjb spps spsv start stz sujb sv swmi tee trcm type wget where wjb write'
    -    // TODO: 'validate[A-Z]+' can't work in keywords
    -  };
    -
    -  const TITLE_NAME_RE = /\w[\w\d]*((-)[\w\d]+)*/;
    -
    -  const BACKTICK_ESCAPE = {
    -    begin: '`[\\s\\S]',
    -    relevance: 0
    -  };
    -
    -  const VAR = {
    -    className: 'variable',
    -    variants: [
    -      {
    -        begin: /\$\B/
    -      },
    -      {
    -        className: 'keyword',
    -        begin: /\$this/
    -      },
    -      {
    -        begin: /\$[\w\d][\w\d_:]*/
    -      }
    -    ]
    -  };
    -
    -  const LITERAL = {
    -    className: 'literal',
    -    begin: /\$(null|true|false)\b/
    -  };
    -
    -  const QUOTE_STRING = {
    -    className: "string",
    -    variants: [
    -      {
    -        begin: /"/,
    -        end: /"/
    -      },
    -      {
    -        begin: /@"/,
    -        end: /^"@/
    -      }
    -    ],
    -    contains: [
    -      BACKTICK_ESCAPE,
    -      VAR,
    -      {
    -        className: 'variable',
    -        begin: /\$[A-z]/,
    -        end: /[^A-z]/
    -      }
    -    ]
    -  };
    -
    -  const APOS_STRING = {
    -    className: 'string',
    -    variants: [
    -      {
    -        begin: /'/,
    -        end: /'/
    -      },
    -      {
    -        begin: /@'/,
    -        end: /^'@/
    -      }
    -    ]
    -  };
    -
    -  const PS_HELPTAGS = {
    -    className: "doctag",
    -    variants: [
    -      /* no paramater help tags */
    -      {
    -        begin: /\.(synopsis|description|example|inputs|outputs|notes|link|component|role|functionality)/
    -      },
    -      /* one parameter help tags */
    -      {
    -        begin: /\.(parameter|forwardhelptargetname|forwardhelpcategory|remotehelprunspace|externalhelp)\s+\S+/
    -      }
    -    ]
    -  };
    -
    -  const PS_COMMENT = hljs.inherit(
    -    hljs.COMMENT(null, null),
    -    {
    -      variants: [
    -        /* single-line comment */
    -        {
    -          begin: /#/,
    -          end: /$/
    -        },
    -        /* multi-line comment */
    -        {
    -          begin: /<#/,
    -          end: /#>/
    -        }
    -      ],
    -      contains: [ PS_HELPTAGS ]
    -    }
    -  );
    -
    -  const CMDLETS = {
    -    className: 'built_in',
    -    variants: [
    -      {
    -        begin: '('.concat(VALID_VERBS, ')+(-)[\\w\\d]+')
    -      }
    -    ]
    -  };
    -
    -  const PS_CLASS = {
    -    className: 'class',
    -    beginKeywords: 'class enum',
    -    end: /\s*[{]/,
    -    excludeEnd: true,
    -    relevance: 0,
    -    contains: [ hljs.TITLE_MODE ]
    -  };
    -
    -  const PS_FUNCTION = {
    -    className: 'function',
    -    begin: /function\s+/,
    -    end: /\s*\{|$/,
    -    excludeEnd: true,
    -    returnBegin: true,
    -    relevance: 0,
    -    contains: [
    -      {
    -        begin: "function",
    -        relevance: 0,
    -        className: "keyword"
    -      },
    -      {
    -        className: "title",
    -        begin: TITLE_NAME_RE,
    -        relevance: 0
    -      },
    -      {
    -        begin: /\(/,
    -        end: /\)/,
    -        className: "params",
    -        relevance: 0,
    -        contains: [ VAR ]
    -      }
    -      // CMDLETS
    -    ]
    -  };
    -
    -  // Using statment, plus type, plus assembly name.
    -  const PS_USING = {
    -    begin: /using\s/,
    -    end: /$/,
    -    returnBegin: true,
    -    contains: [
    -      QUOTE_STRING,
    -      APOS_STRING,
    -      {
    -        className: 'keyword',
    -        begin: /(using|assembly|command|module|namespace|type)/
    -      }
    -    ]
    -  };
    -
    -  // Comperison operators & function named parameters.
    -  const PS_ARGUMENTS = {
    -    variants: [
    -      // PS literals are pretty verbose so it's a good idea to accent them a bit.
    -      {
    -        className: 'operator',
    -        begin: '('.concat(COMPARISON_OPERATORS, ')\\b')
    -      },
    -      {
    -        className: 'literal',
    -        begin: /(-)[\w\d]+/,
    -        relevance: 0
    -      }
    -    ]
    -  };
    -
    -  const HASH_SIGNS = {
    -    className: 'selector-tag',
    -    begin: /@\B/,
    -    relevance: 0
    -  };
    -
    -  // It's a very general rule so I'll narrow it a bit with some strict boundaries
    -  // to avoid any possible false-positive collisions!
    -  const PS_METHODS = {
    -    className: 'function',
    -    begin: /\[.*\]\s*[\w]+[ ]??\(/,
    -    end: /$/,
    -    returnBegin: true,
    -    relevance: 0,
    -    contains: [
    -      {
    -        className: 'keyword',
    -        begin: '('.concat(
    -          KEYWORDS.keyword.toString().replace(/\s/g, '|'
    -          ), ')\\b'),
    -        endsParent: true,
    -        relevance: 0
    -      },
    -      hljs.inherit(hljs.TITLE_MODE, {
    -        endsParent: true
    -      })
    -    ]
    -  };
    -
    -  const GENTLEMANS_SET = [
    -    // STATIC_MEMBER,
    -    PS_METHODS,
    -    PS_COMMENT,
    -    BACKTICK_ESCAPE,
    -    hljs.NUMBER_MODE,
    -    QUOTE_STRING,
    -    APOS_STRING,
    -    // PS_NEW_OBJECT_TYPE,
    -    CMDLETS,
    -    VAR,
    -    LITERAL,
    -    HASH_SIGNS
    -  ];
    -
    -  const PS_TYPE = {
    -    begin: /\[/,
    -    end: /\]/,
    -    excludeBegin: true,
    -    excludeEnd: true,
    -    relevance: 0,
    -    contains: [].concat(
    -      'self',
    -      GENTLEMANS_SET,
    -      {
    -        begin: "(" + TYPES.join("|") + ")",
    -        className: "built_in",
    -        relevance: 0
    -      },
    -      {
    -        className: 'type',
    -        begin: /[\.\w\d]+/,
    -        relevance: 0
    -      }
    -    )
    -  };
    -
    -  PS_METHODS.contains.unshift(PS_TYPE);
    -
    -  return {
    -    name: 'PowerShell',
    -    aliases: [
    -      "ps",
    -      "ps1"
    -    ],
    -    case_insensitive: true,
    -    keywords: KEYWORDS,
    -    contains: GENTLEMANS_SET.concat(
    -      PS_CLASS,
    -      PS_FUNCTION,
    -      PS_USING,
    -      PS_ARGUMENTS,
    -      PS_TYPE
    -    )
    -  };
    -}
    -
    -module.exports = powershell;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/processing.js b/claude-code-source/node_modules/highlight.js/lib/languages/processing.js
    deleted file mode 100644
    index 36903337..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/processing.js
    +++ /dev/null
    @@ -1,58 +0,0 @@
    -/*
    -Language: Processing
    -Description: Processing is a flexible software sketchbook and a language for learning how to code within the context of the visual arts.
    -Author: Erik Paluka 
    -Website: https://processing.org
    -Category: graphics
    -*/
    -
    -function processing(hljs) {
    -  return {
    -    name: 'Processing',
    -    keywords: {
    -      keyword: 'BufferedReader PVector PFont PImage PGraphics HashMap boolean byte char color ' +
    -        'double float int long String Array FloatDict FloatList IntDict IntList JSONArray JSONObject ' +
    -        'Object StringDict StringList Table TableRow XML ' +
    -        // Java keywords
    -        'false synchronized int abstract float private char boolean static null if const ' +
    -        'for true while long throw strictfp finally protected import native final return void ' +
    -        'enum else break transient new catch instanceof byte super volatile case assert short ' +
    -        'package default double public try this switch continue throws protected public private',
    -      literal: 'P2D P3D HALF_PI PI QUARTER_PI TAU TWO_PI',
    -      title: 'setup draw',
    -      built_in: 'displayHeight displayWidth mouseY mouseX mousePressed pmouseX pmouseY key ' +
    -        'keyCode pixels focused frameCount frameRate height width ' +
    -        'size createGraphics beginDraw createShape loadShape PShape arc ellipse line point ' +
    -        'quad rect triangle bezier bezierDetail bezierPoint bezierTangent curve curveDetail curvePoint ' +
    -        'curveTangent curveTightness shape shapeMode beginContour beginShape bezierVertex curveVertex ' +
    -        'endContour endShape quadraticVertex vertex ellipseMode noSmooth rectMode smooth strokeCap ' +
    -        'strokeJoin strokeWeight mouseClicked mouseDragged mouseMoved mousePressed mouseReleased ' +
    -        'mouseWheel keyPressed keyPressedkeyReleased keyTyped print println save saveFrame day hour ' +
    -        'millis minute month second year background clear colorMode fill noFill noStroke stroke alpha ' +
    -        'blue brightness color green hue lerpColor red saturation modelX modelY modelZ screenX screenY ' +
    -        'screenZ ambient emissive shininess specular add createImage beginCamera camera endCamera frustum ' +
    -        'ortho perspective printCamera printProjection cursor frameRate noCursor exit loop noLoop popStyle ' +
    -        'pushStyle redraw binary boolean byte char float hex int str unbinary unhex join match matchAll nf ' +
    -        'nfc nfp nfs split splitTokens trim append arrayCopy concat expand reverse shorten sort splice subset ' +
    -        'box sphere sphereDetail createInput createReader loadBytes loadJSONArray loadJSONObject loadStrings ' +
    -        'loadTable loadXML open parseXML saveTable selectFolder selectInput beginRaw beginRecord createOutput ' +
    -        'createWriter endRaw endRecord PrintWritersaveBytes saveJSONArray saveJSONObject saveStream saveStrings ' +
    -        'saveXML selectOutput popMatrix printMatrix pushMatrix resetMatrix rotate rotateX rotateY rotateZ scale ' +
    -        'shearX shearY translate ambientLight directionalLight lightFalloff lights lightSpecular noLights normal ' +
    -        'pointLight spotLight image imageMode loadImage noTint requestImage tint texture textureMode textureWrap ' +
    -        'blend copy filter get loadPixels set updatePixels blendMode loadShader PShaderresetShader shader createFont ' +
    -        'loadFont text textFont textAlign textLeading textMode textSize textWidth textAscent textDescent abs ceil ' +
    -        'constrain dist exp floor lerp log mag map max min norm pow round sq sqrt acos asin atan atan2 cos degrees ' +
    -        'radians sin tan noise noiseDetail noiseSeed random randomGaussian randomSeed'
    -    },
    -    contains: [
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.C_NUMBER_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = processing;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/profile.js b/claude-code-source/node_modules/highlight.js/lib/languages/profile.js
    deleted file mode 100644
    index 35a8fe70..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/profile.js
    +++ /dev/null
    @@ -1,43 +0,0 @@
    -/*
    -Language: Python profiler
    -Description: Python profiler results
    -Author: Brian Beck 
    -*/
    -
    -function profile(hljs) {
    -  return {
    -    name: 'Python profiler',
    -    contains: [
    -      hljs.C_NUMBER_MODE,
    -      {
    -        begin: '[a-zA-Z_][\\da-zA-Z_]+\\.[\\da-zA-Z_]{1,3}',
    -        end: ':',
    -        excludeEnd: true
    -      },
    -      {
    -        begin: '(ncalls|tottime|cumtime)',
    -        end: '$',
    -        keywords: 'ncalls tottime|10 cumtime|10 filename',
    -        relevance: 10
    -      },
    -      {
    -        begin: 'function calls',
    -        end: '$',
    -        contains: [ hljs.C_NUMBER_MODE ],
    -        relevance: 10
    -      },
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      {
    -        className: 'string',
    -        begin: '\\(',
    -        end: '\\)$',
    -        excludeBegin: true,
    -        excludeEnd: true,
    -        relevance: 0
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = profile;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/prolog.js b/claude-code-source/node_modules/highlight.js/lib/languages/prolog.js
    deleted file mode 100644
    index 25556cdd..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/prolog.js
    +++ /dev/null
    @@ -1,102 +0,0 @@
    -/*
    -Language: Prolog
    -Description: Prolog is a general purpose logic programming language associated with artificial intelligence and computational linguistics.
    -Author: Raivo Laanemets 
    -Website: https://en.wikipedia.org/wiki/Prolog
    -*/
    -
    -function prolog(hljs) {
    -  const ATOM = {
    -
    -    begin: /[a-z][A-Za-z0-9_]*/,
    -    relevance: 0
    -  };
    -
    -  const VAR = {
    -
    -    className: 'symbol',
    -    variants: [
    -      {
    -        begin: /[A-Z][a-zA-Z0-9_]*/
    -      },
    -      {
    -        begin: /_[A-Za-z0-9_]*/
    -      }
    -    ],
    -    relevance: 0
    -  };
    -
    -  const PARENTED = {
    -
    -    begin: /\(/,
    -    end: /\)/,
    -    relevance: 0
    -  };
    -
    -  const LIST = {
    -
    -    begin: /\[/,
    -    end: /\]/
    -  };
    -
    -  const LINE_COMMENT = {
    -
    -    className: 'comment',
    -    begin: /%/,
    -    end: /$/,
    -    contains: [ hljs.PHRASAL_WORDS_MODE ]
    -  };
    -
    -  const BACKTICK_STRING = {
    -
    -    className: 'string',
    -    begin: /`/,
    -    end: /`/,
    -    contains: [ hljs.BACKSLASH_ESCAPE ]
    -  };
    -
    -  const CHAR_CODE = {
    -    className: 'string', // 0'a etc.
    -    begin: /0'(\\'|.)/
    -  };
    -
    -  const SPACE_CODE = {
    -    className: 'string',
    -    begin: /0'\\s/ // 0'\s
    -  };
    -
    -  const PRED_OP = { // relevance booster
    -    begin: /:-/
    -  };
    -
    -  const inner = [
    -
    -    ATOM,
    -    VAR,
    -    PARENTED,
    -    PRED_OP,
    -    LIST,
    -    LINE_COMMENT,
    -    hljs.C_BLOCK_COMMENT_MODE,
    -    hljs.QUOTE_STRING_MODE,
    -    hljs.APOS_STRING_MODE,
    -    BACKTICK_STRING,
    -    CHAR_CODE,
    -    SPACE_CODE,
    -    hljs.C_NUMBER_MODE
    -  ];
    -
    -  PARENTED.contains = inner;
    -  LIST.contains = inner;
    -
    -  return {
    -    name: 'Prolog',
    -    contains: inner.concat([
    -      { // relevance booster
    -        begin: /\.$/
    -      }
    -    ])
    -  };
    -}
    -
    -module.exports = prolog;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/properties.js b/claude-code-source/node_modules/highlight.js/lib/languages/properties.js
    deleted file mode 100644
    index 6ae05a44..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/properties.js
    +++ /dev/null
    @@ -1,85 +0,0 @@
    -/*
    -Language: .properties
    -Contributors: Valentin Aitken , Egor Rogov 
    -Website: https://en.wikipedia.org/wiki/.properties
    -Category: common, config
    -*/
    -
    -function properties(hljs) {
    -
    -  // whitespaces: space, tab, formfeed
    -  var WS0 = '[ \\t\\f]*';
    -  var WS1 = '[ \\t\\f]+';
    -  // delimiter
    -  var EQUAL_DELIM = WS0+'[:=]'+WS0;
    -  var WS_DELIM = WS1;
    -  var DELIM = '(' + EQUAL_DELIM + '|' + WS_DELIM + ')';
    -  var KEY_ALPHANUM = '([^\\\\\\W:= \\t\\f\\n]|\\\\.)+';
    -  var KEY_OTHER = '([^\\\\:= \\t\\f\\n]|\\\\.)+';
    -
    -  var DELIM_AND_VALUE = {
    -          // skip DELIM
    -          end: DELIM,
    -          relevance: 0,
    -          starts: {
    -            // value: everything until end of line (again, taking into account backslashes)
    -            className: 'string',
    -            end: /$/,
    -            relevance: 0,
    -            contains: [
    -              { begin: '\\\\\\\\'},
    -              { begin: '\\\\\\n' }
    -            ]
    -          }
    -        };
    -
    -  return {
    -    name: '.properties',
    -    case_insensitive: true,
    -    illegal: /\S/,
    -    contains: [
    -      hljs.COMMENT('^\\s*[!#]', '$'),
    -      // key: everything until whitespace or = or : (taking into account backslashes)
    -      // case of a "normal" key
    -      {
    -        returnBegin: true,
    -        variants: [
    -          { begin: KEY_ALPHANUM + EQUAL_DELIM, relevance: 1 },
    -          { begin: KEY_ALPHANUM + WS_DELIM, relevance: 0 }
    -        ],
    -        contains: [
    -          {
    -            className: 'attr',
    -            begin: KEY_ALPHANUM,
    -            endsParent: true,
    -            relevance: 0
    -          }
    -        ],
    -        starts: DELIM_AND_VALUE
    -      },
    -      // case of key containing non-alphanumeric chars => relevance = 0
    -      {
    -        begin: KEY_OTHER + DELIM,
    -        returnBegin: true,
    -        relevance: 0,
    -        contains: [
    -          {
    -            className: 'meta',
    -            begin: KEY_OTHER,
    -            endsParent: true,
    -            relevance: 0
    -          }
    -        ],
    -        starts: DELIM_AND_VALUE
    -      },
    -      // case of an empty key
    -      {
    -        className: 'attr',
    -        relevance: 0,
    -        begin: KEY_OTHER + WS0 + '$'
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = properties;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/protobuf.js b/claude-code-source/node_modules/highlight.js/lib/languages/protobuf.js
    deleted file mode 100644
    index 2ab25f19..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/protobuf.js
    +++ /dev/null
    @@ -1,47 +0,0 @@
    -/*
    -Language: Protocol Buffers
    -Author: Dan Tao 
    -Description: Protocol buffer message definition format
    -Website: https://developers.google.com/protocol-buffers/docs/proto3
    -Category: protocols
    -*/
    -
    -function protobuf(hljs) {
    -  return {
    -    name: 'Protocol Buffers',
    -    keywords: {
    -      keyword: 'package import option optional required repeated group oneof',
    -      built_in: 'double float int32 int64 uint32 uint64 sint32 sint64 ' +
    -        'fixed32 fixed64 sfixed32 sfixed64 bool string bytes',
    -      literal: 'true false'
    -    },
    -    contains: [
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.NUMBER_MODE,
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      {
    -        className: 'class',
    -        beginKeywords: 'message enum service', end: /\{/,
    -        illegal: /\n/,
    -        contains: [
    -          hljs.inherit(hljs.TITLE_MODE, {
    -            starts: {endsWithParent: true, excludeEnd: true} // hack: eating everything after the first title
    -          })
    -        ]
    -      },
    -      {
    -        className: 'function',
    -        beginKeywords: 'rpc',
    -        end: /[{;]/, excludeEnd: true,
    -        keywords: 'rpc returns'
    -      },
    -      { // match enum items (relevance)
    -        // BLAH = ...;
    -        begin: /^\s*[A-Z_]+(?=\s*=[^\n]+;$)/
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = protobuf;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/puppet.js b/claude-code-source/node_modules/highlight.js/lib/languages/puppet.js
    deleted file mode 100644
    index 026f63a1..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/puppet.js
    +++ /dev/null
    @@ -1,147 +0,0 @@
    -/*
    -Language: Puppet
    -Author: Jose Molina Colmenero 
    -Website: https://puppet.com/docs
    -Category: config
    -*/
    -
    -function puppet(hljs) {
    -  const PUPPET_KEYWORDS = {
    -    keyword:
    -    /* language keywords */
    -      'and case default else elsif false if in import enherits node or true undef unless main settings $string ',
    -    literal:
    -    /* metaparameters */
    -      'alias audit before loglevel noop require subscribe tag ' +
    -      /* normal attributes */
    -      'owner ensure group mode name|0 changes context force incl lens load_path onlyif provider returns root show_diff type_check ' +
    -      'en_address ip_address realname command environment hour monute month monthday special target weekday ' +
    -      'creates cwd ogoutput refresh refreshonly tries try_sleep umask backup checksum content ctime force ignore ' +
    -      'links mtime purge recurse recurselimit replace selinux_ignore_defaults selrange selrole seltype seluser source ' +
    -      'souirce_permissions sourceselect validate_cmd validate_replacement allowdupe attribute_membership auth_membership forcelocal gid ' +
    -      'ia_load_module members system host_aliases ip allowed_trunk_vlans description device_url duplex encapsulation etherchannel ' +
    -      'native_vlan speed principals allow_root auth_class auth_type authenticate_user k_of_n mechanisms rule session_owner shared options ' +
    -      'device fstype enable hasrestart directory present absent link atboot blockdevice device dump pass remounts poller_tag use ' +
    -      'message withpath adminfile allow_virtual allowcdrom category configfiles flavor install_options instance package_settings platform ' +
    -      'responsefile status uninstall_options vendor unless_system_user unless_uid binary control flags hasstatus manifest pattern restart running ' +
    -      'start stop allowdupe auths expiry gid groups home iterations key_membership keys managehome membership password password_max_age ' +
    -      'password_min_age profile_membership profiles project purge_ssh_keys role_membership roles salt shell uid baseurl cost descr enabled ' +
    -      'enablegroups exclude failovermethod gpgcheck gpgkey http_caching include includepkgs keepalive metadata_expire metalink mirrorlist ' +
    -      'priority protect proxy proxy_password proxy_username repo_gpgcheck s3_enabled skip_if_unavailable sslcacert sslclientcert sslclientkey ' +
    -      'sslverify mounted',
    -    built_in:
    -    /* core facts */
    -      'architecture augeasversion blockdevices boardmanufacturer boardproductname boardserialnumber cfkey dhcp_servers ' +
    -      'domain ec2_ ec2_userdata facterversion filesystems ldom fqdn gid hardwareisa hardwaremodel hostname id|0 interfaces ' +
    -      'ipaddress ipaddress_ ipaddress6 ipaddress6_ iphostnumber is_virtual kernel kernelmajversion kernelrelease kernelversion ' +
    -      'kernelrelease kernelversion lsbdistcodename lsbdistdescription lsbdistid lsbdistrelease lsbmajdistrelease lsbminordistrelease ' +
    -      'lsbrelease macaddress macaddress_ macosx_buildversion macosx_productname macosx_productversion macosx_productverson_major ' +
    -      'macosx_productversion_minor manufacturer memoryfree memorysize netmask metmask_ network_ operatingsystem operatingsystemmajrelease ' +
    -      'operatingsystemrelease osfamily partitions path physicalprocessorcount processor processorcount productname ps puppetversion ' +
    -      'rubysitedir rubyversion selinux selinux_config_mode selinux_config_policy selinux_current_mode selinux_current_mode selinux_enforced ' +
    -      'selinux_policyversion serialnumber sp_ sshdsakey sshecdsakey sshrsakey swapencrypted swapfree swapsize timezone type uniqueid uptime ' +
    -      'uptime_days uptime_hours uptime_seconds uuid virtual vlans xendomains zfs_version zonenae zones zpool_version'
    -  };
    -
    -  const COMMENT = hljs.COMMENT('#', '$');
    -
    -  const IDENT_RE = '([A-Za-z_]|::)(\\w|::)*';
    -
    -  const TITLE = hljs.inherit(hljs.TITLE_MODE, {
    -    begin: IDENT_RE
    -  });
    -
    -  const VARIABLE = {
    -    className: 'variable',
    -    begin: '\\$' + IDENT_RE
    -  };
    -
    -  const STRING = {
    -    className: 'string',
    -    contains: [
    -      hljs.BACKSLASH_ESCAPE,
    -      VARIABLE
    -    ],
    -    variants: [
    -      {
    -        begin: /'/,
    -        end: /'/
    -      },
    -      {
    -        begin: /"/,
    -        end: /"/
    -      }
    -    ]
    -  };
    -
    -  return {
    -    name: 'Puppet',
    -    aliases: [ 'pp' ],
    -    contains: [
    -      COMMENT,
    -      VARIABLE,
    -      STRING,
    -      {
    -        beginKeywords: 'class',
    -        end: '\\{|;',
    -        illegal: /=/,
    -        contains: [
    -          TITLE,
    -          COMMENT
    -        ]
    -      },
    -      {
    -        beginKeywords: 'define',
    -        end: /\{/,
    -        contains: [
    -          {
    -            className: 'section',
    -            begin: hljs.IDENT_RE,
    -            endsParent: true
    -          }
    -        ]
    -      },
    -      {
    -        begin: hljs.IDENT_RE + '\\s+\\{',
    -        returnBegin: true,
    -        end: /\S/,
    -        contains: [
    -          {
    -            className: 'keyword',
    -            begin: hljs.IDENT_RE
    -          },
    -          {
    -            begin: /\{/,
    -            end: /\}/,
    -            keywords: PUPPET_KEYWORDS,
    -            relevance: 0,
    -            contains: [
    -              STRING,
    -              COMMENT,
    -              {
    -                begin: '[a-zA-Z_]+\\s*=>',
    -                returnBegin: true,
    -                end: '=>',
    -                contains: [
    -                  {
    -                    className: 'attr',
    -                    begin: hljs.IDENT_RE
    -                  }
    -                ]
    -              },
    -              {
    -                className: 'number',
    -                begin: '(\\b0[0-7_]+)|(\\b0x[0-9a-fA-F_]+)|(\\b[1-9][0-9_]*(\\.[0-9_]+)?)|[0_]\\b',
    -                relevance: 0
    -              },
    -              VARIABLE
    -            ]
    -          }
    -        ],
    -        relevance: 0
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = puppet;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/purebasic.js b/claude-code-source/node_modules/highlight.js/lib/languages/purebasic.js
    deleted file mode 100644
    index 6dd36cf9..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/purebasic.js
    +++ /dev/null
    @@ -1,101 +0,0 @@
    -/*
    -Language: PureBASIC
    -Author: Tristano Ajmone 
    -Description: Syntax highlighting for PureBASIC (v.5.00-5.60). No inline ASM highlighting. (v.1.2, May 2017)
    -Credits: I've taken inspiration from the PureBasic language file for GeSHi, created by Gustavo Julio Fiorenza (GuShH).
    -Website: https://www.purebasic.com
    -*/
    -
    -// Base deafult colors in PB IDE: background: #FFFFDF; foreground: #000000;
    -
    -function purebasic(hljs) {
    -  const STRINGS = { // PB IDE color: #0080FF (Azure Radiance)
    -    className: 'string',
    -    begin: '(~)?"',
    -    end: '"',
    -    illegal: '\\n'
    -  };
    -  const CONSTANTS = { // PB IDE color: #924B72 (Cannon Pink)
    -    //  "#" + a letter or underscore + letters, digits or underscores + (optional) "$"
    -    className: 'symbol',
    -    begin: '#[a-zA-Z_]\\w*\\$?'
    -  };
    -
    -  return {
    -    name: 'PureBASIC',
    -    aliases: [
    -      'pb',
    -      'pbi'
    -    ],
    -    keywords: // PB IDE color: #006666 (Blue Stone) + Bold
    -      // Keywords from all version of PureBASIC 5.00 upward ...
    -      'Align And Array As Break CallDebugger Case CompilerCase CompilerDefault ' +
    -      'CompilerElse CompilerElseIf CompilerEndIf CompilerEndSelect CompilerError ' +
    -      'CompilerIf CompilerSelect CompilerWarning Continue Data DataSection Debug ' +
    -      'DebugLevel Declare DeclareC DeclareCDLL DeclareDLL DeclareModule Default ' +
    -      'Define Dim DisableASM DisableDebugger DisableExplicit Else ElseIf EnableASM ' +
    -      'EnableDebugger EnableExplicit End EndDataSection EndDeclareModule EndEnumeration ' +
    -      'EndIf EndImport EndInterface EndMacro EndModule EndProcedure EndSelect ' +
    -      'EndStructure EndStructureUnion EndWith Enumeration EnumerationBinary Extends ' +
    -      'FakeReturn For ForEach ForEver Global Gosub Goto If Import ImportC ' +
    -      'IncludeBinary IncludeFile IncludePath Interface List Macro MacroExpandedCount ' +
    -      'Map Module NewList NewMap Next Not Or Procedure ProcedureC ' +
    -      'ProcedureCDLL ProcedureDLL ProcedureReturn Protected Prototype PrototypeC ReDim ' +
    -      'Read Repeat Restore Return Runtime Select Shared Static Step Structure ' +
    -      'StructureUnion Swap Threaded To UndefineMacro Until Until  UnuseModule ' +
    -      'UseModule Wend While With XIncludeFile XOr',
    -    contains: [
    -      // COMMENTS | PB IDE color: #00AAAA (Persian Green)
    -      hljs.COMMENT(';', '$', {
    -        relevance: 0
    -      }),
    -
    -      { // PROCEDURES DEFINITIONS
    -        className: 'function',
    -        begin: '\\b(Procedure|Declare)(C|CDLL|DLL)?\\b',
    -        end: '\\(',
    -        excludeEnd: true,
    -        returnBegin: true,
    -        contains: [
    -          { // PROCEDURE KEYWORDS | PB IDE color: #006666 (Blue Stone) + Bold
    -            className: 'keyword',
    -            begin: '(Procedure|Declare)(C|CDLL|DLL)?',
    -            excludeEnd: true
    -          },
    -          { // PROCEDURE RETURN TYPE SETTING | PB IDE color: #000000 (Black)
    -            className: 'type',
    -            begin: '\\.\\w*'
    -            // end: ' ',
    -          },
    -          hljs.UNDERSCORE_TITLE_MODE // PROCEDURE NAME | PB IDE color: #006666 (Blue Stone)
    -        ]
    -      },
    -      STRINGS,
    -      CONSTANTS
    -    ]
    -  };
    -}
    -
    -/*  ==============================================================================
    -                                      CHANGELOG
    -    ==============================================================================
    -    - v.1.2 (2017-05-12)
    -        -- BUG-FIX: Some keywords were accidentally joyned together. Now fixed.
    -    - v.1.1 (2017-04-30)
    -        -- Updated to PureBASIC 5.60.
    -        -- Keywords list now built by extracting them from the PureBASIC SDK's
    -           "SyntaxHilighting.dll" (from each PureBASIC version). Tokens from each
    -           version are added to the list, and renamed or removed tokens are kept
    -           for the sake of covering all versions of the language from PureBASIC
    -           v5.00 upward. (NOTE: currently, there are no renamed or deprecated
    -           tokens in the keywords list). For more info, see:
    -           -- http://www.purebasic.fr/english/viewtopic.php?&p=506269
    -           -- https://github.com/tajmone/purebasic-archives/tree/master/syntax-highlighting/guidelines
    -    - v.1.0 (April 2016)
    -        -- First release
    -        -- Keywords list taken and adapted from GuShH's (Gustavo Julio Fiorenza)
    -           PureBasic language file for GeSHi:
    -           -- https://github.com/easybook/geshi/blob/master/geshi/purebasic.php
    -*/
    -
    -module.exports = purebasic;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/python-repl.js b/claude-code-source/node_modules/highlight.js/lib/languages/python-repl.js
    deleted file mode 100644
    index 6c1ead0f..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/python-repl.js
    +++ /dev/null
    @@ -1,36 +0,0 @@
    -/*
    -Language: Python REPL
    -Requires: python.js
    -Author: Josh Goebel 
    -Category: common
    -*/
    -
    -function pythonRepl(hljs) {
    -  return {
    -    aliases: [ 'pycon' ],
    -    contains: [
    -      {
    -        className: 'meta',
    -        starts: {
    -          // a space separates the REPL prefix from the actual code
    -          // this is purely for cleaner HTML output
    -          end: / |$/,
    -          starts: {
    -            end: '$',
    -            subLanguage: 'python'
    -          }
    -        },
    -        variants: [
    -          {
    -            begin: /^>>>(?=[ ]|$)/
    -          },
    -          {
    -            begin: /^\.\.\.(?=[ ]|$)/
    -          }
    -        ]
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = pythonRepl;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/python.js b/claude-code-source/node_modules/highlight.js/lib/languages/python.js
    deleted file mode 100644
    index 20ce111a..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/python.js
    +++ /dev/null
    @@ -1,446 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function lookahead(re) {
    -  return concat('(?=', re, ')');
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: Python
    -Description: Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
    -Website: https://www.python.org
    -Category: common
    -*/
    -
    -function python(hljs) {
    -  const RESERVED_WORDS = [
    -    'and',
    -    'as',
    -    'assert',
    -    'async',
    -    'await',
    -    'break',
    -    'class',
    -    'continue',
    -    'def',
    -    'del',
    -    'elif',
    -    'else',
    -    'except',
    -    'finally',
    -    'for',
    -    'from',
    -    'global',
    -    'if',
    -    'import',
    -    'in',
    -    'is',
    -    'lambda',
    -    'nonlocal|10',
    -    'not',
    -    'or',
    -    'pass',
    -    'raise',
    -    'return',
    -    'try',
    -    'while',
    -    'with',
    -    'yield'
    -  ];
    -
    -  const BUILT_INS = [
    -    '__import__',
    -    'abs',
    -    'all',
    -    'any',
    -    'ascii',
    -    'bin',
    -    'bool',
    -    'breakpoint',
    -    'bytearray',
    -    'bytes',
    -    'callable',
    -    'chr',
    -    'classmethod',
    -    'compile',
    -    'complex',
    -    'delattr',
    -    'dict',
    -    'dir',
    -    'divmod',
    -    'enumerate',
    -    'eval',
    -    'exec',
    -    'filter',
    -    'float',
    -    'format',
    -    'frozenset',
    -    'getattr',
    -    'globals',
    -    'hasattr',
    -    'hash',
    -    'help',
    -    'hex',
    -    'id',
    -    'input',
    -    'int',
    -    'isinstance',
    -    'issubclass',
    -    'iter',
    -    'len',
    -    'list',
    -    'locals',
    -    'map',
    -    'max',
    -    'memoryview',
    -    'min',
    -    'next',
    -    'object',
    -    'oct',
    -    'open',
    -    'ord',
    -    'pow',
    -    'print',
    -    'property',
    -    'range',
    -    'repr',
    -    'reversed',
    -    'round',
    -    'set',
    -    'setattr',
    -    'slice',
    -    'sorted',
    -    'staticmethod',
    -    'str',
    -    'sum',
    -    'super',
    -    'tuple',
    -    'type',
    -    'vars',
    -    'zip'
    -  ];
    -
    -  const LITERALS = [
    -    '__debug__',
    -    'Ellipsis',
    -    'False',
    -    'None',
    -    'NotImplemented',
    -    'True'
    -  ];
    -
    -  // https://docs.python.org/3/library/typing.html
    -  // TODO: Could these be supplemented by a CamelCase matcher in certain
    -  // contexts, leaving these remaining only for relevance hinting?
    -  const TYPES = [
    -    "Any",
    -    "Callable",
    -    "Coroutine",
    -    "Dict",
    -    "List",
    -    "Literal",
    -    "Generic",
    -    "Optional",
    -    "Sequence",
    -    "Set",
    -    "Tuple",
    -    "Type",
    -    "Union"
    -  ];
    -
    -  const KEYWORDS = {
    -    $pattern: /[A-Za-z]\w+|__\w+__/,
    -    keyword: RESERVED_WORDS,
    -    built_in: BUILT_INS,
    -    literal: LITERALS,
    -    type: TYPES
    -  };
    -
    -  const PROMPT = {
    -    className: 'meta',
    -    begin: /^(>>>|\.\.\.) /
    -  };
    -
    -  const SUBST = {
    -    className: 'subst',
    -    begin: /\{/,
    -    end: /\}/,
    -    keywords: KEYWORDS,
    -    illegal: /#/
    -  };
    -
    -  const LITERAL_BRACKET = {
    -    begin: /\{\{/,
    -    relevance: 0
    -  };
    -
    -  const STRING = {
    -    className: 'string',
    -    contains: [ hljs.BACKSLASH_ESCAPE ],
    -    variants: [
    -      {
    -        begin: /([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,
    -        end: /'''/,
    -        contains: [
    -          hljs.BACKSLASH_ESCAPE,
    -          PROMPT
    -        ],
    -        relevance: 10
    -      },
    -      {
    -        begin: /([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,
    -        end: /"""/,
    -        contains: [
    -          hljs.BACKSLASH_ESCAPE,
    -          PROMPT
    -        ],
    -        relevance: 10
    -      },
    -      {
    -        begin: /([fF][rR]|[rR][fF]|[fF])'''/,
    -        end: /'''/,
    -        contains: [
    -          hljs.BACKSLASH_ESCAPE,
    -          PROMPT,
    -          LITERAL_BRACKET,
    -          SUBST
    -        ]
    -      },
    -      {
    -        begin: /([fF][rR]|[rR][fF]|[fF])"""/,
    -        end: /"""/,
    -        contains: [
    -          hljs.BACKSLASH_ESCAPE,
    -          PROMPT,
    -          LITERAL_BRACKET,
    -          SUBST
    -        ]
    -      },
    -      {
    -        begin: /([uU]|[rR])'/,
    -        end: /'/,
    -        relevance: 10
    -      },
    -      {
    -        begin: /([uU]|[rR])"/,
    -        end: /"/,
    -        relevance: 10
    -      },
    -      {
    -        begin: /([bB]|[bB][rR]|[rR][bB])'/,
    -        end: /'/
    -      },
    -      {
    -        begin: /([bB]|[bB][rR]|[rR][bB])"/,
    -        end: /"/
    -      },
    -      {
    -        begin: /([fF][rR]|[rR][fF]|[fF])'/,
    -        end: /'/,
    -        contains: [
    -          hljs.BACKSLASH_ESCAPE,
    -          LITERAL_BRACKET,
    -          SUBST
    -        ]
    -      },
    -      {
    -        begin: /([fF][rR]|[rR][fF]|[fF])"/,
    -        end: /"/,
    -        contains: [
    -          hljs.BACKSLASH_ESCAPE,
    -          LITERAL_BRACKET,
    -          SUBST
    -        ]
    -      },
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE
    -    ]
    -  };
    -
    -  // https://docs.python.org/3.9/reference/lexical_analysis.html#numeric-literals
    -  const digitpart = '[0-9](_?[0-9])*';
    -  const pointfloat = `(\\b(${digitpart}))?\\.(${digitpart})|\\b(${digitpart})\\.`;
    -  const NUMBER = {
    -    className: 'number',
    -    relevance: 0,
    -    variants: [
    -      // exponentfloat, pointfloat
    -      // https://docs.python.org/3.9/reference/lexical_analysis.html#floating-point-literals
    -      // optionally imaginary
    -      // https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals
    -      // Note: no leading \b because floats can start with a decimal point
    -      // and we don't want to mishandle e.g. `fn(.5)`,
    -      // no trailing \b for pointfloat because it can end with a decimal point
    -      // and we don't want to mishandle e.g. `0..hex()`; this should be safe
    -      // because both MUST contain a decimal point and so cannot be confused with
    -      // the interior part of an identifier
    -      {
    -        begin: `(\\b(${digitpart})|(${pointfloat}))[eE][+-]?(${digitpart})[jJ]?\\b`
    -      },
    -      {
    -        begin: `(${pointfloat})[jJ]?`
    -      },
    -
    -      // decinteger, bininteger, octinteger, hexinteger
    -      // https://docs.python.org/3.9/reference/lexical_analysis.html#integer-literals
    -      // optionally "long" in Python 2
    -      // https://docs.python.org/2.7/reference/lexical_analysis.html#integer-and-long-integer-literals
    -      // decinteger is optionally imaginary
    -      // https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals
    -      {
    -        begin: '\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?\\b'
    -      },
    -      {
    -        begin: '\\b0[bB](_?[01])+[lL]?\\b'
    -      },
    -      {
    -        begin: '\\b0[oO](_?[0-7])+[lL]?\\b'
    -      },
    -      {
    -        begin: '\\b0[xX](_?[0-9a-fA-F])+[lL]?\\b'
    -      },
    -
    -      // imagnumber (digitpart-based)
    -      // https://docs.python.org/3.9/reference/lexical_analysis.html#imaginary-literals
    -      {
    -        begin: `\\b(${digitpart})[jJ]\\b`
    -      }
    -    ]
    -  };
    -  const COMMENT_TYPE = {
    -    className: "comment",
    -    begin: lookahead(/# type:/),
    -    end: /$/,
    -    keywords: KEYWORDS,
    -    contains: [
    -      { // prevent keywords from coloring `type`
    -        begin: /# type:/
    -      },
    -      // comment within a datatype comment includes no keywords
    -      {
    -        begin: /#/,
    -        end: /\b\B/,
    -        endsWithParent: true
    -      }
    -    ]
    -  };
    -  const PARAMS = {
    -    className: 'params',
    -    variants: [
    -      // Exclude params in functions without params
    -      {
    -        className: "",
    -        begin: /\(\s*\)/,
    -        skip: true
    -      },
    -      {
    -        begin: /\(/,
    -        end: /\)/,
    -        excludeBegin: true,
    -        excludeEnd: true,
    -        keywords: KEYWORDS,
    -        contains: [
    -          'self',
    -          PROMPT,
    -          NUMBER,
    -          STRING,
    -          hljs.HASH_COMMENT_MODE
    -        ]
    -      }
    -    ]
    -  };
    -  SUBST.contains = [
    -    STRING,
    -    NUMBER,
    -    PROMPT
    -  ];
    -
    -  return {
    -    name: 'Python',
    -    aliases: [
    -      'py',
    -      'gyp',
    -      'ipython'
    -    ],
    -    keywords: KEYWORDS,
    -    illegal: /(<\/|->|\?)|=>/,
    -    contains: [
    -      PROMPT,
    -      NUMBER,
    -      {
    -        // very common convention
    -        begin: /\bself\b/
    -      },
    -      {
    -        // eat "if" prior to string so that it won't accidentally be
    -        // labeled as an f-string
    -        beginKeywords: "if",
    -        relevance: 0
    -      },
    -      STRING,
    -      COMMENT_TYPE,
    -      hljs.HASH_COMMENT_MODE,
    -      {
    -        variants: [
    -          {
    -            className: 'function',
    -            beginKeywords: 'def'
    -          },
    -          {
    -            className: 'class',
    -            beginKeywords: 'class'
    -          }
    -        ],
    -        end: /:/,
    -        illegal: /[${=;\n,]/,
    -        contains: [
    -          hljs.UNDERSCORE_TITLE_MODE,
    -          PARAMS,
    -          {
    -            begin: /->/,
    -            endsWithParent: true,
    -            keywords: KEYWORDS
    -          }
    -        ]
    -      },
    -      {
    -        className: 'meta',
    -        begin: /^[\t ]*@/,
    -        end: /(?=#)|$/,
    -        contains: [
    -          NUMBER,
    -          PARAMS,
    -          STRING
    -        ]
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = python;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/q.js b/claude-code-source/node_modules/highlight.js/lib/languages/q.js
    deleted file mode 100644
    index 0737415d..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/q.js
    +++ /dev/null
    @@ -1,37 +0,0 @@
    -/*
    -Language: Q
    -Description: Q is a vector-based functional paradigm programming language built into the kdb+ database.
    -             (K/Q/Kdb+ from Kx Systems)
    -Author: Sergey Vidyuk 
    -Website: https://kx.com/connect-with-us/developers/
    -*/
    -
    -function q(hljs) {
    -  const KEYWORDS = {
    -    $pattern: /(`?)[A-Za-z0-9_]+\b/,
    -    keyword:
    -      'do while select delete by update from',
    -    literal:
    -      '0b 1b',
    -    built_in:
    -      'neg not null string reciprocal floor ceiling signum mod xbar xlog and or each scan over prior mmu lsq inv md5 ltime gtime count first var dev med cov cor all any rand sums prds mins maxs fills deltas ratios avgs differ prev next rank reverse iasc idesc asc desc msum mcount mavg mdev xrank mmin mmax xprev rotate distinct group where flip type key til get value attr cut set upsert raze union inter except cross sv vs sublist enlist read0 read1 hopen hclose hdel hsym hcount peach system ltrim rtrim trim lower upper ssr view tables views cols xcols keys xkey xcol xasc xdesc fkeys meta lj aj aj0 ij pj asof uj ww wj wj1 fby xgroup ungroup ej save load rsave rload show csv parse eval min max avg wavg wsum sin cos tan sum',
    -    type:
    -      '`float `double int `timestamp `timespan `datetime `time `boolean `symbol `char `byte `short `long `real `month `date `minute `second `guid'
    -  };
    -
    -  return {
    -    name: 'Q',
    -    aliases: [
    -      'k',
    -      'kdb'
    -    ],
    -    keywords: KEYWORDS,
    -    contains: [
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.C_NUMBER_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = q;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/qml.js b/claude-code-source/node_modules/highlight.js/lib/languages/qml.js
    deleted file mode 100644
    index 57b109d5..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/qml.js
    +++ /dev/null
    @@ -1,225 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: QML
    -Requires: javascript.js, xml.js
    -Author: John Foster 
    -Description: Syntax highlighting for the Qt Quick QML scripting language, based mostly off
    -             the JavaScript parser.
    -Website: https://doc.qt.io/qt-5/qmlapplications.html
    -Category: scripting
    -*/
    -
    -function qml(hljs) {
    -  const KEYWORDS = {
    -    keyword:
    -      'in of on if for while finally var new function do return void else break catch ' +
    -      'instanceof with throw case default try this switch continue typeof delete ' +
    -      'let yield const export super debugger as async await import',
    -    literal:
    -      'true false null undefined NaN Infinity',
    -    built_in:
    -      'eval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent ' +
    -      'encodeURI encodeURIComponent escape unescape Object Function Boolean Error ' +
    -      'EvalError InternalError RangeError ReferenceError StopIteration SyntaxError ' +
    -      'TypeError URIError Number Math Date String RegExp Array Float32Array ' +
    -      'Float64Array Int16Array Int32Array Int8Array Uint16Array Uint32Array ' +
    -      'Uint8Array Uint8ClampedArray ArrayBuffer DataView JSON Intl arguments require ' +
    -      'module console window document Symbol Set Map WeakSet WeakMap Proxy Reflect ' +
    -      'Behavior bool color coordinate date double enumeration font geocircle georectangle ' +
    -      'geoshape int list matrix4x4 parent point quaternion real rect ' +
    -      'size string url variant vector2d vector3d vector4d ' +
    -      'Promise'
    -  };
    -
    -  const QML_IDENT_RE = '[a-zA-Z_][a-zA-Z0-9\\._]*';
    -
    -  // Isolate property statements. Ends at a :, =, ;, ,, a comment or end of line.
    -  // Use property class.
    -  const PROPERTY = {
    -    className: 'keyword',
    -    begin: '\\bproperty\\b',
    -    starts: {
    -      className: 'string',
    -      end: '(:|=|;|,|//|/\\*|$)',
    -      returnEnd: true
    -    }
    -  };
    -
    -  // Isolate signal statements. Ends at a ) a comment or end of line.
    -  // Use property class.
    -  const SIGNAL = {
    -    className: 'keyword',
    -    begin: '\\bsignal\\b',
    -    starts: {
    -      className: 'string',
    -      end: '(\\(|:|=|;|,|//|/\\*|$)',
    -      returnEnd: true
    -    }
    -  };
    -
    -  // id: is special in QML. When we see id: we want to mark the id: as attribute and
    -  // emphasize the token following.
    -  const ID_ID = {
    -    className: 'attribute',
    -    begin: '\\bid\\s*:',
    -    starts: {
    -      className: 'string',
    -      end: QML_IDENT_RE,
    -      returnEnd: false
    -    }
    -  };
    -
    -  // Find QML object attribute. An attribute is a QML identifier followed by :.
    -  // Unfortunately it's hard to know where it ends, as it may contain scalars,
    -  // objects, object definitions, or javascript. The true end is either when the parent
    -  // ends or the next attribute is detected.
    -  const QML_ATTRIBUTE = {
    -    begin: QML_IDENT_RE + '\\s*:',
    -    returnBegin: true,
    -    contains: [
    -      {
    -        className: 'attribute',
    -        begin: QML_IDENT_RE,
    -        end: '\\s*:',
    -        excludeEnd: true,
    -        relevance: 0
    -      }
    -    ],
    -    relevance: 0
    -  };
    -
    -  // Find QML object. A QML object is a QML identifier followed by { and ends at the matching }.
    -  // All we really care about is finding IDENT followed by { and just mark up the IDENT and ignore the {.
    -  const QML_OBJECT = {
    -    begin: concat(QML_IDENT_RE, /\s*\{/),
    -    end: /\{/,
    -    returnBegin: true,
    -    relevance: 0,
    -    contains: [
    -      hljs.inherit(hljs.TITLE_MODE, {
    -        begin: QML_IDENT_RE
    -      })
    -    ]
    -  };
    -
    -  return {
    -    name: 'QML',
    -    aliases: [ 'qt' ],
    -    case_insensitive: false,
    -    keywords: KEYWORDS,
    -    contains: [
    -      {
    -        className: 'meta',
    -        begin: /^\s*['"]use (strict|asm)['"]/
    -      },
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      { // template string
    -        className: 'string',
    -        begin: '`',
    -        end: '`',
    -        contains: [
    -          hljs.BACKSLASH_ESCAPE,
    -          {
    -            className: 'subst',
    -            begin: '\\$\\{',
    -            end: '\\}'
    -          }
    -        ]
    -      },
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      {
    -        className: 'number',
    -        variants: [
    -          {
    -            begin: '\\b(0[bB][01]+)'
    -          },
    -          {
    -            begin: '\\b(0[oO][0-7]+)'
    -          },
    -          {
    -            begin: hljs.C_NUMBER_RE
    -          }
    -        ],
    -        relevance: 0
    -      },
    -      { // "value" container
    -        begin: '(' + hljs.RE_STARTERS_RE + '|\\b(case|return|throw)\\b)\\s*',
    -        keywords: 'return throw case',
    -        contains: [
    -          hljs.C_LINE_COMMENT_MODE,
    -          hljs.C_BLOCK_COMMENT_MODE,
    -          hljs.REGEXP_MODE,
    -          { // E4X / JSX
    -            begin: /\s*[);\]]/,
    -            relevance: 0,
    -            subLanguage: 'xml'
    -          }
    -        ],
    -        relevance: 0
    -      },
    -      SIGNAL,
    -      PROPERTY,
    -      {
    -        className: 'function',
    -        beginKeywords: 'function',
    -        end: /\{/,
    -        excludeEnd: true,
    -        contains: [
    -          hljs.inherit(hljs.TITLE_MODE, {
    -            begin: /[A-Za-z$_][0-9A-Za-z$_]*/
    -          }),
    -          {
    -            className: 'params',
    -            begin: /\(/,
    -            end: /\)/,
    -            excludeBegin: true,
    -            excludeEnd: true,
    -            contains: [
    -              hljs.C_LINE_COMMENT_MODE,
    -              hljs.C_BLOCK_COMMENT_MODE
    -            ]
    -          }
    -        ],
    -        illegal: /\[|%/
    -      },
    -      {
    -        // hack: prevents detection of keywords after dots
    -        begin: '\\.' + hljs.IDENT_RE,
    -        relevance: 0
    -      },
    -      ID_ID,
    -      QML_ATTRIBUTE,
    -      QML_OBJECT
    -    ],
    -    illegal: /#/
    -  };
    -}
    -
    -module.exports = qml;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/r.js b/claude-code-source/node_modules/highlight.js/lib/languages/r.js
    deleted file mode 100644
    index d6444e08..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/r.js
    +++ /dev/null
    @@ -1,231 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function lookahead(re) {
    -  return concat('(?=', re, ')');
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: R
    -Description: R is a free software environment for statistical computing and graphics.
    -Author: Joe Cheng 
    -Contributors: Konrad Rudolph 
    -Website: https://www.r-project.org
    -Category: common,scientific
    -*/
    -
    -/** @type LanguageFn */
    -function r(hljs) {
    -  // Identifiers in R cannot start with `_`, but they can start with `.` if it
    -  // is not immediately followed by a digit.
    -  // R also supports quoted identifiers, which are near-arbitrary sequences
    -  // delimited by backticks (`…`), which may contain escape sequences. These are
    -  // handled in a separate mode. See `test/markup/r/names.txt` for examples.
    -  // FIXME: Support Unicode identifiers.
    -  const IDENT_RE = /(?:(?:[a-zA-Z]|\.[._a-zA-Z])[._a-zA-Z0-9]*)|\.(?!\d)/;
    -  const SIMPLE_IDENT = /[a-zA-Z][a-zA-Z_0-9]*/;
    -
    -  return {
    -    name: 'R',
    -
    -    // only in Haskell, not R
    -    illegal: /->/,
    -    keywords: {
    -      $pattern: IDENT_RE,
    -      keyword:
    -        'function if in break next repeat else for while',
    -      literal:
    -        'NULL NA TRUE FALSE Inf NaN NA_integer_|10 NA_real_|10 ' +
    -        'NA_character_|10 NA_complex_|10',
    -      built_in:
    -        // Builtin constants
    -        'LETTERS letters month.abb month.name pi T F ' +
    -        // Primitive functions
    -        // These are all the functions in `base` that are implemented as a
    -        // `.Primitive`, minus those functions that are also keywords.
    -        'abs acos acosh all any anyNA Arg as.call as.character ' +
    -        'as.complex as.double as.environment as.integer as.logical ' +
    -        'as.null.default as.numeric as.raw asin asinh atan atanh attr ' +
    -        'attributes baseenv browser c call ceiling class Conj cos cosh ' +
    -        'cospi cummax cummin cumprod cumsum digamma dim dimnames ' +
    -        'emptyenv exp expression floor forceAndCall gamma gc.time ' +
    -        'globalenv Im interactive invisible is.array is.atomic is.call ' +
    -        'is.character is.complex is.double is.environment is.expression ' +
    -        'is.finite is.function is.infinite is.integer is.language ' +
    -        'is.list is.logical is.matrix is.na is.name is.nan is.null ' +
    -        'is.numeric is.object is.pairlist is.raw is.recursive is.single ' +
    -        'is.symbol lazyLoadDBfetch length lgamma list log max min ' +
    -        'missing Mod names nargs nzchar oldClass on.exit pos.to.env ' +
    -        'proc.time prod quote range Re rep retracemem return round ' +
    -        'seq_along seq_len seq.int sign signif sin sinh sinpi sqrt ' +
    -        'standardGeneric substitute sum switch tan tanh tanpi tracemem ' +
    -        'trigamma trunc unclass untracemem UseMethod xtfrm',
    -    },
    -    compilerExtensions: [
    -      // allow beforeMatch to act as a "qualifier" for the match
    -      // the full match begin must be [beforeMatch][begin]
    -      (mode, parent) => {
    -        if (!mode.beforeMatch) return;
    -        // starts conflicts with endsParent which we need to make sure the child
    -        // rule is not matched multiple times
    -        if (mode.starts) throw new Error("beforeMatch cannot be used with starts");
    -
    -        const originalMode = Object.assign({}, mode);
    -        Object.keys(mode).forEach((key) => { delete mode[key]; });
    -
    -        mode.begin = concat(originalMode.beforeMatch, lookahead(originalMode.begin));
    -        mode.starts = {
    -          relevance: 0,
    -          contains: [
    -            Object.assign(originalMode, { endsParent: true })
    -          ]
    -        };
    -        mode.relevance = 0;
    -
    -        delete originalMode.beforeMatch;
    -      }
    -    ],
    -    contains: [
    -      // Roxygen comments
    -      hljs.COMMENT(
    -        /#'/,
    -        /$/,
    -        {
    -          contains: [
    -            {
    -              // Handle `@examples` separately to cause all subsequent code
    -              // until the next `@`-tag on its own line to be kept as-is,
    -              // preventing highlighting. This code is example R code, so nested
    -              // doctags shouldn’t be treated as such. See
    -              // `test/markup/r/roxygen.txt` for an example.
    -              className: 'doctag',
    -              begin: '@examples',
    -              starts: {
    -                contains: [
    -                  { begin: /\n/ },
    -                  {
    -                    begin: /#'\s*(?=@[a-zA-Z]+)/,
    -                    endsParent: true,
    -                  },
    -                  {
    -                    begin: /#'/,
    -                    end: /$/,
    -                    excludeBegin: true,
    -                  }
    -                ]
    -              }
    -            },
    -            {
    -              // Handle `@param` to highlight the parameter name following
    -              // after.
    -              className: 'doctag',
    -              begin: '@param',
    -              end: /$/,
    -              contains: [
    -                {
    -                  className: 'variable',
    -                  variants: [
    -                    { begin: IDENT_RE },
    -                    { begin: /`(?:\\.|[^`\\])+`/ }
    -                  ],
    -                  endsParent: true
    -                }
    -              ]
    -            },
    -            {
    -              className: 'doctag',
    -              begin: /@[a-zA-Z]+/
    -            },
    -            {
    -              className: 'meta-keyword',
    -              begin: /\\[a-zA-Z]+/,
    -            }
    -          ]
    -        }
    -      ),
    -
    -      hljs.HASH_COMMENT_MODE,
    -
    -      {
    -        className: 'string',
    -        contains: [hljs.BACKSLASH_ESCAPE],
    -        variants: [
    -          hljs.END_SAME_AS_BEGIN({ begin: /[rR]"(-*)\(/, end: /\)(-*)"/ }),
    -          hljs.END_SAME_AS_BEGIN({ begin: /[rR]"(-*)\{/, end: /\}(-*)"/ }),
    -          hljs.END_SAME_AS_BEGIN({ begin: /[rR]"(-*)\[/, end: /\](-*)"/ }),
    -          hljs.END_SAME_AS_BEGIN({ begin: /[rR]'(-*)\(/, end: /\)(-*)'/ }),
    -          hljs.END_SAME_AS_BEGIN({ begin: /[rR]'(-*)\{/, end: /\}(-*)'/ }),
    -          hljs.END_SAME_AS_BEGIN({ begin: /[rR]'(-*)\[/, end: /\](-*)'/ }),
    -          {begin: '"', end: '"', relevance: 0},
    -          {begin: "'", end: "'", relevance: 0}
    -        ],
    -      },
    -      {
    -        className: 'number',
    -        relevance: 0,
    -        beforeMatch: /([^a-zA-Z0-9._])/, // not part of an identifier
    -        variants: [
    -          // TODO: replace with negative look-behind when available
    -          // { begin: /(?
    -Category: functional
    -*/
    -function reasonml(hljs) {
    -  function orReValues(ops) {
    -    return ops
    -      .map(function(op) {
    -        return op
    -          .split('')
    -          .map(function(char) {
    -            return '\\' + char;
    -          })
    -          .join('');
    -      })
    -      .join('|');
    -  }
    -
    -  const RE_IDENT = '~?[a-z$_][0-9a-zA-Z$_]*';
    -  const RE_MODULE_IDENT = '`?[A-Z$_][0-9a-zA-Z$_]*';
    -
    -  const RE_PARAM_TYPEPARAM = '\'?[a-z$_][0-9a-z$_]*';
    -  const RE_PARAM_TYPE = '\\s*:\\s*[a-z$_][0-9a-z$_]*(\\(\\s*(' + RE_PARAM_TYPEPARAM + '\\s*(,' + RE_PARAM_TYPEPARAM + '\\s*)*)?\\))?';
    -  const RE_PARAM = RE_IDENT + '(' + RE_PARAM_TYPE + '){0,2}';
    -  const RE_OPERATOR = "(" + orReValues([
    -    '||',
    -    '++',
    -    '**',
    -    '+.',
    -    '*',
    -    '/',
    -    '*.',
    -    '/.',
    -    '...'
    -  ]) + "|\\|>|&&|==|===)";
    -  const RE_OPERATOR_SPACED = "\\s+" + RE_OPERATOR + "\\s+";
    -
    -  const KEYWORDS = {
    -    keyword:
    -      'and as asr assert begin class constraint do done downto else end exception external ' +
    -      'for fun function functor if in include inherit initializer ' +
    -      'land lazy let lor lsl lsr lxor match method mod module mutable new nonrec ' +
    -      'object of open or private rec sig struct then to try type val virtual when while with',
    -    built_in:
    -      'array bool bytes char exn|5 float int int32 int64 list lazy_t|5 nativeint|5 ref string unit ',
    -    literal:
    -      'true false'
    -  };
    -
    -  const RE_NUMBER = '\\b(0[xX][a-fA-F0-9_]+[Lln]?|' +
    -    '0[oO][0-7_]+[Lln]?|' +
    -    '0[bB][01_]+[Lln]?|' +
    -    '[0-9][0-9_]*([Lln]|(\\.[0-9_]*)?([eE][-+]?[0-9_]+)?)?)';
    -
    -  const NUMBER_MODE = {
    -    className: 'number',
    -    relevance: 0,
    -    variants: [
    -      {
    -        begin: RE_NUMBER
    -      },
    -      {
    -        begin: '\\(-' + RE_NUMBER + '\\)'
    -      }
    -    ]
    -  };
    -
    -  const OPERATOR_MODE = {
    -    className: 'operator',
    -    relevance: 0,
    -    begin: RE_OPERATOR
    -  };
    -  const LIST_CONTENTS_MODES = [
    -    {
    -      className: 'identifier',
    -      relevance: 0,
    -      begin: RE_IDENT
    -    },
    -    OPERATOR_MODE,
    -    NUMBER_MODE
    -  ];
    -
    -  const MODULE_ACCESS_CONTENTS = [
    -    hljs.QUOTE_STRING_MODE,
    -    OPERATOR_MODE,
    -    {
    -      className: 'module',
    -      begin: "\\b" + RE_MODULE_IDENT,
    -      returnBegin: true,
    -      end: "\.",
    -      contains: [
    -        {
    -          className: 'identifier',
    -          begin: RE_MODULE_IDENT,
    -          relevance: 0
    -        }
    -      ]
    -    }
    -  ];
    -
    -  const PARAMS_CONTENTS = [
    -    {
    -      className: 'module',
    -      begin: "\\b" + RE_MODULE_IDENT,
    -      returnBegin: true,
    -      end: "\.",
    -      relevance: 0,
    -      contains: [
    -        {
    -          className: 'identifier',
    -          begin: RE_MODULE_IDENT,
    -          relevance: 0
    -        }
    -      ]
    -    }
    -  ];
    -
    -  const PARAMS_MODE = {
    -    begin: RE_IDENT,
    -    end: '(,|\\n|\\))',
    -    relevance: 0,
    -    contains: [
    -      OPERATOR_MODE,
    -      {
    -        className: 'typing',
    -        begin: ':',
    -        end: '(,|\\n)',
    -        returnBegin: true,
    -        relevance: 0,
    -        contains: PARAMS_CONTENTS
    -      }
    -    ]
    -  };
    -
    -  const FUNCTION_BLOCK_MODE = {
    -    className: 'function',
    -    relevance: 0,
    -    keywords: KEYWORDS,
    -    variants: [
    -      {
    -        begin: '\\s(\\(\\.?.*?\\)|' + RE_IDENT + ')\\s*=>',
    -        end: '\\s*=>',
    -        returnBegin: true,
    -        relevance: 0,
    -        contains: [
    -          {
    -            className: 'params',
    -            variants: [
    -              {
    -                begin: RE_IDENT
    -              },
    -              {
    -                begin: RE_PARAM
    -              },
    -              {
    -                begin: /\(\s*\)/
    -              }
    -            ]
    -          }
    -        ]
    -      },
    -      {
    -        begin: '\\s\\(\\.?[^;\\|]*\\)\\s*=>',
    -        end: '\\s=>',
    -        returnBegin: true,
    -        relevance: 0,
    -        contains: [
    -          {
    -            className: 'params',
    -            relevance: 0,
    -            variants: [ PARAMS_MODE ]
    -          }
    -        ]
    -      },
    -      {
    -        begin: '\\(\\.\\s' + RE_IDENT + '\\)\\s*=>'
    -      }
    -    ]
    -  };
    -  MODULE_ACCESS_CONTENTS.push(FUNCTION_BLOCK_MODE);
    -
    -  const CONSTRUCTOR_MODE = {
    -    className: 'constructor',
    -    begin: RE_MODULE_IDENT + '\\(',
    -    end: '\\)',
    -    illegal: '\\n',
    -    keywords: KEYWORDS,
    -    contains: [
    -      hljs.QUOTE_STRING_MODE,
    -      OPERATOR_MODE,
    -      {
    -        className: 'params',
    -        begin: '\\b' + RE_IDENT
    -      }
    -    ]
    -  };
    -
    -  const PATTERN_MATCH_BLOCK_MODE = {
    -    className: 'pattern-match',
    -    begin: '\\|',
    -    returnBegin: true,
    -    keywords: KEYWORDS,
    -    end: '=>',
    -    relevance: 0,
    -    contains: [
    -      CONSTRUCTOR_MODE,
    -      OPERATOR_MODE,
    -      {
    -        relevance: 0,
    -        className: 'constructor',
    -        begin: RE_MODULE_IDENT
    -      }
    -    ]
    -  };
    -
    -  const MODULE_ACCESS_MODE = {
    -    className: 'module-access',
    -    keywords: KEYWORDS,
    -    returnBegin: true,
    -    variants: [
    -      {
    -        begin: "\\b(" + RE_MODULE_IDENT + "\\.)+" + RE_IDENT
    -      },
    -      {
    -        begin: "\\b(" + RE_MODULE_IDENT + "\\.)+\\(",
    -        end: "\\)",
    -        returnBegin: true,
    -        contains: [
    -          FUNCTION_BLOCK_MODE,
    -          {
    -            begin: '\\(',
    -            end: '\\)',
    -            skip: true
    -          }
    -        ].concat(MODULE_ACCESS_CONTENTS)
    -      },
    -      {
    -        begin: "\\b(" + RE_MODULE_IDENT + "\\.)+\\{",
    -        end: /\}/
    -      }
    -    ],
    -    contains: MODULE_ACCESS_CONTENTS
    -  };
    -
    -  PARAMS_CONTENTS.push(MODULE_ACCESS_MODE);
    -
    -  return {
    -    name: 'ReasonML',
    -    aliases: [ 're' ],
    -    keywords: KEYWORDS,
    -    illegal: '(:-|:=|\\$\\{|\\+=)',
    -    contains: [
    -      hljs.COMMENT('/\\*', '\\*/', {
    -        illegal: '^(#,\\/\\/)'
    -      }),
    -      {
    -        className: 'character',
    -        begin: '\'(\\\\[^\']+|[^\'])\'',
    -        illegal: '\\n',
    -        relevance: 0
    -      },
    -      hljs.QUOTE_STRING_MODE,
    -      {
    -        className: 'literal',
    -        begin: '\\(\\)',
    -        relevance: 0
    -      },
    -      {
    -        className: 'literal',
    -        begin: '\\[\\|',
    -        end: '\\|\\]',
    -        relevance: 0,
    -        contains: LIST_CONTENTS_MODES
    -      },
    -      {
    -        className: 'literal',
    -        begin: '\\[',
    -        end: '\\]',
    -        relevance: 0,
    -        contains: LIST_CONTENTS_MODES
    -      },
    -      CONSTRUCTOR_MODE,
    -      {
    -        className: 'operator',
    -        begin: RE_OPERATOR_SPACED,
    -        illegal: '-->',
    -        relevance: 0
    -      },
    -      NUMBER_MODE,
    -      hljs.C_LINE_COMMENT_MODE,
    -      PATTERN_MATCH_BLOCK_MODE,
    -      FUNCTION_BLOCK_MODE,
    -      {
    -        className: 'module-def',
    -        begin: "\\bmodule\\s+" + RE_IDENT + "\\s+" + RE_MODULE_IDENT + "\\s+=\\s+\\{",
    -        end: /\}/,
    -        returnBegin: true,
    -        keywords: KEYWORDS,
    -        relevance: 0,
    -        contains: [
    -          {
    -            className: 'module',
    -            relevance: 0,
    -            begin: RE_MODULE_IDENT
    -          },
    -          {
    -            begin: /\{/,
    -            end: /\}/,
    -            skip: true
    -          }
    -        ].concat(MODULE_ACCESS_CONTENTS)
    -      },
    -      MODULE_ACCESS_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = reasonml;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/rib.js b/claude-code-source/node_modules/highlight.js/lib/languages/rib.js
    deleted file mode 100644
    index f1d0f4a4..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/rib.js
    +++ /dev/null
    @@ -1,37 +0,0 @@
    -/*
    -Language: RenderMan RIB
    -Author: Konstantin Evdokimenko 
    -Contributors: Shuen-Huei Guan 
    -Website: https://renderman.pixar.com/resources/RenderMan_20/ribBinding.html
    -Category: graphics
    -*/
    -
    -function rib(hljs) {
    -  return {
    -    name: 'RenderMan RIB',
    -    keywords:
    -      'ArchiveRecord AreaLightSource Atmosphere Attribute AttributeBegin AttributeEnd Basis ' +
    -      'Begin Blobby Bound Clipping ClippingPlane Color ColorSamples ConcatTransform Cone ' +
    -      'CoordinateSystem CoordSysTransform CropWindow Curves Cylinder DepthOfField Detail ' +
    -      'DetailRange Disk Displacement Display End ErrorHandler Exposure Exterior Format ' +
    -      'FrameAspectRatio FrameBegin FrameEnd GeneralPolygon GeometricApproximation Geometry ' +
    -      'Hider Hyperboloid Identity Illuminate Imager Interior LightSource ' +
    -      'MakeCubeFaceEnvironment MakeLatLongEnvironment MakeShadow MakeTexture Matte ' +
    -      'MotionBegin MotionEnd NuPatch ObjectBegin ObjectEnd ObjectInstance Opacity Option ' +
    -      'Orientation Paraboloid Patch PatchMesh Perspective PixelFilter PixelSamples ' +
    -      'PixelVariance Points PointsGeneralPolygons PointsPolygons Polygon Procedural Projection ' +
    -      'Quantize ReadArchive RelativeDetail ReverseOrientation Rotate Scale ScreenWindow ' +
    -      'ShadingInterpolation ShadingRate Shutter Sides Skew SolidBegin SolidEnd Sphere ' +
    -      'SubdivisionMesh Surface TextureCoordinates Torus Transform TransformBegin TransformEnd ' +
    -      'TransformPoints Translate TrimCurve WorldBegin WorldEnd',
    -    illegal: '
    -Description: Syntax highlighting for Roboconf's DSL
    -Website: http://roboconf.net
    -Category: config
    -*/
    -
    -function roboconf(hljs) {
    -  const IDENTIFIER = '[a-zA-Z-_][^\\n{]+\\{';
    -
    -  const PROPERTY = {
    -    className: 'attribute',
    -    begin: /[a-zA-Z-_]+/,
    -    end: /\s*:/,
    -    excludeEnd: true,
    -    starts: {
    -      end: ';',
    -      relevance: 0,
    -      contains: [
    -        {
    -          className: 'variable',
    -          begin: /\.[a-zA-Z-_]+/
    -        },
    -        {
    -          className: 'keyword',
    -          begin: /\(optional\)/
    -        }
    -      ]
    -    }
    -  };
    -
    -  return {
    -    name: 'Roboconf',
    -    aliases: [
    -      'graph',
    -      'instances'
    -    ],
    -    case_insensitive: true,
    -    keywords: 'import',
    -    contains: [
    -      // Facet sections
    -      {
    -        begin: '^facet ' + IDENTIFIER,
    -        end: /\}/,
    -        keywords: 'facet',
    -        contains: [
    -          PROPERTY,
    -          hljs.HASH_COMMENT_MODE
    -        ]
    -      },
    -
    -      // Instance sections
    -      {
    -        begin: '^\\s*instance of ' + IDENTIFIER,
    -        end: /\}/,
    -        keywords: 'name count channels instance-data instance-state instance of',
    -        illegal: /\S/,
    -        contains: [
    -          'self',
    -          PROPERTY,
    -          hljs.HASH_COMMENT_MODE
    -        ]
    -      },
    -
    -      // Component sections
    -      {
    -        begin: '^' + IDENTIFIER,
    -        end: /\}/,
    -        contains: [
    -          PROPERTY,
    -          hljs.HASH_COMMENT_MODE
    -        ]
    -      },
    -
    -      // Comments
    -      hljs.HASH_COMMENT_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = roboconf;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/routeros.js b/claude-code-source/node_modules/highlight.js/lib/languages/routeros.js
    deleted file mode 100644
    index f4a8d498..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/routeros.js
    +++ /dev/null
    @@ -1,172 +0,0 @@
    -/*
    -Language: Microtik RouterOS script
    -Author: Ivan Dementev 
    -Description: Scripting host provides a way to automate some router maintenance tasks by means of executing user-defined scripts bounded to some event occurrence
    -Website: https://wiki.mikrotik.com/wiki/Manual:Scripting
    -*/
    -
    -// Colors from RouterOS terminal:
    -//   green        - #0E9A00
    -//   teal         - #0C9A9A
    -//   purple       - #99069A
    -//   light-brown  - #9A9900
    -
    -function routeros(hljs) {
    -  const STATEMENTS = 'foreach do while for if from to step else on-error and or not in';
    -
    -  // Global commands: Every global command should start with ":" token, otherwise it will be treated as variable.
    -  const GLOBAL_COMMANDS = 'global local beep delay put len typeof pick log time set find environment terminal error execute parse resolve toarray tobool toid toip toip6 tonum tostr totime';
    -
    -  // Common commands: Following commands available from most sub-menus:
    -  const COMMON_COMMANDS = 'add remove enable disable set get print export edit find run debug error info warning';
    -
    -  const LITERALS = 'true false yes no nothing nil null';
    -
    -  const OBJECTS = 'traffic-flow traffic-generator firewall scheduler aaa accounting address-list address align area bandwidth-server bfd bgp bridge client clock community config connection console customer default dhcp-client dhcp-server discovery dns e-mail ethernet filter firmware gps graphing group hardware health hotspot identity igmp-proxy incoming instance interface ip ipsec ipv6 irq l2tp-server lcd ldp logging mac-server mac-winbox mangle manual mirror mme mpls nat nd neighbor network note ntp ospf ospf-v3 ovpn-server page peer pim ping policy pool port ppp pppoe-client pptp-server prefix profile proposal proxy queue radius resource rip ripng route routing screen script security-profiles server service service-port settings shares smb sms sniffer snmp snooper socks sstp-server system tool tracking type upgrade upnp user-manager users user vlan secret vrrp watchdog web-access wireless pptp pppoe lan wan layer7-protocol lease simple raw';
    -
    -  const VAR = {
    -    className: 'variable',
    -    variants: [
    -      {
    -        begin: /\$[\w\d#@][\w\d_]*/
    -      },
    -      {
    -        begin: /\$\{(.*?)\}/
    -      }
    -    ]
    -  };
    -
    -  const QUOTE_STRING = {
    -    className: 'string',
    -    begin: /"/,
    -    end: /"/,
    -    contains: [
    -      hljs.BACKSLASH_ESCAPE,
    -      VAR,
    -      {
    -        className: 'variable',
    -        begin: /\$\(/,
    -        end: /\)/,
    -        contains: [ hljs.BACKSLASH_ESCAPE ]
    -      }
    -    ]
    -  };
    -
    -  const APOS_STRING = {
    -    className: 'string',
    -    begin: /'/,
    -    end: /'/
    -  };
    -
    -  return {
    -    name: 'Microtik RouterOS script',
    -    aliases: [
    -      'mikrotik'
    -    ],
    -    case_insensitive: true,
    -    keywords: {
    -      $pattern: /:?[\w-]+/,
    -      literal: LITERALS,
    -      keyword: STATEMENTS + ' :' + STATEMENTS.split(' ').join(' :') + ' :' + GLOBAL_COMMANDS.split(' ').join(' :')
    -    },
    -    contains: [
    -      { // illegal syntax
    -        variants: [
    -          { // -- comment
    -            begin: /\/\*/,
    -            end: /\*\//
    -          },
    -          { // Stan comment
    -            begin: /\/\//,
    -            end: /$/
    -          },
    -          { // HTML tags
    -            begin: /<\//,
    -            end: />/
    -          }
    -        ],
    -        illegal: /./
    -      },
    -      hljs.COMMENT('^#', '$'),
    -      QUOTE_STRING,
    -      APOS_STRING,
    -      VAR,
    -      // attribute=value
    -      {
    -        // > is to avoid matches with => in other grammars
    -        begin: /[\w-]+=([^\s{}[\]()>]+)/,
    -        relevance: 0,
    -        returnBegin: true,
    -        contains: [
    -          {
    -            className: 'attribute',
    -            begin: /[^=]+/
    -          },
    -          {
    -            begin: /=/,
    -            endsWithParent: true,
    -            relevance: 0,
    -            contains: [
    -              QUOTE_STRING,
    -              APOS_STRING,
    -              VAR,
    -              {
    -                className: 'literal',
    -                begin: '\\b(' + LITERALS.split(' ').join('|') + ')\\b'
    -              },
    -              {
    -                // Do not format unclassified values. Needed to exclude highlighting of values as built_in.
    -                begin: /("[^"]*"|[^\s{}[\]]+)/
    -              }
    -              /*
    -              {
    -                // IPv4 addresses and subnets
    -                className: 'number',
    -                variants: [
    -                  {begin: IPADDR_wBITMASK+'(,'+IPADDR_wBITMASK+')*'}, //192.168.0.0/24,1.2.3.0/24
    -                  {begin: IPADDR+'-'+IPADDR},       // 192.168.0.1-192.168.0.3
    -                  {begin: IPADDR+'(,'+IPADDR+')*'}, // 192.168.0.1,192.168.0.34,192.168.24.1,192.168.0.1
    -                ]
    -              },
    -              {
    -                // MAC addresses and DHCP Client IDs
    -                className: 'number',
    -                begin: /\b(1:)?([0-9A-Fa-f]{1,2}[:-]){5}([0-9A-Fa-f]){1,2}\b/,
    -              },
    -              */
    -            ]
    -          }
    -        ]
    -      },
    -      {
    -        // HEX values
    -        className: 'number',
    -        begin: /\*[0-9a-fA-F]+/
    -      },
    -      {
    -        begin: '\\b(' + COMMON_COMMANDS.split(' ').join('|') + ')([\\s[(\\]|])',
    -        returnBegin: true,
    -        contains: [
    -          {
    -            className: 'builtin-name', // 'function',
    -            begin: /\w+/
    -          }
    -        ]
    -      },
    -      {
    -        className: 'built_in',
    -        variants: [
    -          {
    -            begin: '(\\.\\./|/|\\s)((' + OBJECTS.split(' ').join('|') + ');?\\s)+'
    -          },
    -          {
    -            begin: /\.\./,
    -            relevance: 0
    -          }
    -        ]
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = routeros;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/rsl.js b/claude-code-source/node_modules/highlight.js/lib/languages/rsl.js
    deleted file mode 100644
    index 2e1983c6..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/rsl.js
    +++ /dev/null
    @@ -1,49 +0,0 @@
    -/*
    -Language: RenderMan RSL
    -Author: Konstantin Evdokimenko 
    -Contributors: Shuen-Huei Guan 
    -Website: https://renderman.pixar.com/resources/RenderMan_20/shadingLanguage.html
    -Category: graphics
    -*/
    -
    -function rsl(hljs) {
    -  return {
    -    name: 'RenderMan RSL',
    -    keywords: {
    -      keyword:
    -        'float color point normal vector matrix while for if do return else break extern continue',
    -      built_in:
    -        'abs acos ambient area asin atan atmosphere attribute calculatenormal ceil cellnoise ' +
    -        'clamp comp concat cos degrees depth Deriv diffuse distance Du Dv environment exp ' +
    -        'faceforward filterstep floor format fresnel incident length lightsource log match ' +
    -        'max min mod noise normalize ntransform opposite option phong pnoise pow printf ' +
    -        'ptlined radians random reflect refract renderinfo round setcomp setxcomp setycomp ' +
    -        'setzcomp shadow sign sin smoothstep specular specularbrdf spline sqrt step tan ' +
    -        'texture textureinfo trace transform vtransform xcomp ycomp zcomp'
    -    },
    -    illegal: ' source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: Ruby
    -Description: Ruby is a dynamic, open source programming language with a focus on simplicity and productivity.
    -Website: https://www.ruby-lang.org/
    -Author: Anton Kovalyov 
    -Contributors: Peter Leonov , Vasily Polovnyov , Loren Segal , Pascal Hurni , Cedric Sohrauer 
    -Category: common
    -*/
    -
    -function ruby(hljs) {
    -  const RUBY_METHOD_RE = '([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)';
    -  const RUBY_KEYWORDS = {
    -    keyword:
    -      'and then defined module in return redo if BEGIN retry end for self when ' +
    -      'next until do begin unless END rescue else break undef not super class case ' +
    -      'require yield alias while ensure elsif or include attr_reader attr_writer attr_accessor ' +
    -      '__FILE__',
    -    built_in: 'proc lambda',
    -    literal:
    -      'true false nil'
    -  };
    -  const YARDOCTAG = {
    -    className: 'doctag',
    -    begin: '@[A-Za-z]+'
    -  };
    -  const IRB_OBJECT = {
    -    begin: '#<',
    -    end: '>'
    -  };
    -  const COMMENT_MODES = [
    -    hljs.COMMENT(
    -      '#',
    -      '$',
    -      {
    -        contains: [ YARDOCTAG ]
    -      }
    -    ),
    -    hljs.COMMENT(
    -      '^=begin',
    -      '^=end',
    -      {
    -        contains: [ YARDOCTAG ],
    -        relevance: 10
    -      }
    -    ),
    -    hljs.COMMENT('^__END__', '\\n$')
    -  ];
    -  const SUBST = {
    -    className: 'subst',
    -    begin: /#\{/,
    -    end: /\}/,
    -    keywords: RUBY_KEYWORDS
    -  };
    -  const STRING = {
    -    className: 'string',
    -    contains: [
    -      hljs.BACKSLASH_ESCAPE,
    -      SUBST
    -    ],
    -    variants: [
    -      {
    -        begin: /'/,
    -        end: /'/
    -      },
    -      {
    -        begin: /"/,
    -        end: /"/
    -      },
    -      {
    -        begin: /`/,
    -        end: /`/
    -      },
    -      {
    -        begin: /%[qQwWx]?\(/,
    -        end: /\)/
    -      },
    -      {
    -        begin: /%[qQwWx]?\[/,
    -        end: /\]/
    -      },
    -      {
    -        begin: /%[qQwWx]?\{/,
    -        end: /\}/
    -      },
    -      {
    -        begin: /%[qQwWx]?/
    -      },
    -      {
    -        begin: /%[qQwWx]?\//,
    -        end: /\//
    -      },
    -      {
    -        begin: /%[qQwWx]?%/,
    -        end: /%/
    -      },
    -      {
    -        begin: /%[qQwWx]?-/,
    -        end: /-/
    -      },
    -      {
    -        begin: /%[qQwWx]?\|/,
    -        end: /\|/
    -      },
    -      // in the following expressions, \B in the beginning suppresses recognition of ?-sequences
    -      // where ? is the last character of a preceding identifier, as in: `func?4`
    -      {
    -        begin: /\B\?(\\\d{1,3})/
    -      },
    -      {
    -        begin: /\B\?(\\x[A-Fa-f0-9]{1,2})/
    -      },
    -      {
    -        begin: /\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/
    -      },
    -      {
    -        begin: /\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/
    -      },
    -      {
    -        begin: /\B\?\\(c|C-)[\x20-\x7e]/
    -      },
    -      {
    -        begin: /\B\?\\?\S/
    -      },
    -      { // heredocs
    -        begin: /<<[-~]?'?(\w+)\n(?:[^\n]*\n)*?\s*\1\b/,
    -        returnBegin: true,
    -        contains: [
    -          {
    -            begin: /<<[-~]?'?/
    -          },
    -          hljs.END_SAME_AS_BEGIN({
    -            begin: /(\w+)/,
    -            end: /(\w+)/,
    -            contains: [
    -              hljs.BACKSLASH_ESCAPE,
    -              SUBST
    -            ]
    -          })
    -        ]
    -      }
    -    ]
    -  };
    -
    -  // Ruby syntax is underdocumented, but this grammar seems to be accurate
    -  // as of version 2.7.2 (confirmed with (irb and `Ripper.sexp(...)`)
    -  // https://docs.ruby-lang.org/en/2.7.0/doc/syntax/literals_rdoc.html#label-Numbers
    -  const decimal = '[1-9](_?[0-9])*|0';
    -  const digits = '[0-9](_?[0-9])*';
    -  const NUMBER = {
    -    className: 'number',
    -    relevance: 0,
    -    variants: [
    -      // decimal integer/float, optionally exponential or rational, optionally imaginary
    -      {
    -        begin: `\\b(${decimal})(\\.(${digits}))?([eE][+-]?(${digits})|r)?i?\\b`
    -      },
    -
    -      // explicit decimal/binary/octal/hexadecimal integer,
    -      // optionally rational and/or imaginary
    -      {
    -        begin: "\\b0[dD][0-9](_?[0-9])*r?i?\\b"
    -      },
    -      {
    -        begin: "\\b0[bB][0-1](_?[0-1])*r?i?\\b"
    -      },
    -      {
    -        begin: "\\b0[oO][0-7](_?[0-7])*r?i?\\b"
    -      },
    -      {
    -        begin: "\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b"
    -      },
    -
    -      // 0-prefixed implicit octal integer, optionally rational and/or imaginary
    -      {
    -        begin: "\\b0(_?[0-7])+r?i?\\b"
    -      }
    -    ]
    -  };
    -
    -  const PARAMS = {
    -    className: 'params',
    -    begin: '\\(',
    -    end: '\\)',
    -    endsParent: true,
    -    keywords: RUBY_KEYWORDS
    -  };
    -
    -  const RUBY_DEFAULT_CONTAINS = [
    -    STRING,
    -    {
    -      className: 'class',
    -      beginKeywords: 'class module',
    -      end: '$|;',
    -      illegal: /=/,
    -      contains: [
    -        hljs.inherit(hljs.TITLE_MODE, {
    -          begin: '[A-Za-z_]\\w*(::\\w+)*(\\?|!)?'
    -        }),
    -        {
    -          begin: '<\\s*',
    -          contains: [
    -            {
    -              begin: '(' + hljs.IDENT_RE + '::)?' + hljs.IDENT_RE,
    -              // we already get points for <, we don't need poitns
    -              // for the name also
    -              relevance: 0
    -            }
    -          ]
    -        }
    -      ].concat(COMMENT_MODES)
    -    },
    -    {
    -      className: 'function',
    -      // def method_name(
    -      // def method_name;
    -      // def method_name (end of line)
    -      begin: concat(/def\s+/, lookahead(RUBY_METHOD_RE + "\\s*(\\(|;|$)")),
    -      relevance: 0, // relevance comes from kewords
    -      keywords: "def",
    -      end: '$|;',
    -      contains: [
    -        hljs.inherit(hljs.TITLE_MODE, {
    -          begin: RUBY_METHOD_RE
    -        }),
    -        PARAMS
    -      ].concat(COMMENT_MODES)
    -    },
    -    {
    -      // swallow namespace qualifiers before symbols
    -      begin: hljs.IDENT_RE + '::'
    -    },
    -    {
    -      className: 'symbol',
    -      begin: hljs.UNDERSCORE_IDENT_RE + '(!|\\?)?:',
    -      relevance: 0
    -    },
    -    {
    -      className: 'symbol',
    -      begin: ':(?!\\s)',
    -      contains: [
    -        STRING,
    -        {
    -          begin: RUBY_METHOD_RE
    -        }
    -      ],
    -      relevance: 0
    -    },
    -    NUMBER,
    -    {
    -      // negative-look forward attemps to prevent false matches like:
    -      // @ident@ or $ident$ that might indicate this is not ruby at all
    -      className: "variable",
    -      begin: '(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])' + `(?![A-Za-z])(?![@$?'])`
    -    },
    -    {
    -      className: 'params',
    -      begin: /\|/,
    -      end: /\|/,
    -      relevance: 0, // this could be a lot of things (in other languages) other than params
    -      keywords: RUBY_KEYWORDS
    -    },
    -    { // regexp container
    -      begin: '(' + hljs.RE_STARTERS_RE + '|unless)\\s*',
    -      keywords: 'unless',
    -      contains: [
    -        {
    -          className: 'regexp',
    -          contains: [
    -            hljs.BACKSLASH_ESCAPE,
    -            SUBST
    -          ],
    -          illegal: /\n/,
    -          variants: [
    -            {
    -              begin: '/',
    -              end: '/[a-z]*'
    -            },
    -            {
    -              begin: /%r\{/,
    -              end: /\}[a-z]*/
    -            },
    -            {
    -              begin: '%r\\(',
    -              end: '\\)[a-z]*'
    -            },
    -            {
    -              begin: '%r!',
    -              end: '![a-z]*'
    -            },
    -            {
    -              begin: '%r\\[',
    -              end: '\\][a-z]*'
    -            }
    -          ]
    -        }
    -      ].concat(IRB_OBJECT, COMMENT_MODES),
    -      relevance: 0
    -    }
    -  ].concat(IRB_OBJECT, COMMENT_MODES);
    -
    -  SUBST.contains = RUBY_DEFAULT_CONTAINS;
    -  PARAMS.contains = RUBY_DEFAULT_CONTAINS;
    -
    -  // >>
    -  // ?>
    -  const SIMPLE_PROMPT = "[>?]>";
    -  // irb(main):001:0>
    -  const DEFAULT_PROMPT = "[\\w#]+\\(\\w+\\):\\d+:\\d+>";
    -  const RVM_PROMPT = "(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>";
    -
    -  const IRB_DEFAULT = [
    -    {
    -      begin: /^\s*=>/,
    -      starts: {
    -        end: '$',
    -        contains: RUBY_DEFAULT_CONTAINS
    -      }
    -    },
    -    {
    -      className: 'meta',
    -      begin: '^(' + SIMPLE_PROMPT + "|" + DEFAULT_PROMPT + '|' + RVM_PROMPT + ')(?=[ ])',
    -      starts: {
    -        end: '$',
    -        contains: RUBY_DEFAULT_CONTAINS
    -      }
    -    }
    -  ];
    -
    -  COMMENT_MODES.unshift(IRB_OBJECT);
    -
    -  return {
    -    name: 'Ruby',
    -    aliases: [
    -      'rb',
    -      'gemspec',
    -      'podspec',
    -      'thor',
    -      'irb'
    -    ],
    -    keywords: RUBY_KEYWORDS,
    -    illegal: /\/\*/,
    -    contains: [
    -      hljs.SHEBANG({
    -        binary: "ruby"
    -      })
    -    ]
    -      .concat(IRB_DEFAULT)
    -      .concat(COMMENT_MODES)
    -      .concat(RUBY_DEFAULT_CONTAINS)
    -  };
    -}
    -
    -module.exports = ruby;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/ruleslanguage.js b/claude-code-source/node_modules/highlight.js/lib/languages/ruleslanguage.js
    deleted file mode 100644
    index f9503eaa..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/ruleslanguage.js
    +++ /dev/null
    @@ -1,78 +0,0 @@
    -/*
    -Language: Oracle Rules Language
    -Author: Jason Jacobson 
    -Description: The Oracle Utilities Rules Language is used to program the Oracle Utilities Applications acquired from LODESTAR Corporation.  The products include Billing Component, LPSS, Pricing Component etc. through version 1.6.1.
    -Website: https://docs.oracle.com/cd/E17904_01/dev.1111/e10227/rlref.htm
    -Category: enterprise
    -*/
    -
    -function ruleslanguage(hljs) {
    -  return {
    -    name: 'Oracle Rules Language',
    -    keywords: {
    -      keyword:
    -        'BILL_PERIOD BILL_START BILL_STOP RS_EFFECTIVE_START RS_EFFECTIVE_STOP RS_JURIS_CODE RS_OPCO_CODE ' +
    -        'INTDADDATTRIBUTE|5 INTDADDVMSG|5 INTDBLOCKOP|5 INTDBLOCKOPNA|5 INTDCLOSE|5 INTDCOUNT|5 ' +
    -        'INTDCOUNTSTATUSCODE|5 INTDCREATEMASK|5 INTDCREATEDAYMASK|5 INTDCREATEFACTORMASK|5 ' +
    -        'INTDCREATEHANDLE|5 INTDCREATEOVERRIDEDAYMASK|5 INTDCREATEOVERRIDEMASK|5 ' +
    -        'INTDCREATESTATUSCODEMASK|5 INTDCREATETOUPERIOD|5 INTDDELETE|5 INTDDIPTEST|5 INTDEXPORT|5 ' +
    -        'INTDGETERRORCODE|5 INTDGETERRORMESSAGE|5 INTDISEQUAL|5 INTDJOIN|5 INTDLOAD|5 INTDLOADACTUALCUT|5 ' +
    -        'INTDLOADDATES|5 INTDLOADHIST|5 INTDLOADLIST|5 INTDLOADLISTDATES|5 INTDLOADLISTENERGY|5 ' +
    -        'INTDLOADLISTHIST|5 INTDLOADRELATEDCHANNEL|5 INTDLOADSP|5 INTDLOADSTAGING|5 INTDLOADUOM|5 ' +
    -        'INTDLOADUOMDATES|5 INTDLOADUOMHIST|5 INTDLOADVERSION|5 INTDOPEN|5 INTDREADFIRST|5 INTDREADNEXT|5 ' +
    -        'INTDRECCOUNT|5 INTDRELEASE|5 INTDREPLACE|5 INTDROLLAVG|5 INTDROLLPEAK|5 INTDSCALAROP|5 INTDSCALE|5 ' +
    -        'INTDSETATTRIBUTE|5 INTDSETDSTPARTICIPANT|5 INTDSETSTRING|5 INTDSETVALUE|5 INTDSETVALUESTATUS|5 ' +
    -        'INTDSHIFTSTARTTIME|5 INTDSMOOTH|5 INTDSORT|5 INTDSPIKETEST|5 INTDSUBSET|5 INTDTOU|5 ' +
    -        'INTDTOURELEASE|5 INTDTOUVALUE|5 INTDUPDATESTATS|5 INTDVALUE|5 STDEV INTDDELETEEX|5 ' +
    -        'INTDLOADEXACTUAL|5 INTDLOADEXCUT|5 INTDLOADEXDATES|5 INTDLOADEX|5 INTDLOADEXRELATEDCHANNEL|5 ' +
    -        'INTDSAVEEX|5 MVLOAD|5 MVLOADACCT|5 MVLOADACCTDATES|5 MVLOADACCTHIST|5 MVLOADDATES|5 MVLOADHIST|5 ' +
    -        'MVLOADLIST|5 MVLOADLISTDATES|5 MVLOADLISTHIST|5 IF FOR NEXT DONE SELECT END CALL ABORT CLEAR CHANNEL FACTOR LIST NUMBER ' +
    -        'OVERRIDE SET WEEK DISTRIBUTIONNODE ELSE WHEN THEN OTHERWISE IENUM CSV INCLUDE LEAVE RIDER SAVE DELETE ' +
    -        'NOVALUE SECTION WARN SAVE_UPDATE DETERMINANT LABEL REPORT REVENUE EACH ' +
    -        'IN FROM TOTAL CHARGE BLOCK AND OR CSV_FILE RATE_CODE AUXILIARY_DEMAND ' +
    -        'UIDACCOUNT RS BILL_PERIOD_SELECT HOURS_PER_MONTH INTD_ERROR_STOP SEASON_SCHEDULE_NAME ' +
    -        'ACCOUNTFACTOR ARRAYUPPERBOUND CALLSTOREDPROC GETADOCONNECTION GETCONNECT GETDATASOURCE ' +
    -        'GETQUALIFIER GETUSERID HASVALUE LISTCOUNT LISTOP LISTUPDATE LISTVALUE PRORATEFACTOR RSPRORATE ' +
    -        'SETBINPATH SETDBMONITOR WQ_OPEN BILLINGHOURS DATE DATEFROMFLOAT DATETIMEFROMSTRING ' +
    -        'DATETIMETOSTRING DATETOFLOAT DAY DAYDIFF DAYNAME DBDATETIME HOUR MINUTE MONTH MONTHDIFF ' +
    -        'MONTHHOURS MONTHNAME ROUNDDATE SAMEWEEKDAYLASTYEAR SECOND WEEKDAY WEEKDIFF YEAR YEARDAY ' +
    -        'YEARSTR COMPSUM HISTCOUNT HISTMAX HISTMIN HISTMINNZ HISTVALUE MAXNRANGE MAXRANGE MINRANGE ' +
    -        'COMPIKVA COMPKVA COMPKVARFROMKQKW COMPLF IDATTR FLAG LF2KW LF2KWH MAXKW POWERFACTOR ' +
    -        'READING2USAGE AVGSEASON MAXSEASON MONTHLYMERGE SEASONVALUE SUMSEASON ACCTREADDATES ' +
    -        'ACCTTABLELOAD CONFIGADD CONFIGGET CREATEOBJECT CREATEREPORT EMAILCLIENT EXPBLKMDMUSAGE ' +
    -        'EXPMDMUSAGE EXPORT_USAGE FACTORINEFFECT GETUSERSPECIFIEDSTOP INEFFECT ISHOLIDAY RUNRATE ' +
    -        'SAVE_PROFILE SETREPORTTITLE USEREXIT WATFORRUNRATE TO TABLE ACOS ASIN ATAN ATAN2 BITAND CEIL ' +
    -        'COS COSECANT COSH COTANGENT DIVQUOT DIVREM EXP FABS FLOOR FMOD FREPM FREXPN LOG LOG10 MAX MAXN ' +
    -        'MIN MINNZ MODF POW ROUND ROUND2VALUE ROUNDINT SECANT SIN SINH SQROOT TAN TANH FLOAT2STRING ' +
    -        'FLOAT2STRINGNC INSTR LEFT LEN LTRIM MID RIGHT RTRIM STRING STRINGNC TOLOWER TOUPPER TRIM ' +
    -        'NUMDAYS READ_DATE STAGING',
    -      built_in:
    -        'IDENTIFIER OPTIONS XML_ELEMENT XML_OP XML_ELEMENT_OF DOMDOCCREATE DOMDOCLOADFILE DOMDOCLOADXML ' +
    -        'DOMDOCSAVEFILE DOMDOCGETROOT DOMDOCADDPI DOMNODEGETNAME DOMNODEGETTYPE DOMNODEGETVALUE DOMNODEGETCHILDCT ' +
    -        'DOMNODEGETFIRSTCHILD DOMNODEGETSIBLING DOMNODECREATECHILDELEMENT DOMNODESETATTRIBUTE ' +
    -        'DOMNODEGETCHILDELEMENTCT DOMNODEGETFIRSTCHILDELEMENT DOMNODEGETSIBLINGELEMENT DOMNODEGETATTRIBUTECT ' +
    -        'DOMNODEGETATTRIBUTEI DOMNODEGETATTRIBUTEBYNAME DOMNODEGETBYNAME'
    -    },
    -    contains: [
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.C_NUMBER_MODE,
    -      {
    -        className: 'literal',
    -        variants: [
    -          { // looks like #-comment
    -            begin: '#\\s+',
    -            relevance: 0
    -          },
    -          {
    -            begin: '#[a-zA-Z .]+'
    -          }
    -        ]
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = ruleslanguage;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/rust.js b/claude-code-source/node_modules/highlight.js/lib/languages/rust.js
    deleted file mode 100644
    index afb2c7e0..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/rust.js
    +++ /dev/null
    @@ -1,146 +0,0 @@
    -/*
    -Language: Rust
    -Author: Andrey Vlasovskikh 
    -Contributors: Roman Shmatov , Kasper Andersen 
    -Website: https://www.rust-lang.org
    -Category: common, system
    -*/
    -
    -function rust(hljs) {
    -  const NUM_SUFFIX = '([ui](8|16|32|64|128|size)|f(32|64))\?';
    -  const KEYWORDS =
    -    'abstract as async await become box break const continue crate do dyn ' +
    -    'else enum extern false final fn for if impl in let loop macro match mod ' +
    -    'move mut override priv pub ref return self Self static struct super ' +
    -    'trait true try type typeof unsafe unsized use virtual where while yield';
    -  const BUILTINS =
    -    // functions
    -    'drop ' +
    -    // types
    -    'i8 i16 i32 i64 i128 isize ' +
    -    'u8 u16 u32 u64 u128 usize ' +
    -    'f32 f64 ' +
    -    'str char bool ' +
    -    'Box Option Result String Vec ' +
    -    // traits
    -    'Copy Send Sized Sync Drop Fn FnMut FnOnce ToOwned Clone Debug ' +
    -    'PartialEq PartialOrd Eq Ord AsRef AsMut Into From Default Iterator ' +
    -    'Extend IntoIterator DoubleEndedIterator ExactSizeIterator ' +
    -    'SliceConcatExt ToString ' +
    -    // macros
    -    'assert! assert_eq! bitflags! bytes! cfg! col! concat! concat_idents! ' +
    -    'debug_assert! debug_assert_eq! env! panic! file! format! format_args! ' +
    -    'include_bin! include_str! line! local_data_key! module_path! ' +
    -    'option_env! print! println! select! stringify! try! unimplemented! ' +
    -    'unreachable! vec! write! writeln! macro_rules! assert_ne! debug_assert_ne!';
    -  return {
    -    name: 'Rust',
    -    aliases: [ 'rs' ],
    -    keywords: {
    -      $pattern: hljs.IDENT_RE + '!?',
    -      keyword:
    -        KEYWORDS,
    -      literal:
    -        'true false Some None Ok Err',
    -      built_in:
    -        BUILTINS
    -    },
    -    illegal: ''
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = rust;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/sas.js b/claude-code-source/node_modules/highlight.js/lib/languages/sas.js
    deleted file mode 100644
    index 1e54ae71..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/sas.js
    +++ /dev/null
    @@ -1,133 +0,0 @@
    -/*
    -Language: SAS
    -Author: Mauricio Caceres 
    -Description: Syntax Highlighting for SAS
    -*/
    -
    -function sas(hljs) {
    -  // Data step and PROC SQL statements
    -  const SAS_KEYWORDS =
    -    'do if then else end until while ' +
    -    '' +
    -    'abort array attrib by call cards cards4 catname continue ' +
    -    'datalines datalines4 delete delim delimiter display dm drop ' +
    -    'endsas error file filename footnote format goto in infile ' +
    -    'informat input keep label leave length libname link list ' +
    -    'lostcard merge missing modify options output out page put ' +
    -    'redirect remove rename replace retain return select set skip ' +
    -    'startsas stop title update waitsas where window x systask ' +
    -    '' +
    -    'add and alter as cascade check create delete describe ' +
    -    'distinct drop foreign from group having index insert into in ' +
    -    'key like message modify msgtype not null on or order primary ' +
    -    'references reset restrict select set table unique update ' +
    -    'validate view where';
    -
    -  // Built-in SAS functions
    -  const SAS_FUN =
    -    'abs|addr|airy|arcos|arsin|atan|attrc|attrn|band|' +
    -    'betainv|blshift|bnot|bor|brshift|bxor|byte|cdf|ceil|' +
    -    'cexist|cinv|close|cnonct|collate|compbl|compound|' +
    -    'compress|cos|cosh|css|curobs|cv|daccdb|daccdbsl|' +
    -    'daccsl|daccsyd|dacctab|dairy|date|datejul|datepart|' +
    -    'datetime|day|dclose|depdb|depdbsl|depdbsl|depsl|' +
    -    'depsl|depsyd|depsyd|deptab|deptab|dequote|dhms|dif|' +
    -    'digamma|dim|dinfo|dnum|dopen|doptname|doptnum|dread|' +
    -    'dropnote|dsname|erf|erfc|exist|exp|fappend|fclose|' +
    -    'fcol|fdelete|fetch|fetchobs|fexist|fget|fileexist|' +
    -    'filename|fileref|finfo|finv|fipname|fipnamel|' +
    -    'fipstate|floor|fnonct|fnote|fopen|foptname|foptnum|' +
    -    'fpoint|fpos|fput|fread|frewind|frlen|fsep|fuzz|' +
    -    'fwrite|gaminv|gamma|getoption|getvarc|getvarn|hbound|' +
    -    'hms|hosthelp|hour|ibessel|index|indexc|indexw|input|' +
    -    'inputc|inputn|int|intck|intnx|intrr|irr|jbessel|' +
    -    'juldate|kurtosis|lag|lbound|left|length|lgamma|' +
    -    'libname|libref|log|log10|log2|logpdf|logpmf|logsdf|' +
    -    'lowcase|max|mdy|mean|min|minute|mod|month|mopen|' +
    -    'mort|n|netpv|nmiss|normal|note|npv|open|ordinal|' +
    -    'pathname|pdf|peek|peekc|pmf|point|poisson|poke|' +
    -    'probbeta|probbnml|probchi|probf|probgam|probhypr|' +
    -    'probit|probnegb|probnorm|probt|put|putc|putn|qtr|' +
    -    'quote|ranbin|rancau|ranexp|rangam|range|rank|rannor|' +
    -    'ranpoi|rantbl|rantri|ranuni|repeat|resolve|reverse|' +
    -    'rewind|right|round|saving|scan|sdf|second|sign|' +
    -    'sin|sinh|skewness|soundex|spedis|sqrt|std|stderr|' +
    -    'stfips|stname|stnamel|substr|sum|symget|sysget|' +
    -    'sysmsg|sysprod|sysrc|system|tan|tanh|time|timepart|' +
    -    'tinv|tnonct|today|translate|tranwrd|trigamma|' +
    -    'trim|trimn|trunc|uniform|upcase|uss|var|varfmt|' +
    -    'varinfmt|varlabel|varlen|varname|varnum|varray|' +
    -    'varrayx|vartype|verify|vformat|vformatd|vformatdx|' +
    -    'vformatn|vformatnx|vformatw|vformatwx|vformatx|' +
    -    'vinarray|vinarrayx|vinformat|vinformatd|vinformatdx|' +
    -    'vinformatn|vinformatnx|vinformatw|vinformatwx|' +
    -    'vinformatx|vlabel|vlabelx|vlength|vlengthx|vname|' +
    -    'vnamex|vtype|vtypex|weekday|year|yyq|zipfips|zipname|' +
    -    'zipnamel|zipstate';
    -
    -  // Built-in macro functions
    -  const SAS_MACRO_FUN =
    -    'bquote|nrbquote|cmpres|qcmpres|compstor|' +
    -    'datatyp|display|do|else|end|eval|global|goto|' +
    -    'if|index|input|keydef|label|left|length|let|' +
    -    'local|lowcase|macro|mend|nrbquote|nrquote|' +
    -    'nrstr|put|qcmpres|qleft|qlowcase|qscan|' +
    -    'qsubstr|qsysfunc|qtrim|quote|qupcase|scan|str|' +
    -    'substr|superq|syscall|sysevalf|sysexec|sysfunc|' +
    -    'sysget|syslput|sysprod|sysrc|sysrput|then|to|' +
    -    'trim|unquote|until|upcase|verify|while|window';
    -
    -  return {
    -    name: 'SAS',
    -    case_insensitive: true, // SAS is case-insensitive
    -    keywords: {
    -      literal:
    -        'null missing _all_ _automatic_ _character_ _infile_ ' +
    -        '_n_ _name_ _null_ _numeric_ _user_ _webout_',
    -      meta:
    -        SAS_KEYWORDS
    -    },
    -    contains: [
    -      {
    -        // Distinct highlight for proc , data, run, quit
    -        className: 'keyword',
    -        begin: /^\s*(proc [\w\d_]+|data|run|quit)[\s;]/
    -      },
    -      {
    -        // Macro variables
    -        className: 'variable',
    -        begin: /&[a-zA-Z_&][a-zA-Z0-9_]*\.?/
    -      },
    -      {
    -        // Special emphasis for datalines|cards
    -        className: 'emphasis',
    -        begin: /^\s*datalines|cards.*;/,
    -        end: /^\s*;\s*$/
    -      },
    -      { // Built-in macro variables take precedence
    -        className: 'built_in',
    -        begin: '%(' + SAS_MACRO_FUN + ')'
    -      },
    -      {
    -        // User-defined macro functions highlighted after
    -        className: 'name',
    -        begin: /%[a-zA-Z_][a-zA-Z_0-9]*/
    -      },
    -      {
    -        className: 'meta',
    -        begin: '[^%](' + SAS_FUN + ')[\(]'
    -      },
    -      {
    -        className: 'string',
    -        variants: [
    -          hljs.APOS_STRING_MODE,
    -          hljs.QUOTE_STRING_MODE
    -        ]
    -      },
    -      hljs.COMMENT('\\*', ';'),
    -      hljs.C_BLOCK_COMMENT_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = sas;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/scala.js b/claude-code-source/node_modules/highlight.js/lib/languages/scala.js
    deleted file mode 100644
    index 712764a3..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/scala.js
    +++ /dev/null
    @@ -1,140 +0,0 @@
    -/*
    -Language: Scala
    -Category: functional
    -Author: Jan Berkel 
    -Contributors: Erik Osheim 
    -Website: https://www.scala-lang.org
    -*/
    -
    -function scala(hljs) {
    -  const ANNOTATION = {
    -    className: 'meta',
    -    begin: '@[A-Za-z]+'
    -  };
    -
    -  // used in strings for escaping/interpolation/substitution
    -  const SUBST = {
    -    className: 'subst',
    -    variants: [
    -      {
    -        begin: '\\$[A-Za-z0-9_]+'
    -      },
    -      {
    -        begin: /\$\{/,
    -        end: /\}/
    -      }
    -    ]
    -  };
    -
    -  const STRING = {
    -    className: 'string',
    -    variants: [
    -      {
    -        begin: '"""',
    -        end: '"""'
    -      },
    -      {
    -        begin: '"',
    -        end: '"',
    -        illegal: '\\n',
    -        contains: [ hljs.BACKSLASH_ESCAPE ]
    -      },
    -      {
    -        begin: '[a-z]+"',
    -        end: '"',
    -        illegal: '\\n',
    -        contains: [
    -          hljs.BACKSLASH_ESCAPE,
    -          SUBST
    -        ]
    -      },
    -      {
    -        className: 'string',
    -        begin: '[a-z]+"""',
    -        end: '"""',
    -        contains: [ SUBST ],
    -        relevance: 10
    -      }
    -    ]
    -
    -  };
    -
    -  const SYMBOL = {
    -    className: 'symbol',
    -    begin: '\'\\w[\\w\\d_]*(?!\')'
    -  };
    -
    -  const TYPE = {
    -    className: 'type',
    -    begin: '\\b[A-Z][A-Za-z0-9_]*',
    -    relevance: 0
    -  };
    -
    -  const NAME = {
    -    className: 'title',
    -    begin: /[^0-9\n\t "'(),.`{}\[\]:;][^\n\t "'(),.`{}\[\]:;]+|[^0-9\n\t "'(),.`{}\[\]:;=]/,
    -    relevance: 0
    -  };
    -
    -  const CLASS = {
    -    className: 'class',
    -    beginKeywords: 'class object trait type',
    -    end: /[:={\[\n;]/,
    -    excludeEnd: true,
    -    contains: [
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      {
    -        beginKeywords: 'extends with',
    -        relevance: 10
    -      },
    -      {
    -        begin: /\[/,
    -        end: /\]/,
    -        excludeBegin: true,
    -        excludeEnd: true,
    -        relevance: 0,
    -        contains: [ TYPE ]
    -      },
    -      {
    -        className: 'params',
    -        begin: /\(/,
    -        end: /\)/,
    -        excludeBegin: true,
    -        excludeEnd: true,
    -        relevance: 0,
    -        contains: [ TYPE ]
    -      },
    -      NAME
    -    ]
    -  };
    -
    -  const METHOD = {
    -    className: 'function',
    -    beginKeywords: 'def',
    -    end: /[:={\[(\n;]/,
    -    excludeEnd: true,
    -    contains: [ NAME ]
    -  };
    -
    -  return {
    -    name: 'Scala',
    -    keywords: {
    -      literal: 'true false null',
    -      keyword: 'type yield lazy override def with val var sealed abstract private trait object if forSome for while throw finally protected extends import final return else break new catch super class case package default try this match continue throws implicit'
    -    },
    -    contains: [
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      STRING,
    -      SYMBOL,
    -      TYPE,
    -      METHOD,
    -      CLASS,
    -      hljs.C_NUMBER_MODE,
    -      ANNOTATION
    -    ]
    -  };
    -}
    -
    -module.exports = scala;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/scheme.js b/claude-code-source/node_modules/highlight.js/lib/languages/scheme.js
    deleted file mode 100644
    index 250d4b31..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/scheme.js
    +++ /dev/null
    @@ -1,207 +0,0 @@
    -/*
    -Language: Scheme
    -Description: Scheme is a programming language in the Lisp family.
    -             (keywords based on http://community.schemewiki.org/?scheme-keywords)
    -Author: JP Verkamp 
    -Contributors: Ivan Sagalaev 
    -Origin: clojure.js
    -Website: http://community.schemewiki.org/?what-is-scheme
    -Category: lisp
    -*/
    -
    -function scheme(hljs) {
    -  const SCHEME_IDENT_RE = '[^\\(\\)\\[\\]\\{\\}",\'`;#|\\\\\\s]+';
    -  const SCHEME_SIMPLE_NUMBER_RE = '(-|\\+)?\\d+([./]\\d+)?';
    -  const SCHEME_COMPLEX_NUMBER_RE = SCHEME_SIMPLE_NUMBER_RE + '[+\\-]' + SCHEME_SIMPLE_NUMBER_RE + 'i';
    -  const KEYWORDS = {
    -    $pattern: SCHEME_IDENT_RE,
    -    'builtin-name':
    -      'case-lambda call/cc class define-class exit-handler field import ' +
    -      'inherit init-field interface let*-values let-values let/ec mixin ' +
    -      'opt-lambda override protect provide public rename require ' +
    -      'require-for-syntax syntax syntax-case syntax-error unit/sig unless ' +
    -      'when with-syntax and begin call-with-current-continuation ' +
    -      'call-with-input-file call-with-output-file case cond define ' +
    -      'define-syntax delay do dynamic-wind else for-each if lambda let let* ' +
    -      'let-syntax letrec letrec-syntax map or syntax-rules \' * + , ,@ - ... / ' +
    -      '; < <= = => > >= ` abs acos angle append apply asin assoc assq assv atan ' +
    -      'boolean? caar cadr call-with-input-file call-with-output-file ' +
    -      'call-with-values car cdddar cddddr cdr ceiling char->integer ' +
    -      'char-alphabetic? char-ci<=? char-ci=? char-ci>? ' +
    -      'char-downcase char-lower-case? char-numeric? char-ready? char-upcase ' +
    -      'char-upper-case? char-whitespace? char<=? char=? char>? ' +
    -      'char? close-input-port close-output-port complex? cons cos ' +
    -      'current-input-port current-output-port denominator display eof-object? ' +
    -      'eq? equal? eqv? eval even? exact->inexact exact? exp expt floor ' +
    -      'force gcd imag-part inexact->exact inexact? input-port? integer->char ' +
    -      'integer? interaction-environment lcm length list list->string ' +
    -      'list->vector list-ref list-tail list? load log magnitude make-polar ' +
    -      'make-rectangular make-string make-vector max member memq memv min ' +
    -      'modulo negative? newline not null-environment null? number->string ' +
    -      'number? numerator odd? open-input-file open-output-file output-port? ' +
    -      'pair? peek-char port? positive? procedure? quasiquote quote quotient ' +
    -      'rational? rationalize read read-char real-part real? remainder reverse ' +
    -      'round scheme-report-environment set! set-car! set-cdr! sin sqrt string ' +
    -      'string->list string->number string->symbol string-append string-ci<=? ' +
    -      'string-ci=? string-ci>? string-copy ' +
    -      'string-fill! string-length string-ref string-set! string<=? string=? string>? string? substring symbol->string symbol? ' +
    -      'tan transcript-off transcript-on truncate values vector ' +
    -      'vector->list vector-fill! vector-length vector-ref vector-set! ' +
    -      'with-input-from-file with-output-to-file write write-char zero?'
    -  };
    -
    -  const LITERAL = {
    -    className: 'literal',
    -    begin: '(#t|#f|#\\\\' + SCHEME_IDENT_RE + '|#\\\\.)'
    -  };
    -
    -  const NUMBER = {
    -    className: 'number',
    -    variants: [
    -      {
    -        begin: SCHEME_SIMPLE_NUMBER_RE,
    -        relevance: 0
    -      },
    -      {
    -        begin: SCHEME_COMPLEX_NUMBER_RE,
    -        relevance: 0
    -      },
    -      {
    -        begin: '#b[0-1]+(/[0-1]+)?'
    -      },
    -      {
    -        begin: '#o[0-7]+(/[0-7]+)?'
    -      },
    -      {
    -        begin: '#x[0-9a-f]+(/[0-9a-f]+)?'
    -      }
    -    ]
    -  };
    -
    -  const STRING = hljs.QUOTE_STRING_MODE;
    -
    -  const COMMENT_MODES = [
    -    hljs.COMMENT(
    -      ';',
    -      '$',
    -      {
    -        relevance: 0
    -      }
    -    ),
    -    hljs.COMMENT('#\\|', '\\|#')
    -  ];
    -
    -  const IDENT = {
    -    begin: SCHEME_IDENT_RE,
    -    relevance: 0
    -  };
    -
    -  const QUOTED_IDENT = {
    -    className: 'symbol',
    -    begin: '\'' + SCHEME_IDENT_RE
    -  };
    -
    -  const BODY = {
    -    endsWithParent: true,
    -    relevance: 0
    -  };
    -
    -  const QUOTED_LIST = {
    -    variants: [
    -      {
    -        begin: /'/
    -      },
    -      {
    -        begin: '`'
    -      }
    -    ],
    -    contains: [
    -      {
    -        begin: '\\(',
    -        end: '\\)',
    -        contains: [
    -          'self',
    -          LITERAL,
    -          STRING,
    -          NUMBER,
    -          IDENT,
    -          QUOTED_IDENT
    -        ]
    -      }
    -    ]
    -  };
    -
    -  const NAME = {
    -    className: 'name',
    -    relevance: 0,
    -    begin: SCHEME_IDENT_RE,
    -    keywords: KEYWORDS
    -  };
    -
    -  const LAMBDA = {
    -    begin: /lambda/,
    -    endsWithParent: true,
    -    returnBegin: true,
    -    contains: [
    -      NAME,
    -      {
    -        endsParent: true,
    -        variants: [
    -          {
    -            begin: /\(/,
    -            end: /\)/
    -          },
    -          {
    -            begin: /\[/,
    -            end: /\]/
    -          }
    -        ],
    -        contains: [ IDENT ]
    -      }
    -    ]
    -  };
    -
    -  const LIST = {
    -    variants: [
    -      {
    -        begin: '\\(',
    -        end: '\\)'
    -      },
    -      {
    -        begin: '\\[',
    -        end: '\\]'
    -      }
    -    ],
    -    contains: [
    -      LAMBDA,
    -      NAME,
    -      BODY
    -    ]
    -  };
    -
    -  BODY.contains = [
    -    LITERAL,
    -    NUMBER,
    -    STRING,
    -    IDENT,
    -    QUOTED_IDENT,
    -    QUOTED_LIST,
    -    LIST
    -  ].concat(COMMENT_MODES);
    -
    -  return {
    -    name: 'Scheme',
    -    illegal: /\S/,
    -    contains: [
    -      hljs.SHEBANG(),
    -      NUMBER,
    -      STRING,
    -      QUOTED_IDENT,
    -      QUOTED_LIST,
    -      LIST
    -    ].concat(COMMENT_MODES)
    -  };
    -}
    -
    -module.exports = scheme;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/scilab.js b/claude-code-source/node_modules/highlight.js/lib/languages/scilab.js
    deleted file mode 100644
    index f9644109..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/scilab.js
    +++ /dev/null
    @@ -1,73 +0,0 @@
    -/*
    -Language: Scilab
    -Author: Sylvestre Ledru 
    -Origin: matlab.js
    -Description: Scilab is a port from Matlab
    -Website: https://www.scilab.org
    -Category: scientific
    -*/
    -
    -function scilab(hljs) {
    -  const COMMON_CONTAINS = [
    -    hljs.C_NUMBER_MODE,
    -    {
    -      className: 'string',
    -      begin: '\'|\"',
    -      end: '\'|\"',
    -      contains: [ hljs.BACKSLASH_ESCAPE,
    -        {
    -          begin: '\'\''
    -        } ]
    -    }
    -  ];
    -
    -  return {
    -    name: 'Scilab',
    -    aliases: [ 'sci' ],
    -    keywords: {
    -      $pattern: /%?\w+/,
    -      keyword: 'abort break case clear catch continue do elseif else endfunction end for function ' +
    -        'global if pause return resume select try then while',
    -      literal:
    -        '%f %F %t %T %pi %eps %inf %nan %e %i %z %s',
    -      built_in: // Scilab has more than 2000 functions. Just list the most commons
    -       'abs and acos asin atan ceil cd chdir clearglobal cosh cos cumprod deff disp error ' +
    -       'exec execstr exists exp eye gettext floor fprintf fread fsolve imag isdef isempty ' +
    -       'isinfisnan isvector lasterror length load linspace list listfiles log10 log2 log ' +
    -       'max min msprintf mclose mopen ones or pathconvert poly printf prod pwd rand real ' +
    -       'round sinh sin size gsort sprintf sqrt strcat strcmps tring sum system tanh tan ' +
    -       'type typename warning zeros matrix'
    -    },
    -    illegal: '("|#|/\\*|\\s+/\\w+)',
    -    contains: [
    -      {
    -        className: 'function',
    -        beginKeywords: 'function',
    -        end: '$',
    -        contains: [
    -          hljs.UNDERSCORE_TITLE_MODE,
    -          {
    -            className: 'params',
    -            begin: '\\(',
    -            end: '\\)'
    -          }
    -        ]
    -      },
    -      // seems to be a guard against [ident]' or [ident].
    -      // perhaps to prevent attributes from flagging as keywords?
    -      {
    -        begin: '[a-zA-Z_][a-zA-Z_0-9]*[\\.\']+',
    -        relevance: 0
    -      },
    -      {
    -        begin: '\\[',
    -        end: '\\][\\.\']*',
    -        relevance: 0,
    -        contains: COMMON_CONTAINS
    -      },
    -      hljs.COMMENT('//', '$')
    -    ].concat(COMMON_CONTAINS)
    -  };
    -}
    -
    -module.exports = scilab;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/scss.js b/claude-code-source/node_modules/highlight.js/lib/languages/scss.js
    deleted file mode 100644
    index 6a5a90d6..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/scss.js
    +++ /dev/null
    @@ -1,545 +0,0 @@
    -const MODES = (hljs) => {
    -  return {
    -    IMPORTANT: {
    -      className: 'meta',
    -      begin: '!important'
    -    },
    -    HEXCOLOR: {
    -      className: 'number',
    -      begin: '#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})'
    -    },
    -    ATTRIBUTE_SELECTOR_MODE: {
    -      className: 'selector-attr',
    -      begin: /\[/,
    -      end: /\]/,
    -      illegal: '$',
    -      contains: [
    -        hljs.APOS_STRING_MODE,
    -        hljs.QUOTE_STRING_MODE
    -      ]
    -    }
    -  };
    -};
    -
    -const TAGS = [
    -  'a',
    -  'abbr',
    -  'address',
    -  'article',
    -  'aside',
    -  'audio',
    -  'b',
    -  'blockquote',
    -  'body',
    -  'button',
    -  'canvas',
    -  'caption',
    -  'cite',
    -  'code',
    -  'dd',
    -  'del',
    -  'details',
    -  'dfn',
    -  'div',
    -  'dl',
    -  'dt',
    -  'em',
    -  'fieldset',
    -  'figcaption',
    -  'figure',
    -  'footer',
    -  'form',
    -  'h1',
    -  'h2',
    -  'h3',
    -  'h4',
    -  'h5',
    -  'h6',
    -  'header',
    -  'hgroup',
    -  'html',
    -  'i',
    -  'iframe',
    -  'img',
    -  'input',
    -  'ins',
    -  'kbd',
    -  'label',
    -  'legend',
    -  'li',
    -  'main',
    -  'mark',
    -  'menu',
    -  'nav',
    -  'object',
    -  'ol',
    -  'p',
    -  'q',
    -  'quote',
    -  'samp',
    -  'section',
    -  'span',
    -  'strong',
    -  'summary',
    -  'sup',
    -  'table',
    -  'tbody',
    -  'td',
    -  'textarea',
    -  'tfoot',
    -  'th',
    -  'thead',
    -  'time',
    -  'tr',
    -  'ul',
    -  'var',
    -  'video'
    -];
    -
    -const MEDIA_FEATURES = [
    -  'any-hover',
    -  'any-pointer',
    -  'aspect-ratio',
    -  'color',
    -  'color-gamut',
    -  'color-index',
    -  'device-aspect-ratio',
    -  'device-height',
    -  'device-width',
    -  'display-mode',
    -  'forced-colors',
    -  'grid',
    -  'height',
    -  'hover',
    -  'inverted-colors',
    -  'monochrome',
    -  'orientation',
    -  'overflow-block',
    -  'overflow-inline',
    -  'pointer',
    -  'prefers-color-scheme',
    -  'prefers-contrast',
    -  'prefers-reduced-motion',
    -  'prefers-reduced-transparency',
    -  'resolution',
    -  'scan',
    -  'scripting',
    -  'update',
    -  'width',
    -  // TODO: find a better solution?
    -  'min-width',
    -  'max-width',
    -  'min-height',
    -  'max-height'
    -];
    -
    -// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes
    -const PSEUDO_CLASSES = [
    -  'active',
    -  'any-link',
    -  'blank',
    -  'checked',
    -  'current',
    -  'default',
    -  'defined',
    -  'dir', // dir()
    -  'disabled',
    -  'drop',
    -  'empty',
    -  'enabled',
    -  'first',
    -  'first-child',
    -  'first-of-type',
    -  'fullscreen',
    -  'future',
    -  'focus',
    -  'focus-visible',
    -  'focus-within',
    -  'has', // has()
    -  'host', // host or host()
    -  'host-context', // host-context()
    -  'hover',
    -  'indeterminate',
    -  'in-range',
    -  'invalid',
    -  'is', // is()
    -  'lang', // lang()
    -  'last-child',
    -  'last-of-type',
    -  'left',
    -  'link',
    -  'local-link',
    -  'not', // not()
    -  'nth-child', // nth-child()
    -  'nth-col', // nth-col()
    -  'nth-last-child', // nth-last-child()
    -  'nth-last-col', // nth-last-col()
    -  'nth-last-of-type', //nth-last-of-type()
    -  'nth-of-type', //nth-of-type()
    -  'only-child',
    -  'only-of-type',
    -  'optional',
    -  'out-of-range',
    -  'past',
    -  'placeholder-shown',
    -  'read-only',
    -  'read-write',
    -  'required',
    -  'right',
    -  'root',
    -  'scope',
    -  'target',
    -  'target-within',
    -  'user-invalid',
    -  'valid',
    -  'visited',
    -  'where' // where()
    -];
    -
    -// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements
    -const PSEUDO_ELEMENTS = [
    -  'after',
    -  'backdrop',
    -  'before',
    -  'cue',
    -  'cue-region',
    -  'first-letter',
    -  'first-line',
    -  'grammar-error',
    -  'marker',
    -  'part',
    -  'placeholder',
    -  'selection',
    -  'slotted',
    -  'spelling-error'
    -];
    -
    -const ATTRIBUTES = [
    -  'align-content',
    -  'align-items',
    -  'align-self',
    -  'animation',
    -  'animation-delay',
    -  'animation-direction',
    -  'animation-duration',
    -  'animation-fill-mode',
    -  'animation-iteration-count',
    -  'animation-name',
    -  'animation-play-state',
    -  'animation-timing-function',
    -  'auto',
    -  'backface-visibility',
    -  'background',
    -  'background-attachment',
    -  'background-clip',
    -  'background-color',
    -  'background-image',
    -  'background-origin',
    -  'background-position',
    -  'background-repeat',
    -  'background-size',
    -  'border',
    -  'border-bottom',
    -  'border-bottom-color',
    -  'border-bottom-left-radius',
    -  'border-bottom-right-radius',
    -  'border-bottom-style',
    -  'border-bottom-width',
    -  'border-collapse',
    -  'border-color',
    -  'border-image',
    -  'border-image-outset',
    -  'border-image-repeat',
    -  'border-image-slice',
    -  'border-image-source',
    -  'border-image-width',
    -  'border-left',
    -  'border-left-color',
    -  'border-left-style',
    -  'border-left-width',
    -  'border-radius',
    -  'border-right',
    -  'border-right-color',
    -  'border-right-style',
    -  'border-right-width',
    -  'border-spacing',
    -  'border-style',
    -  'border-top',
    -  'border-top-color',
    -  'border-top-left-radius',
    -  'border-top-right-radius',
    -  'border-top-style',
    -  'border-top-width',
    -  'border-width',
    -  'bottom',
    -  'box-decoration-break',
    -  'box-shadow',
    -  'box-sizing',
    -  'break-after',
    -  'break-before',
    -  'break-inside',
    -  'caption-side',
    -  'clear',
    -  'clip',
    -  'clip-path',
    -  'color',
    -  'column-count',
    -  'column-fill',
    -  'column-gap',
    -  'column-rule',
    -  'column-rule-color',
    -  'column-rule-style',
    -  'column-rule-width',
    -  'column-span',
    -  'column-width',
    -  'columns',
    -  'content',
    -  'counter-increment',
    -  'counter-reset',
    -  'cursor',
    -  'direction',
    -  'display',
    -  'empty-cells',
    -  'filter',
    -  'flex',
    -  'flex-basis',
    -  'flex-direction',
    -  'flex-flow',
    -  'flex-grow',
    -  'flex-shrink',
    -  'flex-wrap',
    -  'float',
    -  'font',
    -  'font-display',
    -  'font-family',
    -  'font-feature-settings',
    -  'font-kerning',
    -  'font-language-override',
    -  'font-size',
    -  'font-size-adjust',
    -  'font-smoothing',
    -  'font-stretch',
    -  'font-style',
    -  'font-variant',
    -  'font-variant-ligatures',
    -  'font-variation-settings',
    -  'font-weight',
    -  'height',
    -  'hyphens',
    -  'icon',
    -  'image-orientation',
    -  'image-rendering',
    -  'image-resolution',
    -  'ime-mode',
    -  'inherit',
    -  'initial',
    -  'justify-content',
    -  'left',
    -  'letter-spacing',
    -  'line-height',
    -  'list-style',
    -  'list-style-image',
    -  'list-style-position',
    -  'list-style-type',
    -  'margin',
    -  'margin-bottom',
    -  'margin-left',
    -  'margin-right',
    -  'margin-top',
    -  'marks',
    -  'mask',
    -  'max-height',
    -  'max-width',
    -  'min-height',
    -  'min-width',
    -  'nav-down',
    -  'nav-index',
    -  'nav-left',
    -  'nav-right',
    -  'nav-up',
    -  'none',
    -  'normal',
    -  'object-fit',
    -  'object-position',
    -  'opacity',
    -  'order',
    -  'orphans',
    -  'outline',
    -  'outline-color',
    -  'outline-offset',
    -  'outline-style',
    -  'outline-width',
    -  'overflow',
    -  'overflow-wrap',
    -  'overflow-x',
    -  'overflow-y',
    -  'padding',
    -  'padding-bottom',
    -  'padding-left',
    -  'padding-right',
    -  'padding-top',
    -  'page-break-after',
    -  'page-break-before',
    -  'page-break-inside',
    -  'perspective',
    -  'perspective-origin',
    -  'pointer-events',
    -  'position',
    -  'quotes',
    -  'resize',
    -  'right',
    -  'src', // @font-face
    -  'tab-size',
    -  'table-layout',
    -  'text-align',
    -  'text-align-last',
    -  'text-decoration',
    -  'text-decoration-color',
    -  'text-decoration-line',
    -  'text-decoration-style',
    -  'text-indent',
    -  'text-overflow',
    -  'text-rendering',
    -  'text-shadow',
    -  'text-transform',
    -  'text-underline-position',
    -  'top',
    -  'transform',
    -  'transform-origin',
    -  'transform-style',
    -  'transition',
    -  'transition-delay',
    -  'transition-duration',
    -  'transition-property',
    -  'transition-timing-function',
    -  'unicode-bidi',
    -  'vertical-align',
    -  'visibility',
    -  'white-space',
    -  'widows',
    -  'width',
    -  'word-break',
    -  'word-spacing',
    -  'word-wrap',
    -  'z-index'
    -  // reverse makes sure longer attributes `font-weight` are matched fully
    -  // instead of getting false positives on say `font`
    -].reverse();
    -
    -/*
    -Language: SCSS
    -Description: Scss is an extension of the syntax of CSS.
    -Author: Kurt Emch 
    -Website: https://sass-lang.com
    -Category: common, css
    -*/
    -
    -/** @type LanguageFn */
    -function scss(hljs) {
    -  const modes = MODES(hljs);
    -  const PSEUDO_ELEMENTS$1 = PSEUDO_ELEMENTS;
    -  const PSEUDO_CLASSES$1 = PSEUDO_CLASSES;
    -
    -  const AT_IDENTIFIER = '@[a-z-]+'; // @font-face
    -  const AT_MODIFIERS = "and or not only";
    -  const IDENT_RE = '[a-zA-Z-][a-zA-Z0-9_-]*';
    -  const VARIABLE = {
    -    className: 'variable',
    -    begin: '(\\$' + IDENT_RE + ')\\b'
    -  };
    -
    -  return {
    -    name: 'SCSS',
    -    case_insensitive: true,
    -    illegal: '[=/|\']',
    -    contains: [
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      {
    -        className: 'selector-id',
    -        begin: '#[A-Za-z0-9_-]+',
    -        relevance: 0
    -      },
    -      {
    -        className: 'selector-class',
    -        begin: '\\.[A-Za-z0-9_-]+',
    -        relevance: 0
    -      },
    -      modes.ATTRIBUTE_SELECTOR_MODE,
    -      {
    -        className: 'selector-tag',
    -        begin: '\\b(' + TAGS.join('|') + ')\\b',
    -        // was there, before, but why?
    -        relevance: 0
    -      },
    -      {
    -        className: 'selector-pseudo',
    -        begin: ':(' + PSEUDO_CLASSES$1.join('|') + ')'
    -      },
    -      {
    -        className: 'selector-pseudo',
    -        begin: '::(' + PSEUDO_ELEMENTS$1.join('|') + ')'
    -      },
    -      VARIABLE,
    -      { // pseudo-selector params
    -        begin: /\(/,
    -        end: /\)/,
    -        contains: [ hljs.CSS_NUMBER_MODE ]
    -      },
    -      {
    -        className: 'attribute',
    -        begin: '\\b(' + ATTRIBUTES.join('|') + ')\\b'
    -      },
    -      {
    -        begin: '\\b(whitespace|wait|w-resize|visible|vertical-text|vertical-ideographic|uppercase|upper-roman|upper-alpha|underline|transparent|top|thin|thick|text|text-top|text-bottom|tb-rl|table-header-group|table-footer-group|sw-resize|super|strict|static|square|solid|small-caps|separate|se-resize|scroll|s-resize|rtl|row-resize|ridge|right|repeat|repeat-y|repeat-x|relative|progress|pointer|overline|outside|outset|oblique|nowrap|not-allowed|normal|none|nw-resize|no-repeat|no-drop|newspaper|ne-resize|n-resize|move|middle|medium|ltr|lr-tb|lowercase|lower-roman|lower-alpha|loose|list-item|line|line-through|line-edge|lighter|left|keep-all|justify|italic|inter-word|inter-ideograph|inside|inset|inline|inline-block|inherit|inactive|ideograph-space|ideograph-parenthesis|ideograph-numeric|ideograph-alpha|horizontal|hidden|help|hand|groove|fixed|ellipsis|e-resize|double|dotted|distribute|distribute-space|distribute-letter|distribute-all-lines|disc|disabled|default|decimal|dashed|crosshair|collapse|col-resize|circle|char|center|capitalize|break-word|break-all|bottom|both|bolder|bold|block|bidi-override|below|baseline|auto|always|all-scroll|absolute|table|table-cell)\\b'
    -      },
    -      {
    -        begin: ':',
    -        end: ';',
    -        contains: [
    -          VARIABLE,
    -          modes.HEXCOLOR,
    -          hljs.CSS_NUMBER_MODE,
    -          hljs.QUOTE_STRING_MODE,
    -          hljs.APOS_STRING_MODE,
    -          modes.IMPORTANT
    -        ]
    -      },
    -      // matching these here allows us to treat them more like regular CSS
    -      // rules so everything between the {} gets regular rule highlighting,
    -      // which is what we want for page and font-face
    -      {
    -        begin: '@(page|font-face)',
    -        lexemes: AT_IDENTIFIER,
    -        keywords: '@page @font-face'
    -      },
    -      {
    -        begin: '@',
    -        end: '[{;]',
    -        returnBegin: true,
    -        keywords: {
    -          $pattern: /[a-z-]+/,
    -          keyword: AT_MODIFIERS,
    -          attribute: MEDIA_FEATURES.join(" ")
    -        },
    -        contains: [
    -          {
    -            begin: AT_IDENTIFIER,
    -            className: "keyword"
    -          },
    -          {
    -            begin: /[a-z-]+(?=:)/,
    -            className: "attribute"
    -          },
    -          VARIABLE,
    -          hljs.QUOTE_STRING_MODE,
    -          hljs.APOS_STRING_MODE,
    -          modes.HEXCOLOR,
    -          hljs.CSS_NUMBER_MODE
    -        ]
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = scss;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/shell.js b/claude-code-source/node_modules/highlight.js/lib/languages/shell.js
    deleted file mode 100644
    index bb2c8f74..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/shell.js
    +++ /dev/null
    @@ -1,30 +0,0 @@
    -/*
    -Language: Shell Session
    -Requires: bash.js
    -Author: TSUYUSATO Kitsune 
    -Category: common
    -Audit: 2020
    -*/
    -
    -/** @type LanguageFn */
    -function shell(hljs) {
    -  return {
    -    name: 'Shell Session',
    -    aliases: [ 'console' ],
    -    contains: [
    -      {
    -        className: 'meta',
    -        // We cannot add \s (spaces) in the regular expression otherwise it will be too broad and produce unexpected result.
    -        // For instance, in the following example, it would match "echo /path/to/home >" as a prompt:
    -        // echo /path/to/home > t.exe
    -        begin: /^\s{0,3}[/~\w\d[\]()@-]*[>%$#]/,
    -        starts: {
    -          end: /[^\\](?=\s*$)/,
    -          subLanguage: 'bash'
    -        }
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = shell;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/smali.js b/claude-code-source/node_modules/highlight.js/lib/languages/smali.js
    deleted file mode 100644
    index 4e16c8a7..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/smali.js
    +++ /dev/null
    @@ -1,135 +0,0 @@
    -/*
    -Language: Smali
    -Author: Dennis Titze 
    -Description: Basic Smali highlighting
    -Website: https://github.com/JesusFreke/smali
    -*/
    -
    -function smali(hljs) {
    -  const smali_instr_low_prio = [
    -    'add',
    -    'and',
    -    'cmp',
    -    'cmpg',
    -    'cmpl',
    -    'const',
    -    'div',
    -    'double',
    -    'float',
    -    'goto',
    -    'if',
    -    'int',
    -    'long',
    -    'move',
    -    'mul',
    -    'neg',
    -    'new',
    -    'nop',
    -    'not',
    -    'or',
    -    'rem',
    -    'return',
    -    'shl',
    -    'shr',
    -    'sput',
    -    'sub',
    -    'throw',
    -    'ushr',
    -    'xor'
    -  ];
    -  const smali_instr_high_prio = [
    -    'aget',
    -    'aput',
    -    'array',
    -    'check',
    -    'execute',
    -    'fill',
    -    'filled',
    -    'goto/16',
    -    'goto/32',
    -    'iget',
    -    'instance',
    -    'invoke',
    -    'iput',
    -    'monitor',
    -    'packed',
    -    'sget',
    -    'sparse'
    -  ];
    -  const smali_keywords = [
    -    'transient',
    -    'constructor',
    -    'abstract',
    -    'final',
    -    'synthetic',
    -    'public',
    -    'private',
    -    'protected',
    -    'static',
    -    'bridge',
    -    'system'
    -  ];
    -  return {
    -    name: 'Smali',
    -    contains: [
    -      {
    -        className: 'string',
    -        begin: '"',
    -        end: '"',
    -        relevance: 0
    -      },
    -      hljs.COMMENT(
    -        '#',
    -        '$',
    -        {
    -          relevance: 0
    -        }
    -      ),
    -      {
    -        className: 'keyword',
    -        variants: [
    -          {
    -            begin: '\\s*\\.end\\s[a-zA-Z0-9]*'
    -          },
    -          {
    -            begin: '^[ ]*\\.[a-zA-Z]*',
    -            relevance: 0
    -          },
    -          {
    -            begin: '\\s:[a-zA-Z_0-9]*',
    -            relevance: 0
    -          },
    -          {
    -            begin: '\\s(' + smali_keywords.join('|') + ')'
    -          }
    -        ]
    -      },
    -      {
    -        className: 'built_in',
    -        variants: [
    -          {
    -            begin: '\\s(' + smali_instr_low_prio.join('|') + ')\\s'
    -          },
    -          {
    -            begin: '\\s(' + smali_instr_low_prio.join('|') + ')((-|/)[a-zA-Z0-9]+)+\\s',
    -            relevance: 10
    -          },
    -          {
    -            begin: '\\s(' + smali_instr_high_prio.join('|') + ')((-|/)[a-zA-Z0-9]+)*\\s',
    -            relevance: 10
    -          }
    -        ]
    -      },
    -      {
    -        className: 'class',
    -        begin: 'L[^\(;:\n]*;',
    -        relevance: 0
    -      },
    -      {
    -        begin: '[vp][0-9]+'
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = smali;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/smalltalk.js b/claude-code-source/node_modules/highlight.js/lib/languages/smalltalk.js
    deleted file mode 100644
    index c1d02150..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/smalltalk.js
    +++ /dev/null
    @@ -1,63 +0,0 @@
    -/*
    -Language: Smalltalk
    -Description: Smalltalk is an object-oriented, dynamically typed reflective programming language.
    -Author: Vladimir Gubarkov 
    -Website: https://en.wikipedia.org/wiki/Smalltalk
    -*/
    -
    -function smalltalk(hljs) {
    -  const VAR_IDENT_RE = '[a-z][a-zA-Z0-9_]*';
    -  const CHAR = {
    -    className: 'string',
    -    begin: '\\$.{1}'
    -  };
    -  const SYMBOL = {
    -    className: 'symbol',
    -    begin: '#' + hljs.UNDERSCORE_IDENT_RE
    -  };
    -  return {
    -    name: 'Smalltalk',
    -    aliases: [ 'st' ],
    -    keywords: 'self super nil true false thisContext', // only 6
    -    contains: [
    -      hljs.COMMENT('"', '"'),
    -      hljs.APOS_STRING_MODE,
    -      {
    -        className: 'type',
    -        begin: '\\b[A-Z][A-Za-z0-9_]*',
    -        relevance: 0
    -      },
    -      {
    -        begin: VAR_IDENT_RE + ':',
    -        relevance: 0
    -      },
    -      hljs.C_NUMBER_MODE,
    -      SYMBOL,
    -      CHAR,
    -      {
    -        // This looks more complicated than needed to avoid combinatorial
    -        // explosion under V8. It effectively means `| var1 var2 ... |` with
    -        // whitespace adjacent to `|` being optional.
    -        begin: '\\|[ ]*' + VAR_IDENT_RE + '([ ]+' + VAR_IDENT_RE + ')*[ ]*\\|',
    -        returnBegin: true,
    -        end: /\|/,
    -        illegal: /\S/,
    -        contains: [ {
    -          begin: '(\\|[ ]*)?' + VAR_IDENT_RE
    -        } ]
    -      },
    -      {
    -        begin: '#\\(',
    -        end: '\\)',
    -        contains: [
    -          hljs.APOS_STRING_MODE,
    -          CHAR,
    -          hljs.C_NUMBER_MODE,
    -          SYMBOL
    -        ]
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = smalltalk;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/sml.js b/claude-code-source/node_modules/highlight.js/lib/languages/sml.js
    deleted file mode 100644
    index 16b4cc18..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/sml.js
    +++ /dev/null
    @@ -1,81 +0,0 @@
    -/*
    -Language: SML (Standard ML)
    -Author: Edwin Dalorzo 
    -Description: SML language definition.
    -Website: https://www.smlnj.org
    -Origin: ocaml.js
    -Category: functional
    -*/
    -function sml(hljs) {
    -  return {
    -    name: 'SML (Standard ML)',
    -    aliases: [ 'ml' ],
    -    keywords: {
    -      $pattern: '[a-z_]\\w*!?',
    -      keyword:
    -        /* according to Definition of Standard ML 97  */
    -        'abstype and andalso as case datatype do else end eqtype ' +
    -        'exception fn fun functor handle if in include infix infixr ' +
    -        'let local nonfix of op open orelse raise rec sharing sig ' +
    -        'signature struct structure then type val with withtype where while',
    -      built_in:
    -        /* built-in types according to basis library */
    -        'array bool char exn int list option order real ref string substring vector unit word',
    -      literal:
    -        'true false NONE SOME LESS EQUAL GREATER nil'
    -    },
    -    illegal: /\/\/|>>/,
    -    contains: [
    -      {
    -        className: 'literal',
    -        begin: /\[(\|\|)?\]|\(\)/,
    -        relevance: 0
    -      },
    -      hljs.COMMENT(
    -        '\\(\\*',
    -        '\\*\\)',
    -        {
    -          contains: [ 'self' ]
    -        }
    -      ),
    -      { /* type variable */
    -        className: 'symbol',
    -        begin: '\'[A-Za-z_](?!\')[\\w\']*'
    -        /* the grammar is ambiguous on how 'a'b should be interpreted but not the compiler */
    -      },
    -      { /* polymorphic variant */
    -        className: 'type',
    -        begin: '`[A-Z][\\w\']*'
    -      },
    -      { /* module or constructor */
    -        className: 'type',
    -        begin: '\\b[A-Z][\\w\']*',
    -        relevance: 0
    -      },
    -      { /* don't color identifiers, but safely catch all identifiers with ' */
    -        begin: '[a-z_]\\w*\'[\\w\']*'
    -      },
    -      hljs.inherit(hljs.APOS_STRING_MODE, {
    -        className: 'string',
    -        relevance: 0
    -      }),
    -      hljs.inherit(hljs.QUOTE_STRING_MODE, {
    -        illegal: null
    -      }),
    -      {
    -        className: 'number',
    -        begin:
    -          '\\b(0[xX][a-fA-F0-9_]+[Lln]?|' +
    -          '0[oO][0-7_]+[Lln]?|' +
    -          '0[bB][01_]+[Lln]?|' +
    -          '[0-9][0-9_]*([Lln]|(\\.[0-9_]*)?([eE][-+]?[0-9_]+)?)?)',
    -        relevance: 0
    -      },
    -      {
    -        begin: /[-=]>/ // relevance booster
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = sml;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/sqf.js b/claude-code-source/node_modules/highlight.js/lib/languages/sqf.js
    deleted file mode 100644
    index 61648266..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/sqf.js
    +++ /dev/null
    @@ -1,448 +0,0 @@
    -/*
    -Language: SQF
    -Author: Søren Enevoldsen 
    -Contributors: Marvin Saignat , Dedmen Miller 
    -Description: Scripting language for the Arma game series
    -Website: https://community.bistudio.com/wiki/SQF_syntax
    -Category: scripting
    -*/
    -
    -function sqf(hljs) {
    -  // In SQF, a variable start with _
    -  const VARIABLE = {
    -    className: 'variable',
    -    begin: /\b_+[a-zA-Z]\w*/
    -  };
    -
    -  // In SQF, a function should fit myTag_fnc_myFunction pattern
    -  // https://community.bistudio.com/wiki/Functions_Library_(Arma_3)#Adding_a_Function
    -  const FUNCTION = {
    -    className: 'title',
    -    begin: /[a-zA-Z][a-zA-Z0-9]+_fnc_\w*/
    -  };
    -
    -  // In SQF strings, quotes matching the start are escaped by adding a consecutive.
    -  // Example of single escaped quotes: " "" " and  ' '' '.
    -  const STRINGS = {
    -    className: 'string',
    -    variants: [
    -      {
    -        begin: '"',
    -        end: '"',
    -        contains: [ {
    -          begin: '""',
    -          relevance: 0
    -        } ]
    -      },
    -      {
    -        begin: '\'',
    -        end: '\'',
    -        contains: [ {
    -          begin: '\'\'',
    -          relevance: 0
    -        } ]
    -      }
    -    ]
    -  };
    -
    -  // list of keywords from:
    -  // https://community.bistudio.com/wiki/PreProcessor_Commands
    -  const PREPROCESSOR = {
    -    className: 'meta',
    -    begin: /#\s*[a-z]+\b/,
    -    end: /$/,
    -    keywords: {
    -      'meta-keyword':
    -        'define undef ifdef ifndef else endif include'
    -    },
    -    contains: [
    -      {
    -        begin: /\\\n/,
    -        relevance: 0
    -      },
    -      hljs.inherit(STRINGS, {
    -        className: 'meta-string'
    -      }),
    -      {
    -        className: 'meta-string',
    -        begin: /<[^\n>]*>/,
    -        end: /$/,
    -        illegal: '\\n'
    -      },
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE
    -    ]
    -  };
    -
    -  return {
    -    name: 'SQF',
    -    case_insensitive: true,
    -    keywords: {
    -      keyword:
    -        'case catch default do else exit exitWith for forEach from if ' +
    -        'private switch then throw to try waitUntil while with',
    -      built_in:
    -        'abs accTime acos action actionIDs actionKeys actionKeysImages actionKeysNames ' +
    -        'actionKeysNamesArray actionName actionParams activateAddons activatedAddons activateKey ' +
    -        'add3DENConnection add3DENEventHandler add3DENLayer addAction addBackpack addBackpackCargo ' +
    -        'addBackpackCargoGlobal addBackpackGlobal addCamShake addCuratorAddons addCuratorCameraArea ' +
    -        'addCuratorEditableObjects addCuratorEditingArea addCuratorPoints addEditorObject addEventHandler ' +
    -        'addForce addGoggles addGroupIcon addHandgunItem addHeadgear addItem addItemCargo ' +
    -        'addItemCargoGlobal addItemPool addItemToBackpack addItemToUniform addItemToVest addLiveStats ' +
    -        'addMagazine addMagazineAmmoCargo addMagazineCargo addMagazineCargoGlobal addMagazineGlobal ' +
    -        'addMagazinePool addMagazines addMagazineTurret addMenu addMenuItem addMissionEventHandler ' +
    -        'addMPEventHandler addMusicEventHandler addOwnedMine addPlayerScores addPrimaryWeaponItem ' +
    -        'addPublicVariableEventHandler addRating addResources addScore addScoreSide addSecondaryWeaponItem ' +
    -        'addSwitchableUnit addTeamMember addToRemainsCollector addTorque addUniform addVehicle addVest ' +
    -        'addWaypoint addWeapon addWeaponCargo addWeaponCargoGlobal addWeaponGlobal addWeaponItem ' +
    -        'addWeaponPool addWeaponTurret admin agent agents AGLToASL aimedAtTarget aimPos airDensityRTD ' +
    -        'airplaneThrottle airportSide AISFinishHeal alive all3DENEntities allAirports allControls ' +
    -        'allCurators allCutLayers allDead allDeadMen allDisplays allGroups allMapMarkers allMines ' +
    -        'allMissionObjects allow3DMode allowCrewInImmobile allowCuratorLogicIgnoreAreas allowDamage ' +
    -        'allowDammage allowFileOperations allowFleeing allowGetIn allowSprint allPlayers allSimpleObjects ' +
    -        'allSites allTurrets allUnits allUnitsUAV allVariables ammo ammoOnPylon and animate animateBay ' +
    -        'animateDoor animatePylon animateSource animationNames animationPhase animationSourcePhase ' +
    -        'animationState append apply armoryPoints arrayIntersect asin ASLToAGL ASLToATL assert ' +
    -        'assignAsCargo assignAsCargoIndex assignAsCommander assignAsDriver assignAsGunner assignAsTurret ' +
    -        'assignCurator assignedCargo assignedCommander assignedDriver assignedGunner assignedItems ' +
    -        'assignedTarget assignedTeam assignedVehicle assignedVehicleRole assignItem assignTeam ' +
    -        'assignToAirport atan atan2 atg ATLToASL attachedObject attachedObjects attachedTo attachObject ' +
    -        'attachTo attackEnabled backpack backpackCargo backpackContainer backpackItems backpackMagazines ' +
    -        'backpackSpaceFor behaviour benchmark binocular boundingBox boundingBoxReal boundingCenter ' +
    -        'breakOut breakTo briefingName buildingExit buildingPos buttonAction buttonSetAction cadetMode ' +
    -        'call callExtension camCommand camCommit camCommitPrepared camCommitted camConstuctionSetParams ' +
    -        'camCreate camDestroy cameraEffect cameraEffectEnableHUD cameraInterest cameraOn cameraView ' +
    -        'campaignConfigFile camPreload camPreloaded camPrepareBank camPrepareDir camPrepareDive ' +
    -        'camPrepareFocus camPrepareFov camPrepareFovRange camPreparePos camPrepareRelPos camPrepareTarget ' +
    -        'camSetBank camSetDir camSetDive camSetFocus camSetFov camSetFovRange camSetPos camSetRelPos ' +
    -        'camSetTarget camTarget camUseNVG canAdd canAddItemToBackpack canAddItemToUniform canAddItemToVest ' +
    -        'cancelSimpleTaskDestination canFire canMove canSlingLoad canStand canSuspend ' +
    -        'canTriggerDynamicSimulation canUnloadInCombat canVehicleCargo captive captiveNum cbChecked ' +
    -        'cbSetChecked ceil channelEnabled cheatsEnabled checkAIFeature checkVisibility className ' +
    -        'clearAllItemsFromBackpack clearBackpackCargo clearBackpackCargoGlobal clearGroupIcons ' +
    -        'clearItemCargo clearItemCargoGlobal clearItemPool clearMagazineCargo clearMagazineCargoGlobal ' +
    -        'clearMagazinePool clearOverlay clearRadio clearWeaponCargo clearWeaponCargoGlobal clearWeaponPool ' +
    -        'clientOwner closeDialog closeDisplay closeOverlay collapseObjectTree collect3DENHistory ' +
    -        'collectiveRTD combatMode commandArtilleryFire commandChat commander commandFire commandFollow ' +
    -        'commandFSM commandGetOut commandingMenu commandMove commandRadio commandStop ' +
    -        'commandSuppressiveFire commandTarget commandWatch comment commitOverlay compile compileFinal ' +
    -        'completedFSM composeText configClasses configFile configHierarchy configName configProperties ' +
    -        'configSourceAddonList configSourceMod configSourceModList confirmSensorTarget ' +
    -        'connectTerminalToUAV controlsGroupCtrl copyFromClipboard copyToClipboard copyWaypoints cos count ' +
    -        'countEnemy countFriendly countSide countType countUnknown create3DENComposition create3DENEntity ' +
    -        'createAgent createCenter createDialog createDiaryLink createDiaryRecord createDiarySubject ' +
    -        'createDisplay createGearDialog createGroup createGuardedPoint createLocation createMarker ' +
    -        'createMarkerLocal createMenu createMine createMissionDisplay createMPCampaignDisplay ' +
    -        'createSimpleObject createSimpleTask createSite createSoundSource createTask createTeam ' +
    -        'createTrigger createUnit createVehicle createVehicleCrew createVehicleLocal crew ctAddHeader ' +
    -        'ctAddRow ctClear ctCurSel ctData ctFindHeaderRows ctFindRowHeader ctHeaderControls ctHeaderCount ' +
    -        'ctRemoveHeaders ctRemoveRows ctrlActivate ctrlAddEventHandler ctrlAngle ctrlAutoScrollDelay ' +
    -        'ctrlAutoScrollRewind ctrlAutoScrollSpeed ctrlChecked ctrlClassName ctrlCommit ctrlCommitted ' +
    -        'ctrlCreate ctrlDelete ctrlEnable ctrlEnabled ctrlFade ctrlHTMLLoaded ctrlIDC ctrlIDD ' +
    -        'ctrlMapAnimAdd ctrlMapAnimClear ctrlMapAnimCommit ctrlMapAnimDone ctrlMapCursor ctrlMapMouseOver ' +
    -        'ctrlMapScale ctrlMapScreenToWorld ctrlMapWorldToScreen ctrlModel ctrlModelDirAndUp ctrlModelScale ' +
    -        'ctrlParent ctrlParentControlsGroup ctrlPosition ctrlRemoveAllEventHandlers ctrlRemoveEventHandler ' +
    -        'ctrlScale ctrlSetActiveColor ctrlSetAngle ctrlSetAutoScrollDelay ctrlSetAutoScrollRewind ' +
    -        'ctrlSetAutoScrollSpeed ctrlSetBackgroundColor ctrlSetChecked ctrlSetEventHandler ctrlSetFade ' +
    -        'ctrlSetFocus ctrlSetFont ctrlSetFontH1 ctrlSetFontH1B ctrlSetFontH2 ctrlSetFontH2B ctrlSetFontH3 ' +
    -        'ctrlSetFontH3B ctrlSetFontH4 ctrlSetFontH4B ctrlSetFontH5 ctrlSetFontH5B ctrlSetFontH6 ' +
    -        'ctrlSetFontH6B ctrlSetFontHeight ctrlSetFontHeightH1 ctrlSetFontHeightH2 ctrlSetFontHeightH3 ' +
    -        'ctrlSetFontHeightH4 ctrlSetFontHeightH5 ctrlSetFontHeightH6 ctrlSetFontHeightSecondary ' +
    -        'ctrlSetFontP ctrlSetFontPB ctrlSetFontSecondary ctrlSetForegroundColor ctrlSetModel ' +
    -        'ctrlSetModelDirAndUp ctrlSetModelScale ctrlSetPixelPrecision ctrlSetPosition ctrlSetScale ' +
    -        'ctrlSetStructuredText ctrlSetText ctrlSetTextColor ctrlSetTooltip ctrlSetTooltipColorBox ' +
    -        'ctrlSetTooltipColorShade ctrlSetTooltipColorText ctrlShow ctrlShown ctrlText ctrlTextHeight ' +
    -        'ctrlTextWidth ctrlType ctrlVisible ctRowControls ctRowCount ctSetCurSel ctSetData ' +
    -        'ctSetHeaderTemplate ctSetRowTemplate ctSetValue ctValue curatorAddons curatorCamera ' +
    -        'curatorCameraArea curatorCameraAreaCeiling curatorCoef curatorEditableObjects curatorEditingArea ' +
    -        'curatorEditingAreaType curatorMouseOver curatorPoints curatorRegisteredObjects curatorSelected ' +
    -        'curatorWaypointCost current3DENOperation currentChannel currentCommand currentMagazine ' +
    -        'currentMagazineDetail currentMagazineDetailTurret currentMagazineTurret currentMuzzle ' +
    -        'currentNamespace currentTask currentTasks currentThrowable currentVisionMode currentWaypoint ' +
    -        'currentWeapon currentWeaponMode currentWeaponTurret currentZeroing cursorObject cursorTarget ' +
    -        'customChat customRadio cutFadeOut cutObj cutRsc cutText damage date dateToNumber daytime ' +
    -        'deActivateKey debriefingText debugFSM debugLog deg delete3DENEntities deleteAt deleteCenter ' +
    -        'deleteCollection deleteEditorObject deleteGroup deleteGroupWhenEmpty deleteIdentity ' +
    -        'deleteLocation deleteMarker deleteMarkerLocal deleteRange deleteResources deleteSite deleteStatus ' +
    -        'deleteTeam deleteVehicle deleteVehicleCrew deleteWaypoint detach detectedMines ' +
    -        'diag_activeMissionFSMs diag_activeScripts diag_activeSQFScripts diag_activeSQSScripts ' +
    -        'diag_captureFrame diag_captureFrameToFile diag_captureSlowFrame diag_codePerformance ' +
    -        'diag_drawMode diag_enable diag_enabled diag_fps diag_fpsMin diag_frameNo diag_lightNewLoad ' +
    -        'diag_list diag_log diag_logSlowFrame diag_mergeConfigFile diag_recordTurretLimits ' +
    -        'diag_setLightNew diag_tickTime diag_toggle dialog diarySubjectExists didJIP didJIPOwner ' +
    -        'difficulty difficultyEnabled difficultyEnabledRTD difficultyOption direction directSay disableAI ' +
    -        'disableCollisionWith disableConversation disableDebriefingStats disableMapIndicators ' +
    -        'disableNVGEquipment disableRemoteSensors disableSerialization disableTIEquipment ' +
    -        'disableUAVConnectability disableUserInput displayAddEventHandler displayCtrl displayParent ' +
    -        'displayRemoveAllEventHandlers displayRemoveEventHandler displaySetEventHandler dissolveTeam ' +
    -        'distance distance2D distanceSqr distributionRegion do3DENAction doArtilleryFire doFire doFollow ' +
    -        'doFSM doGetOut doMove doorPhase doStop doSuppressiveFire doTarget doWatch drawArrow drawEllipse ' +
    -        'drawIcon drawIcon3D drawLine drawLine3D drawLink drawLocation drawPolygon drawRectangle ' +
    -        'drawTriangle driver drop dynamicSimulationDistance dynamicSimulationDistanceCoef ' +
    -        'dynamicSimulationEnabled dynamicSimulationSystemEnabled echo edit3DENMissionAttributes editObject ' +
    -        'editorSetEventHandler effectiveCommander emptyPositions enableAI enableAIFeature ' +
    -        'enableAimPrecision enableAttack enableAudioFeature enableAutoStartUpRTD enableAutoTrimRTD ' +
    -        'enableCamShake enableCaustics enableChannel enableCollisionWith enableCopilot ' +
    -        'enableDebriefingStats enableDiagLegend enableDynamicSimulation enableDynamicSimulationSystem ' +
    -        'enableEndDialog enableEngineArtillery enableEnvironment enableFatigue enableGunLights ' +
    -        'enableInfoPanelComponent enableIRLasers enableMimics enablePersonTurret enableRadio enableReload ' +
    -        'enableRopeAttach enableSatNormalOnDetail enableSaving enableSentences enableSimulation ' +
    -        'enableSimulationGlobal enableStamina enableTeamSwitch enableTraffic enableUAVConnectability ' +
    -        'enableUAVWaypoints enableVehicleCargo enableVehicleSensor enableWeaponDisassembly ' +
    -        'endLoadingScreen endMission engineOn enginesIsOnRTD enginesRpmRTD enginesTorqueRTD entities ' +
    -        'environmentEnabled estimatedEndServerTime estimatedTimeLeft evalObjectArgument everyBackpack ' +
    -        'everyContainer exec execEditorScript execFSM execVM exp expectedDestination exportJIPMessages ' +
    -        'eyeDirection eyePos face faction fadeMusic fadeRadio fadeSound fadeSpeech failMission ' +
    -        'fillWeaponsFromPool find findCover findDisplay findEditorObject findEmptyPosition ' +
    -        'findEmptyPositionReady findIf findNearestEnemy finishMissionInit finite fire fireAtTarget ' +
    -        'firstBackpack flag flagAnimationPhase flagOwner flagSide flagTexture fleeing floor flyInHeight ' +
    -        'flyInHeightASL fog fogForecast fogParams forceAddUniform forcedMap forceEnd forceFlagTexture ' +
    -        'forceFollowRoad forceMap forceRespawn forceSpeed forceWalk forceWeaponFire forceWeatherChange ' +
    -        'forEachMember forEachMemberAgent forEachMemberTeam forgetTarget format formation ' +
    -        'formationDirection formationLeader formationMembers formationPosition formationTask formatText ' +
    -        'formLeader freeLook fromEditor fuel fullCrew gearIDCAmmoCount gearSlotAmmoCount gearSlotData ' +
    -        'get3DENActionState get3DENAttribute get3DENCamera get3DENConnections get3DENEntity ' +
    -        'get3DENEntityID get3DENGrid get3DENIconsVisible get3DENLayerEntities get3DENLinesVisible ' +
    -        'get3DENMissionAttribute get3DENMouseOver get3DENSelected getAimingCoef getAllEnvSoundControllers ' +
    -        'getAllHitPointsDamage getAllOwnedMines getAllSoundControllers getAmmoCargo getAnimAimPrecision ' +
    -        'getAnimSpeedCoef getArray getArtilleryAmmo getArtilleryComputerSettings getArtilleryETA ' +
    -        'getAssignedCuratorLogic getAssignedCuratorUnit getBackpackCargo getBleedingRemaining ' +
    -        'getBurningValue getCameraViewDirection getCargoIndex getCenterOfMass getClientState ' +
    -        'getClientStateNumber getCompatiblePylonMagazines getConnectedUAV getContainerMaxLoad ' +
    -        'getCursorObjectParams getCustomAimCoef getDammage getDescription getDir getDirVisual ' +
    -        'getDLCAssetsUsage getDLCAssetsUsageByName getDLCs getEditorCamera getEditorMode ' +
    -        'getEditorObjectScope getElevationOffset getEnvSoundController getFatigue getForcedFlagTexture ' +
    -        'getFriend getFSMVariable getFuelCargo getGroupIcon getGroupIconParams getGroupIcons getHideFrom ' +
    -        'getHit getHitIndex getHitPointDamage getItemCargo getMagazineCargo getMarkerColor getMarkerPos ' +
    -        'getMarkerSize getMarkerType getMass getMissionConfig getMissionConfigValue getMissionDLCs ' +
    -        'getMissionLayerEntities getModelInfo getMousePosition getMusicPlayedTime getNumber ' +
    -        'getObjectArgument getObjectChildren getObjectDLC getObjectMaterials getObjectProxy ' +
    -        'getObjectTextures getObjectType getObjectViewDistance getOxygenRemaining getPersonUsedDLCs ' +
    -        'getPilotCameraDirection getPilotCameraPosition getPilotCameraRotation getPilotCameraTarget ' +
    -        'getPlateNumber getPlayerChannel getPlayerScores getPlayerUID getPos getPosASL getPosASLVisual ' +
    -        'getPosASLW getPosATL getPosATLVisual getPosVisual getPosWorld getPylonMagazines getRelDir ' +
    -        'getRelPos getRemoteSensorsDisabled getRepairCargo getResolution getShadowDistance getShotParents ' +
    -        'getSlingLoad getSoundController getSoundControllerResult getSpeed getStamina getStatValue ' +
    -        'getSuppression getTerrainGrid getTerrainHeightASL getText getTotalDLCUsageTime getUnitLoadout ' +
    -        'getUnitTrait getUserMFDText getUserMFDvalue getVariable getVehicleCargo getWeaponCargo ' +
    -        'getWeaponSway getWingsOrientationRTD getWingsPositionRTD getWPPos glanceAt globalChat globalRadio ' +
    -        'goggles goto group groupChat groupFromNetId groupIconSelectable groupIconsVisible groupId ' +
    -        'groupOwner groupRadio groupSelectedUnits groupSelectUnit gunner gusts halt handgunItems ' +
    -        'handgunMagazine handgunWeapon handsHit hasInterface hasPilotCamera hasWeapon hcAllGroups ' +
    -        'hcGroupParams hcLeader hcRemoveAllGroups hcRemoveGroup hcSelected hcSelectGroup hcSetGroup ' +
    -        'hcShowBar hcShownBar headgear hideBody hideObject hideObjectGlobal hideSelection hint hintC ' +
    -        'hintCadet hintSilent hmd hostMission htmlLoad HUDMovementLevels humidity image importAllGroups ' +
    -        'importance in inArea inAreaArray incapacitatedState inflame inflamed infoPanel ' +
    -        'infoPanelComponentEnabled infoPanelComponents infoPanels inGameUISetEventHandler inheritsFrom ' +
    -        'initAmbientLife inPolygon inputAction inRangeOfArtillery insertEditorObject intersect is3DEN ' +
    -        'is3DENMultiplayer isAbleToBreathe isAgent isArray isAutoHoverOn isAutonomous isAutotest ' +
    -        'isBleeding isBurning isClass isCollisionLightOn isCopilotEnabled isDamageAllowed isDedicated ' +
    -        'isDLCAvailable isEngineOn isEqualTo isEqualType isEqualTypeAll isEqualTypeAny isEqualTypeArray ' +
    -        'isEqualTypeParams isFilePatchingEnabled isFlashlightOn isFlatEmpty isForcedWalk isFormationLeader ' +
    -        'isGroupDeletedWhenEmpty isHidden isInRemainsCollector isInstructorFigureEnabled isIRLaserOn ' +
    -        'isKeyActive isKindOf isLaserOn isLightOn isLocalized isManualFire isMarkedForCollection ' +
    -        'isMultiplayer isMultiplayerSolo isNil isNull isNumber isObjectHidden isObjectRTD isOnRoad ' +
    -        'isPipEnabled isPlayer isRealTime isRemoteExecuted isRemoteExecutedJIP isServer isShowing3DIcons ' +
    -        'isSimpleObject isSprintAllowed isStaminaEnabled isSteamMission isStreamFriendlyUIEnabled isText ' +
    -        'isTouchingGround isTurnedOut isTutHintsEnabled isUAVConnectable isUAVConnected isUIContext ' +
    -        'isUniformAllowed isVehicleCargo isVehicleRadarOn isVehicleSensorEnabled isWalking ' +
    -        'isWeaponDeployed isWeaponRested itemCargo items itemsWithMagazines join joinAs joinAsSilent ' +
    -        'joinSilent joinString kbAddDatabase kbAddDatabaseTargets kbAddTopic kbHasTopic kbReact ' +
    -        'kbRemoveTopic kbTell kbWasSaid keyImage keyName knowsAbout land landAt landResult language ' +
    -        'laserTarget lbAdd lbClear lbColor lbColorRight lbCurSel lbData lbDelete lbIsSelected lbPicture ' +
    -        'lbPictureRight lbSelection lbSetColor lbSetColorRight lbSetCurSel lbSetData lbSetPicture ' +
    -        'lbSetPictureColor lbSetPictureColorDisabled lbSetPictureColorSelected lbSetPictureRight ' +
    -        'lbSetPictureRightColor lbSetPictureRightColorDisabled lbSetPictureRightColorSelected ' +
    -        'lbSetSelectColor lbSetSelectColorRight lbSetSelected lbSetText lbSetTextRight lbSetTooltip ' +
    -        'lbSetValue lbSize lbSort lbSortByValue lbText lbTextRight lbValue leader leaderboardDeInit ' +
    -        'leaderboardGetRows leaderboardInit leaderboardRequestRowsFriends leaderboardsRequestUploadScore ' +
    -        'leaderboardsRequestUploadScoreKeepBest leaderboardState leaveVehicle libraryCredits ' +
    -        'libraryDisclaimers lifeState lightAttachObject lightDetachObject lightIsOn lightnings limitSpeed ' +
    -        'linearConversion lineIntersects lineIntersectsObjs lineIntersectsSurfaces lineIntersectsWith ' +
    -        'linkItem list listObjects listRemoteTargets listVehicleSensors ln lnbAddArray lnbAddColumn ' +
    -        'lnbAddRow lnbClear lnbColor lnbCurSelRow lnbData lnbDeleteColumn lnbDeleteRow ' +
    -        'lnbGetColumnsPosition lnbPicture lnbSetColor lnbSetColumnsPos lnbSetCurSelRow lnbSetData ' +
    -        'lnbSetPicture lnbSetText lnbSetValue lnbSize lnbSort lnbSortByValue lnbText lnbValue load loadAbs ' +
    -        'loadBackpack loadFile loadGame loadIdentity loadMagazine loadOverlay loadStatus loadUniform ' +
    -        'loadVest local localize locationPosition lock lockCameraTo lockCargo lockDriver locked ' +
    -        'lockedCargo lockedDriver lockedTurret lockIdentity lockTurret lockWP log logEntities logNetwork ' +
    -        'logNetworkTerminate lookAt lookAtPos magazineCargo magazines magazinesAllTurrets magazinesAmmo ' +
    -        'magazinesAmmoCargo magazinesAmmoFull magazinesDetail magazinesDetailBackpack ' +
    -        'magazinesDetailUniform magazinesDetailVest magazinesTurret magazineTurretAmmo mapAnimAdd ' +
    -        'mapAnimClear mapAnimCommit mapAnimDone mapCenterOnCamera mapGridPosition markAsFinishedOnSteam ' +
    -        'markerAlpha markerBrush markerColor markerDir markerPos markerShape markerSize markerText ' +
    -        'markerType max members menuAction menuAdd menuChecked menuClear menuCollapse menuData menuDelete ' +
    -        'menuEnable menuEnabled menuExpand menuHover menuPicture menuSetAction menuSetCheck menuSetData ' +
    -        'menuSetPicture menuSetValue menuShortcut menuShortcutText menuSize menuSort menuText menuURL ' +
    -        'menuValue min mineActive mineDetectedBy missionConfigFile missionDifficulty missionName ' +
    -        'missionNamespace missionStart missionVersion mod modelToWorld modelToWorldVisual ' +
    -        'modelToWorldVisualWorld modelToWorldWorld modParams moonIntensity moonPhase morale move ' +
    -        'move3DENCamera moveInAny moveInCargo moveInCommander moveInDriver moveInGunner moveInTurret ' +
    -        'moveObjectToEnd moveOut moveTime moveTo moveToCompleted moveToFailed musicVolume name nameSound ' +
    -        'nearEntities nearestBuilding nearestLocation nearestLocations nearestLocationWithDubbing ' +
    -        'nearestObject nearestObjects nearestTerrainObjects nearObjects nearObjectsReady nearRoads ' +
    -        'nearSupplies nearTargets needReload netId netObjNull newOverlay nextMenuItemIndex ' +
    -        'nextWeatherChange nMenuItems not numberOfEnginesRTD numberToDate objectCurators objectFromNetId ' +
    -        'objectParent objStatus onBriefingGroup onBriefingNotes onBriefingPlan onBriefingTeamSwitch ' +
    -        'onCommandModeChanged onDoubleClick onEachFrame onGroupIconClick onGroupIconOverEnter ' +
    -        'onGroupIconOverLeave onHCGroupSelectionChanged onMapSingleClick onPlayerConnected ' +
    -        'onPlayerDisconnected onPreloadFinished onPreloadStarted onShowNewObject onTeamSwitch ' +
    -        'openCuratorInterface openDLCPage openMap openSteamApp openYoutubeVideo or orderGetIn overcast ' +
    -        'overcastForecast owner param params parseNumber parseSimpleArray parseText parsingNamespace ' +
    -        'particlesQuality pickWeaponPool pitch pixelGrid pixelGridBase pixelGridNoUIScale pixelH pixelW ' +
    -        'playableSlotsNumber playableUnits playAction playActionNow player playerRespawnTime playerSide ' +
    -        'playersNumber playGesture playMission playMove playMoveNow playMusic playScriptedMission ' +
    -        'playSound playSound3D position positionCameraToWorld posScreenToWorld posWorldToScreen ' +
    -        'ppEffectAdjust ppEffectCommit ppEffectCommitted ppEffectCreate ppEffectDestroy ppEffectEnable ' +
    -        'ppEffectEnabled ppEffectForceInNVG precision preloadCamera preloadObject preloadSound ' +
    -        'preloadTitleObj preloadTitleRsc preprocessFile preprocessFileLineNumbers primaryWeapon ' +
    -        'primaryWeaponItems primaryWeaponMagazine priority processDiaryLink productVersion profileName ' +
    -        'profileNamespace profileNameSteam progressLoadingScreen progressPosition progressSetPosition ' +
    -        'publicVariable publicVariableClient publicVariableServer pushBack pushBackUnique putWeaponPool ' +
    -        'queryItemsPool queryMagazinePool queryWeaponPool rad radioChannelAdd radioChannelCreate ' +
    -        'radioChannelRemove radioChannelSetCallSign radioChannelSetLabel radioVolume rain rainbow random ' +
    -        'rank rankId rating rectangular registeredTasks registerTask reload reloadEnabled remoteControl ' +
    -        'remoteExec remoteExecCall remoteExecutedOwner remove3DENConnection remove3DENEventHandler ' +
    -        'remove3DENLayer removeAction removeAll3DENEventHandlers removeAllActions removeAllAssignedItems ' +
    -        'removeAllContainers removeAllCuratorAddons removeAllCuratorCameraAreas ' +
    -        'removeAllCuratorEditingAreas removeAllEventHandlers removeAllHandgunItems removeAllItems ' +
    -        'removeAllItemsWithMagazines removeAllMissionEventHandlers removeAllMPEventHandlers ' +
    -        'removeAllMusicEventHandlers removeAllOwnedMines removeAllPrimaryWeaponItems removeAllWeapons ' +
    -        'removeBackpack removeBackpackGlobal removeCuratorAddons removeCuratorCameraArea ' +
    -        'removeCuratorEditableObjects removeCuratorEditingArea removeDrawIcon removeDrawLinks ' +
    -        'removeEventHandler removeFromRemainsCollector removeGoggles removeGroupIcon removeHandgunItem ' +
    -        'removeHeadgear removeItem removeItemFromBackpack removeItemFromUniform removeItemFromVest ' +
    -        'removeItems removeMagazine removeMagazineGlobal removeMagazines removeMagazinesTurret ' +
    -        'removeMagazineTurret removeMenuItem removeMissionEventHandler removeMPEventHandler ' +
    -        'removeMusicEventHandler removeOwnedMine removePrimaryWeaponItem removeSecondaryWeaponItem ' +
    -        'removeSimpleTask removeSwitchableUnit removeTeamMember removeUniform removeVest removeWeapon ' +
    -        'removeWeaponAttachmentCargo removeWeaponCargo removeWeaponGlobal removeWeaponTurret ' +
    -        'reportRemoteTarget requiredVersion resetCamShake resetSubgroupDirection resize resources ' +
    -        'respawnVehicle restartEditorCamera reveal revealMine reverse reversedMouseY roadAt ' +
    -        'roadsConnectedTo roleDescription ropeAttachedObjects ropeAttachedTo ropeAttachEnabled ' +
    -        'ropeAttachTo ropeCreate ropeCut ropeDestroy ropeDetach ropeEndPosition ropeLength ropes ' +
    -        'ropeUnwind ropeUnwound rotorsForcesRTD rotorsRpmRTD round runInitScript safeZoneH safeZoneW ' +
    -        'safeZoneWAbs safeZoneX safeZoneXAbs safeZoneY save3DENInventory saveGame saveIdentity ' +
    -        'saveJoysticks saveOverlay saveProfileNamespace saveStatus saveVar savingEnabled say say2D say3D ' +
    -        'scopeName score scoreSide screenshot screenToWorld scriptDone scriptName scudState ' +
    -        'secondaryWeapon secondaryWeaponItems secondaryWeaponMagazine select selectBestPlaces ' +
    -        'selectDiarySubject selectedEditorObjects selectEditorObject selectionNames selectionPosition ' +
    -        'selectLeader selectMax selectMin selectNoPlayer selectPlayer selectRandom selectRandomWeighted ' +
    -        'selectWeapon selectWeaponTurret sendAUMessage sendSimpleCommand sendTask sendTaskResult ' +
    -        'sendUDPMessage serverCommand serverCommandAvailable serverCommandExecutable serverName serverTime ' +
    -        'set set3DENAttribute set3DENAttributes set3DENGrid set3DENIconsVisible set3DENLayer ' +
    -        'set3DENLinesVisible set3DENLogicType set3DENMissionAttribute set3DENMissionAttributes ' +
    -        'set3DENModelsVisible set3DENObjectType set3DENSelected setAccTime setActualCollectiveRTD ' +
    -        'setAirplaneThrottle setAirportSide setAmmo setAmmoCargo setAmmoOnPylon setAnimSpeedCoef ' +
    -        'setAperture setApertureNew setArmoryPoints setAttributes setAutonomous setBehaviour ' +
    -        'setBleedingRemaining setBrakesRTD setCameraInterest setCamShakeDefParams setCamShakeParams ' +
    -        'setCamUseTI setCaptive setCenterOfMass setCollisionLight setCombatMode setCompassOscillation ' +
    -        'setConvoySeparation setCuratorCameraAreaCeiling setCuratorCoef setCuratorEditingAreaType ' +
    -        'setCuratorWaypointCost setCurrentChannel setCurrentTask setCurrentWaypoint setCustomAimCoef ' +
    -        'setCustomWeightRTD setDamage setDammage setDate setDebriefingText setDefaultCamera setDestination ' +
    -        'setDetailMapBlendPars setDir setDirection setDrawIcon setDriveOnPath setDropInterval ' +
    -        'setDynamicSimulationDistance setDynamicSimulationDistanceCoef setEditorMode setEditorObjectScope ' +
    -        'setEffectCondition setEngineRPMRTD setFace setFaceAnimation setFatigue setFeatureType ' +
    -        'setFlagAnimationPhase setFlagOwner setFlagSide setFlagTexture setFog setFormation ' +
    -        'setFormationTask setFormDir setFriend setFromEditor setFSMVariable setFuel setFuelCargo ' +
    -        'setGroupIcon setGroupIconParams setGroupIconsSelectable setGroupIconsVisible setGroupId ' +
    -        'setGroupIdGlobal setGroupOwner setGusts setHideBehind setHit setHitIndex setHitPointDamage ' +
    -        'setHorizonParallaxCoef setHUDMovementLevels setIdentity setImportance setInfoPanel setLeader ' +
    -        'setLightAmbient setLightAttenuation setLightBrightness setLightColor setLightDayLight ' +
    -        'setLightFlareMaxDistance setLightFlareSize setLightIntensity setLightnings setLightUseFlare ' +
    -        'setLocalWindParams setMagazineTurretAmmo setMarkerAlpha setMarkerAlphaLocal setMarkerBrush ' +
    -        'setMarkerBrushLocal setMarkerColor setMarkerColorLocal setMarkerDir setMarkerDirLocal ' +
    -        'setMarkerPos setMarkerPosLocal setMarkerShape setMarkerShapeLocal setMarkerSize ' +
    -        'setMarkerSizeLocal setMarkerText setMarkerTextLocal setMarkerType setMarkerTypeLocal setMass ' +
    -        'setMimic setMousePosition setMusicEffect setMusicEventHandler setName setNameSound ' +
    -        'setObjectArguments setObjectMaterial setObjectMaterialGlobal setObjectProxy setObjectTexture ' +
    -        'setObjectTextureGlobal setObjectViewDistance setOvercast setOwner setOxygenRemaining ' +
    -        'setParticleCircle setParticleClass setParticleFire setParticleParams setParticleRandom ' +
    -        'setPilotCameraDirection setPilotCameraRotation setPilotCameraTarget setPilotLight setPiPEffect ' +
    -        'setPitch setPlateNumber setPlayable setPlayerRespawnTime setPos setPosASL setPosASL2 setPosASLW ' +
    -        'setPosATL setPosition setPosWorld setPylonLoadOut setPylonsPriority setRadioMsg setRain ' +
    -        'setRainbow setRandomLip setRank setRectangular setRepairCargo setRotorBrakeRTD setShadowDistance ' +
    -        'setShotParents setSide setSimpleTaskAlwaysVisible setSimpleTaskCustomData ' +
    -        'setSimpleTaskDescription setSimpleTaskDestination setSimpleTaskTarget setSimpleTaskType ' +
    -        'setSimulWeatherLayers setSize setSkill setSlingLoad setSoundEffect setSpeaker setSpeech ' +
    -        'setSpeedMode setStamina setStaminaScheme setStatValue setSuppression setSystemOfUnits ' +
    -        'setTargetAge setTaskMarkerOffset setTaskResult setTaskState setTerrainGrid setText ' +
    -        'setTimeMultiplier setTitleEffect setTrafficDensity setTrafficDistance setTrafficGap ' +
    -        'setTrafficSpeed setTriggerActivation setTriggerArea setTriggerStatements setTriggerText ' +
    -        'setTriggerTimeout setTriggerType setType setUnconscious setUnitAbility setUnitLoadout setUnitPos ' +
    -        'setUnitPosWeak setUnitRank setUnitRecoilCoefficient setUnitTrait setUnloadInCombat ' +
    -        'setUserActionText setUserMFDText setUserMFDvalue setVariable setVectorDir setVectorDirAndUp ' +
    -        'setVectorUp setVehicleAmmo setVehicleAmmoDef setVehicleArmor setVehicleCargo setVehicleId ' +
    -        'setVehicleLock setVehiclePosition setVehicleRadar setVehicleReceiveRemoteTargets ' +
    -        'setVehicleReportOwnPosition setVehicleReportRemoteTargets setVehicleTIPars setVehicleVarName ' +
    -        'setVelocity setVelocityModelSpace setVelocityTransformation setViewDistance ' +
    -        'setVisibleIfTreeCollapsed setWantedRPMRTD setWaves setWaypointBehaviour setWaypointCombatMode ' +
    -        'setWaypointCompletionRadius setWaypointDescription setWaypointForceBehaviour setWaypointFormation ' +
    -        'setWaypointHousePosition setWaypointLoiterRadius setWaypointLoiterType setWaypointName ' +
    -        'setWaypointPosition setWaypointScript setWaypointSpeed setWaypointStatements setWaypointTimeout ' +
    -        'setWaypointType setWaypointVisible setWeaponReloadingTime setWind setWindDir setWindForce ' +
    -        'setWindStr setWingForceScaleRTD setWPPos show3DIcons showChat showCinemaBorder showCommandingMenu ' +
    -        'showCompass showCuratorCompass showGPS showHUD showLegend showMap shownArtilleryComputer ' +
    -        'shownChat shownCompass shownCuratorCompass showNewEditorObject shownGPS shownHUD shownMap ' +
    -        'shownPad shownRadio shownScoretable shownUAVFeed shownWarrant shownWatch showPad showRadio ' +
    -        'showScoretable showSubtitles showUAVFeed showWarrant showWatch showWaypoint showWaypoints side ' +
    -        'sideChat sideEnemy sideFriendly sideRadio simpleTasks simulationEnabled simulCloudDensity ' +
    -        'simulCloudOcclusion simulInClouds simulWeatherSync sin size sizeOf skill skillFinal skipTime ' +
    -        'sleep sliderPosition sliderRange sliderSetPosition sliderSetRange sliderSetSpeed sliderSpeed ' +
    -        'slingLoadAssistantShown soldierMagazines someAmmo sort soundVolume spawn speaker speed speedMode ' +
    -        'splitString sqrt squadParams stance startLoadingScreen step stop stopEngineRTD stopped str ' +
    -        'sunOrMoon supportInfo suppressFor surfaceIsWater surfaceNormal surfaceType swimInDepth ' +
    -        'switchableUnits switchAction switchCamera switchGesture switchLight switchMove ' +
    -        'synchronizedObjects synchronizedTriggers synchronizedWaypoints synchronizeObjectsAdd ' +
    -        'synchronizeObjectsRemove synchronizeTrigger synchronizeWaypoint systemChat systemOfUnits tan ' +
    -        'targetKnowledge targets targetsAggregate targetsQuery taskAlwaysVisible taskChildren ' +
    -        'taskCompleted taskCustomData taskDescription taskDestination taskHint taskMarkerOffset taskParent ' +
    -        'taskResult taskState taskType teamMember teamName teams teamSwitch teamSwitchEnabled teamType ' +
    -        'terminate terrainIntersect terrainIntersectASL terrainIntersectAtASL text textLog textLogFormat ' +
    -        'tg time timeMultiplier titleCut titleFadeOut titleObj titleRsc titleText toArray toFixed toLower ' +
    -        'toString toUpper triggerActivated triggerActivation triggerArea triggerAttachedVehicle ' +
    -        'triggerAttachObject triggerAttachVehicle triggerDynamicSimulation triggerStatements triggerText ' +
    -        'triggerTimeout triggerTimeoutCurrent triggerType turretLocal turretOwner turretUnit tvAdd tvClear ' +
    -        'tvCollapse tvCollapseAll tvCount tvCurSel tvData tvDelete tvExpand tvExpandAll tvPicture ' +
    -        'tvSetColor tvSetCurSel tvSetData tvSetPicture tvSetPictureColor tvSetPictureColorDisabled ' +
    -        'tvSetPictureColorSelected tvSetPictureRight tvSetPictureRightColor tvSetPictureRightColorDisabled ' +
    -        'tvSetPictureRightColorSelected tvSetText tvSetTooltip tvSetValue tvSort tvSortByValue tvText ' +
    -        'tvTooltip tvValue type typeName typeOf UAVControl uiNamespace uiSleep unassignCurator ' +
    -        'unassignItem unassignTeam unassignVehicle underwater uniform uniformContainer uniformItems ' +
    -        'uniformMagazines unitAddons unitAimPosition unitAimPositionVisual unitBackpack unitIsUAV unitPos ' +
    -        'unitReady unitRecoilCoefficient units unitsBelowHeight unlinkItem unlockAchievement ' +
    -        'unregisterTask updateDrawIcon updateMenuItem updateObjectTree useAISteeringComponent ' +
    -        'useAudioTimeForMoves userInputDisabled vectorAdd vectorCos vectorCrossProduct vectorDiff ' +
    -        'vectorDir vectorDirVisual vectorDistance vectorDistanceSqr vectorDotProduct vectorFromTo ' +
    -        'vectorMagnitude vectorMagnitudeSqr vectorModelToWorld vectorModelToWorldVisual vectorMultiply ' +
    -        'vectorNormalized vectorUp vectorUpVisual vectorWorldToModel vectorWorldToModelVisual vehicle ' +
    -        'vehicleCargoEnabled vehicleChat vehicleRadio vehicleReceiveRemoteTargets vehicleReportOwnPosition ' +
    -        'vehicleReportRemoteTargets vehicles vehicleVarName velocity velocityModelSpace verifySignature ' +
    -        'vest vestContainer vestItems vestMagazines viewDistance visibleCompass visibleGPS visibleMap ' +
    -        'visiblePosition visiblePositionASL visibleScoretable visibleWatch waves waypointAttachedObject ' +
    -        'waypointAttachedVehicle waypointAttachObject waypointAttachVehicle waypointBehaviour ' +
    -        'waypointCombatMode waypointCompletionRadius waypointDescription waypointForceBehaviour ' +
    -        'waypointFormation waypointHousePosition waypointLoiterRadius waypointLoiterType waypointName ' +
    -        'waypointPosition waypoints waypointScript waypointsEnabledUAV waypointShow waypointSpeed ' +
    -        'waypointStatements waypointTimeout waypointTimeoutCurrent waypointType waypointVisible ' +
    -        'weaponAccessories weaponAccessoriesCargo weaponCargo weaponDirection weaponInertia weaponLowered ' +
    -        'weapons weaponsItems weaponsItemsCargo weaponState weaponsTurret weightRTD WFSideText wind ',
    -      literal:
    -        'blufor civilian configNull controlNull displayNull east endl false grpNull independent lineBreak ' +
    -        'locationNull nil objNull opfor pi resistance scriptNull sideAmbientLife sideEmpty sideLogic ' +
    -        'sideUnknown taskNull teamMemberNull true west'
    -    },
    -    contains: [
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.NUMBER_MODE,
    -      VARIABLE,
    -      FUNCTION,
    -      STRINGS,
    -      PREPROCESSOR
    -    ],
    -    illegal: /#|^\$ /
    -  };
    -}
    -
    -module.exports = sqf;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/sql.js b/claude-code-source/node_modules/highlight.js/lib/languages/sql.js
    deleted file mode 100644
    index 18c2a43d..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/sql.js
    +++ /dev/null
    @@ -1,699 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/**
    - * Any of the passed expresssions may match
    - *
    - * Creates a huge this | this | that | that match
    - * @param {(RegExp | string)[] } args
    - * @returns {string}
    - */
    -function either(...args) {
    -  const joined = '(' + args.map((x) => source(x)).join("|") + ")";
    -  return joined;
    -}
    -
    -/*
    - Language: SQL
    - Website: https://en.wikipedia.org/wiki/SQL
    - Category: common, database
    - */
    -
    -function sql(hljs) {
    -  const COMMENT_MODE = hljs.COMMENT('--', '$');
    -  const STRING = {
    -    className: 'string',
    -    variants: [
    -      {
    -        begin: /'/,
    -        end: /'/,
    -        contains: [
    -          {begin: /''/ }
    -        ]
    -      }
    -    ]
    -  };
    -  const QUOTED_IDENTIFIER = {
    -    begin: /"/,
    -    end: /"/,
    -    contains: [ { begin: /""/ } ]
    -  };
    -
    -  const LITERALS = [
    -    "true",
    -    "false",
    -    // Not sure it's correct to call NULL literal, and clauses like IS [NOT] NULL look strange that way.
    -    // "null",
    -    "unknown"
    -  ];
    -
    -  const MULTI_WORD_TYPES = [
    -    "double precision",
    -    "large object",
    -    "with timezone",
    -    "without timezone"
    -  ];
    -
    -  const TYPES = [
    -    'bigint',
    -    'binary',
    -    'blob',
    -    'boolean',
    -    'char',
    -    'character',
    -    'clob',
    -    'date',
    -    'dec',
    -    'decfloat',
    -    'decimal',
    -    'float',
    -    'int',
    -    'integer',
    -    'interval',
    -    'nchar',
    -    'nclob',
    -    'national',
    -    'numeric',
    -    'real',
    -    'row',
    -    'smallint',
    -    'time',
    -    'timestamp',
    -    'varchar',
    -    'varying', // modifier (character varying)
    -    'varbinary'
    -  ];
    -
    -  const NON_RESERVED_WORDS = [
    -    "add",
    -    "asc",
    -    "collation",
    -    "desc",
    -    "final",
    -    "first",
    -    "last",
    -    "view"
    -  ];
    -
    -  // https://jakewheat.github.io/sql-overview/sql-2016-foundation-grammar.html#reserved-word
    -  const RESERVED_WORDS = [
    -    "abs",
    -    "acos",
    -    "all",
    -    "allocate",
    -    "alter",
    -    "and",
    -    "any",
    -    "are",
    -    "array",
    -    "array_agg",
    -    "array_max_cardinality",
    -    "as",
    -    "asensitive",
    -    "asin",
    -    "asymmetric",
    -    "at",
    -    "atan",
    -    "atomic",
    -    "authorization",
    -    "avg",
    -    "begin",
    -    "begin_frame",
    -    "begin_partition",
    -    "between",
    -    "bigint",
    -    "binary",
    -    "blob",
    -    "boolean",
    -    "both",
    -    "by",
    -    "call",
    -    "called",
    -    "cardinality",
    -    "cascaded",
    -    "case",
    -    "cast",
    -    "ceil",
    -    "ceiling",
    -    "char",
    -    "char_length",
    -    "character",
    -    "character_length",
    -    "check",
    -    "classifier",
    -    "clob",
    -    "close",
    -    "coalesce",
    -    "collate",
    -    "collect",
    -    "column",
    -    "commit",
    -    "condition",
    -    "connect",
    -    "constraint",
    -    "contains",
    -    "convert",
    -    "copy",
    -    "corr",
    -    "corresponding",
    -    "cos",
    -    "cosh",
    -    "count",
    -    "covar_pop",
    -    "covar_samp",
    -    "create",
    -    "cross",
    -    "cube",
    -    "cume_dist",
    -    "current",
    -    "current_catalog",
    -    "current_date",
    -    "current_default_transform_group",
    -    "current_path",
    -    "current_role",
    -    "current_row",
    -    "current_schema",
    -    "current_time",
    -    "current_timestamp",
    -    "current_path",
    -    "current_role",
    -    "current_transform_group_for_type",
    -    "current_user",
    -    "cursor",
    -    "cycle",
    -    "date",
    -    "day",
    -    "deallocate",
    -    "dec",
    -    "decimal",
    -    "decfloat",
    -    "declare",
    -    "default",
    -    "define",
    -    "delete",
    -    "dense_rank",
    -    "deref",
    -    "describe",
    -    "deterministic",
    -    "disconnect",
    -    "distinct",
    -    "double",
    -    "drop",
    -    "dynamic",
    -    "each",
    -    "element",
    -    "else",
    -    "empty",
    -    "end",
    -    "end_frame",
    -    "end_partition",
    -    "end-exec",
    -    "equals",
    -    "escape",
    -    "every",
    -    "except",
    -    "exec",
    -    "execute",
    -    "exists",
    -    "exp",
    -    "external",
    -    "extract",
    -    "false",
    -    "fetch",
    -    "filter",
    -    "first_value",
    -    "float",
    -    "floor",
    -    "for",
    -    "foreign",
    -    "frame_row",
    -    "free",
    -    "from",
    -    "full",
    -    "function",
    -    "fusion",
    -    "get",
    -    "global",
    -    "grant",
    -    "group",
    -    "grouping",
    -    "groups",
    -    "having",
    -    "hold",
    -    "hour",
    -    "identity",
    -    "in",
    -    "indicator",
    -    "initial",
    -    "inner",
    -    "inout",
    -    "insensitive",
    -    "insert",
    -    "int",
    -    "integer",
    -    "intersect",
    -    "intersection",
    -    "interval",
    -    "into",
    -    "is",
    -    "join",
    -    "json_array",
    -    "json_arrayagg",
    -    "json_exists",
    -    "json_object",
    -    "json_objectagg",
    -    "json_query",
    -    "json_table",
    -    "json_table_primitive",
    -    "json_value",
    -    "lag",
    -    "language",
    -    "large",
    -    "last_value",
    -    "lateral",
    -    "lead",
    -    "leading",
    -    "left",
    -    "like",
    -    "like_regex",
    -    "listagg",
    -    "ln",
    -    "local",
    -    "localtime",
    -    "localtimestamp",
    -    "log",
    -    "log10",
    -    "lower",
    -    "match",
    -    "match_number",
    -    "match_recognize",
    -    "matches",
    -    "max",
    -    "member",
    -    "merge",
    -    "method",
    -    "min",
    -    "minute",
    -    "mod",
    -    "modifies",
    -    "module",
    -    "month",
    -    "multiset",
    -    "national",
    -    "natural",
    -    "nchar",
    -    "nclob",
    -    "new",
    -    "no",
    -    "none",
    -    "normalize",
    -    "not",
    -    "nth_value",
    -    "ntile",
    -    "null",
    -    "nullif",
    -    "numeric",
    -    "octet_length",
    -    "occurrences_regex",
    -    "of",
    -    "offset",
    -    "old",
    -    "omit",
    -    "on",
    -    "one",
    -    "only",
    -    "open",
    -    "or",
    -    "order",
    -    "out",
    -    "outer",
    -    "over",
    -    "overlaps",
    -    "overlay",
    -    "parameter",
    -    "partition",
    -    "pattern",
    -    "per",
    -    "percent",
    -    "percent_rank",
    -    "percentile_cont",
    -    "percentile_disc",
    -    "period",
    -    "portion",
    -    "position",
    -    "position_regex",
    -    "power",
    -    "precedes",
    -    "precision",
    -    "prepare",
    -    "primary",
    -    "procedure",
    -    "ptf",
    -    "range",
    -    "rank",
    -    "reads",
    -    "real",
    -    "recursive",
    -    "ref",
    -    "references",
    -    "referencing",
    -    "regr_avgx",
    -    "regr_avgy",
    -    "regr_count",
    -    "regr_intercept",
    -    "regr_r2",
    -    "regr_slope",
    -    "regr_sxx",
    -    "regr_sxy",
    -    "regr_syy",
    -    "release",
    -    "result",
    -    "return",
    -    "returns",
    -    "revoke",
    -    "right",
    -    "rollback",
    -    "rollup",
    -    "row",
    -    "row_number",
    -    "rows",
    -    "running",
    -    "savepoint",
    -    "scope",
    -    "scroll",
    -    "search",
    -    "second",
    -    "seek",
    -    "select",
    -    "sensitive",
    -    "session_user",
    -    "set",
    -    "show",
    -    "similar",
    -    "sin",
    -    "sinh",
    -    "skip",
    -    "smallint",
    -    "some",
    -    "specific",
    -    "specifictype",
    -    "sql",
    -    "sqlexception",
    -    "sqlstate",
    -    "sqlwarning",
    -    "sqrt",
    -    "start",
    -    "static",
    -    "stddev_pop",
    -    "stddev_samp",
    -    "submultiset",
    -    "subset",
    -    "substring",
    -    "substring_regex",
    -    "succeeds",
    -    "sum",
    -    "symmetric",
    -    "system",
    -    "system_time",
    -    "system_user",
    -    "table",
    -    "tablesample",
    -    "tan",
    -    "tanh",
    -    "then",
    -    "time",
    -    "timestamp",
    -    "timezone_hour",
    -    "timezone_minute",
    -    "to",
    -    "trailing",
    -    "translate",
    -    "translate_regex",
    -    "translation",
    -    "treat",
    -    "trigger",
    -    "trim",
    -    "trim_array",
    -    "true",
    -    "truncate",
    -    "uescape",
    -    "union",
    -    "unique",
    -    "unknown",
    -    "unnest",
    -    "update   ",
    -    "upper",
    -    "user",
    -    "using",
    -    "value",
    -    "values",
    -    "value_of",
    -    "var_pop",
    -    "var_samp",
    -    "varbinary",
    -    "varchar",
    -    "varying",
    -    "versioning",
    -    "when",
    -    "whenever",
    -    "where",
    -    "width_bucket",
    -    "window",
    -    "with",
    -    "within",
    -    "without",
    -    "year",
    -  ];
    -
    -  // these are reserved words we have identified to be functions
    -  // and should only be highlighted in a dispatch-like context
    -  // ie, array_agg(...), etc.
    -  const RESERVED_FUNCTIONS = [
    -    "abs",
    -    "acos",
    -    "array_agg",
    -    "asin",
    -    "atan",
    -    "avg",
    -    "cast",
    -    "ceil",
    -    "ceiling",
    -    "coalesce",
    -    "corr",
    -    "cos",
    -    "cosh",
    -    "count",
    -    "covar_pop",
    -    "covar_samp",
    -    "cume_dist",
    -    "dense_rank",
    -    "deref",
    -    "element",
    -    "exp",
    -    "extract",
    -    "first_value",
    -    "floor",
    -    "json_array",
    -    "json_arrayagg",
    -    "json_exists",
    -    "json_object",
    -    "json_objectagg",
    -    "json_query",
    -    "json_table",
    -    "json_table_primitive",
    -    "json_value",
    -    "lag",
    -    "last_value",
    -    "lead",
    -    "listagg",
    -    "ln",
    -    "log",
    -    "log10",
    -    "lower",
    -    "max",
    -    "min",
    -    "mod",
    -    "nth_value",
    -    "ntile",
    -    "nullif",
    -    "percent_rank",
    -    "percentile_cont",
    -    "percentile_disc",
    -    "position",
    -    "position_regex",
    -    "power",
    -    "rank",
    -    "regr_avgx",
    -    "regr_avgy",
    -    "regr_count",
    -    "regr_intercept",
    -    "regr_r2",
    -    "regr_slope",
    -    "regr_sxx",
    -    "regr_sxy",
    -    "regr_syy",
    -    "row_number",
    -    "sin",
    -    "sinh",
    -    "sqrt",
    -    "stddev_pop",
    -    "stddev_samp",
    -    "substring",
    -    "substring_regex",
    -    "sum",
    -    "tan",
    -    "tanh",
    -    "translate",
    -    "translate_regex",
    -    "treat",
    -    "trim",
    -    "trim_array",
    -    "unnest",
    -    "upper",
    -    "value_of",
    -    "var_pop",
    -    "var_samp",
    -    "width_bucket",
    -  ];
    -
    -  // these functions can
    -  const POSSIBLE_WITHOUT_PARENS = [
    -    "current_catalog",
    -    "current_date",
    -    "current_default_transform_group",
    -    "current_path",
    -    "current_role",
    -    "current_schema",
    -    "current_transform_group_for_type",
    -    "current_user",
    -    "session_user",
    -    "system_time",
    -    "system_user",
    -    "current_time",
    -    "localtime",
    -    "current_timestamp",
    -    "localtimestamp"
    -  ];
    -
    -  // those exist to boost relevance making these very
    -  // "SQL like" keyword combos worth +1 extra relevance
    -  const COMBOS = [
    -    "create table",
    -    "insert into",
    -    "primary key",
    -    "foreign key",
    -    "not null",
    -    "alter table",
    -    "add constraint",
    -    "grouping sets",
    -    "on overflow",
    -    "character set",
    -    "respect nulls",
    -    "ignore nulls",
    -    "nulls first",
    -    "nulls last",
    -    "depth first",
    -    "breadth first"
    -  ];
    -
    -  const FUNCTIONS = RESERVED_FUNCTIONS;
    -
    -  const KEYWORDS = [...RESERVED_WORDS, ...NON_RESERVED_WORDS].filter((keyword) => {
    -    return !RESERVED_FUNCTIONS.includes(keyword);
    -  });
    -
    -  const VARIABLE = {
    -    className: "variable",
    -    begin: /@[a-z0-9]+/,
    -  };
    -
    -  const OPERATOR = {
    -    className: "operator",
    -    begin: /[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,
    -    relevance: 0,
    -  };
    -
    -  const FUNCTION_CALL = {
    -    begin: concat(/\b/, either(...FUNCTIONS), /\s*\(/),
    -    keywords: {
    -      built_in: FUNCTIONS
    -    }
    -  };
    -
    -  // keywords with less than 3 letters are reduced in relevancy
    -  function reduceRelevancy(list, {exceptions, when} = {}) {
    -    const qualifyFn = when;
    -    exceptions = exceptions || [];
    -    return list.map((item) => {
    -      if (item.match(/\|\d+$/) || exceptions.includes(item)) {
    -        return item;
    -      } else if (qualifyFn(item)) {
    -        return `${item}|0`;
    -      } else {
    -        return item;
    -      }
    -    });
    -  }
    -
    -  return {
    -    name: 'SQL',
    -    case_insensitive: true,
    -    // does not include {} or HTML tags ` x.length < 3 }),
    -      literal: LITERALS,
    -      type: TYPES,
    -      built_in: POSSIBLE_WITHOUT_PARENS
    -    },
    -    contains: [
    -      {
    -        begin: either(...COMBOS),
    -        keywords: {
    -          $pattern: /[\w\.]+/,
    -          keyword: KEYWORDS.concat(COMBOS),
    -          literal: LITERALS,
    -          type: TYPES
    -        },
    -      },
    -      {
    -        className: "type",
    -        begin: either(...MULTI_WORD_TYPES)
    -      },
    -      FUNCTION_CALL,
    -      VARIABLE,
    -      STRING,
    -      QUOTED_IDENTIFIER,
    -      hljs.C_NUMBER_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      COMMENT_MODE,
    -      OPERATOR
    -    ]
    -  };
    -}
    -
    -module.exports = sql;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/sql_more.js b/claude-code-source/node_modules/highlight.js/lib/languages/sql_more.js
    deleted file mode 100644
    index a45a19ff..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/sql_more.js
    +++ /dev/null
    @@ -1,183 +0,0 @@
    -/*
    - Language: SQL More (mix of MySQL, Oracle, etc)
    - Contributors: Nikolay Lisienko , Heiko August , Travis Odom , Vadimtro , Benjamin Auder 
    - Website: https://en.wikipedia.org/wiki/SQL
    - Category: database
    - */
    -
    -/*
    -
    -This is a preservation of the old bloated SQL grammar which includes pretty much
    -the kitchen sink because no one was keeping track of which keywords belong to
    -which databases.  This is likely to be removed in the future.
    -
    -- Oracle SQL should be factored into it's own 3rd party grammar.
    -- MySQL should be factored out into it's own 3rd party grammar.
    -
    -*/
    -
    -function sql_more(hljs) {
    -  var COMMENT_MODE = hljs.COMMENT('--', '$');
    -  return {
    -    name: 'SQL (more)',
    -    aliases: ["mysql", "oracle"],
    -    disableAutodetect: true,
    -    case_insensitive: true,
    -    illegal: /[<>{}*]/,
    -    contains: [
    -      {
    -        beginKeywords:
    -          'begin end start commit rollback savepoint lock alter create drop rename call ' +
    -          'delete do handler insert load replace select truncate update set show pragma grant ' +
    -          'merge describe use explain help declare prepare execute deallocate release ' +
    -          'unlock purge reset change stop analyze cache flush optimize repair kill ' +
    -          'install uninstall checksum restore check backup revoke comment values with',
    -        end: /;/, endsWithParent: true,
    -        keywords: {
    -          $pattern: /[\w\.]+/,
    -          keyword:
    -            'as abort abs absolute acc acce accep accept access accessed accessible account acos action activate add ' +
    -            'addtime admin administer advanced advise aes_decrypt aes_encrypt after agent aggregate ali alia alias ' +
    -            'all allocate allow alter always analyze ancillary and anti any anydata anydataset anyschema anytype apply ' +
    -            'archive archived archivelog are as asc ascii asin assembly assertion associate asynchronous at atan ' +
    -            'atn2 attr attri attrib attribu attribut attribute attributes audit authenticated authentication authid ' +
    -            'authors auto autoallocate autodblink autoextend automatic availability avg backup badfile basicfile ' +
    -            'before begin beginning benchmark between bfile bfile_base big bigfile bin binary_double binary_float ' +
    -            'binlog bit_and bit_count bit_length bit_or bit_xor bitmap blob_base block blocksize body both bound ' +
    -            'bucket buffer_cache buffer_pool build bulk by byte byteordermark bytes cache caching call calling cancel ' +
    -            'capacity cascade cascaded case cast catalog category ceil ceiling chain change changed char_base ' +
    -            'char_length character_length characters characterset charindex charset charsetform charsetid check ' +
    -            'checksum checksum_agg child choose chr chunk class cleanup clear client clob clob_base clone close ' +
    -            'cluster_id cluster_probability cluster_set clustering coalesce coercibility col collate collation ' +
    -            'collect colu colum column column_value columns columns_updated comment commit compact compatibility ' +
    -            'compiled complete composite_limit compound compress compute concat concat_ws concurrent confirm conn ' +
    -            'connec connect connect_by_iscycle connect_by_isleaf connect_by_root connect_time connection ' +
    -            'consider consistent constant constraint constraints constructor container content contents context ' +
    -            'contributors controlfile conv convert convert_tz corr corr_k corr_s corresponding corruption cos cost ' +
    -            'count count_big counted covar_pop covar_samp cpu_per_call cpu_per_session crc32 create creation ' +
    -            'critical cross cube cume_dist curdate current current_date current_time current_timestamp current_user ' +
    -            'cursor curtime customdatum cycle data database databases datafile datafiles datalength date_add ' +
    -            'date_cache date_format date_sub dateadd datediff datefromparts datename datepart datetime2fromparts ' +
    -            'day day_to_second dayname dayofmonth dayofweek dayofyear days db_role_change dbtimezone ddl deallocate ' +
    -            'declare decode decompose decrement decrypt deduplicate def defa defau defaul default defaults ' +
    -            'deferred defi defin define degrees delayed delegate delete delete_all delimited demand dense_rank ' +
    -            'depth dequeue des_decrypt des_encrypt des_key_file desc descr descri describ describe descriptor ' +
    -            'deterministic diagnostics difference dimension direct_load directory disable disable_all ' +
    -            'disallow disassociate discardfile disconnect diskgroup distinct distinctrow distribute distributed div ' +
    -            'do document domain dotnet double downgrade drop dumpfile duplicate duration each edition editionable ' +
    -            'editions element ellipsis else elsif elt empty enable enable_all enclosed encode encoding encrypt ' +
    -            'end end-exec endian enforced engine engines enqueue enterprise entityescaping eomonth error errors ' +
    -            'escaped evalname evaluate event eventdata events except exception exceptions exchange exclude excluding ' +
    -            'execu execut execute exempt exists exit exp expire explain explode export export_set extended extent external ' +
    -            'external_1 external_2 externally extract failed failed_login_attempts failover failure far fast ' +
    -            'feature_set feature_value fetch field fields file file_name_convert filesystem_like_logging final ' +
    -            'finish first first_value fixed flash_cache flashback floor flush following follows for forall force foreign ' +
    -            'form forma format found found_rows freelist freelists freepools fresh from from_base64 from_days ' +
    -            'ftp full function general generated get get_format get_lock getdate getutcdate global global_name ' +
    -            'globally go goto grant grants greatest group group_concat group_id grouping grouping_id groups ' +
    -            'gtid_subtract guarantee guard handler hash hashkeys having hea head headi headin heading heap help hex ' +
    -            'hierarchy high high_priority hosts hour hours http id ident_current ident_incr ident_seed identified ' +
    -            'identity idle_time if ifnull ignore iif ilike ilm immediate import in include including increment ' +
    -            'index indexes indexing indextype indicator indices inet6_aton inet6_ntoa inet_aton inet_ntoa infile ' +
    -            'initial initialized initially initrans inmemory inner innodb input insert install instance instantiable ' +
    -            'instr interface interleaved intersect into invalidate invisible is is_free_lock is_ipv4 is_ipv4_compat ' +
    -            'is_not is_not_null is_used_lock isdate isnull isolation iterate java join json json_exists ' +
    -            'keep keep_duplicates key keys kill language large last last_day last_insert_id last_value lateral lax lcase ' +
    -            'lead leading least leaves left len lenght length less level levels library like like2 like4 likec limit ' +
    -            'lines link list listagg little ln load load_file lob lobs local localtime localtimestamp locate ' +
    -            'locator lock locked log log10 log2 logfile logfiles logging logical logical_reads_per_call ' +
    -            'logoff logon logs long loop low low_priority lower lpad lrtrim ltrim main make_set makedate maketime ' +
    -            'managed management manual map mapping mask master master_pos_wait match matched materialized max ' +
    -            'maxextents maximize maxinstances maxlen maxlogfiles maxloghistory maxlogmembers maxsize maxtrans ' +
    -            'md5 measures median medium member memcompress memory merge microsecond mid migration min minextents ' +
    -            'minimum mining minus minute minutes minvalue missing mod mode model modification modify module monitoring month ' +
    -            'months mount move movement multiset mutex name name_const names nan national native natural nav nchar ' +
    -            'nclob nested never new newline next nextval no no_write_to_binlog noarchivelog noaudit nobadfile ' +
    -            'nocheck nocompress nocopy nocycle nodelay nodiscardfile noentityescaping noguarantee nokeep nologfile ' +
    -            'nomapping nomaxvalue nominimize nominvalue nomonitoring none noneditionable nonschema noorder ' +
    -            'nopr nopro noprom nopromp noprompt norely noresetlogs noreverse normal norowdependencies noschemacheck ' +
    -            'noswitch not nothing notice notnull notrim novalidate now nowait nth_value nullif nulls num numb numbe ' +
    -            'nvarchar nvarchar2 object ocicoll ocidate ocidatetime ociduration ociinterval ociloblocator ocinumber ' +
    -            'ociref ocirefcursor ocirowid ocistring ocitype oct octet_length of off offline offset oid oidindex old ' +
    -            'on online only opaque open operations operator optimal optimize option optionally or oracle oracle_date ' +
    -            'oradata ord ordaudio orddicom orddoc order ordimage ordinality ordvideo organization orlany orlvary ' +
    -            'out outer outfile outline output over overflow overriding package pad parallel parallel_enable ' +
    -            'parameters parent parse partial partition partitions pascal passing password password_grace_time ' +
    -            'password_lock_time password_reuse_max password_reuse_time password_verify_function patch path patindex ' +
    -            'pctincrease pctthreshold pctused pctversion percent percent_rank percentile_cont percentile_disc ' +
    -            'performance period period_add period_diff permanent physical pi pipe pipelined pivot pluggable plugin ' +
    -            'policy position post_transaction pow power pragma prebuilt precedes preceding precision prediction ' +
    -            'prediction_cost prediction_details prediction_probability prediction_set prepare present preserve ' +
    -            'prior priority private private_sga privileges procedural procedure procedure_analyze processlist ' +
    -            'profiles project prompt protection public publishingservername purge quarter query quick quiesce quota ' +
    -            'quotename radians raise rand range rank raw read reads readsize rebuild record records ' +
    -            'recover recovery recursive recycle redo reduced ref reference referenced references referencing refresh ' +
    -            'regexp_like register regr_avgx regr_avgy regr_count regr_intercept regr_r2 regr_slope regr_sxx regr_sxy ' +
    -            'reject rekey relational relative relaylog release release_lock relies_on relocate rely rem remainder rename ' +
    -            'repair repeat replace replicate replication required reset resetlogs resize resource respect restore ' +
    -            'restricted result result_cache resumable resume retention return returning returns reuse reverse revoke ' +
    -            'right rlike role roles rollback rolling rollup round row row_count rowdependencies rowid rownum rows ' +
    -            'rtrim rules safe salt sample save savepoint sb1 sb2 sb4 scan schema schemacheck scn scope scroll ' +
    -            'sdo_georaster sdo_topo_geometry search sec_to_time second seconds section securefile security seed segment select ' +
    -            'self semi sequence sequential serializable server servererror session session_user sessions_per_user set ' +
    -            'sets settings sha sha1 sha2 share shared shared_pool short show shrink shutdown si_averagecolor ' +
    -            'si_colorhistogram si_featurelist si_positionalcolor si_stillimage si_texture siblings sid sign sin ' +
    -            'size size_t sizes skip slave sleep smalldatetimefromparts smallfile snapshot some soname sort soundex ' +
    -            'source space sparse spfile split sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows ' +
    -            'sql_small_result sql_variant_property sqlcode sqldata sqlerror sqlname sqlstate sqrt square standalone ' +
    -            'standby start starting startup statement static statistics stats_binomial_test stats_crosstab ' +
    -            'stats_ks_test stats_mode stats_mw_test stats_one_way_anova stats_t_test_ stats_t_test_indep ' +
    -            'stats_t_test_one stats_t_test_paired stats_wsr_test status std stddev stddev_pop stddev_samp stdev ' +
    -            'stop storage store stored str str_to_date straight_join strcmp strict string struct stuff style subdate ' +
    -            'subpartition subpartitions substitutable substr substring subtime subtring_index subtype success sum ' +
    -            'suspend switch switchoffset switchover sync synchronous synonym sys sys_xmlagg sysasm sysaux sysdate ' +
    -            'sysdatetimeoffset sysdba sysoper system system_user sysutcdatetime table tables tablespace tablesample tan tdo ' +
    -            'template temporary terminated tertiary_weights test than then thread through tier ties time time_format ' +
    -            'time_zone timediff timefromparts timeout timestamp timestampadd timestampdiff timezone_abbr ' +
    -            'timezone_minute timezone_region to to_base64 to_date to_days to_seconds todatetimeoffset trace tracking ' +
    -            'transaction transactional translate translation treat trigger trigger_nestlevel triggers trim truncate ' +
    -            'try_cast try_convert try_parse type ub1 ub2 ub4 ucase unarchived unbounded uncompress ' +
    -            'under undo unhex unicode uniform uninstall union unique unix_timestamp unknown unlimited unlock unnest unpivot ' +
    -            'unrecoverable unsafe unsigned until untrusted unusable unused update updated upgrade upped upper upsert ' +
    -            'url urowid usable usage use use_stored_outlines user user_data user_resources users using utc_date ' +
    -            'utc_timestamp uuid uuid_short validate validate_password_strength validation valist value values var ' +
    -            'var_samp varcharc vari varia variab variabl variable variables variance varp varraw varrawc varray ' +
    -            'verify version versions view virtual visible void wait wallet warning warnings week weekday weekofyear ' +
    -            'wellformed when whene whenev wheneve whenever where while whitespace window with within without work wrapped ' +
    -            'xdb xml xmlagg xmlattributes xmlcast xmlcolattval xmlelement xmlexists xmlforest xmlindex xmlnamespaces ' +
    -            'xmlpi xmlquery xmlroot xmlschema xmlserialize xmltable xmltype xor year year_to_month years yearweek',
    -          literal:
    -            'true false null unknown',
    -          built_in:
    -            'array bigint binary bit blob bool boolean char character date dec decimal float int int8 integer interval number ' +
    -            'numeric real record serial serial8 smallint text time timestamp tinyint varchar varchar2 varying void'
    -        },
    -        contains: [
    -          {
    -            className: 'string',
    -            begin: '\'', end: '\'',
    -            contains: [{begin: '\'\''}]
    -          },
    -          {
    -            className: 'string',
    -            begin: '"', end: '"',
    -            contains: [{begin: '""'}]
    -          },
    -          {
    -            className: 'string',
    -            begin: '`', end: '`'
    -          },
    -          hljs.C_NUMBER_MODE,
    -          hljs.C_BLOCK_COMMENT_MODE,
    -          COMMENT_MODE,
    -          hljs.HASH_COMMENT_MODE
    -        ]
    -      },
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      COMMENT_MODE,
    -      hljs.HASH_COMMENT_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = sql_more;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/stan.js b/claude-code-source/node_modules/highlight.js/lib/languages/stan.js
    deleted file mode 100644
    index 50c8bdf5..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/stan.js
    +++ /dev/null
    @@ -1,548 +0,0 @@
    -/*
    -Language: Stan
    -Description: The Stan probabilistic programming language
    -Author: Jeffrey B. Arnold 
    -Website: http://mc-stan.org/
    -Category: scientific
    -*/
    -
    -function stan(hljs) {
    -  // variable names cannot conflict with block identifiers
    -  const BLOCKS = [
    -    'functions',
    -    'model',
    -    'data',
    -    'parameters',
    -    'quantities',
    -    'transformed',
    -    'generated'
    -  ];
    -  const STATEMENTS = [
    -    'for',
    -    'in',
    -    'if',
    -    'else',
    -    'while',
    -    'break',
    -    'continue',
    -    'return'
    -  ];
    -  const SPECIAL_FUNCTIONS = [
    -    'print',
    -    'reject',
    -    'increment_log_prob|10',
    -    'integrate_ode|10',
    -    'integrate_ode_rk45|10',
    -    'integrate_ode_bdf|10',
    -    'algebra_solver'
    -  ];
    -  const VAR_TYPES = [
    -    'int',
    -    'real',
    -    'vector',
    -    'ordered',
    -    'positive_ordered',
    -    'simplex',
    -    'unit_vector',
    -    'row_vector',
    -    'matrix',
    -    'cholesky_factor_corr|10',
    -    'cholesky_factor_cov|10',
    -    'corr_matrix|10',
    -    'cov_matrix|10',
    -    'void'
    -  ];
    -  const FUNCTIONS = [
    -    'Phi',
    -    'Phi_approx',
    -    'abs',
    -    'acos',
    -    'acosh',
    -    'algebra_solver',
    -    'append_array',
    -    'append_col',
    -    'append_row',
    -    'asin',
    -    'asinh',
    -    'atan',
    -    'atan2',
    -    'atanh',
    -    'bernoulli_cdf',
    -    'bernoulli_lccdf',
    -    'bernoulli_lcdf',
    -    'bernoulli_logit_lpmf',
    -    'bernoulli_logit_rng',
    -    'bernoulli_lpmf',
    -    'bernoulli_rng',
    -    'bessel_first_kind',
    -    'bessel_second_kind',
    -    'beta_binomial_cdf',
    -    'beta_binomial_lccdf',
    -    'beta_binomial_lcdf',
    -    'beta_binomial_lpmf',
    -    'beta_binomial_rng',
    -    'beta_cdf',
    -    'beta_lccdf',
    -    'beta_lcdf',
    -    'beta_lpdf',
    -    'beta_rng',
    -    'binary_log_loss',
    -    'binomial_cdf',
    -    'binomial_coefficient_log',
    -    'binomial_lccdf',
    -    'binomial_lcdf',
    -    'binomial_logit_lpmf',
    -    'binomial_lpmf',
    -    'binomial_rng',
    -    'block',
    -    'categorical_logit_lpmf',
    -    'categorical_logit_rng',
    -    'categorical_lpmf',
    -    'categorical_rng',
    -    'cauchy_cdf',
    -    'cauchy_lccdf',
    -    'cauchy_lcdf',
    -    'cauchy_lpdf',
    -    'cauchy_rng',
    -    'cbrt',
    -    'ceil',
    -    'chi_square_cdf',
    -    'chi_square_lccdf',
    -    'chi_square_lcdf',
    -    'chi_square_lpdf',
    -    'chi_square_rng',
    -    'cholesky_decompose',
    -    'choose',
    -    'col',
    -    'cols',
    -    'columns_dot_product',
    -    'columns_dot_self',
    -    'cos',
    -    'cosh',
    -    'cov_exp_quad',
    -    'crossprod',
    -    'csr_extract_u',
    -    'csr_extract_v',
    -    'csr_extract_w',
    -    'csr_matrix_times_vector',
    -    'csr_to_dense_matrix',
    -    'cumulative_sum',
    -    'determinant',
    -    'diag_matrix',
    -    'diag_post_multiply',
    -    'diag_pre_multiply',
    -    'diagonal',
    -    'digamma',
    -    'dims',
    -    'dirichlet_lpdf',
    -    'dirichlet_rng',
    -    'distance',
    -    'dot_product',
    -    'dot_self',
    -    'double_exponential_cdf',
    -    'double_exponential_lccdf',
    -    'double_exponential_lcdf',
    -    'double_exponential_lpdf',
    -    'double_exponential_rng',
    -    'e',
    -    'eigenvalues_sym',
    -    'eigenvectors_sym',
    -    'erf',
    -    'erfc',
    -    'exp',
    -    'exp2',
    -    'exp_mod_normal_cdf',
    -    'exp_mod_normal_lccdf',
    -    'exp_mod_normal_lcdf',
    -    'exp_mod_normal_lpdf',
    -    'exp_mod_normal_rng',
    -    'expm1',
    -    'exponential_cdf',
    -    'exponential_lccdf',
    -    'exponential_lcdf',
    -    'exponential_lpdf',
    -    'exponential_rng',
    -    'fabs',
    -    'falling_factorial',
    -    'fdim',
    -    'floor',
    -    'fma',
    -    'fmax',
    -    'fmin',
    -    'fmod',
    -    'frechet_cdf',
    -    'frechet_lccdf',
    -    'frechet_lcdf',
    -    'frechet_lpdf',
    -    'frechet_rng',
    -    'gamma_cdf',
    -    'gamma_lccdf',
    -    'gamma_lcdf',
    -    'gamma_lpdf',
    -    'gamma_p',
    -    'gamma_q',
    -    'gamma_rng',
    -    'gaussian_dlm_obs_lpdf',
    -    'get_lp',
    -    'gumbel_cdf',
    -    'gumbel_lccdf',
    -    'gumbel_lcdf',
    -    'gumbel_lpdf',
    -    'gumbel_rng',
    -    'head',
    -    'hypergeometric_lpmf',
    -    'hypergeometric_rng',
    -    'hypot',
    -    'inc_beta',
    -    'int_step',
    -    'integrate_ode',
    -    'integrate_ode_bdf',
    -    'integrate_ode_rk45',
    -    'inv',
    -    'inv_Phi',
    -    'inv_chi_square_cdf',
    -    'inv_chi_square_lccdf',
    -    'inv_chi_square_lcdf',
    -    'inv_chi_square_lpdf',
    -    'inv_chi_square_rng',
    -    'inv_cloglog',
    -    'inv_gamma_cdf',
    -    'inv_gamma_lccdf',
    -    'inv_gamma_lcdf',
    -    'inv_gamma_lpdf',
    -    'inv_gamma_rng',
    -    'inv_logit',
    -    'inv_sqrt',
    -    'inv_square',
    -    'inv_wishart_lpdf',
    -    'inv_wishart_rng',
    -    'inverse',
    -    'inverse_spd',
    -    'is_inf',
    -    'is_nan',
    -    'lbeta',
    -    'lchoose',
    -    'lgamma',
    -    'lkj_corr_cholesky_lpdf',
    -    'lkj_corr_cholesky_rng',
    -    'lkj_corr_lpdf',
    -    'lkj_corr_rng',
    -    'lmgamma',
    -    'lmultiply',
    -    'log',
    -    'log10',
    -    'log1m',
    -    'log1m_exp',
    -    'log1m_inv_logit',
    -    'log1p',
    -    'log1p_exp',
    -    'log2',
    -    'log_determinant',
    -    'log_diff_exp',
    -    'log_falling_factorial',
    -    'log_inv_logit',
    -    'log_mix',
    -    'log_rising_factorial',
    -    'log_softmax',
    -    'log_sum_exp',
    -    'logistic_cdf',
    -    'logistic_lccdf',
    -    'logistic_lcdf',
    -    'logistic_lpdf',
    -    'logistic_rng',
    -    'logit',
    -    'lognormal_cdf',
    -    'lognormal_lccdf',
    -    'lognormal_lcdf',
    -    'lognormal_lpdf',
    -    'lognormal_rng',
    -    'machine_precision',
    -    'matrix_exp',
    -    'max',
    -    'mdivide_left_spd',
    -    'mdivide_left_tri_low',
    -    'mdivide_right_spd',
    -    'mdivide_right_tri_low',
    -    'mean',
    -    'min',
    -    'modified_bessel_first_kind',
    -    'modified_bessel_second_kind',
    -    'multi_gp_cholesky_lpdf',
    -    'multi_gp_lpdf',
    -    'multi_normal_cholesky_lpdf',
    -    'multi_normal_cholesky_rng',
    -    'multi_normal_lpdf',
    -    'multi_normal_prec_lpdf',
    -    'multi_normal_rng',
    -    'multi_student_t_lpdf',
    -    'multi_student_t_rng',
    -    'multinomial_lpmf',
    -    'multinomial_rng',
    -    'multiply_log',
    -    'multiply_lower_tri_self_transpose',
    -    'neg_binomial_2_cdf',
    -    'neg_binomial_2_lccdf',
    -    'neg_binomial_2_lcdf',
    -    'neg_binomial_2_log_lpmf',
    -    'neg_binomial_2_log_rng',
    -    'neg_binomial_2_lpmf',
    -    'neg_binomial_2_rng',
    -    'neg_binomial_cdf',
    -    'neg_binomial_lccdf',
    -    'neg_binomial_lcdf',
    -    'neg_binomial_lpmf',
    -    'neg_binomial_rng',
    -    'negative_infinity',
    -    'normal_cdf',
    -    'normal_lccdf',
    -    'normal_lcdf',
    -    'normal_lpdf',
    -    'normal_rng',
    -    'not_a_number',
    -    'num_elements',
    -    'ordered_logistic_lpmf',
    -    'ordered_logistic_rng',
    -    'owens_t',
    -    'pareto_cdf',
    -    'pareto_lccdf',
    -    'pareto_lcdf',
    -    'pareto_lpdf',
    -    'pareto_rng',
    -    'pareto_type_2_cdf',
    -    'pareto_type_2_lccdf',
    -    'pareto_type_2_lcdf',
    -    'pareto_type_2_lpdf',
    -    'pareto_type_2_rng',
    -    'pi',
    -    'poisson_cdf',
    -    'poisson_lccdf',
    -    'poisson_lcdf',
    -    'poisson_log_lpmf',
    -    'poisson_log_rng',
    -    'poisson_lpmf',
    -    'poisson_rng',
    -    'positive_infinity',
    -    'pow',
    -    'print',
    -    'prod',
    -    'qr_Q',
    -    'qr_R',
    -    'quad_form',
    -    'quad_form_diag',
    -    'quad_form_sym',
    -    'rank',
    -    'rayleigh_cdf',
    -    'rayleigh_lccdf',
    -    'rayleigh_lcdf',
    -    'rayleigh_lpdf',
    -    'rayleigh_rng',
    -    'reject',
    -    'rep_array',
    -    'rep_matrix',
    -    'rep_row_vector',
    -    'rep_vector',
    -    'rising_factorial',
    -    'round',
    -    'row',
    -    'rows',
    -    'rows_dot_product',
    -    'rows_dot_self',
    -    'scaled_inv_chi_square_cdf',
    -    'scaled_inv_chi_square_lccdf',
    -    'scaled_inv_chi_square_lcdf',
    -    'scaled_inv_chi_square_lpdf',
    -    'scaled_inv_chi_square_rng',
    -    'sd',
    -    'segment',
    -    'sin',
    -    'singular_values',
    -    'sinh',
    -    'size',
    -    'skew_normal_cdf',
    -    'skew_normal_lccdf',
    -    'skew_normal_lcdf',
    -    'skew_normal_lpdf',
    -    'skew_normal_rng',
    -    'softmax',
    -    'sort_asc',
    -    'sort_desc',
    -    'sort_indices_asc',
    -    'sort_indices_desc',
    -    'sqrt',
    -    'sqrt2',
    -    'square',
    -    'squared_distance',
    -    'step',
    -    'student_t_cdf',
    -    'student_t_lccdf',
    -    'student_t_lcdf',
    -    'student_t_lpdf',
    -    'student_t_rng',
    -    'sub_col',
    -    'sub_row',
    -    'sum',
    -    'tail',
    -    'tan',
    -    'tanh',
    -    'target',
    -    'tcrossprod',
    -    'tgamma',
    -    'to_array_1d',
    -    'to_array_2d',
    -    'to_matrix',
    -    'to_row_vector',
    -    'to_vector',
    -    'trace',
    -    'trace_gen_quad_form',
    -    'trace_quad_form',
    -    'trigamma',
    -    'trunc',
    -    'uniform_cdf',
    -    'uniform_lccdf',
    -    'uniform_lcdf',
    -    'uniform_lpdf',
    -    'uniform_rng',
    -    'variance',
    -    'von_mises_lpdf',
    -    'von_mises_rng',
    -    'weibull_cdf',
    -    'weibull_lccdf',
    -    'weibull_lcdf',
    -    'weibull_lpdf',
    -    'weibull_rng',
    -    'wiener_lpdf',
    -    'wishart_lpdf',
    -    'wishart_rng'
    -  ];
    -  const DISTRIBUTIONS = [
    -    'bernoulli',
    -    'bernoulli_logit',
    -    'beta',
    -    'beta_binomial',
    -    'binomial',
    -    'binomial_logit',
    -    'categorical',
    -    'categorical_logit',
    -    'cauchy',
    -    'chi_square',
    -    'dirichlet',
    -    'double_exponential',
    -    'exp_mod_normal',
    -    'exponential',
    -    'frechet',
    -    'gamma',
    -    'gaussian_dlm_obs',
    -    'gumbel',
    -    'hypergeometric',
    -    'inv_chi_square',
    -    'inv_gamma',
    -    'inv_wishart',
    -    'lkj_corr',
    -    'lkj_corr_cholesky',
    -    'logistic',
    -    'lognormal',
    -    'multi_gp',
    -    'multi_gp_cholesky',
    -    'multi_normal',
    -    'multi_normal_cholesky',
    -    'multi_normal_prec',
    -    'multi_student_t',
    -    'multinomial',
    -    'neg_binomial',
    -    'neg_binomial_2',
    -    'neg_binomial_2_log',
    -    'normal',
    -    'ordered_logistic',
    -    'pareto',
    -    'pareto_type_2',
    -    'poisson',
    -    'poisson_log',
    -    'rayleigh',
    -    'scaled_inv_chi_square',
    -    'skew_normal',
    -    'student_t',
    -    'uniform',
    -    'von_mises',
    -    'weibull',
    -    'wiener',
    -    'wishart'
    -  ];
    -
    -  return {
    -    name: 'Stan',
    -    aliases: [ 'stanfuncs' ],
    -    keywords: {
    -      $pattern: hljs.IDENT_RE,
    -      title: BLOCKS,
    -      keyword: STATEMENTS.concat(VAR_TYPES).concat(SPECIAL_FUNCTIONS),
    -      built_in: FUNCTIONS
    -    },
    -    contains: [
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.COMMENT(
    -        /#/,
    -        /$/,
    -        {
    -          relevance: 0,
    -          keywords: {
    -            'meta-keyword': 'include'
    -          }
    -        }
    -      ),
    -      hljs.COMMENT(
    -        /\/\*/,
    -        /\*\//,
    -        {
    -          relevance: 0,
    -          // highlight doc strings mentioned in Stan reference
    -          contains: [
    -            {
    -              className: 'doctag',
    -              begin: /@(return|param)/
    -            }
    -          ]
    -        }
    -      ),
    -      {
    -        // hack: in range constraints, lower must follow "<"
    -        begin: /<\s*lower\s*=/,
    -        keywords: 'lower'
    -      },
    -      {
    -        // hack: in range constraints, upper must follow either , or <
    -        //  or 
    -        begin: /[<,]\s*upper\s*=/,
    -        keywords: 'upper'
    -      },
    -      {
    -        className: 'keyword',
    -        begin: /\btarget\s*\+=/,
    -        relevance: 10
    -      },
    -      {
    -        begin: '~\\s*(' + hljs.IDENT_RE + ')\\s*\\(',
    -        keywords: DISTRIBUTIONS
    -      },
    -      {
    -        className: 'number',
    -        variants: [
    -          {
    -            begin: /\b\d+(?:\.\d*)?(?:[eE][+-]?\d+)?/
    -          },
    -          {
    -            begin: /\.\d+(?:[eE][+-]?\d+)?\b/
    -          }
    -        ],
    -        relevance: 0
    -      },
    -      {
    -        className: 'string',
    -        begin: '"',
    -        end: '"',
    -        relevance: 0
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = stan;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/stata.js b/claude-code-source/node_modules/highlight.js/lib/languages/stata.js
    deleted file mode 100644
    index 7a9561d4..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/stata.js
    +++ /dev/null
    @@ -1,60 +0,0 @@
    -/*
    -Language: Stata
    -Author: Brian Quistorff 
    -Contributors: Drew McDonald 
    -Description: Stata is a general-purpose statistical software package created in 1985 by StataCorp.
    -Website: https://en.wikipedia.org/wiki/Stata
    -Category: scientific
    -*/
    -
    -/*
    -  This is a fork and modification of Drew McDonald's file (https://github.com/drewmcdonald/stata-highlighting). I have also included a list of builtin commands from https://bugs.kde.org/show_bug.cgi?id=135646.
    -*/
    -
    -function stata(hljs) {
    -  return {
    -    name: 'Stata',
    -    aliases: [
    -      'do',
    -      'ado'
    -    ],
    -    case_insensitive: true,
    -    keywords: 'if else in foreach for forv forva forval forvalu forvalue forvalues by bys bysort xi quietly qui capture about ac ac_7 acprplot acprplot_7 adjust ado adopath adoupdate alpha ameans an ano anov anova anova_estat anova_terms anovadef aorder ap app appe appen append arch arch_dr arch_estat arch_p archlm areg areg_p args arima arima_dr arima_estat arima_p as asmprobit asmprobit_estat asmprobit_lf asmprobit_mfx__dlg asmprobit_p ass asse asser assert avplot avplot_7 avplots avplots_7 bcskew0 bgodfrey bias binreg bip0_lf biplot bipp_lf bipr_lf bipr_p biprobit bitest bitesti bitowt blogit bmemsize boot bootsamp bootstrap bootstrap_8 boxco_l boxco_p boxcox boxcox_6 boxcox_p bprobit br break brier bro brow brows browse brr brrstat bs bs_7 bsampl_w bsample bsample_7 bsqreg bstat bstat_7 bstat_8 bstrap bstrap_7 bubble bubbleplot ca ca_estat ca_p cabiplot camat canon canon_8 canon_8_p canon_estat canon_p cap caprojection capt captu captur capture cat cc cchart cchart_7 cci cd censobs_table centile cf char chdir checkdlgfiles checkestimationsample checkhlpfiles checksum chelp ci cii cl class classutil clear cli clis clist clo clog clog_lf clog_p clogi clogi_sw clogit clogit_lf clogit_p clogitp clogl_sw cloglog clonevar clslistarray cluster cluster_measures cluster_stop cluster_tree cluster_tree_8 clustermat cmdlog cnr cnre cnreg cnreg_p cnreg_sw cnsreg codebook collaps4 collapse colormult_nb colormult_nw compare compress conf confi confir confirm conren cons const constr constra constrai constrain constraint continue contract copy copyright copysource cor corc corr corr2data corr_anti corr_kmo corr_smc corre correl correla correlat correlate corrgram cou coun count cox cox_p cox_sw coxbase coxhaz coxvar cprplot cprplot_7 crc cret cretu cretur creturn cross cs cscript cscript_log csi ct ct_is ctset ctst_5 ctst_st cttost cumsp cumsp_7 cumul cusum cusum_7 cutil d|0 datasig datasign datasigna datasignat datasignatu datasignatur datasignature datetof db dbeta de dec deco decod decode deff des desc descr descri describ describe destring dfbeta dfgls dfuller di di_g dir dirstats dis discard disp disp_res disp_s displ displa display distinct do doe doed doedi doedit dotplot dotplot_7 dprobit drawnorm drop ds ds_util dstdize duplicates durbina dwstat dydx e|0 ed edi edit egen eivreg emdef en enc enco encod encode eq erase ereg ereg_lf ereg_p ereg_sw ereghet ereghet_glf ereghet_glf_sh ereghet_gp ereghet_ilf ereghet_ilf_sh ereghet_ip eret eretu eretur ereturn err erro error esize est est_cfexist est_cfname est_clickable est_expand est_hold est_table est_unhold est_unholdok estat estat_default estat_summ estat_vce_only esti estimates etodow etof etomdy ex exi exit expand expandcl fac fact facto factor factor_estat factor_p factor_pca_rotated factor_rotate factormat fcast fcast_compute fcast_graph fdades fdadesc fdadescr fdadescri fdadescrib fdadescribe fdasav fdasave fdause fh_st file open file read file close file filefilter fillin find_hlp_file findfile findit findit_7 fit fl fli flis flist for5_0 forest forestplot form forma format fpredict frac_154 frac_adj frac_chk frac_cox frac_ddp frac_dis frac_dv frac_in frac_mun frac_pp frac_pq frac_pv frac_wgt frac_xo fracgen fracplot fracplot_7 fracpoly fracpred fron_ex fron_hn fron_p fron_tn fron_tn2 frontier ftodate ftoe ftomdy ftowdate funnel funnelplot g|0 gamhet_glf gamhet_gp gamhet_ilf gamhet_ip gamma gamma_d2 gamma_p gamma_sw gammahet gdi_hexagon gdi_spokes ge gen gene gener genera generat generate genrank genstd genvmean gettoken gl gladder gladder_7 glim_l01 glim_l02 glim_l03 glim_l04 glim_l05 glim_l06 glim_l07 glim_l08 glim_l09 glim_l10 glim_l11 glim_l12 glim_lf glim_mu glim_nw1 glim_nw2 glim_nw3 glim_p glim_v1 glim_v2 glim_v3 glim_v4 glim_v5 glim_v6 glim_v7 glm glm_6 glm_p glm_sw glmpred glo glob globa global glogit glogit_8 glogit_p gmeans gnbre_lf gnbreg gnbreg_5 gnbreg_p gomp_lf gompe_sw gomper_p gompertz gompertzhet gomphet_glf gomphet_glf_sh gomphet_gp gomphet_ilf gomphet_ilf_sh gomphet_ip gphdot gphpen gphprint gprefs gprobi_p gprobit gprobit_8 gr gr7 gr_copy gr_current gr_db gr_describe gr_dir gr_draw gr_draw_replay gr_drop gr_edit gr_editviewopts gr_example gr_example2 gr_export gr_print gr_qscheme gr_query gr_read gr_rename gr_replay gr_save gr_set gr_setscheme gr_table gr_undo gr_use graph graph7 grebar greigen greigen_7 greigen_8 grmeanby grmeanby_7 gs_fileinfo gs_filetype gs_graphinfo gs_stat gsort gwood h|0 hadimvo hareg hausman haver he heck_d2 heckma_p heckman heckp_lf heckpr_p heckprob hel help hereg hetpr_lf hetpr_p hetprob hettest hexdump hilite hist hist_7 histogram hlogit hlu hmeans hotel hotelling hprobit hreg hsearch icd9 icd9_ff icd9p iis impute imtest inbase include inf infi infil infile infix inp inpu input ins insheet insp inspe inspec inspect integ inten intreg intreg_7 intreg_p intrg2_ll intrg_ll intrg_ll2 ipolate iqreg ir irf irf_create irfm iri is_svy is_svysum isid istdize ivprob_1_lf ivprob_lf ivprobit ivprobit_p ivreg ivreg_footnote ivtob_1_lf ivtob_lf ivtobit ivtobit_p jackknife jacknife jknife jknife_6 jknife_8 jkstat joinby kalarma1 kap kap_3 kapmeier kappa kapwgt kdensity kdensity_7 keep ksm ksmirnov ktau kwallis l|0 la lab labbe labbeplot labe label labelbook ladder levels levelsof leverage lfit lfit_p li lincom line linktest lis list lloghet_glf lloghet_glf_sh lloghet_gp lloghet_ilf lloghet_ilf_sh lloghet_ip llogi_sw llogis_p llogist llogistic llogistichet lnorm_lf lnorm_sw lnorma_p lnormal lnormalhet lnormhet_glf lnormhet_glf_sh lnormhet_gp lnormhet_ilf lnormhet_ilf_sh lnormhet_ip lnskew0 loadingplot loc loca local log logi logis_lf logistic logistic_p logit logit_estat logit_p loglogs logrank loneway lookfor lookup lowess lowess_7 lpredict lrecomp lroc lroc_7 lrtest ls lsens lsens_7 lsens_x lstat ltable ltable_7 ltriang lv lvr2plot lvr2plot_7 m|0 ma mac macr macro makecns man manova manova_estat manova_p manovatest mantel mark markin markout marksample mat mat_capp mat_order mat_put_rr mat_rapp mata mata_clear mata_describe mata_drop mata_matdescribe mata_matsave mata_matuse mata_memory mata_mlib mata_mosave mata_rename mata_which matalabel matcproc matlist matname matr matri matrix matrix_input__dlg matstrik mcc mcci md0_ md1_ md1debug_ md2_ md2debug_ mds mds_estat mds_p mdsconfig mdslong mdsmat mdsshepard mdytoe mdytof me_derd mean means median memory memsize menl meqparse mer merg merge meta mfp mfx mhelp mhodds minbound mixed_ll mixed_ll_reparm mkassert mkdir mkmat mkspline ml ml_5 ml_adjs ml_bhhhs ml_c_d ml_check ml_clear ml_cnt ml_debug ml_defd ml_e0 ml_e0_bfgs ml_e0_cycle ml_e0_dfp ml_e0i ml_e1 ml_e1_bfgs ml_e1_bhhh ml_e1_cycle ml_e1_dfp ml_e2 ml_e2_cycle ml_ebfg0 ml_ebfr0 ml_ebfr1 ml_ebh0q ml_ebhh0 ml_ebhr0 ml_ebr0i ml_ecr0i ml_edfp0 ml_edfr0 ml_edfr1 ml_edr0i ml_eds ml_eer0i ml_egr0i ml_elf ml_elf_bfgs ml_elf_bhhh ml_elf_cycle ml_elf_dfp ml_elfi ml_elfs ml_enr0i ml_enrr0 ml_erdu0 ml_erdu0_bfgs ml_erdu0_bhhh ml_erdu0_bhhhq ml_erdu0_cycle ml_erdu0_dfp ml_erdu0_nrbfgs ml_exde ml_footnote ml_geqnr ml_grad0 ml_graph ml_hbhhh ml_hd0 ml_hold ml_init ml_inv ml_log ml_max ml_mlout ml_mlout_8 ml_model ml_nb0 ml_opt ml_p ml_plot ml_query ml_rdgrd ml_repor ml_s_e ml_score ml_searc ml_technique ml_unhold mleval mlf_ mlmatbysum mlmatsum mlog mlogi mlogit mlogit_footnote mlogit_p mlopts mlsum mlvecsum mnl0_ mor more mov move mprobit mprobit_lf mprobit_p mrdu0_ mrdu1_ mvdecode mvencode mvreg mvreg_estat n|0 nbreg nbreg_al nbreg_lf nbreg_p nbreg_sw nestreg net newey newey_7 newey_p news nl nl_7 nl_9 nl_9_p nl_p nl_p_7 nlcom nlcom_p nlexp2 nlexp2_7 nlexp2a nlexp2a_7 nlexp3 nlexp3_7 nlgom3 nlgom3_7 nlgom4 nlgom4_7 nlinit nllog3 nllog3_7 nllog4 nllog4_7 nlog_rd nlogit nlogit_p nlogitgen nlogittree nlpred no nobreak noi nois noisi noisil noisily note notes notes_dlg nptrend numlabel numlist odbc old_ver olo olog ologi ologi_sw ologit ologit_p ologitp on one onew onewa oneway op_colnm op_comp op_diff op_inv op_str opr opro oprob oprob_sw oprobi oprobi_p oprobit oprobitp opts_exclusive order orthog orthpoly ou out outf outfi outfil outfile outs outsh outshe outshee outsheet ovtest pac pac_7 palette parse parse_dissim pause pca pca_8 pca_display pca_estat pca_p pca_rotate pcamat pchart pchart_7 pchi pchi_7 pcorr pctile pentium pergram pergram_7 permute permute_8 personal peto_st pkcollapse pkcross pkequiv pkexamine pkexamine_7 pkshape pksumm pksumm_7 pl plo plot plugin pnorm pnorm_7 poisgof poiss_lf poiss_sw poisso_p poisson poisson_estat post postclose postfile postutil pperron pr prais prais_e prais_e2 prais_p predict predictnl preserve print pro prob probi probit probit_estat probit_p proc_time procoverlay procrustes procrustes_estat procrustes_p profiler prog progr progra program prop proportion prtest prtesti pwcorr pwd q\\s qby qbys qchi qchi_7 qladder qladder_7 qnorm qnorm_7 qqplot qqplot_7 qreg qreg_c qreg_p qreg_sw qu quadchk quantile quantile_7 que quer query range ranksum ratio rchart rchart_7 rcof recast reclink recode reg reg3 reg3_p regdw regr regre regre_p2 regres regres_p regress regress_estat regriv_p remap ren rena renam rename renpfix repeat replace report reshape restore ret retu retur return rm rmdir robvar roccomp roccomp_7 roccomp_8 rocf_lf rocfit rocfit_8 rocgold rocplot rocplot_7 roctab roctab_7 rolling rologit rologit_p rot rota rotat rotate rotatemat rreg rreg_p ru run runtest rvfplot rvfplot_7 rvpplot rvpplot_7 sa safesum sample sampsi sav save savedresults saveold sc sca scal scala scalar scatter scm_mine sco scob_lf scob_p scobi_sw scobit scor score scoreplot scoreplot_help scree screeplot screeplot_help sdtest sdtesti se search separate seperate serrbar serrbar_7 serset set set_defaults sfrancia sh she shel shell shewhart shewhart_7 signestimationsample signrank signtest simul simul_7 simulate simulate_8 sktest sleep slogit slogit_d2 slogit_p smooth snapspan so sor sort spearman spikeplot spikeplot_7 spikeplt spline_x split sqreg sqreg_p sret sretu sretur sreturn ssc st st_ct st_hc st_hcd st_hcd_sh st_is st_issys st_note st_promo st_set st_show st_smpl st_subid stack statsby statsby_8 stbase stci stci_7 stcox stcox_estat stcox_fr stcox_fr_ll stcox_p stcox_sw stcoxkm stcoxkm_7 stcstat stcurv stcurve stcurve_7 stdes stem stepwise stereg stfill stgen stir stjoin stmc stmh stphplot stphplot_7 stphtest stphtest_7 stptime strate strate_7 streg streg_sw streset sts sts_7 stset stsplit stsum sttocc sttoct stvary stweib su suest suest_8 sum summ summa summar summari summariz summarize sunflower sureg survcurv survsum svar svar_p svmat svy svy_disp svy_dreg svy_est svy_est_7 svy_estat svy_get svy_gnbreg_p svy_head svy_header svy_heckman_p svy_heckprob_p svy_intreg_p svy_ivreg_p svy_logistic_p svy_logit_p svy_mlogit_p svy_nbreg_p svy_ologit_p svy_oprobit_p svy_poisson_p svy_probit_p svy_regress_p svy_sub svy_sub_7 svy_x svy_x_7 svy_x_p svydes svydes_8 svygen svygnbreg svyheckman svyheckprob svyintreg svyintreg_7 svyintrg svyivreg svylc svylog_p svylogit svymarkout svymarkout_8 svymean svymlog svymlogit svynbreg svyolog svyologit svyoprob svyoprobit svyopts svypois svypois_7 svypoisson svyprobit svyprobt svyprop svyprop_7 svyratio svyreg svyreg_p svyregress svyset svyset_7 svyset_8 svytab svytab_7 svytest svytotal sw sw_8 swcnreg swcox swereg swilk swlogis swlogit swologit swoprbt swpois swprobit swqreg swtobit swweib symmetry symmi symplot symplot_7 syntax sysdescribe sysdir sysuse szroeter ta tab tab1 tab2 tab_or tabd tabdi tabdis tabdisp tabi table tabodds tabodds_7 tabstat tabu tabul tabula tabulat tabulate te tempfile tempname tempvar tes test testnl testparm teststd tetrachoric time_it timer tis tob tobi tobit tobit_p tobit_sw token tokeni tokeniz tokenize tostring total translate translator transmap treat_ll treatr_p treatreg trim trimfill trnb_cons trnb_mean trpoiss_d2 trunc_ll truncr_p truncreg tsappend tset tsfill tsline tsline_ex tsreport tsrevar tsrline tsset tssmooth tsunab ttest ttesti tut_chk tut_wait tutorial tw tware_st two twoway twoway__fpfit_serset twoway__function_gen twoway__histogram_gen twoway__ipoint_serset twoway__ipoints_serset twoway__kdensity_gen twoway__lfit_serset twoway__normgen_gen twoway__pci_serset twoway__qfit_serset twoway__scatteri_serset twoway__sunflower_gen twoway_ksm_serset ty typ type typeof u|0 unab unabbrev unabcmd update us use uselabel var var_mkcompanion var_p varbasic varfcast vargranger varirf varirf_add varirf_cgraph varirf_create varirf_ctable varirf_describe varirf_dir varirf_drop varirf_erase varirf_graph varirf_ograph varirf_rename varirf_set varirf_table varlist varlmar varnorm varsoc varstable varstable_w varstable_w2 varwle vce vec vec_fevd vec_mkphi vec_p vec_p_w vecirf_create veclmar veclmar_w vecnorm vecnorm_w vecrank vecstable verinst vers versi versio version view viewsource vif vwls wdatetof webdescribe webseek webuse weib1_lf weib2_lf weib_lf weib_lf0 weibhet_glf weibhet_glf_sh weibhet_glfa weibhet_glfa_sh weibhet_gp weibhet_ilf weibhet_ilf_sh weibhet_ilfa weibhet_ilfa_sh weibhet_ip weibu_sw weibul_p weibull weibull_c weibull_s weibullhet wh whelp whi which whil while wilc_st wilcoxon win wind windo window winexec wntestb wntestb_7 wntestq xchart xchart_7 xcorr xcorr_7 xi xi_6 xmlsav xmlsave xmluse xpose xsh xshe xshel xshell xt_iis xt_tis xtab_p xtabond xtbin_p xtclog xtcloglog xtcloglog_8 xtcloglog_d2 xtcloglog_pa_p xtcloglog_re_p xtcnt_p xtcorr xtdata xtdes xtfront_p xtfrontier xtgee xtgee_elink xtgee_estat xtgee_makeivar xtgee_p xtgee_plink xtgls xtgls_p xthaus xthausman xtht_p xthtaylor xtile xtint_p xtintreg xtintreg_8 xtintreg_d2 xtintreg_p xtivp_1 xtivp_2 xtivreg xtline xtline_ex xtlogit xtlogit_8 xtlogit_d2 xtlogit_fe_p xtlogit_pa_p xtlogit_re_p xtmixed xtmixed_estat xtmixed_p xtnb_fe xtnb_lf xtnbreg xtnbreg_pa_p xtnbreg_refe_p xtpcse xtpcse_p xtpois xtpoisson xtpoisson_d2 xtpoisson_pa_p xtpoisson_refe_p xtpred xtprobit xtprobit_8 xtprobit_d2 xtprobit_re_p xtps_fe xtps_lf xtps_ren xtps_ren_8 xtrar_p xtrc xtrc_p xtrchh xtrefe_p xtreg xtreg_be xtreg_fe xtreg_ml xtreg_pa_p xtreg_re xtregar xtrere_p xtset xtsf_ll xtsf_llti xtsum xttab xttest0 xttobit xttobit_8 xttobit_p xttrans yx yxview__barlike_draw yxview_area_draw yxview_bar_draw yxview_dot_draw yxview_dropline_draw yxview_function_draw yxview_iarrow_draw yxview_ilabels_draw yxview_normal_draw yxview_pcarrow_draw yxview_pcbarrow_draw yxview_pccapsym_draw yxview_pcscatter_draw yxview_pcspike_draw yxview_rarea_draw yxview_rbar_draw yxview_rbarm_draw yxview_rcap_draw yxview_rcapsym_draw yxview_rconnected_draw yxview_rline_draw yxview_rscatter_draw yxview_rspike_draw yxview_spike_draw yxview_sunflower_draw zap_s zinb zinb_llf zinb_plf zip zip_llf zip_p zip_plf zt_ct_5 zt_hc_5 zt_hcd_5 zt_is_5 zt_iss_5 zt_sho_5 zt_smp_5 ztbase_5 ztcox_5 ztdes_5 ztereg_5 ztfill_5 ztgen_5 ztir_5 ztjoin_5 ztnb ztnb_p ztp ztp_p zts_5 ztset_5 ztspli_5 ztsum_5 zttoct_5 ztvary_5 ztweib_5',
    -    contains: [
    -      {
    -        className: 'symbol',
    -        begin: /`[a-zA-Z0-9_]+'/
    -      },
    -      {
    -        className: 'variable',
    -        begin: /\$\{?[a-zA-Z0-9_]+\}?/
    -      },
    -      {
    -        className: 'string',
    -        variants: [
    -          {
    -            begin: '`"[^\r\n]*?"\''
    -          },
    -          {
    -            begin: '"[^\r\n"]*"'
    -          }
    -        ]
    -      },
    -
    -      {
    -        className: 'built_in',
    -        variants: [
    -          {
    -            begin: '\\b(abs|acos|asin|atan|atan2|atanh|ceil|cloglog|comb|cos|digamma|exp|floor|invcloglog|invlogit|ln|lnfact|lnfactorial|lngamma|log|log10|max|min|mod|reldif|round|sign|sin|sqrt|sum|tan|tanh|trigamma|trunc|betaden|Binomial|binorm|binormal|chi2|chi2tail|dgammapda|dgammapdada|dgammapdadx|dgammapdx|dgammapdxdx|F|Fden|Ftail|gammaden|gammap|ibeta|invbinomial|invchi2|invchi2tail|invF|invFtail|invgammap|invibeta|invnchi2|invnFtail|invnibeta|invnorm|invnormal|invttail|nbetaden|nchi2|nFden|nFtail|nibeta|norm|normal|normalden|normd|npnchi2|tden|ttail|uniform|abbrev|char|index|indexnot|length|lower|ltrim|match|plural|proper|real|regexm|regexr|regexs|reverse|rtrim|string|strlen|strlower|strltrim|strmatch|strofreal|strpos|strproper|strreverse|strrtrim|strtrim|strupper|subinstr|subinword|substr|trim|upper|word|wordcount|_caller|autocode|byteorder|chop|clip|cond|e|epsdouble|epsfloat|group|inlist|inrange|irecode|matrix|maxbyte|maxdouble|maxfloat|maxint|maxlong|mi|minbyte|mindouble|minfloat|minint|minlong|missing|r|recode|replay|return|s|scalar|d|date|day|dow|doy|halfyear|mdy|month|quarter|week|year|d|daily|dofd|dofh|dofm|dofq|dofw|dofy|h|halfyearly|hofd|m|mofd|monthly|q|qofd|quarterly|tin|twithin|w|weekly|wofd|y|yearly|yh|ym|yofd|yq|yw|cholesky|colnumb|colsof|corr|det|diag|diag0cnt|el|get|hadamard|I|inv|invsym|issym|issymmetric|J|matmissing|matuniform|mreldif|nullmat|rownumb|rowsof|sweep|syminv|trace|vec|vecdiag)(?=\\()'
    -          }
    -        ]
    -      },
    -
    -      hljs.COMMENT('^[ \t]*\\*.*$', false),
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = stata;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/step21.js b/claude-code-source/node_modules/highlight.js/lib/languages/step21.js
    deleted file mode 100644
    index 09fc2ba1..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/step21.js
    +++ /dev/null
    @@ -1,66 +0,0 @@
    -/*
    -Language: STEP Part 21
    -Contributors: Adam Joseph Cook 
    -Description: Syntax highlighter for STEP Part 21 files (ISO 10303-21).
    -Website: https://en.wikipedia.org/wiki/ISO_10303-21
    -*/
    -
    -function step21(hljs) {
    -  const STEP21_IDENT_RE = '[A-Z_][A-Z0-9_.]*';
    -  const STEP21_KEYWORDS = {
    -    $pattern: STEP21_IDENT_RE,
    -    keyword: 'HEADER ENDSEC DATA'
    -  };
    -  const STEP21_START = {
    -    className: 'meta',
    -    begin: 'ISO-10303-21;',
    -    relevance: 10
    -  };
    -  const STEP21_CLOSE = {
    -    className: 'meta',
    -    begin: 'END-ISO-10303-21;',
    -    relevance: 10
    -  };
    -
    -  return {
    -    name: 'STEP Part 21',
    -    aliases: [
    -      'p21',
    -      'step',
    -      'stp'
    -    ],
    -    case_insensitive: true, // STEP 21 is case insensitive in theory, in practice all non-comments are capitalized.
    -    keywords: STEP21_KEYWORDS,
    -    contains: [
    -      STEP21_START,
    -      STEP21_CLOSE,
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.COMMENT('/\\*\\*!', '\\*/'),
    -      hljs.C_NUMBER_MODE,
    -      hljs.inherit(hljs.APOS_STRING_MODE, {
    -        illegal: null
    -      }),
    -      hljs.inherit(hljs.QUOTE_STRING_MODE, {
    -        illegal: null
    -      }),
    -      {
    -        className: 'string',
    -        begin: "'",
    -        end: "'"
    -      },
    -      {
    -        className: 'symbol',
    -        variants: [
    -          {
    -            begin: '#',
    -            end: '\\d+',
    -            illegal: '\\W'
    -          }
    -        ]
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = step21;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/stylus.js b/claude-code-source/node_modules/highlight.js/lib/languages/stylus.js
    deleted file mode 100644
    index 78448fc7..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/stylus.js
    +++ /dev/null
    @@ -1,609 +0,0 @@
    -const MODES = (hljs) => {
    -  return {
    -    IMPORTANT: {
    -      className: 'meta',
    -      begin: '!important'
    -    },
    -    HEXCOLOR: {
    -      className: 'number',
    -      begin: '#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})'
    -    },
    -    ATTRIBUTE_SELECTOR_MODE: {
    -      className: 'selector-attr',
    -      begin: /\[/,
    -      end: /\]/,
    -      illegal: '$',
    -      contains: [
    -        hljs.APOS_STRING_MODE,
    -        hljs.QUOTE_STRING_MODE
    -      ]
    -    }
    -  };
    -};
    -
    -const TAGS = [
    -  'a',
    -  'abbr',
    -  'address',
    -  'article',
    -  'aside',
    -  'audio',
    -  'b',
    -  'blockquote',
    -  'body',
    -  'button',
    -  'canvas',
    -  'caption',
    -  'cite',
    -  'code',
    -  'dd',
    -  'del',
    -  'details',
    -  'dfn',
    -  'div',
    -  'dl',
    -  'dt',
    -  'em',
    -  'fieldset',
    -  'figcaption',
    -  'figure',
    -  'footer',
    -  'form',
    -  'h1',
    -  'h2',
    -  'h3',
    -  'h4',
    -  'h5',
    -  'h6',
    -  'header',
    -  'hgroup',
    -  'html',
    -  'i',
    -  'iframe',
    -  'img',
    -  'input',
    -  'ins',
    -  'kbd',
    -  'label',
    -  'legend',
    -  'li',
    -  'main',
    -  'mark',
    -  'menu',
    -  'nav',
    -  'object',
    -  'ol',
    -  'p',
    -  'q',
    -  'quote',
    -  'samp',
    -  'section',
    -  'span',
    -  'strong',
    -  'summary',
    -  'sup',
    -  'table',
    -  'tbody',
    -  'td',
    -  'textarea',
    -  'tfoot',
    -  'th',
    -  'thead',
    -  'time',
    -  'tr',
    -  'ul',
    -  'var',
    -  'video'
    -];
    -
    -const MEDIA_FEATURES = [
    -  'any-hover',
    -  'any-pointer',
    -  'aspect-ratio',
    -  'color',
    -  'color-gamut',
    -  'color-index',
    -  'device-aspect-ratio',
    -  'device-height',
    -  'device-width',
    -  'display-mode',
    -  'forced-colors',
    -  'grid',
    -  'height',
    -  'hover',
    -  'inverted-colors',
    -  'monochrome',
    -  'orientation',
    -  'overflow-block',
    -  'overflow-inline',
    -  'pointer',
    -  'prefers-color-scheme',
    -  'prefers-contrast',
    -  'prefers-reduced-motion',
    -  'prefers-reduced-transparency',
    -  'resolution',
    -  'scan',
    -  'scripting',
    -  'update',
    -  'width',
    -  // TODO: find a better solution?
    -  'min-width',
    -  'max-width',
    -  'min-height',
    -  'max-height'
    -];
    -
    -// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-classes
    -const PSEUDO_CLASSES = [
    -  'active',
    -  'any-link',
    -  'blank',
    -  'checked',
    -  'current',
    -  'default',
    -  'defined',
    -  'dir', // dir()
    -  'disabled',
    -  'drop',
    -  'empty',
    -  'enabled',
    -  'first',
    -  'first-child',
    -  'first-of-type',
    -  'fullscreen',
    -  'future',
    -  'focus',
    -  'focus-visible',
    -  'focus-within',
    -  'has', // has()
    -  'host', // host or host()
    -  'host-context', // host-context()
    -  'hover',
    -  'indeterminate',
    -  'in-range',
    -  'invalid',
    -  'is', // is()
    -  'lang', // lang()
    -  'last-child',
    -  'last-of-type',
    -  'left',
    -  'link',
    -  'local-link',
    -  'not', // not()
    -  'nth-child', // nth-child()
    -  'nth-col', // nth-col()
    -  'nth-last-child', // nth-last-child()
    -  'nth-last-col', // nth-last-col()
    -  'nth-last-of-type', //nth-last-of-type()
    -  'nth-of-type', //nth-of-type()
    -  'only-child',
    -  'only-of-type',
    -  'optional',
    -  'out-of-range',
    -  'past',
    -  'placeholder-shown',
    -  'read-only',
    -  'read-write',
    -  'required',
    -  'right',
    -  'root',
    -  'scope',
    -  'target',
    -  'target-within',
    -  'user-invalid',
    -  'valid',
    -  'visited',
    -  'where' // where()
    -];
    -
    -// https://developer.mozilla.org/en-US/docs/Web/CSS/Pseudo-elements
    -const PSEUDO_ELEMENTS = [
    -  'after',
    -  'backdrop',
    -  'before',
    -  'cue',
    -  'cue-region',
    -  'first-letter',
    -  'first-line',
    -  'grammar-error',
    -  'marker',
    -  'part',
    -  'placeholder',
    -  'selection',
    -  'slotted',
    -  'spelling-error'
    -];
    -
    -const ATTRIBUTES = [
    -  'align-content',
    -  'align-items',
    -  'align-self',
    -  'animation',
    -  'animation-delay',
    -  'animation-direction',
    -  'animation-duration',
    -  'animation-fill-mode',
    -  'animation-iteration-count',
    -  'animation-name',
    -  'animation-play-state',
    -  'animation-timing-function',
    -  'auto',
    -  'backface-visibility',
    -  'background',
    -  'background-attachment',
    -  'background-clip',
    -  'background-color',
    -  'background-image',
    -  'background-origin',
    -  'background-position',
    -  'background-repeat',
    -  'background-size',
    -  'border',
    -  'border-bottom',
    -  'border-bottom-color',
    -  'border-bottom-left-radius',
    -  'border-bottom-right-radius',
    -  'border-bottom-style',
    -  'border-bottom-width',
    -  'border-collapse',
    -  'border-color',
    -  'border-image',
    -  'border-image-outset',
    -  'border-image-repeat',
    -  'border-image-slice',
    -  'border-image-source',
    -  'border-image-width',
    -  'border-left',
    -  'border-left-color',
    -  'border-left-style',
    -  'border-left-width',
    -  'border-radius',
    -  'border-right',
    -  'border-right-color',
    -  'border-right-style',
    -  'border-right-width',
    -  'border-spacing',
    -  'border-style',
    -  'border-top',
    -  'border-top-color',
    -  'border-top-left-radius',
    -  'border-top-right-radius',
    -  'border-top-style',
    -  'border-top-width',
    -  'border-width',
    -  'bottom',
    -  'box-decoration-break',
    -  'box-shadow',
    -  'box-sizing',
    -  'break-after',
    -  'break-before',
    -  'break-inside',
    -  'caption-side',
    -  'clear',
    -  'clip',
    -  'clip-path',
    -  'color',
    -  'column-count',
    -  'column-fill',
    -  'column-gap',
    -  'column-rule',
    -  'column-rule-color',
    -  'column-rule-style',
    -  'column-rule-width',
    -  'column-span',
    -  'column-width',
    -  'columns',
    -  'content',
    -  'counter-increment',
    -  'counter-reset',
    -  'cursor',
    -  'direction',
    -  'display',
    -  'empty-cells',
    -  'filter',
    -  'flex',
    -  'flex-basis',
    -  'flex-direction',
    -  'flex-flow',
    -  'flex-grow',
    -  'flex-shrink',
    -  'flex-wrap',
    -  'float',
    -  'font',
    -  'font-display',
    -  'font-family',
    -  'font-feature-settings',
    -  'font-kerning',
    -  'font-language-override',
    -  'font-size',
    -  'font-size-adjust',
    -  'font-smoothing',
    -  'font-stretch',
    -  'font-style',
    -  'font-variant',
    -  'font-variant-ligatures',
    -  'font-variation-settings',
    -  'font-weight',
    -  'height',
    -  'hyphens',
    -  'icon',
    -  'image-orientation',
    -  'image-rendering',
    -  'image-resolution',
    -  'ime-mode',
    -  'inherit',
    -  'initial',
    -  'justify-content',
    -  'left',
    -  'letter-spacing',
    -  'line-height',
    -  'list-style',
    -  'list-style-image',
    -  'list-style-position',
    -  'list-style-type',
    -  'margin',
    -  'margin-bottom',
    -  'margin-left',
    -  'margin-right',
    -  'margin-top',
    -  'marks',
    -  'mask',
    -  'max-height',
    -  'max-width',
    -  'min-height',
    -  'min-width',
    -  'nav-down',
    -  'nav-index',
    -  'nav-left',
    -  'nav-right',
    -  'nav-up',
    -  'none',
    -  'normal',
    -  'object-fit',
    -  'object-position',
    -  'opacity',
    -  'order',
    -  'orphans',
    -  'outline',
    -  'outline-color',
    -  'outline-offset',
    -  'outline-style',
    -  'outline-width',
    -  'overflow',
    -  'overflow-wrap',
    -  'overflow-x',
    -  'overflow-y',
    -  'padding',
    -  'padding-bottom',
    -  'padding-left',
    -  'padding-right',
    -  'padding-top',
    -  'page-break-after',
    -  'page-break-before',
    -  'page-break-inside',
    -  'perspective',
    -  'perspective-origin',
    -  'pointer-events',
    -  'position',
    -  'quotes',
    -  'resize',
    -  'right',
    -  'src', // @font-face
    -  'tab-size',
    -  'table-layout',
    -  'text-align',
    -  'text-align-last',
    -  'text-decoration',
    -  'text-decoration-color',
    -  'text-decoration-line',
    -  'text-decoration-style',
    -  'text-indent',
    -  'text-overflow',
    -  'text-rendering',
    -  'text-shadow',
    -  'text-transform',
    -  'text-underline-position',
    -  'top',
    -  'transform',
    -  'transform-origin',
    -  'transform-style',
    -  'transition',
    -  'transition-delay',
    -  'transition-duration',
    -  'transition-property',
    -  'transition-timing-function',
    -  'unicode-bidi',
    -  'vertical-align',
    -  'visibility',
    -  'white-space',
    -  'widows',
    -  'width',
    -  'word-break',
    -  'word-spacing',
    -  'word-wrap',
    -  'z-index'
    -  // reverse makes sure longer attributes `font-weight` are matched fully
    -  // instead of getting false positives on say `font`
    -].reverse();
    -
    -/*
    -Language: Stylus
    -Author: Bryant Williams 
    -Description: Stylus is an expressive, robust, feature-rich CSS language built for nodejs.
    -Website: https://github.com/stylus/stylus
    -Category: css
    -*/
    -
    -/** @type LanguageFn */
    -function stylus(hljs) {
    -  const modes = MODES(hljs);
    -
    -  const AT_MODIFIERS = "and or not only";
    -  const VARIABLE = {
    -    className: 'variable',
    -    begin: '\\$' + hljs.IDENT_RE
    -  };
    -
    -  const AT_KEYWORDS = [
    -    'charset',
    -    'css',
    -    'debug',
    -    'extend',
    -    'font-face',
    -    'for',
    -    'import',
    -    'include',
    -    'keyframes',
    -    'media',
    -    'mixin',
    -    'page',
    -    'warn',
    -    'while'
    -  ];
    -
    -  const LOOKAHEAD_TAG_END = '(?=[.\\s\\n[:,(])';
    -
    -  // illegals
    -  const ILLEGAL = [
    -    '\\?',
    -    '(\\bReturn\\b)', // monkey
    -    '(\\bEnd\\b)', // monkey
    -    '(\\bend\\b)', // vbscript
    -    '(\\bdef\\b)', // gradle
    -    ';', // a whole lot of languages
    -    '#\\s', // markdown
    -    '\\*\\s', // markdown
    -    '===\\s', // markdown
    -    '\\|',
    -    '%' // prolog
    -  ];
    -
    -  return {
    -    name: 'Stylus',
    -    aliases: [ 'styl' ],
    -    case_insensitive: false,
    -    keywords: 'if else for in',
    -    illegal: '(' + ILLEGAL.join('|') + ')',
    -    contains: [
    -
    -      // strings
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.APOS_STRING_MODE,
    -
    -      // comments
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -
    -      // hex colors
    -      modes.HEXCOLOR,
    -
    -      // class tag
    -      {
    -        begin: '\\.[a-zA-Z][a-zA-Z0-9_-]*' + LOOKAHEAD_TAG_END,
    -        className: 'selector-class'
    -      },
    -
    -      // id tag
    -      {
    -        begin: '#[a-zA-Z][a-zA-Z0-9_-]*' + LOOKAHEAD_TAG_END,
    -        className: 'selector-id'
    -      },
    -
    -      // tags
    -      {
    -        begin: '\\b(' + TAGS.join('|') + ')' + LOOKAHEAD_TAG_END,
    -        className: 'selector-tag'
    -      },
    -
    -      // psuedo selectors
    -      {
    -        className: 'selector-pseudo',
    -        begin: '&?:(' + PSEUDO_CLASSES.join('|') + ')' + LOOKAHEAD_TAG_END
    -      },
    -      {
    -        className: 'selector-pseudo',
    -        begin: '&?::(' + PSEUDO_ELEMENTS.join('|') + ')' + LOOKAHEAD_TAG_END
    -      },
    -
    -      modes.ATTRIBUTE_SELECTOR_MODE,
    -
    -      {
    -        className: "keyword",
    -        begin: /@media/,
    -        starts: {
    -          end: /[{;}]/,
    -          keywords: {
    -            $pattern: /[a-z-]+/,
    -            keyword: AT_MODIFIERS,
    -            attribute: MEDIA_FEATURES.join(" ")
    -          },
    -          contains: [ hljs.CSS_NUMBER_MODE ]
    -        }
    -      },
    -
    -      // @ keywords
    -      {
    -        className: 'keyword',
    -        begin: '\@((-(o|moz|ms|webkit)-)?(' + AT_KEYWORDS.join('|') + '))\\b'
    -      },
    -
    -      // variables
    -      VARIABLE,
    -
    -      // dimension
    -      hljs.CSS_NUMBER_MODE,
    -
    -      // functions
    -      //  - only from beginning of line + whitespace
    -      {
    -        className: 'function',
    -        begin: '^[a-zA-Z][a-zA-Z0-9_\-]*\\(.*\\)',
    -        illegal: '[\\n]',
    -        returnBegin: true,
    -        contains: [
    -          {
    -            className: 'title',
    -            begin: '\\b[a-zA-Z][a-zA-Z0-9_\-]*'
    -          },
    -          {
    -            className: 'params',
    -            begin: /\(/,
    -            end: /\)/,
    -            contains: [
    -              modes.HEXCOLOR,
    -              VARIABLE,
    -              hljs.APOS_STRING_MODE,
    -              hljs.CSS_NUMBER_MODE,
    -              hljs.QUOTE_STRING_MODE
    -            ]
    -          }
    -        ]
    -      },
    -
    -      // attributes
    -      //  - only from beginning of line + whitespace
    -      //  - must have whitespace after it
    -      {
    -        className: 'attribute',
    -        begin: '\\b(' + ATTRIBUTES.join('|') + ')\\b',
    -        starts: {
    -          // value container
    -          end: /;|$/,
    -          contains: [
    -            modes.HEXCOLOR,
    -            VARIABLE,
    -            hljs.APOS_STRING_MODE,
    -            hljs.QUOTE_STRING_MODE,
    -            hljs.CSS_NUMBER_MODE,
    -            hljs.C_BLOCK_COMMENT_MODE,
    -            modes.IMPORTANT
    -          ],
    -          illegal: /\./,
    -          relevance: 0
    -        }
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = stylus;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/subunit.js b/claude-code-source/node_modules/highlight.js/lib/languages/subunit.js
    deleted file mode 100644
    index 00add37b..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/subunit.js
    +++ /dev/null
    @@ -1,51 +0,0 @@
    -/*
    -Language: SubUnit
    -Author: Sergey Bronnikov 
    -Website: https://pypi.org/project/python-subunit/
    -*/
    -
    -function subunit(hljs) {
    -  const DETAILS = {
    -    className: 'string',
    -    begin: '\\[\n(multipart)?',
    -    end: '\\]\n'
    -  };
    -  const TIME = {
    -    className: 'string',
    -    begin: '\\d{4}-\\d{2}-\\d{2}(\\s+)\\d{2}:\\d{2}:\\d{2}\.\\d+Z'
    -  };
    -  const PROGRESSVALUE = {
    -    className: 'string',
    -    begin: '(\\+|-)\\d+'
    -  };
    -  const KEYWORDS = {
    -    className: 'keyword',
    -    relevance: 10,
    -    variants: [
    -      {
    -        begin: '^(test|testing|success|successful|failure|error|skip|xfail|uxsuccess)(:?)\\s+(test)?'
    -      },
    -      {
    -        begin: '^progress(:?)(\\s+)?(pop|push)?'
    -      },
    -      {
    -        begin: '^tags:'
    -      },
    -      {
    -        begin: '^time:'
    -      }
    -    ]
    -  };
    -  return {
    -    name: 'SubUnit',
    -    case_insensitive: true,
    -    contains: [
    -      DETAILS,
    -      TIME,
    -      PROGRESSVALUE,
    -      KEYWORDS
    -    ]
    -  };
    -}
    -
    -module.exports = subunit;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/swift.js b/claude-code-source/node_modules/highlight.js/lib/languages/swift.js
    deleted file mode 100644
    index 09a21989..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/swift.js
    +++ /dev/null
    @@ -1,873 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function lookahead(re) {
    -  return concat('(?=', re, ')');
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/**
    - * Any of the passed expresssions may match
    - *
    - * Creates a huge this | this | that | that match
    - * @param {(RegExp | string)[] } args
    - * @returns {string}
    - */
    -function either(...args) {
    -  const joined = '(' + args.map((x) => source(x)).join("|") + ")";
    -  return joined;
    -}
    -
    -const keywordWrapper = keyword => concat(
    -  /\b/,
    -  keyword,
    -  /\w$/.test(keyword) ? /\b/ : /\B/
    -);
    -
    -// Keywords that require a leading dot.
    -const dotKeywords = [
    -  'Protocol', // contextual
    -  'Type' // contextual
    -].map(keywordWrapper);
    -
    -// Keywords that may have a leading dot.
    -const optionalDotKeywords = [
    -  'init',
    -  'self'
    -].map(keywordWrapper);
    -
    -// should register as keyword, not type
    -const keywordTypes = [
    -  'Any',
    -  'Self'
    -];
    -
    -// Regular keywords and literals.
    -const keywords = [
    -  // strings below will be fed into the regular `keywords` engine while regex
    -  // will result in additional modes being created to scan for those keywords to
    -  // avoid conflicts with other rules
    -  'associatedtype',
    -  'async',
    -  'await',
    -  /as\?/, // operator
    -  /as!/, // operator
    -  'as', // operator
    -  'break',
    -  'case',
    -  'catch',
    -  'class',
    -  'continue',
    -  'convenience', // contextual
    -  'default',
    -  'defer',
    -  'deinit',
    -  'didSet', // contextual
    -  'do',
    -  'dynamic', // contextual
    -  'else',
    -  'enum',
    -  'extension',
    -  'fallthrough',
    -  /fileprivate\(set\)/,
    -  'fileprivate',
    -  'final', // contextual
    -  'for',
    -  'func',
    -  'get', // contextual
    -  'guard',
    -  'if',
    -  'import',
    -  'indirect', // contextual
    -  'infix', // contextual
    -  /init\?/,
    -  /init!/,
    -  'inout',
    -  /internal\(set\)/,
    -  'internal',
    -  'in',
    -  'is', // operator
    -  'lazy', // contextual
    -  'let',
    -  'mutating', // contextual
    -  'nonmutating', // contextual
    -  /open\(set\)/, // contextual
    -  'open', // contextual
    -  'operator',
    -  'optional', // contextual
    -  'override', // contextual
    -  'postfix', // contextual
    -  'precedencegroup',
    -  'prefix', // contextual
    -  /private\(set\)/,
    -  'private',
    -  'protocol',
    -  /public\(set\)/,
    -  'public',
    -  'repeat',
    -  'required', // contextual
    -  'rethrows',
    -  'return',
    -  'set', // contextual
    -  'some', // contextual
    -  'static',
    -  'struct',
    -  'subscript',
    -  'super',
    -  'switch',
    -  'throws',
    -  'throw',
    -  /try\?/, // operator
    -  /try!/, // operator
    -  'try', // operator
    -  'typealias',
    -  /unowned\(safe\)/, // contextual
    -  /unowned\(unsafe\)/, // contextual
    -  'unowned', // contextual
    -  'var',
    -  'weak', // contextual
    -  'where',
    -  'while',
    -  'willSet' // contextual
    -];
    -
    -// NOTE: Contextual keywords are reserved only in specific contexts.
    -// Ideally, these should be matched using modes to avoid false positives.
    -
    -// Literals.
    -const literals = [
    -  'false',
    -  'nil',
    -  'true'
    -];
    -
    -// Keywords used in precedence groups.
    -const precedencegroupKeywords = [
    -  'assignment',
    -  'associativity',
    -  'higherThan',
    -  'left',
    -  'lowerThan',
    -  'none',
    -  'right'
    -];
    -
    -// Keywords that start with a number sign (#).
    -// #available is handled separately.
    -const numberSignKeywords = [
    -  '#colorLiteral',
    -  '#column',
    -  '#dsohandle',
    -  '#else',
    -  '#elseif',
    -  '#endif',
    -  '#error',
    -  '#file',
    -  '#fileID',
    -  '#fileLiteral',
    -  '#filePath',
    -  '#function',
    -  '#if',
    -  '#imageLiteral',
    -  '#keyPath',
    -  '#line',
    -  '#selector',
    -  '#sourceLocation',
    -  '#warn_unqualified_access',
    -  '#warning'
    -];
    -
    -// Global functions in the Standard Library.
    -const builtIns = [
    -  'abs',
    -  'all',
    -  'any',
    -  'assert',
    -  'assertionFailure',
    -  'debugPrint',
    -  'dump',
    -  'fatalError',
    -  'getVaList',
    -  'isKnownUniquelyReferenced',
    -  'max',
    -  'min',
    -  'numericCast',
    -  'pointwiseMax',
    -  'pointwiseMin',
    -  'precondition',
    -  'preconditionFailure',
    -  'print',
    -  'readLine',
    -  'repeatElement',
    -  'sequence',
    -  'stride',
    -  'swap',
    -  'swift_unboxFromSwiftValueWithType',
    -  'transcode',
    -  'type',
    -  'unsafeBitCast',
    -  'unsafeDowncast',
    -  'withExtendedLifetime',
    -  'withUnsafeMutablePointer',
    -  'withUnsafePointer',
    -  'withVaList',
    -  'withoutActuallyEscaping',
    -  'zip'
    -];
    -
    -// Valid first characters for operators.
    -const operatorHead = either(
    -  /[/=\-+!*%<>&|^~?]/,
    -  /[\u00A1-\u00A7]/,
    -  /[\u00A9\u00AB]/,
    -  /[\u00AC\u00AE]/,
    -  /[\u00B0\u00B1]/,
    -  /[\u00B6\u00BB\u00BF\u00D7\u00F7]/,
    -  /[\u2016-\u2017]/,
    -  /[\u2020-\u2027]/,
    -  /[\u2030-\u203E]/,
    -  /[\u2041-\u2053]/,
    -  /[\u2055-\u205E]/,
    -  /[\u2190-\u23FF]/,
    -  /[\u2500-\u2775]/,
    -  /[\u2794-\u2BFF]/,
    -  /[\u2E00-\u2E7F]/,
    -  /[\u3001-\u3003]/,
    -  /[\u3008-\u3020]/,
    -  /[\u3030]/
    -);
    -
    -// Valid characters for operators.
    -const operatorCharacter = either(
    -  operatorHead,
    -  /[\u0300-\u036F]/,
    -  /[\u1DC0-\u1DFF]/,
    -  /[\u20D0-\u20FF]/,
    -  /[\uFE00-\uFE0F]/,
    -  /[\uFE20-\uFE2F]/
    -  // TODO: The following characters are also allowed, but the regex isn't supported yet.
    -  // /[\u{E0100}-\u{E01EF}]/u
    -);
    -
    -// Valid operator.
    -const operator = concat(operatorHead, operatorCharacter, '*');
    -
    -// Valid first characters for identifiers.
    -const identifierHead = either(
    -  /[a-zA-Z_]/,
    -  /[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,
    -  /[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,
    -  /[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,
    -  /[\u1E00-\u1FFF]/,
    -  /[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,
    -  /[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,
    -  /[\u2C00-\u2DFF\u2E80-\u2FFF]/,
    -  /[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,
    -  /[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,
    -  /[\uFE47-\uFEFE\uFF00-\uFFFD]/ // Should be /[\uFE47-\uFFFD]/, but we have to exclude FEFF.
    -  // The following characters are also allowed, but the regexes aren't supported yet.
    -  // /[\u{10000}-\u{1FFFD}\u{20000-\u{2FFFD}\u{30000}-\u{3FFFD}\u{40000}-\u{4FFFD}]/u,
    -  // /[\u{50000}-\u{5FFFD}\u{60000-\u{6FFFD}\u{70000}-\u{7FFFD}\u{80000}-\u{8FFFD}]/u,
    -  // /[\u{90000}-\u{9FFFD}\u{A0000-\u{AFFFD}\u{B0000}-\u{BFFFD}\u{C0000}-\u{CFFFD}]/u,
    -  // /[\u{D0000}-\u{DFFFD}\u{E0000-\u{EFFFD}]/u
    -);
    -
    -// Valid characters for identifiers.
    -const identifierCharacter = either(
    -  identifierHead,
    -  /\d/,
    -  /[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/
    -);
    -
    -// Valid identifier.
    -const identifier = concat(identifierHead, identifierCharacter, '*');
    -
    -// Valid type identifier.
    -const typeIdentifier = concat(/[A-Z]/, identifierCharacter, '*');
    -
    -// Built-in attributes, which are highlighted as keywords.
    -// @available is handled separately.
    -const keywordAttributes = [
    -  'autoclosure',
    -  concat(/convention\(/, either('swift', 'block', 'c'), /\)/),
    -  'discardableResult',
    -  'dynamicCallable',
    -  'dynamicMemberLookup',
    -  'escaping',
    -  'frozen',
    -  'GKInspectable',
    -  'IBAction',
    -  'IBDesignable',
    -  'IBInspectable',
    -  'IBOutlet',
    -  'IBSegueAction',
    -  'inlinable',
    -  'main',
    -  'nonobjc',
    -  'NSApplicationMain',
    -  'NSCopying',
    -  'NSManaged',
    -  concat(/objc\(/, identifier, /\)/),
    -  'objc',
    -  'objcMembers',
    -  'propertyWrapper',
    -  'requires_stored_property_inits',
    -  'testable',
    -  'UIApplicationMain',
    -  'unknown',
    -  'usableFromInline'
    -];
    -
    -// Contextual keywords used in @available and #available.
    -const availabilityKeywords = [
    -  'iOS',
    -  'iOSApplicationExtension',
    -  'macOS',
    -  'macOSApplicationExtension',
    -  'macCatalyst',
    -  'macCatalystApplicationExtension',
    -  'watchOS',
    -  'watchOSApplicationExtension',
    -  'tvOS',
    -  'tvOSApplicationExtension',
    -  'swift'
    -];
    -
    -/*
    -Language: Swift
    -Description: Swift is a general-purpose programming language built using a modern approach to safety, performance, and software design patterns.
    -Author: Steven Van Impe 
    -Contributors: Chris Eidhof , Nate Cook , Alexander Lichter , Richard Gibson 
    -Website: https://swift.org
    -Category: common, system
    -*/
    -
    -/** @type LanguageFn */
    -function swift(hljs) {
    -  const WHITESPACE = {
    -    match: /\s+/,
    -    relevance: 0
    -  };
    -  // https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#ID411
    -  const BLOCK_COMMENT = hljs.COMMENT(
    -    '/\\*',
    -    '\\*/',
    -    {
    -      contains: [ 'self' ]
    -    }
    -  );
    -  const COMMENTS = [
    -    hljs.C_LINE_COMMENT_MODE,
    -    BLOCK_COMMENT
    -  ];
    -
    -  // https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#ID413
    -  // https://docs.swift.org/swift-book/ReferenceManual/zzSummaryOfTheGrammar.html
    -  const DOT_KEYWORD = {
    -    className: 'keyword',
    -    begin: concat(/\./, lookahead(either(...dotKeywords, ...optionalDotKeywords))),
    -    end: either(...dotKeywords, ...optionalDotKeywords),
    -    excludeBegin: true
    -  };
    -  const KEYWORD_GUARD = {
    -    // Consume .keyword to prevent highlighting properties and methods as keywords.
    -    match: concat(/\./, either(...keywords)),
    -    relevance: 0
    -  };
    -  const PLAIN_KEYWORDS = keywords
    -    .filter(kw => typeof kw === 'string')
    -    .concat([ "_|0" ]); // seems common, so 0 relevance
    -  const REGEX_KEYWORDS = keywords
    -    .filter(kw => typeof kw !== 'string') // find regex
    -    .concat(keywordTypes)
    -    .map(keywordWrapper);
    -  const KEYWORD = {
    -    variants: [
    -      {
    -        className: 'keyword',
    -        match: either(...REGEX_KEYWORDS, ...optionalDotKeywords)
    -      }
    -    ]
    -  };
    -  // find all the regular keywords
    -  const KEYWORDS = {
    -    $pattern: either(
    -      /\b\w+/, // regular keywords
    -      /#\w+/ // number keywords
    -    ),
    -    keyword: PLAIN_KEYWORDS
    -      .concat(numberSignKeywords),
    -    literal: literals
    -  };
    -  const KEYWORD_MODES = [
    -    DOT_KEYWORD,
    -    KEYWORD_GUARD,
    -    KEYWORD
    -  ];
    -
    -  // https://github.com/apple/swift/tree/main/stdlib/public/core
    -  const BUILT_IN_GUARD = {
    -    // Consume .built_in to prevent highlighting properties and methods.
    -    match: concat(/\./, either(...builtIns)),
    -    relevance: 0
    -  };
    -  const BUILT_IN = {
    -    className: 'built_in',
    -    match: concat(/\b/, either(...builtIns), /(?=\()/)
    -  };
    -  const BUILT_INS = [
    -    BUILT_IN_GUARD,
    -    BUILT_IN
    -  ];
    -
    -  // https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#ID418
    -  const OPERATOR_GUARD = {
    -    // Prevent -> from being highlighting as an operator.
    -    match: /->/,
    -    relevance: 0
    -  };
    -  const OPERATOR = {
    -    className: 'operator',
    -    relevance: 0,
    -    variants: [
    -      {
    -        match: operator
    -      },
    -      {
    -        // dot-operator: only operators that start with a dot are allowed to use dots as
    -        // characters (..., ...<, .*, etc). So there rule here is: a dot followed by one or more
    -        // characters that may also include dots.
    -        match: `\\.(\\.|${operatorCharacter})+`
    -      }
    -    ]
    -  };
    -  const OPERATORS = [
    -    OPERATOR_GUARD,
    -    OPERATOR
    -  ];
    -
    -  // https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#grammar_numeric-literal
    -  // TODO: Update for leading `-` after lookbehind is supported everywhere
    -  const decimalDigits = '([0-9]_*)+';
    -  const hexDigits = '([0-9a-fA-F]_*)+';
    -  const NUMBER = {
    -    className: 'number',
    -    relevance: 0,
    -    variants: [
    -      // decimal floating-point-literal (subsumes decimal-literal)
    -      {
    -        match: `\\b(${decimalDigits})(\\.(${decimalDigits}))?` + `([eE][+-]?(${decimalDigits}))?\\b`
    -      },
    -      // hexadecimal floating-point-literal (subsumes hexadecimal-literal)
    -      {
    -        match: `\\b0x(${hexDigits})(\\.(${hexDigits}))?` + `([pP][+-]?(${decimalDigits}))?\\b`
    -      },
    -      // octal-literal
    -      {
    -        match: /\b0o([0-7]_*)+\b/
    -      },
    -      // binary-literal
    -      {
    -        match: /\b0b([01]_*)+\b/
    -      }
    -    ]
    -  };
    -
    -  // https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#grammar_string-literal
    -  const ESCAPED_CHARACTER = (rawDelimiter = "") => ({
    -    className: 'subst',
    -    variants: [
    -      {
    -        match: concat(/\\/, rawDelimiter, /[0\\tnr"']/)
    -      },
    -      {
    -        match: concat(/\\/, rawDelimiter, /u\{[0-9a-fA-F]{1,8}\}/)
    -      }
    -    ]
    -  });
    -  const ESCAPED_NEWLINE = (rawDelimiter = "") => ({
    -    className: 'subst',
    -    match: concat(/\\/, rawDelimiter, /[\t ]*(?:[\r\n]|\r\n)/)
    -  });
    -  const INTERPOLATION = (rawDelimiter = "") => ({
    -    className: 'subst',
    -    label: "interpol",
    -    begin: concat(/\\/, rawDelimiter, /\(/),
    -    end: /\)/
    -  });
    -  const MULTILINE_STRING = (rawDelimiter = "") => ({
    -    begin: concat(rawDelimiter, /"""/),
    -    end: concat(/"""/, rawDelimiter),
    -    contains: [
    -      ESCAPED_CHARACTER(rawDelimiter),
    -      ESCAPED_NEWLINE(rawDelimiter),
    -      INTERPOLATION(rawDelimiter)
    -    ]
    -  });
    -  const SINGLE_LINE_STRING = (rawDelimiter = "") => ({
    -    begin: concat(rawDelimiter, /"/),
    -    end: concat(/"/, rawDelimiter),
    -    contains: [
    -      ESCAPED_CHARACTER(rawDelimiter),
    -      INTERPOLATION(rawDelimiter)
    -    ]
    -  });
    -  const STRING = {
    -    className: 'string',
    -    variants: [
    -      MULTILINE_STRING(),
    -      MULTILINE_STRING("#"),
    -      MULTILINE_STRING("##"),
    -      MULTILINE_STRING("###"),
    -      SINGLE_LINE_STRING(),
    -      SINGLE_LINE_STRING("#"),
    -      SINGLE_LINE_STRING("##"),
    -      SINGLE_LINE_STRING("###")
    -    ]
    -  };
    -
    -  // https://docs.swift.org/swift-book/ReferenceManual/LexicalStructure.html#ID412
    -  const QUOTED_IDENTIFIER = {
    -    match: concat(/`/, identifier, /`/)
    -  };
    -  const IMPLICIT_PARAMETER = {
    -    className: 'variable',
    -    match: /\$\d+/
    -  };
    -  const PROPERTY_WRAPPER_PROJECTION = {
    -    className: 'variable',
    -    match: `\\$${identifierCharacter}+`
    -  };
    -  const IDENTIFIERS = [
    -    QUOTED_IDENTIFIER,
    -    IMPLICIT_PARAMETER,
    -    PROPERTY_WRAPPER_PROJECTION
    -  ];
    -
    -  // https://docs.swift.org/swift-book/ReferenceManual/Attributes.html
    -  const AVAILABLE_ATTRIBUTE = {
    -    match: /(@|#)available/,
    -    className: "keyword",
    -    starts: {
    -      contains: [
    -        {
    -          begin: /\(/,
    -          end: /\)/,
    -          keywords: availabilityKeywords,
    -          contains: [
    -            ...OPERATORS,
    -            NUMBER,
    -            STRING
    -          ]
    -        }
    -      ]
    -    }
    -  };
    -  const KEYWORD_ATTRIBUTE = {
    -    className: 'keyword',
    -    match: concat(/@/, either(...keywordAttributes))
    -  };
    -  const USER_DEFINED_ATTRIBUTE = {
    -    className: 'meta',
    -    match: concat(/@/, identifier)
    -  };
    -  const ATTRIBUTES = [
    -    AVAILABLE_ATTRIBUTE,
    -    KEYWORD_ATTRIBUTE,
    -    USER_DEFINED_ATTRIBUTE
    -  ];
    -
    -  // https://docs.swift.org/swift-book/ReferenceManual/Types.html
    -  const TYPE = {
    -    match: lookahead(/\b[A-Z]/),
    -    relevance: 0,
    -    contains: [
    -      { // Common Apple frameworks, for relevance boost
    -        className: 'type',
    -        match: concat(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/, identifierCharacter, '+')
    -      },
    -      { // Type identifier
    -        className: 'type',
    -        match: typeIdentifier,
    -        relevance: 0
    -      },
    -      { // Optional type
    -        match: /[?!]+/,
    -        relevance: 0
    -      },
    -      { // Variadic parameter
    -        match: /\.\.\./,
    -        relevance: 0
    -      },
    -      { // Protocol composition
    -        match: concat(/\s+&\s+/, lookahead(typeIdentifier)),
    -        relevance: 0
    -      }
    -    ]
    -  };
    -  const GENERIC_ARGUMENTS = {
    -    begin: //,
    -    keywords: KEYWORDS,
    -    contains: [
    -      ...COMMENTS,
    -      ...KEYWORD_MODES,
    -      ...ATTRIBUTES,
    -      OPERATOR_GUARD,
    -      TYPE
    -    ]
    -  };
    -  TYPE.contains.push(GENERIC_ARGUMENTS);
    -
    -  // https://docs.swift.org/swift-book/ReferenceManual/Expressions.html#ID552
    -  // Prevents element names from being highlighted as keywords.
    -  const TUPLE_ELEMENT_NAME = {
    -    match: concat(identifier, /\s*:/),
    -    keywords: "_|0",
    -    relevance: 0
    -  };
    -  // Matches tuples as well as the parameter list of a function type.
    -  const TUPLE = {
    -    begin: /\(/,
    -    end: /\)/,
    -    relevance: 0,
    -    keywords: KEYWORDS,
    -    contains: [
    -      'self',
    -      TUPLE_ELEMENT_NAME,
    -      ...COMMENTS,
    -      ...KEYWORD_MODES,
    -      ...BUILT_INS,
    -      ...OPERATORS,
    -      NUMBER,
    -      STRING,
    -      ...IDENTIFIERS,
    -      ...ATTRIBUTES,
    -      TYPE
    -    ]
    -  };
    -
    -  // https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID362
    -  // Matches both the keyword func and the function title.
    -  // Grouping these lets us differentiate between the operator function <
    -  // and the start of the generic parameter clause (also <).
    -  const FUNC_PLUS_TITLE = {
    -    beginKeywords: 'func',
    -    contains: [
    -      {
    -        className: 'title',
    -        match: either(QUOTED_IDENTIFIER.match, identifier, operator),
    -        // Required to make sure the opening < of the generic parameter clause
    -        // isn't parsed as a second title.
    -        endsParent: true,
    -        relevance: 0
    -      },
    -      WHITESPACE
    -    ]
    -  };
    -  const GENERIC_PARAMETERS = {
    -    begin: //,
    -    contains: [
    -      ...COMMENTS,
    -      TYPE
    -    ]
    -  };
    -  const FUNCTION_PARAMETER_NAME = {
    -    begin: either(
    -      lookahead(concat(identifier, /\s*:/)),
    -      lookahead(concat(identifier, /\s+/, identifier, /\s*:/))
    -    ),
    -    end: /:/,
    -    relevance: 0,
    -    contains: [
    -      {
    -        className: 'keyword',
    -        match: /\b_\b/
    -      },
    -      {
    -        className: 'params',
    -        match: identifier
    -      }
    -    ]
    -  };
    -  const FUNCTION_PARAMETERS = {
    -    begin: /\(/,
    -    end: /\)/,
    -    keywords: KEYWORDS,
    -    contains: [
    -      FUNCTION_PARAMETER_NAME,
    -      ...COMMENTS,
    -      ...KEYWORD_MODES,
    -      ...OPERATORS,
    -      NUMBER,
    -      STRING,
    -      ...ATTRIBUTES,
    -      TYPE,
    -      TUPLE
    -    ],
    -    endsParent: true,
    -    illegal: /["']/
    -  };
    -  const FUNCTION = {
    -    className: 'function',
    -    match: lookahead(/\bfunc\b/),
    -    contains: [
    -      FUNC_PLUS_TITLE,
    -      GENERIC_PARAMETERS,
    -      FUNCTION_PARAMETERS,
    -      WHITESPACE
    -    ],
    -    illegal: [
    -      /\[/,
    -      /%/
    -    ]
    -  };
    -
    -  // https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID375
    -  // https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID379
    -  const INIT_SUBSCRIPT = {
    -    className: 'function',
    -    match: /\b(subscript|init[?!]?)\s*(?=[<(])/,
    -    keywords: {
    -      keyword: "subscript init init? init!",
    -      $pattern: /\w+[?!]?/
    -    },
    -    contains: [
    -      GENERIC_PARAMETERS,
    -      FUNCTION_PARAMETERS,
    -      WHITESPACE
    -    ],
    -    illegal: /\[|%/
    -  };
    -  // https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID380
    -  const OPERATOR_DECLARATION = {
    -    beginKeywords: 'operator',
    -    end: hljs.MATCH_NOTHING_RE,
    -    contains: [
    -      {
    -        className: 'title',
    -        match: operator,
    -        endsParent: true,
    -        relevance: 0
    -      }
    -    ]
    -  };
    -
    -  // https://docs.swift.org/swift-book/ReferenceManual/Declarations.html#ID550
    -  const PRECEDENCEGROUP = {
    -    beginKeywords: 'precedencegroup',
    -    end: hljs.MATCH_NOTHING_RE,
    -    contains: [
    -      {
    -        className: 'title',
    -        match: typeIdentifier,
    -        relevance: 0
    -      },
    -      {
    -        begin: /{/,
    -        end: /}/,
    -        relevance: 0,
    -        endsParent: true,
    -        keywords: [
    -          ...precedencegroupKeywords,
    -          ...literals
    -        ],
    -        contains: [ TYPE ]
    -      }
    -    ]
    -  };
    -
    -  // Add supported submodes to string interpolation.
    -  for (const variant of STRING.variants) {
    -    const interpolation = variant.contains.find(mode => mode.label === "interpol");
    -    // TODO: Interpolation can contain any expression, so there's room for improvement here.
    -    interpolation.keywords = KEYWORDS;
    -    const submodes = [
    -      ...KEYWORD_MODES,
    -      ...BUILT_INS,
    -      ...OPERATORS,
    -      NUMBER,
    -      STRING,
    -      ...IDENTIFIERS
    -    ];
    -    interpolation.contains = [
    -      ...submodes,
    -      {
    -        begin: /\(/,
    -        end: /\)/,
    -        contains: [
    -          'self',
    -          ...submodes
    -        ]
    -      }
    -    ];
    -  }
    -
    -  return {
    -    name: 'Swift',
    -    keywords: KEYWORDS,
    -    contains: [
    -      ...COMMENTS,
    -      FUNCTION,
    -      INIT_SUBSCRIPT,
    -      {
    -        className: 'class',
    -        beginKeywords: 'struct protocol class extension enum',
    -        end: '\\{',
    -        excludeEnd: true,
    -        keywords: KEYWORDS,
    -        contains: [
    -          hljs.inherit(hljs.TITLE_MODE, {
    -            begin: /[A-Za-z$_][\u00C0-\u02B80-9A-Za-z$_]*/
    -          }),
    -          ...KEYWORD_MODES
    -        ]
    -      },
    -      OPERATOR_DECLARATION,
    -      PRECEDENCEGROUP,
    -      {
    -        beginKeywords: 'import',
    -        end: /$/,
    -        contains: [ ...COMMENTS ],
    -        relevance: 0
    -      },
    -      ...KEYWORD_MODES,
    -      ...BUILT_INS,
    -      ...OPERATORS,
    -      NUMBER,
    -      STRING,
    -      ...IDENTIFIERS,
    -      ...ATTRIBUTES,
    -      TYPE,
    -      TUPLE
    -    ]
    -  };
    -}
    -
    -module.exports = swift;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/taggerscript.js b/claude-code-source/node_modules/highlight.js/lib/languages/taggerscript.js
    deleted file mode 100644
    index c82ba288..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/taggerscript.js
    +++ /dev/null
    @@ -1,52 +0,0 @@
    -/*
    -Language: Tagger Script
    -Author: Philipp Wolfer 
    -Description: Syntax Highlighting for the Tagger Script as used by MusicBrainz Picard.
    -Website: https://picard.musicbrainz.org
    - */
    -function taggerscript(hljs) {
    -  const COMMENT = {
    -    className: 'comment',
    -    begin: /\$noop\(/,
    -    end: /\)/,
    -    contains: [ {
    -      begin: /\(/,
    -      end: /\)/,
    -      contains: [ 'self',
    -        {
    -          begin: /\\./
    -        } ]
    -    } ],
    -    relevance: 10
    -  };
    -
    -  const FUNCTION = {
    -    className: 'keyword',
    -    begin: /\$(?!noop)[a-zA-Z][_a-zA-Z0-9]*/,
    -    end: /\(/,
    -    excludeEnd: true
    -  };
    -
    -  const VARIABLE = {
    -    className: 'variable',
    -    begin: /%[_a-zA-Z0-9:]*/,
    -    end: '%'
    -  };
    -
    -  const ESCAPE_SEQUENCE = {
    -    className: 'symbol',
    -    begin: /\\./
    -  };
    -
    -  return {
    -    name: 'Tagger Script',
    -    contains: [
    -      COMMENT,
    -      FUNCTION,
    -      VARIABLE,
    -      ESCAPE_SEQUENCE
    -    ]
    -  };
    -}
    -
    -module.exports = taggerscript;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/tap.js b/claude-code-source/node_modules/highlight.js/lib/languages/tap.js
    deleted file mode 100644
    index c57ab402..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/tap.js
    +++ /dev/null
    @@ -1,55 +0,0 @@
    -/*
    -Language: Test Anything Protocol
    -Description: TAP, the Test Anything Protocol, is a simple text-based interface between testing modules in a test harness.
    -Requires: yaml.js
    -Author: Sergey Bronnikov 
    -Website: https://testanything.org
    -*/
    -
    -function tap(hljs) {
    -  return {
    -    name: 'Test Anything Protocol',
    -    case_insensitive: true,
    -    contains: [
    -      hljs.HASH_COMMENT_MODE,
    -      // version of format and total amount of testcases
    -      {
    -        className: 'meta',
    -        variants: [
    -          {
    -            begin: '^TAP version (\\d+)$'
    -          },
    -          {
    -            begin: '^1\\.\\.(\\d+)$'
    -          }
    -        ]
    -      },
    -      // YAML block
    -      {
    -        begin: /---$/,
    -        end: '\\.\\.\\.$',
    -        subLanguage: 'yaml',
    -        relevance: 0
    -      },
    -      // testcase number
    -      {
    -        className: 'number',
    -        begin: ' (\\d+) '
    -      },
    -      // testcase status and description
    -      {
    -        className: 'symbol',
    -        variants: [
    -          {
    -            begin: '^ok'
    -          },
    -          {
    -            begin: '^not ok'
    -          }
    -        ]
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = tap;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/tcl.js b/claude-code-source/node_modules/highlight.js/lib/languages/tcl.js
    deleted file mode 100644
    index d319223a..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/tcl.js
    +++ /dev/null
    @@ -1,115 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function optional(re) {
    -  return concat('(', re, ')?');
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: Tcl
    -Description: Tcl is a very simple programming language.
    -Author: Radek Liska 
    -Website: https://www.tcl.tk/about/language.html
    -*/
    -
    -function tcl(hljs) {
    -  const TCL_IDENT = /[a-zA-Z_][a-zA-Z0-9_]*/;
    -
    -  const NUMBER = {
    -    className: 'number',
    -    variants: [hljs.BINARY_NUMBER_MODE, hljs.C_NUMBER_MODE]
    -  };
    -
    -  return {
    -    name: 'Tcl',
    -    aliases: ['tk'],
    -    keywords: 'after append apply array auto_execok auto_import auto_load auto_mkindex ' +
    -      'auto_mkindex_old auto_qualify auto_reset bgerror binary break catch cd chan clock ' +
    -      'close concat continue dde dict encoding eof error eval exec exit expr fblocked ' +
    -      'fconfigure fcopy file fileevent filename flush for foreach format gets glob global ' +
    -      'history http if incr info interp join lappend|10 lassign|10 lindex|10 linsert|10 list ' +
    -      'llength|10 load lrange|10 lrepeat|10 lreplace|10 lreverse|10 lsearch|10 lset|10 lsort|10 '+
    -      'mathfunc mathop memory msgcat namespace open package parray pid pkg::create pkg_mkIndex '+
    -      'platform platform::shell proc puts pwd read refchan regexp registry regsub|10 rename '+
    -      'return safe scan seek set socket source split string subst switch tcl_endOfWord '+
    -      'tcl_findLibrary tcl_startOfNextWord tcl_startOfPreviousWord tcl_wordBreakAfter '+
    -      'tcl_wordBreakBefore tcltest tclvars tell time tm trace unknown unload unset update '+
    -      'uplevel upvar variable vwait while',
    -    contains: [
    -      hljs.COMMENT(';[ \\t]*#', '$'),
    -      hljs.COMMENT('^[ \\t]*#', '$'),
    -      {
    -        beginKeywords: 'proc',
    -        end: '[\\{]',
    -        excludeEnd: true,
    -        contains: [
    -          {
    -            className: 'title',
    -            begin: '[ \\t\\n\\r]+(::)?[a-zA-Z_]((::)?[a-zA-Z0-9_])*',
    -            end: '[ \\t\\n\\r]',
    -            endsWithParent: true,
    -            excludeEnd: true
    -          }
    -        ]
    -      },
    -      {
    -        className: "variable",
    -        variants: [
    -          {
    -            begin: concat(
    -              /\$/,
    -              optional(/::/),
    -              TCL_IDENT,
    -              '(::',
    -              TCL_IDENT,
    -              ')*'
    -            )
    -          },
    -          {
    -            begin: '\\$\\{(::)?[a-zA-Z_]((::)?[a-zA-Z0-9_])*',
    -            end: '\\}',
    -            contains: [
    -              NUMBER
    -            ]
    -          }
    -        ]
    -      },
    -      {
    -        className: 'string',
    -        contains: [hljs.BACKSLASH_ESCAPE],
    -        variants: [
    -          hljs.inherit(hljs.QUOTE_STRING_MODE, {illegal: null})
    -        ]
    -      },
    -      NUMBER
    -    ]
    -  }
    -}
    -
    -module.exports = tcl;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/thrift.js b/claude-code-source/node_modules/highlight.js/lib/languages/thrift.js
    deleted file mode 100644
    index 7d05b877..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/thrift.js
    +++ /dev/null
    @@ -1,51 +0,0 @@
    -/*
    -Language: Thrift
    -Author: Oleg Efimov 
    -Description: Thrift message definition format
    -Website: https://thrift.apache.org
    -Category: protocols
    -*/
    -
    -function thrift(hljs) {
    -  const BUILT_IN_TYPES = 'bool byte i16 i32 i64 double string binary';
    -  return {
    -    name: 'Thrift',
    -    keywords: {
    -      keyword:
    -        'namespace const typedef struct enum service exception void oneway set list map required optional',
    -      built_in:
    -        BUILT_IN_TYPES,
    -      literal:
    -        'true false'
    -    },
    -    contains: [
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.NUMBER_MODE,
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      {
    -        className: 'class',
    -        beginKeywords: 'struct enum service exception',
    -        end: /\{/,
    -        illegal: /\n/,
    -        contains: [
    -          hljs.inherit(hljs.TITLE_MODE, {
    -            // hack: eating everything after the first title
    -            starts: {
    -              endsWithParent: true,
    -              excludeEnd: true
    -            }
    -          })
    -        ]
    -      },
    -      {
    -        begin: '\\b(set|list|map)\\s*<',
    -        end: '>',
    -        keywords: BUILT_IN_TYPES,
    -        contains: [ 'self' ]
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = thrift;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/tp.js b/claude-code-source/node_modules/highlight.js/lib/languages/tp.js
    deleted file mode 100644
    index 58b4d439..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/tp.js
    +++ /dev/null
    @@ -1,95 +0,0 @@
    -/*
    -Language: TP
    -Author: Jay Strybis 
    -Description: FANUC TP programming language (TPP).
    -*/
    -
    -function tp(hljs) {
    -  const TPID = {
    -    className: 'number',
    -    begin: '[1-9][0-9]*', /* no leading zeros */
    -    relevance: 0
    -  };
    -  const TPLABEL = {
    -    className: 'symbol',
    -    begin: ':[^\\]]+'
    -  };
    -  const TPDATA = {
    -    className: 'built_in',
    -    begin: '(AR|P|PAYLOAD|PR|R|SR|RSR|LBL|VR|UALM|MESSAGE|UTOOL|UFRAME|TIMER|' +
    -    'TIMER_OVERFLOW|JOINT_MAX_SPEED|RESUME_PROG|DIAG_REC)\\[',
    -    end: '\\]',
    -    contains: [
    -      'self',
    -      TPID,
    -      TPLABEL
    -    ]
    -  };
    -  const TPIO = {
    -    className: 'built_in',
    -    begin: '(AI|AO|DI|DO|F|RI|RO|UI|UO|GI|GO|SI|SO)\\[',
    -    end: '\\]',
    -    contains: [
    -      'self',
    -      TPID,
    -      hljs.QUOTE_STRING_MODE, /* for pos section at bottom */
    -      TPLABEL
    -    ]
    -  };
    -
    -  return {
    -    name: 'TP',
    -    keywords: {
    -      keyword:
    -        'ABORT ACC ADJUST AND AP_LD BREAK CALL CNT COL CONDITION CONFIG DA DB ' +
    -        'DIV DETECT ELSE END ENDFOR ERR_NUM ERROR_PROG FINE FOR GP GUARD INC ' +
    -        'IF JMP LINEAR_MAX_SPEED LOCK MOD MONITOR OFFSET Offset OR OVERRIDE ' +
    -        'PAUSE PREG PTH RT_LD RUN SELECT SKIP Skip TA TB TO TOOL_OFFSET ' +
    -        'Tool_Offset UF UT UFRAME_NUM UTOOL_NUM UNLOCK WAIT X Y Z W P R STRLEN ' +
    -        'SUBSTR FINDSTR VOFFSET PROG ATTR MN POS',
    -      literal:
    -        'ON OFF max_speed LPOS JPOS ENABLE DISABLE START STOP RESET'
    -    },
    -    contains: [
    -      TPDATA,
    -      TPIO,
    -      {
    -        className: 'keyword',
    -        begin: '/(PROG|ATTR|MN|POS|END)\\b'
    -      },
    -      {
    -        /* this is for cases like ,CALL */
    -        className: 'keyword',
    -        begin: '(CALL|RUN|POINT_LOGIC|LBL)\\b'
    -      },
    -      {
    -        /* this is for cases like CNT100 where the default lexemes do not
    -         * separate the keyword and the number */
    -        className: 'keyword',
    -        begin: '\\b(ACC|CNT|Skip|Offset|PSPD|RT_LD|AP_LD|Tool_Offset)'
    -      },
    -      {
    -        /* to catch numbers that do not have a word boundary on the left */
    -        className: 'number',
    -        begin: '\\d+(sec|msec|mm/sec|cm/min|inch/min|deg/sec|mm|in|cm)?\\b',
    -        relevance: 0
    -      },
    -      hljs.COMMENT('//', '[;$]'),
    -      hljs.COMMENT('!', '[;$]'),
    -      hljs.COMMENT('--eg:', '$'),
    -      hljs.QUOTE_STRING_MODE,
    -      {
    -        className: 'string',
    -        begin: '\'',
    -        end: '\''
    -      },
    -      hljs.C_NUMBER_MODE,
    -      {
    -        className: 'variable',
    -        begin: '\\$[A-Za-z0-9_]+'
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = tp;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/twig.js b/claude-code-source/node_modules/highlight.js/lib/languages/twig.js
    deleted file mode 100644
    index 216c8b16..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/twig.js
    +++ /dev/null
    @@ -1,77 +0,0 @@
    -/*
    -Language: Twig
    -Requires: xml.js
    -Author: Luke Holder 
    -Description: Twig is a templating language for PHP
    -Website: https://twig.symfony.com
    -Category: template
    -*/
    -
    -function twig(hljs) {
    -  var PARAMS = {
    -    className: 'params',
    -    begin: '\\(', end: '\\)'
    -  };
    -
    -  var FUNCTION_NAMES = 'attribute block constant cycle date dump include ' +
    -                  'max min parent random range source template_from_string';
    -
    -  var FUNCTIONS = {
    -    beginKeywords: FUNCTION_NAMES,
    -    keywords: {name: FUNCTION_NAMES},
    -    relevance: 0,
    -    contains: [
    -      PARAMS
    -    ]
    -  };
    -
    -  var FILTER = {
    -    begin: /\|[A-Za-z_]+:?/,
    -    keywords:
    -      'abs batch capitalize column convert_encoding date date_modify default ' +
    -      'escape filter first format inky_to_html inline_css join json_encode keys last ' +
    -      'length lower map markdown merge nl2br number_format raw reduce replace ' +
    -      'reverse round slice sort spaceless split striptags title trim upper url_encode',
    -    contains: [
    -      FUNCTIONS
    -    ]
    -  };
    -
    -  var TAGS = 'apply autoescape block deprecated do embed extends filter flush for from ' +
    -    'if import include macro sandbox set use verbatim with';
    -
    -  TAGS = TAGS + ' ' + TAGS.split(' ').map(function(t){return 'end' + t}).join(' ');
    -
    -  return {
    -    name: 'Twig',
    -    aliases: ['craftcms'],
    -    case_insensitive: true,
    -    subLanguage: 'xml',
    -    contains: [
    -      hljs.COMMENT(/\{#/, /#\}/),
    -      {
    -        className: 'template-tag',
    -        begin: /\{%/, end: /%\}/,
    -        contains: [
    -          {
    -            className: 'name',
    -            begin: /\w+/,
    -            keywords: TAGS,
    -            starts: {
    -              endsWithParent: true,
    -              contains: [FILTER, FUNCTIONS],
    -              relevance: 0
    -            }
    -          }
    -        ]
    -      },
    -      {
    -        className: 'template-variable',
    -        begin: /\{\{/, end: /\}\}/,
    -        contains: ['self', FILTER, FUNCTIONS]
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = twig;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/typescript.js b/claude-code-source/node_modules/highlight.js/lib/languages/typescript.js
    deleted file mode 100644
    index 24202814..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/typescript.js
    +++ /dev/null
    @@ -1,697 +0,0 @@
    -const IDENT_RE = '[A-Za-z$_][0-9A-Za-z$_]*';
    -const KEYWORDS = [
    -  "as", // for exports
    -  "in",
    -  "of",
    -  "if",
    -  "for",
    -  "while",
    -  "finally",
    -  "var",
    -  "new",
    -  "function",
    -  "do",
    -  "return",
    -  "void",
    -  "else",
    -  "break",
    -  "catch",
    -  "instanceof",
    -  "with",
    -  "throw",
    -  "case",
    -  "default",
    -  "try",
    -  "switch",
    -  "continue",
    -  "typeof",
    -  "delete",
    -  "let",
    -  "yield",
    -  "const",
    -  "class",
    -  // JS handles these with a special rule
    -  // "get",
    -  // "set",
    -  "debugger",
    -  "async",
    -  "await",
    -  "static",
    -  "import",
    -  "from",
    -  "export",
    -  "extends"
    -];
    -const LITERALS = [
    -  "true",
    -  "false",
    -  "null",
    -  "undefined",
    -  "NaN",
    -  "Infinity"
    -];
    -
    -const TYPES = [
    -  "Intl",
    -  "DataView",
    -  "Number",
    -  "Math",
    -  "Date",
    -  "String",
    -  "RegExp",
    -  "Object",
    -  "Function",
    -  "Boolean",
    -  "Error",
    -  "Symbol",
    -  "Set",
    -  "Map",
    -  "WeakSet",
    -  "WeakMap",
    -  "Proxy",
    -  "Reflect",
    -  "JSON",
    -  "Promise",
    -  "Float64Array",
    -  "Int16Array",
    -  "Int32Array",
    -  "Int8Array",
    -  "Uint16Array",
    -  "Uint32Array",
    -  "Float32Array",
    -  "Array",
    -  "Uint8Array",
    -  "Uint8ClampedArray",
    -  "ArrayBuffer",
    -  "BigInt64Array",
    -  "BigUint64Array",
    -  "BigInt"
    -];
    -
    -const ERROR_TYPES = [
    -  "EvalError",
    -  "InternalError",
    -  "RangeError",
    -  "ReferenceError",
    -  "SyntaxError",
    -  "TypeError",
    -  "URIError"
    -];
    -
    -const BUILT_IN_GLOBALS = [
    -  "setInterval",
    -  "setTimeout",
    -  "clearInterval",
    -  "clearTimeout",
    -
    -  "require",
    -  "exports",
    -
    -  "eval",
    -  "isFinite",
    -  "isNaN",
    -  "parseFloat",
    -  "parseInt",
    -  "decodeURI",
    -  "decodeURIComponent",
    -  "encodeURI",
    -  "encodeURIComponent",
    -  "escape",
    -  "unescape"
    -];
    -
    -const BUILT_IN_VARIABLES = [
    -  "arguments",
    -  "this",
    -  "super",
    -  "console",
    -  "window",
    -  "document",
    -  "localStorage",
    -  "module",
    -  "global" // Node.js
    -];
    -
    -const BUILT_INS = [].concat(
    -  BUILT_IN_GLOBALS,
    -  BUILT_IN_VARIABLES,
    -  TYPES,
    -  ERROR_TYPES
    -);
    -
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function lookahead(re) {
    -  return concat('(?=', re, ')');
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/*
    -Language: JavaScript
    -Description: JavaScript (JS) is a lightweight, interpreted, or just-in-time compiled programming language with first-class functions.
    -Category: common, scripting
    -Website: https://developer.mozilla.org/en-US/docs/Web/JavaScript
    -*/
    -
    -/** @type LanguageFn */
    -function javascript(hljs) {
    -  /**
    -   * Takes a string like " {
    -    const tag = "',
    -    end: ''
    -  };
    -  const XML_TAG = {
    -    begin: /<[A-Za-z0-9\\._:-]+/,
    -    end: /\/[A-Za-z0-9\\._:-]+>|\/>/,
    -    /**
    -     * @param {RegExpMatchArray} match
    -     * @param {CallbackResponse} response
    -     */
    -    isTrulyOpeningTag: (match, response) => {
    -      const afterMatchIndex = match[0].length + match.index;
    -      const nextChar = match.input[afterMatchIndex];
    -      // nested type?
    -      // HTML should not include another raw `<` inside a tag
    -      // But a type might: `>`, etc.
    -      if (nextChar === "<") {
    -        response.ignoreMatch();
    -        return;
    -      }
    -      // 
    -      // This is now either a tag or a type.
    -      if (nextChar === ">") {
    -        // if we cannot find a matching closing tag, then we
    -        // will ignore it
    -        if (!hasClosingTag(match, { after: afterMatchIndex })) {
    -          response.ignoreMatch();
    -        }
    -      }
    -    }
    -  };
    -  const KEYWORDS$1 = {
    -    $pattern: IDENT_RE,
    -    keyword: KEYWORDS,
    -    literal: LITERALS,
    -    built_in: BUILT_INS
    -  };
    -
    -  // https://tc39.es/ecma262/#sec-literals-numeric-literals
    -  const decimalDigits = '[0-9](_?[0-9])*';
    -  const frac = `\\.(${decimalDigits})`;
    -  // DecimalIntegerLiteral, including Annex B NonOctalDecimalIntegerLiteral
    -  // https://tc39.es/ecma262/#sec-additional-syntax-numeric-literals
    -  const decimalInteger = `0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*`;
    -  const NUMBER = {
    -    className: 'number',
    -    variants: [
    -      // DecimalLiteral
    -      { begin: `(\\b(${decimalInteger})((${frac})|\\.)?|(${frac}))` +
    -        `[eE][+-]?(${decimalDigits})\\b` },
    -      { begin: `\\b(${decimalInteger})\\b((${frac})\\b|\\.)?|(${frac})\\b` },
    -
    -      // DecimalBigIntegerLiteral
    -      { begin: `\\b(0|[1-9](_?[0-9])*)n\\b` },
    -
    -      // NonDecimalIntegerLiteral
    -      { begin: "\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b" },
    -      { begin: "\\b0[bB][0-1](_?[0-1])*n?\\b" },
    -      { begin: "\\b0[oO][0-7](_?[0-7])*n?\\b" },
    -
    -      // LegacyOctalIntegerLiteral (does not include underscore separators)
    -      // https://tc39.es/ecma262/#sec-additional-syntax-numeric-literals
    -      { begin: "\\b0[0-7]+n?\\b" },
    -    ],
    -    relevance: 0
    -  };
    -
    -  const SUBST = {
    -    className: 'subst',
    -    begin: '\\$\\{',
    -    end: '\\}',
    -    keywords: KEYWORDS$1,
    -    contains: [] // defined later
    -  };
    -  const HTML_TEMPLATE = {
    -    begin: 'html`',
    -    end: '',
    -    starts: {
    -      end: '`',
    -      returnEnd: false,
    -      contains: [
    -        hljs.BACKSLASH_ESCAPE,
    -        SUBST
    -      ],
    -      subLanguage: 'xml'
    -    }
    -  };
    -  const CSS_TEMPLATE = {
    -    begin: 'css`',
    -    end: '',
    -    starts: {
    -      end: '`',
    -      returnEnd: false,
    -      contains: [
    -        hljs.BACKSLASH_ESCAPE,
    -        SUBST
    -      ],
    -      subLanguage: 'css'
    -    }
    -  };
    -  const TEMPLATE_STRING = {
    -    className: 'string',
    -    begin: '`',
    -    end: '`',
    -    contains: [
    -      hljs.BACKSLASH_ESCAPE,
    -      SUBST
    -    ]
    -  };
    -  const JSDOC_COMMENT = hljs.COMMENT(
    -    /\/\*\*(?!\/)/,
    -    '\\*/',
    -    {
    -      relevance: 0,
    -      contains: [
    -        {
    -          className: 'doctag',
    -          begin: '@[A-Za-z]+',
    -          contains: [
    -            {
    -              className: 'type',
    -              begin: '\\{',
    -              end: '\\}',
    -              relevance: 0
    -            },
    -            {
    -              className: 'variable',
    -              begin: IDENT_RE$1 + '(?=\\s*(-)|$)',
    -              endsParent: true,
    -              relevance: 0
    -            },
    -            // eat spaces (not newlines) so we can find
    -            // types or variables
    -            {
    -              begin: /(?=[^\n])\s/,
    -              relevance: 0
    -            }
    -          ]
    -        }
    -      ]
    -    }
    -  );
    -  const COMMENT = {
    -    className: "comment",
    -    variants: [
    -      JSDOC_COMMENT,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.C_LINE_COMMENT_MODE
    -    ]
    -  };
    -  const SUBST_INTERNALS = [
    -    hljs.APOS_STRING_MODE,
    -    hljs.QUOTE_STRING_MODE,
    -    HTML_TEMPLATE,
    -    CSS_TEMPLATE,
    -    TEMPLATE_STRING,
    -    NUMBER,
    -    hljs.REGEXP_MODE
    -  ];
    -  SUBST.contains = SUBST_INTERNALS
    -    .concat({
    -      // we need to pair up {} inside our subst to prevent
    -      // it from ending too early by matching another }
    -      begin: /\{/,
    -      end: /\}/,
    -      keywords: KEYWORDS$1,
    -      contains: [
    -        "self"
    -      ].concat(SUBST_INTERNALS)
    -    });
    -  const SUBST_AND_COMMENTS = [].concat(COMMENT, SUBST.contains);
    -  const PARAMS_CONTAINS = SUBST_AND_COMMENTS.concat([
    -    // eat recursive parens in sub expressions
    -    {
    -      begin: /\(/,
    -      end: /\)/,
    -      keywords: KEYWORDS$1,
    -      contains: ["self"].concat(SUBST_AND_COMMENTS)
    -    }
    -  ]);
    -  const PARAMS = {
    -    className: 'params',
    -    begin: /\(/,
    -    end: /\)/,
    -    excludeBegin: true,
    -    excludeEnd: true,
    -    keywords: KEYWORDS$1,
    -    contains: PARAMS_CONTAINS
    -  };
    -
    -  return {
    -    name: 'Javascript',
    -    aliases: ['js', 'jsx', 'mjs', 'cjs'],
    -    keywords: KEYWORDS$1,
    -    // this will be extended by TypeScript
    -    exports: { PARAMS_CONTAINS },
    -    illegal: /#(?![$_A-z])/,
    -    contains: [
    -      hljs.SHEBANG({
    -        label: "shebang",
    -        binary: "node",
    -        relevance: 5
    -      }),
    -      {
    -        label: "use_strict",
    -        className: 'meta',
    -        relevance: 10,
    -        begin: /^\s*['"]use (strict|asm)['"]/
    -      },
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      HTML_TEMPLATE,
    -      CSS_TEMPLATE,
    -      TEMPLATE_STRING,
    -      COMMENT,
    -      NUMBER,
    -      { // object attr container
    -        begin: concat(/[{,\n]\s*/,
    -          // we need to look ahead to make sure that we actually have an
    -          // attribute coming up so we don't steal a comma from a potential
    -          // "value" container
    -          //
    -          // NOTE: this might not work how you think.  We don't actually always
    -          // enter this mode and stay.  Instead it might merely match `,
    -          // ` and then immediately end after the , because it
    -          // fails to find any actual attrs. But this still does the job because
    -          // it prevents the value contain rule from grabbing this instead and
    -          // prevening this rule from firing when we actually DO have keys.
    -          lookahead(concat(
    -            // we also need to allow for multiple possible comments inbetween
    -            // the first key:value pairing
    -            /(((\/\/.*$)|(\/\*(\*[^/]|[^*])*\*\/))\s*)*/,
    -            IDENT_RE$1 + '\\s*:'))),
    -        relevance: 0,
    -        contains: [
    -          {
    -            className: 'attr',
    -            begin: IDENT_RE$1 + lookahead('\\s*:'),
    -            relevance: 0
    -          }
    -        ]
    -      },
    -      { // "value" container
    -        begin: '(' + hljs.RE_STARTERS_RE + '|\\b(case|return|throw)\\b)\\s*',
    -        keywords: 'return throw case',
    -        contains: [
    -          COMMENT,
    -          hljs.REGEXP_MODE,
    -          {
    -            className: 'function',
    -            // we have to count the parens to make sure we actually have the
    -            // correct bounding ( ) before the =>.  There could be any number of
    -            // sub-expressions inside also surrounded by parens.
    -            begin: '(\\(' +
    -            '[^()]*(\\(' +
    -            '[^()]*(\\(' +
    -            '[^()]*' +
    -            '\\)[^()]*)*' +
    -            '\\)[^()]*)*' +
    -            '\\)|' + hljs.UNDERSCORE_IDENT_RE + ')\\s*=>',
    -            returnBegin: true,
    -            end: '\\s*=>',
    -            contains: [
    -              {
    -                className: 'params',
    -                variants: [
    -                  {
    -                    begin: hljs.UNDERSCORE_IDENT_RE,
    -                    relevance: 0
    -                  },
    -                  {
    -                    className: null,
    -                    begin: /\(\s*\)/,
    -                    skip: true
    -                  },
    -                  {
    -                    begin: /\(/,
    -                    end: /\)/,
    -                    excludeBegin: true,
    -                    excludeEnd: true,
    -                    keywords: KEYWORDS$1,
    -                    contains: PARAMS_CONTAINS
    -                  }
    -                ]
    -              }
    -            ]
    -          },
    -          { // could be a comma delimited list of params to a function call
    -            begin: /,/, relevance: 0
    -          },
    -          {
    -            className: '',
    -            begin: /\s/,
    -            end: /\s*/,
    -            skip: true
    -          },
    -          { // JSX
    -            variants: [
    -              { begin: FRAGMENT.begin, end: FRAGMENT.end },
    -              {
    -                begin: XML_TAG.begin,
    -                // we carefully check the opening tag to see if it truly
    -                // is a tag and not a false positive
    -                'on:begin': XML_TAG.isTrulyOpeningTag,
    -                end: XML_TAG.end
    -              }
    -            ],
    -            subLanguage: 'xml',
    -            contains: [
    -              {
    -                begin: XML_TAG.begin,
    -                end: XML_TAG.end,
    -                skip: true,
    -                contains: ['self']
    -              }
    -            ]
    -          }
    -        ],
    -        relevance: 0
    -      },
    -      {
    -        className: 'function',
    -        beginKeywords: 'function',
    -        end: /[{;]/,
    -        excludeEnd: true,
    -        keywords: KEYWORDS$1,
    -        contains: [
    -          'self',
    -          hljs.inherit(hljs.TITLE_MODE, { begin: IDENT_RE$1 }),
    -          PARAMS
    -        ],
    -        illegal: /%/
    -      },
    -      {
    -        // prevent this from getting swallowed up by function
    -        // since they appear "function like"
    -        beginKeywords: "while if switch catch for"
    -      },
    -      {
    -        className: 'function',
    -        // we have to count the parens to make sure we actually have the correct
    -        // bounding ( ).  There could be any number of sub-expressions inside
    -        // also surrounded by parens.
    -        begin: hljs.UNDERSCORE_IDENT_RE +
    -          '\\(' + // first parens
    -          '[^()]*(\\(' +
    -            '[^()]*(\\(' +
    -              '[^()]*' +
    -            '\\)[^()]*)*' +
    -          '\\)[^()]*)*' +
    -          '\\)\\s*\\{', // end parens
    -        returnBegin:true,
    -        contains: [
    -          PARAMS,
    -          hljs.inherit(hljs.TITLE_MODE, { begin: IDENT_RE$1 }),
    -        ]
    -      },
    -      // hack: prevents detection of keywords in some circumstances
    -      // .keyword()
    -      // $keyword = x
    -      {
    -        variants: [
    -          { begin: '\\.' + IDENT_RE$1 },
    -          { begin: '\\$' + IDENT_RE$1 }
    -        ],
    -        relevance: 0
    -      },
    -      { // ES6 class
    -        className: 'class',
    -        beginKeywords: 'class',
    -        end: /[{;=]/,
    -        excludeEnd: true,
    -        illegal: /[:"[\]]/,
    -        contains: [
    -          { beginKeywords: 'extends' },
    -          hljs.UNDERSCORE_TITLE_MODE
    -        ]
    -      },
    -      {
    -        begin: /\b(?=constructor)/,
    -        end: /[{;]/,
    -        excludeEnd: true,
    -        contains: [
    -          hljs.inherit(hljs.TITLE_MODE, { begin: IDENT_RE$1 }),
    -          'self',
    -          PARAMS
    -        ]
    -      },
    -      {
    -        begin: '(get|set)\\s+(?=' + IDENT_RE$1 + '\\()',
    -        end: /\{/,
    -        keywords: "get set",
    -        contains: [
    -          hljs.inherit(hljs.TITLE_MODE, { begin: IDENT_RE$1 }),
    -          { begin: /\(\)/ }, // eat to avoid empty params
    -          PARAMS
    -        ]
    -      },
    -      {
    -        begin: /\$[(.]/ // relevance booster for a pattern common to JS libs: `$(something)` and `$.something`
    -      }
    -    ]
    -  };
    -}
    -
    -/*
    -Language: TypeScript
    -Author: Panu Horsmalahti 
    -Contributors: Ike Ku 
    -Description: TypeScript is a strict superset of JavaScript
    -Website: https://www.typescriptlang.org
    -Category: common, scripting
    -*/
    -
    -/** @type LanguageFn */
    -function typescript(hljs) {
    -  const IDENT_RE$1 = IDENT_RE;
    -  const NAMESPACE = {
    -    beginKeywords: 'namespace', end: /\{/, excludeEnd: true
    -  };
    -  const INTERFACE = {
    -    beginKeywords: 'interface', end: /\{/, excludeEnd: true,
    -    keywords: 'interface extends'
    -  };
    -  const USE_STRICT = {
    -    className: 'meta',
    -    relevance: 10,
    -    begin: /^\s*['"]use strict['"]/
    -  };
    -  const TYPES = [
    -    "any",
    -    "void",
    -    "number",
    -    "boolean",
    -    "string",
    -    "object",
    -    "never",
    -    "enum"
    -  ];
    -  const TS_SPECIFIC_KEYWORDS = [
    -    "type",
    -    "namespace",
    -    "typedef",
    -    "interface",
    -    "public",
    -    "private",
    -    "protected",
    -    "implements",
    -    "declare",
    -    "abstract",
    -    "readonly"
    -  ];
    -  const KEYWORDS$1 = {
    -    $pattern: IDENT_RE,
    -    keyword: KEYWORDS.concat(TS_SPECIFIC_KEYWORDS),
    -    literal: LITERALS,
    -    built_in: BUILT_INS.concat(TYPES)
    -  };
    -  const DECORATOR = {
    -    className: 'meta',
    -    begin: '@' + IDENT_RE$1,
    -  };
    -
    -  const swapMode = (mode, label, replacement) => {
    -    const indx = mode.contains.findIndex(m => m.label === label);
    -    if (indx === -1) { throw new Error("can not find mode to replace"); }
    -    mode.contains.splice(indx, 1, replacement);
    -  };
    -
    -  const tsLanguage = javascript(hljs);
    -
    -  // this should update anywhere keywords is used since
    -  // it will be the same actual JS object
    -  Object.assign(tsLanguage.keywords, KEYWORDS$1);
    -
    -  tsLanguage.exports.PARAMS_CONTAINS.push(DECORATOR);
    -  tsLanguage.contains = tsLanguage.contains.concat([
    -    DECORATOR,
    -    NAMESPACE,
    -    INTERFACE,
    -  ]);
    -
    -  // TS gets a simpler shebang rule than JS
    -  swapMode(tsLanguage, "shebang", hljs.SHEBANG());
    -  // JS use strict rule purposely excludes `asm` which makes no sense
    -  swapMode(tsLanguage, "use_strict", USE_STRICT);
    -
    -  const functionDeclaration = tsLanguage.contains.find(m => m.className === "function");
    -  functionDeclaration.relevance = 0; // () => {} is more typical in TypeScript
    -
    -  Object.assign(tsLanguage, {
    -    name: 'TypeScript',
    -    aliases: ['ts', 'tsx']
    -  });
    -
    -  return tsLanguage;
    -}
    -
    -module.exports = typescript;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/vala.js b/claude-code-source/node_modules/highlight.js/lib/languages/vala.js
    deleted file mode 100644
    index e3a577de..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/vala.js
    +++ /dev/null
    @@ -1,61 +0,0 @@
    -/*
    -Language: Vala
    -Author: Antono Vasiljev 
    -Description: Vala is a new programming language that aims to bring modern programming language features to GNOME developers without imposing any additional runtime requirements and without using a different ABI compared to applications and libraries written in C.
    -Website: https://wiki.gnome.org/Projects/Vala
    -*/
    -
    -function vala(hljs) {
    -  return {
    -    name: 'Vala',
    -    keywords: {
    -      keyword:
    -        // Value types
    -        'char uchar unichar int uint long ulong short ushort int8 int16 int32 int64 uint8 ' +
    -        'uint16 uint32 uint64 float double bool struct enum string void ' +
    -        // Reference types
    -        'weak unowned owned ' +
    -        // Modifiers
    -        'async signal static abstract interface override virtual delegate ' +
    -        // Control Structures
    -        'if while do for foreach else switch case break default return try catch ' +
    -        // Visibility
    -        'public private protected internal ' +
    -        // Other
    -        'using new this get set const stdout stdin stderr var',
    -      built_in:
    -        'DBus GLib CCode Gee Object Gtk Posix',
    -      literal:
    -        'false true null'
    -    },
    -    contains: [
    -      {
    -        className: 'class',
    -        beginKeywords: 'class interface namespace',
    -        end: /\{/,
    -        excludeEnd: true,
    -        illegal: '[^,:\\n\\s\\.]',
    -        contains: [ hljs.UNDERSCORE_TITLE_MODE ]
    -      },
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      {
    -        className: 'string',
    -        begin: '"""',
    -        end: '"""',
    -        relevance: 5
    -      },
    -      hljs.APOS_STRING_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      hljs.C_NUMBER_MODE,
    -      {
    -        className: 'meta',
    -        begin: '^#',
    -        end: '$',
    -        relevance: 2
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = vala;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/vbnet.js b/claude-code-source/node_modules/highlight.js/lib/languages/vbnet.js
    deleted file mode 100644
    index 5afe2ebe..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/vbnet.js
    +++ /dev/null
    @@ -1,214 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/**
    - * Any of the passed expresssions may match
    - *
    - * Creates a huge this | this | that | that match
    - * @param {(RegExp | string)[] } args
    - * @returns {string}
    - */
    -function either(...args) {
    -  const joined = '(' + args.map((x) => source(x)).join("|") + ")";
    -  return joined;
    -}
    -
    -/*
    -Language: Visual Basic .NET
    -Description: Visual Basic .NET (VB.NET) is a multi-paradigm, object-oriented programming language, implemented on the .NET Framework.
    -Authors: Poren Chiang , Jan Pilzer
    -Website: https://docs.microsoft.com/dotnet/visual-basic/getting-started
    -Category: common
    -*/
    -
    -/** @type LanguageFn */
    -function vbnet(hljs) {
    -  /**
    -   * Character Literal
    -   * Either a single character ("a"C) or an escaped double quote (""""C).
    -   */
    -  const CHARACTER = {
    -    className: 'string',
    -    begin: /"(""|[^/n])"C\b/
    -  };
    -
    -  const STRING = {
    -    className: 'string',
    -    begin: /"/,
    -    end: /"/,
    -    illegal: /\n/,
    -    contains: [
    -      {
    -        // double quote escape
    -        begin: /""/
    -      }
    -    ]
    -  };
    -
    -  /** Date Literals consist of a date, a time, or both separated by whitespace, surrounded by # */
    -  const MM_DD_YYYY = /\d{1,2}\/\d{1,2}\/\d{4}/;
    -  const YYYY_MM_DD = /\d{4}-\d{1,2}-\d{1,2}/;
    -  const TIME_12H = /(\d|1[012])(:\d+){0,2} *(AM|PM)/;
    -  const TIME_24H = /\d{1,2}(:\d{1,2}){1,2}/;
    -  const DATE = {
    -    className: 'literal',
    -    variants: [
    -      {
    -        // #YYYY-MM-DD# (ISO-Date) or #M/D/YYYY# (US-Date)
    -        begin: concat(/# */, either(YYYY_MM_DD, MM_DD_YYYY), / *#/)
    -      },
    -      {
    -        // #H:mm[:ss]# (24h Time)
    -        begin: concat(/# */, TIME_24H, / *#/)
    -      },
    -      {
    -        // #h[:mm[:ss]] A# (12h Time)
    -        begin: concat(/# */, TIME_12H, / *#/)
    -      },
    -      {
    -        // date plus time
    -        begin: concat(
    -          /# */,
    -          either(YYYY_MM_DD, MM_DD_YYYY),
    -          / +/,
    -          either(TIME_12H, TIME_24H),
    -          / *#/
    -        )
    -      }
    -    ]
    -  };
    -
    -  const NUMBER = {
    -    className: 'number',
    -    relevance: 0,
    -    variants: [
    -      {
    -        // Float
    -        begin: /\b\d[\d_]*((\.[\d_]+(E[+-]?[\d_]+)?)|(E[+-]?[\d_]+))[RFD@!#]?/
    -      },
    -      {
    -        // Integer (base 10)
    -        begin: /\b\d[\d_]*((U?[SIL])|[%&])?/
    -      },
    -      {
    -        // Integer (base 16)
    -        begin: /&H[\dA-F_]+((U?[SIL])|[%&])?/
    -      },
    -      {
    -        // Integer (base 8)
    -        begin: /&O[0-7_]+((U?[SIL])|[%&])?/
    -      },
    -      {
    -        // Integer (base 2)
    -        begin: /&B[01_]+((U?[SIL])|[%&])?/
    -      }
    -    ]
    -  };
    -
    -  const LABEL = {
    -    className: 'label',
    -    begin: /^\w+:/
    -  };
    -
    -  const DOC_COMMENT = hljs.COMMENT(/'''/, /$/, {
    -    contains: [
    -      {
    -        className: 'doctag',
    -        begin: /<\/?/,
    -        end: />/
    -      }
    -    ]
    -  });
    -
    -  const COMMENT = hljs.COMMENT(null, /$/, {
    -    variants: [
    -      {
    -        begin: /'/
    -      },
    -      {
    -        // TODO: Use `beforeMatch:` for leading spaces
    -        begin: /([\t ]|^)REM(?=\s)/
    -      }
    -    ]
    -  });
    -
    -  const DIRECTIVES = {
    -    className: 'meta',
    -    // TODO: Use `beforeMatch:` for indentation once available
    -    begin: /[\t ]*#(const|disable|else|elseif|enable|end|externalsource|if|region)\b/,
    -    end: /$/,
    -    keywords: {
    -      'meta-keyword':
    -        'const disable else elseif enable end externalsource if region then'
    -    },
    -    contains: [ COMMENT ]
    -  };
    -
    -  return {
    -    name: 'Visual Basic .NET',
    -    aliases: [ 'vb' ],
    -    case_insensitive: true,
    -    classNameAliases: {
    -      label: 'symbol'
    -    },
    -    keywords: {
    -      keyword:
    -        'addhandler alias aggregate ansi as async assembly auto binary by byref byval ' + /* a-b */
    -        'call case catch class compare const continue custom declare default delegate dim distinct do ' + /* c-d */
    -        'each equals else elseif end enum erase error event exit explicit finally for friend from function ' + /* e-f */
    -        'get global goto group handles if implements imports in inherits interface into iterator ' + /* g-i */
    -        'join key let lib loop me mid module mustinherit mustoverride mybase myclass ' + /* j-m */
    -        'namespace narrowing new next notinheritable notoverridable ' + /* n */
    -        'of off on operator option optional order overloads overridable overrides ' + /* o */
    -        'paramarray partial preserve private property protected public ' + /* p */
    -        'raiseevent readonly redim removehandler resume return ' + /* r */
    -        'select set shadows shared skip static step stop structure strict sub synclock ' + /* s */
    -        'take text then throw to try unicode until using when where while widening with withevents writeonly yield' /* t-y */,
    -      built_in:
    -        // Operators https://docs.microsoft.com/dotnet/visual-basic/language-reference/operators
    -        'addressof and andalso await directcast gettype getxmlnamespace is isfalse isnot istrue like mod nameof new not or orelse trycast typeof xor ' +
    -        // Type Conversion Functions https://docs.microsoft.com/dotnet/visual-basic/language-reference/functions/type-conversion-functions
    -        'cbool cbyte cchar cdate cdbl cdec cint clng cobj csbyte cshort csng cstr cuint culng cushort',
    -      type:
    -        // Data types https://docs.microsoft.com/dotnet/visual-basic/language-reference/data-types
    -        'boolean byte char date decimal double integer long object sbyte short single string uinteger ulong ushort',
    -      literal: 'true false nothing'
    -    },
    -    illegal:
    -      '//|\\{|\\}|endif|gosub|variant|wend|^\\$ ' /* reserved deprecated keywords */,
    -    contains: [
    -      CHARACTER,
    -      STRING,
    -      DATE,
    -      NUMBER,
    -      LABEL,
    -      DOC_COMMENT,
    -      COMMENT,
    -      DIRECTIVES
    -    ]
    -  };
    -}
    -
    -module.exports = vbnet;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/vbscript-html.js b/claude-code-source/node_modules/highlight.js/lib/languages/vbscript-html.js
    deleted file mode 100644
    index 24c13193..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/vbscript-html.js
    +++ /dev/null
    @@ -1,24 +0,0 @@
    -/*
    -Language: VBScript in HTML
    -Requires: xml.js, vbscript.js
    -Author: Ivan Sagalaev 
    -Description: "Bridge" language defining fragments of VBScript in HTML within <% .. %>
    -Website: https://en.wikipedia.org/wiki/VBScript
    -Category: scripting
    -*/
    -
    -function vbscriptHtml(hljs) {
    -  return {
    -    name: 'VBScript in HTML',
    -    subLanguage: 'xml',
    -    contains: [
    -      {
    -        begin: '<%',
    -        end: '%>',
    -        subLanguage: 'vbscript'
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = vbscriptHtml;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/vbscript.js b/claude-code-source/node_modules/highlight.js/lib/languages/vbscript.js
    deleted file mode 100644
    index ad09830d..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/vbscript.js
    +++ /dev/null
    @@ -1,109 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/**
    - * Any of the passed expresssions may match
    - *
    - * Creates a huge this | this | that | that match
    - * @param {(RegExp | string)[] } args
    - * @returns {string}
    - */
    -function either(...args) {
    -  const joined = '(' + args.map((x) => source(x)).join("|") + ")";
    -  return joined;
    -}
    -
    -/*
    -Language: VBScript
    -Description: VBScript ("Microsoft Visual Basic Scripting Edition") is an Active Scripting language developed by Microsoft that is modeled on Visual Basic.
    -Author: Nikita Ledyaev 
    -Contributors: Michal Gabrukiewicz 
    -Website: https://en.wikipedia.org/wiki/VBScript
    -Category: scripting
    -*/
    -
    -/** @type LanguageFn */
    -function vbscript(hljs) {
    -  const BUILT_IN_FUNCTIONS = ('lcase month vartype instrrev ubound setlocale getobject rgb getref string ' +
    -  'weekdayname rnd dateadd monthname now day minute isarray cbool round formatcurrency ' +
    -  'conversions csng timevalue second year space abs clng timeserial fixs len asc ' +
    -  'isempty maths dateserial atn timer isobject filter weekday datevalue ccur isdate ' +
    -  'instr datediff formatdatetime replace isnull right sgn array snumeric log cdbl hex ' +
    -  'chr lbound msgbox ucase getlocale cos cdate cbyte rtrim join hour oct typename trim ' +
    -  'strcomp int createobject loadpicture tan formatnumber mid ' +
    -  'split  cint sin datepart ltrim sqr ' +
    -  'time derived eval date formatpercent exp inputbox left ascw ' +
    -  'chrw regexp cstr err').split(" ");
    -  const BUILT_IN_OBJECTS = [
    -    "server",
    -    "response",
    -    "request",
    -    // take no arguments so can be called without ()
    -    "scriptengine",
    -    "scriptenginebuildversion",
    -    "scriptengineminorversion",
    -    "scriptenginemajorversion"
    -  ];
    -
    -  const BUILT_IN_CALL = {
    -    begin: concat(either(...BUILT_IN_FUNCTIONS), "\\s*\\("),
    -    // relevance 0 because this is acting as a beginKeywords really
    -    relevance:0,
    -    keywords: {
    -      built_in: BUILT_IN_FUNCTIONS
    -    }
    -  };
    -
    -  return {
    -    name: 'VBScript',
    -    aliases: ['vbs'],
    -    case_insensitive: true,
    -    keywords: {
    -      keyword:
    -        'call class const dim do loop erase execute executeglobal exit for each next function ' +
    -        'if then else on error option explicit new private property let get public randomize ' +
    -        'redim rem select case set stop sub while wend with end to elseif is or xor and not ' +
    -        'class_initialize class_terminate default preserve in me byval byref step resume goto',
    -      built_in: BUILT_IN_OBJECTS,
    -      literal:
    -        'true false null nothing empty'
    -    },
    -    illegal: '//',
    -    contains: [
    -      BUILT_IN_CALL,
    -      hljs.inherit(hljs.QUOTE_STRING_MODE, {contains: [{begin: '""'}]}),
    -      hljs.COMMENT(
    -        /'/,
    -        /$/,
    -        {
    -          relevance: 0
    -        }
    -      ),
    -      hljs.C_NUMBER_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = vbscript;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/verilog.js b/claude-code-source/node_modules/highlight.js/lib/languages/verilog.js
    deleted file mode 100644
    index b5435ee5..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/verilog.js
    +++ /dev/null
    @@ -1,131 +0,0 @@
    -/*
    -Language: Verilog
    -Author: Jon Evans 
    -Contributors: Boone Severson 
    -Description: Verilog is a hardware description language used in electronic design automation to describe digital and mixed-signal systems. This highlighter supports Verilog and SystemVerilog through IEEE 1800-2012.
    -Website: http://www.verilog.com
    -*/
    -
    -function verilog(hljs) {
    -  const SV_KEYWORDS = {
    -    $pattern: /[\w\$]+/,
    -    keyword:
    -      'accept_on alias always always_comb always_ff always_latch and assert assign ' +
    -      'assume automatic before begin bind bins binsof bit break buf|0 bufif0 bufif1 ' +
    -      'byte case casex casez cell chandle checker class clocking cmos config const ' +
    -      'constraint context continue cover covergroup coverpoint cross deassign default ' +
    -      'defparam design disable dist do edge else end endcase endchecker endclass ' +
    -      'endclocking endconfig endfunction endgenerate endgroup endinterface endmodule ' +
    -      'endpackage endprimitive endprogram endproperty endspecify endsequence endtable ' +
    -      'endtask enum event eventually expect export extends extern final first_match for ' +
    -      'force foreach forever fork forkjoin function generate|5 genvar global highz0 highz1 ' +
    -      'if iff ifnone ignore_bins illegal_bins implements implies import incdir include ' +
    -      'initial inout input inside instance int integer interconnect interface intersect ' +
    -      'join join_any join_none large let liblist library local localparam logic longint ' +
    -      'macromodule matches medium modport module nand negedge nettype new nexttime nmos ' +
    -      'nor noshowcancelled not notif0 notif1 or output package packed parameter pmos ' +
    -      'posedge primitive priority program property protected pull0 pull1 pulldown pullup ' +
    -      'pulsestyle_ondetect pulsestyle_onevent pure rand randc randcase randsequence rcmos ' +
    -      'real realtime ref reg reject_on release repeat restrict return rnmos rpmos rtran ' +
    -      'rtranif0 rtranif1 s_always s_eventually s_nexttime s_until s_until_with scalared ' +
    -      'sequence shortint shortreal showcancelled signed small soft solve specify specparam ' +
    -      'static string strong strong0 strong1 struct super supply0 supply1 sync_accept_on ' +
    -      'sync_reject_on table tagged task this throughout time timeprecision timeunit tran ' +
    -      'tranif0 tranif1 tri tri0 tri1 triand trior trireg type typedef union unique unique0 ' +
    -      'unsigned until until_with untyped use uwire var vectored virtual void wait wait_order ' +
    -      'wand weak weak0 weak1 while wildcard wire with within wor xnor xor',
    -    literal:
    -      'null',
    -    built_in:
    -      '$finish $stop $exit $fatal $error $warning $info $realtime $time $printtimescale ' +
    -      '$bitstoreal $bitstoshortreal $itor $signed $cast $bits $stime $timeformat ' +
    -      '$realtobits $shortrealtobits $rtoi $unsigned $asserton $assertkill $assertpasson ' +
    -      '$assertfailon $assertnonvacuouson $assertoff $assertcontrol $assertpassoff ' +
    -      '$assertfailoff $assertvacuousoff $isunbounded $sampled $fell $changed $past_gclk ' +
    -      '$fell_gclk $changed_gclk $rising_gclk $steady_gclk $coverage_control ' +
    -      '$coverage_get $coverage_save $set_coverage_db_name $rose $stable $past ' +
    -      '$rose_gclk $stable_gclk $future_gclk $falling_gclk $changing_gclk $display ' +
    -      '$coverage_get_max $coverage_merge $get_coverage $load_coverage_db $typename ' +
    -      '$unpacked_dimensions $left $low $increment $clog2 $ln $log10 $exp $sqrt $pow ' +
    -      '$floor $ceil $sin $cos $tan $countbits $onehot $isunknown $fatal $warning ' +
    -      '$dimensions $right $high $size $asin $acos $atan $atan2 $hypot $sinh $cosh ' +
    -      '$tanh $asinh $acosh $atanh $countones $onehot0 $error $info $random ' +
    -      '$dist_chi_square $dist_erlang $dist_exponential $dist_normal $dist_poisson ' +
    -      '$dist_t $dist_uniform $q_initialize $q_remove $q_exam $async$and$array ' +
    -      '$async$nand$array $async$or$array $async$nor$array $sync$and$array ' +
    -      '$sync$nand$array $sync$or$array $sync$nor$array $q_add $q_full $psprintf ' +
    -      '$async$and$plane $async$nand$plane $async$or$plane $async$nor$plane ' +
    -      '$sync$and$plane $sync$nand$plane $sync$or$plane $sync$nor$plane $system ' +
    -      '$display $displayb $displayh $displayo $strobe $strobeb $strobeh $strobeo ' +
    -      '$write $readmemb $readmemh $writememh $value$plusargs ' +
    -      '$dumpvars $dumpon $dumplimit $dumpports $dumpportson $dumpportslimit ' +
    -      '$writeb $writeh $writeo $monitor $monitorb $monitorh $monitoro $writememb ' +
    -      '$dumpfile $dumpoff $dumpall $dumpflush $dumpportsoff $dumpportsall ' +
    -      '$dumpportsflush $fclose $fdisplay $fdisplayb $fdisplayh $fdisplayo ' +
    -      '$fstrobe $fstrobeb $fstrobeh $fstrobeo $swrite $swriteb $swriteh ' +
    -      '$swriteo $fscanf $fread $fseek $fflush $feof $fopen $fwrite $fwriteb ' +
    -      '$fwriteh $fwriteo $fmonitor $fmonitorb $fmonitorh $fmonitoro $sformat ' +
    -      '$sformatf $fgetc $ungetc $fgets $sscanf $rewind $ftell $ferror'
    -  };
    -
    -  return {
    -    name: 'Verilog',
    -    aliases: [
    -      'v',
    -      'sv',
    -      'svh'
    -    ],
    -    case_insensitive: false,
    -    keywords: SV_KEYWORDS,
    -    contains: [
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.QUOTE_STRING_MODE,
    -      {
    -        className: 'number',
    -        contains: [ hljs.BACKSLASH_ESCAPE ],
    -        variants: [
    -          {
    -            begin: '\\b((\\d+\'(b|h|o|d|B|H|O|D))[0-9xzXZa-fA-F_]+)'
    -          },
    -          {
    -            begin: '\\B((\'(b|h|o|d|B|H|O|D))[0-9xzXZa-fA-F_]+)'
    -          },
    -          {
    -            begin: '\\b([0-9_])+',
    -            relevance: 0
    -          }
    -        ]
    -      },
    -      /* parameters to instances */
    -      {
    -        className: 'variable',
    -        variants: [
    -          {
    -            begin: '#\\((?!parameter).+\\)'
    -          },
    -          {
    -            begin: '\\.\\w+',
    -            relevance: 0
    -          }
    -        ]
    -      },
    -      {
    -        className: 'meta',
    -        begin: '`',
    -        end: '$',
    -        keywords: {
    -          'meta-keyword':
    -            'define __FILE__ ' +
    -            '__LINE__ begin_keywords celldefine default_nettype define ' +
    -            'else elsif end_keywords endcelldefine endif ifdef ifndef ' +
    -            'include line nounconnected_drive pragma resetall timescale ' +
    -            'unconnected_drive undef undefineall'
    -        },
    -        relevance: 0
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = verilog;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/vhdl.js b/claude-code-source/node_modules/highlight.js/lib/languages/vhdl.js
    deleted file mode 100644
    index 80966add..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/vhdl.js
    +++ /dev/null
    @@ -1,71 +0,0 @@
    -/*
    -Language: VHDL
    -Author: Igor Kalnitsky 
    -Contributors: Daniel C.K. Kho , Guillaume Savaton 
    -Description: VHDL is a hardware description language used in electronic design automation to describe digital and mixed-signal systems.
    -Website: https://en.wikipedia.org/wiki/VHDL
    -*/
    -
    -function vhdl(hljs) {
    -  // Regular expression for VHDL numeric literals.
    -
    -  // Decimal literal:
    -  const INTEGER_RE = '\\d(_|\\d)*';
    -  const EXPONENT_RE = '[eE][-+]?' + INTEGER_RE;
    -  const DECIMAL_LITERAL_RE = INTEGER_RE + '(\\.' + INTEGER_RE + ')?' + '(' + EXPONENT_RE + ')?';
    -  // Based literal:
    -  const BASED_INTEGER_RE = '\\w+';
    -  const BASED_LITERAL_RE = INTEGER_RE + '#' + BASED_INTEGER_RE + '(\\.' + BASED_INTEGER_RE + ')?' + '#' + '(' + EXPONENT_RE + ')?';
    -
    -  const NUMBER_RE = '\\b(' + BASED_LITERAL_RE + '|' + DECIMAL_LITERAL_RE + ')';
    -
    -  return {
    -    name: 'VHDL',
    -    case_insensitive: true,
    -    keywords: {
    -      keyword:
    -        'abs access after alias all and architecture array assert assume assume_guarantee attribute ' +
    -        'begin block body buffer bus case component configuration constant context cover disconnect ' +
    -        'downto default else elsif end entity exit fairness file for force function generate ' +
    -        'generic group guarded if impure in inertial inout is label library linkage literal ' +
    -        'loop map mod nand new next nor not null of on open or others out package parameter port ' +
    -        'postponed procedure process property protected pure range record register reject ' +
    -        'release rem report restrict restrict_guarantee return rol ror select sequence ' +
    -        'severity shared signal sla sll sra srl strong subtype then to transport type ' +
    -        'unaffected units until use variable view vmode vprop vunit wait when while with xnor xor',
    -      built_in:
    -        'boolean bit character ' +
    -        'integer time delay_length natural positive ' +
    -        'string bit_vector file_open_kind file_open_status ' +
    -        'std_logic std_logic_vector unsigned signed boolean_vector integer_vector ' +
    -        'std_ulogic std_ulogic_vector unresolved_unsigned u_unsigned unresolved_signed u_signed ' +
    -        'real_vector time_vector',
    -      literal:
    -        'false true note warning error failure ' + // severity_level
    -        'line text side width' // textio
    -    },
    -    illegal: /\{/,
    -    contains: [
    -      hljs.C_BLOCK_COMMENT_MODE, // VHDL-2008 block commenting.
    -      hljs.COMMENT('--', '$'),
    -      hljs.QUOTE_STRING_MODE,
    -      {
    -        className: 'number',
    -        begin: NUMBER_RE,
    -        relevance: 0
    -      },
    -      {
    -        className: 'string',
    -        begin: '\'(U|X|0|1|Z|W|L|H|-)\'',
    -        contains: [ hljs.BACKSLASH_ESCAPE ]
    -      },
    -      {
    -        className: 'symbol',
    -        begin: '\'[A-Za-z](_?[A-Za-z0-9])*',
    -        contains: [ hljs.BACKSLASH_ESCAPE ]
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = vhdl;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/vim.js b/claude-code-source/node_modules/highlight.js/lib/languages/vim.js
    deleted file mode 100644
    index 13810ae8..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/vim.js
    +++ /dev/null
    @@ -1,123 +0,0 @@
    -/*
    -Language: Vim Script
    -Author: Jun Yang 
    -Description: full keyword and built-in from http://vimdoc.sourceforge.net/htmldoc/
    -Website: https://www.vim.org
    -Category: scripting
    -*/
    -
    -function vim(hljs) {
    -  return {
    -    name: 'Vim Script',
    -    keywords: {
    -      $pattern: /[!#@\w]+/,
    -      keyword:
    -        // express version except: ! & * < = > !! # @ @@
    -        'N|0 P|0 X|0 a|0 ab abc abo al am an|0 ar arga argd arge argdo argg argl argu as au aug aun b|0 bN ba bad bd be bel bf bl bm bn bo bp br brea breaka breakd breakl bro bufdo buffers bun bw c|0 cN cNf ca cabc caddb cad caddf cal cat cb cc ccl cd ce cex cf cfir cgetb cgete cg changes chd che checkt cl cla clo cm cmapc cme cn cnew cnf cno cnorea cnoreme co col colo com comc comp con conf cope ' +
    -        'cp cpf cq cr cs cst cu cuna cunme cw delm deb debugg delc delf dif diffg diffo diffp diffpu diffs diffthis dig di dl dell dj dli do doautoa dp dr ds dsp e|0 ea ec echoe echoh echom echon el elsei em en endfo endf endt endw ene ex exe exi exu f|0 files filet fin fina fini fir fix fo foldc foldd folddoc foldo for fu go gr grepa gu gv ha helpf helpg helpt hi hid his ia iabc if ij il im imapc ' +
    -        'ime ino inorea inoreme int is isp iu iuna iunme j|0 ju k|0 keepa kee keepj lN lNf l|0 lad laddb laddf la lan lat lb lc lch lcl lcs le lefta let lex lf lfir lgetb lgete lg lgr lgrepa lh ll lla lli lmak lm lmapc lne lnew lnf ln loadk lo loc lockv lol lope lp lpf lr ls lt lu lua luad luaf lv lvimgrepa lw m|0 ma mak map mapc marks mat me menut mes mk mks mksp mkv mkvie mod mz mzf nbc nb nbs new nm nmapc nme nn nnoreme noa no noh norea noreme norm nu nun nunme ol o|0 om omapc ome on ono onoreme opt ou ounme ow p|0 ' +
    -        'profd prof pro promptr pc ped pe perld po popu pp pre prev ps pt ptN ptf ptj ptl ptn ptp ptr pts pu pw py3 python3 py3d py3f py pyd pyf quita qa rec red redi redr redraws reg res ret retu rew ri rightb rub rubyd rubyf rund ru rv sN san sa sal sav sb sbN sba sbf sbl sbm sbn sbp sbr scrip scripte scs se setf setg setl sf sfir sh sim sig sil sl sla sm smap smapc sme sn sni sno snor snoreme sor ' +
    -        'so spelld spe spelli spellr spellu spellw sp spr sre st sta startg startr star stopi stj sts sun sunm sunme sus sv sw sy synti sync tN tabN tabc tabdo tabe tabf tabfir tabl tabm tabnew ' +
    -        'tabn tabo tabp tabr tabs tab ta tags tc tcld tclf te tf th tj tl tm tn to tp tr try ts tu u|0 undoj undol una unh unl unlo unm unme uns up ve verb vert vim vimgrepa vi viu vie vm vmapc vme vne vn vnoreme vs vu vunme windo w|0 wN wa wh wi winc winp wn wp wq wqa ws wu wv x|0 xa xmapc xm xme xn xnoreme xu xunme y|0 z|0 ~ ' +
    -        // full version
    -        'Next Print append abbreviate abclear aboveleft all amenu anoremenu args argadd argdelete argedit argglobal arglocal argument ascii autocmd augroup aunmenu buffer bNext ball badd bdelete behave belowright bfirst blast bmodified bnext botright bprevious brewind break breakadd breakdel breaklist browse bunload ' +
    -        'bwipeout change cNext cNfile cabbrev cabclear caddbuffer caddexpr caddfile call catch cbuffer cclose center cexpr cfile cfirst cgetbuffer cgetexpr cgetfile chdir checkpath checktime clist clast close cmap cmapclear cmenu cnext cnewer cnfile cnoremap cnoreabbrev cnoremenu copy colder colorscheme command comclear compiler continue confirm copen cprevious cpfile cquit crewind cscope cstag cunmap ' +
    -        'cunabbrev cunmenu cwindow delete delmarks debug debuggreedy delcommand delfunction diffupdate diffget diffoff diffpatch diffput diffsplit digraphs display deletel djump dlist doautocmd doautoall deletep drop dsearch dsplit edit earlier echo echoerr echohl echomsg else elseif emenu endif endfor ' +
    -        'endfunction endtry endwhile enew execute exit exusage file filetype find finally finish first fixdel fold foldclose folddoopen folddoclosed foldopen function global goto grep grepadd gui gvim hardcopy help helpfind helpgrep helptags highlight hide history insert iabbrev iabclear ijump ilist imap ' +
    -        'imapclear imenu inoremap inoreabbrev inoremenu intro isearch isplit iunmap iunabbrev iunmenu join jumps keepalt keepmarks keepjumps lNext lNfile list laddexpr laddbuffer laddfile last language later lbuffer lcd lchdir lclose lcscope left leftabove lexpr lfile lfirst lgetbuffer lgetexpr lgetfile lgrep lgrepadd lhelpgrep llast llist lmake lmap lmapclear lnext lnewer lnfile lnoremap loadkeymap loadview ' +
    -        'lockmarks lockvar lolder lopen lprevious lpfile lrewind ltag lunmap luado luafile lvimgrep lvimgrepadd lwindow move mark make mapclear match menu menutranslate messages mkexrc mksession mkspell mkvimrc mkview mode mzscheme mzfile nbclose nbkey nbsart next nmap nmapclear nmenu nnoremap ' +
    -        'nnoremenu noautocmd noremap nohlsearch noreabbrev noremenu normal number nunmap nunmenu oldfiles open omap omapclear omenu only onoremap onoremenu options ounmap ounmenu ownsyntax print profdel profile promptfind promptrepl pclose pedit perl perldo pop popup ppop preserve previous psearch ptag ptNext ' +
    -        'ptfirst ptjump ptlast ptnext ptprevious ptrewind ptselect put pwd py3do py3file python pydo pyfile quit quitall qall read recover redo redir redraw redrawstatus registers resize retab return rewind right rightbelow ruby rubydo rubyfile rundo runtime rviminfo substitute sNext sandbox sargument sall saveas sbuffer sbNext sball sbfirst sblast sbmodified sbnext sbprevious sbrewind scriptnames scriptencoding ' +
    -        'scscope set setfiletype setglobal setlocal sfind sfirst shell simalt sign silent sleep slast smagic smapclear smenu snext sniff snomagic snoremap snoremenu sort source spelldump spellgood spellinfo spellrepall spellundo spellwrong split sprevious srewind stop stag startgreplace startreplace ' +
    -        'startinsert stopinsert stjump stselect sunhide sunmap sunmenu suspend sview swapname syntax syntime syncbind tNext tabNext tabclose tabedit tabfind tabfirst tablast tabmove tabnext tabonly tabprevious tabrewind tag tcl tcldo tclfile tearoff tfirst throw tjump tlast tmenu tnext topleft tprevious ' + 'trewind tselect tunmenu undo undojoin undolist unabbreviate unhide unlet unlockvar unmap unmenu unsilent update vglobal version verbose vertical vimgrep vimgrepadd visual viusage view vmap vmapclear vmenu vnew ' +
    -        'vnoremap vnoremenu vsplit vunmap vunmenu write wNext wall while winsize wincmd winpos wnext wprevious wqall wsverb wundo wviminfo xit xall xmapclear xmap xmenu xnoremap xnoremenu xunmap xunmenu yank',
    -      built_in: // built in func
    -        'synIDtrans atan2 range matcharg did_filetype asin feedkeys xor argv ' +
    -        'complete_check add getwinposx getqflist getwinposy screencol ' +
    -        'clearmatches empty extend getcmdpos mzeval garbagecollect setreg ' +
    -        'ceil sqrt diff_hlID inputsecret get getfperm getpid filewritable ' +
    -        'shiftwidth max sinh isdirectory synID system inputrestore winline ' +
    -        'atan visualmode inputlist tabpagewinnr round getregtype mapcheck ' +
    -        'hasmapto histdel argidx findfile sha256 exists toupper getcmdline ' +
    -        'taglist string getmatches bufnr strftime winwidth bufexists ' +
    -        'strtrans tabpagebuflist setcmdpos remote_read printf setloclist ' +
    -        'getpos getline bufwinnr float2nr len getcmdtype diff_filler luaeval ' +
    -        'resolve libcallnr foldclosedend reverse filter has_key bufname ' +
    -        'str2float strlen setline getcharmod setbufvar index searchpos ' +
    -        'shellescape undofile foldclosed setqflist buflisted strchars str2nr ' +
    -        'virtcol floor remove undotree remote_expr winheight gettabwinvar ' +
    -        'reltime cursor tabpagenr finddir localtime acos getloclist search ' +
    -        'tanh matchend rename gettabvar strdisplaywidth type abs py3eval ' +
    -        'setwinvar tolower wildmenumode log10 spellsuggest bufloaded ' +
    -        'synconcealed nextnonblank server2client complete settabwinvar ' +
    -        'executable input wincol setmatches getftype hlID inputsave ' +
    -        'searchpair or screenrow line settabvar histadd deepcopy strpart ' +
    -        'remote_peek and eval getftime submatch screenchar winsaveview ' +
    -        'matchadd mkdir screenattr getfontname libcall reltimestr getfsize ' +
    -        'winnr invert pow getbufline byte2line soundfold repeat fnameescape ' +
    -        'tagfiles sin strwidth spellbadword trunc maparg log lispindent ' +
    -        'hostname setpos globpath remote_foreground getchar synIDattr ' +
    -        'fnamemodify cscope_connection stridx winbufnr indent min ' +
    -        'complete_add nr2char searchpairpos inputdialog values matchlist ' +
    -        'items hlexists strridx browsedir expand fmod pathshorten line2byte ' +
    -        'argc count getwinvar glob foldtextresult getreg foreground cosh ' +
    -        'matchdelete has char2nr simplify histget searchdecl iconv ' +
    -        'winrestcmd pumvisible writefile foldlevel haslocaldir keys cos ' +
    -        'matchstr foldtext histnr tan tempname getcwd byteidx getbufvar ' +
    -        'islocked escape eventhandler remote_send serverlist winrestview ' +
    -        'synstack pyeval prevnonblank readfile cindent filereadable changenr ' +
    -        'exp'
    -    },
    -    illegal: /;/,
    -    contains: [
    -      hljs.NUMBER_MODE,
    -      {
    -        className: 'string',
    -        begin: '\'',
    -        end: '\'',
    -        illegal: '\\n'
    -      },
    -
    -      /*
    -      A double quote can start either a string or a line comment. Strings are
    -      ended before the end of a line by another double quote and can contain
    -      escaped double-quotes and post-escaped line breaks.
    -
    -      Also, any double quote at the beginning of a line is a comment but we
    -      don't handle that properly at the moment: any double quote inside will
    -      turn them into a string. Handling it properly will require a smarter
    -      parser.
    -      */
    -      {
    -        className: 'string',
    -        begin: /"(\\"|\n\\|[^"\n])*"/
    -      },
    -      hljs.COMMENT('"', '$'),
    -
    -      {
    -        className: 'variable',
    -        begin: /[bwtglsav]:[\w\d_]*/
    -      },
    -      {
    -        className: 'function',
    -        beginKeywords: 'function function!',
    -        end: '$',
    -        relevance: 0,
    -        contains: [
    -          hljs.TITLE_MODE,
    -          {
    -            className: 'params',
    -            begin: '\\(',
    -            end: '\\)'
    -          }
    -        ]
    -      },
    -      {
    -        className: 'symbol',
    -        begin: /<[\w-]+>/
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = vim;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/x86asm.js b/claude-code-source/node_modules/highlight.js/lib/languages/x86asm.js
    deleted file mode 100644
    index 8736cf09..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/x86asm.js
    +++ /dev/null
    @@ -1,163 +0,0 @@
    -/*
    -Language: Intel x86 Assembly
    -Author: innocenat 
    -Description: x86 assembly language using Intel's mnemonic and NASM syntax
    -Website: https://en.wikipedia.org/wiki/X86_assembly_language
    -Category: assembler
    -*/
    -
    -function x86asm(hljs) {
    -  return {
    -    name: 'Intel x86 Assembly',
    -    case_insensitive: true,
    -    keywords: {
    -      $pattern: '[.%]?' + hljs.IDENT_RE,
    -      keyword:
    -        'lock rep repe repz repne repnz xaquire xrelease bnd nobnd ' +
    -        'aaa aad aam aas adc add and arpl bb0_reset bb1_reset bound bsf bsr bswap bt btc btr bts call cbw cdq cdqe clc cld cli clts cmc cmp cmpsb cmpsd cmpsq cmpsw cmpxchg cmpxchg486 cmpxchg8b cmpxchg16b cpuid cpu_read cpu_write cqo cwd cwde daa das dec div dmint emms enter equ f2xm1 fabs fadd faddp fbld fbstp fchs fclex fcmovb fcmovbe fcmove fcmovnb fcmovnbe fcmovne fcmovnu fcmovu fcom fcomi fcomip fcomp fcompp fcos fdecstp fdisi fdiv fdivp fdivr fdivrp femms feni ffree ffreep fiadd ficom ficomp fidiv fidivr fild fimul fincstp finit fist fistp fisttp fisub fisubr fld fld1 fldcw fldenv fldl2e fldl2t fldlg2 fldln2 fldpi fldz fmul fmulp fnclex fndisi fneni fninit fnop fnsave fnstcw fnstenv fnstsw fpatan fprem fprem1 fptan frndint frstor fsave fscale fsetpm fsin fsincos fsqrt fst fstcw fstenv fstp fstsw fsub fsubp fsubr fsubrp ftst fucom fucomi fucomip fucomp fucompp fxam fxch fxtract fyl2x fyl2xp1 hlt ibts icebp idiv imul in inc incbin insb insd insw int int01 int1 int03 int3 into invd invpcid invlpg invlpga iret iretd iretq iretw jcxz jecxz jrcxz jmp jmpe lahf lar lds lea leave les lfence lfs lgdt lgs lidt lldt lmsw loadall loadall286 lodsb lodsd lodsq lodsw loop loope loopne loopnz loopz lsl lss ltr mfence monitor mov movd movq movsb movsd movsq movsw movsx movsxd movzx mul mwait neg nop not or out outsb outsd outsw packssdw packsswb packuswb paddb paddd paddsb paddsiw paddsw paddusb paddusw paddw pand pandn pause paveb pavgusb pcmpeqb pcmpeqd pcmpeqw pcmpgtb pcmpgtd pcmpgtw pdistib pf2id pfacc pfadd pfcmpeq pfcmpge pfcmpgt pfmax pfmin pfmul pfrcp pfrcpit1 pfrcpit2 pfrsqit1 pfrsqrt pfsub pfsubr pi2fd pmachriw pmaddwd pmagw pmulhriw pmulhrwa pmulhrwc pmulhw pmullw pmvgezb pmvlzb pmvnzb pmvzb pop popa popad popaw popf popfd popfq popfw por prefetch prefetchw pslld psllq psllw psrad psraw psrld psrlq psrlw psubb psubd psubsb psubsiw psubsw psubusb psubusw psubw punpckhbw punpckhdq punpckhwd punpcklbw punpckldq punpcklwd push pusha pushad pushaw pushf pushfd pushfq pushfw pxor rcl rcr rdshr rdmsr rdpmc rdtsc rdtscp ret retf retn rol ror rdm rsdc rsldt rsm rsts sahf sal salc sar sbb scasb scasd scasq scasw sfence sgdt shl shld shr shrd sidt sldt skinit smi smint smintold smsw stc std sti stosb stosd stosq stosw str sub svdc svldt svts swapgs syscall sysenter sysexit sysret test ud0 ud1 ud2b ud2 ud2a umov verr verw fwait wbinvd wrshr wrmsr xadd xbts xchg xlatb xlat xor cmove cmovz cmovne cmovnz cmova cmovnbe cmovae cmovnb cmovb cmovnae cmovbe cmovna cmovg cmovnle cmovge cmovnl cmovl cmovnge cmovle cmovng cmovc cmovnc cmovo cmovno cmovs cmovns cmovp cmovpe cmovnp cmovpo je jz jne jnz ja jnbe jae jnb jb jnae jbe jna jg jnle jge jnl jl jnge jle jng jc jnc jo jno js jns jpo jnp jpe jp sete setz setne setnz seta setnbe setae setnb setnc setb setnae setcset setbe setna setg setnle setge setnl setl setnge setle setng sets setns seto setno setpe setp setpo setnp addps addss andnps andps cmpeqps cmpeqss cmpleps cmpless cmpltps cmpltss cmpneqps cmpneqss cmpnleps cmpnless cmpnltps cmpnltss cmpordps cmpordss cmpunordps cmpunordss cmpps cmpss comiss cvtpi2ps cvtps2pi cvtsi2ss cvtss2si cvttps2pi cvttss2si divps divss ldmxcsr maxps maxss minps minss movaps movhps movlhps movlps movhlps movmskps movntps movss movups mulps mulss orps rcpps rcpss rsqrtps rsqrtss shufps sqrtps sqrtss stmxcsr subps subss ucomiss unpckhps unpcklps xorps fxrstor fxrstor64 fxsave fxsave64 xgetbv xsetbv xsave xsave64 xsaveopt xsaveopt64 xrstor xrstor64 prefetchnta prefetcht0 prefetcht1 prefetcht2 maskmovq movntq pavgb pavgw pextrw pinsrw pmaxsw pmaxub pminsw pminub pmovmskb pmulhuw psadbw pshufw pf2iw pfnacc pfpnacc pi2fw pswapd maskmovdqu clflush movntdq movnti movntpd movdqa movdqu movdq2q movq2dq paddq pmuludq pshufd pshufhw pshuflw pslldq psrldq psubq punpckhqdq punpcklqdq addpd addsd andnpd andpd cmpeqpd cmpeqsd cmplepd cmplesd cmpltpd cmpltsd cmpneqpd cmpneqsd cmpnlepd cmpnlesd cmpnltpd cmpnltsd cmpordpd cmpordsd cmpunordpd cmpunordsd cmppd comisd cvtdq2pd cvtdq2ps cvtpd2dq cvtpd2pi cvtpd2ps cvtpi2pd cvtps2dq cvtps2pd cvtsd2si cvtsd2ss cvtsi2sd cvtss2sd cvttpd2pi cvttpd2dq cvttps2dq cvttsd2si divpd divsd maxpd maxsd minpd minsd movapd movhpd movlpd movmskpd movupd mulpd mulsd orpd shufpd sqrtpd sqrtsd subpd subsd ucomisd unpckhpd unpcklpd xorpd addsubpd addsubps haddpd haddps hsubpd hsubps lddqu movddup movshdup movsldup clgi stgi vmcall vmclear vmfunc vmlaunch vmload vmmcall vmptrld vmptrst vmread vmresume vmrun vmsave vmwrite vmxoff vmxon invept invvpid pabsb pabsw pabsd palignr phaddw phaddd phaddsw phsubw phsubd phsubsw pmaddubsw pmulhrsw pshufb psignb psignw psignd extrq insertq movntsd movntss lzcnt blendpd blendps blendvpd blendvps dppd dpps extractps insertps movntdqa mpsadbw packusdw pblendvb pblendw pcmpeqq pextrb pextrd pextrq phminposuw pinsrb pinsrd pinsrq pmaxsb pmaxsd pmaxud pmaxuw pminsb pminsd pminud pminuw pmovsxbw pmovsxbd pmovsxbq pmovsxwd pmovsxwq pmovsxdq pmovzxbw pmovzxbd pmovzxbq pmovzxwd pmovzxwq pmovzxdq pmuldq pmulld ptest roundpd roundps roundsd roundss crc32 pcmpestri pcmpestrm pcmpistri pcmpistrm pcmpgtq popcnt getsec pfrcpv pfrsqrtv movbe aesenc aesenclast aesdec aesdeclast aesimc aeskeygenassist vaesenc vaesenclast vaesdec vaesdeclast vaesimc vaeskeygenassist vaddpd vaddps vaddsd vaddss vaddsubpd vaddsubps vandpd vandps vandnpd vandnps vblendpd vblendps vblendvpd vblendvps vbroadcastss vbroadcastsd vbroadcastf128 vcmpeq_ospd vcmpeqpd vcmplt_ospd vcmpltpd vcmple_ospd vcmplepd vcmpunord_qpd vcmpunordpd vcmpneq_uqpd vcmpneqpd vcmpnlt_uspd vcmpnltpd vcmpnle_uspd vcmpnlepd vcmpord_qpd vcmpordpd vcmpeq_uqpd vcmpnge_uspd vcmpngepd vcmpngt_uspd vcmpngtpd vcmpfalse_oqpd vcmpfalsepd vcmpneq_oqpd vcmpge_ospd vcmpgepd vcmpgt_ospd vcmpgtpd vcmptrue_uqpd vcmptruepd vcmplt_oqpd vcmple_oqpd vcmpunord_spd vcmpneq_uspd vcmpnlt_uqpd vcmpnle_uqpd vcmpord_spd vcmpeq_uspd vcmpnge_uqpd vcmpngt_uqpd vcmpfalse_ospd vcmpneq_ospd vcmpge_oqpd vcmpgt_oqpd vcmptrue_uspd vcmppd vcmpeq_osps vcmpeqps vcmplt_osps vcmpltps vcmple_osps vcmpleps vcmpunord_qps vcmpunordps vcmpneq_uqps vcmpneqps vcmpnlt_usps vcmpnltps vcmpnle_usps vcmpnleps vcmpord_qps vcmpordps vcmpeq_uqps vcmpnge_usps vcmpngeps vcmpngt_usps vcmpngtps vcmpfalse_oqps vcmpfalseps vcmpneq_oqps vcmpge_osps vcmpgeps vcmpgt_osps vcmpgtps vcmptrue_uqps vcmptrueps vcmplt_oqps vcmple_oqps vcmpunord_sps vcmpneq_usps vcmpnlt_uqps vcmpnle_uqps vcmpord_sps vcmpeq_usps vcmpnge_uqps vcmpngt_uqps vcmpfalse_osps vcmpneq_osps vcmpge_oqps vcmpgt_oqps vcmptrue_usps vcmpps vcmpeq_ossd vcmpeqsd vcmplt_ossd vcmpltsd vcmple_ossd vcmplesd vcmpunord_qsd vcmpunordsd vcmpneq_uqsd vcmpneqsd vcmpnlt_ussd vcmpnltsd vcmpnle_ussd vcmpnlesd vcmpord_qsd vcmpordsd vcmpeq_uqsd vcmpnge_ussd vcmpngesd vcmpngt_ussd vcmpngtsd vcmpfalse_oqsd vcmpfalsesd vcmpneq_oqsd vcmpge_ossd vcmpgesd vcmpgt_ossd vcmpgtsd vcmptrue_uqsd vcmptruesd vcmplt_oqsd vcmple_oqsd vcmpunord_ssd vcmpneq_ussd vcmpnlt_uqsd vcmpnle_uqsd vcmpord_ssd vcmpeq_ussd vcmpnge_uqsd vcmpngt_uqsd vcmpfalse_ossd vcmpneq_ossd vcmpge_oqsd vcmpgt_oqsd vcmptrue_ussd vcmpsd vcmpeq_osss vcmpeqss vcmplt_osss vcmpltss vcmple_osss vcmpless vcmpunord_qss vcmpunordss vcmpneq_uqss vcmpneqss vcmpnlt_usss vcmpnltss vcmpnle_usss vcmpnless vcmpord_qss vcmpordss vcmpeq_uqss vcmpnge_usss vcmpngess vcmpngt_usss vcmpngtss vcmpfalse_oqss vcmpfalsess vcmpneq_oqss vcmpge_osss vcmpgess vcmpgt_osss vcmpgtss vcmptrue_uqss vcmptruess vcmplt_oqss vcmple_oqss vcmpunord_sss vcmpneq_usss vcmpnlt_uqss vcmpnle_uqss vcmpord_sss vcmpeq_usss vcmpnge_uqss vcmpngt_uqss vcmpfalse_osss vcmpneq_osss vcmpge_oqss vcmpgt_oqss vcmptrue_usss vcmpss vcomisd vcomiss vcvtdq2pd vcvtdq2ps vcvtpd2dq vcvtpd2ps vcvtps2dq vcvtps2pd vcvtsd2si vcvtsd2ss vcvtsi2sd vcvtsi2ss vcvtss2sd vcvtss2si vcvttpd2dq vcvttps2dq vcvttsd2si vcvttss2si vdivpd vdivps vdivsd vdivss vdppd vdpps vextractf128 vextractps vhaddpd vhaddps vhsubpd vhsubps vinsertf128 vinsertps vlddqu vldqqu vldmxcsr vmaskmovdqu vmaskmovps vmaskmovpd vmaxpd vmaxps vmaxsd vmaxss vminpd vminps vminsd vminss vmovapd vmovaps vmovd vmovq vmovddup vmovdqa vmovqqa vmovdqu vmovqqu vmovhlps vmovhpd vmovhps vmovlhps vmovlpd vmovlps vmovmskpd vmovmskps vmovntdq vmovntqq vmovntdqa vmovntpd vmovntps vmovsd vmovshdup vmovsldup vmovss vmovupd vmovups vmpsadbw vmulpd vmulps vmulsd vmulss vorpd vorps vpabsb vpabsw vpabsd vpacksswb vpackssdw vpackuswb vpackusdw vpaddb vpaddw vpaddd vpaddq vpaddsb vpaddsw vpaddusb vpaddusw vpalignr vpand vpandn vpavgb vpavgw vpblendvb vpblendw vpcmpestri vpcmpestrm vpcmpistri vpcmpistrm vpcmpeqb vpcmpeqw vpcmpeqd vpcmpeqq vpcmpgtb vpcmpgtw vpcmpgtd vpcmpgtq vpermilpd vpermilps vperm2f128 vpextrb vpextrw vpextrd vpextrq vphaddw vphaddd vphaddsw vphminposuw vphsubw vphsubd vphsubsw vpinsrb vpinsrw vpinsrd vpinsrq vpmaddwd vpmaddubsw vpmaxsb vpmaxsw vpmaxsd vpmaxub vpmaxuw vpmaxud vpminsb vpminsw vpminsd vpminub vpminuw vpminud vpmovmskb vpmovsxbw vpmovsxbd vpmovsxbq vpmovsxwd vpmovsxwq vpmovsxdq vpmovzxbw vpmovzxbd vpmovzxbq vpmovzxwd vpmovzxwq vpmovzxdq vpmulhuw vpmulhrsw vpmulhw vpmullw vpmulld vpmuludq vpmuldq vpor vpsadbw vpshufb vpshufd vpshufhw vpshuflw vpsignb vpsignw vpsignd vpslldq vpsrldq vpsllw vpslld vpsllq vpsraw vpsrad vpsrlw vpsrld vpsrlq vptest vpsubb vpsubw vpsubd vpsubq vpsubsb vpsubsw vpsubusb vpsubusw vpunpckhbw vpunpckhwd vpunpckhdq vpunpckhqdq vpunpcklbw vpunpcklwd vpunpckldq vpunpcklqdq vpxor vrcpps vrcpss vrsqrtps vrsqrtss vroundpd vroundps vroundsd vroundss vshufpd vshufps vsqrtpd vsqrtps vsqrtsd vsqrtss vstmxcsr vsubpd vsubps vsubsd vsubss vtestps vtestpd vucomisd vucomiss vunpckhpd vunpckhps vunpcklpd vunpcklps vxorpd vxorps vzeroall vzeroupper pclmullqlqdq pclmulhqlqdq pclmullqhqdq pclmulhqhqdq pclmulqdq vpclmullqlqdq vpclmulhqlqdq vpclmullqhqdq vpclmulhqhqdq vpclmulqdq vfmadd132ps vfmadd132pd vfmadd312ps vfmadd312pd vfmadd213ps vfmadd213pd vfmadd123ps vfmadd123pd vfmadd231ps vfmadd231pd vfmadd321ps vfmadd321pd vfmaddsub132ps vfmaddsub132pd vfmaddsub312ps vfmaddsub312pd vfmaddsub213ps vfmaddsub213pd vfmaddsub123ps vfmaddsub123pd vfmaddsub231ps vfmaddsub231pd vfmaddsub321ps vfmaddsub321pd vfmsub132ps vfmsub132pd vfmsub312ps vfmsub312pd vfmsub213ps vfmsub213pd vfmsub123ps vfmsub123pd vfmsub231ps vfmsub231pd vfmsub321ps vfmsub321pd vfmsubadd132ps vfmsubadd132pd vfmsubadd312ps vfmsubadd312pd vfmsubadd213ps vfmsubadd213pd vfmsubadd123ps vfmsubadd123pd vfmsubadd231ps vfmsubadd231pd vfmsubadd321ps vfmsubadd321pd vfnmadd132ps vfnmadd132pd vfnmadd312ps vfnmadd312pd vfnmadd213ps vfnmadd213pd vfnmadd123ps vfnmadd123pd vfnmadd231ps vfnmadd231pd vfnmadd321ps vfnmadd321pd vfnmsub132ps vfnmsub132pd vfnmsub312ps vfnmsub312pd vfnmsub213ps vfnmsub213pd vfnmsub123ps vfnmsub123pd vfnmsub231ps vfnmsub231pd vfnmsub321ps vfnmsub321pd vfmadd132ss vfmadd132sd vfmadd312ss vfmadd312sd vfmadd213ss vfmadd213sd vfmadd123ss vfmadd123sd vfmadd231ss vfmadd231sd vfmadd321ss vfmadd321sd vfmsub132ss vfmsub132sd vfmsub312ss vfmsub312sd vfmsub213ss vfmsub213sd vfmsub123ss vfmsub123sd vfmsub231ss vfmsub231sd vfmsub321ss vfmsub321sd vfnmadd132ss vfnmadd132sd vfnmadd312ss vfnmadd312sd vfnmadd213ss vfnmadd213sd vfnmadd123ss vfnmadd123sd vfnmadd231ss vfnmadd231sd vfnmadd321ss vfnmadd321sd vfnmsub132ss vfnmsub132sd vfnmsub312ss vfnmsub312sd vfnmsub213ss vfnmsub213sd vfnmsub123ss vfnmsub123sd vfnmsub231ss vfnmsub231sd vfnmsub321ss vfnmsub321sd rdfsbase rdgsbase rdrand wrfsbase wrgsbase vcvtph2ps vcvtps2ph adcx adox rdseed clac stac xstore xcryptecb xcryptcbc xcryptctr xcryptcfb xcryptofb montmul xsha1 xsha256 llwpcb slwpcb lwpval lwpins vfmaddpd vfmaddps vfmaddsd vfmaddss vfmaddsubpd vfmaddsubps vfmsubaddpd vfmsubaddps vfmsubpd vfmsubps vfmsubsd vfmsubss vfnmaddpd vfnmaddps vfnmaddsd vfnmaddss vfnmsubpd vfnmsubps vfnmsubsd vfnmsubss vfrczpd vfrczps vfrczsd vfrczss vpcmov vpcomb vpcomd vpcomq vpcomub vpcomud vpcomuq vpcomuw vpcomw vphaddbd vphaddbq vphaddbw vphadddq vphaddubd vphaddubq vphaddubw vphaddudq vphadduwd vphadduwq vphaddwd vphaddwq vphsubbw vphsubdq vphsubwd vpmacsdd vpmacsdqh vpmacsdql vpmacssdd vpmacssdqh vpmacssdql vpmacsswd vpmacssww vpmacswd vpmacsww vpmadcsswd vpmadcswd vpperm vprotb vprotd vprotq vprotw vpshab vpshad vpshaq vpshaw vpshlb vpshld vpshlq vpshlw vbroadcasti128 vpblendd vpbroadcastb vpbroadcastw vpbroadcastd vpbroadcastq vpermd vpermpd vpermps vpermq vperm2i128 vextracti128 vinserti128 vpmaskmovd vpmaskmovq vpsllvd vpsllvq vpsravd vpsrlvd vpsrlvq vgatherdpd vgatherqpd vgatherdps vgatherqps vpgatherdd vpgatherqd vpgatherdq vpgatherqq xabort xbegin xend xtest andn bextr blci blcic blsi blsic blcfill blsfill blcmsk blsmsk blsr blcs bzhi mulx pdep pext rorx sarx shlx shrx tzcnt tzmsk t1mskc valignd valignq vblendmpd vblendmps vbroadcastf32x4 vbroadcastf64x4 vbroadcasti32x4 vbroadcasti64x4 vcompresspd vcompressps vcvtpd2udq vcvtps2udq vcvtsd2usi vcvtss2usi vcvttpd2udq vcvttps2udq vcvttsd2usi vcvttss2usi vcvtudq2pd vcvtudq2ps vcvtusi2sd vcvtusi2ss vexpandpd vexpandps vextractf32x4 vextractf64x4 vextracti32x4 vextracti64x4 vfixupimmpd vfixupimmps vfixupimmsd vfixupimmss vgetexppd vgetexpps vgetexpsd vgetexpss vgetmantpd vgetmantps vgetmantsd vgetmantss vinsertf32x4 vinsertf64x4 vinserti32x4 vinserti64x4 vmovdqa32 vmovdqa64 vmovdqu32 vmovdqu64 vpabsq vpandd vpandnd vpandnq vpandq vpblendmd vpblendmq vpcmpltd vpcmpled vpcmpneqd vpcmpnltd vpcmpnled vpcmpd vpcmpltq vpcmpleq vpcmpneqq vpcmpnltq vpcmpnleq vpcmpq vpcmpequd vpcmpltud vpcmpleud vpcmpnequd vpcmpnltud vpcmpnleud vpcmpud vpcmpequq vpcmpltuq vpcmpleuq vpcmpnequq vpcmpnltuq vpcmpnleuq vpcmpuq vpcompressd vpcompressq vpermi2d vpermi2pd vpermi2ps vpermi2q vpermt2d vpermt2pd vpermt2ps vpermt2q vpexpandd vpexpandq vpmaxsq vpmaxuq vpminsq vpminuq vpmovdb vpmovdw vpmovqb vpmovqd vpmovqw vpmovsdb vpmovsdw vpmovsqb vpmovsqd vpmovsqw vpmovusdb vpmovusdw vpmovusqb vpmovusqd vpmovusqw vpord vporq vprold vprolq vprolvd vprolvq vprord vprorq vprorvd vprorvq vpscatterdd vpscatterdq vpscatterqd vpscatterqq vpsraq vpsravq vpternlogd vpternlogq vptestmd vptestmq vptestnmd vptestnmq vpxord vpxorq vrcp14pd vrcp14ps vrcp14sd vrcp14ss vrndscalepd vrndscaleps vrndscalesd vrndscaless vrsqrt14pd vrsqrt14ps vrsqrt14sd vrsqrt14ss vscalefpd vscalefps vscalefsd vscalefss vscatterdpd vscatterdps vscatterqpd vscatterqps vshuff32x4 vshuff64x2 vshufi32x4 vshufi64x2 kandnw kandw kmovw knotw kortestw korw kshiftlw kshiftrw kunpckbw kxnorw kxorw vpbroadcastmb2q vpbroadcastmw2d vpconflictd vpconflictq vplzcntd vplzcntq vexp2pd vexp2ps vrcp28pd vrcp28ps vrcp28sd vrcp28ss vrsqrt28pd vrsqrt28ps vrsqrt28sd vrsqrt28ss vgatherpf0dpd vgatherpf0dps vgatherpf0qpd vgatherpf0qps vgatherpf1dpd vgatherpf1dps vgatherpf1qpd vgatherpf1qps vscatterpf0dpd vscatterpf0dps vscatterpf0qpd vscatterpf0qps vscatterpf1dpd vscatterpf1dps vscatterpf1qpd vscatterpf1qps prefetchwt1 bndmk bndcl bndcu bndcn bndmov bndldx bndstx sha1rnds4 sha1nexte sha1msg1 sha1msg2 sha256rnds2 sha256msg1 sha256msg2 hint_nop0 hint_nop1 hint_nop2 hint_nop3 hint_nop4 hint_nop5 hint_nop6 hint_nop7 hint_nop8 hint_nop9 hint_nop10 hint_nop11 hint_nop12 hint_nop13 hint_nop14 hint_nop15 hint_nop16 hint_nop17 hint_nop18 hint_nop19 hint_nop20 hint_nop21 hint_nop22 hint_nop23 hint_nop24 hint_nop25 hint_nop26 hint_nop27 hint_nop28 hint_nop29 hint_nop30 hint_nop31 hint_nop32 hint_nop33 hint_nop34 hint_nop35 hint_nop36 hint_nop37 hint_nop38 hint_nop39 hint_nop40 hint_nop41 hint_nop42 hint_nop43 hint_nop44 hint_nop45 hint_nop46 hint_nop47 hint_nop48 hint_nop49 hint_nop50 hint_nop51 hint_nop52 hint_nop53 hint_nop54 hint_nop55 hint_nop56 hint_nop57 hint_nop58 hint_nop59 hint_nop60 hint_nop61 hint_nop62 hint_nop63',
    -      built_in:
    -        // Instruction pointer
    -        'ip eip rip ' +
    -        // 8-bit registers
    -        'al ah bl bh cl ch dl dh sil dil bpl spl r8b r9b r10b r11b r12b r13b r14b r15b ' +
    -        // 16-bit registers
    -        'ax bx cx dx si di bp sp r8w r9w r10w r11w r12w r13w r14w r15w ' +
    -        // 32-bit registers
    -        'eax ebx ecx edx esi edi ebp esp eip r8d r9d r10d r11d r12d r13d r14d r15d ' +
    -        // 64-bit registers
    -        'rax rbx rcx rdx rsi rdi rbp rsp r8 r9 r10 r11 r12 r13 r14 r15 ' +
    -        // Segment registers
    -        'cs ds es fs gs ss ' +
    -        // Floating point stack registers
    -        'st st0 st1 st2 st3 st4 st5 st6 st7 ' +
    -        // MMX Registers
    -        'mm0 mm1 mm2 mm3 mm4 mm5 mm6 mm7 ' +
    -        // SSE registers
    -        'xmm0  xmm1  xmm2  xmm3  xmm4  xmm5  xmm6  xmm7  xmm8  xmm9 xmm10  xmm11 xmm12 xmm13 xmm14 xmm15 ' +
    -        'xmm16 xmm17 xmm18 xmm19 xmm20 xmm21 xmm22 xmm23 xmm24 xmm25 xmm26 xmm27 xmm28 xmm29 xmm30 xmm31 ' +
    -        // AVX registers
    -        'ymm0  ymm1  ymm2  ymm3  ymm4  ymm5  ymm6  ymm7  ymm8  ymm9 ymm10  ymm11 ymm12 ymm13 ymm14 ymm15 ' +
    -        'ymm16 ymm17 ymm18 ymm19 ymm20 ymm21 ymm22 ymm23 ymm24 ymm25 ymm26 ymm27 ymm28 ymm29 ymm30 ymm31 ' +
    -        // AVX-512F registers
    -        'zmm0  zmm1  zmm2  zmm3  zmm4  zmm5  zmm6  zmm7  zmm8  zmm9 zmm10  zmm11 zmm12 zmm13 zmm14 zmm15 ' +
    -        'zmm16 zmm17 zmm18 zmm19 zmm20 zmm21 zmm22 zmm23 zmm24 zmm25 zmm26 zmm27 zmm28 zmm29 zmm30 zmm31 ' +
    -        // AVX-512F mask registers
    -        'k0 k1 k2 k3 k4 k5 k6 k7 ' +
    -        // Bound (MPX) register
    -        'bnd0 bnd1 bnd2 bnd3 ' +
    -        // Special register
    -        'cr0 cr1 cr2 cr3 cr4 cr8 dr0 dr1 dr2 dr3 dr8 tr3 tr4 tr5 tr6 tr7 ' +
    -        // NASM altreg package
    -        'r0 r1 r2 r3 r4 r5 r6 r7 r0b r1b r2b r3b r4b r5b r6b r7b ' +
    -        'r0w r1w r2w r3w r4w r5w r6w r7w r0d r1d r2d r3d r4d r5d r6d r7d ' +
    -        'r0h r1h r2h r3h ' +
    -        'r0l r1l r2l r3l r4l r5l r6l r7l r8l r9l r10l r11l r12l r13l r14l r15l ' +
    -
    -        'db dw dd dq dt ddq do dy dz ' +
    -        'resb resw resd resq rest resdq reso resy resz ' +
    -        'incbin equ times ' +
    -        'byte word dword qword nosplit rel abs seg wrt strict near far a32 ptr',
    -
    -      meta:
    -        '%define %xdefine %+ %undef %defstr %deftok %assign %strcat %strlen %substr %rotate %elif %else %endif ' +
    -        '%if %ifmacro %ifctx %ifidn %ifidni %ifid %ifnum %ifstr %iftoken %ifempty %ifenv %error %warning %fatal %rep ' +
    -        '%endrep %include %push %pop %repl %pathsearch %depend %use %arg %stacksize %local %line %comment %endcomment ' +
    -        '.nolist ' +
    -        '__FILE__ __LINE__ __SECT__  __BITS__ __OUTPUT_FORMAT__ __DATE__ __TIME__ __DATE_NUM__ __TIME_NUM__ ' +
    -        '__UTC_DATE__ __UTC_TIME__ __UTC_DATE_NUM__ __UTC_TIME_NUM__  __PASS__ struc endstruc istruc at iend ' +
    -        'align alignb sectalign daz nodaz up down zero default option assume public ' +
    -
    -        'bits use16 use32 use64 default section segment absolute extern global common cpu float ' +
    -        '__utf16__ __utf16le__ __utf16be__ __utf32__ __utf32le__ __utf32be__ ' +
    -        '__float8__ __float16__ __float32__ __float64__ __float80m__ __float80e__ __float128l__ __float128h__ ' +
    -        '__Infinity__ __QNaN__ __SNaN__ Inf NaN QNaN SNaN float8 float16 float32 float64 float80m float80e ' +
    -        'float128l float128h __FLOAT_DAZ__ __FLOAT_ROUND__ __FLOAT__'
    -    },
    -    contains: [
    -      hljs.COMMENT(
    -        ';',
    -        '$',
    -        {
    -          relevance: 0
    -        }
    -      ),
    -      {
    -        className: 'number',
    -        variants: [
    -          // Float number and x87 BCD
    -          {
    -            begin: '\\b(?:([0-9][0-9_]*)?\\.[0-9_]*(?:[eE][+-]?[0-9_]+)?|' +
    -                   '(0[Xx])?[0-9][0-9_]*(\\.[0-9_]*)?(?:[pP](?:[+-]?[0-9_]+)?)?)\\b',
    -            relevance: 0
    -          },
    -
    -          // Hex number in $
    -          {
    -            begin: '\\$[0-9][0-9A-Fa-f]*',
    -            relevance: 0
    -          },
    -
    -          // Number in H,D,T,Q,O,B,Y suffix
    -          {
    -            begin: '\\b(?:[0-9A-Fa-f][0-9A-Fa-f_]*[Hh]|[0-9][0-9_]*[DdTt]?|[0-7][0-7_]*[QqOo]|[0-1][0-1_]*[BbYy])\\b'
    -          },
    -
    -          // Number in X,D,T,Q,O,B,Y prefix
    -          {
    -            begin: '\\b(?:0[Xx][0-9A-Fa-f_]+|0[DdTt][0-9_]+|0[QqOo][0-7_]+|0[BbYy][0-1_]+)\\b'
    -          }
    -        ]
    -      },
    -      // Double quote string
    -      hljs.QUOTE_STRING_MODE,
    -      {
    -        className: 'string',
    -        variants: [
    -          // Single-quoted string
    -          {
    -            begin: '\'',
    -            end: '[^\\\\]\''
    -          },
    -          // Backquoted string
    -          {
    -            begin: '`',
    -            end: '[^\\\\]`'
    -          }
    -        ],
    -        relevance: 0
    -      },
    -      {
    -        className: 'symbol',
    -        variants: [
    -          // Global label and local label
    -          {
    -            begin: '^\\s*[A-Za-z._?][A-Za-z0-9_$#@~.?]*(:|\\s+label)'
    -          },
    -          // Macro-local label
    -          {
    -            begin: '^\\s*%%[A-Za-z0-9_$#@~.?]*:'
    -          }
    -        ],
    -        relevance: 0
    -      },
    -      // Macro parameter
    -      {
    -        className: 'subst',
    -        begin: '%[0-9]+',
    -        relevance: 0
    -      },
    -      // Macro parameter
    -      {
    -        className: 'subst',
    -        begin: '%!\S+',
    -        relevance: 0
    -      },
    -      {
    -        className: 'meta',
    -        begin: /^\s*\.[\w_-]+/
    -      }
    -    ]
    -  };
    -}
    -
    -module.exports = x86asm;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/xl.js b/claude-code-source/node_modules/highlight.js/lib/languages/xl.js
    deleted file mode 100644
    index 270741db..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/xl.js
    +++ /dev/null
    @@ -1,92 +0,0 @@
    -/*
    -Language: XL
    -Author: Christophe de Dinechin 
    -Description: An extensible programming language, based on parse tree rewriting
    -Website: http://xlr.sf.net
    -*/
    -
    -function xl(hljs) {
    -  const BUILTIN_MODULES =
    -    'ObjectLoader Animate MovieCredits Slides Filters Shading Materials LensFlare Mapping VLCAudioVideo ' +
    -    'StereoDecoder PointCloud NetworkAccess RemoteControl RegExp ChromaKey Snowfall NodeJS Speech Charts';
    -
    -  const XL_KEYWORDS = {
    -    $pattern: /[a-zA-Z][a-zA-Z0-9_?]*/,
    -    keyword:
    -      'if then else do while until for loop import with is as where when by data constant ' +
    -      'integer real text name boolean symbol infix prefix postfix block tree',
    -    literal:
    -      'true false nil',
    -    built_in:
    -      'in mod rem and or xor not abs sign floor ceil sqrt sin cos tan asin ' +
    -      'acos atan exp expm1 log log2 log10 log1p pi at text_length text_range ' +
    -      'text_find text_replace contains page slide basic_slide title_slide ' +
    -      'title subtitle fade_in fade_out fade_at clear_color color line_color ' +
    -      'line_width texture_wrap texture_transform texture scale_?x scale_?y ' +
    -      'scale_?z? translate_?x translate_?y translate_?z? rotate_?x rotate_?y ' +
    -      'rotate_?z? rectangle circle ellipse sphere path line_to move_to ' +
    -      'quad_to curve_to theme background contents locally time mouse_?x ' +
    -      'mouse_?y mouse_buttons ' +
    -      BUILTIN_MODULES
    -  };
    -
    -  const DOUBLE_QUOTE_TEXT = {
    -    className: 'string',
    -    begin: '"',
    -    end: '"',
    -    illegal: '\\n'
    -  };
    -  const SINGLE_QUOTE_TEXT = {
    -    className: 'string',
    -    begin: '\'',
    -    end: '\'',
    -    illegal: '\\n'
    -  };
    -  const LONG_TEXT = {
    -    className: 'string',
    -    begin: '<<',
    -    end: '>>'
    -  };
    -  const BASED_NUMBER = {
    -    className: 'number',
    -    begin: '[0-9]+#[0-9A-Z_]+(\\.[0-9-A-Z_]+)?#?([Ee][+-]?[0-9]+)?'
    -  };
    -  const IMPORT = {
    -    beginKeywords: 'import',
    -    end: '$',
    -    keywords: XL_KEYWORDS,
    -    contains: [ DOUBLE_QUOTE_TEXT ]
    -  };
    -  const FUNCTION_DEFINITION = {
    -    className: 'function',
    -    begin: /[a-z][^\n]*->/,
    -    returnBegin: true,
    -    end: /->/,
    -    contains: [
    -      hljs.inherit(hljs.TITLE_MODE, {
    -        starts: {
    -          endsWithParent: true,
    -          keywords: XL_KEYWORDS
    -        }
    -      })
    -    ]
    -  };
    -  return {
    -    name: 'XL',
    -    aliases: [ 'tao' ],
    -    keywords: XL_KEYWORDS,
    -    contains: [
    -      hljs.C_LINE_COMMENT_MODE,
    -      hljs.C_BLOCK_COMMENT_MODE,
    -      DOUBLE_QUOTE_TEXT,
    -      SINGLE_QUOTE_TEXT,
    -      LONG_TEXT,
    -      FUNCTION_DEFINITION,
    -      IMPORT,
    -      BASED_NUMBER,
    -      hljs.NUMBER_MODE
    -    ]
    -  };
    -}
    -
    -module.exports = xl;
    diff --git a/claude-code-source/node_modules/highlight.js/lib/languages/xml.js b/claude-code-source/node_modules/highlight.js/lib/languages/xml.js
    deleted file mode 100644
    index 1c81810d..00000000
    --- a/claude-code-source/node_modules/highlight.js/lib/languages/xml.js
    +++ /dev/null
    @@ -1,287 +0,0 @@
    -/**
    - * @param {string} value
    - * @returns {RegExp}
    - * */
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function source(re) {
    -  if (!re) return null;
    -  if (typeof re === "string") return re;
    -
    -  return re.source;
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function lookahead(re) {
    -  return concat('(?=', re, ')');
    -}
    -
    -/**
    - * @param {RegExp | string } re
    - * @returns {string}
    - */
    -function optional(re) {
    -  return concat('(', re, ')?');
    -}
    -
    -/**
    - * @param {...(RegExp | string) } args
    - * @returns {string}
    - */
    -function concat(...args) {
    -  const joined = args.map((x) => source(x)).join("");
    -  return joined;
    -}
    -
    -/**
    - * Any of the passed expresssions may match
    - *
    - * Creates a huge this | this | that | that match
    - * @param {(RegExp | string)[] } args
    - * @returns {string}
    - */
    -function either(...args) {
    -  const joined = '(' + args.map((x) => source(x)).join("|") + ")";
    -  return joined;
    -}
    -
    -/*
    -Language: HTML, XML
    -Website: https://www.w3.org/XML/
    -Category: common
    -Audit: 2020
    -*/
    -
    -/** @type LanguageFn */
    -function xml(hljs) {
    -  // Element names can contain letters, digits, hyphens, underscores, and periods
    -  const TAG_NAME_RE = concat(/[A-Z_]/, optional(/[A-Z0-9_.-]*:/), /[A-Z0-9_.-]*/);
    -  const XML_IDENT_RE = /[A-Za-z0-9._:-]+/;
    -  const XML_ENTITIES = {
    -    className: 'symbol',
    -    begin: /&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/
    -  };
    -  const XML_META_KEYWORDS = {
    -    begin: /\s/,
    -    contains: [
    -      {
    -        className: 'meta-keyword',
    -        begin: /#?[a-z_][a-z1-9_-]+/,
    -        illegal: /\n/
    -      }
    -    ]
    -  };
    -  const XML_META_PAR_KEYWORDS = hljs.inherit(XML_META_KEYWORDS, {
    -    begin: /\(/,
    -    end: /\)/
    -  });
    -  const APOS_META_STRING_MODE = hljs.inherit(hljs.APOS_STRING_MODE, {
    -    className: 'meta-string'
    -  });
    -  const QUOTE_META_STRING_MODE = hljs.inherit(hljs.QUOTE_STRING_MODE, {
    -    className: 'meta-string'
    -  });
    -  const TAG_INTERNALS = {
    -    endsWithParent: true,
    -    illegal: /`]+/
    -              }
    -            ]
    -          }
    -        ]
    -      }
    -    ]
    -  };
    -  return {
    -    name: 'HTML, XML',
    -    aliases: [
    -      'html',
    -      'xhtml',
    -      'rss',
    -      'atom',
    -      'xjb',
    -      'xsd',
    -      'xsl',
    -      'plist',
    -      'wsf',
    -      'svg'
    -    ],
    -    case_insensitive: true,
    -    contains: [
    -      {
    -        className: 'meta',
    -        begin: //,
    -        relevance: 10,
    -        contains: [
    -          XML_META_KEYWORDS,
    -          QUOTE_META_STRING_MODE,
    -          APOS_META_STRING_MODE,
    -          XML_META_PAR_KEYWORDS,
    -          {
    -            begin: /\[/,
    -            end: /\]/,
    -            contains: [
    -              {
    -                className: 'meta',
    -                begin: //,
    -                contains: [
    -                  XML_META_KEYWORDS,
    -                  XML_META_PAR_KEYWORDS,
    -                  QUOTE_META_STRING_MODE,
    -                  APOS_META_STRING_MODE
    -                ]
    -              }
    -            ]
    -          }
    -        ]
    -      },
    -      hljs.COMMENT(
    -        //,
    -        {
    -          relevance: 10
    -        }
    -      ),
    -      {
    -        begin: //,
    -        relevance: 10
    -      },
    -      XML_ENTITIES,
    -      {
    -        className: 'meta',
    -        begin: /<\?xml/,
    -        end: /\?>/,
    -        relevance: 10
    -      },
    -      {
    -        className: 'tag',
    -        /*
    -        The lookahead pattern (?=...) ensures that 'begin' only matches
    -        ')/,
    -        end: />/,
    -        keywords: {
    -          name: 'style'
    -        },
    -        contains: [ TAG_INTERNALS ],
    -        starts: {
    -          end: /<\/style>/,
    -          returnEnd: true,
    -          subLanguage: [
    -            'css',
    -            'xml'
    -          ]
    -        }
    -      },
    -      {
    -        className: 'tag',
    -        // See the comment in the